klaudius 0.31.1 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as f,m as G,n as ie,p as A}from"./chunk-4OWKYGZF.js";import{useEffect as Ue,useMemo as Ne,useRef as re,useState as R}from"react";import{Box as B,Text as k,useApp as De,useInput as Ve}from"ink";import{Box as se,Text as be}from"ink";import{jsx as ce,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 ae({items:e}){return ce(se,{flexDirection:"column",width:28,flexShrink:0,children:e.map(r=>{let o=r.status==="skipped"||r.status==="pending";return ce(se,{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 le}from"react";import{Box as K,Text as O,useInput as we}from"ink";import ke from"ink-text-input";import{jsx as U,jsxs as q}from"react/jsx-runtime";function pe({spec:e,masked:r,onSubmit:o,onBack:t}){let p=typeof e.initialValue=="string"?e.initialValue:"",n=r&&p.length>0,[i,T]=le(n?"":p),[g,a]=le(null);ye(()=>(f("TextPromptUI:mount",{masked:r,message:e.message.slice(0,60),initial:typeof e.initialValue=="string"?e.initialValue.slice(0,30):null}),()=>{f("TextPromptUI:unmount")}),[r,e.message,e.initialValue]),we((u,x)=>{f("TextPromptUI:useInput fired",{input:u,ctrl:x.ctrl,escape:x.escape,return:x.return}),x.escape&&t()});let I=u=>{f("TextPromptUI:handleSubmit",{raw:u.slice(0,30)});let x=u.length===0&&n?p:u;if(e.validate){let l=e.validate(x);if(l){f("TextPromptUI:validate failed",{err:l}),a(l);return}}a(null),o(x)};return q(K,{flexDirection:"column",children:[q(O,{children:[U(O,{color:"cyan",children:"?"})," ",e.message]}),q(K,{children:[U(O,{color:"green",children:"\u203A "}),U(ke,{value:i,onChange:T,onSubmit:I,placeholder:n?"type or paste a new value \u2014 or press Enter to keep the current one":e.placeholder,mask:r?"\u2022":void 0})]}),g&&U(K,{marginTop:0,children:U(O,{color:"red",children:g})})]})}import{useState as Ie}from"react";import{Box as J,Text as M,useInput as Ae}from"ink";import{jsx as F,jsxs as Q}from"react/jsx-runtime";function ue({spec:e,onSubmit:r,onBack:o}){let t=e.options??[],p=typeof e.initialValue=="string"?Math.max(0,t.findIndex(T=>T.value===e.initialValue)):0,[n,i]=Ie(p===-1?0:p);return Ae((T,g)=>{if(g.escape)o();else if(g.upArrow)i(a=>(a-1+t.length)%t.length);else if(g.downArrow)i(a=>(a+1)%t.length);else if(g.return){let a=t[n];a&&r(a.value)}}),Q(J,{flexDirection:"column",children:[Q(M,{children:[F(M,{color:"cyan",children:"?"})," ",e.message]}),F(J,{flexDirection:"column",marginTop:0,children:t.map((T,g)=>{let a=g===n;return Q(M,{color:a?"cyan":void 0,bold:a,children:[a?"\u25CF ":"\u25CB ",T.label]},T.value)})}),F(J,{marginTop:1,children:F(M,{dimColor:!0,children:"Use the \u2191 \u2193 arrow keys to choose, then press Enter"})})]})}import{useState as Re}from"react";import{Box as Z,Text as E,useInput as Ee}from"ink";import{jsx as j,jsxs as N}from"react/jsx-runtime";function me({spec:e,onSubmit:r,onBack:o}){let[t,p]=Re(typeof e.initialValue=="boolean"?e.initialValue:!0);return Ee((n,i)=>{i.escape?o():i.leftArrow||i.rightArrow?p(T=>!T):n==="y"||n==="Y"?p(!0):n==="n"||n==="N"?p(!1):i.return&&r(t)}),N(Z,{flexDirection:"column",children:[N(E,{children:[j(E,{color:"cyan",children:"?"})," ",e.message]}),N(Z,{marginTop:0,children:[N(E,{color:t?"cyan":void 0,bold:t,children:[t?"\u25CF ":"\u25CB ","Yes"]}),j(E,{children:" "}),N(E,{color:t?void 0:"cyan",bold:!t,children:[t?"\u25CB ":"\u25CF ","No"]})]}),j(Z,{marginTop:1,children:j(E,{dimColor:!0,children:"Use the \u2190 \u2192 arrow keys (or y / n) to choose, then press Enter"})})]})}import{useState as _}from"react";import{Box as L,Text as D,useInput as Ce}from"ink";import{jsx as V,jsxs as Y}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(u=>u.trim()).filter(Boolean):[]),[n,i]=_(0),[T,g]=_(p),[a,I]=_(null);return Ce((u,x)=>{if(x.escape)o();else if(x.upArrow)i(l=>(l-1+t.length)%t.length);else if(x.downArrow)i(l=>(l+1)%t.length);else if(u===" "){let l=t[n];l&&(I(null),g(y=>{let P=new Set(y);return P.has(l.value)?P.delete(l.value):P.add(l.value),P}))}else if(x.return){let l=t.map(P=>P.value).filter(P=>T.has(P)).join(","),y=e.validate?.(l);if(y){I(y);return}r(l)}}),Y(L,{flexDirection:"column",children:[Y(D,{children:[V(D,{color:"cyan",children:"?"})," ",e.message]}),V(L,{flexDirection:"column",marginTop:0,children:t.map((u,x)=>{let l=x===n,y=T.has(u.value);return Y(D,{color:l?"cyan":void 0,bold:l,children:[l?"\u203A ":" ",y?"\u25C9 ":"\u25EF ",u.label]},u.value)})}),a&&V(L,{marginTop:0,children:V(D,{color:"red",children:a})}),V(L,{marginTop:1,children:Y(D,{dimColor:!0,children:["\u2191 \u2193 to move, Space to tick/untick, Enter to confirm",e.validate?" (tick at least one)":" (ticking none is fine)"]})})]})}import{Box as fe,Text as ge}from"ink";import{jsx as ee,jsxs as ze}from"react/jsx-runtime";function te({title:e,body:r}){let o=r.split(`
|
|
2
|
+
`);return ze(fe,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[ee(ge,{color:"cyan",bold:!0,children:e}),ee(fe,{flexDirection:"column",marginTop:0,children:o.map((t,p)=>ee(ge,{dimColor:!1,children:t.length===0?" ":t},p))})]})}import{jsx as c,jsxs as W}from"react/jsx-runtime";function yt({defaults:e,onComplete:r,onlySection:o,banner:t}){let{exit:p}=De(),n=re({...e}),i=re(new Map),[,T]=R(0),g=()=>T(m=>m+1),[a,I]=R(null),[u,x]=R(null),[l,y]=R([]),[P,oe]=R(null),[ne,xe]=R(!1),[$,Se]=R({current:0,total:0}),C=()=>{let m=i.current;for(let S of A){let X=S.isApplicable(n.current),s=m.get(S.id);X?o&&S.id!==o?s!=="current"&&m.set(S.id,"done"):(s==="skipped"||!s)&&m.set(S.id,"pending"):m.set(S.id,"skipped")}};i.current.size===0&&C();let H=re(!1);Ue(()=>{if(f("WizardApp:useEffect fired",{startedAlready:H.current}),H.current){f("WizardApp:useEffect returning early (startedRef true)");return}H.current=!0,f("WizardApp:orchestrator starting");let m=0,S=s=>{let v=++m;return f("orchestrator:promptFn called",{id:v,type:s.type,message:s.message.slice(0,60)}),oe(null),new Promise((b,d)=>{x({id:v,spec:s,resolve:w=>{f("orchestrator:prompt resolved",{id:v,type:s.type,value:typeof w=="string"?w.slice(0,30):w}),b(w)},reject:w=>{f("orchestrator:prompt rejected",{id:v,reason:w.message}),d(w)}})})},X=s=>{y(v=>[...v,s])};return(async()=>{try{let s=o?A.filter(d=>d.id===o):A,v=()=>s.filter(d=>d.isApplicable(n.current)).length,b=0;for(;b<s.length;){let d=s[b];if(!d.isApplicable(n.current)){i.current.set(d.id,"skipped"),b++,C(),g();continue}y([]);for(let h of A)h.id===d.id?i.current.set(h.id,"current"):i.current.get(h.id)==="current"&&i.current.set(h.id,"pending");I(d.id);let w=s.slice(0,b+1).filter(h=>h.isApplicable(n.current)).length;Se({current:w,total:v()}),g();try{let h=await d.execute(n.current,{prompt:S,info:X});n.current={...n.current,...h},i.current.set(d.id,"done"),C(),b++}catch(h){if(h instanceof G){if(o&&d.clearOnSkip){for(let Pe of d.clearOnSkip)n.current[Pe]=void 0;i.current.set(d.id,"skipped"),C(),b++;continue}if(o)continue;i.current.set(d.id,"pending");let z=b-1;for(;z>=0&&!s[z].isApplicable(n.current);)z--;z<0||(b=z,i.current.set(s[b].id,"pending")),C(),g();continue}throw h}}f("orchestrator:all sections done, calling onComplete + exit"),xe(!0),x(null),I(null),g(),await new Promise(d=>setTimeout(d,200)),r(n.current),p()}catch(s){f("orchestrator:caught error",{name:s?.name,message:s?.message}),s instanceof ie&&(p(),process.exit(0));let v=s instanceof Error?s.message:String(s);oe(`Setup error: ${v}`),g()}})(),()=>{f("WizardApp:useEffect cleanup ran (component unmounting)")}},[p,r]),Ve((m,S)=>{f("WizardApp:useInput fired",{input:m,ctrl:S.ctrl,escape:S.escape,return:S.return}),S.ctrl&&m==="c"&&(f("WizardApp:Ctrl+C \u2192 exiting"),p(),process.exit(0))});let Te=Ne(()=>A.map(m=>({id:m.id,title:m.title,status:i.current.get(m.id)??"pending"})),[a,ne,P]);return W(B,{flexDirection:"column",paddingY:1,children:[W(B,{marginBottom:1,children:[c(k,{bold:!0,color:"cyan",children:"Klaudius setup"}),c(k,{dimColor:!0,children:" \xB7 "}),c(k,{dimColor:!0,children:$.total>0?`Step ${$.current} of ${$.total}`:"Loading\u2026"})]}),W(B,{children:[c(ae,{items:Te}),W(B,{flexDirection:"column",flexGrow:1,marginLeft:2,children:[t&&W(B,{marginBottom:1,borderStyle:"round",borderColor:"red",paddingX:1,flexDirection:"column",children:[c(k,{color:"red",bold:!0,children:"\u26A0 Heads up"}),c(k,{children:t})]}),!o&&a!==null&&a!=="ai-agent"&&c(B,{marginBottom:1,children:c(k,{color:"green",children:"Nothing here is permanent, you can customize any of this later."})}),l.map((m,S)=>c(B,{marginBottom:1,children:c(te,{title:m.title,body:m.body})},S)),u?.spec.note&&c(B,{marginBottom:1,children:c(te,{title:u.spec.note.title,body:u.spec.note.body})}),u&&Oe(u),P&&c(B,{marginTop:1,children:c(k,{color:"red",children:P})}),ne&&c(B,{marginTop:1,children:c(k,{color:"green",bold:!0,children:"\u2713 Setup complete. Continuing\u2026"})})]})]}),c(B,{marginTop:1,children:c(k,{dimColor:!0,children:We(o,a)})})]})}function We(e,r){if(e){let o=A.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 G);switch(e.spec.type){case"text":case"password":return c(pe,{spec:e.spec,masked:e.spec.type==="password",onSubmit:r,onBack:o},e.id);case"select":return c(ue,{spec:e.spec,onSubmit:r,onBack:o},e.id);case"multiselect":return c(de,{spec:e.spec,onSubmit:r,onBack:o},e.id);case"confirm":return c(me,{spec:e.spec,onSubmit:r,onBack:o},e.id)}}export{yt as WizardApp};
|
package/dist/bin.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as ke,c as Be,d as J,e as T,f as en,g as tn,h as Ve,i as Ye,j as de,k as nn,l as sn,o as on,q as Ae,r as We,s as N}from"./chunk-
|
|
2
|
+
import{b as ke,c as Be,d as J,e as T,f as en,g as tn,h as Ve,i as Ye,j as de,k as nn,l as sn,o as on,q as Ae,r as We,s as N}from"./chunk-4OWKYGZF.js";import{Command as Lr}from"commander";import{spawn as ln}from"child_process";import{existsSync as Bs}from"fs";import{homedir as Vs}from"os";import O from"picocolors";import{win32 as xs}from"path";var Os=["&","^","%","!"];function vs(e){return Os.filter(t=>e.includes(t))}function Ee(e){let t=[];for(let{label:n,path:s}of e){let o=vs(s);o.length>0&&t.push({label:n,path:s,chars:o})}return t}function $s(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=xs.basename(t).toLowerCase();return["pwsh","pwsh.exe","bash","bash.exe","sh","sh.exe"].includes(s)?t:null}function Pe(e,t){let n=$s(e);return n===null?!1:t?t(n):!0}function Se(e,t){let n=e[0],s=[...new Set(e.flatMap(f=>f.chars))],o=s.map(f=>`"${f}"`).join(", "),r=s.includes("&");return{detail:`${n.label} is "${n.path}" \u2014 the ${o} in it ${r?"breaks":"can break"} npm's package build steps (cmd.exe treats it as a command character and cuts the path)`,action:`Native-module installs ${r?"will":"may"} fail here with a misleading demand to install Visual Studio \u2014 Visual Studio is NOT needed and installing it will not fix this. Instead point npm's build steps at a shell that parses these paths correctly: PowerShell 7 (pwsh) or Git Bash, whichever is installed \u2014 npm config set script-shell "<full path to pwsh.exe or bash.exe>" (applies to all npm projects on this machine) \u2014 ${t==="preflight"?'then re-run this preflight \u2014 the "Install path safe for npm builds" check passes once script-shell is set.':t==="doctor"?"then re-run doctor \u2014 this check passes once script-shell is set.":'then re-run `npx klaudius@latest install`; `npx klaudius@latest doctor` confirms the fix (its "Install path safe for npm builds" check passes once script-shell is set).'} Windows PowerShell 5.1 ("powershell") will NOT work: it can't run the "||" in packages' install scripts. If neither shell is installed, PowerShell 7 is a small download: winget install Microsoft.PowerShell. If only the PROJECT folder is affected (not the user folder), moving the project to a plain path like C:\\klaudius also fixes it, or scope the npm setting to just this project by adding --location=project (run inside the project folder).`}}function ue(){let e=process.version,t=/^v(\d+)\.(\d+)\.(\d+)/.exec(e);if(!t)return{ok:!1,message:`Could not parse the Node.js version string ("${e}"). Klaudius requires Node.js 22.15 or newer \u2014 install from https://nodejs.org/.`};let n=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10),r=`${n}.${s}.${o}`;return n<22||n===22&&s<15?{ok:!1,version:r,major:n,minor:s,message:`Your installed Node.js is ${r}. Klaudius requires Node.js 22.15 or newer (the dependency installer relies on the --use-system-ca flag, which was added in 22.15 to handle Windows machines where antivirus or corporate-proxy software MITMs HTTPS). Install a newer Node.js from https://nodejs.org/ \u2014 after installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:r,major:n,minor:s}}import{spawn as Ls}from"child_process";import{existsSync as Ns}from"fs";import{homedir as Ms}from"os";import{delimiter as Ds,join as ze}from"path";var Fs=new Set(["Restricted","AllSigned"]);function Hs(e,t=Ns){for(let n of e.split(Ds)){let s=n.replace(/"/g,"");if(!s)continue;let o=ze(s,"npx.ps1");if(t(o))return{path:o,isPs1:!0};for(let r of["npx.exe","npx.bat","npx.cmd"]){let a=ze(s,r);if(t(a))return{path:a,isPs1:!1}}}return null}async function an(){let e=Hs(process.env.PATH??"");if(!e)return{blocked:!1,npxMissing:!0};if(!e.isPs1)return{blocked:!1};let t=await Us();if(!t)return{blocked:!1,shimPath:e.path};let n=ze(Ms(),".local","node")+"\\";return{blocked:Fs.has(t),policy:t,shimPath:e.path,ownInstall:e.path.toLowerCase().startsWith(n.toLowerCase())}}async function Us(){let e=ze(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return await rn(e)??await rn("powershell.exe")}function rn(e){let t={...process.env};for(let n of Object.keys(t))n.toLowerCase()==="psmodulepath"&&delete t[n];return new Promise(n=>{let s=Ls(e,["-NoProfile","-NonInteractive","-Command","Get-ExecutionPolicy"],{stdio:["ignore","pipe","pipe"],env:t}),o="",r=setTimeout(()=>{s.kill(),n(null)},8e3);s.stdout.on("data",a=>{o+=a.toString()}),s.stderr?.resume(),s.on("close",a=>{clearTimeout(r),n(a===0&&o.trim()?o.trim():null)}),s.on("error",()=>{clearTimeout(r),n(null)})})}import{spawn as js}from"child_process";var Ne=3,qe=10,Ks=[["python3"],["python"],["py","-3"]];async function K(){for(let e of Ks){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),r=parseInt(s[2],10),a=s[3]?`${o}.${r}.${s[3]}`:`${o}.${r}`;return{command:[...e],version:a,major:o,minor:r}}return null}async function be(){let e=Gs(),t=await K();if(!t){let a=process.platform==="win32"?` On Windows the \`python3\` / \`python\` commands are often the Microsoft Store placeholder, not a real interpreter \u2014 install from ${e} (tick "Add python.exe to PATH"), or disable the alias under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases.`:"";return{ok:!1,message:`Python ${Ne}.${qe}+ is not installed (or not on PATH). Install it from ${e}.`+a}}let{command:n,version:s,major:o,minor:r}=t;return o<Ne||o===Ne&&r<qe?{ok:!1,version:s,major:o,minor:r,command:n,message:`Your installed Python is ${s}. Klaudius needs Python ${Ne}.${qe} or newer (the pipeline depends on packages that only ship wheels for ${Ne}.${qe}+). Install a newer Python from ${e} \u2014 it lives alongside your existing Python, nothing breaks. After installing, close every Terminal window, open a new one, then re-run klaudius.`}:{ok:!0,version:s,major:o,minor:r,command:n}}function Gs(){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=js(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",a=>{o+=a.toString()}),s.stderr?.on("data",a=>{r+=a.toString()}),s.on("close",a=>n({code:a??1,stdout:o,stderr:r})),s.on("error",()=>n({code:1,stdout:o,stderr:r}))})}var cn=(process.env.KLAUDIUS_API_URL??"https://klaudius.dev").replace(/\/$/,"");async function dn(e={}){console.log(O.bold(`Klaudius preflight \u2014 checking your machine\u2026
|
|
3
3
|
`));let t=[];t.push(Ys());let n=await be();if(t.push(Ws(n)),t.push(await zs(n.command)),t.push(await qs()),process.platform==="win32"){let o=await Qs();o&&t.push(o);let r=await Js();r&&t.push(r)}t.push(await Xs());for(let o of t){let r=o.status==="ok"?O.green("\u2713"):o.status==="warn"?O.yellow("!"):O.red("\u2717");console.log(` ${r} ${o.name}${o.detail?O.dim(` \u2014 ${o.detail}`):""}`),o.nextAction&&console.log(` ${O.dim("\u2192")} ${O.cyan(o.nextAction)}`)}console.log();let s=t.filter(o=>o.status==="fail");if(s.length===0){let o=t.filter(r=>r.status==="warn").length;Zs(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 Ys(){let e=ue();return e.ok?{name:"Node.js \u2265 22.15",status:"ok",detail:e.version}:{name:"Node.js \u2265 22.15",status:"fail",detail:e.version??"not detected",nextAction:"Install Node.js 22.15+ from https://nodejs.org/ \u2014 then open a NEW terminal window before re-running."}}function Ws(e){return e.ok?{name:"Python \u2265 3.10",status:"ok",detail:e.version}:{name:"Python \u2265 3.10",status:"fail",detail:e.version??"not found",nextAction:e.message??"Install Python 3.10+ from https://www.python.org/downloads/"}}async function zs(e){let t=e??["python3"],n=await Je(t[0],[...t.slice(1),"-m","pip","--version"]);return n.code===0?{name:"pip available",status:"ok",detail:(n.stdout||n.stderr).trim().split(`
|
|
4
|
-
`)[0]||"ok"}:{name:"pip available",status:"fail",detail:`${t.join(" ")} -m pip not runnable`,nextAction:`Add pip to your Python: \`${t.join(" ")} -m ensurepip --upgrade\` (or reinstall Python from python.org, which bundles pip).`}}async function qs(){let e=process.platform==="win32",t=await Je("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 Je("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 Qs(){let e=await an();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 Js(){let e=Ee([{label:"your Windows user folder",path:Vs()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await Je("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(Pe(s,Bs))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(l=>`"${l}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=Se(e,"preflight"),a=e.some(l=>l.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function Xs(){try{return await fetch(cn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:cn}}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 Zs(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 Je(e,t,n=!1){return new Promise(s=>{let o=n?ln([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):ln(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>s({code:l??1,stdout:r,stderr:a})),o.on("error",()=>s({code:1,stdout:r,stderr:a}))})}import{mkdir as Ut,readdir as os,readFile as jt,stat as Kt,writeFile as Ht}from"fs/promises";import{spawnSync as Gt}from"child_process";import{homedir as bo}from"os";import{resolve as _o,isAbsolute as Io,join as X,normalize as To}from"path";import*as S from"@clack/prompts";import h from"picocolors";var ei={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"},ti={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 un(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9., ]*$/.test(n))return n;let s=ti[(t??"").toUpperCase()];return s?`${s.pre??""}${n}${s.post??""}`:n}function Ot(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?ei[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 vt="claude-code",$t="gpt-5.6-terra";function pn(e){if(e==="claude-code"||e==="codex")return e}var ni=["claude-pro","claude-max-5x","claude-max-20x","claude-other","codex-plus","codex-pro","codex-other"];function Xe(e){let t=e?.trim().toLowerCase()??"";return ni.includes(t)?t:void 0}function Ze(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 Lt="vercel";function fn(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function hn(e){if(e==="telegram"||e==="email"||e==="sms")return e}function mn(e){if(e==="password"||e==="oauth-microsoft")return e}function si(e){if(e==="custom"||e!==void 0&&Object.hasOwn(J,e))return e}function et(e){let t=si(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 gn(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let s of t.split(",")){let o=s.trim().toLowerCase();o&&o!=="primary"&&!n.includes(o)&&n.push(o)}return n.map(s=>{let o=/^[a-z0-9_]+$/.test(s)&&s!=="auto",r=l=>{let c=e[`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`];return c?.trim()?c.trim():void 0},a=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(l=>!r(l)).map(l=>`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`);for(let l of["SMTP_PORT","IMAP_PORT"]){let c=r(l);c!==void 0&&!/^\d+$/.test(c)&&a.push(`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`)}return{label:s,valid:o,auth:(r("AUTH")??"password").toLowerCase(),address:r("ADDRESS"),missing:a,smtpHost:r("SMTP_HOST"),smtpPort:parseInt(r("SMTP_PORT")??"587",10),imapHost:r("IMAP_HOST"),imapPort:parseInt(r("IMAP_PORT")??"993",10),password:r("PASSWORD"),login:r("LOGIN")}})}function tt(e){let t=[],n=l=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${l}`),t.push("# "+"=".repeat(60)),t.push("")},s=(l,c)=>{if(c==null||c===""){t.push(`# ${l}=`);return}let f=String(c);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(f)){let u=f.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${l}="${u}"`)}else t.push(`${l}=${f}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),s("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),s("AI_AGENT",e.aiAgent??vt),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",un(e.pricing,e.countryCode)),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",un(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",Ot(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??Lt),s("VERCEL_TOKEN",e.vercelToken),s("VERCEL_SCOPE",e.vercelScope??""),s("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),s("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),s("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),s("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),s("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),s("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),s("NOTIFY_CHANNEL",e.notifyChannel),s("NOTIFY_TO",e.notifyTo),s("TELEGRAM_BOT_TOKEN",e.telegramBotToken),s("TELEGRAM_CHAT_ID",e.telegramChatId);let r=new Set(t.map(l=>/^#?\s*([A-Z0-9_]+)=/.exec(l)?.[1]).filter(l=>!!l)),a=Object.entries(e.preservedEnv??{}).filter(([l])=>!r.has(l));if(a.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[l,c]of a)s(l,c)}return t.join(`
|
|
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 qs(){let e=process.platform==="win32",t=await Je("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 Je("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 Qs(){let e=await an();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 Js(){let e=Ee([{label:"your Windows user folder",path:Vs()},{label:"this folder",path:process.cwd()}]);if(e.length===0)return null;let t="Install path safe for npm builds",n=await Je("npm",["config","get","script-shell"],!0),s=n.code===0?n.stdout.trim():void 0;if(Pe(s,Bs))return{name:t,status:"ok",detail:`${e[0].label} contains ${e[0].chars.map(l=>`"${l}"`).join(", ")}, but npm's script-shell (${s}) handles it`};let{detail:o,action:r}=Se(e,"preflight"),a=e.some(l=>l.chars.includes("&"));return{name:t,status:a?"fail":"warn",detail:o,nextAction:r}}async function Xs(){try{return await fetch(cn,{method:"HEAD",signal:AbortSignal.timeout(8e3)}),{name:"klaudius.dev reachable",status:"ok",detail:cn}}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 Zs(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 Je(e,t,n=!1){return new Promise(s=>{let o=n?ln([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):ln(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>s({code:l??1,stdout:r,stderr:a})),o.on("error",()=>s({code:1,stdout:r,stderr:a}))})}import{mkdir as Ut,readdir as os,readFile as jt,stat as Kt,writeFile as Ht}from"fs/promises";import{spawnSync as Gt}from"child_process";import{homedir as bo}from"os";import{resolve as _o,isAbsolute as Io,join as X,normalize as To}from"path";import*as S from"@clack/prompts";import h from"picocolors";var ei={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"},ti={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 un(e,t){if(!e)return e;let n=e.trim();if(!/^[0-9][0-9., ]*$/.test(n))return n;let s=ti[(t??"").toUpperCase()];return s?`${s.pre??""}${n}${s.post??""}`:n}function Ot(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?ei[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 vt="claude-code",$t="gpt-5.6-terra";function pn(e){if(e==="claude-code"||e==="codex")return e}var ni=["claude-pro","claude-max-5x","claude-max-20x","claude-other","codex-plus","codex-pro","codex-other"];function Xe(e){let t=e?.trim().toLowerCase()??"";return ni.includes(t)?t:void 0}function Ze(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 Lt="vercel";function fn(e){if(e==="vercel"||e==="cloudflare"||e==="netlify"||e==="selfhost")return e}function hn(e){if(e==="telegram"||e==="email"||e==="sms")return e}function mn(e){if(e==="password"||e==="oauth-microsoft")return e}function si(e){if(e==="custom"||e!==void 0&&Object.hasOwn(J,e))return e}function et(e){let t=si(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 gn(e){let t=(e.EMAIL_ACCOUNTS??"").trim();if(!t)return[];let n=[];for(let s of t.split(",")){let o=s.trim().toLowerCase();o&&o!=="primary"&&!n.includes(o)&&n.push(o)}return n.map(s=>{let o=/^[a-z0-9_]+$/.test(s)&&s!=="auto",r=l=>{let c=e[`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`];return c?.trim()?c.trim():void 0},a=["ADDRESS","PASSWORD","SMTP_HOST","IMAP_HOST"].filter(l=>!r(l)).map(l=>`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`);for(let l of["SMTP_PORT","IMAP_PORT"]){let c=r(l);c!==void 0&&!/^\d+$/.test(c)&&a.push(`EMAIL_ACCOUNT_${s.toUpperCase()}_${l}`)}return{label:s,valid:o,auth:(r("AUTH")??"password").toLowerCase(),address:r("ADDRESS"),missing:a,smtpHost:r("SMTP_HOST"),smtpPort:parseInt(r("SMTP_PORT")??"587",10),imapHost:r("IMAP_HOST"),imapPort:parseInt(r("IMAP_PORT")??"993",10),password:r("PASSWORD"),login:r("LOGIN")}})}function tt(e){let t=[],n=l=>{t.push(""),t.push("# "+"=".repeat(60)),t.push(`# ${l}`),t.push("# "+"=".repeat(60)),t.push("")},s=(l,c)=>{if(c==null||c===""){t.push(`# ${l}=`);return}let f=String(c);if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(f)){let u=f.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");t.push(`${l}="${u}"`)}else t.push(`${l}=${f}`)};t.push("# Klaudius configuration"),t.push("# Generated by `npx klaudius init`. Edit freely."),t.push("# NEVER commit this file. .gitignore already excludes it."),n("Klaudius licence"),s("KLAUDIUS_LICENSE_KEY",e.licenseKey),n("AI coding agent"),s("AI_AGENT",e.aiAgent??vt),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(o)].join(",")),n("Pricing"),s("PRICING",un(e.pricing,e.countryCode)),s("PRICING_TERMS",e.pricingTerms),s("PRICING_MONTHLY",un(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",Ot(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??Lt),s("VERCEL_TOKEN",e.vercelToken),s("VERCEL_SCOPE",e.vercelScope??""),s("CLOUDFLARE_API_TOKEN",e.cloudflareApiToken),s("CLOUDFLARE_ACCOUNT_ID",e.cloudflareAccountId),s("NETLIFY_AUTH_TOKEN",e.netlifyAuthToken),s("NETLIFY_ACCOUNT_SLUG",e.netlifyAccountSlug??""),s("SELFHOST_DEPLOY_TARGET",e.selfhostDeployTarget),s("SELFHOST_URL_TEMPLATE",e.selfhostUrlTemplate),n("Search APIs"),s("GOOGLE_PLACES_API_KEY",e.googlePlacesApiKey),n("Notifications (optional)"),s("NOTIFY_CHANNEL",e.notifyChannel),s("NOTIFY_TO",e.notifyTo),s("TELEGRAM_BOT_TOKEN",e.telegramBotToken),s("TELEGRAM_CHAT_ID",e.telegramChatId);let r=new Set(t.map(l=>/^#?\s*([A-Z0-9_]+)=/.exec(l)?.[1]).filter(l=>!!l)),a=Object.entries(e.preservedEnv??{}).filter(([l])=>!r.has(l));if(a.length>0){n("Other settings (preserved as-is \u2014 written by skills or by hand, not by the wizard)");for(let[l,c]of a)s(l,c)}return t.join(`
|
|
5
5
|
`)+`
|
|
6
6
|
`}function nt(e){let t={mcpServers:{supabase:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest",`--project-ref=${e.supabaseProjectRef}`],env:{SUPABASE_ACCESS_TOKEN:e.supabasePat,NODE_OPTIONS:"--use-system-ca"}}}};return JSON.stringify(t,null,2)+`
|
|
7
7
|
`}function st(e){let t=e.supabaseProjectRef,n=ii(e.supabasePat);return["# Codex MCP config \u2014 generated by `npx klaudius init` / `configure`.","# Edit freely. NEVER commit this file \u2014 .gitignore already excludes it.","# See `.codex/config.toml.example` for the documented format.","",...e.aiPlan==="codex-plus"?["# Set by the wizard for ChatGPT Plus. Change or delete to use Codex's default.",`model = "${$t}"`,""]:[],"[mcp_servers.supabase]",'command = "npx"',`args = ["-y", "@supabase/mcp-server-supabase@latest", "--project-ref=${t}"]`,`env = { SUPABASE_ACCESS_TOKEN = "${n}", NODE_OPTIONS = "--use-system-ca" }`,""].join(`
|
|
8
|
-
`)}function ii(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var yn=[{key:"AI_AGENT",value:"claude-code",comment:"Which AI coding agent drives this install. Pre-codex installs were Claude Code by default \u2014 this records that explicitly so `update` re-fetches the matching template tarball and `doctor` checks the right CLI."},{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."},{key:"VERCEL_SCOPE",value:"",comment:"Vercel team slug. Leave blank unless `vercel link` errors about scope (post-2024 multi-team Vercel accounts)."},{key:"DEPLOY_PROVIDER",value:"vercel",comment:"Where the deploy skill ships client sites: 'vercel', 'cloudflare', or 'netlify'. Pre-Cloudflare installs deployed to Vercel, so this records that explicitly. To switch host, run `npx klaudius@latest configure` (Cloudflare adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID; Netlify adds NETLIFY_AUTH_TOKEN)."},{key:"PIPELINE_MODES",value:"classic",comment:"Lead streams the pipeline targets
|
|
8
|
+
`)}function ii(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var yn=[{key:"AI_AGENT",value:"claude-code",comment:"Which AI coding agent drives this install. Pre-codex installs were Claude Code by default \u2014 this records that explicitly so `update` re-fetches the matching template tarball and `doctor` checks the right CLI."},{key:"PRICING_TERMS",value:"one-off, no monthly fees",comment:"Phrasing slotted next to ${PRICING} in outreach copy. See template/CLAUDE.md."},{key:"VERCEL_SCOPE",value:"",comment:"Vercel team slug. Leave blank unless `vercel link` errors about scope (post-2024 multi-team Vercel accounts)."},{key:"DEPLOY_PROVIDER",value:"vercel",comment:"Where the deploy skill ships client sites: 'vercel', 'cloudflare', or 'netlify'. Pre-Cloudflare installs deployed to Vercel, so this records that explicitly. To switch host, run `npx klaudius@latest configure` (Cloudflare adds CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID; Netlify adds NETLIFY_AUTH_TOKEN)."},{key:"PIPELINE_MODES",value:"classic",comment:"Lead streams the pipeline targets \u2014 any combination of 'classic' (no website at all), 'rescue' (existing website verifiably dead or bad) and 'booking' (Google-listed website is a booking-platform page), at least one. Pre-modes installs targeted no-website businesses only \u2014 this records that explicitly. Edit the list (e.g. 'classic,rescue,booking') or re-run `npx klaudius@latest configure`."},{key:"OPERATOR_COUNTRY",value:"the United Kingdom",comment:"Operating country (canonical full name). Used as the default region for /find."},{key:"OPERATOR_COUNTRY_CODE",value:"GB",comment:"ISO 3166-1 alpha-2 code. Passed to the Google Places API for region biasing."},{key:"OPERATOR_LANGUAGE",value:"English",comment:"Language all outreach + websites are written in."},{key:"OPERATOR_LANGUAGE_CODE",value:"en",comment:'ISO 639-1 code. Used by Google Places + <html lang="..."> on built sites.'},{key:"NOTIFY_CHANNEL",value:"telegram",comment:"How scripts/notify.sh routes pipeline alerts: 'telegram' (default), 'email' (to your own inbox), or 'sms' (to your own phone). Pre-NOTIFY_CHANNEL installs alerted via Telegram, so this records that explicitly. NOTIFY_TO optionally overrides the email/sms destination."},{key:"QA_PHASE",value:"on",comment:"'on' runs the independent QA pass after each build (the behaviour this install already had); 'off' goes straight from build to deploy for more sites per usage window. Flip it here any time, or run `npx klaudius@latest configure` and pick your plan to get the matching default."}];function oi(e,t){if(/[\s"'`$\\#&|<>;()*?\[\]{}!~]/.test(t)){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");return`${e}="${n}"`}return`${e}=${t}`}function wn(e,t,n){let s=n.filter(a=>!(a.key in t));if(s.length===0)return null;let o=e.endsWith(`
|
|
9
9
|
`)?"":`
|
|
10
10
|
`,r=["","# "+"=".repeat(60),"# Backfilled by `klaudius update` (new template env keys)","# "+"=".repeat(60)];for(let a of s)r.push(""),a.comment&&r.push(`# ${a.comment}`),r.push(oi(a.key,a.value));return e+o+r.join(`
|
|
11
11
|
`)+`
|
|
12
12
|
`}function ri(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\\$/g,"$").replace(/\\`/g,"`"):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function G(e){let t={};for(let n of e.split(`
|
|
13
13
|
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),a=ri(s.slice(o+1).trim());t[r]=a}return t}function kn(e){let t=l=>{let c=e[l];if(!c)return;let f=parseInt(c,10);return isNaN(f)?void 0:f},n=e.SMS_PROVIDER,s=l=>l==="email"||l==="sms"||l==="whatsapp"||l==="letter",o=e.OUTREACH_CHANNELS?.split(",").map(l=>l.trim()).filter(s),r=e.OUTREACH_PRIORITY?.split(",").map(l=>l.trim()).filter(s),a=e.WHATSAPP_ACCOUNTS?.split(",").map(l=>l.trim()).filter(l=>l.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:pn(e.AI_AGENT)??vt,aiPlan:Xe(e.AI_PLAN),qaPhase:Ze(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(l=>l.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:o&&o.length>0?o:void 0,outreachPriority:r&&r.length>0?r:void 0,whatsappAccounts:a&&a.length>0?a:void 0,emailProvider:et(e),emailAuth:mn(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:Ot(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:fn(e.DEPLOY_PROVIDER)??Lt,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:hn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function it(e){let t=_=>{let ce=e[_];if(!ce)return;let j=parseInt(ce,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,""),r=e.SUPABASE_PROJECT_REF,a=e.PRICING,l=e.PRICING_TERMS||"one-off, no monthly fees",c=fn(e.DEPLOY_PROVIDER)??Lt,f=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,w=e.CLOUDFLARE_ACCOUNT_ID,d=e.NETLIFY_AUTH_TOKEN,P=e.SELFHOST_DEPLOY_TARGET,y=e.SELFHOST_URL_TEMPLATE;if(!a||!n||!s||!o||!r||!(c==="cloudflare"?!!u&&!!w:c==="netlify"?!!d:c==="selfhost"?!!P&&!!y:!!f))return null;let b=e.SMS_PROVIDER,C=_=>_==="email"||_==="sms"||_==="whatsapp"||_==="letter",V=e.OUTREACH_CHANNELS?.split(",").map(_=>_.trim()).filter(C),le=e.OUTREACH_PRIORITY?.split(",").map(_=>_.trim()).filter(C),R=e.WHATSAPP_ACCOUNTS?.split(",").map(_=>_.trim()).filter(_=>_.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:pn(e.AI_AGENT)??vt,aiPlan:Xe(e.AI_PLAN),qaPhase:Ze(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(_=>_.trim().toLowerCase()).filter(Boolean):void 0,pricing:a,pricingTerms:l,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:V&&V.length>0?V:void 0,outreachPriority:le&&le.length>0?le:void 0,whatsappAccounts:R&&R.length>0?R:void 0,emailProvider:et(e),emailAuth:mn(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:Ot(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,letterProvider:e.LETTER_PROVIDER==="pingen"||e.LETTER_PROVIDER==="postgrid"?e.LETTER_PROVIDER:void 0,pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,deployProvider:c,vercelToken:f,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:u||void 0,cloudflareAccountId:w||void 0,netlifyAuthToken:d||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:P||void 0,selfhostUrlTemplate:y||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:r,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:hn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as ua,mkdir as pa,readdir as hi,stat as fa}from"fs/promises";import{dirname as ma,join as In,relative as mi,sep as gi}from"path";import{fileURLToPath as ya}from"url";import{createHash as An}from"crypto";import{readFile as ai}from"fs/promises";async function _e(e){let t=await ai(e);return An("sha256").update(t).digest("hex")}function Nt(e){return An("sha256").update(e).digest("hex")}import{mkdir as li,readFile as ci,writeFile as di,access as ui}from"fs/promises";import{dirname as pi,join as En}from"path";var fi=".klaudius",Pn=`${fi}/manifest.json`,ot=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml",".ms-token.json"]),Sn=new Set(["clients/README.md"]),rt=new Set(["package-lock.json"]);async function bn(e){let t=En(e,Pn);try{await ui(t)}catch{return null}let n=await ci(t,"utf-8"),s=JSON.parse(n),o={};for(let[r,a]of Object.entries(s.files??{}))o[r.split("\\").join("/")]=a;return s.files=o,Array.isArray(s.ignored)?s.ignored=s.ignored.filter(r=>typeof r=="string").map(r=>r.split("\\").join("/")):delete s.ignored,s}async function Me(e,t){let n=En(e,Pn);await li(pi(n),{recursive:!0}),await di(n,JSON.stringify(t,null,2)+`
|
|
14
|
-
`,"utf-8")}function _n(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 hi(e,{withFileTypes:!0}),s=[];for(let o of n){let r=In(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await ge(r,t)):o.isFile()&&s.push(mi(t,r).split(gi).join("/")))}return s}async function Tn(e){let t=await ge(e),n={};for(let s of t)ot.has(s)||(n[s]=await _e(In(e,s)));return n}import{copyFile as yi,mkdir as Cn,mkdtemp as wi,readdir as Rn,rm as xn}from"fs/promises";import{tmpdir as ki}from"os";import{dirname as Ai,join as at}from"path";import{Readable as Ei}from"stream";import*as On from"tar";var Pi="https://klaudius.dev/api/template";function Si(e){return Ei.fromWeb(e)}async function lt(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Pi,n="0.
|
|
15
|
-
`+pe.bold(pe.cyan(e))),detail:e=>console.log(pe.dim(" "+e))};var Ri="https://registry.npmjs.org/klaudius/latest";async function xi(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Ri,{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 Oi(e,t){let n=r=>r.split("-")[0].split(".").map(a=>Number.parseInt(a,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(s[r])||Number.isNaN(o[r]))return!1;if(s[r]>o[r])return!0;if(s[r]<o[r])return!1}return!1}async function ut(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await xi();!n||!Oi(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 vi}from"crypto";import{hostname as Fn,userInfo as $i,platform as Hn,arch as Un}from"os";var Li="https://klaudius.dev",Ni="/api/licenses/validate",Mi="0.
|
|
14
|
+
`,"utf-8")}function _n(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 hi(e,{withFileTypes:!0}),s=[];for(let o of n){let r=In(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await ge(r,t)):o.isFile()&&s.push(mi(t,r).split(gi).join("/")))}return s}async function Tn(e){let t=await ge(e),n={};for(let s of t)ot.has(s)||(n[s]=await _e(In(e,s)));return n}import{copyFile as yi,mkdir as Cn,mkdtemp as wi,readdir as Rn,rm as xn}from"fs/promises";import{tmpdir as ki}from"os";import{dirname as Ai,join as at}from"path";import{Readable as Ei}from"stream";import*as On from"tar";var Pi="https://klaudius.dev/api/template";function Si(e){return Ei.fromWeb(e)}async function lt(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Pi,n="0.32.0",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(l){throw new Error(`Could not reach klaudius.dev to download the template: ${T(l)}`)}if(!s.ok){let l="";try{let c=await s.json();l=c.reason?` (${c.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${s.status}${l}`)}if(!s.body)throw new Error("Template download succeeded but response had no body");let o=s.headers.get("x-klaudius-tier"),r=await wi(at(ki(),"klaudius-template-")),a=0;try{try{await new Promise((f,u)=>{let w=On.extract({cwd:r,strict:!0});w.on("finish",f),w.on("error",u),Si(s.body).on("error",u).pipe(w)})}catch(f){throw new Error(`Failed to extract template archive: ${f.message}`)}await Cn(e.destDir,{recursive:!0});let l=new Set(await Rn(e.destDir)),c=await ge(r);try{for(let f of c){let u=at(e.destDir,f);await Cn(Ai(u),{recursive:!0}),await yi(at(r,f),u),a++}}catch(f){let u=await Rn(e.destDir).catch(()=>[]);for(let w of u)l.has(w)||await xn(at(e.destDir,w),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${f.message}`)}}finally{await xn(r,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:a,tier:o}}import{copyFile as bi,mkdir as _i,readFile as vn,rm as Ii}from"fs/promises";import{dirname as Ti,join as ye}from"path";import{structuredPatch as Ci}from"diff";var $n=ye(".klaudius","base"),ct=ye(".klaudius","conflict-base");async function dt(e,t,n){let s=ye(e,$n);await Ii(s,{recursive:!0,force:!0});for(let o of n){let r=ye(s,o);await _i(Ti(r),{recursive:!0}),await bi(ye(t,o),r)}}async function Ln(e,t){try{return await vn(ye(e,$n,t),"utf-8")}catch{return null}}async function Nn(e,t){try{return await vn(ye(e,ct,t),"utf-8")}catch{return null}}function Mn(e,t,n,s){return Ie(n)?null:e!==null&&!Ie(e)&&(!s||Nt(e)===s)?e:t!==null&&!Ie(t)&&s&&Nt(t)===s?t:null}function Ie(e){return e.includes("\0")||e.includes("\uFFFD")}function Dn(e,t,n=60){let s=Ci("base","new",e,t,"","",{context:2});if(s.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=s.hunks.map(c=>`${c.newStart}-${c.newStart+Math.max(c.newLines-1,0)}`).join(", "),r=[`Upstream changed ${s.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],a=0,l=!1;for(let c of s.hunks){if(a>=n){l=!0;break}r.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),a+=1;let f=Math.max(n-a,0),u=c.lines.slice(0,f);if(r.push(...u),a+=u.length,u.length<c.lines.length){l=!0;break}}return r.push("```"),l&&r.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),r}import pe from"picocolors";var i={info:e=>console.log(pe.cyan("\u2139"),e),success:e=>console.log(pe.green("\u2713"),e),warn:e=>console.log(pe.yellow("\u26A0"),e),error:e=>console.error(pe.red("\u2717"),e),step:e=>console.log(pe.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
|
|
15
|
+
`+pe.bold(pe.cyan(e))),detail:e=>console.log(pe.dim(" "+e))};var Ri="https://registry.npmjs.org/klaudius/latest";async function xi(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Ri,{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 Oi(e,t){let n=r=>r.split("-")[0].split(".").map(a=>Number.parseInt(a,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let r=0;r<3;r++){if(Number.isNaN(s[r])||Number.isNaN(o[r]))return!1;if(s[r]>o[r])return!0;if(s[r]<o[r])return!1}return!1}async function ut(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await xi();!n||!Oi(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 vi}from"crypto";import{hostname as Fn,userInfo as $i,platform as Hn,arch as Un}from"os";var Li="https://klaudius.dev",Ni="/api/licenses/validate",Mi="0.32.0";async function jn(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??Li).replace(/\/$/,"")+Ni,o=De(),r;try{r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:Fn(),os:`${Hn()}-${Un()}`,cli_version:Mi})})}catch(l){return{ok:!1,reason:`Could not reach the Klaudius license server (${T(l)}). Check your internet connection or try again later.`}}let a;try{a=await r.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${r.status}).`}}return a.ok?{ok:!0,tier:a.tier??"core"}:{ok:!1,reason:a.reason??`License rejected (HTTP ${r.status}).`}}function De(){let e=[Fn(),$i().username,Hn(),Un()].join("|");return vi("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Di}from"fs/promises";import{join as Fi}from"path";async function Te(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: ${T(n)}`}}}async function Kn(e){let t;try{t=await Di(Fi(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 pt(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: ${T(t)}`}}}var Gn="https://api.cloudflare.com/client/v4";function Bn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function ft(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${Gn}/user/tokens/verify`,{headers:s});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let r=await o.json(),a=r.result?.status;if(r.success===!1||a&&a!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${a?` (status: ${a})`:""}. ${Bn(r)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${T(o)}`}}try{let o=await fetch(`${Gn}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:s});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let r=await o.json();return r.success===!1?{ok:!1,message:Bn(r)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(r.result)?r.result.length:void 0}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${T(o)}`}}}var Vn="https://api.netlify.com/api/v1";async function ht(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${Vn}/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: ${T(s)}`}}try{let s=await fetch(`${Vn}/accounts`,{headers:n});if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} listing your teams. Try again or check netlifystatus.com.`};let o=await s.json(),r=Array.isArray(o)?o:[];if(r.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let a=typeof r[0]?.slug=="string"?r[0].slug:void 0;return{ok:!0,accountCount:r.length,accountSlug:a}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${T(s)}`}}}function Hi(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=nn(e);if(t)return{ok:!1,message:t};let n=de(e),s=n.value,o=r=>{let a=[r],l=sn(e);return l&&a.push(l),n.repairs.length>0&&a.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),a.join(`
|
|
16
16
|
`)};try{let r=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(r.ok)return{ok:!0};if(r.status===429)return{ok:!0};let a={};try{a=await r.json()}catch{}let l=a.error?.message??"",c=a.error?.status??"";return r.status===400&&(c==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(l))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library/places.googleapis.com and press Enable for the project this key belongs to, then try again. (That page is 'Places API (New)' \u2014 the older 'Places API' is a different API and won't work.)"}:r.status===401||r.status===403?{ok:!1,message:o(Hi(r.status,l))}:{ok:!1,message:o(`Google API returned HTTP ${r.status}${l?`: ${l}`:""}.`)}}catch(r){return{ok:!1,message:`Could not reach Google: ${T(r)}`}}}import Ui from"nodemailer";import{ImapFlow as ji}from"imapflow";function Ki(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function Yn(e,t,n){let s=t.toLowerCase(),o=e.filter(Ki);if(o.some(l=>l.path.toLowerCase()===s))return;let r=s.startsWith("inbox")?void 0:[`inbox.${s}`,`inbox/${s}`],a=o.find(l=>l.specialUse===n)?.path??(r&&o.find(l=>r.includes(l.path.toLowerCase()))?.path);return{configured:t,detected:a||void 0}}function Wn(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 oe(e){let t=Ui.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(a){return{ok:!1,failedAt:"smtp",message:zn(a,"SMTP",e.usesAccountPassword),failureKind:Wn(a)}}finally{t.close()}let n=new ji({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,o,r;try{if(await n.connect(),e.sentFolder||e.draftsFolder)try{let a=await n.list();e.sentFolder&&(s=Yn(a,e.sentFolder,"\\Sent")),e.draftsFolder&&(o=Yn(a,e.draftsFolder,"\\Drafts"))}catch{r=!0}await n.logout()}catch(a){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:zn(a,"IMAP",e.usesAccountPassword),failureKind:Wn(a)}}return{ok:!0,sentFolderIssue:s,draftsFolderIssue:o,foldersUnverified:r}}function zn(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 ke,c as Be,d as J,e as T,f as en,g as tn,h as Ve,i as Ye,j as de,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}`}import*as mt from"@clack/prompts";var Gi=[{key:"emailSentFolder",envKey:"EMAIL_SENT_FOLDER",label:"Sent",consequence:"Sent mail wouldn't be filed there, and follow-ups couldn't see what was sent to whom.",issue:e=>e.sentFolderIssue},{key:"emailDraftsFolder",envKey:"EMAIL_DRAFTS_FOLDER",label:"Drafts",consequence:"Saving drafts (manual-approval outreach, /send-invoice) would fail.",issue:e=>e.draftsFolderIssue}];async function gt(e,t,n){let s=!1;for(let o of Gi){let r=o.issue(e);if(r){if(i.blank(),r.detected){if(n.nonInteractive){t[o.key]=r.detected,s=!0,i.warn(`Your mailbox has no "${r.configured}" folder \u2014 it calls its ${o.label} folder "${r.detected}". Using that.`);continue}i.warn(`Your mailbox has no "${r.configured}" folder.`),i.detail(`It calls its ${o.label} folder "${r.detected}".`);let a=await mt.confirm({message:`Use "${r.detected}" instead?`,initialValue:!0});if(mt.isCancel(a))return n.onCancel?.(),s;a?(t[o.key]=r.detected,s=!0,i.success(`${o.envKey} set to "${r.detected}"`)):i.warn(`Keeping "${r.configured}". ${o.consequence}`);continue}i.warn(`Your mailbox has no "${r.configured}" folder. ${o.consequence}`),i.detail(`After setup, ask your AI agent to list the mailbox's folders and set ${o.envKey} in .env to the real name.`)}}return s}async function qn(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: ${T(s)}`}}}async function yt(e){return e.provider==="pingen"?Bi(e):Vi(e)}async function Bi(e){if(!e.pingenClientId||!e.pingenClientSecret||!e.pingenOrgId)return{ok:!1,message:"Missing Pingen Client ID, Client Secret, or organisation id."};let t=e.pingenStaging?"https://identity-staging.pingen.com":"https://identity.pingen.com",n=e.pingenStaging?"https://api-staging.pingen.com":"https://api.pingen.com";try{let s=await fetch(`${t}/auth/access-tokens`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:e.pingenClientId,client_secret:e.pingenClientSecret,scope:"letter"})});if(!s.ok)return{ok:!1,message:`Pingen rejected the API client credentials (HTTP ${s.status}). Check the Client ID and Secret under your organisation's 'API Access' page \u2014 note that staging and production credentials are separate.`};let o=(await s.json()).access_token;if(!o)return{ok:!1,message:"Pingen returned no access token \u2014 try again."};let r=await fetch(`${n}/organisations/${encodeURIComponent(e.pingenOrgId)}/deliveries/letters?page[limit]=1`,{headers:{Authorization:`Bearer ${o}`}});return r.status===403||r.status===404?{ok:!1,message:"Pingen accepted the credentials but not the organisation id. Copy it from the dashboard URL: app.pingen.com/organisations/<id>/\u2026"}:r.ok?{ok:!0,friendlyName:e.pingenStaging?"staging \u2014 letters will NOT print":void 0}:{ok:!1,message:`Pingen API returned HTTP ${r.status}. Try again shortly.`}}catch(s){return{ok:!1,message:`Could not reach Pingen: ${T(s)}`}}}async function Vi(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: ${T(t)}`}}}import{spawn as Yi}from"child_process";async function Qn(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 Wi(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 Wi(e){return new Promise(t=>{let n=Yi("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 wt}from"child_process";import{existsSync as zi}from"fs";import{homedir as qi}from"os";function Qi(){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,Jn=2e3,Ji=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function Xn(e,t){let n=e+`
|
|
27
27
|
`+t;return Ji.some(s=>s.test(n))}function Zn(e){return new Promise(t=>setTimeout(t,e))}function Xi(e,t,n){return new Promise(s=>{let o=n.shell?wt([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):wt(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),r="",a="";o.stdout?.on("data",l=>{let c=l.toString();r+=c,process.stdout.write(c)}),o.stderr?.on("data",l=>{let c=l.toString();a+=c,process.stderr.write(c)}),o.on("close",l=>s({code:l??1,stdout:r,stderr:a})),o.on("error",l=>s({code:1,stdout:r,stderr:a+l.message}))})}async function Mt(e,t,n){let s={code:0,stdout:"",stderr:""};for(let o=0;o<=Re;o++){if(s=await Xi(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),s.code===0||!Xn(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 Zn(Jn))}return s}function Zi(e,t,n){return new Promise(s=>{let o=wt(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),r="",a="";o.stdout?.on("data",l=>{r+=l.toString()}),o.stderr?.on("data",l=>{a+=l.toString()}),o.on("close",l=>s({code:l??1,stdout:r,stderr:a})),o.on("error",l=>s({code:1,stdout:r,stderr:a+l.message}))})}var eo=[{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 to(e){let t=`${e.stderr??""}
|
|
28
28
|
${e.stdout??""}`;return eo.find(s=>s.pattern.test(t))?.hint}async function no(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await K())?.command??["python3"],r=async l=>{let c={code:0,stdout:"",stderr:""};for(let f=0;f<=Re;f++){if(c=await Zi(o[0],[...o.slice(1),...l],{cwd:e}),c.code===0||!Xn(c.stderr,c.stdout))return c;f<Re&&(i.detail(`pip install hit a transient network error \u2014 retrying (${f+2}/${Re+1})\u2026`),await Zn(Jn))}return c},a=await r([...n,"--break-system-packages",...t]);return a.code!==0&&/no such option:.*break-system-packages/i.test(a.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),a=await r([...n,...t])),a.code!==0&&(a.stderr.trim()&&process.stderr.write(a.stderr),a.stdout.trim()&&process.stdout.write(a.stdout)),a}async function kt(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=Qi(),s=process.platform==="win32",o;if(s){let u=Ee([{label:"your Windows user folder",path:qi()},{label:"the project folder",path:e}]);if(u.length>0){let w=await new Promise(P=>{let y=wt("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=>P({code:C??1,stdout:E,stderr:b})),y.on("error",C=>P({code:1,stdout:E,stderr:C.message}))}),d=w.code===0?w.stdout.trim():void 0;if(!Pe(d,zi)){let{detail:P,action:y}=Se(u,"install");o=`${P}. ${y}`}}}let r=(u,w)=>{let d=to(w);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 a=await Mt("npm",["install"],{cwd:e,label:"npm install",env:n,shell:s});t.npm=a.code===0?"ok":"failed",a.code!==0&&r("npm",a),i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let l=await no(e);t.pip=l.code===0?"ok":"failed",l.code!==0&&r("pip",l),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Mt("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:s});t.playwright=c.code===0?"ok":"failed",c.code!==0&&r("playwright",c),i.step("Installing Patchright browser (chromium ~200MB; one-time)...");let f=await Mt("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:s});return t.patchright=f.code===0?"ok":"failed",f.code!==0&&r("patchright",f),t}import{copyFile as so,access as io}from"fs/promises";import{dirname as oo,join as ro}from"path";async function es(){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 Dt(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await es();if(e.state==="real")return{status:"ok",version:e.version};let t=await K();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function ao(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 r=ro(oo(o),"python3.exe"),a=await io(r).then(()=>!0,()=>!1);if(!a){if(/[\\/]WindowsApps[\\/]/i.test(r))return{ok:!1,reason:"store-python",target:r};try{await so(o,r)}catch{return{ok:!1,reason:"not-writable",target:r,manualCommand:`copy "${o}" "${r}"`}}}let l=await es();return{ok:!0,target:r,created:!a,verified:l.state==="real",postState:l.state==="real"?void 0:l.state}}var lo="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 At(){let e=await Dt();if(e.status!=="broken")return;let t=await ao(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(lo);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 co,spawnSync as ts}from"child_process";import{mkdtemp as uo,rm as po,rmdir as fo,writeFile as ho,stat as Ft,unlink as mo,mkdir as go}from"fs/promises";import{createServer as yo}from"net";import{tmpdir as wo}from"os";import{join as xe}from"path";function ko(){return new Promise((e,t)=>{let n=yo();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 Et(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?ts(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):ts("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function Pt(e){try{return await Ao(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function Ao(e){let t=`klaudius-smoke-${process.pid}`,n=xe(".klaudius",`qa-smoke-${process.pid}.png`),s=xe(e,n),o,r,a=!1;try{o=await uo(xe(wo(),"klaudius-qa-smoke-")),await ho(xe(o,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let l=await ko();r=co("python3",["-m","http.server",String(l),"--directory",o],{stdio:"ignore",shell:!1});let c=!1;r.on("error",()=>{c=!0}),r.on("exit",()=>{c=!0});let f=`http://127.0.0.1:${l}/`,u=!1;for(let b=0;b<24&&!c;b++)try{if((await fetch(f,{signal:AbortSignal.timeout(1e3)})).ok){u=!0;break}}catch{await new Promise(C=>setTimeout(C,500))}if(!u)return{ok:!1,stage:"python3-server",detail:"`python3 -m http.server` never came up on a free local port",remediation:process.platform==="win32"?"python3 on this machine isn't runnable (usually the Microsoft Store placeholder). Running `npx klaudius@latest update` fixes it automatically.":"Check `python3 --version` works in this terminal."};let w=xe(e,".klaudius"),d=await Ft(w).then(()=>!0,()=>!1);await go(w,{recursive:!0}),a=!d;let P=Et(e,[`-s=${t}`,"open",f]);if(P.status!==0)return{ok:!1,stage:"browser",detail:((P.stderr??"")+(P.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=Et(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),E=await Ft(s).catch(()=>null);if((!E||E.size===0)&&(y=Et(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),E=await Ft(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{Et(e,[`-s=${t}`,"close"]),r&&!r.killed&&r.kill(),await mo(s).catch(()=>{}),a&&await fo(xe(e,".klaudius")).catch(()=>{}),o&&await po(o,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as Eo,readFile as Po,writeFile as So}from"fs/promises";import{join as ns}from"path";async function St(e,t){let n=ns(e,".claude");await Eo(n,{recursive:!0});let s=ns(n,"settings.json"),o={};try{let c=await Po(s,"utf-8"),f=JSON.parse(c);f&&typeof f=="object"&&!Array.isArray(f)&&(o=f)}catch{}let r=o.enabledMcpjsonServers,a=Array.isArray(r)?r.filter(c=>typeof c=="string"):[];a.includes(t)||a.push(t);let l={...o,enabledMcpjsonServers:a};await So(s,JSON.stringify(l,null,2)+`
|
|
29
|
-
`,"utf-8")}var ss="0.
|
|
29
|
+
`,"utf-8")}var ss="0.32.0",v=5,F=!1;function H(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 Co(e){let t;try{t=await jt(e,"utf-8")}catch{H("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let s=JSON.parse(n),o={};for(let[r,a]of Object.entries(s))a!=null&&(o[r]=typeof a=="string"?a:String(a));return o}catch(s){H("answers",`Answers file is not valid JSON: ${s.message}`)}return G(t)}function re(e){return`npx klaudius@latest init ${bt(Oe(e))}`}function Oe(e){if(process.platform==="win32")return e;let t=bo();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function Ro(e){let t=[];try{let s=(await os(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let r=X(e,o.name);if(!await is(X(r,".env")))continue;let a=await is(X(r,".klaudius","manifest.json"));if(t.push({path:r,finished:a}),t.length>=3)break}}catch{}return t}async function is(e){try{return await Kt(e),!0}catch{return!1}}function bt(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(re(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 rs(e){let t=e.target??".",n=Io(t)?t:_o(process.cwd(),t),s=$o(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"&&Lo()&&(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 ut("init",ss);let o=await xo(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 ${bt(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 p=t===".",g=await Ro(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(re(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(),p?(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 r=null;e.answers&&(F=!0,r=await Co(e.answers),i.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let a=e.license??r?.KLAUDIUS_LICENSE_KEY;F&&(!a||a.trim().length===0)&&H("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let l=await vo(a),c=S.spinner();c.start("Validating license");let f=await jn(l);f.ok||(c.stop(`License invalid: ${f.reason??"unknown"}`,2),i.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),F&&H("license",`${f.reason??"The license could not be validated."} If you believe this is in error, email hello@klaudius.dev with your purchase details.`),process.exit(1)),c.stop(`License valid (${f.tier??"core"} tier)`);let u=await be();u.ok||(i.error(u.message??"Python version check failed."),i.blank(),i.detail(`Once you've installed Python 3.10+, re-run the same command: ${re(n)}`),process.exit(1)),await At();let w=ue();w.ok||(i.error(w.message??"Node.js version check failed."),i.blank(),i.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${re(n)}`),process.exit(1));let d,P=!1;if(r){let p=it(r);p||H("answers","The answers file is missing required fields. Required: PRICING, SUPABASE_URL, SUPABASE_SERVICE_KEY, SUPABASE_PAT, SUPABASE_PROJECT_REF, plus the credentials for your DEPLOY_PROVIDER (VERCEL_TOKEN, or CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID, or NETLIFY_AUTH_TOKEN, or SELFHOST_DEPLOY_TARGET + SELFHOST_URL_TEMPLATE). Keys match a working .env."),d=p,i.success("Loaded setup answers (non-interactive mode)")}else if(o.kind==="partial")if(await Oo(n)==="resume"){let g=await jt(o.envPath,"utf-8"),m=it(G(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,P=!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 jt(o.envPath,"utf-8"),m=it(G(g));d=await N(m??{})}else d=await N();d.licenseKey=l,await M(n,d),P||(i.success("Saved .env"),i.success(d.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.blank();for(let p=1;;p++){let g=S.spinner();g.start("Validating Supabase credentials");let m=await Te({url:d.supabaseUrl,serviceKey:d.supabaseServiceKey});if(m.ok){g.stop("Supabase credentials accepted");break}g.stop(m.message??"Supabase check failed",2),p>=v&&ee(n,"Supabase",m.message??"Supabase check failed");let A=m.message??"Supabase check failed";i.blank(),F&&H("supabase",A),i.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${p+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
|
|
|
@@ -101,7 +101,7 @@ password. Your browser will open to Microsoft's sign-in page \u2014
|
|
|
101
101
|
sign in as `+(d.emailAddress??"your outreach mailbox")+` and approve.
|
|
102
102
|
(No browser on this machine? It falls back to a short code you can
|
|
103
103
|
enter from any device.)`)),i.blank();let p=await K();if(p){let[g,...m]=p.command,A=Gt(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.`)),k(p))}else console.log(h.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),k(null)}else we&&!Le&&(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,...V?["schema"]:[]];if(x.length>0){S.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,Ge]of Object.entries(_))console.log(h.yellow(`Likely cause of ${D} failure:`)),console.log(h.dim(` ${Ge}`)),i.blank();let p=n!==process.cwd()&&e.target?` ${h.cyan(`cd ${bt(e.target)}`)}
|
|
104
|
-
`:"",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(),p&&process.stdout.write(p),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(),p&&process.stdout.write(p),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retry the failing installers")}`),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify everything")}`),i.blank()),V&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(le)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),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 ${No()}`)),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(Mo(d,n,e.target),y){let p=d.aiAgent==="codex"?"Codex":"Claude Code";console.log(h.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(h.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(h.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(h.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(h.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(h.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(h.cyan(' and send a test email to my own address to confirm."')),d.outreachEnabled&&(d.outreachChannels??[]).length>0&&(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 Ut(e,{recursive:!0}),await Ht(X(e,".env"),tt(t),"utf-8"),t.aiAgent==="codex"?(await Ut(X(e,".codex"),{recursive:!0}),await Ht(X(e,".codex","config.toml"),st(t),"utf-8")):(await Ht(X(e,".mcp.json"),nt(t),"utf-8"),await St(e,"supabase"))}async function xo(e){try{(await Kt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await os(e),n=t.filter(l=>!l.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(l=>s.has(l)),r=n.includes(".env"),a=t.includes(".klaudius");if(o&&r&&!a)return{kind:"partial",envPath:X(e,".env")};if(a&&r){let l=!0;try{l=!(await Kt(X(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function Oo(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 S.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 S.isCancel(t)&&(S.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function vo(e){if(e&&e.trim().length>0)return e;S.intro("Klaudius");let t=await S.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 S.isCancel(t)&&(S.cancel("Setup cancelled. No files written."),process.exit(0)),t}function $o(e){let t=To(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 Lo(){if(process.platform!=="win32")return!1;try{return Gt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function No(){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 Mo(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(S.outro(h.green(h.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ae(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${We[e.aiPlan]}`),console.log(h.dim(r?` \u2192 QA pass off${e.aiPlan==="codex-plus"&&e.aiAgent==="codex"?", model pinned to Terra":""}, so each run fits your usage window.`:" \u2192 full pipeline, including the independent QA pass after every build.")),console.log(h.dim(` Change it any time: ask ${o} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),i.blank()}if(console.log(h.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let r=`cd ${bt(n)}`;console.log(` ${h.cyan(r)}${" ".repeat(Math.max(1,27-r.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 Do,readFile as Fo}from"fs/promises";import{join as Bt,resolve as Ho}from"path";import Y from"picocolors";async function ls(e){let t=e.target?Ho(process.cwd(),e.target):process.cwd(),n=await as(Bt(t,".env")),s=await as(Bt(t,"package.json"));(!n||!s)&&(i.error("This doesn't look like a Klaudius project."),i.detail(`Path: ${t}`),n||i.detail("Missing: .env"),s||i.detail("Missing: package.json"),i.blank(),i.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),i.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{G(await Fo(Bt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let r=await kt(t);i.blank(),i.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let a=[];if(r.npm==="failed"&&a.push("npm"),r.pip==="failed"&&a.push("pip"),r.playwright==="failed"&&a.push("playwright"),r.patchright==="failed"&&a.push("patchright"),a.length===0){i.blank(),console.log(Y.green(Y.bold("All dependencies installed."))),console.log(Y.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(Y.yellow(Y.bold(`${a.join(", ")} still failing.`))),i.blank();for(let[u,w]of Object.entries(r.hints??{}))console.log(Y.yellow(`Likely cause of ${u} failure:`)),console.log(Y.dim(` ${w}`)),i.blank();let l=o==="codex"?"codex":"claude",c=o==="codex"?"Codex":"Claude Code",f=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(Y.dim("Options:")),console.log(Y.dim(` \u2022 Open ${c} in this folder (\`${l}\`) and paste:`)),console.log(Y.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(Y.dim(` (Don't have ${c} yet? Install with: \`${f}\`)`)),console.log(Y.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(Y.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function as(e){try{return await Do(e),!0}catch{return!1}}import{readFile as Uo,writeFile as Vt,access as jo}from"fs/promises";import{join as ve}from"path";import*as te from"@clack/prompts";import ae from"picocolors";import{mkdir as Ko}from"fs/promises";import{spawnSync as cs}from"child_process";async function ds(e){let t=e.projectRoot??process.cwd(),n=ve(t,".env"),s=ve(t,".mcp.json"),o=ve(t,".codex","config.toml"),r=await Yt(ve(t,".klaudius","manifest.json")),a=await Yt(n);!r&&!a&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let l=ue();l.ok||(i.error(l.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let c={};try{let P=await Uo(n,"utf-8");c=G(P)}catch{i.warn("No .env found. Starting from an empty configuration.")}let f=kn(c);Object.keys(c).length>0&&(f.pipelineModes??=["classic"]),te.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let u=await N(f),w=f.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==w&&(i.error(`Switching AI coding agent (${w} \u2192 ${u.aiAgent}) isn't supported via configure.`),i.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest init <new-folder>")} ${ae.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==c.SUPABASE_URL||u.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let P=await Te({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});P.ok||(i.error(P.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let d=de(u.googlePlacesApiKey??"");if(d.changed&&u.googlePlacesApiKey){i.heading("Checking your Google Places API key");let P=await Ce(u.googlePlacesApiKey);if(P.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(P.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(Go(u,c)){let P=te.spinner();P.start("Validating email credentials (SMTP + IMAP)");let y=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:ke(u.emailSmtpHost),E=await oe({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:y?J[y].usesAccountPassword:void 0,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});E.ok?(P.stop("Email credentials accepted (SMTP + IMAP)"),await gt(E,u,{nonInteractive:!1,onCancel:()=>i.detail("Left the folder names as they are.")})):(P.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 Vt(n,tt(u),"utf-8"),i.success("Updated .env"),u.aiAgent==="codex"?(await Ko(ve(t,".codex"),{recursive:!0}),await Vt(o,st(u),"utf-8"),i.success("Updated .codex/config.toml")):(await Vt(s,nt(u),"utf-8"),i.success("Updated .mcp.json"),await St(t,"supabase")),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let P=await K();if(!(P!==null&&cs(P.command[0],[...P.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!P)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: ${P.command.join(" ")} scripts/ms_oauth.py login`):cs(P.command[0],[...P.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: ${P.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),te.outro(ae.green("Configuration updated.")),await Bo(t,r)}function Go(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];if(n.some(([o])=>o===void 0||o===""))return!1;let s=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([o,r])=>String(o)!==(t[r]??""))||s.some(([o,r])=>o!==void 0&&o!==(t[r]??""))}async function Bo(e,t){let n=await Yt(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(` ${ae.cyan("npx klaudius@latest install")} ${ae.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest doctor")} ${ae.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest init")} ${ae.dim("# pick Resume when prompted")}`),i.blank())}async function Yt(e){try{return await jo(e),!0}catch{return!1}}import{copyFile as us,mkdir as Wt,readFile as _t,rm as fe,writeFile as It,access as ps}from"fs/promises";import{dirname as zt,join as $}from"path";import{tmpdir as Vo}from"os";import*as he from"@clack/prompts";import Fe from"picocolors";var He="0.31.1";async function fs(e){let t=e.projectRoot??process.cwd(),n=await bn(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 k of ot)delete n.files[k];let s,o=$(t,".env"),r,a;try{r=await _t(o,"utf-8"),a=G(r)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=a.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let l=e.check?null:wn(r,a,yn);l!==null&&(await It(o,l,"utf-8"),i.detail("Backfilled new env keys")),await ut("update",He),he.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${He}`),await At();let f=a.AI_AGENT==="codex"?"codex":"claude-code",u=$(Vo(),`klaudius-update-${process.pid}-${Date.now()}`),w;try{i.heading("Downloading the latest Klaudius template");let k=await lt({licenseKey:s,machineId:De(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:f,destDir:u});i.success(`Fetched ${k.filesExtracted} canonical files`),w=u}catch(k){i.error(k.message),i.detail("Update aborted. Your project is unchanged."),await fe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await Yo(w,t,n);if(e.check){let k=d.filter(p=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(p.state)),x=d.filter(p=>["conflict","locally-deleted","removed-modified"].includes(p.state));i.blank(),k.length===0?he.outro(Fe.green("Already up to date.")):(i.detail(`${W(k.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),he.outro(Fe.yellow("An update is available."))),console.log(`[klaudius-update-check] status=${k.length===0?"current":"behind"} pending=${k.length} conflicts=${x.length}`),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}let P=!1,y=d.find(k=>k.path===".gitignore"&&k.state==="conflict");if(y){let k=$(t,".gitignore"),x=await _t(k,"utf-8"),p=await _t($(w,".gitignore"),"utf-8"),{merged:g,added:m}=Wo(x,p);m.length>0&&await It(k,g,"utf-8"),n.files[".gitignore"]=y.canonicalHash,y.state="gitignore-merged",P=!0,i.detail(m.length>0?`.gitignore auto-merged: kept all your lines, appended ${W(m.length,"new canonical pattern")}: ${m.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let E=d.filter(k=>k.state==="new"),b=d.filter(k=>k.state==="clean-update"),C=d.filter(k=>k.state==="user-only"),V=d.filter(k=>k.state==="conflict"),le=d.filter(k=>k.state==="no-change"),R=d.filter(k=>k.state==="locally-deleted"),_=d.filter(k=>k.state==="removed-clean"),ce=d.filter(k=>k.state==="removed-modified"),j=[...V,...R,...ce],we=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${W(le.length,"file")} unchanged`),i.detail(`${W(E.length,"new file")}`),i.detail(`${W(b.length,"file")} updated cleanly (no local edits)`),i.detail(`${W(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${W(_.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${W(V.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${W(R.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${W(ce.length,"file")} removed upstream but edited locally (need your decision)`),we>0&&(i.detail(`${W(we,"file")} kept deleted (previously resolved \u2014 skipped)`),we<=10))for(let k of n.ignored)i.detail(` kept deleted: ${k}`);let Le=async()=>{let k=!1,x=p=>fe(p,{recursive:!0,force:!0}).catch(()=>{k=!0});await x($(t,".klaudius","incoming")),await x($(t,ct)),await x($(t,".klaudius","conflicts.md")),k&&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&&!P){await Le(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=He,await Me(t,n)),i.blank(),he.outro(Fe.green("Already up to date.")),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let k of[...E,...b]){let x=$(w,k.path),p=$(t,k.path);await Wt(zt(p),{recursive:!0}),await us(x,p),n.files[k.path]=k.canonicalHash}E.length+b.length>0&&i.success(`Wrote ${W(E.length+b.length,"file")}`),[...E,...b].some(k=>k.path==="package.json"||k.path==="package-lock.json")&&i.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let k of _){let x=$(t,k.path);await fe(x,{force:!0}),delete n.files[k.path]}if(_.length>0&&i.success(`Deleted ${W(_.length,"file")} removed upstream`),j.length>0){i.blank(),i.heading(`${j.length} conflict(s) need resolution`);let k=$(t,".klaudius","incoming");try{await fe(k,{recursive:!0,force:!0})}catch{}for(let m of[...V,...R]){let A=$(w,m.path),I=$(k,m.path);await Wt(zt(I),{recursive:!0}),await us(A,I)}let x=new Map,p=new Map;for(let m of V){let A=await Ln(t,m.path),I=await Nn(t,m.path),L=await _t($(w,m.path),"utf-8"),D=Mn(A,I,L,m.manifestHash);D!==null?(p.set(m.path,D),x.set(m.path,Dn(D,L))):A!==null&&(Ie(A)||Ie(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,ct);try{await fe(g,{recursive:!0,force:!0})}catch{}for(let[m,A]of p){let I=$(g,m);await Wt(zt(I),{recursive:!0}),await It(I,A,"utf-8")}await It($(t,".klaudius","conflicts.md"),zo(j,n.templateVersion,He,x,p),"utf-8"),V.length+R.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),p.size>0&&i.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=He,j.length===0?(delete n.pendingConflicts,await Le()):n.pendingConflicts=j.length,await Me(t,n);try{await dt(t,w,await ge(w))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),j.length===0)he.outro(Fe.green("Update complete."));else{let k=f==="codex"?"Codex":"Claude Code";he.outro(Fe.yellow(`${j.length} conflict(s) staged. Open ${k} in this project and ask:
|
|
104
|
+
`:"",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(),p&&process.stdout.write(p),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(),p&&process.stdout.write(p),console.log(` ${h.cyan("npx klaudius@latest install")} ${h.dim("# retry the failing installers")}`),console.log(` ${h.cyan("npx klaudius@latest doctor")} ${h.dim("# verify everything")}`),i.blank()),V&&(console.log(h.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${h.cyan(le)}`),console.log(h.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),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 ${No()}`)),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(Mo(d,n,e.target),y){let p=d.aiAgent==="codex"?"Codex":"Claude Code";console.log(h.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(h.dim(`Your details are saved in .env. To finish it, ask ${p}:`)),console.log(h.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(h.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(h.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(h.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(h.cyan(' and send a test email to my own address to confirm."')),d.outreachEnabled&&(d.outreachChannels??[]).length>0&&(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 Ut(e,{recursive:!0}),await Ht(X(e,".env"),tt(t),"utf-8"),t.aiAgent==="codex"?(await Ut(X(e,".codex"),{recursive:!0}),await Ht(X(e,".codex","config.toml"),st(t),"utf-8")):(await Ht(X(e,".mcp.json"),nt(t),"utf-8"),await St(e,"supabase"))}async function xo(e){try{(await Kt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await os(e),n=t.filter(l=>!l.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(l=>s.has(l)),r=n.includes(".env"),a=t.includes(".klaudius");if(o&&r&&!a)return{kind:"partial",envPath:X(e,".env")};if(a&&r){let l=!0;try{l=!(await Kt(X(e,"node_modules"))).isDirectory()}catch{l=!0}return{kind:"scaffolded",nodeModulesMissing:l}}return{kind:"occupied",entries:n}}async function Oo(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 S.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 S.isCancel(t)&&(S.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function vo(e){if(e&&e.trim().length>0)return e;S.intro("Klaudius");let t=await S.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 S.isCancel(t)&&(S.cancel("Setup cancelled. No files written."),process.exit(0)),t}function $o(e){let t=To(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 Lo(){if(process.platform!=="win32")return!1;try{return Gt("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function No(){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 Mo(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(S.outro(h.green(h.bold("Project ready."))),e.aiPlan){let r=(e.qaPhase??Ae(e.aiPlan))==="off";console.log(`${h.bold("Your plan:")} ${We[e.aiPlan]}`),console.log(h.dim(r?` \u2192 QA pass off${e.aiPlan==="codex-plus"&&e.aiAgent==="codex"?", model pinned to Terra":""}, so each run fits your usage window.`:" \u2192 full pipeline, including the independent QA pass after every build.")),console.log(h.dim(` Change it any time: ask ${o} to turn the QA pass on or off, or re-run \`npx klaudius@latest configure\`.`)),i.blank()}if(console.log(h.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let r=`cd ${bt(n)}`;console.log(` ${h.cyan(r)}${" ".repeat(Math.max(1,27-r.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 Do,readFile as Fo}from"fs/promises";import{join as Bt,resolve as Ho}from"path";import Y from"picocolors";async function ls(e){let t=e.target?Ho(process.cwd(),e.target):process.cwd(),n=await as(Bt(t,".env")),s=await as(Bt(t,"package.json"));(!n||!s)&&(i.error("This doesn't look like a Klaudius project."),i.detail(`Path: ${t}`),n||i.detail("Missing: .env"),s||i.detail("Missing: package.json"),i.blank(),i.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),i.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{G(await Fo(Bt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let r=await kt(t);i.blank(),i.detail(`npm: ${r.npm}, pip: ${r.pip}, playwright: ${r.playwright}, patchright: ${r.patchright}`);let a=[];if(r.npm==="failed"&&a.push("npm"),r.pip==="failed"&&a.push("pip"),r.playwright==="failed"&&a.push("playwright"),r.patchright==="failed"&&a.push("patchright"),a.length===0){i.blank(),console.log(Y.green(Y.bold("All dependencies installed."))),console.log(Y.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(Y.yellow(Y.bold(`${a.join(", ")} still failing.`))),i.blank();for(let[u,w]of Object.entries(r.hints??{}))console.log(Y.yellow(`Likely cause of ${u} failure:`)),console.log(Y.dim(` ${w}`)),i.blank();let l=o==="codex"?"codex":"claude",c=o==="codex"?"Codex":"Claude Code",f=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(Y.dim("Options:")),console.log(Y.dim(` \u2022 Open ${c} in this folder (\`${l}\`) and paste:`)),console.log(Y.cyan(` "Finish my Klaudius install \u2014 ${a.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(Y.dim(` (Don't have ${c} yet? Install with: \`${f}\`)`)),console.log(Y.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(Y.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function as(e){try{return await Do(e),!0}catch{return!1}}import{readFile as Uo,writeFile as Vt,access as jo}from"fs/promises";import{join as ve}from"path";import*as te from"@clack/prompts";import ae from"picocolors";import{mkdir as Ko}from"fs/promises";import{spawnSync as cs}from"child_process";async function ds(e){let t=e.projectRoot??process.cwd(),n=ve(t,".env"),s=ve(t,".mcp.json"),o=ve(t,".codex","config.toml"),r=await Yt(ve(t,".klaudius","manifest.json")),a=await Yt(n);!r&&!a&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let l=ue();l.ok||(i.error(l.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let c={};try{let P=await Uo(n,"utf-8");c=G(P)}catch{i.warn("No .env found. Starting from an empty configuration.")}let f=kn(c);Object.keys(c).length>0&&(f.pipelineModes??=["classic"]),te.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let u=await N(f),w=f.aiAgent??"claude-code";if(u.aiAgent&&u.aiAgent!==w&&(i.error(`Switching AI coding agent (${w} \u2192 ${u.aiAgent}) isn't supported via configure.`),i.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest init <new-folder>")} ${ae.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),u.supabaseUrl!==c.SUPABASE_URL||u.supabaseServiceKey!==c.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let P=await Te({url:u.supabaseUrl,serviceKey:u.supabaseServiceKey});P.ok||(i.error(P.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let d=de(u.googlePlacesApiKey??"");if(d.changed&&u.googlePlacesApiKey){i.heading("Checking your Google Places API key");let P=await Ce(u.googlePlacesApiKey);if(P.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(P.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(Go(u,c)){let P=te.spinner();P.start("Validating email credentials (SMTP + IMAP)");let y=u.emailProvider&&u.emailProvider!=="custom"?u.emailProvider:ke(u.emailSmtpHost),E=await oe({emailAddress:u.emailAddress,emailLogin:u.preservedEnv?.EMAIL_LOGIN?.trim()||void 0,emailPassword:u.emailPassword,emailSmtpHost:u.emailSmtpHost,emailSmtpPort:u.emailSmtpPort,emailImapHost:u.emailImapHost,emailImapPort:u.emailImapPort,usesAccountPassword:y?J[y].usesAccountPassword:void 0,sentFolder:(u.emailSentFolder??"").trim()||"Sent",draftsFolder:(u.emailDraftsFolder??"").trim()||"Drafts"});E.ok?(P.stop("Email credentials accepted (SMTP + IMAP)"),await gt(E,u,{nonInteractive:!1,onCancel:()=>i.detail("Left the folder names as they are.")})):(P.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 Vt(n,tt(u),"utf-8"),i.success("Updated .env"),u.aiAgent==="codex"?(await Ko(ve(t,".codex"),{recursive:!0}),await Vt(o,st(u),"utf-8"),i.success("Updated .codex/config.toml")):(await Vt(s,nt(u),"utf-8"),i.success("Updated .mcp.json"),await St(t,"supabase")),u.emailAuth==="oauth-microsoft"&&u.outreachEnabled&&u.outreachChannels?.includes("email")){let P=await K();if(!(P!==null&&cs(P.command[0],[...P.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!P)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: ${P.command.join(" ")} scripts/ms_oauth.py login`):cs(P.command[0],[...P.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: ${P.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),te.outro(ae.green("Configuration updated.")),await Bo(t,r)}function Go(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];if(n.some(([o])=>o===void 0||o===""))return!1;let s=[[e.emailSentFolder,"EMAIL_SENT_FOLDER"],[e.emailDraftsFolder,"EMAIL_DRAFTS_FOLDER"]];return n.some(([o,r])=>String(o)!==(t[r]??""))||s.some(([o,r])=>o!==void 0&&o!==(t[r]??""))}async function Bo(e,t){let n=await Yt(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(` ${ae.cyan("npx klaudius@latest install")} ${ae.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest doctor")} ${ae.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${ae.cyan("npx klaudius@latest init")} ${ae.dim("# pick Resume when prompted")}`),i.blank())}async function Yt(e){try{return await jo(e),!0}catch{return!1}}import{copyFile as us,mkdir as Wt,readFile as _t,rm as fe,writeFile as It,access as ps}from"fs/promises";import{dirname as zt,join as $}from"path";import{tmpdir as Vo}from"os";import*as he from"@clack/prompts";import Fe from"picocolors";var He="0.32.0";async function fs(e){let t=e.projectRoot??process.cwd(),n=await bn(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 k of ot)delete n.files[k];let s,o=$(t,".env"),r,a;try{r=await _t(o,"utf-8"),a=G(r)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=a.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let l=e.check?null:wn(r,a,yn);l!==null&&(await It(o,l,"utf-8"),i.detail("Backfilled new env keys")),await ut("update",He),he.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${He}`),await At();let f=a.AI_AGENT==="codex"?"codex":"claude-code",u=$(Vo(),`klaudius-update-${process.pid}-${Date.now()}`),w;try{i.heading("Downloading the latest Klaudius template");let k=await lt({licenseKey:s,machineId:De(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:f,destDir:u});i.success(`Fetched ${k.filesExtracted} canonical files`),w=u}catch(k){i.error(k.message),i.detail("Update aborted. Your project is unchanged."),await fe(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let d=await Yo(w,t,n);if(e.check){let k=d.filter(p=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(p.state)),x=d.filter(p=>["conflict","locally-deleted","removed-modified"].includes(p.state));i.blank(),k.length===0?he.outro(Fe.green("Already up to date.")):(i.detail(`${W(k.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),he.outro(Fe.yellow("An update is available."))),console.log(`[klaudius-update-check] status=${k.length===0?"current":"behind"} pending=${k.length} conflicts=${x.length}`),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}let P=!1,y=d.find(k=>k.path===".gitignore"&&k.state==="conflict");if(y){let k=$(t,".gitignore"),x=await _t(k,"utf-8"),p=await _t($(w,".gitignore"),"utf-8"),{merged:g,added:m}=Wo(x,p);m.length>0&&await It(k,g,"utf-8"),n.files[".gitignore"]=y.canonicalHash,y.state="gitignore-merged",P=!0,i.detail(m.length>0?`.gitignore auto-merged: kept all your lines, appended ${W(m.length,"new canonical pattern")}: ${m.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let E=d.filter(k=>k.state==="new"),b=d.filter(k=>k.state==="clean-update"),C=d.filter(k=>k.state==="user-only"),V=d.filter(k=>k.state==="conflict"),le=d.filter(k=>k.state==="no-change"),R=d.filter(k=>k.state==="locally-deleted"),_=d.filter(k=>k.state==="removed-clean"),ce=d.filter(k=>k.state==="removed-modified"),j=[...V,...R,...ce],we=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${W(le.length,"file")} unchanged`),i.detail(`${W(E.length,"new file")}`),i.detail(`${W(b.length,"file")} updated cleanly (no local edits)`),i.detail(`${W(C.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${W(_.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${W(V.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${W(R.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${W(ce.length,"file")} removed upstream but edited locally (need your decision)`),we>0&&(i.detail(`${W(we,"file")} kept deleted (previously resolved \u2014 skipped)`),we<=10))for(let k of n.ignored)i.detail(` kept deleted: ${k}`);let Le=async()=>{let k=!1,x=p=>fe(p,{recursive:!0,force:!0}).catch(()=>{k=!0});await x($(t,".klaudius","incoming")),await x($(t,ct)),await x($(t,".klaudius","conflicts.md")),k&&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&&!P){await Le(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=He,await Me(t,n)),i.blank(),he.outro(Fe.green("Already up to date.")),await fe(u,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let k of[...E,...b]){let x=$(w,k.path),p=$(t,k.path);await Wt(zt(p),{recursive:!0}),await us(x,p),n.files[k.path]=k.canonicalHash}E.length+b.length>0&&i.success(`Wrote ${W(E.length+b.length,"file")}`),[...E,...b].some(k=>k.path==="package.json"||k.path==="package-lock.json")&&i.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let k of _){let x=$(t,k.path);await fe(x,{force:!0}),delete n.files[k.path]}if(_.length>0&&i.success(`Deleted ${W(_.length,"file")} removed upstream`),j.length>0){i.blank(),i.heading(`${j.length} conflict(s) need resolution`);let k=$(t,".klaudius","incoming");try{await fe(k,{recursive:!0,force:!0})}catch{}for(let m of[...V,...R]){let A=$(w,m.path),I=$(k,m.path);await Wt(zt(I),{recursive:!0}),await us(A,I)}let x=new Map,p=new Map;for(let m of V){let A=await Ln(t,m.path),I=await Nn(t,m.path),L=await _t($(w,m.path),"utf-8"),D=Mn(A,I,L,m.manifestHash);D!==null?(p.set(m.path,D),x.set(m.path,Dn(D,L))):A!==null&&(Ie(A)||Ie(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,ct);try{await fe(g,{recursive:!0,force:!0})}catch{}for(let[m,A]of p){let I=$(g,m);await Wt(zt(I),{recursive:!0}),await It(I,A,"utf-8")}await It($(t,".klaudius","conflicts.md"),zo(j,n.templateVersion,He,x,p),"utf-8"),V.length+R.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),p.size>0&&i.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=He,j.length===0?(delete n.pendingConflicts,await Le()):n.pendingConflicts=j.length,await Me(t,n);try{await dt(t,w,await ge(w))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),j.length===0)he.outro(Fe.green("Update complete."));else{let k=f==="codex"?"Codex":"Claude Code";he.outro(Fe.yellow(`${j.length} conflict(s) staged. Open ${k} in this project and ask:
|
|
105
105
|
"Run /resolve-conflicts"`))}await fe(u,{recursive:!0,force:!0}).catch(()=>{})}async function Yo(e,t,n){let s=await ge(e),o=new Set(s),r=new Set(n.ignored??[]),a=[];for(let l of s){if(r.has(l))continue;let c=await _e($(e,l)),f=n.files[l],u=$(t,l),w;try{await ps(u),w=await _e(u)}catch{let P=f!==void 0&&!Sn.has(l)&&!rt.has(l)?"locally-deleted":"new";a.push({path:l,state:P,canonicalHash:c,manifestHash:f});continue}let d=rt.has(l);c===f?w===f||d?a.push({path:l,state:"no-change",canonicalHash:c,localHash:w,manifestHash:f}):a.push({path:l,state:"user-only",canonicalHash:c,localHash:w,manifestHash:f}):w===f||d?a.push({path:l,state:"clean-update",canonicalHash:c,localHash:w,manifestHash:f}):a.push({path:l,state:"conflict",canonicalHash:c,localHash:w,manifestHash:f})}for(let l of Object.keys(n.files)){if(o.has(l))continue;let c=n.files[l],f=$(t,l),u;try{await ps(f),u=await _e(f)}catch{delete n.files[l];continue}u===c||rt.has(l)?a.push({path:l,state:"removed-clean",localHash:u,manifestHash:c}):a.push({path:l,state:"removed-modified",localHash:u,manifestHash:c})}return a}function W(e,t){return`${e} ${t}${e===1?"":"s"}`}function Wo(e,t){let n=e.includes(`\r
|
|
106
106
|
`)?`\r
|
|
107
107
|
`:`
|
|
@@ -121,7 +121,7 @@ except Exception as e:
|
|
|
121
121
|
`));let r=wr(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(r.status===0){console.log(B.green(`Paired '${o}'.`)),console.log(B.dim(`
|
|
122
122
|
If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
|
|
123
123
|
WHATSAPP_ACCOUNTS=primary,${o}
|
|
124
|
-
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(B.red(`Pair failed: ${r.error.message}`)):(console.error(B.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(B.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(B.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(B.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as $e,spawn as Er}from"child_process";import{existsSync as je,mkdirSync as Pr,readdirSync as Sr,rmSync as Ps,mkdtempSync as Ss}from"fs";import{homedir as Qt,tmpdir as bs}from"os";import{join as Q}from"path";import se from"picocolors";var br=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function ks(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function _s(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&Ke()&&Ts();let t=Ir();if(t&&!e.reinstall&&!e.from){Es(),console.log(se.green("Opened the Klaudius app.")),As();return}let n=await Cr(e.from);console.log(se.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Rr(n):xr(n),Es(),console.log(se.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),As()}function As(){process.platform==="darwin"?console.log(se.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(se.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function Tt(){return Q(Qt(),"Applications","Klaudius.app")}function Is(){return process.env.LOCALAPPDATA??Q(Qt(),"AppData","Local")}function _r(){return Q(Is(),"Klaudius")}function Ke(){let e=Q(Is(),"Programs");try{for(let t of Sr(e)){if(!/laudius/i.test(t))continue;let n=Q(e,t,"Klaudius.exe");if(je(n))return n}}catch{}return null}function Ir(){return process.platform==="darwin"?je(Tt()):Ke()!==null}async function Tr(){try{let{readFileSync:e}=await import("fs"),n=e(Q(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function Cr(e){if(e)return je(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await Tr();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=`${br}?file=${encodeURIComponent(ks())}`,s=Q(Ss(Q(bs(),"klaudius-app-")),ks());console.log(se.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.
|
|
124
|
+
(Skip this if '${o}' is already there or you set it via the init wizard.)`));return}r.error?console.error(B.red(`Pair failed: ${r.error.message}`)):(console.error(B.red(`Pair did not complete (exit ${r.status??"signalled"}). Common causes:`)),console.error(B.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(B.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(B.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(r.status??1)}import{spawnSync as $e,spawn as Er}from"child_process";import{existsSync as je,mkdirSync as Pr,readdirSync as Sr,rmSync as Ps,mkdtempSync as Ss}from"fs";import{homedir as Qt,tmpdir as bs}from"os";import{join as Q}from"path";import se from"picocolors";var br=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function ks(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function _s(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&Ke()&&Ts();let t=Ir();if(t&&!e.reinstall&&!e.from){Es(),console.log(se.green("Opened the Klaudius app.")),As();return}let n=await Cr(e.from);console.log(se.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Rr(n):xr(n),Es(),console.log(se.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),As()}function As(){process.platform==="darwin"?console.log(se.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(se.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function Tt(){return Q(Qt(),"Applications","Klaudius.app")}function Is(){return process.env.LOCALAPPDATA??Q(Qt(),"AppData","Local")}function _r(){return Q(Is(),"Klaudius")}function Ke(){let e=Q(Is(),"Programs");try{for(let t of Sr(e)){if(!/laudius/i.test(t))continue;let n=Q(e,t,"Klaudius.exe");if(je(n))return n}}catch{}return null}function Ir(){return process.platform==="darwin"?je(Tt()):Ke()!==null}async function Tr(){try{let{readFileSync:e}=await import("fs"),n=e(Q(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m);return n?n[2].trim():null}catch{return null}}async function Cr(e){if(e)return je(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await Tr();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=`${br}?file=${encodeURIComponent(ks())}`,s=Q(Ss(Q(bs(),"klaudius-app-")),ks());console.log(se.cyan("Downloading the Klaudius app\u2026"));try{let o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.32.0"}});if(!o.ok){let l=`HTTP ${o.status}`;try{let c=await o.json();c.reason&&(l=c.reason)}catch{}throw new Error(l)}let r=Buffer.from(await o.arrayBuffer()),{writeFileSync:a}=await import("fs");return a(s,r),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 Rr(e){let t=Q(Qt(),"Applications");Pr(t,{recursive:!0});let n=Ss(Q(bs(),"klaudius-app-x-")),s=$e("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=Q(n,"Klaudius.app");je(o)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),Ps(Tt(),{recursive:!0,force:!0});let r=$e("mv",[o,Tt()],{stdio:"pipe"});r.status!==0&&(console.error(`Couldn't install to ~/Applications: ${r.stderr?.toString().trim()}`),process.exit(1))}function xr(e){/\.exe$/i.test(e)||(console.error("Expected the Klaudius installer (.exe). A zip can't be installed here \u2014 an unzipped copy can never update itself."),process.exit(1));let t=$e(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!Or(6e4)){let s=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,o=Ke();if(o&&Cs(o)){console.log(se.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(se.dim("Open it from the Start Menu if it doesn't appear shortly."));return}console.error(`Klaudius didn't finish installing (${s}).`),console.error("Check your Start Menu for Klaudius \u2014 it may still be finishing."),console.error("If it isn't there, email hello@klaudius.dev."),process.exit(1)}Ts()}function Or(e){let t=Date.now()+e;for(;;){let n=Ke();if(n)return n;if(Date.now()>=t)return null;vr(500)}}function vr(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Ts(){let e=_r();if(!je(Q(e,"app","Klaudius.exe")))return;console.log(se.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
|
|
125
125
|
$legacy = '${e.replace(/'/g,"''")}'
|
|
126
126
|
# Compare against the directory PLUS its separator, so a sibling folder whose
|
|
127
127
|
# name merely starts with the same text ("Klaudius Desktop") is never matched.
|
|
@@ -135,4 +135,4 @@ foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetF
|
|
|
135
135
|
Remove-Item -LiteralPath $lnk -Force -ErrorAction SilentlyContinue
|
|
136
136
|
}
|
|
137
137
|
}
|
|
138
|
-
}`;$e("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{Ps(e,{recursive:!0,force:!0})}catch{console.log(se.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function Es(){if(process.platform==="darwin"){$e("open",["-a",Tt()],{stdio:"pipe"});return}let e=Ke();if(!e||Cs(e))return;Er(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function Cs(e){let t=$e("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(s=>s.trim().toLowerCase()===n)}import{spawnSync as $r}from"child_process";var Jt="--use-system-ca";function Rs(){let e=process.env.NODE_OPTIONS??"";if(e.includes(Jt)||!ue().ok)return;let n=e?`${e} ${Jt}`:Jt,s=$r(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)}Rs();var Nr="0.
|
|
138
|
+
}`;$e("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{Ps(e,{recursive:!0,force:!0})}catch{console.log(se.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function Es(){if(process.platform==="darwin"){$e("open",["-a",Tt()],{stdio:"pipe"});return}let e=Ke();if(!e||Cs(e))return;Er(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function Cs(e){let t=$e("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(s=>s.trim().toLowerCase()===n)}import{spawnSync as $r}from"child_process";var Jt="--use-system-ca";function Rs(){let e=process.env.NODE_OPTIONS??"";if(e.includes(Jt)||!ue().ok)return;let n=e?`${e} ${Jt}`:Jt,s=$r(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)}Rs();var Nr="0.32.0",ie=new Lr;ie.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Nr);ie.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 dn({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});ie.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").option("--answers <file>","Non-interactive setup: read answers from a JSON or dotenv-format file (same keys as .env). On a failed check, exits with code 2 and an INIT-BLOCKED line instead of reopening the wizard.").action(async(e,t)=>{try{await rs({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers})}catch(n){console.error("init failed:",n.message),process.exit(1)}});ie.command("install").description("Re-run dependency installers against an already-scaffolded project (npm, pip, playwright, patchright)").argument("[target]","Project directory (defaults to current directory)").action(async e=>{try{await ls({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});ie.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await ds({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});ie.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 fs({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});ie.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 ms({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});ie.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 _s({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});ie.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 ws({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ie.parse(process.argv);
|