klaudius 0.37.4 → 0.37.5

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.
Files changed (2) hide show
  1. package/dist/bin.js +6 -6
  2. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -14,7 +14,7 @@ Please share that file so we can trace what happened.`);return i}var rr={GB:"44"
14
14
  `)){let i=n.trim();if(!i||i.startsWith("#"))continue;let s=i.indexOf("=");if(s===-1)continue;let o=i.slice(0,s).trim(),r=Fn(i.slice(s+1).trim());t[o]=r}return t}var Fi=["VERCEL_TOKEN","CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","NETLIFY_AUTH_TOKEN","SELFHOST_DEPLOY_TARGET","SELFHOST_URL_TEMPLATE","EMAIL_PROVIDER","EMAIL_AUTH","EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT","SMS_PROVIDER","TEST_PHONE","TWILIO_ACCOUNT_SID","TWILIO_AUTH_TOKEN","TWILIO_PHONE_NUMBER","WHATSAPP_ACCOUNTS","LETTER_PROVIDER","PINGEN_CLIENT_ID","PINGEN_CLIENT_SECRET","PINGEN_ORG_ID","POSTGRID_API_KEY","NOTIFY_CHANNEL","TELEGRAM_BOT_TOKEN","TELEGRAM_CHAT_ID"];function Un(e,t,n){let i=Ti(Wt(t,e.countryCode)??"",Wt(n,e.countryCode)??"");e.pricing=i.pricing,e.pricingTerms=i.pricingTerms,e.pricingMonthly=i.pricingMonthly}function Hn(e){let t=e&&e!=="custom"?te[e]:void 0;return[["EMAIL_SENT_FOLDER","emailSentFolder",t?.sentFolder],["EMAIL_DRAFTS_FOLDER","emailDraftsFolder",t?.draftsFolder],["EMAIL_INBOX_FOLDER","emailInboxFolder",t?.inboxFolder]]}function Ui(e,t,n={}){let i={...e},s=r=>(t[r]??"").trim()!=="";!s("PRICING_TERMS")&&(s("PRICING")||s("PRICING_MONTHLY"))&&Un(i,t.PRICING,t.PRICING_MONTHLY),i.signature&&i.name&&i.signature.trim()===i.name.trim()&&(i.signature=void 0),s("EMAIL_FROM_NAME")||(i.emailFromName=i.name?.trim()&&i.emailAddress?.trim()?i.name.trim():void 0);let o=Ie(n)===i.emailProvider&&(n.EMAIL_ADDRESS??"").trim().toLowerCase()===(i.emailAddress??"").trim().toLowerCase();for(let[r,d,c]of Hn(i.emailProvider))s(r)||o&&(n[r]??"").trim()||(i[d]=c);return i}function Hi(e){let t=d=>{let c=e[d];if(!c)return;let p=parseInt(c,10);return isNaN(p)?void 0:p},n=e.SMS_PROVIDER,i=d=>d==="email"||d==="sms"||d==="whatsapp"||d==="letter",s=e.OUTREACH_CHANNELS?.split(",").map(d=>d.trim()).filter(i),o=e.OUTREACH_PRIORITY?.split(",").map(d=>d.trim()).filter(i),r=e.WHATSAPP_ACCOUNTS?.split(",").map(d=>d.trim()).filter(d=>d.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:On(e.AI_AGENT)??vn,aiPlan:_t(e.AI_PLAN),qaPhase:Tt(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(d=>d.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:s&&s.length>0?s:void 0,outreachPriority:o&&o.length>0?o:void 0,whatsappAccounts:r&&r.length>0?r:void 0,emailProvider:Ie(e),emailAuth:$n(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:Mn(n),testPhone:Rn(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,letterProvider:Dn(e.LETTER_PROVIDER),pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:Ln(e.DEPLOY_PROVIDER)??xn,vercelToken:e.VERCEL_TOKEN,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN||void 0,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID||void 0,netlifyAuthToken:e.NETLIFY_AUTH_TOKEN||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:e.SELFHOST_DEPLOY_TARGET||void 0,selfhostUrlTemplate:e.SELFHOST_URL_TEMPLATE||void 0,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,emailPassword:e.EMAIL_PASSWORD,notifyChannel:Nn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function rt(e){let t=_=>{let C=e[_];if(!C)return;let M=parseInt(C,10);return isNaN(M)?void 0:M},n=e.SUPABASE_URL,i=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),s=e.SUPABASE_PAT?.replace(/\s+/g,""),o=e.SUPABASE_PROJECT_REF,r=e.PRICING,d=e.PRICING_TERMS||"one-off, no monthly fees",c=Ln(e.DEPLOY_PROVIDER)??xn,p=e.VERCEL_TOKEN,u=e.CLOUDFLARE_API_TOKEN,g=e.CLOUDFLARE_ACCOUNT_ID,m=e.NETLIFY_AUTH_TOKEN,w=e.SELFHOST_DEPLOY_TARGET,y=e.SELFHOST_URL_TEMPLATE;if(!r||!n||!i||!s||!o||!(c==="cloudflare"?!!u&&!!g:c==="netlify"?!!m:c==="selfhost"?!!w&&!!y:!!p))return null;let P=e.SMS_PROVIDER,T=_=>_==="email"||_==="sms"||_==="whatsapp"||_==="letter",I=e.OUTREACH_CHANNELS?.split(",").map(_=>_.trim()).filter(T),L=e.OUTREACH_PRIORITY?.split(",").map(_=>_.trim()).filter(T),$=e.WHATSAPP_ACCOUNTS?.split(",").map(_=>_.trim()).filter(_=>_.length>0);return{preservedEnv:e,licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:On(e.AI_AGENT)??vn,aiPlan:_t(e.AI_PLAN),qaPhase:Tt(e.QA_PHASE),country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(_=>_.trim().toLowerCase()).filter(Boolean):void 0,pricing:r,pricingTerms:d,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:I&&I.length>0?I:void 0,outreachPriority:L&&L.length>0?L:void 0,whatsappAccounts:$&&$.length>0?$:void 0,emailProvider:Ie(e),emailAuth:$n(e.EMAIL_AUTH),emailAddress:e.EMAIL_ADDRESS,emailPassword:e.EMAIL_PASSWORD,emailFromName:e.EMAIL_FROM_NAME,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:t("EMAIL_SMTP_PORT"),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:t("EMAIL_IMAP_PORT"),emailSentFolder:e.EMAIL_SENT_FOLDER,emailInboxFolder:e.EMAIL_INBOX_FOLDER,emailDraftsFolder:e.EMAIL_DRAFTS_FOLDER,smsProvider:Mn(P),testPhone:Rn(e.TEST_PHONE,e.OPERATOR_COUNTRY_CODE),twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,letterProvider:Dn(e.LETTER_PROVIDER),pingenClientId:e.PINGEN_CLIENT_ID||void 0,pingenClientSecret:e.PINGEN_CLIENT_SECRET||void 0,pingenOrgId:e.PINGEN_ORG_ID||void 0,postgridApiKey:e.POSTGRID_API_KEY||void 0,deployProvider:c,vercelToken:p,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:u||void 0,cloudflareAccountId:g||void 0,netlifyAuthToken:m||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:w||void 0,selfhostUrlTemplate:y||void 0,supabaseUrl:n,supabaseServiceKey:i,supabasePat:s,supabaseAnonKey:e.SUPABASE_ANON_KEY||void 0,supabaseProjectRef:o,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:Nn(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{readFile as dr}from"fs/promises";import Le from"picocolors";var a={info:e=>console.log(Le.cyan("\u2139"),e),success:e=>console.log(Le.green("\u2713"),e),warn:e=>console.log(Le.yellow("\u26A0"),e),error:e=>console.error(Le.red("\u2717"),e),step:e=>console.log(Le.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
15
15
  `+Le.bold(Le.cyan(e))),detail:e=>console.log(Le.dim(" "+e))};var ur="Fix this section's values and try again.";function S(e,t){a.blank();for(let n of pr(e,t))console.error(n);process.exit(2)}function pr(e,t){return[`INIT-BLOCKED section=${e}`,t,ur,"INIT-BLOCKED end"]}function zt(e){for(let t of Object.keys(qt)){if(!(t in e))continue;let n=e[t]??"";n.trim()!==""&&Ni(t,n)===void 0&&S("answers",`${t} is set to "${n}", which isn't one of the values it can take: ${qt[t].join(", ")}.`)}}async function Jt(e){let t;try{t=await dr(e,"utf-8")}catch{S("answers",`Couldn't read answers file: ${e}`)}let n=t.trim();if(n.startsWith("{"))try{let i=JSON.parse(n),s={};for(let[o,r]of Object.entries(i))r!=null&&(s[o]=typeof r=="string"?r:String(r));return s}catch(i){S("answers",`Answers file is not valid JSON: ${i.message}`)}return J(t)}function jn(e){return e.filter(([,t])=>!t?.trim()).map(([t,,n])=>[t,n])}function Kn(e,t){return e.some(([,n])=>(t[n]??"").trim()!=="")?"were cleared":"have never been set"}function Qt(e,t={}){if(!e.smsProvider)return"SMS is still switched on but no SMS provider is set \u2014 turn SMS off, or pick iMessage or Twilio.";if(e.smsProvider!=="twilio")return;let n=jn([["Account SID",e.twilioAccountSid,"TWILIO_ACCOUNT_SID"],["Auth Token",e.twilioAuthToken,"TWILIO_AUTH_TOKEN"],["sending number",e.twilioPhoneNumber,"TWILIO_PHONE_NUMBER"]]);return n.length>0?`SMS is still switched on but its Twilio details ${Kn(n,t)} (${n.map(([i])=>i).join(", ")}) \u2014 turn SMS off, or add the details.`:void 0}function Xt(e,t={}){if(!e.letterProvider)return"Letters are still switched on but no letter provider is set \u2014 turn letters off, or pick Pingen or PostGrid.";let n=e.letterProvider==="pingen"?jn([["Client ID",e.pingenClientId,"PINGEN_CLIENT_ID"],["Client Secret",e.pingenClientSecret,"PINGEN_CLIENT_SECRET"],["organisation id",e.pingenOrgId,"PINGEN_ORG_ID"]]):jn([["API key",e.postgridApiKey,"POSTGRID_API_KEY"]]);return n.length===0?void 0:`Letters are still switched on but the ${e.letterProvider==="pingen"?"Pingen":"PostGrid"} details ${Kn(n,t)} (${n.map(([s])=>s).join(", ")}) \u2014 turn letters off, or add the details.`}function Zt(e,t={}){let n=e.notifyChannel;if(n==="telegram"&&(!e.telegramBotToken?.trim()||!e.telegramChatId?.trim()))return`Alerts are still set to reach you on Telegram but the bot token and chat ID ${Kn([["bot token","TELEGRAM_BOT_TOKEN"],["chat ID","TELEGRAM_CHAT_ID"]],t)} \u2014 add them back, or choose another way to be alerted.`;if(n==="email"&&!e.notifyTo?.trim()&&!e.emailAddress?.trim())return"Alerts are still set to reach you by email but there's no address left to send them to \u2014 set one, or choose another way to be alerted.";if(n==="sms"&&!e.notifyTo?.trim()&&!e.testPhone?.trim())return"Alerts are still set to reach you by text but there's no number left to send them to \u2014 set one, or choose another way to be alerted."}import{readFile as qi,writeFile as wr}from"fs/promises";import{join as zi}from"path";import{mkdir as hr,readFile as gr,access as yr}from"fs/promises";import{dirname as kr,join as Bi}from"path";import{chmod as ji,rename as fr,unlink as mr,writeFile as Ki}from"fs/promises";var Gi=new Set(["EPERM","EACCES","EBUSY"]);async function Ee(e,t,n){let i=`${e}.${process.pid}-${Date.now()}.tmp`;await Ki(i,t);for(let s=1;;s++)try{await fr(i,e),n!==void 0&&await ji(e,n).catch(()=>{});return}catch(o){let r=o.code??"";if(Gi.has(r)&&s<5){await new Promise(d=>setTimeout(d,50*s));continue}if(await mr(i).catch(()=>{}),!Gi.has(r))throw o;await Ki(e,t),n!==void 0&&await ji(e,n).catch(()=>{});return}}var Ce=".klaudius",Vi=`${Ce}/manifest.json`,It=new Set([".env",".mcp.json",".claude/settings.json",".claude/settings.local.json",".codex/config.toml",".ms-token.json","prompts/lessons/find.md","prompts/lessons/gather.md","prompts/lessons/build.md","prompts/lessons/deploy.md","prompts/lessons/outreach.md"]),Yi=new Set(["clients/README.md"]),en=new Set(["package-lock.json"]);async function tn(e){let t=Bi(e,Vi);try{await yr(t)}catch{return null}let n=await gr(t,"utf-8"),i=JSON.parse(n),s={};for(let[o,r]of Object.entries(i.files??{}))s[o.split("\\").join("/")]=r;return i.files=s,Array.isArray(i.ignored)?i.ignored=i.ignored.filter(o=>typeof o=="string").map(o=>o.split("\\").join("/")):delete i.ignored,i}async function Ne(e,t){let n=Bi(e,Vi);await hr(kr(n),{recursive:!0}),await Ee(n,JSON.stringify(t,null,2)+`
16
16
  `)}function Wi(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}function nn(e){return zi(e,Ce,"ms-signin.json")}async function Ji(e){return qi(zi(e,".ms-token.json"),"utf-8").then(t=>String(JSON.parse(t).account?.address??"")).then(t=>t.trim().toLowerCase()).catch(()=>"")}async function sn(e,t){let n=t.trim().toLowerCase();if(n==="")return!1;let i=await Ji(e);if(i==="")return!1;if(i===n)return!0;let s=await qi(nn(e),"utf-8").then(d=>JSON.parse(d)).catch(()=>null),o=String(s?.entered??"").trim().toLowerCase(),r=String(s?.token??"").trim().toLowerCase();return o!==""&&o===n&&r===i}async function on(e,t){let n={entered:t.trim(),token:await Ji(e)};await wr(nn(e),`${JSON.stringify(n)}
17
- `,"utf-8").catch(()=>{})}import{copyFile as Kd,mkdir as Gd,readdir as Er,stat as Bd}from"fs/promises";import{dirname as Yd,join as Xi,relative as Pr,sep as Sr}from"path";import{fileURLToPath as qd}from"url";import{createHash as Qi}from"crypto";import{readFile as Ar}from"fs/promises";async function fe(e){let t=await Ar(e);return Qi("sha256").update(t).digest("hex")}function Gn(e){return Qi("sha256").update(e).digest("hex")}async function qe(e,t=e){let n=await Er(e,{withFileTypes:!0}),i=[];for(let s of n){let o=Xi(e,s.name);s.name===".klaudius"&&e===t||(s.isDirectory()?i.push(...await qe(o,t)):s.isFile()&&i.push(Pr(t,o).split(Sr).join("/")))}return i}async function Zi(e){let t=await qe(e),n={};for(let i of t)It.has(i)||(n[i]=await fe(Xi(e,i)));return n}import{copyFile as br,mkdir as es,mkdtemp as _r,readdir as ts,rm as ns}from"fs/promises";import{tmpdir as Tr}from"os";import{dirname as Ir,join as an}from"path";import{Readable as Cr}from"stream";import*as is from"tar";var Re="Couldn't reach Klaudius just now. Try again in a minute.";function rn(e,t){return e>=500||e===408||e===429?!0:!(typeof t=="object"&&t!==null&&typeof t.ok=="boolean")}var Rr="https://klaudius.dev/api/template";function vr(e){return Cr.fromWeb(e)}var at=class extends Error{unavailable=!0;detail;constructor(t){super(`${Re} (${t})`),this.detail=t}},Ct=class extends Error{outdated;reason;constructor(t,n){super(`Template download failed: HTTP ${t}${n?` (${n})`:""}`),this.outdated=t===426,this.reason=n}};async function ln(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Rr,n="0.37.4",i;try{i=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(d){throw new at(H(d))}if(!i.ok){let d=null;try{d=await i.json()}catch{}throw rn(i.status,d)?new at(`HTTP ${i.status}`):new Ct(i.status,d.reason??"")}if(!i.body)throw new Error("Template download succeeded but response had no body");let s=i.headers.get("x-klaudius-tier"),o=await _r(an(Tr(),"klaudius-template-")),r=0;try{try{await new Promise((p,u)=>{let g=is.extract({cwd:o,strict:!0});g.on("finish",p),g.on("error",u),vr(i.body).on("error",u).pipe(g)})}catch(p){throw new Error(`Failed to extract template archive: ${p.message}`)}await es(e.destDir,{recursive:!0});let d=new Set(await ts(e.destDir)),c=await qe(o);try{for(let p of c){let u=an(e.destDir,p);await es(Ir(u),{recursive:!0}),await br(an(o,p),u),r++}}catch(p){let u=await ts(e.destDir).catch(()=>[]);for(let g of u)d.has(g)||await ns(an(e.destDir,g),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await ns(o,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:r,tier:s}}import{copyFile as Or,mkdir as ss,readFile as Bn,rm as xr,writeFile as Lr}from"fs/promises";import{dirname as Nr,join as ve}from"path";import{structuredPatch as $r}from"diff";var Rt=ve(".klaudius","base"),Oe=ve(".klaudius","conflict-base"),os=".klaudius-snapshot-id";async function cn(e,t,n,i){let s=ve(e,Rt);await xr(s,{recursive:!0,force:!0}),await ss(s,{recursive:!0});for(let o of n){let r=ve(s,o);await ss(Nr(r),{recursive:!0}),await Or(ve(t,o),r)}i!==void 0&&await Lr(ve(s,os),i,"utf-8")}async function rs(e){try{return(await Bn(ve(e,Rt,os),"utf-8")).trim()}catch{return null}}async function as(e,t){try{return await Bn(ve(e,Rt,t),"utf-8")}catch{return null}}async function ls(e,t){try{return await Bn(ve(e,Oe,t),"utf-8")}catch{return null}}function cs(e,t,n,i){return!i||$e(n)?null:e!==null&&!$e(e)&&Gn(e)===i?e:t!==null&&!$e(t)&&Gn(t)===i?t:null}function $e(e){return e.includes("\0")||e.includes("\uFFFD")}function ds(e,t,n=60){let i=$r("base","new",e,t,"","",{context:2});if(i.hunks.length===0)return["Upstream content is identical to your base for this file."];let s=i.hunks.map(c=>`${c.newStart}-${c.newStart+Math.max(c.newLines-1,0)}`).join(", "),o=[`Upstream changed ${i.hunks.length} hunk(s) (new-version lines ${s}):`,"","```diff"],r=0,d=!1;for(let c of i.hunks){if(r>=n){d=!0;break}o.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),r+=1;let p=Math.max(n-r,0),u=c.lines.slice(0,p);if(o.push(...u),r+=u.length,u.length<c.lines.length){d=!0;break}}return o.push("```"),d&&o.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),o}var Mr="https://registry.npmjs.org/klaudius/latest";async function Dr(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(Mr,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let s=await i.json();return typeof s.version=="string"?s.version:null}catch{return null}finally{clearTimeout(n)}}function Fr(e,t){let n=o=>o.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),i=n(e),s=n(t);if(i.length<3||s.length<3)return!1;for(let o=0;o<3;o++){if(Number.isNaN(i[o])||Number.isNaN(s[o]))return!1;if(i[o]>s[o])return!0;if(i[o]<s[o])return!1}return!1}async function dn(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Dr();!n||!Fr(n,t)||(a.blank(),a.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(a.detail("Your project content is fetched fresh either way, so you're not missing any"),a.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),a.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),a.blank())}import{createHash as Ur}from"crypto";import{hostname as us,userInfo as Hr,platform as ps,arch as fs}from"os";var jr="https://klaudius.dev",Kr="/api/licenses/validate",Gr="0.37.4";async function ms(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),i=(process.env.KLAUDIUS_API_URL??jr).replace(/\/$/,"")+Kr,s=vt(),o;try{o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:s,hostname:us(),os:`${ps()}-${fs()}`,cli_version:Gr})})}catch(c){return{ok:!1,unavailable:!0,reason:Re,detail:H(c)}}let r=null;try{r=await o.json()}catch{}if(rn(o.status,r))return{ok:!1,unavailable:!0,reason:Re,detail:`HTTP ${o.status}`};let d=r;return d.ok?{ok:!0,tier:d.tier??"core"}:{ok:!1,reason:d.reason??`License rejected (HTTP ${o.status}).`,...o.status===426?{outdated:!0}:{}}}function vt(){let e=[us(),Hr().username,ps(),fs()].join("|");return Ur("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Br}from"fs/promises";import{join as Vr}from"path";async function Me(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${H(n)}`}}}function Ot(e){return`https://supabase.com/dashboard/project/${e}/sql/new`}async function lt(e){let t;try{t=await Br(Vr(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(i){return{ok:!1,message:`Could not read scripts/schema.sql: ${i.message}`}}let n=e.pat.replace(/\s+/g,"");try{let i=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(i.ok)return{ok:!0};let s=qr(i.status,await i.text());return(i.status===401||i.status===403)&&e.url&&e.serviceKey?await Yr({url:e.url,serviceKey:e.serviceKey,projectRef:e.projectRef,sql:t,status:i.status,rejection:s}):{ok:!1,message:s}}catch(i){return{ok:!1,message:`Schema apply failed: ${H(i)}`}}}async function Yr(e){let t=e.projectRef.trim().toLowerCase();if(/^https?:\/\/([a-z0-9]+)\.supabase\.co(?=[:/]|$)/i.exec(e.url.trim())?.[1]?.toLowerCase()!==t)return{ok:!1,message:`${e.rejection} The tables couldn't be checked either: the database URL isn't this project's address (https://${t}.supabase.co).`};let i=hs(e.sql);if(i.tables.length===0&&Object.keys(i.columns).length===0)return{ok:!1,message:e.rejection};let s=await xt({url:e.url,serviceKey:e.serviceKey,sql:e.sql});return s.unreachable?{ok:!1,message:`${e.rejection} The tables already in the database couldn't be checked either (${s.unreachable}).`}:s.ok?{ok:!0,tokenRefused:e.status}:{ok:!1,message:`${e.rejection} Not in the database yet: ${s.missing.join(", ")}.`}}function ct(e){return e===401?"Your agent uses the same access token for some of its database work, and Supabase says it's invalid, expired or revoked: replace it when you can with a new one from https://supabase.com/dashboard/account/tokens.":"Your agent uses the same access token for some of its database work, so replace it when you can with a new one from https://supabase.com/dashboard/account/tokens, made in an account with access to this project, with full access (or at least Database and Migrations read-write and API Keys read on this project)."}function dt(e){return`Only tables and columns can be checked without the token. If you haven't just done it, open ${Ot(e)}, paste in the contents of scripts/schema.sql from your project folder, and click Run, so the rest of it is current too (safe to re-run).`}function hs(e){let t=e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/--[^\n]*/g," "),n=o=>!o||o.toLowerCase()==="public",i=[];for(let o of t.matchAll(/CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+(?:(\w+)\.)?(\w+)/gi)){let r=o[2].toLowerCase();n(o[1])&&!i.includes(r)&&i.push(r)}let s=Object.create(null);for(let o of t.matchAll(/ALTER\s+TABLE\s+(IF\s+EXISTS\s+)?(?:ONLY\s+)?(?:(\w+)\.)?(\w+)\s+([^;]*)/gi)){if(o[1]||!n(o[2]))continue;let r=o[3].toLowerCase();for(let d of o[4].matchAll(/ADD\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+(\w+)/gi)){let c=d[1].toLowerCase(),p=s[r]??(s[r]=[]);p.includes(c)||p.push(c)}}return{tables:i,columns:s}}function Wr(e,t){let n="";try{let s=JSON.parse(t);s&&typeof s.code=="string"&&(n=s.code)}catch{}return{missing:e===400&&n==="42703"||e===404&&(n==="PGRST205"||n==="42P01"),code:n}}async function xt(e){let t=e.url.trim().replace(/\/+$/,""),n=e.serviceKey.replace(/\s+/g,""),{tables:i,columns:s}=hs(e.sql),o=[];try{for(let r of new Set([...i,...Object.keys(s)])){let d=s[r]??[],c=await fetch(`${t}/rest/v1/${r}?select=${d.length>0?d.join(","):"*"}&limit=0`,{headers:{apikey:n,Authorization:`Bearer ${n}`}});if(c.ok)continue;let p=Wr(c.status,await c.text());if(p.missing){o.push(c.status===404?`${r} table`:`${r} columns`);continue}return{ok:!1,missing:o,unreachable:`HTTP ${c.status}${p.code?` ${p.code}`:""}`}}}catch(r){return{ok:!1,missing:o,unreachable:H(r)}}return{ok:o.length===0,missing:o}}function qr(e,t){let n=t,i=!1;try{let o=JSON.parse(t);o&&typeof o.message=="string"&&(n=o.message,i=!0)}catch{}n=n.replace(/\s+/g," ").trim();let s=i&&n?`: "${zr(n,300)}"`:"";return e===401?`Supabase rejected the access token (HTTP 401${s}) \u2014 SUPABASE_PAT in .env is invalid, expired or revoked. Create a new token at https://supabase.com/dashboard/account/tokens and run \`npx klaudius@latest configure\`.`:e===403?`Supabase refused the access token for this project (HTTP 403${s}). Create a new token at https://supabase.com/dashboard/account/tokens, signed in to an account with access to this project, with full access \u2014 or, if you choose its permissions, at least Database and Migrations read-write and API Keys read on this project \u2014 and run \`npx klaudius@latest configure\`.`:e===429?"Supabase rate-limited the request (HTTP 429). Wait a minute and try again.":`Supabase Management API rejected the schema (HTTP ${e}): ${n.slice(0,300)}`}function zr(e,t){return e.length>t?`${e.slice(0,t-1).trimEnd()}\u2026`:e}function Jr(e){try{let t=JSON.parse(e);return t.error?.code==="not_found"?!0:/user not found/i.test(t.error?.message??"")}catch{return!1}}function Qr(e,t){return e===401||e===403?{kind:"rejected",message:`Vercel rejected the token (HTTP ${e}). It may be invalid, expired or revoked.`}:e===404&&Jr(t)?{kind:"scope",message:"Vercel rejected the token (HTTP 404). Its Scope doesn't include your account, for example it was limited to a single project."}:{kind:"api",message:`Vercel API returned HTTP ${e}. Try again or check status.vercel.com.`}}async function De(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let i=await t.text().catch(()=>"");return{ok:!1,...Qr(t.status,i)}}let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,kind:"network",message:`Could not reach Vercel: ${H(t)}`}}}var gs="https://api.cloudflare.com/client/v4";function ys(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Fe(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let s=await fetch(`${gs}/user/tokens/verify`,{headers:i});if(s.status===401||s.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} verifying the token. Try again or check cloudflarestatus.com.`};let o=await s.json(),r=o.result?.status;if(o.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${ys(o)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${H(s)}`}}try{let s=await fetch(`${gs}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:i});if(s.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(s.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let o=await s.json();return o.success===!1?{ok:!1,message:ys(o)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(o.result)?o.result.length:void 0}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${H(s)}`}}}var ks="https://api.netlify.com/api/v1";async function Ue(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${ks}/user`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} verifying the token. Try again or check netlifystatus.com.`}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${H(i)}`}}try{let i=await fetch(`${ks}/accounts`,{headers:n});if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} listing your teams. Try again or check netlifystatus.com.`};let s=await i.json(),o=Array.isArray(s)?s:[];if(o.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let r=typeof o[0]?.slug=="string"?o[0].slug:void 0;return{ok:!0,accountCount:o.length,accountSlug:r}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${H(i)}`}}}function Xr(e,t){let n=t?`Google rejected your Places API key: "${t}".`:`Google rejected your Places API key (HTTP ${e}).`,i=/caller does not have permission|billing/i.test(t)?"This usually means the key's Google Cloud project has no active billing account \u2014 Places needs billing set up even though Google's free monthly credit covers normal use. Check https://console.cloud.google.com/billing for the project this key belongs to. (Less often: the key's restrictions block the Places API \u2014 check Credentials.)":"Common causes: the key is wrong or deleted, billing is not enabled on its Cloud project, or the key's restrictions block the Places API. Check https://console.cloud.google.com/billing and the key's entry under Credentials.";return`${n} ${i}`}async function He(e){let t=Ii(e);if(t)return{ok:!1,message:t};let n=we(e),i=n.value,s=o=>{let r=[o],d=Ci(e);return d&&r.push(d),n.repairs.length>0&&r.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),r.join(`
17
+ `,"utf-8").catch(()=>{})}import{copyFile as Kd,mkdir as Gd,readdir as Er,stat as Bd}from"fs/promises";import{dirname as Yd,join as Xi,relative as Pr,sep as Sr}from"path";import{fileURLToPath as qd}from"url";import{createHash as Qi}from"crypto";import{readFile as Ar}from"fs/promises";async function fe(e){let t=await Ar(e);return Qi("sha256").update(t).digest("hex")}function Gn(e){return Qi("sha256").update(e).digest("hex")}async function qe(e,t=e){let n=await Er(e,{withFileTypes:!0}),i=[];for(let s of n){let o=Xi(e,s.name);s.name===".klaudius"&&e===t||(s.isDirectory()?i.push(...await qe(o,t)):s.isFile()&&i.push(Pr(t,o).split(Sr).join("/")))}return i}async function Zi(e){let t=await qe(e),n={};for(let i of t)It.has(i)||(n[i]=await fe(Xi(e,i)));return n}import{copyFile as br,mkdir as es,mkdtemp as _r,readdir as ts,rm as ns}from"fs/promises";import{tmpdir as Tr}from"os";import{dirname as Ir,join as an}from"path";import{Readable as Cr}from"stream";import*as is from"tar";var Re="Couldn't reach Klaudius just now. Try again in a minute.";function rn(e,t){return e>=500||e===408||e===429?!0:!(typeof t=="object"&&t!==null&&typeof t.ok=="boolean")}var Rr="https://klaudius.dev/api/template";function vr(e){return Cr.fromWeb(e)}var at=class extends Error{unavailable=!0;detail;constructor(t){super(`${Re} (${t})`),this.detail=t}},Ct=class extends Error{outdated;reason;constructor(t,n){super(`Template download failed: HTTP ${t}${n?` (${n})`:""}`),this.outdated=t===426,this.reason=n}};async function ln(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Rr,n="0.37.5",i;try{i=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(d){throw new at(H(d))}if(!i.ok){let d=null;try{d=await i.json()}catch{}throw rn(i.status,d)?new at(`HTTP ${i.status}`):new Ct(i.status,d.reason??"")}if(!i.body)throw new Error("Template download succeeded but response had no body");let s=i.headers.get("x-klaudius-tier"),o=await _r(an(Tr(),"klaudius-template-")),r=0;try{try{await new Promise((p,u)=>{let g=is.extract({cwd:o,strict:!0});g.on("finish",p),g.on("error",u),vr(i.body).on("error",u).pipe(g)})}catch(p){throw new Error(`Failed to extract template archive: ${p.message}`)}await es(e.destDir,{recursive:!0});let d=new Set(await ts(e.destDir)),c=await qe(o);try{for(let p of c){let u=an(e.destDir,p);await es(Ir(u),{recursive:!0}),await br(an(o,p),u),r++}}catch(p){let u=await ts(e.destDir).catch(()=>[]);for(let g of u)d.has(g)||await ns(an(e.destDir,g),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${p.message}`)}}finally{await ns(o,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:r,tier:s}}import{copyFile as Or,mkdir as ss,readFile as Bn,rm as xr,writeFile as Lr}from"fs/promises";import{dirname as Nr,join as ve}from"path";import{structuredPatch as $r}from"diff";var Rt=ve(".klaudius","base"),Oe=ve(".klaudius","conflict-base"),os=".klaudius-snapshot-id";async function cn(e,t,n,i){let s=ve(e,Rt);await xr(s,{recursive:!0,force:!0}),await ss(s,{recursive:!0});for(let o of n){let r=ve(s,o);await ss(Nr(r),{recursive:!0}),await Or(ve(t,o),r)}i!==void 0&&await Lr(ve(s,os),i,"utf-8")}async function rs(e){try{return(await Bn(ve(e,Rt,os),"utf-8")).trim()}catch{return null}}async function as(e,t){try{return await Bn(ve(e,Rt,t),"utf-8")}catch{return null}}async function ls(e,t){try{return await Bn(ve(e,Oe,t),"utf-8")}catch{return null}}function cs(e,t,n,i){return!i||$e(n)?null:e!==null&&!$e(e)&&Gn(e)===i?e:t!==null&&!$e(t)&&Gn(t)===i?t:null}function $e(e){return e.includes("\0")||e.includes("\uFFFD")}function ds(e,t,n=60){let i=$r("base","new",e,t,"","",{context:2});if(i.hunks.length===0)return["Upstream content is identical to your base for this file."];let s=i.hunks.map(c=>`${c.newStart}-${c.newStart+Math.max(c.newLines-1,0)}`).join(", "),o=[`Upstream changed ${i.hunks.length} hunk(s) (new-version lines ${s}):`,"","```diff"],r=0,d=!1;for(let c of i.hunks){if(r>=n){d=!0;break}o.push(`@@ -${c.oldStart},${c.oldLines} +${c.newStart},${c.newLines} @@`),r+=1;let p=Math.max(n-r,0),u=c.lines.slice(0,p);if(o.push(...u),r+=u.length,u.length<c.lines.length){d=!0;break}}return o.push("```"),d&&o.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),o}var Mr="https://registry.npmjs.org/klaudius/latest";async function Dr(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let i=await fetch(Mr,{signal:t.signal,headers:{accept:"application/json"}});if(!i.ok)return null;let s=await i.json();return typeof s.version=="string"?s.version:null}catch{return null}finally{clearTimeout(n)}}function Fr(e,t){let n=o=>o.split("-")[0].split(".").map(r=>Number.parseInt(r,10)),i=n(e),s=n(t);if(i.length<3||s.length<3)return!1;for(let o=0;o<3;o++){if(Number.isNaN(i[o])||Number.isNaN(s[o]))return!1;if(i[o]>s[o])return!0;if(i[o]<s[o])return!1}return!1}async function dn(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await Dr();!n||!Fr(n,t)||(a.blank(),a.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(a.detail("Your project content is fetched fresh either way, so you're not missing any"),a.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),a.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),a.blank())}import{createHash as Ur}from"crypto";import{hostname as us,userInfo as Hr,platform as ps,arch as fs}from"os";var jr="https://klaudius.dev",Kr="/api/licenses/validate",Gr="0.37.5";async function ms(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),i=(process.env.KLAUDIUS_API_URL??jr).replace(/\/$/,"")+Kr,s=vt(),o;try{o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:s,hostname:us(),os:`${ps()}-${fs()}`,cli_version:Gr})})}catch(c){return{ok:!1,unavailable:!0,reason:Re,detail:H(c)}}let r=null;try{r=await o.json()}catch{}if(rn(o.status,r))return{ok:!1,unavailable:!0,reason:Re,detail:`HTTP ${o.status}`};let d=r;return d.ok?{ok:!0,tier:d.tier??"core"}:{ok:!1,reason:d.reason??`License rejected (HTTP ${o.status}).`,...o.status===426?{outdated:!0}:{}}}function vt(){let e=[us(),Hr().username,ps(),fs()].join("|");return Ur("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Br}from"fs/promises";import{join as Vr}from"path";async function Me(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${H(n)}`}}}function Ot(e){return`https://supabase.com/dashboard/project/${e}/sql/new`}async function lt(e){let t;try{t=await Br(Vr(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(i){return{ok:!1,message:`Could not read scripts/schema.sql: ${i.message}`}}let n=e.pat.replace(/\s+/g,"");try{let i=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(i.ok)return{ok:!0};let s=qr(i.status,await i.text());return(i.status===401||i.status===403)&&e.url&&e.serviceKey?await Yr({url:e.url,serviceKey:e.serviceKey,projectRef:e.projectRef,sql:t,status:i.status,rejection:s}):{ok:!1,message:s}}catch(i){return{ok:!1,message:`Schema apply failed: ${H(i)}`}}}async function Yr(e){let t=e.projectRef.trim().toLowerCase();if(/^https?:\/\/([a-z0-9]+)\.supabase\.co(?=[:/]|$)/i.exec(e.url.trim())?.[1]?.toLowerCase()!==t)return{ok:!1,message:`${e.rejection} The tables couldn't be checked either: the database URL isn't this project's address (https://${t}.supabase.co).`};let i=hs(e.sql);if(i.tables.length===0&&Object.keys(i.columns).length===0)return{ok:!1,message:e.rejection};let s=await xt({url:e.url,serviceKey:e.serviceKey,sql:e.sql});return s.unreachable?{ok:!1,message:`${e.rejection} The tables already in the database couldn't be checked either (${s.unreachable}).`}:s.ok?{ok:!0,tokenRefused:e.status}:{ok:!1,message:`${e.rejection} Not in the database yet: ${s.missing.join(", ")}.`}}function ct(e){return e===401?"Your agent uses the same access token for some of its database work, and Supabase says it's invalid, expired or revoked: replace it when you can with a new one from https://supabase.com/dashboard/account/tokens.":"Your agent uses the same access token for some of its database work, so replace it when you can with a new one from https://supabase.com/dashboard/account/tokens, made in an account with access to this project, with full access (or at least Database and Migrations read-write and API Keys read on this project)."}function dt(e){return`Only tables and columns can be checked without the token. If you haven't just done it, open ${Ot(e)}, paste in the contents of scripts/schema.sql from your project folder, and click Run, so the rest of it is current too (safe to re-run).`}function hs(e){let t=e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/--[^\n]*/g," "),n=o=>!o||o.toLowerCase()==="public",i=[];for(let o of t.matchAll(/CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+(?:(\w+)\.)?(\w+)/gi)){let r=o[2].toLowerCase();n(o[1])&&!i.includes(r)&&i.push(r)}let s=Object.create(null);for(let o of t.matchAll(/ALTER\s+TABLE\s+(IF\s+EXISTS\s+)?(?:ONLY\s+)?(?:(\w+)\.)?(\w+)\s+([^;]*)/gi)){if(o[1]||!n(o[2]))continue;let r=o[3].toLowerCase();for(let d of o[4].matchAll(/ADD\s+COLUMN\s+IF\s+NOT\s+EXISTS\s+(\w+)/gi)){let c=d[1].toLowerCase(),p=s[r]??(s[r]=[]);p.includes(c)||p.push(c)}}return{tables:i,columns:s}}function Wr(e,t){let n="";try{let s=JSON.parse(t);s&&typeof s.code=="string"&&(n=s.code)}catch{}return{missing:e===400&&n==="42703"||e===404&&(n==="PGRST205"||n==="42P01"),code:n}}async function xt(e){let t=e.url.trim().replace(/\/+$/,""),n=e.serviceKey.replace(/\s+/g,""),{tables:i,columns:s}=hs(e.sql),o=[];try{for(let r of new Set([...i,...Object.keys(s)])){let d=s[r]??[],c=await fetch(`${t}/rest/v1/${r}?select=${d.length>0?d.join(","):"*"}&limit=0`,{headers:{apikey:n,Authorization:`Bearer ${n}`}});if(c.ok)continue;let p=Wr(c.status,await c.text());if(p.missing){o.push(c.status===404?`${r} table`:`${r} columns`);continue}return{ok:!1,missing:o,unreachable:`HTTP ${c.status}${p.code?` ${p.code}`:""}`}}}catch(r){return{ok:!1,missing:o,unreachable:H(r)}}return{ok:o.length===0,missing:o}}function qr(e,t){let n=t,i=!1;try{let o=JSON.parse(t);o&&typeof o.message=="string"&&(n=o.message,i=!0)}catch{}n=n.replace(/\s+/g," ").trim();let s=i&&n?`: "${zr(n,300)}"`:"";return e===401?`Supabase rejected the access token (HTTP 401${s}) \u2014 SUPABASE_PAT in .env is invalid, expired or revoked. Create a new token at https://supabase.com/dashboard/account/tokens and run \`npx klaudius@latest configure\`.`:e===403?`Supabase refused the access token for this project (HTTP 403${s}). Create a new token at https://supabase.com/dashboard/account/tokens, signed in to an account with access to this project, with full access \u2014 or, if you choose its permissions, at least Database and Migrations read-write and API Keys read on this project \u2014 and run \`npx klaudius@latest configure\`.`:e===429?"Supabase rate-limited the request (HTTP 429). Wait a minute and try again.":`Supabase Management API rejected the schema (HTTP ${e}): ${n.slice(0,300)}`}function zr(e,t){return e.length>t?`${e.slice(0,t-1).trimEnd()}\u2026`:e}function Jr(e){try{let t=JSON.parse(e);return t.error?.code==="not_found"?!0:/user not found/i.test(t.error?.message??"")}catch{return!1}}function Qr(e,t){return e===401||e===403?{kind:"rejected",message:`Vercel rejected the token (HTTP ${e}). It may be invalid, expired or revoked.`}:e===404&&Jr(t)?{kind:"scope",message:"Vercel rejected the token (HTTP 404). Its Scope doesn't include your account, for example it was limited to a single project."}:{kind:"api",message:`Vercel API returned HTTP ${e}. Try again or check status.vercel.com.`}}async function De(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let i=await t.text().catch(()=>"");return{ok:!1,...Qr(t.status,i)}}let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,kind:"network",message:`Could not reach Vercel: ${H(t)}`}}}var gs="https://api.cloudflare.com/client/v4";function ys(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Fe(e){let{token:t,accountId:n}=e,i={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let s=await fetch(`${gs}/user/tokens/verify`,{headers:i});if(s.status===401||s.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} verifying the token. Try again or check cloudflarestatus.com.`};let o=await s.json(),r=o.result?.status;if(o.success===!1||r&&r!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${r?` (status: ${r})`:""}. ${ys(o)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${H(s)}`}}try{let s=await fetch(`${gs}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:i});if(s.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(s.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!s.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${s.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let o=await s.json();return o.success===!1?{ok:!1,message:ys(o)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(o.result)?o.result.length:void 0}}catch(s){return{ok:!1,message:`Could not reach Cloudflare: ${H(s)}`}}}var ks="https://api.netlify.com/api/v1";async function Ue(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let i=await fetch(`${ks}/user`,{headers:n});if(i.status===401||i.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${i.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} verifying the token. Try again or check netlifystatus.com.`}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${H(i)}`}}try{let i=await fetch(`${ks}/accounts`,{headers:n});if(!i.ok)return{ok:!1,message:`Netlify API returned HTTP ${i.status} listing your teams. Try again or check netlifystatus.com.`};let s=await i.json(),o=Array.isArray(s)?s:[];if(o.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let r=typeof o[0]?.slug=="string"?o[0].slug:void 0;return{ok:!0,accountCount:o.length,accountSlug:r}}catch(i){return{ok:!1,message:`Could not reach Netlify: ${H(i)}`}}}function Xr(e,t){let n=t?`Google rejected your Places API key: "${t}".`:`Google rejected your Places API key (HTTP ${e}).`,i=/caller does not have permission|billing/i.test(t)?"This usually means the key's Google Cloud project has no active billing account \u2014 Places needs billing set up even though Google's free monthly credit covers normal use. Check https://console.cloud.google.com/billing for the project this key belongs to. (Less often: the key's restrictions block the Places API \u2014 check Credentials.)":"Common causes: the key is wrong or deleted, billing is not enabled on its Cloud project, or the key's restrictions block the Places API. Check https://console.cloud.google.com/billing and the key's entry under Credentials.";return`${n} ${i}`}async function He(e){let t=Ii(e);if(t)return{ok:!1,message:t};let n=we(e),i=n.value,s=o=>{let r=[o],d=Ci(e);return d&&r.push(d),n.repairs.length>0&&r.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),r.join(`
18
18
  `)};try{let o=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":i,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(o.ok)return{ok:!0};if(o.status===429)return{ok:!0};let r={};try{r=await o.json()}catch{}let d=r.error?.message??"",c=r.error?.status??"";return o.status===400&&(c==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(d))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library/places.googleapis.com and press Enable for the project this key belongs to, then try again. (That page is 'Places API (New)' \u2014 the older 'Places API' is a different API and won't work.)"}:o.status===401||o.status===403?{ok:!1,message:s(Xr(o.status,d))}:{ok:!1,message:s(`Google API returned HTTP ${o.status}${d?`: ${d}`:""}.`)}}catch(o){return{ok:!1,message:`Could not reach Google: ${H(o)}`}}}import Zr from"nodemailer";import{ImapFlow as ea}from"imapflow";function ta(e){return!(e.flags instanceof Set?[...e.flags]:e.flags??[]).some(n=>String(n).toLowerCase()==="\\noselect")}function ws(e,t,n){let i=t.toLowerCase(),s=e.filter(ta);if(s.some(d=>d.path.toLowerCase()===i))return;let o=i.startsWith("inbox")?void 0:[`inbox.${i}`,`inbox/${i}`],r=s.find(d=>d.specialUse===n)?.path??(o&&s.find(d=>o.includes(d.path.toLowerCase()))?.path);return{configured:t,detected:r||void 0}}function Vn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let i=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return i.includes("invalid credentials")||i.includes("authentication failed")||i.includes("auth failed")||i.includes("login failed")||i.includes("invalid login")?"auth":i.includes("etimedout")||i.includes("timeout")||i.includes("enotfound")||i.includes("getaddrinfo")||i.includes("econnrefused")||i.includes("econnreset")?"network":"other"}async function me(e){let t=Zr.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(r){return{ok:!1,failedAt:"smtp",message:As(r,"SMTP",e.usesAccountPassword,e.knownProvider,e.errorHint),failureKind:Vn(r)}}finally{t.close()}let n=new ea({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailLogin||e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4}),i,s,o;try{if(await n.connect(),e.sentFolder||e.draftsFolder)try{let r=await n.list();e.sentFolder&&(i=ws(r,e.sentFolder,"\\Sent")),e.draftsFolder&&(s=ws(r,e.draftsFolder,"\\Drafts"))}catch{o=!0}await n.logout()}catch(r){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:As(r,"IMAP",e.usesAccountPassword,e.knownProvider,e.errorHint),failureKind:Vn(r)}}return{ok:!0,sentFolderIssue:i,draftsFolderIssue:s,foldersUnverified:o}}function na(e){if(e?.form)return`Keep the alias as
19
19
  the email address and put the primary address in "Sign-in username".`;let t=e?.addressSetting??"EMAIL_ADDRESS",n=e?.loginSetting??"EMAIL_LOGIN";return`Keep the alias as
20
20
  ${t} and set ${n} in .env to the primary address.`}function ia(e){let t=e,i=(typeof t?.responseText=="string"&&t.responseText||typeof t?.response=="string"&&t.response||typeof t?.message=="string"&&t.message||"").replace(/^invalid login:\s*/i,"").replace(/https?:\/\/\S+/g,"").replace(/\bfor more information,? go to\b/gi,"").replace(/\b(AUTH\s+(?:PLAIN|LOGIN))\s+\S+/gi,"$1 \u2026").replace(/(?=[A-Za-z0-9+/]*\d)(?=[A-Za-z0-9+/]*[a-z])(?=[A-Za-z0-9+/]*[A-Z])[A-Za-z0-9+/]{16,}={0,2}/g,"\u2026").replace(/\n\s*\d{3}[ -]\d\.\d+\.\d+\s*/g," ").replace(/\s+/g," ").replace(/[\s.]+$/,"").trim();return!i||/^command failed$/i.test(i)?"":i.length>160?`${i.slice(0,157)}...`:i}function As(e,t,n,i,s){let o=e instanceof Error?e.message:String(e),r=o.toLowerCase();if(Vn(e)==="auth"||r.includes("invalid credentials")||r.includes("authentication failed")||r.includes("auth failed")||r.includes("login failed")){let d=ia(e),c=d?`${t} rejected the credentials (${d}).`:`${t} rejected the credentials.`;return!n&&/application-specific password required/i.test(d)?`${c}
@@ -39,7 +39,7 @@ Please share that file so we can trace what happened.`);return i}var rr={GB:"44"
39
39
  `+t;return pa.some(i=>i.test(n))}function bs(e){return new Promise(t=>setTimeout(t,e))}function fa(e,t,n){return new Promise(i=>{let s=n.shell?fn([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):fn(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),o="",r="";s.stdout?.on("data",d=>{let c=d.toString();o+=c,process.stdout.write(c)}),s.stderr?.on("data",d=>{let c=d.toString();r+=c,process.stderr.write(c)}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",d=>i({code:1,stdout:o,stderr:r+d.message}))})}async function Yn(e,t,n){let i={code:0,stdout:"",stderr:""};for(let s=0;s<=ft;s++){if(i=await fa(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),i.code===0||!Ss(i.stderr,i.stdout))return i;s<ft&&(a.detail(`${n.label} failed with a transient network error \u2014 retrying (${s+2}/${ft+1})\u2026`),await bs(Ps))}return i}function ma(e,t,n){return new Promise(i=>{let s=fn(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",d=>{o+=d.toString()}),s.stderr?.on("data",d=>{r+=d.toString()}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",d=>i({code:1,stdout:o,stderr:r+d.message}))})}var ha=[{pattern:/UNABLE_TO_VERIFY_LEAF_SIGNATURE|unable to verify the first certificate/i,hint:"TLS-handshake error \u2014 your machine appears to be intercepting HTTPS (antivirus, corporate proxy, or VPN re-signing traffic with its own root CA). We work around this with NODE_OPTIONS=--use-system-ca, which needs Node 22.15+. Run `node --version` to verify, upgrade if older, then re-run setup."},{pattern:/Microsoft Visual C\+\+ 14\.0 or greater is required/i,hint:"Python tried to compile a package from source and couldn't find the Microsoft C++ Build Tools. The latest Klaudius pins supabase<2.26 to skip the offending dependency entirely. Re-run with `npx klaudius@latest init` (pulls the latest) \u2014 that should bypass the source build."}];function ga(e){let t=`${e.stderr??""}
40
40
  ${e.stdout??""}`;return ha.find(i=>i.pattern.test(t))?.hint}async function ya(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],s=(await Q())?.command??["python3"],o=async d=>{let c={code:0,stdout:"",stderr:""};for(let p=0;p<=ft;p++){if(c=await ma(s[0],[...s.slice(1),...d],{cwd:e}),c.code===0||!Ss(c.stderr,c.stdout))return c;p<ft&&(a.detail(`pip install hit a transient network error \u2014 retrying (${p+2}/${ft+1})\u2026`),await bs(Ps))}return c},r=await o([...n,"--break-system-packages",...t]);return r.code!==0&&/no such option:.*break-system-packages/i.test(r.stderr)&&(a.detail("Older pip detected; retrying without --break-system-packages"),r=await o([...n,...t])),r.code!==0&&(r.stderr.trim()&&process.stderr.write(r.stderr),r.stdout.trim()&&process.stdout.write(r.stdout)),r}async function mn(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=ua(),i=process.platform==="win32",s;if(i){let u=Ze([{label:"your Windows user folder",path:da()},{label:"the project folder",path:e}]);if(u.length>0){let g=await new Promise(w=>{let y=fn("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),l="",P="";y.stdout?.on("data",T=>{l+=T.toString()}),y.stderr?.on("data",T=>{P+=T.toString()}),y.on("close",T=>w({code:T??1,stdout:l,stderr:P})),y.on("error",T=>w({code:1,stdout:l,stderr:T.message}))}),m=g.code===0?g.stdout.trim():void 0;if(!et(m,ca)){let{detail:w,action:y}=tt(u,"install");s=`${w}. ${y}`}}}let o=(u,g)=>{let m=ga(g);if(m){(t.hints??={})[u]=m;return}s&&(u==="npm"||u==="playwright"||u==="patchright")&&!Object.values(t.hints??{}).includes(s)&&((t.hints??={})[u]=s)};a.step("Running npm install (Next.js, Playwright JS, etc.)...");let r=await Yn("npm",["install"],{cwd:e,label:"npm install",env:n,shell:i});t.npm=r.code===0?"ok":"failed",r.code!==0&&o("npm",r),a.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let d=await ya(e);t.pip=d.code===0?"ok":"failed",d.code!==0&&o("pip",d),a.step("Installing Playwright browser (chromium ~200MB; one-time)...");let c=await Yn("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:i});t.playwright=c.code===0?"ok":"failed",c.code!==0&&o("playwright",c),a.step("Installing Patchright browser (chromium ~200MB; one-time)...");let p=await Yn("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:i});return t.patchright=p.code===0?"ok":"failed",p.code!==0&&o("patchright",p),t}import{copyFile as ka,access as wa}from"fs/promises";import{dirname as Aa,join as Ea}from"path";async function _s(){let e=await Vt("python3",["--version"]),t=(e.stdout+e.stderr).trim();if(/Python was not found/i.test(t))return{state:"stub"};let n=/Python\s+(\d+\.\d+(?:\.\d+)?)/.exec(t);return e.code===0&&n?{state:"real",version:n[1]}:{state:"missing"}}async function Wn(){if(process.platform!=="win32")return{status:"irrelevant"};let e=await _s();if(e.state==="real")return{status:"ok",version:e.version};let t=await Q();return t?{status:"broken",literal:e.state,fallback:t}:{status:"no-python"}}async function Pa(e){let[t,...n]=e.command,i=await Vt(t,[...n,"-c","import sys; print(sys.executable)"]),s=i.stdout.trim().split(/\r?\n/).pop()?.trim()??"";if(i.code!==0||!s)return{ok:!1,reason:"no-exe-path"};let o=Ea(Aa(s),"python3.exe"),r=await wa(o).then(()=>!0,()=>!1);if(!r){if(/[\\/]WindowsApps[\\/]/i.test(o))return{ok:!1,reason:"store-python",target:o};try{await ka(s,o)}catch{return{ok:!1,reason:"not-writable",target:o,manualCommand:`copy "${s}" "${o}"`}}}let d=await _s();return{ok:!0,target:o,created:!r,verified:d.state==="real",postState:d.state==="real"?void 0:d.state}}var Sa="A real python3.exe now exists, but the Microsoft Store placeholder still shadows it. Turn OFF both `python.exe` and `python3.exe` under Settings \u2192 Apps \u2192 Advanced app settings \u2192 App execution aliases, then open a fresh terminal.";async function hn(){let e=await Wn();if(e.status!=="broken")return;let t=await Pa(e.fallback);if(t.ok&&t.verified){let n=t.created?e.literal==="stub"?"Fixed a Windows quirk: `python3` was a Store placeholder; it now runs your real Python.":"Fixed a Windows quirk: created the missing `python3` command from your real Python.":"The `python3` command now works \u2014 it runs your real Python.";a.success(n);return}if(t.ok&&t.postState==="stub"){a.warn("A real python3.exe is in place, but a Windows placeholder still shadows it."),a.detail(Sa);return}if(t.ok){a.warn("A python3.exe is in place next to your Python, but that folder isn't on this machine's PATH, so commands can't find it."),a.detail('Re-installing Python from python.org with "Add python.exe to PATH" ticked resolves it \u2014 then open a fresh terminal.');return}if(t.reason==="store-python"){a.warn('This Python was installed from the Microsoft Store, which blocks creating the `python3` alias next to it. Installing Python from python.org (tick "Add python.exe to PATH") resolves it.');return}if(t.reason==="not-writable"){a.warn("This machine's `python3` needs a one-time fix that requires an Administrator terminal \u2014 run this there:"),a.detail(t.manualCommand??"");return}a.warn("This machine's `python3` command isn't working, and the automatic fix could not complete. Re-installing Python from python.org (tick \"Add python.exe to PATH\") resolves it.")}import{spawn as ba,spawnSync as Ts}from"child_process";import{mkdtemp as _a,rm as Ta,rmdir as Ia,writeFile as Ca,stat as qn,unlink as Ra,mkdir as va}from"fs/promises";import{createServer as Oa}from"net";import{tmpdir as xa}from"os";import{join as mt}from"path";function La(){return new Promise((e,t)=>{let n=Oa();n.on("error",t),n.listen(0,"127.0.0.1",()=>{let i=n.address(),s=typeof i=="object"&&i?i.port:0;n.close(()=>e(s))})})}function gn(e,t){let n=["npx","playwright-cli",...t];return process.platform==="win32"?Ts(n.join(" "),{cwd:e,shell:!0,encoding:"utf8",timeout:12e4}):Ts("npx",n.slice(1),{cwd:e,shell:!1,encoding:"utf8",timeout:12e4})}async function yn(e){try{return await Na(e)}catch(t){return{ok:!1,detail:`the check itself could not run: ${t.message}`}}}async function Na(e){let t=`klaudius-smoke-${process.pid}`,n=mt(".klaudius",`qa-smoke-${process.pid}.png`),i=mt(e,n),s,o,r=!1;try{s=await _a(mt(xa(),"klaudius-qa-smoke-")),await Ca(mt(s,"index.html"),"<html><body>klaudius qa smoke</body></html>","utf8");let d=await La();o=ba("python3",["-m","http.server",String(d),"--directory",s],{stdio:"ignore",shell:!1});let c=!1;o.on("error",()=>{c=!0}),o.on("exit",()=>{c=!0});let p=`http://127.0.0.1:${d}/`,u=!1;for(let P=0;P<24&&!c;P++)try{if((await fetch(p,{signal:AbortSignal.timeout(1e3)})).ok){u=!0;break}}catch{await new Promise(T=>setTimeout(T,500))}if(!u)return{ok:!1,stage:"python3-server",detail:"`python3 -m http.server` never came up on a free local port",remediation:process.platform==="win32"?"python3 on this machine isn't runnable (usually the Microsoft Store placeholder). Running `npx klaudius@latest update` fixes it automatically.":"Check `python3 --version` works in this terminal."};let g=mt(e,".klaudius"),m=await qn(g).then(()=>!0,()=>!1);await va(g,{recursive:!0}),r=!m;let w=gn(e,[`-s=${t}`,"open",p]);if(w.status!==0)return{ok:!1,stage:"browser",detail:((w.stderr??"")+(w.stdout??"")).slice(-400).trim()||"playwright-cli could not open a browser",remediation:"Run `npx playwright install chromium` in this folder"+(process.platform==="linux"?", and under WSL also `npx playwright install-deps chromium` (missing system libraries are the usual cause there).":".")};let y=gn(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await qn(i).catch(()=>null);if((!l||l.size===0)&&(y=gn(e,[`-s=${t}`,"screenshot",`--filename=${n}`]),l=await qn(i).catch(()=>null)),!l||l.size===0){let P=((y.stderr??"")+(y.stdout??"")).slice(-300).trim();return{ok:!1,stage:"screenshot",detail:`browser opened but no screenshot file was written${P?` (${P})`:""}`,remediation:"Re-run `npx playwright install chromium` in this folder."}}return{ok:!0}}finally{gn(e,[`-s=${t}`,"close"]),o&&!o.killed&&o.kill(),await Ra(i).catch(()=>{}),r&&await Ia(mt(e,".klaudius")).catch(()=>{}),s&&await Ta(s,{recursive:!0,force:!0}).catch(()=>{})}}import{mkdir as Is,readFile as $a,writeFile as Cs}from"fs/promises";import{join as kn}from"path";var je="Bash(claude --bg --permission-mode auto *)";async function Rs(e){let t;try{t=await $a(e,"utf-8")}catch{return{}}try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return null}async function Ke(e,t){let n=kn(e,".claude"),i=kn(n,"settings.local.json"),s=".claude/settings.local.json";try{await Is(n,{recursive:!0});let o=await Rs(i);if(o===null)return a.warn(`${s} isn't valid JSON, so it was left as-is. Fix it and re-run to pre-approve the parallel-run dispatch.`),"skipped";let r=o.permissions&&typeof o.permissions=="object"&&!Array.isArray(o.permissions)?o.permissions:{},d=r.allow,c=Array.isArray(d)?d.filter(u=>typeof u=="string"):[];if(c.includes(t))return"present";c.push(t);let p={...o,permissions:{...r,allow:c}};return await Cs(i,JSON.stringify(p,null,2)+`
41
41
  `,"utf-8"),"added"}catch(o){return a.warn(`Couldn't write ${s} (${o instanceof Error?o.message:String(o)}). The parallel-run dispatch may occasionally ask for approval.`),"skipped"}}async function ht(e,t){let n=kn(e,".claude");await Is(n,{recursive:!0});let i=kn(n,"settings.json"),s=await Rs(i)??{},o=s.enabledMcpjsonServers,r=Array.isArray(o)?o.filter(c=>typeof c=="string"):[];r.includes(t)||r.push(t);let d={...s,enabledMcpjsonServers:r};await Cs(i,JSON.stringify(d,null,2)+`
42
- `,"utf-8")}var Jn="0.37.4",V=5,x=!1;function Qn(e){return X(e,Ce,"setup-pending")}function Ha(e){let t=process.env.KLAUDIUS_WHATSAPP_STATE_DIR||X(Ns(),".klaudius","whatsapp");return Ma(X(t,e,"auth","creds.json"))}var Os="Klaudius needs its latest update before setup can finish. Try again in a little while.";function xs(e){return`${e||"The license could not be validated."} If you believe this is in error, email hello@klaudius.dev with your purchase details.`}function he(e){return`npx klaudius@latest init ${En(gt(e))}`}function gt(e){if(process.platform==="win32")return e;let t=Ns();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function ja(e){let t=[];try{let i=(await Ls(e,{withFileTypes:!0})).filter(s=>s.isDirectory()&&!s.name.startsWith(".")).slice(0,200);for(let s of i){let o=X(e,s.name);if(!await ei(X(o,".env")))continue;let r=await ei(X(o,".klaudius","manifest.json"));if(t.push({path:o,finished:r}),t.length>=3)break}}catch{}return t}async function ei(e){try{return await Xn(e),!0}catch{return!1}}function En(e){return/\s/.test(e)?`"${e}"`:e}function Pe(e,t,n){a.blank(),a.error(`${t} validation failed ${V} times in a row. Pausing setup so you don't get stuck in a loop.`),a.detail(`Last error: ${n}`),a.blank(),a.detail("Your credentials are saved in `.env`. Two ways forward:"),a.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),a.blank(),console.log(` ${A.cyan(he(e))}`),a.blank(),a.detail(` (Your .env is at ${gt(X(e,".env"))} \u2014 open it in any text editor.)`),a.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),a.blank(),process.exit(1)}async function $s(e){x=!!e.answers;let t=e.target??".",n=Fa(t)?t:Da(process.cwd(),t),i=Va(n);i&&(a.error("Klaudius can't be installed inside a protected system folder."),a.detail(`Path: ${n}`),a.detail(`Reason: ${i}`),a.blank(),a.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),a.blank(),process.platform==="win32"?(a.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${A.cyan("cd $HOME\\Documents")}`),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`)):(a.detail("For example:"),console.log(` ${A.cyan("cd ~/Documents")}`),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`)),a.blank(),process.exit(1)),process.platform==="win32"&&Ya()&&(a.warn("You appear to be running in an elevated (Administrator) PowerShell."),a.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),a.blank()),await dn("init",Jn);let s=await Ka(n),o=s.kind==="scaffolded"&&!!e.answers&&await ei(Qn(n));if(s.kind==="scaffolded"&&!o){x&&S("folder","There's already a Klaudius project in this folder. Choose a new folder name, or open that project instead."),a.blank(),a.warn(`Found an existing Klaudius project at ${A.bold(n)}.`),a.detail("(Your .env and project files are in place.)"),a.blank(),s.nodeModulesMissing?(a.detail("It looks like a previous setup didn't finish installing dependencies."),a.detail("To pick up where it left off, run:"),a.blank(),n!==process.cwd()&&console.log(` ${A.cyan(`cd ${En(t)}`)}`),console.log(` ${A.cyan("npx klaudius@latest install")} ${A.dim("# retries npm + pip + browsers; idempotent")}`),a.blank(),a.detail("Then verify with:"),a.blank(),console.log(` ${A.cyan("npx klaudius@latest doctor")} ${A.dim("# checks Node / Python / installers / credentials")}`),a.blank()):(a.detail("Everything is scaffolded and dependencies look installed."),a.detail("Pick the action you wanted:"),a.blank(),console.log(` ${A.cyan("npx klaudius@latest doctor")} ${A.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${A.cyan("npx klaudius@latest configure")} ${A.dim("# change a credential / API key")}`),console.log(` ${A.cyan("npx klaudius@latest update")} ${A.dim("# pull the latest skills, scripts and prompts")}`),a.blank()),a.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),a.blank();return}if(s.kind==="occupied"){x&&S("folder","This folder already has files in it. Choose an empty folder or a new name.");let h=t===".",f=await ja(n);if(f.length>0){a.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),a.detail(`You're in: ${gt(n)}`),a.blank();for(let k of f)a.detail(k.finished?`Found a finished project at ${gt(k.path)}. To work in it:`:`Found an unfinished setup at ${gt(k.path)}. To pick up where it left off:`),a.blank(),k.finished?(console.log(` ${A.cyan(`cd ${gt(k.path)}`)}`),console.log(` ${A.cyan("claude")} ${A.dim("# open Claude Code in the project")}`)):console.log(` ${A.cyan(he(k.path))} ${A.dim("# then pick Resume")}`),a.blank();process.exit(1)}a.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),a.detail(`Path: ${n}`),a.detail(`Contains: ${s.entries.slice(0,5).join(", ")}${s.entries.length>5?`, \u2026 (+${s.entries.length-5} more)`:""}`),a.blank(),h?(a.detail("Two ways forward:"),a.blank(),a.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`),a.blank(),a.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${A.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(a.detail(`The folder '${t}' already exists and isn't empty.`),a.detail("Either pick a different name:"),console.log(` ${A.cyan(`npx klaudius@latest init ${t}-2`)}`),a.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=null;e.answers&&(r=await Jt(e.answers),zt(r),a.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let d=r??{},c={};if(r){let h=await zn(X(n,".env"),"utf-8").catch(()=>null);h&&(c=J(h),r={...Object.fromEntries(Object.entries(c).filter(([k])=>!Fi.includes(k))),...r})}let p=e.license??r?.KLAUDIUS_LICENSE_KEY;x&&(!p||p.trim().length===0)&&S("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let u=await Ba(p),g=v.spinner();g.start("Validating license");let m=await ms(u);!m.ok&&m.unavailable&&(g.stop(x?"Couldn't check the licence key":Re,2),m.detail&&a.detail(`Details: ${m.detail}`),x&&S("unavailable",Re),a.detail(`To try again, re-run the same command: ${he(n)}`),process.exit(1)),!m.ok&&m.outdated&&(g.stop(`This copy of Klaudius (${Jn}) is out of date, so it can't set up.`,2),x&&S("install",Os),a.detail(`Run the latest one instead: ${he(n)}`),process.exit(1)),m.ok||(g.stop(`License invalid: ${m.reason??"unknown"}`,2),a.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),x&&S("license",xs(m.reason)),process.exit(1)),g.stop(`License valid (${m.tier??"core"} tier)`);let w=await nt();w.ok||(a.error(w.message??"Python version check failed."),a.blank(),a.detail(`Once you've installed Python 3.10+, re-run the same command: ${he(n)}`),process.exit(1)),await hn();let y=Ae();y.ok||(a.error(y.message??"Node.js version check failed."),a.blank(),a.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${he(n)}`),process.exit(1));let l,P=!1;if(r){let h=rt(r);h||S("answers","The answers file is missing required fields. Required: PRICING, SUPABASE_URL, SUPABASE_SERVICE_KEY, SUPABASE_PAT, SUPABASE_PROJECT_REF, plus the credentials for your DEPLOY_PROVIDER (VERCEL_TOKEN, or CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID, or NETLIFY_AUTH_TOKEN, or SELFHOST_DEPLOY_TARGET + SELFHOST_URL_TEMPLATE). Keys match a working .env."),l=Ui(h,d,c),a.success("Loaded setup answers (non-interactive mode)");let f=c.AI_AGENT==="codex"?"codex":"claude-code";if(o&&f!==(l.aiAgent??"claude-code")){let k=E=>E==="codex"?"Codex":"Claude Code";S("folder",`This folder was set up for ${k(f)}, so it can't carry on as ${k(l.aiAgent??"claude-code")}. Give the folder a different name to set up fresh, or switch back.`)}}else if(s.kind==="partial")if(await Ga(n)==="resume"){let f=await zn(s.envPath,"utf-8"),k=rt(J(f));k?(a.success("Resuming with values from your existing .env"),a.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=k,P=!0,l.aiPlan||(l=await W(l,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
42
+ `,"utf-8")}var Jn="0.37.5",V=5,x=!1;function Qn(e){return X(e,Ce,"setup-pending")}function Ha(e){let t=process.env.KLAUDIUS_WHATSAPP_STATE_DIR||X(Ns(),".klaudius","whatsapp");return Ma(X(t,e,"auth","creds.json"))}var Os="Klaudius needs its latest update before setup can finish. Try again in a little while.";function xs(e){return`${e||"The license could not be validated."} If you believe this is in error, email hello@klaudius.dev with your purchase details.`}function he(e){return`npx klaudius@latest init ${En(gt(e))}`}function gt(e){if(process.platform==="win32")return e;let t=Ns();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function ja(e){let t=[];try{let i=(await Ls(e,{withFileTypes:!0})).filter(s=>s.isDirectory()&&!s.name.startsWith(".")).slice(0,200);for(let s of i){let o=X(e,s.name);if(!await ei(X(o,".env")))continue;let r=await ei(X(o,".klaudius","manifest.json"));if(t.push({path:o,finished:r}),t.length>=3)break}}catch{}return t}async function ei(e){try{return await Xn(e),!0}catch{return!1}}function En(e){return/\s/.test(e)?`"${e}"`:e}function Pe(e,t,n){a.blank(),a.error(`${t} validation failed ${V} times in a row. Pausing setup so you don't get stuck in a loop.`),a.detail(`Last error: ${n}`),a.blank(),a.detail("Your credentials are saved in `.env`. Two ways forward:"),a.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),a.blank(),console.log(` ${A.cyan(he(e))}`),a.blank(),a.detail(` (Your .env is at ${gt(X(e,".env"))} \u2014 open it in any text editor.)`),a.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),a.blank(),process.exit(1)}async function $s(e){x=!!e.answers;let t=e.target??".",n=Fa(t)?t:Da(process.cwd(),t),i=Va(n);i&&(a.error("Klaudius can't be installed inside a protected system folder."),a.detail(`Path: ${n}`),a.detail(`Reason: ${i}`),a.blank(),a.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),a.blank(),process.platform==="win32"?(a.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${A.cyan("cd $HOME\\Documents")}`),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`)):(a.detail("For example:"),console.log(` ${A.cyan("cd ~/Documents")}`),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`)),a.blank(),process.exit(1)),process.platform==="win32"&&Ya()&&(a.warn("You appear to be running in an elevated (Administrator) PowerShell."),a.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),a.blank()),await dn("init",Jn);let s=await Ka(n),o=s.kind==="scaffolded"&&!!e.answers&&await ei(Qn(n));if(s.kind==="scaffolded"&&!o){x&&S("folder","There's already a Klaudius project in this folder. Choose a new folder name, or open that project instead."),a.blank(),a.warn(`Found an existing Klaudius project at ${A.bold(n)}.`),a.detail("(Your .env and project files are in place.)"),a.blank(),s.nodeModulesMissing?(a.detail("It looks like a previous setup didn't finish installing dependencies."),a.detail("To pick up where it left off, run:"),a.blank(),n!==process.cwd()&&console.log(` ${A.cyan(`cd ${En(t)}`)}`),console.log(` ${A.cyan("npx klaudius@latest install")} ${A.dim("# retries npm + pip + browsers; idempotent")}`),a.blank(),a.detail("Then verify with:"),a.blank(),console.log(` ${A.cyan("npx klaudius@latest doctor")} ${A.dim("# checks Node / Python / installers / credentials")}`),a.blank()):(a.detail("Everything is scaffolded and dependencies look installed."),a.detail("Pick the action you wanted:"),a.blank(),console.log(` ${A.cyan("npx klaudius@latest doctor")} ${A.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${A.cyan("npx klaudius@latest configure")} ${A.dim("# change a credential / API key")}`),console.log(` ${A.cyan("npx klaudius@latest update")} ${A.dim("# pull the latest skills, scripts and prompts")}`),a.blank()),a.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),a.blank();return}if(s.kind==="occupied"){x&&S("folder","This folder already has files in it. Choose an empty folder or a new name.");let h=t===".",f=await ja(n);if(f.length>0){a.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),a.detail(`You're in: ${gt(n)}`),a.blank();for(let k of f)a.detail(k.finished?`Found a finished project at ${gt(k.path)}. To work in it:`:`Found an unfinished setup at ${gt(k.path)}. To pick up where it left off:`),a.blank(),k.finished?(console.log(` ${A.cyan(`cd ${gt(k.path)}`)}`),console.log(` ${A.cyan("claude")} ${A.dim("# open Claude Code in the project")}`)):console.log(` ${A.cyan(he(k.path))} ${A.dim("# then pick Resume")}`),a.blank();process.exit(1)}a.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),a.detail(`Path: ${n}`),a.detail(`Contains: ${s.entries.slice(0,5).join(", ")}${s.entries.length>5?`, \u2026 (+${s.entries.length-5} more)`:""}`),a.blank(),h?(a.detail("Two ways forward:"),a.blank(),a.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${A.cyan("npx klaudius@latest init my-agency")}`),a.blank(),a.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${A.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(a.detail(`The folder '${t}' already exists and isn't empty.`),a.detail("Either pick a different name:"),console.log(` ${A.cyan(`npx klaudius@latest init ${t}-2`)}`),a.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let r=null;e.answers&&(r=await Jt(e.answers),zt(r),a.detail(`Non-interactive mode: answers loaded from ${e.answers}`));let d=r??{},c={};if(r){let h=await zn(X(n,".env"),"utf-8").catch(()=>null);h&&(c=J(h),r={...Object.fromEntries(Object.entries(c).filter(([k])=>!Fi.includes(k))),...r})}let p=e.license??r?.KLAUDIUS_LICENSE_KEY;x&&(!p||p.trim().length===0)&&S("license","No licence key: pass --license or include KLAUDIUS_LICENSE_KEY in the answers file.");let u=await Ba(p),g=v.spinner();g.start("Validating license");let m=await ms(u);!m.ok&&m.unavailable&&(g.stop(x?"Couldn't check the licence key":Re,2),m.detail&&a.detail(`Details: ${m.detail}`),x&&S("unavailable",Re),a.detail(`To try again, re-run the same command: ${he(n)}`),process.exit(1)),!m.ok&&m.outdated&&(g.stop(`This copy of Klaudius (${Jn}) is out of date, so it can't set up.`,2),x&&S("install",Os),a.detail(`Run the latest one instead: ${he(n)}`),process.exit(1)),m.ok||(g.stop(`License invalid: ${m.reason??"unknown"}`,2),a.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),x&&S("license",xs(m.reason)),process.exit(1)),g.stop(`License valid (${m.tier??"core"} tier)`);let w=await nt();w.ok||(a.error(w.message??"Python version check failed."),a.blank(),a.detail(`Once you've installed Python 3.10+, re-run the same command: ${he(n)}`),process.exit(1)),await hn();let y=Ae();y.ok||(a.error(y.message??"Node.js version check failed."),a.blank(),a.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${he(n)}`),process.exit(1));let l,P=!1;if(r){let h=rt(r);h||S("answers","The answers file is missing required fields. Required: PRICING, SUPABASE_URL, SUPABASE_SERVICE_KEY, SUPABASE_PAT, SUPABASE_PROJECT_REF, plus the credentials for your DEPLOY_PROVIDER (VERCEL_TOKEN, or CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID, or NETLIFY_AUTH_TOKEN, or SELFHOST_DEPLOY_TARGET + SELFHOST_URL_TEMPLATE). Keys match a working .env."),l=Ui(h,d,c),a.success("Loaded setup answers (non-interactive mode)");let f=c.AI_AGENT==="codex"?"codex":"claude-code";if(o&&f!==(l.aiAgent??"claude-code")){let k=E=>E==="codex"?"Codex":"Claude Code";S("folder",`This folder was set up for ${k(f)}, so it can't carry on as ${k(l.aiAgent??"claude-code")}. Give the folder a different name to set up fresh, or switch back.`)}}else if(s.kind==="partial")if(await Ga(n)==="resume"){let f=await zn(s.envPath,"utf-8"),k=rt(J(f));k?(a.success("Resuming with values from your existing .env"),a.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),l=k,P=!0,l.aiPlan||(l=await W(l,{onlySection:"ai-plan",banner:`One new question since this .env was written: which plan your agent
43
43
  runs on. It sets the QA-pass default (and, on the smaller ChatGPT plans, the model).`}))):(a.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),l=await W())}else{let f=await zn(s.envPath,"utf-8"),k=rt(J(f));l=await W(k??{})}else l=await W();l.licenseKey=u,await q(n,l),P||(a.success("Saved .env"),a.success(l.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),a.blank();for(let h=1;;h++){let f=v.spinner();f.start("Validating Supabase credentials");let k=await Me({url:l.supabaseUrl,serviceKey:l.supabaseServiceKey});if(k.ok){f.stop("Supabase credentials accepted");break}f.stop(k.message??"Supabase check failed",2),h>=V&&Pe(n,"Supabase",k.message??"Supabase check failed");let E=k.message??"Supabase check failed";a.blank(),x&&S("supabase",E),a.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${h+1} of ${V})`),a.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),a.blank(),l=await W(l,{onlySection:"supabase",banner:`Supabase rejected your credentials:
44
44
  ${E}
45
45
 
@@ -131,7 +131,7 @@ If the token keeps being refused, open ${Ot(p.supabaseProjectRef)}, paste in the
131
131
  `)[0]})})})}var to=40;function jl(e,t){let n=d=>{let c=d.toLowerCase(),p=new Map;for(let u=0;u<c.length-1;u++)p.set(c.slice(u,u+2),(p.get(c.slice(u,u+2))??0)+1);return p},[i,s]=[n(e),n(t)],o=0,r=0;for(let[d,c]of i)o+=Math.min(c,s.get(d)??0),r+=c;for(let d of s.values())r+=d;return r>0&&2*o/r>=.5}async function Kl(e,t,n,i){let s=r=>r.replace(/\r\n?/g,`
132
132
  `),o;try{o=await ro(K(lo(),"klaudius-clash-"))}catch{return[]}try{let[r,d,c]=["mine","base","theirs"].map(L=>K(o,L));await Nt(r,s(t)),await Nt(d,s(e)),await Nt(c,s(n));let p=await new Promise(L=>ci("git",["merge-file","-p","--diff3",`--marker-size=${to}`,r,d,c],{encoding:"utf8",maxBuffer:64*1024*1024,windowsHide:!0},($,_)=>{let C=$?.code;L(!$||typeof C=="number"&&C>0&&C<128?_:null)}));if(p===null)return[];let u=L=>{let $=new Map;for(let _ of s(L).split(`
133
133
  `)){let C=_.trim();C&&$.set(C,($.get(C)??0)+1)}return $},g=(L,$)=>L.get($)??0,[m,w,y]=[u(i),u(t),u(n)],l=L=>L.repeat(to),P=[],T=null,I={mine:[],base:[],theirs:[]};for(let L of p.split(`
134
- `))if(L.startsWith(`${l("<")} `))T="mine",I={mine:[],base:[],theirs:[]};else if(T&&L.startsWith(`${l("|")} `))T="base";else if(T&&L===l("="))T="theirs";else if(T&&L.startsWith(`${l(">")} `)){let $=G=>G.map(U=>U.trim()),_=$(I.mine),C=$(I.base),M=$(I.theirs);if(C.length>0&&_.length===C.length&&M.length===C.length)for(let G=0;G<C.length;G++){let[U,O,R]=[_[G],C[G],M[G]];!U||!R||U===O||R===O||U===R||!jl(U,R)||g(m,U)>g(y,U)&&g(m,R)>g(w,R)&&P.push(` kept both versions: ${U.slice(0,120)} / ${R.slice(0,120)}`)}T=null}else T&&I[T].push(L);return P}catch{return[]}finally{await At(o,{recursive:!0,force:!0}).catch(()=>{})}}async function no(e,t,n,i){let s=await se(K(e,Oe,t),"utf-8").catch(()=>null);if(s===null)return["No pre-edit base was staged for this file, so there is no line check. Say in plain words what the merge keeps from each side."];let o=await se(K(e,i,`${t}.bak`),"utf-8").catch(()=>null)??await se(K(e,t),"utf-8").catch(()=>""),r=await se(K(e,di,t),"utf-8");return[s,o,r,n].some($e)?["Binary file: no line check."]:["Line check against the pre-edit base:",...Ul(s,o,r,n),...await Kl(s,o,r,n)]}function Pn(e,t,n=0){for(let i of e)console.log(i);return console.log(`[klaudius-resolve] ${t}`),n}function j(e,t){return console.error(`${e} Nothing was changed.`),console.log(`[klaudius-resolve] refused${t===void 0?"":` remaining=${t}`}`),1}async function io(e,t,n,i){let s=n?.match(/to \*\*([^*]+)\*\*/)?.[1]?.trim();(i||s||t.pendingConflicts!==void 0)&&(s&&(t.templateVersion=s),delete t.pendingConflicts,t.updatedAt=new Date().toISOString(),await Ne(e,t));let o=d=>At(K(e,d),{recursive:!0,force:!0,maxRetries:3}).then(()=>!0,()=>!1);if(!await o(li))return{complete:!1,lines:[".klaudius/conflicts.md couldn't be removed, so the update staging was kept. Close anything that has it open, then run the same command again."]};let r=!1;for(let d of[di,Oe,$t])await o(d)||(r=!0);return{complete:!0,lines:[r?"Nothing is waiting for a decision. Some staging under .klaudius/ couldn't be removed; the next update clears it.":"Nothing is waiting for a decision. Update staging cleared."]}}var so=e=>new Promise(t=>setTimeout(t,e));function Gl(e,t){if(Date.now()-t>Rl)return!0;let n=Number(e.trim());if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!1}catch(i){return i.code==="ESRCH"}}async function Bl(e,t){let n=K(e,Cl),i=Date.now(),s=!1,o=0;for(;;)try{let r=await _l(n,"wx");await r.writeFile(String(process.pid)).finally(()=>r.close());break}catch(r){let d=r.code;if(d!=="EEXIST"&&d!=="EPERM")throw r;let c=await ao(n).catch(()=>null);if(c===null){if(d==="EPERM"&&++o>5)throw r;await so(50);continue}let p=await se(n,"utf-8").catch(()=>"");if(!s&&Gl(p,c.mtimeMs)){s=!0,await se(n,"utf-8").catch(()=>"")===p&&await At(n).catch(u=>{if(u.code!=="ENOENT")throw new Error(`.klaudius/resolve.lock was left by an earlier run and can't be removed (${u.message})`)});continue}if(Date.now()-i>vl)return null;await so(100)}try{return await t()}finally{await At(n,{force:!0}).catch(()=>{})}}async function uo(e){let t=e.projectRoot??process.cwd();return await wt(K(t,".klaudius","manifest.json"))?await Bl(t,()=>Vl(t,e))??j("Another resolve is still running in this project; run this again once it has finished."):j("No .klaudius/manifest.json here: run this from the Klaudius project folder.")}async function Vl(e,t){let n;try{n=await tn(e)}catch(R){return j(`.klaudius/manifest.json can't be read (${R.message}).`)}if(!n)return j("No .klaudius/manifest.json here: run this from the Klaudius project folder.");let i=await se(K(e,li),"utf-8").catch(()=>null),s=i===null?null:$l(i);if(t.finish){if(t.path||t.action)return j("--finish takes no file or action.");let R=s?.sections.length??0;if(R>0)return j(`${R} ${R===1?"conflict is":"conflicts are"} still waiting in .klaudius/conflicts.md.`,R);let Y=await io(e,n,i,!1);return Pn(Y.lines,Y.complete?"finished remaining=0":"remaining=0 incomplete",Y.complete?0:1)}if(!t.path||!t.action)return j("Name one file and exactly one action.",s?.sections.length);if(!s)return j("No conflicts are staged (.klaudius/conflicts.md is missing).",0);let o=s.sections.length,r=t.path.split("\\").join("/");if(si(t.path)&&(r=Xs(e,t.path).split("\\").join("/")),r=r.replace(/^\.\//,""),r===""||si(r)||/^[a-zA-Z]:/.test(r)||r.split("/").includes(".."))return j(`${t.path} isn't a path inside this project.`,o);let d=s.sections.find(R=>R.path===r);if(!d)return j(`${r} isn't waiting in .klaudius/conflicts.md (waiting: ${s.sections.map(R=>R.path).join(", ")||"none"}).`,o);let c=K(e,r),p=K(e,di,r),u=await wt(c),g=await wt(p),m=d.type??(g?u?"Edit conflict":"Deleted locally":"Removed upstream"),w=t.action;if(!ai[m].includes(w))return j(`${r} is a "${m}" conflict; its options are ${ai[m].map(R=>`--${R}`).join(", ")}.`,o);if(m!=="Removed upstream"&&!g)return j(`The staged new version .klaudius/incoming/${r} is missing; run npx klaudius@latest update to stage it again.`,o);if(m==="Edit conflict"&&!u&&(w==="keep-mine"||w==="check-merge"||w==="merge"||w==="auto-merge"))return j(`${r} is no longer on disk, so there's no version of yours to ${w==="keep-mine"?"keep":"merge"}; choose --take-new.`,o);let y=Dl(i),l=null,P=[];if(w==="check-merge"||w==="merge"){if(!t.draft)return j(`--${w} needs the merged draft's path.`,o);if(l=Lt(e,t.draft),process.platform==="linux"?l===Lt(c):l.toLowerCase()===Lt(c).toLowerCase())return j(`Write the merged version to its own draft file (${xl(r)}), not over ${r}: the original is what gets backed up.`,o);let Y=await se(l,"utf-8").catch(()=>null);if(Y===null)return j(`Can't read the draft ${t.draft}.`,o);let re=await se(p,"utf-8").catch(()=>null),z=await se(c,"utf-8").catch(()=>null),h=Zs(r,Y,re,z)??(re!==null&&z!==null?await eo(r,Y,z,re,ze(c)):null);if(h)return j(`The draft ${t.draft} ${h}.`,o);if(P=await no(e,r,Y,y),w==="check-merge")return Pn(P,`checked path=${r} remaining=${o}`)}let T=null;if(w==="auto-merge"){if(r.split("/").pop()===".gitignore")return j(".gitignore is only merged as a union (every line of the user's kept, the new patterns added, nothing removed), so it can't be merged automatically; merge it by hand.",o);let R=K(e,Oe,r);if(!await wt(R))return j(`${r} has no pre-edit base, so it can't be merged automatically; merge it by hand.`,o);let Y=K(e,y,`${r}.bak`),re=await wt(Y)?Y:c,z=await Hl(re,R,p);if("overlaps"in z)return j(`Your edits and the update's overlap in ${r} (${z.overlaps} place${z.overlaps===1?"":"s"}), so it can't be merged automatically; merge it by hand.`,o);if("unavailable"in z)return j(`git merge-file couldn't run (${z.unavailable}), so ${r} can't be merged automatically; merge it by hand.`,o);let h=z.merged.toString("utf-8"),f=await se(p,"utf-8").catch(()=>null),k=await se(re,"utf-8").catch(()=>null),E=Zs(r,h,f,k)??(f!==null&&k!==null?await eo(r,z.merged,k,f,ze(c)):null);if(E)return j(`The automatic merge of ${r} ${E}; merge it by hand.`,o);P=await no(e,r,h,y);let D=P.filter(b=>/^\s+(dropped|still present|kept both versions):/.test(b)).map(b=>b.trim());if(D.length>0)return j(`The automatic merge of ${r} doesn't keep every edit (${D.join("; ")}); merge it by hand.`,o);T=z.merged}if(w==="keep-deleted"&&u)return j(`${r} exists again, so it can't stay deleted; choose --restore, or move the file away first.`,o);let I=g?await fe(p):void 0,L=w==="take-new"||w==="restore"?I:w==="merge"?await fe(l):T?Pl("sha256").update(T).digest("hex"):void 0,$=u&&(w==="delete"||L!==void 0&&await fe(c)!==L),_=null;if($)try{_=await Fl(e,y,r)}catch(R){return j(`Couldn't save a backup copy of ${r} (${R.message}).`,o)}let C=[];switch(w){case"keep-mine":m==="Edit conflict"?(n.files[r]=I,C.push(`Kept your version of ${r}. Later updates treat it as your edit.`)):(delete n.files[r],C.push(`Kept ${r}. Klaudius no longer tracks it, so updates leave it alone.`));break;case"take-new":case"restore":await ri(ze(c),{recursive:!0}),await oo(p,c),n.files[r]=I,n.ignored&&(n.ignored=n.ignored.filter(R=>R!==r)),C.push(w==="take-new"?`Replaced ${r} with the new version.`:`Restored ${r} in its new version.`);break;case"merge":case"auto-merge":{let R=u?(await ao(c)).mode&4095:void 0,Y=T??await se(l);await ri(ze(c),{recursive:!0}),u&&(await bl(c)).isSymbolicLink()?await Nt(c,Y):await Ee(c,Y,R),n.files[r]=I,C.push(`Wrote the merged version to ${r}.`,...P);break}case"keep-deleted":delete n.files[r],n.ignored=[...new Set([...n.ignored??[],r])],C.push(`${r} stays deleted; updates won't reinstall it.`);break;case"delete":u&&await At(c,{force:!0}),delete n.files[r],C.push(`Deleted ${r}.`);break}_&&C.push(`Your previous version is saved at ${_}.`);let M=o-1,G=!0;if(M>0)n.pendingConflicts=M,n.updatedAt=new Date().toISOString(),await Ne(e,n),await Ee(K(e,li),Ml(s,d,M));else{let R=await io(e,n,i,!0);C.push(...R.lines),G=R.complete}let U=l===null?"":Xs(Lt(e,$t),l);G&&U&&!U.startsWith("..")&&!si(U)&&await Il(l).catch(()=>{});let O=`path=${r} action=${w} remaining=${M}`;return G?Pn(C,O):Pn(C,`${O} incomplete`,1)}var Ft="0.37.4";async function mo(e){let t=e.projectRoot??process.cwd(),n=await tn(t);n||(a.error("This doesn't look like a Klaudius project."),a.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let f of It)delete n.files[f];let i,s=F(t,".env"),o,r;try{o=await Mt(s,"utf-8"),r=J(o)}catch{a.error("Couldn't read .env from this directory."),a.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=r.KLAUDIUS_LICENSE_KEY??"",i||(a.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),a.detail("This file is created by `npx klaudius@latest init`. If your project predates"),a.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),a.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let d=e.check?null:Di(o,r,Mi);d!==null&&(await bn(s,d,"utf-8"),a.detail("Backfilled new env keys")),await dn("update",Ft),Ge.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Ft}`),await hn();let p=r.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&p==="claude-code"&&await Ke(t,je)==="added"&&a.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=F(Yl(),`klaudius-update-${process.pid}-${Date.now()}`),g;try{a.heading("Downloading the latest Klaudius template");let f=await ln({licenseKey:i,machineId:vt(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:u});a.success(`Fetched ${f.filesExtracted} canonical files`),g=u}catch(f){a.error(f.message),a.detail("Update aborted. Your project is unchanged."),await Se(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let m=await ql(g,t,n);if(e.check){let f=m.filter(b=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(b.state)),k=m.filter(b=>["conflict","locally-deleted","removed-modified"].includes(b.state)&&!(b.path===".gitignore"&&b.state==="conflict")),E="unknown";if(r.SUPABASE_URL&&r.SUPABASE_SERVICE_KEY){let b=await Mt(F(g,"scripts","schema.sql"),"utf-8").catch(()=>""),N=await xt({url:r.SUPABASE_URL,serviceKey:r.SUPABASE_SERVICE_KEY,sql:b});N.unreachable?a.detail(`Database schema not checked (${N.unreachable}).`):N.ok?E="current":(E="stale",a.detail(`Database schema is behind (missing: ${N.missing.join(", ")}); update applies scripts/schema.sql.`))}let D=f.length>0||E==="stale";a.blank(),D?(f.length>0&&a.detail(`${Z(f.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),Ge.outro(Dt.yellow("An update is available."))):Ge.outro(Dt.green("Already up to date.")),console.log(`[klaudius-update-check] status=${D?"behind":"current"} pending=${f.length+(E==="stale"?1:0)} conflicts=${k.length} schema=${E}`),await Se(u,{recursive:!0,force:!0}).catch(()=>{});return}let w=!1,y=m.find(f=>f.path===".gitignore"&&f.state==="conflict");if(y){let f=F(t,".gitignore"),k=await Mt(f,"utf-8"),E=await Mt(F(g,".gitignore"),"utf-8"),{merged:D,added:b}=Jl(k,E);b.length>0&&await bn(f,D,"utf-8"),n.files[".gitignore"]=y.canonicalHash,y.state="gitignore-merged",w=!0,a.detail(b.length>0?`.gitignore auto-merged: kept all your lines, appended ${Z(b.length,"new canonical pattern")}: ${b.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let l=m.filter(f=>f.state==="new"),P=m.filter(f=>f.state==="clean-update"),T=m.filter(f=>f.state==="user-only"),I=m.filter(f=>f.state==="conflict"),L=m.filter(f=>f.state==="no-change"),$=m.filter(f=>f.state==="locally-deleted"),_=m.filter(f=>f.state==="removed-clean"),C=m.filter(f=>f.state==="removed-modified"),M=[...I,...$,...C],G=n.ignored?.length??0;a.blank(),a.heading("Change summary"),a.detail(`${Z(L.length,"file")} unchanged`),a.detail(`${Z(l.length,"new file")}`),a.detail(`${Z(P.length,"file")} updated cleanly (no local edits)`),a.detail(`${Z(T.length,"file")} you've edited (no upstream change \u2014 left alone)`),a.detail(`${Z(_.length,"file")} removed upstream (deleted cleanly)`);let U=I.filter(f=>f.reason==="untracked-local").length,O=I.filter(f=>f.reason==="manifest-mismatch").length;a.detail(`${Z(I.filter(f=>!f.reason).length,"file")} with conflicts (you edited AND we have a new version)`),U>0&&a.detail(`${Z(U,"file")} of your own at a path the new version now ships (need your decision)`),O>0&&a.detail(`${fi(O)}, and we have a new version (need your decision)`),a.detail(`${Z($.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`);let R=C.filter(f=>f.reason==="manifest-mismatch").length;if(a.detail(`${Z(C.length-R,"file")} removed upstream but edited locally (need your decision)`),R>0&&a.detail(`${fi(R)}, removed upstream (need your decision)`),G>0&&(a.detail(`${Z(G,"file")} kept deleted (previously resolved \u2014 skipped)`),G<=10))for(let f of n.ignored)a.detail(` kept deleted: ${f}`);let Y=async()=>{let f=!1,k=E=>Se(E,{recursive:!0,force:!0}).catch(()=>{f=!0});await k(F(t,".klaudius","incoming")),await k(F(t,Oe)),await k(F(t,$t)),await k(F(t,".klaudius","conflicts.md")),f&&a.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/, .klaudius/merged/ and .klaudius/conflicts.md by hand)")};if(l.length===0&&P.length===0&&_.length===0&&M.length===0&&!w){await po(t,r,!1),await Y(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Ft,await Ne(t,n)),a.blank(),Ge.outro(Dt.green("Already up to date.")),await Se(u,{recursive:!0,force:!0}).catch(()=>{});return}let re=new Date().toISOString().replace(/[:.]/g,"-"),z=`.klaudius/backup/update-${re}`,h=0;for(let f of[...P,..._]){if(f.localHash===void 0||f.localHash===f.canonicalHash)continue;let k=F(t,z,`${f.path}.bak`);try{await Sn(_n(k),{recursive:!0}),await ui(F(t,f.path),k)}catch(E){a.error(`Couldn't save a backup copy of ${f.path}: ${E.message}`),a.detail("Update stopped before replacing or removing any files (additions already made, such as new .env keys, are kept)."),await Se(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}h++}a.blank(),a.heading("Applying clean updates");for(let f of[...l,...P]){let k=F(g,f.path),E=F(t,f.path);await Sn(_n(E),{recursive:!0}),await ui(k,E),n.files[f.path]=f.canonicalHash}l.length+P.length>0&&a.success(`Wrote ${Z(l.length+P.length,"file")}`),[...l,...P].some(f=>f.path==="package.json"||f.path==="package-lock.json")&&a.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let f of _){let k=F(t,f.path);await Se(k,{force:!0}),delete n.files[f.path]}if(_.length>0){a.success(`Deleted ${Z(_.length,"file")} removed upstream`);for(let f of _.slice(0,20))a.detail(` removed: ${f.path}`);_.length>20&&a.detail(` \u2026and ${_.length-20} more`)}if(h>0&&a.detail(`Previous copies of the ${Z(h,"file")} replaced or removed are in ${z}/ (each saved as <name>.bak)`),await po(t,r,M.some(f=>f.path==="scripts/schema.sql")),M.length>0){a.blank(),a.heading(`${M.length} conflict(s) need resolution`);let f=F(t,".klaudius","incoming");try{await Se(f,{recursive:!0,force:!0})}catch{}await Se(F(t,$t),{recursive:!0,force:!0}).catch(()=>{});for(let b of[...I,...$]){let N=F(g,b.path),ie=F(f,b.path);await Sn(_n(ie),{recursive:!0}),await ui(N,ie)}let k=new Map,E=new Map;for(let b of I){let N=await as(t,b.path),ie=await ls(t,b.path),_e=await Mt(F(g,b.path),"utf-8"),ae=cs(N,ie,_e,b.manifestHash);b.reason==="untracked-local"?k.set(b.path,["_Klaudius doesn't track this file (it's your own, or one kept after an earlier version dropped it), and the new version ships one at the same path. No common base exists: compare your copy with `.klaudius/incoming/"+b.path+"` directly._"]):b.reason==="manifest-mismatch"?k.set(b.path,["_The manifest's entry for this file isn't the version Klaudius last installed (a hand-edited manifest, a conflict resolved outside `/resolve-conflicts`, or a folder restored from an older copy), so your copy was left in place. No verified base exists: compare it with `.klaudius/incoming/"+b.path+"` directly. If the file was never changed on purpose, taking the new version is safe._"]):ae!==null?(E.set(b.path,ae),k.set(b.path,ds(ae,_e))):N!==null&&($e(N)||$e(_e))?k.set(b.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+b.path+"` directly._"]):N===null?k.set(b.path,["_No base snapshot on this install (it predates upstream-change summaries). This update saves one, so the next update can show exactly what changed._"]):k.set(b.path,["_The base snapshot is newer than the version your edits diverged from (an earlier update's conflicts were left unresolved), so a precise upstream diff isn't available for this file \u2014 compare against `.klaudius/incoming/"+b.path+"` directly._"])}let D=F(t,Oe);try{await Se(D,{recursive:!0,force:!0})}catch{}for(let[b,N]of E){let ie=F(D,b);await Sn(_n(ie),{recursive:!0}),await bn(ie,N,"utf-8")}await bn(F(t,".klaudius","conflicts.md"),Ql(M,n.templateVersion,Ft,k,E),"utf-8"),I.length+$.length>0&&a.detail("Staged canonical versions to .klaudius/incoming/"),E.size>0&&a.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),a.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=Ft,n.baseSnapshot=re,M.length===0?(delete n.pendingConflicts,await Y()):n.pendingConflicts=M.length,await Ne(t,n);try{await cn(t,g,await qe(g),re)}catch{a.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(a.blank(),M.length===0)Ge.outro(Dt.green("Update complete."));else{let f=p==="codex"?"Codex":"Claude Code";Ge.outro(Dt.yellow(`${M.length} conflict(s) staged. Open ${f} in this project and ask:
134
+ `))if(L.startsWith(`${l("<")} `))T="mine",I={mine:[],base:[],theirs:[]};else if(T&&L.startsWith(`${l("|")} `))T="base";else if(T&&L===l("="))T="theirs";else if(T&&L.startsWith(`${l(">")} `)){let $=G=>G.map(U=>U.trim()),_=$(I.mine),C=$(I.base),M=$(I.theirs);if(C.length>0&&_.length===C.length&&M.length===C.length)for(let G=0;G<C.length;G++){let[U,O,R]=[_[G],C[G],M[G]];!U||!R||U===O||R===O||U===R||!jl(U,R)||g(m,U)>g(y,U)&&g(m,R)>g(w,R)&&P.push(` kept both versions: ${U.slice(0,120)} / ${R.slice(0,120)}`)}T=null}else T&&I[T].push(L);return P}catch{return[]}finally{await At(o,{recursive:!0,force:!0}).catch(()=>{})}}async function no(e,t,n,i){let s=await se(K(e,Oe,t),"utf-8").catch(()=>null);if(s===null)return["No pre-edit base was staged for this file, so there is no line check. Say in plain words what the merge keeps from each side."];let o=await se(K(e,i,`${t}.bak`),"utf-8").catch(()=>null)??await se(K(e,t),"utf-8").catch(()=>""),r=await se(K(e,di,t),"utf-8");return[s,o,r,n].some($e)?["Binary file: no line check."]:["Line check against the pre-edit base:",...Ul(s,o,r,n),...await Kl(s,o,r,n)]}function Pn(e,t,n=0){for(let i of e)console.log(i);return console.log(`[klaudius-resolve] ${t}`),n}function j(e,t){return console.error(`${e} Nothing was changed.`),console.log(`[klaudius-resolve] refused${t===void 0?"":` remaining=${t}`}`),1}async function io(e,t,n,i){let s=n?.match(/to \*\*([^*]+)\*\*/)?.[1]?.trim();(i||s||t.pendingConflicts!==void 0)&&(s&&(t.templateVersion=s),delete t.pendingConflicts,t.updatedAt=new Date().toISOString(),await Ne(e,t));let o=d=>At(K(e,d),{recursive:!0,force:!0,maxRetries:3}).then(()=>!0,()=>!1);if(!await o(li))return{complete:!1,lines:[".klaudius/conflicts.md couldn't be removed, so the update staging was kept. Close anything that has it open, then run the same command again."]};let r=!1;for(let d of[di,Oe,$t])await o(d)||(r=!0);return{complete:!0,lines:[r?"Nothing is waiting for a decision. Some staging under .klaudius/ couldn't be removed; the next update clears it.":"Nothing is waiting for a decision. Update staging cleared."]}}var so=e=>new Promise(t=>setTimeout(t,e));function Gl(e,t){if(Date.now()-t>Rl)return!0;let n=Number(e.trim());if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!1}catch(i){return i.code==="ESRCH"}}async function Bl(e,t){let n=K(e,Cl),i=Date.now(),s=!1,o=0;for(;;)try{let r=await _l(n,"wx");await r.writeFile(String(process.pid)).finally(()=>r.close());break}catch(r){let d=r.code;if(d!=="EEXIST"&&d!=="EPERM")throw r;let c=await ao(n).catch(()=>null);if(c===null){if(d==="EPERM"&&++o>5)throw r;await so(50);continue}let p=await se(n,"utf-8").catch(()=>"");if(!s&&Gl(p,c.mtimeMs)){s=!0,await se(n,"utf-8").catch(()=>"")===p&&await At(n).catch(u=>{if(u.code!=="ENOENT")throw new Error(`.klaudius/resolve.lock was left by an earlier run and can't be removed (${u.message})`)});continue}if(Date.now()-i>vl)return null;await so(100)}try{return await t()}finally{await At(n,{force:!0}).catch(()=>{})}}async function uo(e){let t=e.projectRoot??process.cwd();return await wt(K(t,".klaudius","manifest.json"))?await Bl(t,()=>Vl(t,e))??j("Another resolve is still running in this project; run this again once it has finished."):j("No .klaudius/manifest.json here: run this from the Klaudius project folder.")}async function Vl(e,t){let n;try{n=await tn(e)}catch(R){return j(`.klaudius/manifest.json can't be read (${R.message}).`)}if(!n)return j("No .klaudius/manifest.json here: run this from the Klaudius project folder.");let i=await se(K(e,li),"utf-8").catch(()=>null),s=i===null?null:$l(i);if(t.finish){if(t.path||t.action)return j("--finish takes no file or action.");let R=s?.sections.length??0;if(R>0)return j(`${R} ${R===1?"conflict is":"conflicts are"} still waiting in .klaudius/conflicts.md.`,R);let Y=await io(e,n,i,!1);return Pn(Y.lines,Y.complete?"finished remaining=0":"remaining=0 incomplete",Y.complete?0:1)}if(!t.path||!t.action)return j("Name one file and exactly one action.",s?.sections.length);if(!s)return j("No conflicts are staged (.klaudius/conflicts.md is missing).",0);let o=s.sections.length,r=t.path.split("\\").join("/");if(si(t.path)&&(r=Xs(e,t.path).split("\\").join("/")),r=r.replace(/^\.\//,""),r===""||si(r)||/^[a-zA-Z]:/.test(r)||r.split("/").includes(".."))return j(`${t.path} isn't a path inside this project.`,o);let d=s.sections.find(R=>R.path===r);if(!d)return j(`${r} isn't waiting in .klaudius/conflicts.md (waiting: ${s.sections.map(R=>R.path).join(", ")||"none"}).`,o);let c=K(e,r),p=K(e,di,r),u=await wt(c),g=await wt(p),m=d.type??(g?u?"Edit conflict":"Deleted locally":"Removed upstream"),w=t.action;if(!ai[m].includes(w))return j(`${r} is a "${m}" conflict; its options are ${ai[m].map(R=>`--${R}`).join(", ")}.`,o);if(m!=="Removed upstream"&&!g)return j(`The staged new version .klaudius/incoming/${r} is missing; run npx klaudius@latest update to stage it again.`,o);if(m==="Edit conflict"&&!u&&(w==="keep-mine"||w==="check-merge"||w==="merge"||w==="auto-merge"))return j(`${r} is no longer on disk, so there's no version of yours to ${w==="keep-mine"?"keep":"merge"}; choose --take-new.`,o);let y=Dl(i),l=null,P=[];if(w==="check-merge"||w==="merge"){if(!t.draft)return j(`--${w} needs the merged draft's path.`,o);if(l=Lt(e,t.draft),process.platform==="linux"?l===Lt(c):l.toLowerCase()===Lt(c).toLowerCase())return j(`Write the merged version to its own draft file (${xl(r)}), not over ${r}: the original is what gets backed up.`,o);let Y=await se(l,"utf-8").catch(()=>null);if(Y===null)return j(`Can't read the draft ${t.draft}.`,o);let re=await se(p,"utf-8").catch(()=>null),z=await se(c,"utf-8").catch(()=>null),h=Zs(r,Y,re,z)??(re!==null&&z!==null?await eo(r,Y,z,re,ze(c)):null);if(h)return j(`The draft ${t.draft} ${h}.`,o);if(P=await no(e,r,Y,y),w==="check-merge")return Pn(P,`checked path=${r} remaining=${o}`)}let T=null;if(w==="auto-merge"){if(r.split("/").pop()===".gitignore")return j(".gitignore is only merged as a union (every line of the user's kept, the new patterns added, nothing removed), so it can't be merged automatically; merge it by hand.",o);let R=K(e,Oe,r);if(!await wt(R))return j(`${r} has no pre-edit base, so it can't be merged automatically; merge it by hand.`,o);let Y=K(e,y,`${r}.bak`),re=await wt(Y)?Y:c,z=await Hl(re,R,p);if("overlaps"in z)return j(`Your edits and the update's overlap in ${r} (${z.overlaps} place${z.overlaps===1?"":"s"}), so it can't be merged automatically; merge it by hand.`,o);if("unavailable"in z)return j(`git merge-file couldn't run (${z.unavailable}), so ${r} can't be merged automatically; merge it by hand.`,o);let h=z.merged.toString("utf-8"),f=await se(p,"utf-8").catch(()=>null),k=await se(re,"utf-8").catch(()=>null),E=Zs(r,h,f,k)??(f!==null&&k!==null?await eo(r,z.merged,k,f,ze(c)):null);if(E)return j(`The automatic merge of ${r} ${E}; merge it by hand.`,o);P=await no(e,r,h,y);let D=P.filter(b=>/^\s+(dropped|still present|kept both versions):/.test(b)).map(b=>b.trim());if(D.length>0)return j(`The automatic merge of ${r} doesn't keep every edit (${D.join("; ")}); merge it by hand.`,o);T=z.merged}if(w==="keep-deleted"&&u)return j(`${r} exists again, so it can't stay deleted; choose --restore, or move the file away first.`,o);let I=g?await fe(p):void 0,L=w==="take-new"||w==="restore"?I:w==="merge"?await fe(l):T?Pl("sha256").update(T).digest("hex"):void 0,$=u&&(w==="delete"||L!==void 0&&await fe(c)!==L),_=null;if($)try{_=await Fl(e,y,r)}catch(R){return j(`Couldn't save a backup copy of ${r} (${R.message}).`,o)}let C=[];switch(w){case"keep-mine":m==="Edit conflict"?(n.files[r]=I,C.push(`Kept your version of ${r}. Later updates treat it as your edit.`)):(delete n.files[r],C.push(`Kept ${r}. Klaudius no longer tracks it, so updates leave it alone.`));break;case"take-new":case"restore":await ri(ze(c),{recursive:!0}),await oo(p,c),n.files[r]=I,n.ignored&&(n.ignored=n.ignored.filter(R=>R!==r)),C.push(w==="take-new"?`Replaced ${r} with the new version.`:`Restored ${r} in its new version.`);break;case"merge":case"auto-merge":{let R=u?(await ao(c)).mode&4095:void 0,Y=T??await se(l);await ri(ze(c),{recursive:!0}),u&&(await bl(c)).isSymbolicLink()?await Nt(c,Y):await Ee(c,Y,R),n.files[r]=I,C.push(`Wrote the merged version to ${r}.`,...P);break}case"keep-deleted":delete n.files[r],n.ignored=[...new Set([...n.ignored??[],r])],C.push(`${r} stays deleted; updates won't reinstall it.`);break;case"delete":u&&await At(c,{force:!0}),delete n.files[r],C.push(`Deleted ${r}.`);break}_&&C.push(`Your previous version is saved at ${_}.`);let M=o-1,G=!0;if(M>0)n.pendingConflicts=M,n.updatedAt=new Date().toISOString(),await Ne(e,n),await Ee(K(e,li),Ml(s,d,M));else{let R=await io(e,n,i,!0);C.push(...R.lines),G=R.complete}let U=l===null?"":Xs(Lt(e,$t),l);G&&U&&!U.startsWith("..")&&!si(U)&&await Il(l).catch(()=>{});let O=`path=${r} action=${w} remaining=${M}`;return G?Pn(C,O):Pn(C,`${O} incomplete`,1)}var Ft="0.37.5";async function mo(e){let t=e.projectRoot??process.cwd(),n=await tn(t);n||(a.error("This doesn't look like a Klaudius project."),a.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let f of It)delete n.files[f];let i,s=F(t,".env"),o,r;try{o=await Mt(s,"utf-8"),r=J(o)}catch{a.error("Couldn't read .env from this directory."),a.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}i=r.KLAUDIUS_LICENSE_KEY??"",i||(a.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),a.detail("This file is created by `npx klaudius@latest init`. If your project predates"),a.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),a.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let d=e.check?null:Di(o,r,Mi);d!==null&&(await bn(s,d,"utf-8"),a.detail("Backfilled new env keys")),await dn("update",Ft),Ge.intro(e.check?`Checking for updates (you're on ${n.templateVersion})`:`Update from ${n.templateVersion} \u2192 ${Ft}`),await hn();let p=r.AI_AGENT==="codex"?"codex":"claude-code";!e.check&&p==="claude-code"&&await Ke(t,je)==="added"&&a.detail("Pre-approved the parallel-run dispatch in .claude/settings.local.json");let u=F(Yl(),`klaudius-update-${process.pid}-${Date.now()}`),g;try{a.heading("Downloading the latest Klaudius template");let f=await ln({licenseKey:i,machineId:vt(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:p,destDir:u});a.success(`Fetched ${f.filesExtracted} canonical files`),g=u}catch(f){a.error(f.message),a.detail("Update aborted. Your project is unchanged."),await Se(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let m=await ql(g,t,n);if(e.check){let f=m.filter(b=>["new","clean-update","removed-clean","conflict","locally-deleted","removed-modified"].includes(b.state)),k=m.filter(b=>["conflict","locally-deleted","removed-modified"].includes(b.state)&&!(b.path===".gitignore"&&b.state==="conflict")),E="unknown";if(r.SUPABASE_URL&&r.SUPABASE_SERVICE_KEY){let b=await Mt(F(g,"scripts","schema.sql"),"utf-8").catch(()=>""),N=await xt({url:r.SUPABASE_URL,serviceKey:r.SUPABASE_SERVICE_KEY,sql:b});N.unreachable?a.detail(`Database schema not checked (${N.unreachable}).`):N.ok?E="current":(E="stale",a.detail(`Database schema is behind (missing: ${N.missing.join(", ")}); update applies scripts/schema.sql.`))}let D=f.length>0||E==="stale";a.blank(),D?(f.length>0&&a.detail(`${Z(f.length,"file")} would change; run \`npx klaudius@latest update\` to apply.`),Ge.outro(Dt.yellow("An update is available."))):Ge.outro(Dt.green("Already up to date.")),console.log(`[klaudius-update-check] status=${D?"behind":"current"} pending=${f.length+(E==="stale"?1:0)} conflicts=${k.length} schema=${E}`),await Se(u,{recursive:!0,force:!0}).catch(()=>{});return}let w=!1,y=m.find(f=>f.path===".gitignore"&&f.state==="conflict");if(y){let f=F(t,".gitignore"),k=await Mt(f,"utf-8"),E=await Mt(F(g,".gitignore"),"utf-8"),{merged:D,added:b}=Jl(k,E);b.length>0&&await bn(f,D,"utf-8"),n.files[".gitignore"]=y.canonicalHash,y.state="gitignore-merged",w=!0,a.detail(b.length>0?`.gitignore auto-merged: kept all your lines, appended ${Z(b.length,"new canonical pattern")}: ${b.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let l=m.filter(f=>f.state==="new"),P=m.filter(f=>f.state==="clean-update"),T=m.filter(f=>f.state==="user-only"),I=m.filter(f=>f.state==="conflict"),L=m.filter(f=>f.state==="no-change"),$=m.filter(f=>f.state==="locally-deleted"),_=m.filter(f=>f.state==="removed-clean"),C=m.filter(f=>f.state==="removed-modified"),M=[...I,...$,...C],G=n.ignored?.length??0;a.blank(),a.heading("Change summary"),a.detail(`${Z(L.length,"file")} unchanged`),a.detail(`${Z(l.length,"new file")}`),a.detail(`${Z(P.length,"file")} updated cleanly (no local edits)`),a.detail(`${Z(T.length,"file")} you've edited (no upstream change \u2014 left alone)`),a.detail(`${Z(_.length,"file")} removed upstream (deleted cleanly)`);let U=I.filter(f=>f.reason==="untracked-local").length,O=I.filter(f=>f.reason==="manifest-mismatch").length;a.detail(`${Z(I.filter(f=>!f.reason).length,"file")} with conflicts (you edited AND we have a new version)`),U>0&&a.detail(`${Z(U,"file")} of your own at a path the new version now ships (need your decision)`),O>0&&a.detail(`${fi(O)}, and we have a new version (need your decision)`),a.detail(`${Z($.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`);let R=C.filter(f=>f.reason==="manifest-mismatch").length;if(a.detail(`${Z(C.length-R,"file")} removed upstream but edited locally (need your decision)`),R>0&&a.detail(`${fi(R)}, removed upstream (need your decision)`),G>0&&(a.detail(`${Z(G,"file")} kept deleted (previously resolved \u2014 skipped)`),G<=10))for(let f of n.ignored)a.detail(` kept deleted: ${f}`);let Y=async()=>{let f=!1,k=E=>Se(E,{recursive:!0,force:!0}).catch(()=>{f=!0});await k(F(t,".klaudius","incoming")),await k(F(t,Oe)),await k(F(t,$t)),await k(F(t,".klaudius","conflicts.md")),f&&a.detail("(couldn't fully clear old conflict staging \u2014 close any editor holding .klaudius/conflicts.md, then delete .klaudius/incoming/, .klaudius/conflict-base/, .klaudius/merged/ and .klaudius/conflicts.md by hand)")};if(l.length===0&&P.length===0&&_.length===0&&M.length===0&&!w){await po(t,r,!1),await Y(),n.pendingConflicts!==void 0&&(delete n.pendingConflicts,n.templateVersion=Ft,await Ne(t,n)),a.blank(),Ge.outro(Dt.green("Already up to date.")),await Se(u,{recursive:!0,force:!0}).catch(()=>{});return}let re=new Date().toISOString().replace(/[:.]/g,"-"),z=`.klaudius/backup/update-${re}`,h=0;for(let f of[...P,..._]){if(f.localHash===void 0||f.localHash===f.canonicalHash)continue;let k=F(t,z,`${f.path}.bak`);try{await Sn(_n(k),{recursive:!0}),await ui(F(t,f.path),k)}catch(E){a.error(`Couldn't save a backup copy of ${f.path}: ${E.message}`),a.detail("Update stopped before replacing or removing any files (additions already made, such as new .env keys, are kept)."),await Se(u,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}h++}a.blank(),a.heading("Applying clean updates");for(let f of[...l,...P]){let k=F(g,f.path),E=F(t,f.path);await Sn(_n(E),{recursive:!0}),await ui(k,E),n.files[f.path]=f.canonicalHash}l.length+P.length>0&&a.success(`Wrote ${Z(l.length+P.length,"file")}`),[...l,...P].some(f=>f.path==="package.json"||f.path==="package-lock.json")&&a.detail("Dependencies changed. Ask your agent to reinstall, or run `npx klaudius@latest install`, so node_modules matches.");for(let f of _){let k=F(t,f.path);await Se(k,{force:!0}),delete n.files[f.path]}if(_.length>0){a.success(`Deleted ${Z(_.length,"file")} removed upstream`);for(let f of _.slice(0,20))a.detail(` removed: ${f.path}`);_.length>20&&a.detail(` \u2026and ${_.length-20} more`)}if(h>0&&a.detail(`Previous copies of the ${Z(h,"file")} replaced or removed are in ${z}/ (each saved as <name>.bak)`),await po(t,r,M.some(f=>f.path==="scripts/schema.sql")),M.length>0){a.blank(),a.heading(`${M.length} conflict(s) need resolution`);let f=F(t,".klaudius","incoming");try{await Se(f,{recursive:!0,force:!0})}catch{}await Se(F(t,$t),{recursive:!0,force:!0}).catch(()=>{});for(let b of[...I,...$]){let N=F(g,b.path),ie=F(f,b.path);await Sn(_n(ie),{recursive:!0}),await ui(N,ie)}let k=new Map,E=new Map;for(let b of I){let N=await as(t,b.path),ie=await ls(t,b.path),_e=await Mt(F(g,b.path),"utf-8"),ae=cs(N,ie,_e,b.manifestHash);b.reason==="untracked-local"?k.set(b.path,["_Klaudius doesn't track this file (it's your own, or one kept after an earlier version dropped it), and the new version ships one at the same path. No common base exists: compare your copy with `.klaudius/incoming/"+b.path+"` directly._"]):b.reason==="manifest-mismatch"?k.set(b.path,["_The manifest's entry for this file isn't the version Klaudius last installed (a hand-edited manifest, a conflict resolved outside `/resolve-conflicts`, or a folder restored from an older copy), so your copy was left in place. No verified base exists: compare it with `.klaudius/incoming/"+b.path+"` directly. If the file was never changed on purpose, taking the new version is safe._"]):ae!==null?(E.set(b.path,ae),k.set(b.path,ds(ae,_e))):N!==null&&($e(N)||$e(_e))?k.set(b.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+b.path+"` directly._"]):N===null?k.set(b.path,["_No base snapshot on this install (it predates upstream-change summaries). This update saves one, so the next update can show exactly what changed._"]):k.set(b.path,["_The base snapshot is newer than the version your edits diverged from (an earlier update's conflicts were left unresolved), so a precise upstream diff isn't available for this file \u2014 compare against `.klaudius/incoming/"+b.path+"` directly._"])}let D=F(t,Oe);try{await Se(D,{recursive:!0,force:!0})}catch{}for(let[b,N]of E){let ie=F(D,b);await Sn(_n(ie),{recursive:!0}),await bn(ie,N,"utf-8")}await bn(F(t,".klaudius","conflicts.md"),Ql(M,n.templateVersion,Ft,k,E),"utf-8"),I.length+$.length>0&&a.detail("Staged canonical versions to .klaudius/incoming/"),E.size>0&&a.detail("Staged pre-edit base versions to .klaudius/conflict-base/"),a.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),n.templateVersion=Ft,n.baseSnapshot=re,M.length===0?(delete n.pendingConflicts,await Y()):n.pendingConflicts=M.length,await Ne(t,n);try{await cn(t,g,await qe(g),re)}catch{a.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(a.blank(),M.length===0)Ge.outro(Dt.green("Update complete."));else{let f=p==="codex"?"Codex":"Claude Code";Ge.outro(Dt.yellow(`${M.length} conflict(s) staged. Open ${f} in this project and ask:
135
135
  "Run /resolve-conflicts"`))}await Se(u,{recursive:!0,force:!0}).catch(()=>{})}async function po(e,t,n){let i=await Wl(e,t,n);return console.log(`[klaudius-update] schema=${i}`),i}async function Wl(e,t,n){let i=(t.SUPABASE_PAT??"").replace(/\s+/g,""),s=(t.SUPABASE_PROJECT_REF??"").trim();if(!i||!s)return a.detail("Database schema not checked: SUPABASE_PAT / SUPABASE_PROJECT_REF aren't in .env. Run `npx klaudius@latest configure` to add them, or paste scripts/schema.sql into your Supabase SQL editor (safe to re-run)."),"skipped";let o=await lt({projectRoot:e,pat:i,projectRef:s,url:t.SUPABASE_URL,serviceKey:t.SUPABASE_SERVICE_KEY});return o.ok&&o.tokenRefused?(a.warn(`Supabase refused the access token (HTTP ${o.tokenRefused}), so scripts/schema.sql wasn't re-applied; every table and column in it is already in the database.`),n&&a.detail("scripts/schema.sql is in conflict, so the check used your current copy \u2014 resolve its conflict, then run update again."),a.detail(ct(o.tokenRefused)),a.detail(dt(s)),"present"):o.ok?(a.success(n?"Database schema applied from your current scripts/schema.sql \u2014 resolve its conflict, then run update again to apply the new version":"Database schema up to date"),"applied"):(a.warn(o.message??"Database schema could not be applied"),a.detail(`Paste scripts/schema.sql into the SQL editor to apply it by hand (safe to re-run): ${Ot(s)}`),"failed")}async function ql(e,t,n){let i=await qe(e),s=new Set(i),o=new Map;for(let p of i)o.set(p,await fe(F(e,p)));let r=await zl(t,n,o),d=new Set(n.ignored??[]),c=[];for(let p of i){if(d.has(p)||It.has(p))continue;let u=o.get(p),g=n.files[p],m=F(t,p),w;try{await pi(m),w=await fe(m)}catch{let l=g!==void 0&&!Yi.has(p)&&!en.has(p)?"locally-deleted":"new";c.push({path:p,state:l,canonicalHash:u,manifestHash:g});continue}let y=en.has(p);u===g?w===g||y?c.push({path:p,state:"no-change",canonicalHash:u,localHash:w,manifestHash:g}):c.push({path:p,state:"user-only",canonicalHash:u,localHash:w,manifestHash:g}):w===u||y?c.push({path:p,state:"clean-update",canonicalHash:u,localHash:w,manifestHash:g}):g===void 0?c.push({path:p,state:"conflict",reason:"untracked-local",canonicalHash:u,localHash:w,manifestHash:g}):w!==g?c.push({path:p,state:"conflict",canonicalHash:u,localHash:w,manifestHash:g}):await r(p,g)?c.push({path:p,state:"conflict",reason:"manifest-mismatch",canonicalHash:u,localHash:w,manifestHash:g}):c.push({path:p,state:"clean-update",canonicalHash:u,localHash:w,manifestHash:g})}for(let p of Object.keys(n.files)){if(s.has(p))continue;let u=n.files[p],g=F(t,p),m;try{await pi(g),m=await fe(g)}catch{delete n.files[p];continue}en.has(p)?c.push({path:p,state:"removed-clean",localHash:m,manifestHash:u}):m!==u?c.push({path:p,state:"removed-modified",localHash:m,manifestHash:u}):await r(p,u)?c.push({path:p,state:"removed-modified",reason:"manifest-mismatch",localHash:m,manifestHash:u}):c.push({path:p,state:"removed-clean",localHash:m,manifestHash:u})}return c}async function zl(e,t,n){let i=F(e,Rt),s=async p=>{try{return await fe(p)}catch{return null}},o=async(p,u,g)=>{let m=await s(F(i,p));return m===u||await s(F(e,Oe,p))===u?!1:m!==null||g},r=await rs(e),d=r!==null&&r===t.baseSnapshot,c=d;if(!d&&r===null&&t.baseSnapshot===void 0&&await pi(i).then(()=>!0,()=>!1)){c=!0;for(let[p,u]of Object.entries(t.files)){if(n.get(p)!==u)continue;let g=await s(F(i,p));if(g!==null&&g!==u){c=!1;break}}}return async(p,u)=>c&&await o(p,u,d)}function fi(e){return`${Z(e,"file")} Klaudius can't confirm ${e===1?"is":"are"} unedited`}function fo(e){return e.reason==="manifest-mismatch"?"Hash the manifest records: ":"Hash at last install/update:"}function Z(e,t){return`${e} ${t}${e===1?"":"s"}`}function Jl(e,t){let n=e.includes(`\r
136
136
  `)?`\r
137
137
  `:`
@@ -147,11 +147,11 @@ except Exception as e:
147
147
  `,n=await Q();if(!n)return{name:"Python packages installed",status:"fail",detail:"no Python interpreter found (tried python3, python, py -3)",nextAction:"Fix the Python check above first \u2014 the packages live inside that interpreter."};let i=n.command,s=await gi(i[0],[...i.slice(1),"-c",t]);return s.code===0?{name:"Python packages installed",status:"ok",detail:e.join(", ")}:{name:"Python packages installed",status:"fail",detail:(s.stdout||s.stderr).trim().split(`
148
148
  `).pop()??"import failed",nextAction:"Run `npx klaudius@latest install` in this folder."}}async function hc(e,t,n){if(e.SUPABASE_URL&&e.SUPABASE_SERVICE_KEY){let r=await Me({url:e.SUPABASE_URL,serviceKey:e.SUPABASE_SERVICE_KEY});t.push({name:"Supabase credentials",status:r.ok?"ok":"fail",detail:r.ok?"connected":r.message,nextAction:r.ok?void 0:"Run `npx klaudius@latest configure` to fix the URL or key."})}else t.push({name:"Supabase credentials",status:"fail",detail:"missing in .env"});let i=e.DEPLOY_PROVIDER==="cloudflare"?"cloudflare":e.DEPLOY_PROVIDER==="netlify"?"netlify":e.DEPLOY_PROVIDER==="selfhost"?"selfhost":"vercel";if(i==="selfhost"){let r=e.SELFHOST_DEPLOY_TARGET??"",d=e.SELFHOST_URL_TEMPLATE??"",c=[],p=Qe(r);p&&c.push(`SELFHOST_DEPLOY_TARGET: ${p}`);let u=Xe(d);u&&c.push(`SELFHOST_URL_TEMPLATE: ${u}`),t.push({name:"Self-host deploy config",status:c.length===0?"ok":"fail",detail:c.length===0?`target ${r} (SSH reachability tested at first deploy)`:c.join("; "),nextAction:c.length===0?void 0:"Run `npx klaudius@latest configure` and fix the self-host deployment answers."})}else if(i==="cloudflare")if(e.CLOUDFLARE_API_TOKEN&&e.CLOUDFLARE_ACCOUNT_ID){let r=await Fe({token:e.CLOUDFLARE_API_TOKEN,accountId:e.CLOUDFLARE_ACCOUNT_ID});t.push({name:"Cloudflare token + account",status:r.ok?"ok":"fail",detail:r.ok?`valid (${r.projectCount??0} Pages project${r.projectCount===1?"":"s"})`:r.message,nextAction:r.ok?void 0:"Fix the token/account at https://dash.cloudflare.com/profile/api-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Cloudflare token + account",status:"fail",detail:"CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Cloudflare."});else if(i==="netlify")if(e.NETLIFY_AUTH_TOKEN){let r=await Ue({token:e.NETLIFY_AUTH_TOKEN});t.push({name:"Netlify token",status:r.ok?"ok":"fail",detail:r.ok?r.accountSlug?`valid (team: ${r.accountSlug})`:"valid":r.message,nextAction:r.ok?void 0:"Fix the token at https://app.netlify.com/user/applications#personal-access-tokens, then `npx klaudius@latest configure`."})}else t.push({name:"Netlify token",status:"fail",detail:"NETLIFY_AUTH_TOKEN missing in .env",nextAction:"Run `npx klaudius@latest configure` and pick Netlify."});else if(e.VERCEL_TOKEN){let r=await De(e.VERCEL_TOKEN);t.push({name:"Vercel token",status:r.ok?"ok":"fail",detail:r.ok?r.username??"valid":r.message,nextAction:r.ok?void 0:r.kind==="rejected"||r.kind==="scope"?"Create a new token at https://vercel.com/account/settings/tokens (Scope: Full Account, Expiration: No Expiration), then `npx klaudius@latest configure`.":r.kind==="network"?"Couldn't reach Vercel \u2014 check your connection, then re-run `npx klaudius@latest doctor`.":"Vercel's API returned an error \u2014 try again shortly (status.vercel.com), then re-run `npx klaudius@latest doctor`."})}else t.push({name:"Vercel token",status:"fail",detail:"missing in .env"});if(e.GOOGLE_PLACES_API_KEY){let r=await He(e.GOOGLE_PLACES_API_KEY),d=we(e.GOOGLE_PLACES_API_KEY);r.ok&&d.changed?t.push({name:"Google Places API key",status:"fail",detail:"The key works, but the copy stored in .env is not the key we had to send \u2014 "+(d.repairs.length>0?`it contains look-alike characters (${d.repairs.join("; ")}). `:"it contains invisible or stray characters. ")+"The pipeline's scripts read .env directly and will fail on it.",nextAction:"Run `npx klaudius@latest configure` and press Enter through the prompts \u2014 it rewrites .env with the corrected key."}):t.push({name:"Google Places API key",status:r.ok?"ok":"fail",detail:r.ok?"accepted":r.message,nextAction:r.ok?void 0:"Fix the key in https://console.cloud.google.com and `npx klaudius@latest configure`."})}else t.push({name:"Google Places API key",status:"warn",detail:"not set (find skill will fail until you add one)"});t.push(await Ec(e,n)),t.push(...await Pc(e)),t.push(await kc(e,n)),e.STRIPE_SECRET_KEY&&t.push(await wc(e.STRIPE_SECRET_KEY)),t.push(await Ac(e));let s=(e.NOTIFY_CHANNEL??"").toLowerCase(),o=s==="email"||s==="sms"||s==="none"||s==="off"?s:"telegram";if(o==="none"||o==="off")t.push({name:"Notifications",status:"skip",detail:"disabled (NOTIFY_CHANNEL=none)"});else if(o==="email"){let r=e.NOTIFY_TO||e.EMAIL_ADDRESS;t.push({name:"Notifications (email)",status:r&&e.EMAIL_ADDRESS?"ok":"fail",detail:r&&e.EMAIL_ADDRESS?`alerts go to ${r}`:"NOTIFY_CHANNEL=email but no NOTIFY_TO/EMAIL_ADDRESS (or email account) in .env",nextAction:r&&e.EMAIL_ADDRESS?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(o==="sms"){let r=e.NOTIFY_TO||e.TEST_PHONE,d=e.SMS_PROVIDER==="twilio"?!!(e.TWILIO_ACCOUNT_SID&&e.TWILIO_AUTH_TOKEN&&e.TWILIO_PHONE_NUMBER):!0;t.push({name:"Notifications (SMS)",status:r&&d?"ok":"fail",detail:r&&d?`alerts go to ${r} via ${e.SMS_PROVIDER==="twilio"?"Twilio":"iMessage"}`:r?"NOTIFY_CHANNEL=sms with SMS_PROVIDER=twilio but Twilio credentials incomplete":"NOTIFY_CHANNEL=sms but no NOTIFY_TO/TEST_PHONE in .env",nextAction:r&&d?void 0:"Run `npx klaudius@latest configure` and redo the notifications step."})}else if(e.TELEGRAM_BOT_TOKEN&&e.TELEGRAM_CHAT_ID){let r=await Si({botToken:e.TELEGRAM_BOT_TOKEN});t.push({name:"Telegram bot token",status:r.ok?"ok":"fail",detail:r.ok?`bot ${r.botHandle??"ok"} (chat_id not tested)`:r.message,nextAction:r.ok?void 0:"Fix TELEGRAM_BOT_TOKEN in .env (or blank both Telegram lines to disable)."})}else e.TELEGRAM_BOT_TOKEN||e.TELEGRAM_CHAT_ID?t.push({name:"Telegram credentials",status:"warn",detail:"partial config (one of bot token / chat ID set, other missing)",nextAction:"Either set both, or blank both to disable Telegram notifications."}):t.push({name:"Notifications",status:"skip",detail:"not configured (optional)"})}function gc(e){let t=o=>!!o&&/^\d+$/.test(o.trim()),n=wo(e)?!!e.EMAIL_ADDRESS:!!e.EMAIL_ADDRESS&&!!e.EMAIL_PASSWORD&&!!e.EMAIL_SMTP_HOST&&t(e.EMAIL_SMTP_PORT)&&!!e.EMAIL_IMAP_HOST&&t(e.EMAIL_IMAP_PORT),i=(e.OUTREACH_CHANNELS??"").split(",").map(o=>o.trim()),s=e.OUTREACH_ENABLED?.toLowerCase()==="true"&&i.includes("email");return s&&n?"active":s?"incomplete":n?"parked":"unconfigured"}function wo(e){return(e.EMAIL_AUTH??"").trim().toLowerCase()==="oauth-microsoft"}async function yc(e){let t="Email account (Microsoft sign-in)",n=await Q(),s=`Run \`${n?n.command.join(" "):"python3"} scripts/ms_oauth.py login\` from the project folder.`;if(n){let[r,...d]=n.command,c=ic(r,[...d,"scripts/ms_oauth.py","status"],{cwd:e,encoding:"utf-8",timeout:6e4,windowsHide:!0}),p=`${c.stdout??""}${c.stderr??""}`.trim();if(c.status===0){let u=/signed in as (\S+)/.exec(p)?.[1];return{name:t,status:"ok",detail:u?`signed in as ${u} (token refresh works)`:"signed in (token refresh works)"}}return{name:t,status:"fail",detail:p.split(`
149
149
  `)[0]?.slice(0,200)||"Microsoft sign-in is missing or expired",nextAction:s}}return await Ve(ee(e,".ms-token.json"))?{name:t,status:"warn",detail:"token cache present, but no Python found to verify it"}:{name:t,status:"fail",detail:"no Microsoft sign-in found (.ms-token.json missing)",nextAction:s}}async function kc(e,t){let n="Database schema up to date",i=(e.SUPABASE_URL??"").trim(),s=(e.SUPABASE_SERVICE_KEY??"").trim();if(!i||!s)return{name:n,status:"skip",detail:"Supabase credentials not set"};let o="";try{o=await Be(ee(t,"scripts","schema.sql"),"utf-8")}catch{return{name:n,status:"skip",detail:"scripts/schema.sql missing \u2014 run `npx klaudius@latest update`"}}let r=await xt({url:i,serviceKey:s,sql:o});return r.unreachable?{name:n,status:"skip",detail:`Could not verify (${r.unreachable}) \u2014 see the Supabase rows above.`}:r.ok?{name:n,status:"ok",detail:"every table and column the pipeline expects is present"}:{name:n,status:"warn",detail:`missing: ${r.missing.join(", ")} \u2014 this database was provisioned before they were added, so the pipeline files ahead of it will fail on them.`,nextAction:"Run `npx klaudius@latest update` \u2014 it re-applies scripts/schema.sql (safe on an existing database). Or paste scripts/schema.sql into your Supabase SQL editor."}}async function wc(e){let t="Stripe key",n=await ho(e);if(!n.ok)return{name:t,status:"fail",detail:n.message,nextAction:n.kind==="network"?"Couldn't reach Stripe \u2014 check your connection, then re-run `npx klaudius@latest doctor`.":'Create a new restricted key at https://dashboard.stripe.com/apikeys, then tell your agent "connect Stripe" to store it.'};let i=!n.restricted;return{name:t,status:n.livemode&&!i?"ok":"warn",detail:`${n.accountName??"account"} \xB7 ${n.livemode?"live mode":"TEST mode \u2014 links made with this key can't take real payments"}${i?" \xB7 full secret key, which can do anything in the account":""}`,nextAction:i?'Create a restricted key at https://dashboard.stripe.com/apikeys with the permissions listed in .env.example, then tell your agent "connect Stripe".':n.livemode?void 0:`Swap in a live-mode key when you're ready to take real payments: tell your agent "connect Stripe".`}}async function Ac(e){let t="Letter provider (postal outreach)",n=(e.OUTREACH_CHANNELS??"").split(",").map(p=>p.trim().toLowerCase()),i=(e.LETTER_PROVIDER??"").trim().toLowerCase(),s=n.includes("letter");if(!s&&(!i||i==="none"))return{name:t,status:"skip",detail:"not configured (letter isn't an outreach channel)"};if(s&&i!=="pingen"&&i!=="postgrid")return{name:t,status:"fail",detail:"letter is in OUTREACH_CHANNELS but LETTER_PROVIDER isn't set to pingen or postgrid",nextAction:"Run `npx klaudius@latest configure` and redo the letter step."};if(!s)return{name:t,status:"warn",detail:`LETTER_PROVIDER=${i} but letter isn't in OUTREACH_CHANNELS (channel is off)`,nextAction:"Add letter to OUTREACH_CHANNELS/OUTREACH_PRIORITY in .env to enable it."};let o=await pt({provider:i,pingenClientId:e.PINGEN_CLIENT_ID,pingenClientSecret:e.PINGEN_CLIENT_SECRET,pingenOrgId:e.PINGEN_ORG_ID,pingenStaging:(e.PINGEN_USE_STAGING??"").toLowerCase()==="true",postgridApiKey:e.POSTGRID_API_KEY});if(!o.ok)return{name:t,status:"fail",detail:o.message,nextAction:"Fix the letter provider credentials \u2014 `npx klaudius@latest configure`, letter step."};let r=`${i} credentials accepted`+(o.friendlyName?` (${o.friendlyName})`:""),d=(e.SUPABASE_ANON_KEY??"").trim();if(!d)return{name:t,status:"warn",detail:r+", but SUPABASE_ANON_KEY is missing \u2014 claim pages can't be built without it",nextAction:"Add SUPABASE_ANON_KEY to .env (Supabase dashboard \u2192 Settings \u2192 API keys, the publishable key)."};let c=_i(d);if(c&&c!=="anon")return{name:t,status:"fail",detail:r+`, but SUPABASE_ANON_KEY holds a '${c}' key \u2014 shipping it in a claim page would expose the whole database`,nextAction:"Replace SUPABASE_ANON_KEY with the key whose role is 'anon' (Supabase dashboard \u2192 Settings \u2192 API keys)."};if(e.SUPABASE_URL)try{let p=await fetch(`${e.SUPABASE_URL}/rest/v1/clients?select=slug&limit=1`,{headers:{apikey:d,Authorization:`Bearer ${d}`}});if(p.ok){let u=await p.json();if(Array.isArray(u)&&u.length>0)return{name:t,status:"fail",detail:r+", but the anon key can READ the clients table \u2014 a permissive policy is still active and any claim page would expose the CRM",nextAction:'In the Supabase SQL editor run: DROP POLICY IF EXISTS "Allow all for service role" ON clients; then re-run doctor.'}}}catch{}if(i==="postgrid"){let p=["INVOICE_ADDR_STREET","INVOICE_ADDR_ZIP","INVOICE_ADDR_CITY"].filter(u=>!(e[u]??"").trim());if(p.length>0)return{name:t,status:"warn",detail:r+`, but PostGrid needs your return address and .env is missing ${p.join(", ")}`,nextAction:"Ask your AI agent to add your return address to .env (the INVOICE_ADDR_* lines) \u2014 every letter carries it."}}return{name:t,status:"ok",detail:r}}async function Ec(e,t){let n="Email credentials (SMTP + IMAP)",i=gc(e);if(i==="unconfigured")return{name:n,status:"skip",detail:"not configured (email isn't an outreach channel)"};if(wo(e))return i==="parked"?{name:"Email account (Microsoft sign-in)",status:"warn",detail:"Outlook mailbox saved in .env but email isn't an active outreach channel (skipped during setup?)",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."}:i==="incomplete"?{name:"Email account (Microsoft sign-in)",status:"fail",detail:"EMAIL_AUTH=oauth-microsoft but EMAIL_ADDRESS is missing from .env",nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}:yc(t);if(i==="parked")return{name:n,status:"warn",detail:"saved in .env but email isn't an active outreach channel (skipped during setup?) \u2014 never verified",nextAction:"Ask your AI agent to finish email setup \u2014 or run `npx klaudius@latest configure`."};if(i==="incomplete"){let c=["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_SMTP_HOST","EMAIL_SMTP_PORT","EMAIL_IMAP_HOST","EMAIL_IMAP_PORT"].filter(p=>p.endsWith("_PORT")?!e[p]||!/^\d+$/.test(e[p].trim()):!e[p]);return{name:n,status:"fail",detail:`email is an active outreach channel but .env has missing or invalid ${c.join(", ")}`,nextAction:"Run `npx klaudius@latest configure` to re-enter the email details."}}let s=Ie(e),o=s&&s!=="custom"?s:pe(e.EMAIL_SMTP_HOST),r={emailAddress:e.EMAIL_ADDRESS,emailLogin:(e.EMAIL_LOGIN??"").trim()||void 0,emailPassword:e.EMAIL_PASSWORD,emailSmtpHost:e.EMAIL_SMTP_HOST,emailSmtpPort:parseInt(e.EMAIL_SMTP_PORT,10),emailImapHost:e.EMAIL_IMAP_HOST,emailImapPort:parseInt(e.EMAIL_IMAP_PORT,10),usesAccountPassword:o?te[o].usesAccountPassword:void 0,knownProvider:!!o,sentFolder:(e.EMAIL_SENT_FOLDER??"").trim()||"Sent",draftsFolder:(e.EMAIL_DRAFTS_FOLDER??"").trim()||"Drafts"},d=await me(r);if(d.ok){if(d.foldersUnverified)return{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but the mailbox's folder list could not be read, so the Sent and Drafts folder names are unverified`,nextAction:"Re-run doctor; if it persists, check the mailbox's folder names by hand."};let c=Ao(d,{sentKey:"EMAIL_SENT_FOLDER",draftsKey:"EMAIL_DRAFTS_FOLDER",python:(await Q())?.command.join(" ")});return c?{name:n,status:"warn",detail:`authenticated (${e.EMAIL_SMTP_HOST}), but ${c.detail}`,nextAction:c.nextAction}:{name:n,status:"ok",detail:`authenticated (${e.EMAIL_SMTP_HOST})`}}if(d.failureKind==="network")return{name:n,status:"fail",detail:d.message,nextAction:"This looks like a network/host problem, not a password problem \u2014 check EMAIL_SMTP_HOST/EMAIL_IMAP_HOST and your connection, then re-run doctor."};if(o){let c=jt(o,e.EMAIL_SMTP_HOST,e.EMAIL_IMAP_HOST);if(c.length>0){console.log(ne.dim(` (email login rejected \u2014 probing ${te[o].label}'s other regional servers, up to ~10s each\u2026)`));let p=0;for(let g of c){let m=await me({...r,emailSmtpHost:g.smtpHost,emailImapHost:g.imapHost});if(!m.ok&&m.failureKind!=="network"&&p++,m.ok)return{name:n,status:"fail",detail:`${e.EMAIL_SMTP_HOST} rejected the login \u2014 but the SAME login works on ${g.label} (${g.smtpHost}). Wrong regional server in .env.`,nextAction:`Set EMAIL_SMTP_HOST=${g.smtpHost} and EMAIL_IMAP_HOST=${g.imapHost} in .env (or ask your AI agent to).`}}let u=(d.message??"login rejected").split(/\.\s|\n/)[0];return p===0?{name:n,status:"fail",detail:`${u} \u2014 and none of the alternate servers were reachable either; this looks like a network problem`,nextAction:"Check your connection and re-run doctor before touching the password."}:{name:n,status:"fail",detail:`${u} \u2014 tried all ${te[o].label} regional servers; none accepted this login, so the server isn't the problem`,nextAction:o==="zoho"?"Generate a fresh app password (accounts.zoho.com \u2192 Security \u2192 App Passwords) \u2014 and note Zoho's FREE plan has no IMAP/SMTP (Mail Lite ~$1/mo unlocks it). Then `npx klaudius@latest configure`.":o==="titan"?'In Titan webmail check Settings \u2192 "Enable Titan on Other Apps" is ON and Two-Factor Authentication is OFF (Titan has no app passwords \u2014 2FA blocks third-party access entirely). Then `npx klaudius@latest configure`.':"Re-check the mailbox password (2FA accounts need an app password instead), then `npx klaudius@latest configure`."}}}return{name:n,status:"fail",detail:d.message,nextAction:"Run `npx klaudius@latest configure` and re-enter the email details."}}function Ao(e,t){let n=[],i=[],s=[];if(e.sentFolderIssue){let{configured:r,detected:d}=e.sentFolderIssue;n.push(`the server has no "${r}" folder \u2014 sent mail isn't being filed, so follow-ups can't see what was sent to whom`),d?i.push(`${t.sentKey}="${d}"`):s.push(t.sentKey)}if(e.draftsFolderIssue){let{configured:r,detected:d}=e.draftsFolderIssue;n.push(`the server has no "${r}" folder \u2014 saving drafts (manual-approval outreach, /send-invoice) would fail`),d?i.push(`${t.draftsKey}="${d}"`):s.push(t.draftsKey)}if(n.length===0)return;let o=[];if(i.length>0&&o.push(`Set ${i.join(" and ")} in .env (or ask your AI agent to).`),s.length>0){let r=t.python||"python3",d=t.account&&t.account!=="primary"?`${r} scripts/gmail.py folders --account ${t.account}`:`${r} scripts/gmail.py folders`;o.push(`Run \`${d}\` to list this mailbox's folder names, then set ${s.join(" and ")} in .env.`)}return{detail:n.join("; and "),nextAction:o.join(" ")}}async function Pc(e){let t=[];for(let n of $i(e)){let i=`Email mailbox '${n.label}'`;if(!n.valid){t.push({name:i,status:"fail",detail:"label in EMAIL_ACCOUNTS may only use lowercase letters, digits and underscores ('auto' is reserved)",nextAction:"Rename the label in EMAIL_ACCOUNTS and in its EMAIL_ACCOUNT_* keys."});continue}if(n.auth==="oauth-microsoft"){t.push({name:i,status:"fail",detail:"EMAIL_ACCOUNT_*_AUTH=oauth-microsoft isn't supported \u2014 Outlook / Microsoft 365 sign-in works for the primary mailbox only",nextAction:"Make the Outlook account the primary mailbox (plain EMAIL_* block), or use an app-password provider for this one."});continue}if(n.auth!=="password"){t.push({name:i,status:"fail",detail:`unrecognised EMAIL_ACCOUNT_${n.label.toUpperCase()}_AUTH value: ${n.auth}`,nextAction:"Set it to 'password' (or remove the key \u2014 password is the default)."});continue}if(n.missing.length>0){t.push({name:i,status:"fail",detail:`missing or invalid ${n.missing.join(", ")}`,nextAction:"Fill in the mailbox's block in .env \u2014 see the mailbox-accounts section of .env.example."});continue}let s=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_SENT_FOLDER`,o=`EMAIL_ACCOUNT_${n.label.toUpperCase()}_DRAFTS_FOLDER`,r=pe(n.smtpHost),d=await me({emailAddress:n.address,emailLogin:n.login,emailPassword:n.password,emailSmtpHost:n.smtpHost,emailSmtpPort:n.smtpPort,emailImapHost:n.imapHost,emailImapPort:n.imapPort,usesAccountPassword:r?te[r].usesAccountPassword:void 0,knownProvider:!!r,errorHint:{addressSetting:`EMAIL_ACCOUNT_${n.label.toUpperCase()}_ADDRESS`,loginSetting:`EMAIL_ACCOUNT_${n.label.toUpperCase()}_LOGIN`},sentFolder:(e[s]??"").trim()||"Sent",draftsFolder:(e[o]??"").trim()||"Drafts"});if(d.ok){let c=Ao(d,{sentKey:s,draftsKey:o,account:n.label,python:(await Q())?.command.join(" ")});c?t.push({name:i,status:"warn",detail:`authenticated (${n.smtpHost}), but ${c.detail}`,nextAction:c.nextAction}):t.push({name:i,status:"ok",detail:`authenticated (${n.smtpHost})`})}else t.push({name:i,status:"fail",detail:d.message,nextAction:d.failureKind==="network"?"Looks like a network/host problem \u2014 check this mailbox's SMTP/IMAP hosts in .env.":"Check this mailbox's password and hosts in .env (regional providers often need a different server)."})}return t}async function Sc(e){let t=e==="codex"?"codex":"claude",n=e==="codex"?"Codex CLI on PATH":"Claude Code CLI on PATH",i=e==="codex"?"Install Codex with `npm install -g @openai/codex` (or your preferred installer).":"Install Claude Code with `npm install -g @anthropic-ai/claude-code`.",s=await gi(t,["--version"],process.platform==="win32");if(s.code===0){let o=(s.stdout||s.stderr).trim().split(`
150
- `)[0]??"";return e==="codex"&&bc(o)?{name:n,status:"warn",detail:`${o} \u2014 older than ${hi}`,nextAction:`Update the Codex your terminal runs (\`npm install -g @openai/codex@latest\`): versions before ${hi} can't use GPT-6 Sol, Codex's default model.`}:{name:n,status:"ok",detail:o}}return{name:n,status:"warn",detail:"not found",nextAction:i}}var hi="0.155.0";function bc(e){let t=e.match(/(\d+)\.(\d+)\.(\d+)(-\S+)?/);if(!t)return!1;let n=t.slice(1,4).map(Number),i=hi.split(".").map(Number);for(let s=0;s<3;s++)if(n[s]!==i[s])return n[s]<i[s];return t[4]!==void 0}function gi(e,t,n=!1){return new Promise(i=>{let s=n?go([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):go(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",d=>{o+=d.toString()}),s.stderr?.on("data",d=>{r+=d.toString()}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",()=>i({code:1,stdout:o,stderr:r}))})}import{existsSync as _c}from"fs";import{spawnSync as Tc}from"child_process";import{join as Ic,resolve as Cc}from"path";import oe from"picocolors";async function Eo(e){let t=Cc(e.projectRoot??process.cwd()),n=Ic(t,"scripts","whatsapp.mjs");_c(n)||(console.error(oe.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(oe.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(oe.dim(`Looked for: ${n}`)),process.exit(1));let i=(e.label??"primary").trim(),s=i.replace(/[^A-Za-z0-9_-]/g,"");s||(console.error(oe.red(`Invalid label '${i}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),s!==i&&console.error(oe.yellow(`Note: cleaned label '${i}' \u2192 '${s}' (filename-safe characters only).`)),console.log(oe.cyan(`Pairing WhatsApp account '${s}'...`)),console.log(oe.dim(`If a daemon is already running for this account, it will be stopped automatically before the QR prompt. After the pair completes, the next /outreach send for this account will respawn the daemon with the new auth.
150
+ `)[0]??"";return e==="codex"&&bc(o)?{name:n,status:"warn",detail:`${o} \u2014 older than ${hi}`,nextAction:`Update the Codex your terminal runs (\`npm install -g @openai/codex@latest\`, or however you installed it): from ${hi}, Codex starts on GPT-6.1 Sol; older versions can start on GPT-6 Astra, which uses up your limits about five times as fast.`}:{name:n,status:"ok",detail:o}}return{name:n,status:"warn",detail:"not found",nextAction:i}}var hi="0.159.1";function bc(e){let t=e.match(/(\d+)\.(\d+)\.(\d+)(-\S+)?/);if(!t)return!1;let n=t.slice(1,4).map(Number),i=hi.split(".").map(Number);for(let s=0;s<3;s++)if(n[s]!==i[s])return n[s]<i[s];return t[4]!==void 0}function gi(e,t,n=!1){return new Promise(i=>{let s=n?go([e,...t].join(" "),{stdio:["ignore","pipe","pipe"],shell:!0}):go(e,t,{stdio:["ignore","pipe","pipe"],shell:!1}),o="",r="";s.stdout?.on("data",d=>{o+=d.toString()}),s.stderr?.on("data",d=>{r+=d.toString()}),s.on("close",d=>i({code:d??1,stdout:o,stderr:r})),s.on("error",()=>i({code:1,stdout:o,stderr:r}))})}import{existsSync as _c}from"fs";import{spawnSync as Tc}from"child_process";import{join as Ic,resolve as Cc}from"path";import oe from"picocolors";async function Eo(e){let t=Cc(e.projectRoot??process.cwd()),n=Ic(t,"scripts","whatsapp.mjs");_c(n)||(console.error(oe.red("Couldn't find scripts/whatsapp.mjs in this directory.")),console.error(oe.dim("Run this command from the root of a Klaudius project (the directory created by `npx klaudius@latest init`).")),console.error(oe.dim(`Looked for: ${n}`)),process.exit(1));let i=(e.label??"primary").trim(),s=i.replace(/[^A-Za-z0-9_-]/g,"");s||(console.error(oe.red(`Invalid label '${i}'. Use letters, digits, underscore, or hyphen only.`)),process.exit(1)),s!==i&&console.error(oe.yellow(`Note: cleaned label '${i}' \u2192 '${s}' (filename-safe characters only).`)),console.log(oe.cyan(`Pairing WhatsApp account '${s}'...`)),console.log(oe.dim(`If a daemon is already running for this account, it will be stopped automatically before the QR prompt. After the pair completes, the next /outreach send for this account will respawn the daemon with the new auth.
151
151
  `));let o=Tc(process.execPath,[n,"pair","--account",s],{cwd:t,stdio:"inherit"});if(o.status===0){console.log(oe.green(`Paired '${s}'.`)),console.log(oe.dim(`
152
152
  If you haven't already, add '${s}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
153
153
  WHATSAPP_ACCOUNTS=primary,${s}
154
- (Skip this if '${s}' is already there or you set it via the init wizard.)`));return}o.error?console.error(oe.red(`Pair failed: ${o.error.message}`)):(console.error(oe.red(`Pair did not complete (exit ${o.status??"signalled"}). Common causes:`)),console.error(oe.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(oe.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(oe.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${s}/daemon.log`))),process.exit(o.status??1)}import{spawnSync as Et,spawn as Rc}from"child_process";import{existsSync as Ut,mkdirSync as vc,readdirSync as Oc,rmSync as _o,mkdtempSync as To}from"fs";import{homedir as yi,tmpdir as Io}from"os";import{join as ue}from"path";import be from"picocolors";var xc=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function Po(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function Co(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&Ht()&&vo();let t=Nc();if(t&&!e.reinstall&&!e.from){bo(),console.log(be.green("Opened the Klaudius app.")),So();return}let n=await Mc(e.from);console.log(be.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Dc(n):Fc(n),bo(),console.log(be.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),So()}function So(){process.platform==="darwin"?console.log(be.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(be.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function Tn(){return ue(yi(),"Applications","Klaudius.app")}function Ro(){return process.env.LOCALAPPDATA??ue(yi(),"AppData","Local")}function Lc(){return ue(Ro(),"Klaudius")}function Ht(){let e=ue(Ro(),"Programs");try{for(let t of Oc(e)){if(!/laudius/i.test(t))continue;let n=ue(e,t,"Klaudius.exe");if(Ut(n))return n}}catch{}return null}function Nc(){return process.platform==="darwin"?Ut(Tn()):Ht()!==null}async function $c(){try{let{readFileSync:e}=await import("fs");return e(ue(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m)?.[2]?.trim()??null}catch{return null}}async function Mc(e){if(e)return Ut(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await $c();t||(console.error("Couldn't find your license key."),console.error("Run this from inside your Klaudius folder (the one `npx klaudius init` created)."),process.exit(1));let n=`${xc}?file=${encodeURIComponent(Po())}`,i=ue(To(ue(Io(),"klaudius-app-")),Po());console.log(be.cyan("Downloading the Klaudius app\u2026"));try{let s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.37.4"}});if(!s.ok){let d=`HTTP ${s.status}`;try{let c=await s.json();c.reason&&(d=c.reason)}catch{}throw new Error(d)}let o=Buffer.from(await s.arrayBuffer()),{writeFileSync:r}=await import("fs");return r(i,o),i}catch(s){console.error(`Couldn't download the app (${s.message}). If you're offline, try again later; otherwise email hello@klaudius.dev.`),process.exit(1)}}function Dc(e){let t=ue(yi(),"Applications");vc(t,{recursive:!0});let n=To(ue(Io(),"klaudius-app-x-")),i=Et("ditto",["-xk",e,n],{stdio:"pipe"});i.status!==0&&(console.error(`Couldn't extract the app: ${i.stderr?.toString().trim()}`),process.exit(1));let s=ue(n,"Klaudius.app");Ut(s)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),_o(Tn(),{recursive:!0,force:!0});let o=Et("mv",[s,Tn()],{stdio:"pipe"});o.status!==0&&(console.error(`Couldn't install to ~/Applications: ${o.stderr?.toString().trim()}`),process.exit(1))}function Fc(e){/\.exe$/i.test(e)||(console.error("Expected the Klaudius installer (.exe). A zip can't be installed here \u2014 an unzipped copy can never update itself."),process.exit(1));let t=Et(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!Uc(6e4)){let i=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,s=Ht();if(s&&Oo(s)){console.log(be.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(be.dim("Open it from the Start Menu if it doesn't appear shortly."));return}console.error(`Klaudius didn't finish installing (${i}).`),console.error("Check your Start Menu for Klaudius \u2014 it may still be finishing."),console.error("If it isn't there, email hello@klaudius.dev."),process.exit(1)}vo()}function Uc(e){let t=Date.now()+e;for(;;){let n=Ht();if(n)return n;if(Date.now()>=t)return null;Hc(500)}}function Hc(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function vo(){let e=Lc();if(!Ut(ue(e,"app","Klaudius.exe")))return;console.log(be.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
154
+ (Skip this if '${s}' is already there or you set it via the init wizard.)`));return}o.error?console.error(oe.red(`Pair failed: ${o.error.message}`)):(console.error(oe.red(`Pair did not complete (exit ${o.status??"signalled"}). Common causes:`)),console.error(oe.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(oe.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(oe.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${s}/daemon.log`))),process.exit(o.status??1)}import{spawnSync as Et,spawn as Rc}from"child_process";import{existsSync as Ut,mkdirSync as vc,readdirSync as Oc,rmSync as _o,mkdtempSync as To}from"fs";import{homedir as yi,tmpdir as Io}from"os";import{join as ue}from"path";import be from"picocolors";var xc=process.env.KLAUDIUS_APP_BASE_URL??"https://klaudius.dev/api/app/download";function Po(){return process.platform==="darwin"?process.arch==="arm64"?"Klaudius-arm64-mac.zip":"Klaudius-x64-mac.zip":"Klaudius-x64-win-setup.exe"}async function Co(e){process.platform!=="darwin"&&process.platform!=="win32"&&(console.error("The Klaudius desktop app currently supports macOS and Windows."),process.exit(1)),process.platform==="win32"&&Ht()&&vo();let t=Nc();if(t&&!e.reinstall&&!e.from){bo(),console.log(be.green("Opened the Klaudius app.")),So();return}let n=await Mc(e.from);console.log(be.cyan(t?"Updating the Klaudius app\u2026":"Installing the Klaudius app\u2026")),process.platform==="darwin"?Dc(n):Fc(n),bo(),console.log(be.green(t?"Updated and opened the Klaudius app.":"Installed and opened the Klaudius app.")),So()}function So(){process.platform==="darwin"?console.log(be.dim("From now on: open it from Spotlight (\u2318-Space, type \u201CKlaudius\u201D) or Launchpad \u2014 no terminal needed.")):console.log(be.dim("From now on: open it from the Start Menu or the desktop shortcut \u2014 no terminal needed."))}function Tn(){return ue(yi(),"Applications","Klaudius.app")}function Ro(){return process.env.LOCALAPPDATA??ue(yi(),"AppData","Local")}function Lc(){return ue(Ro(),"Klaudius")}function Ht(){let e=ue(Ro(),"Programs");try{for(let t of Oc(e)){if(!/laudius/i.test(t))continue;let n=ue(e,t,"Klaudius.exe");if(Ut(n))return n}}catch{}return null}function Nc(){return process.platform==="darwin"?Ut(Tn()):Ht()!==null}async function $c(){try{let{readFileSync:e}=await import("fs");return e(ue(process.cwd(),".env"),"utf-8").match(/^KLAUDIUS_LICENSE_KEY=("?)(.+?)\1\s*$/m)?.[2]?.trim()??null}catch{return null}}async function Mc(e){if(e)return Ut(e)||(console.error(`Archive not found: ${e}`),process.exit(1)),e;let t=await $c();t||(console.error("Couldn't find your license key."),console.error("Run this from inside your Klaudius folder (the one `npx klaudius init` created)."),process.exit(1));let n=`${xc}?file=${encodeURIComponent(Po())}`,i=ue(To(ue(Io(),"klaudius-app-")),Po());console.log(be.cyan("Downloading the Klaudius app\u2026"));try{let s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,"x-klaudius-cli-version":"0.37.5"}});if(!s.ok){let d=`HTTP ${s.status}`;try{let c=await s.json();c.reason&&(d=c.reason)}catch{}throw new Error(d)}let o=Buffer.from(await s.arrayBuffer()),{writeFileSync:r}=await import("fs");return r(i,o),i}catch(s){console.error(`Couldn't download the app (${s.message}). If you're offline, try again later; otherwise email hello@klaudius.dev.`),process.exit(1)}}function Dc(e){let t=ue(yi(),"Applications");vc(t,{recursive:!0});let n=To(ue(Io(),"klaudius-app-x-")),i=Et("ditto",["-xk",e,n],{stdio:"pipe"});i.status!==0&&(console.error(`Couldn't extract the app: ${i.stderr?.toString().trim()}`),process.exit(1));let s=ue(n,"Klaudius.app");Ut(s)||(console.error("Archive didn't contain Klaudius.app \u2014 is this the right file?"),process.exit(1)),_o(Tn(),{recursive:!0,force:!0});let o=Et("mv",[s,Tn()],{stdio:"pipe"});o.status!==0&&(console.error(`Couldn't install to ~/Applications: ${o.stderr?.toString().trim()}`),process.exit(1))}function Fc(e){/\.exe$/i.test(e)||(console.error("Expected the Klaudius installer (.exe). A zip can't be installed here \u2014 an unzipped copy can never update itself."),process.exit(1));let t=Et(e,["/S"],{stdio:"pipe",windowsHide:!0});if(!Uc(6e4)){let i=t.stderr?.toString().trim()||t.error?.message||`exit ${t.status??"unknown"}`,s=Ht();if(s&&Oo(s)){console.log(be.yellow("Klaudius is starting up \u2014 the installer is still finishing off.")),console.log(be.dim("Open it from the Start Menu if it doesn't appear shortly."));return}console.error(`Klaudius didn't finish installing (${i}).`),console.error("Check your Start Menu for Klaudius \u2014 it may still be finishing."),console.error("If it isn't there, email hello@klaudius.dev."),process.exit(1)}vo()}function Uc(e){let t=Date.now()+e;for(;;){let n=Ht();if(n)return n;if(Date.now()>=t)return null;Hc(500)}}function Hc(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function vo(){let e=Lc();if(!Ut(ue(e,"app","Klaudius.exe")))return;console.log(be.dim("Removing an older copy of the app that couldn't update itself\u2026"));let t=`
155
155
  $legacy = '${e.replace(/'/g,"''")}'
156
156
  # Compare against the directory PLUS its separator, so a sibling folder whose
157
157
  # name merely starts with the same text ("Klaudius Desktop") is never matched.
@@ -165,4 +165,4 @@ foreach ($dir in @([Environment]::GetFolderPath('Programs'), [Environment]::GetF
165
165
  Remove-Item -LiteralPath $lnk -Force -ErrorAction SilentlyContinue
166
166
  }
167
167
  }
168
- }`;Et("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{_o(e,{recursive:!0,force:!0})}catch{console.log(be.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function bo(){if(process.platform==="darwin"){Et("open",["-a",Tn()],{stdio:"pipe"});return}let e=Ht();if(!e||Oo(e))return;Rc(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function Oo(e){let t=Et("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(i=>i.trim().toLowerCase()===n)}function xo(e){return new Promise(t=>{if(e.destroyed||e.writableEnded||!e.writable){t();return}let n=()=>t();e.once("error",n);try{e.write("",n)}catch{n()}})}async function ki(e=0){await Promise.all([xo(process.stdout),xo(process.stderr)]),process.exit(e)}import{spawnSync as jc}from"child_process";var wi="--use-system-ca";function Lo(){let e=process.env.NODE_OPTIONS??"";if(e.includes(wi)||!Ae().ok)return;let n=e?`${e} ${wi}`:wi,i=jc(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}Lo();var Gc="0.37.4",ye=new Kc;ye.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Gc);ye.command("preflight").description("Check this machine can run Klaudius (Node, Python, pip, npm, network) \u2014 no project or license needed. Safe for an AI assistant to run, fix, and re-run before init.").action(async()=>{try{await Li({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});ye.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").option("--answers <file>","Non-interactive setup: read answers from a JSON or dotenv-format file (same keys as .env). On a failed check, exits with code 2 and an INIT-BLOCKED line instead of reopening the wizard.").action(async(e,t)=>{try{await $s({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await ki(process.exitCode??0)}catch(n){console.error("init failed:",n.message),process.exit(1)}});ye.command("install").description("Re-run dependency installers against an already-scaffolded project (npm, pip, playwright, patchright)").argument("[target]","Project directory (defaults to current directory)").action(async e=>{try{await Ds({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});ye.command("configure").description("Re-run the setup wizard with current values pre-filled").option("--answers <file>","Non-interactive: read new answers from a JSON or dotenv-format file (same keys as .env) \u2014 a delta, holding only the settings that changed. Keys in the file replace what .env holds, a key present but empty clears it, and every key it leaves out is KEPT (unlike `init --answers`, where a setting the form owns reverts to its default when left out). Checks run before anything is written; on a failed check nothing is changed and it exits 2 with an INIT-BLOCKED line. On success it prints CONFIGURE-DONE sections=<changed> checked=<sections whose check ran>.").option("--sections <list>","Only with --answers: comma-separated sections whose credential checks should run (supabase, vercel, cloudflare, netlify, selfhost, google-places, email, sms, letter, notifications). Default: every section the answers file changes.").action(async e=>{try{await Qs({answers:e.answers,sections:e.sections}),await ki(process.exitCode??0)}catch(t){console.error("configure failed:",t.message),process.exit(1)}});ye.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").option("--check","Report whether an update is available without changing anything").action(async e=>{try{await mo({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});ye.command("resolve").description("Record your decision on one conflict `update` staged (the /resolve-conflicts skill runs this for you)").argument("[file]","The conflicted file, as named in .klaudius/conflicts.md").allowExcessArguments(!1).option("--keep-mine","Keep your version").option("--take-new","Use the new version (yours is backed up first)").option("--check-merge <draft>","Show what a merged draft keeps from each side, changing nothing").option("--merge <draft>","Use a merged draft (yours is backed up first)").option("--auto-merge","Merge automatically when your edits and the update's don't overlap (yours is backed up first)").option("--restore","Bring back a file you deleted, in its new version").option("--keep-deleted","Keep a file you deleted out for good").option("--delete","Delete a file the new version dropped (backed up first)").option("--finish","Clear the update staging once nothing is waiting").action(async(e,t)=>{try{process.exitCode=await uo(co(e,t))}catch(n){console.error("resolve failed:",n.message),process.exit(1)}});ye.command("doctor").description("Diagnose a broken install \u2014 env versions, files, installed deps, credentials").option("--offline","Skip credential validations that require network calls").action(async e=>{try{await ko({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});ye.command("app").description("Install (first run) and open the Klaudius desktop app").option("--from <archive>","Install from a local app archive (testing)").option("--reinstall","Reinstall even if already installed").action(async e=>{try{await Co({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});ye.command("pair-whatsapp").description("Link a WhatsApp account to this project (or re-pair if it logged out)").option("--label <name>","Account label (default: primary). Should match a value in WHATSAPP_ACCOUNTS.","primary").action(async e=>{try{await Eo({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ye.parse(process.argv);
168
+ }`;Et("powershell.exe",["-NoProfile","-Command",t],{stdio:"pipe",windowsHide:!0});try{_o(e,{recursive:!0,force:!0})}catch{console.log(be.dim(`Couldn't fully remove ${e} \u2014 you can delete that folder yourself.`))}}function bo(){if(process.platform==="darwin"){Et("open",["-a",Tn()],{stdio:"pipe"});return}let e=Ht();if(!e||Oo(e))return;Rc(e,[],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function Oo(e){let t=Et("powershell.exe",["-NoProfile","-Command","Get-Process -Name Klaudius -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }"],{stdio:"pipe",windowsHide:!0});if(t.status!==0)return!1;let n=e.toLowerCase();return t.stdout?.toString().split(/\r?\n/).some(i=>i.trim().toLowerCase()===n)}function xo(e){return new Promise(t=>{if(e.destroyed||e.writableEnded||!e.writable){t();return}let n=()=>t();e.once("error",n);try{e.write("",n)}catch{n()}})}async function ki(e=0){await Promise.all([xo(process.stdout),xo(process.stderr)]),process.exit(e)}import{spawnSync as jc}from"child_process";var wi="--use-system-ca";function Lo(){let e=process.env.NODE_OPTIONS??"";if(e.includes(wi)||!Ae().ok)return;let n=e?`${e} ${wi}`:wi,i=jc(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});i.signal&&(process.kill(process.pid,i.signal),process.exit(1)),process.exit(i.status??1)}Lo();var Gc="0.37.5",ye=new Kc;ye.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(Gc);ye.command("preflight").description("Check this machine can run Klaudius (Node, Python, pip, npm, network) \u2014 no project or license needed. Safe for an AI assistant to run, fix, and re-run before init.").action(async()=>{try{await Li({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});ye.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").option("--answers <file>","Non-interactive setup: read answers from a JSON or dotenv-format file (same keys as .env). On a failed check, exits with code 2 and an INIT-BLOCKED line instead of reopening the wizard.").action(async(e,t)=>{try{await $s({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema,answers:t.answers}),await ki(process.exitCode??0)}catch(n){console.error("init failed:",n.message),process.exit(1)}});ye.command("install").description("Re-run dependency installers against an already-scaffolded project (npm, pip, playwright, patchright)").argument("[target]","Project directory (defaults to current directory)").action(async e=>{try{await Ds({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});ye.command("configure").description("Re-run the setup wizard with current values pre-filled").option("--answers <file>","Non-interactive: read new answers from a JSON or dotenv-format file (same keys as .env) \u2014 a delta, holding only the settings that changed. Keys in the file replace what .env holds, a key present but empty clears it, and every key it leaves out is KEPT (unlike `init --answers`, where a setting the form owns reverts to its default when left out). Checks run before anything is written; on a failed check nothing is changed and it exits 2 with an INIT-BLOCKED line. On success it prints CONFIGURE-DONE sections=<changed> checked=<sections whose check ran>.").option("--sections <list>","Only with --answers: comma-separated sections whose credential checks should run (supabase, vercel, cloudflare, netlify, selfhost, google-places, email, sms, letter, notifications). Default: every section the answers file changes.").action(async e=>{try{await Qs({answers:e.answers,sections:e.sections}),await ki(process.exitCode??0)}catch(t){console.error("configure failed:",t.message),process.exit(1)}});ye.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").option("--check","Report whether an update is available without changing anything").action(async e=>{try{await mo({check:e.check})}catch(t){console.error("update failed:",t.message),process.exit(1)}});ye.command("resolve").description("Record your decision on one conflict `update` staged (the /resolve-conflicts skill runs this for you)").argument("[file]","The conflicted file, as named in .klaudius/conflicts.md").allowExcessArguments(!1).option("--keep-mine","Keep your version").option("--take-new","Use the new version (yours is backed up first)").option("--check-merge <draft>","Show what a merged draft keeps from each side, changing nothing").option("--merge <draft>","Use a merged draft (yours is backed up first)").option("--auto-merge","Merge automatically when your edits and the update's don't overlap (yours is backed up first)").option("--restore","Bring back a file you deleted, in its new version").option("--keep-deleted","Keep a file you deleted out for good").option("--delete","Delete a file the new version dropped (backed up first)").option("--finish","Clear the update staging once nothing is waiting").action(async(e,t)=>{try{process.exitCode=await uo(co(e,t))}catch(n){console.error("resolve failed:",n.message),process.exit(1)}});ye.command("doctor").description("Diagnose a broken install \u2014 env versions, files, installed deps, credentials").option("--offline","Skip credential validations that require network calls").action(async e=>{try{await ko({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});ye.command("app").description("Install (first run) and open the Klaudius desktop app").option("--from <archive>","Install from a local app archive (testing)").option("--reinstall","Reinstall even if already installed").action(async e=>{try{await Co({from:e.from,reinstall:!!e.reinstall})}catch(t){console.error("app failed:",t.message),process.exit(1)}});ye.command("pair-whatsapp").description("Link a WhatsApp account to this project (or re-pair if it logged out)").option("--label <name>","Account label (default: primary). Should match a value in WHATSAPP_ACCOUNTS.","primary").action(async e=>{try{await Eo({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});ye.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klaudius",
3
- "version": "0.37.4",
3
+ "version": "0.37.5",
4
4
  "description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code or Codex (find, build, deploy, outreach end-to-end).",
5
5
  "homepage": "https://klaudius.dev",
6
6
  "bugs": {