klaudius 0.24.1 → 0.24.2

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 (3) hide show
  1. package/README.md +25 -17
  2. package/dist/bin.js +5 -5
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # Klaudius
2
2
 
3
- > An autonomous web agency, running on Claude Code. Find, build, deploy, outreach — end-to-end.
3
+ > An autonomous web agency, run by AI. It finds local businesses that need a website, builds each one a bespoke site, deploys it, and pitches the owner — end-to-end.
4
4
 
5
- Klaudius is a Claude Code-driven pipeline for solo developers running a small web design business. Give it a region. It finds local businesses without websites, gathers their content from public sources, builds them bespoke sites, deploys them, and runs the outreach. You direct from inside Claude Code; Klaudius does the work.
5
+ Klaudius is a complete web-agency pipeline driven by Claude Code or Codex. Give it a region and the AI does the work: it finds local businesses with no website — or a dead one, or nothing but a booking-platform page — gathers their content from public sources, builds each one a bespoke Next.js website, deploys it, and sends the outreach and follow-ups that turn a build into a paying client. You direct everything in plain English from inside your agent.
6
6
 
7
- One command installs the full pipeline into your project a Next.js trade-site template, design-system generation skills, lead-sourcing scripts, deployment automation, a Supabase pipeline schema, and email/SMS outreach scaffolding.
7
+ You don't need to be able to code to run it. Non-technical operators run Klaudius as a turnkey business; web designers and agencies run it as a production multiplier. It's region-agnostic — point it at any populated country and it works in the local language.
8
8
 
9
- > **Note:** this npm package contains only the CLI binary. The actual project source — Claude Code skills, Python scripts, Next.js trade-site template, Supabase schema — is delivered to your project directory by the `init` command, after your licence key is validated against [klaudius.dev](https://klaudius.dev). Running `npm pack klaudius` or `npm install klaudius` directly will not give you the project source.
9
+ > **Note:** this npm package contains only the CLI binary. The actual project source — the agent skills, scripts, site template, and database schema — is delivered to your project directory by the `init` command, after your licence key is validated against [klaudius.dev](https://klaudius.dev). Running `npm pack klaudius` or `npm install klaudius` directly will not give you the project source.
10
10
 
11
11
  ## Quick start
12
12
 
@@ -21,13 +21,16 @@ npx klaudius init my-agency
21
21
 
22
22
  # 3. Operate the pipeline from inside your agent:
23
23
  cd my-agency
24
- claude
24
+ claude # or: codex
25
+ > Run the pipeline for New Jersey.
25
26
  ```
26
27
 
27
- The setup command installs Node and Python into your user space (no admin password needed), skips anything you already have at a good version, and finishes with a preflight check that points you to `init`. The `init` wizard prompts for credentials (Supabase, Vercel, your email and SMS provider, and a few API keys), scaffolds the full project, applies the database schema, and installs dependencies. After that you operate the pipeline from inside Claude Code or Codex.
28
+ The setup command installs Node and Python into your user space (no admin password needed), skips anything you already have at a good version, and finishes with a preflight check that points you to `init`. The `init` wizard walks you through everything your pricing, country and language, outreach channels, deployment host, and the credentials each one needs — then scaffolds the full project, applies the database schema, and installs dependencies. After that you operate the pipeline from inside Claude Code or Codex.
28
29
 
29
30
  ## Commands
30
31
 
32
+ `init` and `configure` are the two you type yourself — both open an interactive wizard, so they need a real terminal and your agent can't drive them. The rest you never need to memorise: ask your agent in plain English ("update Klaudius", "check my install is healthy") and it runs them for you. Most `configure`-shaped requests don't need the wizard at all — "change my pricing to $899" or "switch me to Cloudflare Pages" is just an `.env` edit your agent makes directly.
33
+
31
34
  ```bash
32
35
  npx klaudius preflight # Re-check this machine is ready (Node, Python, pip, npm, network; on Windows also that PowerShell can run npx)
33
36
  npx klaudius init [target] # Scaffold a fresh project
@@ -38,20 +41,25 @@ npx klaudius doctor # Diagnose a broken install (env, files, deps, cred
38
41
 
39
42
  ## What gets scaffolded
40
43
 
41
- - **Next.js trade-site template** — a customisable React/Tailwind starting point each generated client site builds from
42
- - **Claude Code skills** `find`, `gather`, `build`, `deploy`, `outreach`, `follow-up`, `qa-fix`, plus a fresh-eyes `qa-reviewer` agent
43
- - **Python scripts** — Gmail and IMAP wrappers, iMessage and Twilio adapters, Supabase database helpers, public-data gathering scripts
44
- - **Supabase schema** — pre-built Postgres schema for tracking project candidates, active client work, and follow-up scheduling
45
- - **`CLAUDE.md` operating manual** the playbook Claude Code reads when you ask it to run the pipeline
44
+ - **Pipeline skills for your agent** — `find`, `gather`, `build`, `deploy`, `outreach`, `follow-up`, `warm-leads`, plus a fresh-eyes `qa-reviewer` agent that independently checks every site before it deploys
45
+ - **Upsell skills** that retrofit extras onto a client's live site when they convert — a self-serve CMS, a bespoke booking system, go-live SEO, a live auto-updating Google-rating badge, PDF invoicing
46
+ - **A Next.js/Tailwind site template** — the customisable starting point each bespoke client build works from
47
+ - **Python and Node scripts** — email senders and readers, adapters for the other outreach channels, database helpers, public-data gathering, deliverability checks
48
+ - **A pre-built database schema** for the pipeline's CRM candidates, statuses, outreach threads, follow-up state
49
+ - **The operating manual your agent reads** (`CLAUDE.md` for Claude Code installs, `AGENTS.md` for Codex) plus operator docs (`DOCS.html`, `operator-guide.html`) for you
50
+
51
+ ## Updates
52
+
53
+ Lifetime updates are included with every licence. Ask your agent to "update Klaudius" and it pulls the latest skills, scripts, and template files, applies everything that's safe to apply, and walks you through anything that needs a decision from you — your own edits are never silently overwritten.
46
54
 
47
55
  ## Prerequisites
48
56
 
49
57
  - Node 22.15+ and Python 3.10+ (the setup command above installs both if missing)
50
- - A Claude Code subscription (Pro or Max plan)
51
- - A Supabase project (free tier is fine to start)
52
- - A Vercel team (Hobby tier is fine to start)
53
- - An email and SMS provider — Gmail, Outlook, IONOS, Fastmail, Zoho, or Titan (123 Reg / Hostinger / Name.com mail) for email; iMessage on macOS or Twilio for SMS
54
- - API keys for any public-data sources you want to gather from
58
+ - An AI coding agent subscription: Claude Code (Anthropic Pro or Max plan) or Codex (OpenAI — ChatGPT Plus or Pro)
59
+ - A free-tier account with the cloud database the pipeline's CRM runs on (the setup wizard names it and walks you through creating the project)
60
+ - Somewhere to deploy the sites: Vercel (the default), Cloudflare Pages, or Netlify — free tiers are fine to start — or any server of your own
61
+ - An email account to send outreach from — Gmail, Outlook / Microsoft 365, IONOS, Fastmail, Zoho, or Titan (123 Reg / Hostinger / Name.com mail) all work. Klaudius supports further outreach channels beyond email you opt in and set the priority order during the wizard
62
+ - API keys for the public-data sources you want to gather from
55
63
 
56
64
  Full prerequisites and setup notes at [klaudius.dev](https://klaudius.dev).
57
65
 
@@ -61,7 +69,7 @@ One-time licence per purchase, granted to a single individual or single entity,
61
69
 
62
70
  ## Support
63
71
 
64
- Email [hello@klaudius.dev](mailto:hello@klaudius.dev).
72
+ Email [hello@klaudius.dev](mailto:hello@klaudius.dev) — you get a detailed, considered reply within 24 hours, usually faster.
65
73
 
66
74
  ## About
67
75
 
package/dist/bin.js CHANGED
@@ -12,8 +12,8 @@ Please share that file so we can trace what happened.`);return s}var st="claude-
12
12
  `)+`
13
13
  `}function ms(e){return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\"/g,'"').replace(/\\\$/g,"$").replace(/\\`/g,"`"):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function F(e){let t={};for(let n of e.split(`
14
14
  `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let a=s.slice(0,o).trim(),l=ms(s.slice(o+1).trim());t[a]=l}return t}function Dt(e){let t=c=>{let d=e[c];if(!d)return;let u=parseInt(d,10);return isNaN(u)?void 0:u},n=e.SMS_PROVIDER,s=c=>c==="email"||c==="sms"||c==="whatsapp",o=e.OUTREACH_CHANNELS?.split(",").map(c=>c.trim()).filter(s),a=e.OUTREACH_PRIORITY?.split(",").map(c=>c.trim()).filter(s),l=e.WHATSAPP_ACCOUNTS?.split(",").map(c=>c.trim()).filter(c=>c.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Ot(e.AI_AGENT)??st,country:e.OPERATOR_COUNTRY||void 0,countryCode:e.OPERATOR_COUNTRY_CODE||void 0,language:e.OPERATOR_LANGUAGE||void 0,languageCode:e.OPERATOR_LANGUAGE_CODE||void 0,pipelineModes:e.PIPELINE_MODES?e.PIPELINE_MODES.split(",").map(c=>c.trim().toLowerCase()).filter(Boolean):void 0,pricing:e.PRICING,pricingTerms:e.PRICING_TERMS,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?e.OUTREACH_ENABLED.toLowerCase()==="true":void 0,name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:o&&o.length>0?o:void 0,outreachPriority:a&&a.length>0?a:void 0,whatsappAccounts:l&&l.length>0?l:void 0,emailProvider:Le(e),emailAuth:Nt(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,smsProvider:n==="imessage"||n==="twilio"?n:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,twilioAuthToken:e.TWILIO_AUTH_TOKEN,supabaseUrl:e.SUPABASE_URL,supabaseProjectRef:e.SUPABASE_PROJECT_REF,supabaseServiceKey:e.SUPABASE_SERVICE_KEY,supabasePat:e.SUPABASE_PAT,deployProvider:vt(e.DEPLOY_PROVIDER)??it,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:$t(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}function ot(e){let t=P=>{let ee=e[P];if(!ee)return;let D=parseInt(ee,10);return isNaN(D)?void 0:D},n=e.SUPABASE_URL,s=e.SUPABASE_SERVICE_KEY?.replace(/\s+/g,""),o=e.SUPABASE_PAT?.replace(/\s+/g,""),a=e.SUPABASE_PROJECT_REF,l=e.PRICING,c=e.PRICING_TERMS||"one-off, no monthly fees",d=vt(e.DEPLOY_PROVIDER)??it,u=e.VERCEL_TOKEN,r=e.CLOUDFLARE_API_TOKEN,y=e.CLOUDFLARE_ACCOUNT_ID,g=e.NETLIFY_AUTH_TOKEN,A=e.SELFHOST_DEPLOY_TARGET,b=e.SELFHOST_URL_TEMPLATE;if(!l||!n||!s||!o||!a||!(d==="cloudflare"?!!r&&!!y:d==="netlify"?!!g:d==="selfhost"?!!A&&!!b:!!u))return null;let C=e.SMS_PROVIDER,O=P=>P==="email"||P==="sms"||P==="whatsapp",T=e.OUTREACH_CHANNELS?.split(",").map(P=>P.trim()).filter(O),W=e.OUTREACH_PRIORITY?.split(",").map(P=>P.trim()).filter(O),G=e.WHATSAPP_ACCOUNTS?.split(",").map(P=>P.trim()).filter(P=>P.length>0);return{licenseKey:e.KLAUDIUS_LICENSE_KEY,aiAgent:Ot(e.AI_AGENT)??st,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(P=>P.trim().toLowerCase()).filter(Boolean):void 0,pricing:l,pricingTerms:c,pricingMonthly:e.PRICING_MONTHLY||void 0,outreachEnabled:e.OUTREACH_ENABLED?.toLowerCase()==="true",name:e.OPERATOR_NAME,signature:e.SIGNATURE,outreachChannels:T&&T.length>0?T:void 0,outreachPriority:W&&W.length>0?W:void 0,whatsappAccounts:G&&G.length>0?G:void 0,emailProvider:Le(e),emailAuth:Nt(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,smsProvider:C==="imessage"||C==="twilio"?C:void 0,testPhone:e.TEST_PHONE,twilioAccountSid:e.TWILIO_ACCOUNT_SID,twilioAuthToken:e.TWILIO_AUTH_TOKEN,twilioPhoneNumber:e.TWILIO_PHONE_NUMBER,deployProvider:d,vercelToken:u,vercelScope:e.VERCEL_SCOPE||void 0,cloudflareApiToken:r||void 0,cloudflareAccountId:y||void 0,netlifyAuthToken:g||void 0,netlifyAccountSlug:e.NETLIFY_ACCOUNT_SLUG||void 0,selfhostDeployTarget:A||void 0,selfhostUrlTemplate:b||void 0,supabaseUrl:n,supabaseServiceKey:s,supabasePat:o,supabaseProjectRef:a,googlePlacesApiKey:e.GOOGLE_PLACES_API_KEY,notifyChannel:$t(e.NOTIFY_CHANNEL),notifyTo:e.NOTIFY_TO||void 0,telegramBotToken:e.TELEGRAM_BOT_TOKEN,telegramChatId:e.TELEGRAM_CHAT_ID}}import{copyFile as Mo,mkdir as Do,readdir as Ps,stat as Ho}from"fs/promises";import{dirname as Uo,join as Bt,relative as bs,sep as Ts}from"path";import{fileURLToPath as Ko}from"url";import{createHash as Ht}from"crypto";import{readFile as hs}from"fs/promises";async function ye(e){let t=await hs(e);return Ht("sha256").update(t).digest("hex")}function jt(e){return Ht("sha256").update(e).digest("hex")}import{mkdir as gs,readFile as ys,writeFile as ks,access as ws}from"fs/promises";import{dirname as As,join as Ut}from"path";var Es=".klaudius",Ft=`${Es}/manifest.json`,je=new Set([".env",".mcp.json",".claude/settings.json",".codex/config.toml",".ms-token.json"]),Kt=new Set(["clients/README.md"]);async function Gt(e){let t=Ut(e,Ft);try{await ws(t)}catch{return null}let n=await ys(t,"utf-8"),s=JSON.parse(n),o={};for(let[a,l]of Object.entries(s.files??{}))o[a.split("\\").join("/")]=l;return s.files=o,Array.isArray(s.ignored)?s.ignored=s.ignored.filter(a=>typeof a=="string").map(a=>a.split("\\").join("/")):delete s.ignored,s}async function Ue(e,t){let n=Ut(e,Ft);await gs(As(n),{recursive:!0}),await ks(n,JSON.stringify(t,null,2)+`
15
- `,"utf-8")}function Vt(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function le(e,t=e){let n=await Ps(e,{withFileTypes:!0}),s=[];for(let o of n){let a=Bt(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await le(a,t)):o.isFile()&&s.push(bs(t,a).split(Ts).join("/")))}return s}async function Yt(e){let t=await le(e),n={};for(let s of t)je.has(s)||(n[s]=await ye(Bt(e,s)));return n}import{copyFile as Ss,mkdir as Wt,mkdtemp as _s,readdir as zt,rm as qt}from"fs/promises";import{tmpdir as Is}from"os";import{dirname as Cs,join as Fe}from"path";import{Readable as xs}from"stream";import*as Jt from"tar";var Rs="https://klaudius.dev/api/template";function Os(e){return xs.fromWeb(e)}async function Ke(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Rs,n="0.24.1",s;try{s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${I(c)}`)}if(!s.ok){let c="";try{let d=await s.json();c=d.reason?` (${d.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${s.status}${c}`)}if(!s.body)throw new Error("Template download succeeded but response had no body");let o=s.headers.get("x-klaudius-tier"),a=await _s(Fe(Is(),"klaudius-template-")),l=0;try{try{await new Promise((u,r)=>{let y=Jt.extract({cwd:a,strict:!0});y.on("finish",u),y.on("error",r),Os(s.body).on("error",r).pipe(y)})}catch(u){throw new Error(`Failed to extract template archive: ${u.message}`)}await Wt(e.destDir,{recursive:!0});let c=new Set(await zt(e.destDir)),d=await le(a);try{for(let u of d){let r=Fe(e.destDir,u);await Wt(Cs(r),{recursive:!0}),await Ss(Fe(a,u),r),l++}}catch(u){let r=await zt(e.destDir).catch(()=>[]);for(let y of r)c.has(y)||await qt(Fe(e.destDir,y),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${u.message}`)}}finally{await qt(a,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:o}}import{copyFile as vs,mkdir as $s,readFile as Ns,rm as Ls}from"fs/promises";import{dirname as Ms,join as Se}from"path";import{structuredPatch as Ds}from"diff";var Xt=Se(".klaudius","base");async function Ge(e,t,n){let s=Se(e,Xt);await Ls(s,{recursive:!0,force:!0});for(let o of n){let a=Se(s,o);await $s(Ms(a),{recursive:!0}),await vs(Se(t,o),a)}}async function Qt(e,t){try{return await Ns(Se(e,Xt,t),"utf-8")}catch{return null}}function at(e){return e.includes("\0")||e.includes("\uFFFD")}function Zt(e,t,n=60){let s=Ds("base","new",e,t,"","",{context:2});if(s.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=s.hunks.map(d=>`${d.newStart}-${d.newStart+Math.max(d.newLines-1,0)}`).join(", "),a=[`Upstream changed ${s.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],l=0,c=!1;for(let d of s.hunks){if(l>=n){c=!0;break}a.push(`@@ -${d.oldStart},${d.oldLines} +${d.newStart},${d.newLines} @@`),l+=1;let u=Math.max(n-l,0),r=d.lines.slice(0,u);if(a.push(...r),l+=r.length,r.length<d.lines.length){c=!0;break}}return a.push("```"),c&&a.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),a}import se from"picocolors";var i={info:e=>console.log(se.cyan("\u2139"),e),success:e=>console.log(se.green("\u2713"),e),warn:e=>console.log(se.yellow("\u26A0"),e),error:e=>console.error(se.red("\u2717"),e),step:e=>console.log(se.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
16
- `+se.bold(se.cyan(e))),detail:e=>console.log(se.dim(" "+e))};var Hs="https://registry.npmjs.org/klaudius/latest";async function js(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Hs,{signal:t.signal,headers:{accept:"application/json"}});if(!s.ok)return null;let o=await s.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function Us(e,t){let n=a=>a.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(s[a])||Number.isNaN(o[a]))return!1;if(s[a]>o[a])return!0;if(s[a]<o[a])return!1}return!1}async function Ve(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await js();!n||!Us(n,t)||(i.blank(),i.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(i.detail("Your project content is fetched fresh either way, so you're not missing any"),i.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),i.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),i.blank())}import{createHash as Fs}from"crypto";import{hostname as en,userInfo as Ks,platform as tn,arch as nn}from"os";var Gs="https://klaudius.dev",Vs="/api/licenses/validate",Bs="0.24.1";async function sn(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),s=(process.env.KLAUDIUS_API_URL??Gs).replace(/\/$/,"")+Vs,o=_e(),a;try{a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:en(),os:`${tn()}-${nn()}`,cli_version:Bs})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${I(c)}). Check your internet connection or try again later.`}}let l;try{l=await a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return l.ok?{ok:!0,tier:l.tier??"core"}:{ok:!1,reason:l.reason??`License rejected (HTTP ${a.status}).`}}function _e(){let e=[en(),Ks().username,tn(),nn()].join("|");return Fs("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Ys}from"fs/promises";import{join as Ws}from"path";async function ke(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${I(n)}`}}}async function on(e){let t;try{t=await Ys(Ws(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(s){return{ok:!1,message:`Could not read scripts/schema.sql: ${s.message}`}}let n=e.pat.replace(/\s+/g,"");try{let s=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(s.ok)return{ok:!0};let o=await s.text();return o.includes("already exists")||o.includes('relation "clients" already exists')||o.includes("duplicate")?(i.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${s.status}): ${o.slice(0,300)}`}}catch(s){return{ok:!1,message:`Schema apply failed: ${s.message}`}}}async function Be(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${I(t)}`}}}var an="https://api.cloudflare.com/client/v4";function rn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Ye(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${an}/user/tokens/verify`,{headers:s});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await o.json(),l=a.result?.status;if(a.success===!1||l&&l!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${l?` (status: ${l})`:""}. ${rn(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}try{let o=await fetch(`${an}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:s});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await o.json();return a.success===!1?{ok:!1,message:rn(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}}var ln="https://api.netlify.com/api/v1";async function We(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${ln}/user`,{headers:n});if(s.status===401||s.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} verifying the token. Try again or check netlifystatus.com.`}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${I(s)}`}}try{let s=await fetch(`${ln}/accounts`,{headers:n});if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} listing your teams. Try again or check netlifystatus.com.`};let o=await s.json(),a=Array.isArray(o)?o:[];if(a.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let l=typeof a[0]?.slug=="string"?a[0].slug:void 0;return{ok:!0,accountCount:a.length,accountSlug:l}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${I(s)}`}}}async function we(e){let t=Tt(e);if(t)return{ok:!1,message:t};let n=te(e),s=n.value,o=a=>{let l=[a],c=St(e);return c&&l.push(c),n.repairs.length>0&&l.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),l.join(`
15
+ `,"utf-8")}function Vt(e,t){let n=new Date().toISOString();return{version:1,templateVersion:e,installedAt:n,updatedAt:n,files:t}}async function le(e,t=e){let n=await Ps(e,{withFileTypes:!0}),s=[];for(let o of n){let a=Bt(e,o.name);o.name===".klaudius"&&e===t||(o.isDirectory()?s.push(...await le(a,t)):o.isFile()&&s.push(bs(t,a).split(Ts).join("/")))}return s}async function Yt(e){let t=await le(e),n={};for(let s of t)je.has(s)||(n[s]=await ye(Bt(e,s)));return n}import{copyFile as Ss,mkdir as Wt,mkdtemp as _s,readdir as zt,rm as qt}from"fs/promises";import{tmpdir as Is}from"os";import{dirname as Cs,join as Fe}from"path";import{Readable as xs}from"stream";import*as Jt from"tar";var Rs="https://klaudius.dev/api/template";function Os(e){return xs.fromWeb(e)}async function Ke(e){let t=process.env.KLAUDIUS_TEMPLATE_URL??Rs,n="0.24.2",s;try{s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.licenseKey}`,"Content-Type":"application/json"},body:JSON.stringify({machine_id:e.machineId,hostname:e.hostname,os:e.os,cli_version:n,...e.agent==="codex"?{agent:"codex"}:{}})})}catch(c){throw new Error(`Could not reach klaudius.dev to download the template: ${I(c)}`)}if(!s.ok){let c="";try{let d=await s.json();c=d.reason?` (${d.reason})`:""}catch{}throw new Error(`Template download failed: HTTP ${s.status}${c}`)}if(!s.body)throw new Error("Template download succeeded but response had no body");let o=s.headers.get("x-klaudius-tier"),a=await _s(Fe(Is(),"klaudius-template-")),l=0;try{try{await new Promise((u,r)=>{let y=Jt.extract({cwd:a,strict:!0});y.on("finish",u),y.on("error",r),Os(s.body).on("error",r).pipe(y)})}catch(u){throw new Error(`Failed to extract template archive: ${u.message}`)}await Wt(e.destDir,{recursive:!0});let c=new Set(await zt(e.destDir)),d=await le(a);try{for(let u of d){let r=Fe(e.destDir,u);await Wt(Cs(r),{recursive:!0}),await Ss(Fe(a,u),r),l++}}catch(u){let r=await zt(e.destDir).catch(()=>[]);for(let y of r)c.has(y)||await qt(Fe(e.destDir,y),{recursive:!0,force:!0}).catch(()=>{});throw new Error(`Downloaded the template but couldn't copy it into ${e.destDir}: ${u.message}`)}}finally{await qt(a,{recursive:!0,force:!0}).catch(()=>{})}return{filesExtracted:l,tier:o}}import{copyFile as vs,mkdir as $s,readFile as Ns,rm as Ls}from"fs/promises";import{dirname as Ms,join as Se}from"path";import{structuredPatch as Ds}from"diff";var Xt=Se(".klaudius","base");async function Ge(e,t,n){let s=Se(e,Xt);await Ls(s,{recursive:!0,force:!0});for(let o of n){let a=Se(s,o);await $s(Ms(a),{recursive:!0}),await vs(Se(t,o),a)}}async function Qt(e,t){try{return await Ns(Se(e,Xt,t),"utf-8")}catch{return null}}function at(e){return e.includes("\0")||e.includes("\uFFFD")}function Zt(e,t,n=60){let s=Ds("base","new",e,t,"","",{context:2});if(s.hunks.length===0)return["Upstream content is identical to your base for this file."];let o=s.hunks.map(d=>`${d.newStart}-${d.newStart+Math.max(d.newLines-1,0)}`).join(", "),a=[`Upstream changed ${s.hunks.length} hunk(s) (new-version lines ${o}):`,"","```diff"],l=0,c=!1;for(let d of s.hunks){if(l>=n){c=!0;break}a.push(`@@ -${d.oldStart},${d.oldLines} +${d.newStart},${d.newLines} @@`),l+=1;let u=Math.max(n-l,0),r=d.lines.slice(0,u);if(a.push(...r),l+=r.length,r.length<d.lines.length){c=!0;break}}return a.push("```"),c&&a.push(`_\u2026truncated at ${n} diff lines. The full new version is staged in \`.klaudius/incoming/\` for a complete compare._`),a}import se from"picocolors";var i={info:e=>console.log(se.cyan("\u2139"),e),success:e=>console.log(se.green("\u2713"),e),warn:e=>console.log(se.yellow("\u26A0"),e),error:e=>console.error(se.red("\u2717"),e),step:e=>console.log(se.dim("\u2192"),e),blank:()=>console.log(""),heading:e=>console.log(`
16
+ `+se.bold(se.cyan(e))),detail:e=>console.log(se.dim(" "+e))};var Hs="https://registry.npmjs.org/klaudius/latest";async function js(e=1500){let t=new AbortController,n=setTimeout(()=>t.abort(),e);try{let s=await fetch(Hs,{signal:t.signal,headers:{accept:"application/json"}});if(!s.ok)return null;let o=await s.json();return typeof o.version=="string"?o.version:null}catch{return null}finally{clearTimeout(n)}}function Us(e,t){let n=a=>a.split("-")[0].split(".").map(l=>Number.parseInt(l,10)),s=n(e),o=n(t);if(s.length<3||o.length<3)return!1;for(let a=0;a<3;a++){if(Number.isNaN(s[a])||Number.isNaN(o[a]))return!1;if(s[a]>o[a])return!0;if(s[a]<o[a])return!1}return!1}async function Ve(e,t){if(t==="dev"||process.env.CI||process.env.NO_UPDATE_NOTIFIER)return;let n=await js();!n||!Us(n,t)||(i.blank(),i.warn(`A newer Klaudius CLI is available: you have ${t}, latest is ${n}.`),e==="update"&&(i.detail("Your project content is fetched fresh either way, so you're not missing any"),i.detail("pipeline updates. But the CLI itself, including its update logic, is behind.")),i.detail(`Re-run with \`npx klaudius@latest ${e}\` to use the latest CLI.`),i.blank())}import{createHash as Fs}from"crypto";import{hostname as en,userInfo as Ks,platform as tn,arch as nn}from"os";var Gs="https://klaudius.dev",Vs="/api/licenses/validate",Bs="0.24.2";async function sn(e){if(!e||e.trim().length===0)return{ok:!1,reason:"No license key provided. Pass one via --license <key> or paste it when prompted."};let t=e.trim(),s=(process.env.KLAUDIUS_API_URL??Gs).replace(/\/$/,"")+Vs,o=_e(),a;try{a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:t,machine_id:o,hostname:en(),os:`${tn()}-${nn()}`,cli_version:Bs})})}catch(c){return{ok:!1,reason:`Could not reach the Klaudius license server (${I(c)}). Check your internet connection or try again later.`}}let l;try{l=await a.json()}catch{return{ok:!1,reason:`License server returned an unparseable response (HTTP ${a.status}).`}}return l.ok?{ok:!0,tier:l.tier??"core"}:{ok:!1,reason:l.reason??`License rejected (HTTP ${a.status}).`}}function _e(){let e=[en(),Ks().username,tn(),nn()].join("|");return Fs("sha256").update(e).digest("hex").slice(0,32)}import{readFile as Ys}from"fs/promises";import{join as Ws}from"path";async function ke(e){let t=e.serviceKey.replace(/\s+/g,"");try{let n=await fetch(e.url+"/rest/v1/",{headers:{apikey:t,Authorization:`Bearer ${t}`}});return n.status===401||n.status===403?{ok:!1,message:`Supabase rejected auth (HTTP ${n.status}). Check SUPABASE_SERVICE_KEY.`}:{ok:!0}}catch(n){return{ok:!1,message:`Could not reach Supabase: ${I(n)}`}}}async function on(e){let t;try{t=await Ys(Ws(e.projectRoot,"scripts","schema.sql"),"utf-8")}catch(s){return{ok:!1,message:`Could not read scripts/schema.sql: ${s.message}`}}let n=e.pat.replace(/\s+/g,"");try{let s=await fetch(`https://api.supabase.com/v1/projects/${e.projectRef}/database/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({query:t})});if(s.ok)return{ok:!0};let o=await s.text();return o.includes("already exists")||o.includes('relation "clients" already exists')||o.includes("duplicate")?(i.detail("Schema appears already applied (tables exist). Skipping."),{ok:!0}):{ok:!1,message:`Supabase Management API rejected schema (HTTP ${s.status}): ${o.slice(0,300)}`}}catch(s){return{ok:!1,message:`Schema apply failed: ${s.message}`}}}async function Be(e){try{let t=await fetch("https://api.vercel.com/v2/user",{headers:{Authorization:`Bearer ${e}`}});if(t.status===401||t.status===403)return{ok:!1,message:`Vercel rejected the token (HTTP ${t.status}). The token is invalid, expired, or has been revoked.`};if(!t.ok)return{ok:!1,message:`Vercel API returned HTTP ${t.status}. Try again or check status.vercel.com.`};let n=await t.json();return{ok:!0,username:n.user?.username??n.user?.email}}catch(t){return{ok:!1,message:`Could not reach Vercel: ${I(t)}`}}}var an="https://api.cloudflare.com/client/v4";function rn(e){let t=e?.errors?.[0];if(t)return t.message?`${t.message}${t.code?` (code ${t.code})`:""}`:void 0}async function Ye(e){let{token:t,accountId:n}=e,s={Authorization:`Bearer ${t}`,"Content-Type":"application/json"};try{let o=await fetch(`${an}/user/tokens/verify`,{headers:s});if(o.status===401||o.status===403)return{ok:!1,message:`Cloudflare rejected the token (HTTP ${o.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://dash.cloudflare.com/profile/api-tokens.`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} verifying the token. Try again or check cloudflarestatus.com.`};let a=await o.json(),l=a.result?.status;if(a.success===!1||l&&l!=="active")return{ok:!1,message:`Cloudflare reports the token is not active${l?` (status: ${l})`:""}. ${rn(a)??"Create a fresh token at https://dash.cloudflare.com/profile/api-tokens."}`}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}try{let o=await fetch(`${an}/accounts/${encodeURIComponent(n)}/pages/projects`,{headers:s});if(o.status===403)return{ok:!1,message:`The token is valid but can't manage Pages in account ${n} (HTTP 403). Most likely the token is missing the "Account \u2192 Cloudflare Pages \u2192 Edit" permission, or the Account ID belongs to a different account than the token. Re-create the token with that exact permission and your account selected under "Account Resources".`};if(o.status===404)return{ok:!1,message:`Account ${n} was not found (HTTP 404). Double-check the Account ID \u2014 it's the 32-character hex string in the dashboard URL (dash.cloudflare.com/<ID>).`};if(!o.ok)return{ok:!1,message:`Cloudflare API returned HTTP ${o.status} listing Pages projects. Try again or check cloudflarestatus.com.`};let a=await o.json();return a.success===!1?{ok:!1,message:rn(a)??"Cloudflare rejected the Pages project listing request."}:{ok:!0,projectCount:Array.isArray(a.result)?a.result.length:void 0}}catch(o){return{ok:!1,message:`Could not reach Cloudflare: ${I(o)}`}}}var ln="https://api.netlify.com/api/v1";async function We(e){let{token:t}=e,n={Authorization:`Bearer ${t}`};try{let s=await fetch(`${ln}/user`,{headers:n});if(s.status===401||s.status===403)return{ok:!1,message:`Netlify rejected the token (HTTP ${s.status}). The token is invalid, expired, or has been revoked. Create a fresh one at https://app.netlify.com/user/applications#personal-access-tokens.`};if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} verifying the token. Try again or check netlifystatus.com.`}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${I(s)}`}}try{let s=await fetch(`${ln}/accounts`,{headers:n});if(!s.ok)return{ok:!1,message:`Netlify API returned HTTP ${s.status} listing your teams. Try again or check netlifystatus.com.`};let o=await s.json(),a=Array.isArray(o)?o:[];if(a.length===0)return{ok:!1,message:"The token is valid but isn't a member of any Netlify team. Klaudius creates each client's site under a team, so it needs at least one. Open https://app.netlify.com and confirm your account has a team."};let l=typeof a[0]?.slug=="string"?a[0].slug:void 0;return{ok:!0,accountCount:a.length,accountSlug:l}}catch(s){return{ok:!1,message:`Could not reach Netlify: ${I(s)}`}}}async function we(e){let t=Tt(e);if(t)return{ok:!1,message:t};let n=te(e),s=n.value,o=a=>{let l=[a],c=St(e);return c&&l.push(c),n.repairs.length>0&&l.push(`Note: we corrected ${n.repairs.length} look-alike character(s) in this key before sending it (${n.repairs.join("; ")}). Some look-alikes are ambiguous, so if the key is otherwise correct, re-copy it with the copy button in the Cloud Console rather than retyping it.`),l.join(`
17
17
  `)};try{let a=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":s,"X-Goog-FieldMask":"places.id"},body:JSON.stringify({textQuery:"x"})});if(a.ok)return{ok:!0};if(a.status===429)return{ok:!0};let l={};try{l=await a.json()}catch{}let c=l.error?.message??"",d=l.error?.status??"";return a.status===400&&(d==="PERMISSION_DENIED"||/Places API \(New\) has not been enabled|API_KEY_SERVICE_BLOCKED/i.test(c))?{ok:!1,message:"Key is valid, but Places API (New) is not enabled on its Cloud project. Open https://console.cloud.google.com/apis/library and enable 'Places API (New)' for the project this key belongs to, then try again."}:a.status===401||a.status===403?{ok:!1,message:o(c||`Google rejected the key (HTTP ${a.status}). Common causes: invalid key, billing not enabled on the Cloud project, or API key restrictions blocking this caller.`)}:{ok:!1,message:o(`Google API returned HTTP ${a.status}${c?`: ${c}`:""}.`)}}catch(a){return{ok:!1,message:`Could not reach Google: ${I(a)}`}}}import zs from"nodemailer";import{ImapFlow as qs}from"imapflow";function cn(e){let t=e;if(t?.authenticationFailed)return"auth";let n=typeof t?.code=="string"?t.code.toUpperCase():"";if(n==="EAUTH")return"auth";if(["ETIMEDOUT","ESOCKET","ECONNECTION","EDNS","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ECONNRESET"].includes(n))return"network";let s=(typeof t?.message=="string"?t.message:String(e)).toLowerCase();return s.includes("invalid credentials")||s.includes("authentication failed")||s.includes("auth failed")||s.includes("login failed")||s.includes("invalid login")?"auth":s.includes("etimedout")||s.includes("timeout")||s.includes("enotfound")||s.includes("getaddrinfo")||s.includes("econnrefused")||s.includes("econnreset")?"network":"other"}async function ie(e){let t=zs.createTransport({host:e.emailSmtpHost,port:e.emailSmtpPort,secure:e.emailSmtpPort===465,auth:{user:e.emailAddress,pass:e.emailPassword},connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await t.verify()}catch(s){return{ok:!1,failedAt:"smtp",message:dn(s,"SMTP",e.usesAccountPassword),failureKind:cn(s)}}finally{t.close()}let n=new qs({host:e.emailImapHost,port:e.emailImapPort,secure:e.emailImapPort===993,auth:{user:e.emailAddress,pass:e.emailPassword},logger:!1,connectionTimeout:1e4,greetingTimeout:5e3,socketTimeout:1e4});try{await n.connect(),await n.logout()}catch(s){try{await n.logout()}catch{}return{ok:!1,failedAt:"imap",message:dn(s,"IMAP",e.usesAccountPassword),failureKind:cn(s)}}return{ok:!0}}function dn(e,t,n){let s=e instanceof Error?e.message:String(e),o=s.toLowerCase();return o.includes("invalid credentials")||o.includes("authentication failed")||o.includes("auth failed")||o.includes("login failed")?n?`${t} rejected the credentials. Most common causes:
18
18
  \u2022 The mailbox password is wrong or mistyped.
19
19
  \u2022 The email address doesn't match this mailbox's login.
@@ -24,7 +24,7 @@ Please share that file so we can trace what happened.`);return s}var st="claude-
24
24
  \u2022 2FA is required but no app-specific password was generated.`:o.includes("etimedout")||o.includes("timeout")?`${t} server didn't respond in time. Check the host/port, or your network.`:o.includes("enotfound")||o.includes("getaddrinfo")?`${t} host could not be resolved. Check the host setting.`:`${t} check failed: ${s}`}async function un(e){if(!e.accountSid||!e.authToken)return{ok:!1,message:"Missing Twilio Account SID or Auth Token."};let t=`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(e.accountSid)}.json`,n=Buffer.from(`${e.accountSid}:${e.authToken}`).toString("base64");try{let s=await fetch(t,{headers:{Authorization:`Basic ${n}`}});if(s.status===401)return{ok:!1,message:"Twilio rejected the credentials (401). Check the Account SID and Auth Token from https://console.twilio.com/ \u2014 the Auth Token shown there is the value to paste."};if(!s.ok)return{ok:!1,message:`Twilio API returned HTTP ${s.status}. Try again or check status.twilio.com.`};let o=await s.json();return o.status&&o.status!=="active"?{ok:!1,message:`Twilio account is in '${o.status}' state. Check the console for any holds before sending SMS.`}:{ok:!0,friendlyName:o.friendly_name}}catch(s){return{ok:!1,message:`Could not reach Twilio: ${I(s)}`}}}import{spawn as Js}from"child_process";async function pn(e){if(process.platform!=="darwin")return{ok:!1,message:"iMessage send is only supported on macOS. To run init from a non-Mac, switch the SMS provider to Twilio in the wizard."};let n=`tell application "Messages" to send "Klaudius connected (setup ping; ignore)." to buddy "${e.testPhone.replace(/"/g,"")}"`,s=await Xs(n);if(s.code===0)return{ok:!0};let o=s.stderr.toLowerCase();return o.includes("can't get application")||o.includes("isn't running")||o.includes("can't make some data")?{ok:!1,message:"Messages.app didn't respond. Open Messages on your Mac and sign in with your Apple ID, then retry."}:o.includes("(-1728)")||o.includes("not found")||o.includes("buddy")?{ok:!1,message:`Couldn't reach ${e.testPhone}. Either the number format is wrong (use the international format with a leading +) or this Mac doesn't have a path to that number. If TEST_PHONE is a non-Apple phone (Android), you need an iPhone signed into the same Apple ID with Settings \u2192 Messages \u2192 Text Message Forwarding turned ON for this Mac.`}:o.includes("(-1719)")||o.includes("(-25006)")?{ok:!1,message:"Messages.app refused the send \u2014 usually means iMessage isn't configured on this Mac. Open Messages \u2192 Settings \u2192 iMessage and sign in with your Apple ID."}:{ok:!1,message:`osascript error: ${s.stderr.trim()||`exit code ${s.code}`}`}}function Xs(e){return new Promise(t=>{let n=Js("osascript",["-e",e],{stdio:["ignore","ignore","pipe"]}),s="";n.stderr.on("data",o=>{s+=o.toString()}),n.on("close",o=>t({code:o??1,stderr:s})),n.on("error",o=>t({code:1,stderr:o.message}))})}import{spawn as ze}from"child_process";import{existsSync as Qs}from"fs";import{homedir as Zs}from"os";function ei(){let e=process.env.NODE_OPTIONS?.trim(),t=e?`${e} --use-system-ca`:"--use-system-ca";return{...process.env,NODE_OPTIONS:t}}var Ae=2,fn=2e3,ti=[/ECONNRESET/,/ETIMEDOUT/,/ENOTFOUND/,/EAI_AGAIN/,/socket hang up/i,/Connection reset/i,/network timeout/i,/could not resolve host/i];function mn(e,t){let n=e+`
25
25
  `+t;return ti.some(s=>s.test(n))}function hn(e){return new Promise(t=>setTimeout(t,e))}function ni(e,t,n){return new Promise(s=>{let o=n.shell?ze([e,...t].join(" "),{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!0,env:n.env??process.env}):ze(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1,env:n.env??process.env}),a="",l="";o.stdout?.on("data",c=>{let d=c.toString();a+=d,process.stdout.write(d)}),o.stderr?.on("data",c=>{let d=c.toString();l+=d,process.stderr.write(d)}),o.on("close",c=>s({code:c??1,stdout:a,stderr:l})),o.on("error",c=>s({code:1,stdout:a,stderr:l+c.message}))})}async function rt(e,t,n){let s={code:0,stdout:"",stderr:""};for(let o=0;o<=Ae;o++){if(s=await ni(e,t,{cwd:n.cwd,env:n.env,shell:n.shell}),s.code===0||!mn(s.stderr,s.stdout))return s;o<Ae&&(i.detail(`${n.label} failed with a transient network error \u2014 retrying (${o+2}/${Ae+1})\u2026`),await hn(fn))}return s}function si(e,t,n){return new Promise(s=>{let o=ze(e,t,{cwd:n.cwd,stdio:["ignore","pipe","pipe"],shell:!1}),a="",l="";o.stdout?.on("data",c=>{a+=c.toString()}),o.stderr?.on("data",c=>{l+=c.toString()}),o.on("close",c=>s({code:c??1,stdout:a,stderr:l})),o.on("error",c=>s({code:1,stdout:a,stderr:l+c.message}))})}var ii=[{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 oi(e){let t=`${e.stderr??""}
26
26
  ${e.stdout??""}`;return ii.find(s=>s.pattern.test(t))?.hint}async function ai(e){let t=["supabase<2.26","python-dotenv","requests","httpx","Pillow","truststore"],n=["-m","pip","install","--quiet","--user","--prefer-binary"],o=(await z())?.command??["python3"],a=async c=>{let d={code:0,stdout:"",stderr:""};for(let u=0;u<=Ae;u++){if(d=await si(o[0],[...o.slice(1),...c],{cwd:e}),d.code===0||!mn(d.stderr,d.stdout))return d;u<Ae&&(i.detail(`pip install hit a transient network error \u2014 retrying (${u+2}/${Ae+1})\u2026`),await hn(fn))}return d},l=await a([...n,"--break-system-packages",...t]);return l.code!==0&&/no such option:.*break-system-packages/i.test(l.stderr)&&(i.detail("Older pip detected; retrying without --break-system-packages"),l=await a([...n,...t])),l.code!==0&&(l.stderr.trim()&&process.stderr.write(l.stderr),l.stdout.trim()&&process.stdout.write(l.stdout)),l}async function qe(e){let t={npm:"skipped",pip:"skipped",playwright:"skipped",patchright:"skipped"},n=ei(),s=process.platform==="win32",o;if(s){let r=fe([{label:"your Windows user folder",path:Zs()},{label:"the project folder",path:e}]);if(r.length>0){let y=await new Promise(A=>{let b=ze("npm config get script-shell",{cwd:e,stdio:["ignore","pipe","pipe"],shell:!0}),S="",C="";b.stdout?.on("data",O=>{S+=O.toString()}),b.stderr?.on("data",O=>{C+=O.toString()}),b.on("close",O=>A({code:O??1,stdout:S,stderr:C})),b.on("error",O=>A({code:1,stdout:S,stderr:O.message}))}),g=y.code===0?y.stdout.trim():void 0;if(!me(g,Qs)){let{detail:A,action:b}=he(r,"install");o=`${A}. ${b}`}}}let a=(r,y)=>{let g=oi(y);if(g){(t.hints??={})[r]=g;return}o&&(r==="npm"||r==="playwright"||r==="patchright")&&!Object.values(t.hints??{}).includes(o)&&((t.hints??={})[r]=o)};i.step("Running npm install (Next.js, Playwright JS, etc.)...");let l=await rt("npm",["install"],{cwd:e,label:"npm install",env:n,shell:s});t.npm=l.code===0?"ok":"failed",l.code!==0&&a("npm",l),i.step("Installing Python packages (supabase, dotenv, requests, httpx, Pillow)...");let c=await ai(e);t.pip=c.code===0?"ok":"failed",c.code!==0&&a("pip",c),i.step("Installing Playwright browser (chromium ~200MB; one-time)...");let d=await rt("npx",["playwright","install","chromium"],{cwd:e,label:"playwright install",env:n,shell:s});t.playwright=d.code===0?"ok":"failed",d.code!==0&&a("playwright",d),i.step("Installing Patchright browser (chromium ~200MB; one-time)...");let u=await rt("npx",["patchright","install","chromium"],{cwd:e,label:"patchright install",env:n,shell:s});return t.patchright=u.code===0?"ok":"failed",u.code!==0&&a("patchright",u),t}import{mkdir as ri,readFile as li,writeFile as ci}from"fs/promises";import{join as gn}from"path";async function Je(e,t){let n=gn(e,".claude");await ri(n,{recursive:!0});let s=gn(n,"settings.json"),o={};try{let d=await li(s,"utf-8"),u=JSON.parse(d);u&&typeof u=="object"&&!Array.isArray(u)&&(o=u)}catch{}let a=o.enabledMcpjsonServers,l=Array.isArray(a)?a.filter(d=>typeof d=="string"):[];l.includes(t)||l.push(t);let c={...o,enabledMcpjsonServers:l};await ci(s,JSON.stringify(c,null,2)+`
27
- `,"utf-8")}var kn="0.24.1",x=5;function ce(e){return`npx klaudius@latest init ${Xe(Ee(e))}`}function Ee(e){if(process.platform==="win32")return e;let t=di();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function mi(e){let t=[];try{let s=(await An(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let a=B(e,o.name);if(!await wn(B(a,".env")))continue;let l=await wn(B(a,".klaudius","manifest.json"));if(t.push({path:a,finished:l}),t.length>=3)break}}catch{}return t}async function wn(e){try{return await dt(e),!0}catch{return!1}}function Xe(e){return/\s/.test(e)?`"${e}"`:e}function oe(e,t,n){i.blank(),i.error(`${t} validation failed ${x} times in a row. Pausing setup so you don't get stuck in a loop.`),i.detail(`Last error: ${n}`),i.blank(),i.detail("Your credentials are saved in `.env`. Two ways forward:"),i.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),i.blank(),console.log(` ${p.cyan(ce(e))}`),i.blank(),i.detail(` (Your .env is at ${Ee(B(e,".env"))} \u2014 open it in any text editor.)`),i.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),i.blank(),process.exit(1)}async function En(e){let t=e.target??".",n=pi(t)?t:ui(process.cwd(),t),s=ki(n);s&&(i.error("Klaudius can't be installed inside a protected system folder."),i.detail(`Path: ${n}`),i.detail(`Reason: ${s}`),i.blank(),i.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),i.blank(),process.platform==="win32"?(i.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${p.cyan("cd $HOME\\Documents")}`),console.log(` ${p.cyan("npx klaudius@latest init my-agency")}`)):(i.detail("For example:"),console.log(` ${p.cyan("cd ~/Documents")}`),console.log(` ${p.cyan("npx klaudius@latest init my-agency")}`)),i.blank(),process.exit(1)),process.platform==="win32"&&wi()&&(i.warn("You appear to be running in an elevated (Administrator) PowerShell."),i.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),i.blank()),await Ve("init",kn);let o=await hi(n);if(o.kind==="scaffolded"){i.blank(),i.warn(`Found an existing Klaudius project at ${p.bold(n)}.`),i.detail("(Your .env and project files are in place.)"),i.blank(),o.nodeModulesMissing?(i.detail("It looks like a previous setup didn't finish installing dependencies."),i.detail("To pick up where it left off, run:"),i.blank(),n!==process.cwd()&&console.log(` ${p.cyan(`cd ${Xe(t)}`)}`),console.log(` ${p.cyan("npx klaudius@latest install")} ${p.dim("# retries npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${p.cyan("npx klaudius@latest doctor")} ${p.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Everything is scaffolded and dependencies look installed."),i.detail("Pick the action you wanted:"),i.blank(),console.log(` ${p.cyan("npx klaudius@latest doctor")} ${p.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${p.cyan("npx klaudius@latest configure")} ${p.dim("# change a credential / API key")}`),console.log(` ${p.cyan("npx klaudius@latest update")} ${p.dim("# pull the latest skills, scripts, lessons")}`),i.blank()),i.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),i.blank();return}if(o.kind==="occupied"){let f=t===".",h=await mi(n);if(h.length>0){i.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),i.detail(`You're in: ${Ee(n)}`),i.blank();for(let m of h)i.detail(m.finished?`Found a finished project at ${Ee(m.path)}. To work in it:`:`Found an unfinished setup at ${Ee(m.path)}. To pick up where it left off:`),i.blank(),m.finished?(console.log(` ${p.cyan(`cd ${Ee(m.path)}`)}`),console.log(` ${p.cyan("claude")} ${p.dim("# open Claude Code in the project")}`)):console.log(` ${p.cyan(ce(m.path))} ${p.dim("# then pick Resume")}`),i.blank();process.exit(1)}i.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),i.detail(`Path: ${n}`),i.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),i.blank(),f?(i.detail("Two ways forward:"),i.blank(),i.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${p.cyan("npx klaudius@latest init my-agency")}`),i.blank(),i.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${p.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(i.detail(`The folder '${t}' already exists and isn't empty.`),i.detail("Either pick a different name:"),console.log(` ${p.cyan(`npx klaudius@latest init ${t}-2`)}`),i.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=await yi(e.license),l=E.spinner();l.start("Validating license");let c=await sn(a);c.ok||(l.stop(`License invalid: ${c.reason??"unknown"}`,2),i.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),l.stop(`License valid (${c.tier??"core"} tier)`);let d=await ge();d.ok||(i.error(d.message??"Python version check failed."),i.blank(),i.detail(`Once you've installed Python 3.10+, re-run the same command: ${ce(n)}`),process.exit(1));let u=ne();u.ok||(i.error(u.message??"Node.js version check failed."),i.blank(),i.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${ce(n)}`),process.exit(1));let r,y=!1;if(o.kind==="partial")if(await gi(n)==="resume"){let h=await yn(o.envPath,"utf-8"),m=ot(F(h));m?(i.success("Resuming with values from your existing .env"),i.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),r=m,y=!0):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await R())}else{let h=await yn(o.envPath,"utf-8"),m=ot(F(h));r=await R(m??{})}else r=await R();r.licenseKey=a,await $(n,r),y||(i.success("Saved .env"),i.success(r.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.blank();for(let f=1;;f++){let h=E.spinner();h.start("Validating Supabase credentials");let m=await ke({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(m.ok){h.stop("Supabase credentials accepted");break}h.stop(m.message??"Supabase check failed",2),f>=x&&oe(n,"Supabase",m.message??"Supabase check failed");let w=m.message??"Supabase check failed";i.blank(),i.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${f+1} of ${x})`),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await R(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
27
+ `,"utf-8")}var kn="0.24.2",x=5;function ce(e){return`npx klaudius@latest init ${Xe(Ee(e))}`}function Ee(e){if(process.platform==="win32")return e;let t=di();return e===t?"~":e.startsWith(t+"/")?`~/${e.slice(t.length+1)}`:e}async function mi(e){let t=[];try{let s=(await An(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).slice(0,200);for(let o of s){let a=B(e,o.name);if(!await wn(B(a,".env")))continue;let l=await wn(B(a,".klaudius","manifest.json"));if(t.push({path:a,finished:l}),t.length>=3)break}}catch{}return t}async function wn(e){try{return await dt(e),!0}catch{return!1}}function Xe(e){return/\s/.test(e)?`"${e}"`:e}function oe(e,t,n){i.blank(),i.error(`${t} validation failed ${x} times in a row. Pausing setup so you don't get stuck in a loop.`),i.detail(`Last error: ${n}`),i.blank(),i.detail("Your credentials are saved in `.env`. Two ways forward:"),i.detail(" \u2022 Fix the value, then re-run setup and pick Resume \u2014 it keeps everything else you've entered:"),i.blank(),console.log(` ${p.cyan(ce(e))}`),i.blank(),i.detail(` (Your .env is at ${Ee(B(e,".env"))} \u2014 open it in any text editor.)`),i.detail(" \u2022 Or email hello@klaudius.dev with the error above and we'll dig in."),i.blank(),process.exit(1)}async function En(e){let t=e.target??".",n=pi(t)?t:ui(process.cwd(),t),s=ki(n);s&&(i.error("Klaudius can't be installed inside a protected system folder."),i.detail(`Path: ${n}`),i.detail(`Reason: ${s}`),i.blank(),i.detail("Pick a normal user folder instead \u2014 Documents and Desktop are the safe defaults."),i.blank(),process.platform==="win32"?(i.detail("For example, open a fresh PowerShell window (not 'Run as Administrator') and run:"),console.log(` ${p.cyan("cd $HOME\\Documents")}`),console.log(` ${p.cyan("npx klaudius@latest init my-agency")}`)):(i.detail("For example:"),console.log(` ${p.cyan("cd ~/Documents")}`),console.log(` ${p.cyan("npx klaudius@latest init my-agency")}`)),i.blank(),process.exit(1)),process.platform==="win32"&&wi()&&(i.warn("You appear to be running in an elevated (Administrator) PowerShell."),i.detail("This isn't fatal, but Python paths and Playwright's browser cache will land in a different location than a normal user shell, which often causes installs to fail or run-time scripts to break. Easiest fix: close this window, open a new regular PowerShell (NOT 'Run as Administrator'), then re-run npx klaudius@latest init."),i.blank()),await Ve("init",kn);let o=await hi(n);if(o.kind==="scaffolded"){i.blank(),i.warn(`Found an existing Klaudius project at ${p.bold(n)}.`),i.detail("(Your .env and project files are in place.)"),i.blank(),o.nodeModulesMissing?(i.detail("It looks like a previous setup didn't finish installing dependencies."),i.detail("To pick up where it left off, run:"),i.blank(),n!==process.cwd()&&console.log(` ${p.cyan(`cd ${Xe(t)}`)}`),console.log(` ${p.cyan("npx klaudius@latest install")} ${p.dim("# retries npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${p.cyan("npx klaudius@latest doctor")} ${p.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Everything is scaffolded and dependencies look installed."),i.detail("Pick the action you wanted:"),i.blank(),console.log(` ${p.cyan("npx klaudius@latest doctor")} ${p.dim("# verify Node / Python / installers / credentials")}`),console.log(` ${p.cyan("npx klaudius@latest configure")} ${p.dim("# change a credential / API key")}`),console.log(` ${p.cyan("npx klaudius@latest update")} ${p.dim("# pull the latest skills, scripts, lessons")}`),i.blank()),i.detail("If you wanted to start over from scratch, delete this folder and re-run `npx klaudius@latest init`."),i.blank();return}if(o.kind==="occupied"){let f=t===".",h=await mi(n);if(h.length>0){i.warn("You're not inside your Klaudius project \u2014 it's in a folder below this one."),i.detail(`You're in: ${Ee(n)}`),i.blank();for(let m of h)i.detail(m.finished?`Found a finished project at ${Ee(m.path)}. To work in it:`:`Found an unfinished setup at ${Ee(m.path)}. To pick up where it left off:`),i.blank(),m.finished?(console.log(` ${p.cyan(`cd ${Ee(m.path)}`)}`),console.log(` ${p.cyan("claude")} ${p.dim("# open Claude Code in the project")}`)):console.log(` ${p.cyan(ce(m.path))} ${p.dim("# then pick Resume")}`),i.blank();process.exit(1)}i.error("Klaudius needs an empty folder to scaffold into. This directory isn't empty."),i.detail(`Path: ${n}`),i.detail(`Contains: ${o.entries.slice(0,5).join(", ")}${o.entries.length>5?`, \u2026 (+${o.entries.length-5} more)`:""}`),i.blank(),f?(i.detail("Two ways forward:"),i.blank(),i.detail("1. Pass a folder name and Klaudius creates it for you:"),console.log(` ${p.cyan("npx klaudius@latest init my-agency")}`),i.blank(),i.detail("2. Or cd into an empty folder first, then re-run:"),console.log(` ${p.cyan("mkdir my-agency && cd my-agency && npx klaudius@latest init")}`)):(i.detail(`The folder '${t}' already exists and isn't empty.`),i.detail("Either pick a different name:"),console.log(` ${p.cyan(`npx klaudius@latest init ${t}-2`)}`),i.detail("\u2026or delete the existing folder if it's safe to remove.")),process.exit(1)}let a=await yi(e.license),l=E.spinner();l.start("Validating license");let c=await sn(a);c.ok||(l.stop(`License invalid: ${c.reason??"unknown"}`,2),i.detail("If you believe this is in error, email hello@klaudius.dev with your purchase details."),process.exit(1)),l.stop(`License valid (${c.tier??"core"} tier)`);let d=await ge();d.ok||(i.error(d.message??"Python version check failed."),i.blank(),i.detail(`Once you've installed Python 3.10+, re-run the same command: ${ce(n)}`),process.exit(1));let u=ne();u.ok||(i.error(u.message??"Node.js version check failed."),i.blank(),i.detail(`Once you've installed Node.js 22.15+, re-run the same command: ${ce(n)}`),process.exit(1));let r,y=!1;if(o.kind==="partial")if(await gi(n)==="resume"){let h=await yn(o.envPath,"utf-8"),m=ot(F(h));m?(i.success("Resuming with values from your existing .env"),i.detail("(Skipping the wizard \u2014 edit .env directly if you need to change anything.)"),r=m,y=!0):(i.warn("Existing .env was missing required fields \u2014 starting wizard fresh."),r=await R())}else{let h=await yn(o.envPath,"utf-8"),m=ot(F(h));r=await R(m??{})}else r=await R();r.licenseKey=a,await $(n,r),y||(i.success("Saved .env"),i.success(r.aiAgent==="codex"?"Saved .codex/config.toml":"Saved .mcp.json")),i.blank();for(let f=1;;f++){let h=E.spinner();h.start("Validating Supabase credentials");let m=await ke({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});if(m.ok){h.stop("Supabase credentials accepted");break}h.stop(m.message??"Supabase check failed",2),f>=x&&oe(n,"Supabase",m.message??"Supabase check failed");let w=m.message??"Supabase check failed";i.blank(),i.warn(`Bouncing you back into the Supabase section so you can fix it in place. (attempt ${f+1} of ${x})`),i.detail("(Press Enter through any field to keep its current value. Ctrl+C to exit.)"),i.blank(),r=await R(r,{onlySection:"supabase",banner:`Supabase rejected your credentials:
28
28
  ${w}
29
29
 
30
30
  Re-enter the URL, secret key, or PAT below. Press Enter on any
@@ -86,7 +86,7 @@ password. Your browser will open to Microsoft's sign-in page \u2014
86
86
  sign in as `+(r.emailAddress??"your outreach mailbox")+` and approve.
87
87
  (No browser on this machine? It falls back to a short code you can
88
88
  enter from any device.)`)),i.blank();let f=await z();if(f){let[h,...m]=f.command,w=ut(h,[...m,"-u","scripts/ms_oauth.py","login"],{cwd:n,stdio:"inherit",timeout:39e5});w.status===0?i.success("Outlook mailbox connected."):(i.blank(),console.log(p.yellow(`The Microsoft sign-in didn't complete (exit ${w.status??"signalled"}). Setup continues without it.`)),de(f))}else console.log(p.yellow("No Python interpreter found to run the sign-in. Setup continues without it.")),de(null)}else ee&&!D&&(i.blank(),console.log(p.yellow("Skipping the Microsoft mailbox sign-in \u2014 Python dependencies aren't installed yet (pip failed earlier or was skipped).")),console.log(p.dim("Once `npx klaudius@latest install` completes successfully:")),console.log(p.cyan(" python3 scripts/ms_oauth.py login")));i.blank();let k=[...T,...C?["schema"]:[]];if(k.length>0){E.outro(p.yellow(p.bold(`Setup paused \u2014 ${k.join(", ")} failed.`))),console.log(p.dim("Your credentials and project files are all saved.")),i.blank();for(let[j,Ce]of Object.entries(W))console.log(p.yellow(`Likely cause of ${j} failure:`)),console.log(p.dim(` ${Ce}`)),i.blank();let f=n!==process.cwd()&&e.target?` ${p.cyan(`cd ${Xe(e.target)}`)}
89
- `:"",h=r.aiAgent==="codex"?"codex":"claude",m=r.aiAgent==="codex"?"Codex":"Claude Code",w=r.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";T.length>0&&(console.log(p.dim(`Easiest fix \u2014 let ${m} finish it for you:`)),i.blank(),f&&process.stdout.write(f),console.log(` ${p.cyan(h)} ${p.dim(`# open ${m} in this folder`)}`),console.log(p.dim(" Then paste:")),console.log(p.cyan(` "Finish my Klaudius install \u2014 ${T.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(p.dim(` (Don't have ${m} yet? Install with: \`${w}\`)`)),i.blank(),console.log(p.dim("Or do it yourself:")),i.blank(),f&&process.stdout.write(f),console.log(` ${p.cyan("npx klaudius@latest install")} ${p.dim("# retry the failing installers")}`),console.log(` ${p.cyan("npx klaudius@latest doctor")} ${p.dim("# verify everything")}`),i.blank()),C&&(console.log(p.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${p.cyan(O)}`),console.log(p.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),T.includes("pip")&&!W.pip&&(console.log(p.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(p.dim(`Python 3.10+. Install a newer one from ${Ai()}`)),console.log(p.dim("and open a fresh Terminal before retrying.")),i.blank());let v=["npm","playwright","patchright"].filter(j=>T.includes(j)&&!W[j]);if(v.length>0){let j=v.length===1?"keeps":"keep";console.log(p.dim(`If ${v.join(" / ")} ${j} failing with network errors (ECONNRESET,`)),console.log(p.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(p.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),i.blank()}g&&(console.log(p.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${m}`)),console.log(p.dim("to finish setting it up \u2014 your email details are saved in .env.")),i.blank()),console.log(p.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(Ei(r,n,e.target),g){let f=r.aiAgent==="codex"?"Codex":"Claude Code";console.log(p.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(p.dim(`Your details are saved in .env. To finish it, ask ${f}:`)),console.log(p.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(p.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(p.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(p.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(p.cyan(' and send a test email to my own address to confirm."')),r.outreachEnabled&&(r.outreachChannels??[]).length>0&&(i.blank(),console.log(p.yellow(`Note: your other channel(s) \u2014 ${(r.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),i.blank()}}async function $(e,t){await ct(e,{recursive:!0}),await lt(B(e,".env"),Me(t),"utf-8"),t.aiAgent==="codex"?(await ct(B(e,".codex"),{recursive:!0}),await lt(B(e,".codex","config.toml"),He(t),"utf-8")):(await lt(B(e,".mcp.json"),De(t),"utf-8"),await Je(e,"supabase"))}async function hi(e){try{(await dt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await An(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(c=>s.has(c)),a=n.includes(".env"),l=t.includes(".klaudius");if(o&&a&&!l)return{kind:"partial",envPath:B(e,".env")};if(l&&a){let c=!0;try{c=!(await dt(B(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function gi(e){i.blank(),i.warn(`Found a partial setup at ${p.bold(e)}.`),i.detail(`A previous init wrote ${p.bold(".env")} but didn't finish scaffolding.`),i.blank();let t=await E.select({message:`How would you like to proceed? ${p.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return E.isCancel(t)&&(E.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function yi(e){if(e&&e.trim().length>0)return e;E.intro("Klaudius");let t=await E.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return E.isCancel(t)&&(E.cancel("Setup cancelled. No files written."),process.exit(0)),t}function ki(e){let t=fi(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let s of n)if(t.startsWith(s))return`Inside ${s.slice(0,-1)} (system-managed directory).`}}function wi(){if(process.platform!=="win32")return!1;try{return ut("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Ai(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Ei(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(E.outro(p.green(p.bold("Project ready."))),console.log(p.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let a=`cd ${Xe(n)}`;console.log(` ${p.cyan(a)}${" ".repeat(Math.max(1,27-a.length))}${p.dim("# go into your project folder")}`)}console.log(` ${p.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${p.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(p.bold(`Some starter prompts for ${o}:`)),i.blank(),console.log(` ${p.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${p.cyan(`I know I'm ready to start using Klaudius."`)}`),i.blank(),console.log(` ${p.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.blank(),console.log(` ${p.cyan('"Run the pipeline for one client."')}`),console.log(p.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),i.blank(),e.aiAgent!=="codex"&&(console.log(p.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(p.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),i.blank())}import{access as Pi,readFile as bi}from"fs/promises";import{join as pt,resolve as Ti}from"path";import H from"picocolors";async function bn(e){let t=e.target?Ti(process.cwd(),e.target):process.cwd(),n=await Pn(pt(t,".env")),s=await Pn(pt(t,"package.json"));(!n||!s)&&(i.error("This doesn't look like a Klaudius project."),i.detail(`Path: ${t}`),n||i.detail("Missing: .env"),s||i.detail("Missing: package.json"),i.blank(),i.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),i.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{F(await bi(pt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let a=await qe(t);i.blank(),i.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let l=[];if(a.npm==="failed"&&l.push("npm"),a.pip==="failed"&&l.push("pip"),a.playwright==="failed"&&l.push("playwright"),a.patchright==="failed"&&l.push("patchright"),l.length===0){i.blank(),console.log(H.green(H.bold("All dependencies installed."))),console.log(H.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(H.yellow(H.bold(`${l.join(", ")} still failing.`))),i.blank();for(let[r,y]of Object.entries(a.hints??{}))console.log(H.yellow(`Likely cause of ${r} failure:`)),console.log(H.dim(` ${y}`)),i.blank();let c=o==="codex"?"codex":"claude",d=o==="codex"?"Codex":"Claude Code",u=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(H.dim("Options:")),console.log(H.dim(` \u2022 Open ${d} in this folder (\`${c}\`) and paste:`)),console.log(H.cyan(` "Finish my Klaudius install \u2014 ${l.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(H.dim(` (Don't have ${d} yet? Install with: \`${u}\`)`)),console.log(H.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(H.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function Pn(e){try{return await Pi(e),!0}catch{return!1}}import{readFile as Si,writeFile as ft,access as _i}from"fs/promises";import{join as Pe}from"path";import*as q from"@clack/prompts";import X from"picocolors";import{mkdir as Ii}from"fs/promises";import{spawnSync as Tn}from"child_process";async function Sn(e){let t=e.projectRoot??process.cwd(),n=Pe(t,".env"),s=Pe(t,".mcp.json"),o=Pe(t,".codex","config.toml"),a=await mt(Pe(t,".klaudius","manifest.json")),l=await mt(n);!a&&!l&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=ne();c.ok||(i.error(c.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let d={};try{let A=await Si(n,"utf-8");d=F(A)}catch{i.warn("No .env found. Starting from an empty configuration.")}let u=Dt(d);Object.keys(d).length>0&&(u.pipelineModes??=["classic"]),q.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let r=await R(u),y=u.aiAgent??"claude-code";if(r.aiAgent&&r.aiAgent!==y&&(i.error(`Switching AI coding agent (${y} \u2192 ${r.aiAgent}) isn't supported via configure.`),i.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),i.blank(),console.log(` ${X.cyan("npx klaudius@latest init <new-folder>")} ${X.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),r.supabaseUrl!==d.SUPABASE_URL||r.supabaseServiceKey!==d.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let A=await ke({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});A.ok||(i.error(A.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let g=te(r.googlePlacesApiKey??"");if(g.changed&&r.googlePlacesApiKey){i.heading("Checking your Google Places API key");let A=await we(r.googlePlacesApiKey);if(A.ok){if(g.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let b of g.repairs)i.detail(` ${b}`);i.detail("These come from keys that were transcribed rather than copied.")}r.googlePlacesApiKey=g.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(A.message??"Google rejected the Google Places API key"),i.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),i.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Ci(r,d)){let A=q.spinner();A.start("Validating email credentials (SMTP + IMAP)");let b=r.emailProvider&&r.emailProvider!=="custom"?r.emailProvider:pe(r.emailSmtpHost),S=await ie({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort,usesAccountPassword:b?V[b].usesAccountPassword:void 0});S.ok?A.stop("Email credentials accepted (SMTP + IMAP)"):(A.stop(S.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(S.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await ft(n,Me(r),"utf-8"),i.success("Updated .env"),r.aiAgent==="codex"?(await Ii(Pe(t,".codex"),{recursive:!0}),await ft(o,He(r),"utf-8"),i.success("Updated .codex/config.toml")):(await ft(s,De(r),"utf-8"),i.success("Updated .mcp.json"),await Je(t,"supabase")),r.emailAuth==="oauth-microsoft"&&r.outreachEnabled&&r.outreachChannels?.includes("email")){let A=await z();if(!(A!==null&&Tn(A.command[0],[...A.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!A)i.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),i.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let S=await q.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});q.isCancel(S)||!S?i.detail(`Skipped. Connect it any time with: ${A.command.join(" ")} scripts/ms_oauth.py login`):Tn(A.command[0],[...A.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?i.success("Outlook mailbox connected."):(i.warn("The Microsoft sign-in didn't complete."),i.detail(`Connect it any time with: ${A.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),q.outro(X.green("Configuration updated.")),await xi(t,a)}function Ci(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];return n.some(([s])=>s===void 0||s==="")?!1:n.some(([s,o])=>String(s)!==(t[o]??""))}async function xi(e,t){let n=await mt(Pe(e,"node_modules"));i.blank(),t?n||(i.detail("Your project files are in place but dependencies aren't installed yet."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${X.cyan("npx klaudius@latest install")} ${X.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${X.cyan("npx klaudius@latest doctor")} ${X.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${X.cyan("npx klaudius@latest init")} ${X.dim("# pick Resume when prompted")}`),i.blank())}async function mt(e){try{return await _i(e),!0}catch{return!1}}import{copyFile as _n,mkdir as In,readFile as Qe,rm as Ie,writeFile as ht,access as Cn}from"fs/promises";import{dirname as xn,join as N}from"path";import{tmpdir as Ri}from"os";import*as be from"@clack/prompts";import gt from"picocolors";var Ze="0.24.1";async function Rn(e){let t=e.projectRoot??process.cwd(),n=await Gt(t);n||(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let k of je)delete n.files[k];let s,o=N(t,".env"),a,l;try{a=await Qe(o,"utf-8"),l=F(a)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=l.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=Mt(a,l,Lt);c!==null&&(await ht(o,c,"utf-8"),i.detail("Backfilled new env keys")),await Ve("update",Ze),be.intro(`Update from ${n.templateVersion} \u2192 ${Ze}`);let u=l.AI_AGENT==="codex"?"codex":"claude-code",r=N(Ri(),`klaudius-update-${process.pid}-${Date.now()}`),y;try{i.heading("Downloading the latest Klaudius template");let k=await Ke({licenseKey:s,machineId:_e(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:u,destDir:r});i.success(`Fetched ${k.filesExtracted} canonical files`),y=r}catch(k){i.error(k.message),i.detail("Update aborted. Your project is unchanged."),await Ie(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let g=await Oi(y,t,n),A=!1,b=g.find(k=>k.path===".gitignore"&&k.state==="conflict");if(b){let k=N(t,".gitignore"),f=await Qe(k,"utf-8"),h=await Qe(N(y,".gitignore"),"utf-8"),{merged:m,added:w}=vi(f,h);w.length>0&&await ht(k,m,"utf-8"),n.files[".gitignore"]=b.canonicalHash,b.state="gitignore-merged",A=!0,i.detail(w.length>0?`.gitignore auto-merged: kept all your lines, appended ${K(w.length,"new canonical pattern")}: ${w.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let S=g.filter(k=>k.state==="new"),C=g.filter(k=>k.state==="clean-update"),O=g.filter(k=>k.state==="user-only"),T=g.filter(k=>k.state==="conflict"),W=g.filter(k=>k.state==="no-change"),G=g.filter(k=>k.state==="locally-deleted"),P=g.filter(k=>k.state==="removed-clean"),ee=g.filter(k=>k.state==="removed-modified"),D=[...T,...G,...ee],de=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${K(W.length,"file")} unchanged`),i.detail(`${K(S.length,"new file")}`),i.detail(`${K(C.length,"file")} updated cleanly (no local edits)`),i.detail(`${K(O.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${K(P.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${K(T.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${K(G.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${K(ee.length,"file")} removed upstream but edited locally (need your decision)`),de>0&&(i.detail(`${K(de,"file")} kept deleted (previously resolved \u2014 skipped)`),de<=10))for(let k of n.ignored)i.detail(` kept deleted: ${k}`);if(S.length===0&&C.length===0&&P.length===0&&D.length===0&&!A){i.blank(),be.outro(gt.green("Already up to date.")),await Ie(r,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let k of[...S,...C]){let f=N(y,k.path),h=N(t,k.path);await In(xn(h),{recursive:!0}),await _n(f,h),n.files[k.path]=k.canonicalHash}S.length+C.length>0&&i.success(`Wrote ${K(S.length+C.length,"file")}`);for(let k of P){let f=N(t,k.path);await Ie(f,{force:!0}),delete n.files[k.path]}if(P.length>0&&i.success(`Deleted ${K(P.length,"file")} removed upstream`),D.length>0){i.blank(),i.heading(`${D.length} conflict(s) need resolution`);let k=N(t,".klaudius","incoming");try{await Ie(k,{recursive:!0,force:!0})}catch{}for(let h of[...T,...G]){let m=N(y,h.path),w=N(k,h.path);await In(xn(w),{recursive:!0}),await _n(m,w)}let f=new Map;for(let h of T){let m=await Qt(t,h.path),w=m!==null?await Qe(N(y,h.path),"utf-8"):"";m!==null&&(at(m)||at(w))?f.set(h.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+h.path+"` directly._"]):m===null?f.set(h.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._"]):h.manifestHash&&jt(m)!==h.manifestHash?f.set(h.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/"+h.path+"` directly._"]):f.set(h.path,Zt(m,w))}await ht(N(t,".klaudius","conflicts.md"),$i(D,n.templateVersion,Ze,f),"utf-8"),T.length+G.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),D.length===0&&(n.templateVersion=Ze),await Ue(t,n);try{await Ge(t,y,await le(y))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),D.length===0)be.outro(gt.green("Update complete."));else{let k=u==="codex"?"Codex":"Claude Code";be.outro(gt.yellow(`${D.length} conflict(s) staged. Open ${k} in this project and ask:
89
+ `:"",h=r.aiAgent==="codex"?"codex":"claude",m=r.aiAgent==="codex"?"Codex":"Claude Code",w=r.aiAgent==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";T.length>0&&(console.log(p.dim(`Easiest fix \u2014 let ${m} finish it for you:`)),i.blank(),f&&process.stdout.write(f),console.log(` ${p.cyan(h)} ${p.dim(`# open ${m} in this folder`)}`),console.log(p.dim(" Then paste:")),console.log(p.cyan(` "Finish my Klaudius install \u2014 ${T.join(", ")} failed during setup. Debug the install output, retry, then run npx klaudius@latest doctor."`)),i.blank(),console.log(p.dim(` (Don't have ${m} yet? Install with: \`${w}\`)`)),i.blank(),console.log(p.dim("Or do it yourself:")),i.blank(),f&&process.stdout.write(f),console.log(` ${p.cyan("npx klaudius@latest install")} ${p.dim("# retry the failing installers")}`),console.log(` ${p.cyan("npx klaudius@latest doctor")} ${p.dim("# verify everything")}`),i.blank()),C&&(console.log(p.dim("For the schema failure specifically, apply scripts/schema.sql in the Supabase SQL editor:")),console.log(` ${p.cyan(O)}`),console.log(p.dim(" Open scripts/schema.sql, copy the contents, paste into the editor, click Run.")),i.blank()),T.includes("pip")&&!W.pip&&(console.log(p.dim("If pip fails again with a build error, check `python3 --version` \u2014 Klaudius needs")),console.log(p.dim(`Python 3.10+. Install a newer one from ${Ai()}`)),console.log(p.dim("and open a fresh Terminal before retrying.")),i.blank());let v=["npm","playwright","patchright"].filter(j=>T.includes(j)&&!W[j]);if(v.length>0){let j=v.length===1?"keeps":"keep";console.log(p.dim(`If ${v.join(" / ")} ${j} failing with network errors (ECONNRESET,`)),console.log(p.dim("ETIMEDOUT, ENOTFOUND), they're transient \u2014 try a different network or your")),console.log(p.dim("phone's hotspot, then re-run `npx klaudius@latest install`.")),i.blank()}g&&(console.log(p.dim(`Note: email outreach was skipped during setup. Once the install succeeds, ask ${m}`)),console.log(p.dim("to finish setting it up \u2014 your email details are saved in .env.")),i.blank()),console.log(p.dim("Stuck? Email hello@klaudius.dev with the last ~20 lines of the install output.")),i.blank();return}if(Ei(r,n,e.target),g){let f=r.aiAgent==="codex"?"Codex":"Claude Code";console.log(p.yellow("Email outreach is parked \u2014 the credential check didn't pass during setup.")),console.log(p.dim(`Your details are saved in .env. To finish it, ask ${f}:`)),console.log(p.cyan(' "Set up my email outreach. My details are in .env (EMAIL_*) but the')),console.log(p.cyan(" SMTP/IMAP check failed during init. Work out the right servers for my")),console.log(p.cyan(" provider, test them with scripts/gmail.py, fix .env, re-add email to")),console.log(p.cyan(" OUTREACH_CHANNELS and OUTREACH_PRIORITY, set OUTREACH_ENABLED=true,")),console.log(p.cyan(' and send a test email to my own address to confirm."')),r.outreachEnabled&&(r.outreachChannels??[]).length>0&&(i.blank(),console.log(p.yellow(`Note: your other channel(s) \u2014 ${(r.outreachChannels??[]).join(", ")} \u2014 are still live, so the pipeline WILL still pitch businesses.`))),i.blank()}}async function $(e,t){await ct(e,{recursive:!0}),await lt(B(e,".env"),Me(t),"utf-8"),t.aiAgent==="codex"?(await ct(B(e,".codex"),{recursive:!0}),await lt(B(e,".codex","config.toml"),He(t),"utf-8")):(await lt(B(e,".mcp.json"),De(t),"utf-8"),await Je(e,"supabase"))}async function hi(e){try{(await dt(e)).isDirectory()||(i.error(`Target exists but is not a directory: ${e}`),process.exit(1))}catch{return{kind:"fresh"}}let t=await An(e),n=t.filter(c=>!c.startsWith(".DS_Store"));if(n.length===0)return{kind:"fresh"};let s=new Set([".env",".mcp.json",".claude",".codex"]),o=n.every(c=>s.has(c)),a=n.includes(".env"),l=t.includes(".klaudius");if(o&&a&&!l)return{kind:"partial",envPath:B(e,".env")};if(l&&a){let c=!0;try{c=!(await dt(B(e,"node_modules"))).isDirectory()}catch{c=!0}return{kind:"scaffolded",nodeModulesMissing:c}}return{kind:"occupied",entries:n}}async function gi(e){i.blank(),i.warn(`Found a partial setup at ${p.bold(e)}.`),i.detail(`A previous init wrote ${p.bold(".env")} but didn't finish scaffolding.`),i.blank();let t=await E.select({message:`How would you like to proceed? ${p.dim("(\u2191 \u2193 arrow keys, then Enter)")}`,initialValue:"resume",options:[{value:"resume",label:"Resume \u2014 use my saved .env values, skip the wizard, retry validation"},{value:"redo",label:"Restart \u2014 walk through the wizard again (existing values pre-filled as defaults)"}]});return E.isCancel(t)&&(E.cancel("Setup cancelled. Existing .env left in place."),process.exit(0)),t}async function yi(e){if(e&&e.trim().length>0)return e;E.intro("Klaudius");let t=await E.text({message:"Enter your Klaudius license key",placeholder:"KLAU-XXXX-XXXX-XXXX-XXXX",validate:n=>n.trim().length===0?"Required. Check your purchase confirmation email.":void 0});return E.isCancel(t)&&(E.cancel("Setup cancelled. No files written."),process.exit(0)),t}function ki(e){let t=fi(e);if(process.platform==="win32"){let n=t.toLowerCase();if(n.startsWith("c:\\windows\\"))return"Inside C:\\Windows (Windows system directory).";if(n.startsWith("c:\\program files\\"))return"Inside C:\\Program Files (Windows protected directory).";if(n.startsWith("c:\\program files (x86)\\"))return"Inside C:\\Program Files (x86) (Windows protected directory).";if(n.startsWith("c:\\programdata\\"))return"Inside C:\\ProgramData (Windows protected directory)."}else{let n=["/System/","/usr/","/bin/","/sbin/"];for(let s of n)if(t.startsWith(s))return`Inside ${s.slice(0,-1)} (system-managed directory).`}}function wi(){if(process.platform!=="win32")return!1;try{return ut("net",["session"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Ai(){switch(process.platform){case"win32":return"https://www.python.org/downloads/windows/";case"darwin":return"https://www.python.org/downloads/macos/";default:return"https://www.python.org/downloads/"}}function Ei(e,t,n){let s=e.aiAgent==="codex"?"codex":"claude",o=e.aiAgent==="codex"?"Codex":"Claude Code";if(E.outro(p.green(p.bold("Project ready."))),console.log(p.bold("Next steps:")),i.blank(),t!==process.cwd()&&n){let a=`cd ${Xe(n)}`;console.log(` ${p.cyan(a)}${" ".repeat(Math.max(1,27-a.length))}${p.dim("# go into your project folder")}`)}console.log(` ${p.cyan(s)}${" ".repeat(Math.max(1,27-s.length))}${p.dim(`# opens ${o} in this project`)}`),i.blank(),console.log(p.bold(`Some starter prompts for ${o}:`)),i.blank(),console.log(` ${p.cyan(`"Run klaudius doctor and fix anything that's missing or broken, so`)}`),console.log(` ${p.cyan(`I know I'm ready to start using Klaudius."`)}`),i.blank(),console.log(` ${p.cyan('"Open DOCS.html in my browser so I can read the docs."')}`),i.blank(),console.log(` ${p.cyan('"Run the pipeline for one client."')}`),console.log(p.dim(e.outreachEnabled?" \u2192 finds a business, builds their site, deploys it, and pitches them.":" \u2192 finds a business, builds their site, deploys it. Outreach is off \u2014 nothing is sent.")),i.blank(),e.aiAgent!=="codex"&&(console.log(p.dim("Prefer a more comfortable interface than a terminal? Claude Code also comes as")),console.log(p.dim("a desktop app \u2014 same tool, friendlier: https://code.claude.com/docs/en/setup")),i.blank())}import{access as Pi,readFile as bi}from"fs/promises";import{join as pt,resolve as Ti}from"path";import H from"picocolors";async function bn(e){let t=e.target?Ti(process.cwd(),e.target):process.cwd(),n=await Pn(pt(t,".env")),s=await Pn(pt(t,"package.json"));(!n||!s)&&(i.error("This doesn't look like a Klaudius project."),i.detail(`Path: ${t}`),n||i.detail("Missing: .env"),s||i.detail("Missing: package.json"),i.blank(),i.detail("Run `npx klaudius@latest init` to scaffold a new project first,"),i.detail("or cd into an existing project directory and re-run this command."),process.exit(1));let o="claude-code";try{F(await bi(pt(t,".env"),"utf-8")).AI_AGENT==="codex"&&(o="codex")}catch{}i.heading("Installing dependencies");let a=await qe(t);i.blank(),i.detail(`npm: ${a.npm}, pip: ${a.pip}, playwright: ${a.playwright}, patchright: ${a.patchright}`);let l=[];if(a.npm==="failed"&&l.push("npm"),a.pip==="failed"&&l.push("pip"),a.playwright==="failed"&&l.push("playwright"),a.patchright==="failed"&&l.push("patchright"),l.length===0){i.blank(),console.log(H.green(H.bold("All dependencies installed."))),console.log(H.dim("Run `npx klaudius@latest doctor` to verify everything else (credentials, files).")),i.blank();return}i.blank(),console.log(H.yellow(H.bold(`${l.join(", ")} still failing.`))),i.blank();for(let[r,y]of Object.entries(a.hints??{}))console.log(H.yellow(`Likely cause of ${r} failure:`)),console.log(H.dim(` ${y}`)),i.blank();let c=o==="codex"?"codex":"claude",d=o==="codex"?"Codex":"Claude Code",u=o==="codex"?"npm install -g @openai/codex":"npm install -g @anthropic-ai/claude-code";console.log(H.dim("Options:")),console.log(H.dim(` \u2022 Open ${d} in this folder (\`${c}\`) and paste:`)),console.log(H.cyan(` "Finish my Klaudius install \u2014 ${l.join(", ")} failed. Debug the install output, retry, then run npx klaudius@latest doctor."`)),console.log(H.dim(` (Don't have ${d} yet? Install with: \`${u}\`)`)),console.log(H.dim(" \u2022 Or run `npx klaudius@latest doctor` for a structured diagnostic.")),console.log(H.dim(" \u2022 Or email hello@klaudius.dev with the last ~20 lines of the install output above.")),i.blank(),process.exitCode=1}async function Pn(e){try{return await Pi(e),!0}catch{return!1}}import{readFile as Si,writeFile as ft,access as _i}from"fs/promises";import{join as Pe}from"path";import*as q from"@clack/prompts";import X from"picocolors";import{mkdir as Ii}from"fs/promises";import{spawnSync as Tn}from"child_process";async function Sn(e){let t=e.projectRoot??process.cwd(),n=Pe(t,".env"),s=Pe(t,".mcp.json"),o=Pe(t,".codex","config.toml"),a=await mt(Pe(t,".klaudius","manifest.json")),l=await mt(n);!a&&!l&&(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json` or `.env` in this folder. Run `npx klaudius@latest init` first."),process.exit(1));let c=ne();c.ok||(i.error(c.message??"Node.js version check failed."),i.blank(),i.detail("Once you've installed Node.js 22.15+, re-run `npx klaudius@latest configure` in this folder."),process.exit(1));let d={};try{let A=await Si(n,"utf-8");d=F(A)}catch{i.warn("No .env found. Starting from an empty configuration.")}let u=Dt(d);Object.keys(d).length>0&&(u.pipelineModes??=["classic"]),q.intro("Reconfigure Klaudius"),i.detail("Press Enter on any prompt to keep its current value."),i.blank();let r=await R(u),y=u.aiAgent??"claude-code";if(r.aiAgent&&r.aiAgent!==y&&(i.error(`Switching AI coding agent (${y} \u2192 ${r.aiAgent}) isn't supported via configure.`),i.detail("configure only rewrites .env / MCP config \u2014 it doesn't restructure the scaffolded files. To switch, run:"),i.blank(),console.log(` ${X.cyan("npx klaudius@latest init <new-folder>")} ${X.dim("# pick the new agent in the wizard")}`),i.blank(),i.detail(".env is unchanged."),process.exit(1)),r.supabaseUrl!==d.SUPABASE_URL||r.supabaseServiceKey!==d.SUPABASE_SERVICE_KEY){i.heading("Re-validating Supabase credentials");let A=await ke({url:r.supabaseUrl,serviceKey:r.supabaseServiceKey});A.ok||(i.error(A.message??"Supabase check failed"),i.warn("Aborting. .env not modified."),process.exit(1)),i.success("Supabase credentials accepted")}let g=te(r.googlePlacesApiKey??"");if(g.changed&&r.googlePlacesApiKey){i.heading("Checking your Google Places API key");let A=await we(r.googlePlacesApiKey);if(A.ok){if(g.repairs.length>0){i.warn("Corrected look-alike characters in your Google Places API key:");for(let b of g.repairs)i.detail(` ${b}`);i.detail("These come from keys that were transcribed rather than copied.")}r.googlePlacesApiKey=g.value,i.success("Google accepted the key \u2014 writing the corrected value to .env")}else i.error(A.message??"Google rejected the Google Places API key"),i.warn("Writing the key exactly as you entered it \u2014 nothing has been guessed on your behalf."),i.detail("Re-run `npx klaudius@latest configure` with a key copied straight from the Cloud Console's copy button.")}if(Ci(r,d)){let A=q.spinner();A.start("Validating email credentials (SMTP + IMAP)");let b=r.emailProvider&&r.emailProvider!=="custom"?r.emailProvider:pe(r.emailSmtpHost),S=await ie({emailAddress:r.emailAddress,emailPassword:r.emailPassword,emailSmtpHost:r.emailSmtpHost,emailSmtpPort:r.emailSmtpPort,emailImapHost:r.emailImapHost,emailImapPort:r.emailImapPort,usesAccountPassword:b?V[b].usesAccountPassword:void 0});S.ok?A.stop("Email credentials accepted (SMTP + IMAP)"):(A.stop(S.message??"Email check failed",2),i.warn("Writing the email settings exactly as you entered them \u2014 not verified."),i.detail(S.failureKind==="network"?"This looks like a network/host problem, not a password problem \u2014 check the SMTP/IMAP hosts and your connection, then run `npx klaudius@latest doctor`.":"Run `npx klaudius@latest doctor` \u2014 it tries your provider's alternate regional servers and names the likely fix."))}if(await ft(n,Me(r),"utf-8"),i.success("Updated .env"),r.aiAgent==="codex"?(await Ii(Pe(t,".codex"),{recursive:!0}),await ft(o,He(r),"utf-8"),i.success("Updated .codex/config.toml")):(await ft(s,De(r),"utf-8"),i.success("Updated .mcp.json"),await Je(t,"supabase")),r.emailAuth==="oauth-microsoft"&&r.outreachEnabled&&r.outreachChannels?.includes("email")){let A=await z();if(!(A!==null&&Tn(A.command[0],[...A.command.slice(1),"scripts/ms_oauth.py","status"],{cwd:t,encoding:"utf-8",timeout:6e4,windowsHide:!0}).status===0))if(i.blank(),!A)i.warn("Outlook mailbox not connected \u2014 no Python interpreter found to run the sign-in."),i.detail("Once Python is installed: python3 scripts/ms_oauth.py login");else{let S=await q.confirm({message:"Connect your Outlook / Microsoft 365 mailbox now? (one-time browser sign-in)",initialValue:!0});q.isCancel(S)||!S?i.detail(`Skipped. Connect it any time with: ${A.command.join(" ")} scripts/ms_oauth.py login`):Tn(A.command[0],[...A.command.slice(1),"-u","scripts/ms_oauth.py","login"],{cwd:t,stdio:"inherit",timeout:39e5}).status===0?i.success("Outlook mailbox connected."):(i.warn("The Microsoft sign-in didn't complete."),i.detail(`Connect it any time with: ${A.command.join(" ")} scripts/ms_oauth.py login`))}}i.blank(),q.outro(X.green("Configuration updated.")),await xi(t,a)}function Ci(e,t){let n=[[e.emailAddress,"EMAIL_ADDRESS"],[e.emailPassword,"EMAIL_PASSWORD"],[e.emailSmtpHost,"EMAIL_SMTP_HOST"],[e.emailSmtpPort,"EMAIL_SMTP_PORT"],[e.emailImapHost,"EMAIL_IMAP_HOST"],[e.emailImapPort,"EMAIL_IMAP_PORT"]];return n.some(([s])=>s===void 0||s==="")?!1:n.some(([s,o])=>String(s)!==(t[o]??""))}async function xi(e,t){let n=await mt(Pe(e,"node_modules"));i.blank(),t?n||(i.detail("Your project files are in place but dependencies aren't installed yet."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${X.cyan("npx klaudius@latest install")} ${X.dim("# (re-)installs npm + pip + browsers; idempotent")}`),i.blank(),i.detail("Then verify with:"),i.blank(),console.log(` ${X.cyan("npx klaudius@latest doctor")} ${X.dim("# checks Node / Python / installers / credentials")}`),i.blank()):(i.detail("Looks like a previous `klaudius init` saved your .env but didn't finish scaffolding."),i.detail("To finish setup, run:"),i.blank(),console.log(` ${X.cyan("npx klaudius@latest init")} ${X.dim("# pick Resume when prompted")}`),i.blank())}async function mt(e){try{return await _i(e),!0}catch{return!1}}import{copyFile as _n,mkdir as In,readFile as Qe,rm as Ie,writeFile as ht,access as Cn}from"fs/promises";import{dirname as xn,join as N}from"path";import{tmpdir as Ri}from"os";import*as be from"@clack/prompts";import gt from"picocolors";var Ze="0.24.2";async function Rn(e){let t=e.projectRoot??process.cwd(),n=await Gt(t);n||(i.error("This doesn't look like a Klaudius project."),i.detail("Expected `.klaudius/manifest.json`. Run `npx klaudius@latest init` first."),process.exit(1));for(let k of je)delete n.files[k];let s,o=N(t,".env"),a,l;try{a=await Qe(o,"utf-8"),l=F(a)}catch{i.error("Couldn't read .env from this directory."),i.detail("Are you running `klaudius update` from inside a Klaudius project?"),process.exit(1)}s=l.KLAUDIUS_LICENSE_KEY??"",s||(i.error("Couldn't find KLAUDIUS_LICENSE_KEY in your .env file."),i.detail("This file is created by `npx klaudius@latest init`. If your project predates"),i.detail("the licence-gated template (CLI version 0.1.x), re-run `npx klaudius@latest init`"),i.detail("in a sibling directory, then copy KLAUDIUS_LICENSE_KEY from its .env."),process.exit(1));let c=Mt(a,l,Lt);c!==null&&(await ht(o,c,"utf-8"),i.detail("Backfilled new env keys")),await Ve("update",Ze),be.intro(`Update from ${n.templateVersion} \u2192 ${Ze}`);let u=l.AI_AGENT==="codex"?"codex":"claude-code",r=N(Ri(),`klaudius-update-${process.pid}-${Date.now()}`),y;try{i.heading("Downloading the latest Klaudius template");let k=await Ke({licenseKey:s,machineId:_e(),hostname:process.env.HOSTNAME??process.env.COMPUTERNAME,os:`${process.platform}-${process.arch}`,agent:u,destDir:r});i.success(`Fetched ${k.filesExtracted} canonical files`),y=r}catch(k){i.error(k.message),i.detail("Update aborted. Your project is unchanged."),await Ie(r,{recursive:!0,force:!0}).catch(()=>{}),process.exit(1)}let g=await Oi(y,t,n),A=!1,b=g.find(k=>k.path===".gitignore"&&k.state==="conflict");if(b){let k=N(t,".gitignore"),f=await Qe(k,"utf-8"),h=await Qe(N(y,".gitignore"),"utf-8"),{merged:m,added:w}=vi(f,h);w.length>0&&await ht(k,m,"utf-8"),n.files[".gitignore"]=b.canonicalHash,b.state="gitignore-merged",A=!0,i.detail(w.length>0?`.gitignore auto-merged: kept all your lines, appended ${K(w.length,"new canonical pattern")}: ${w.join(", ")}`:".gitignore: yours already covers every canonical pattern \u2014 kept as-is")}let S=g.filter(k=>k.state==="new"),C=g.filter(k=>k.state==="clean-update"),O=g.filter(k=>k.state==="user-only"),T=g.filter(k=>k.state==="conflict"),W=g.filter(k=>k.state==="no-change"),G=g.filter(k=>k.state==="locally-deleted"),P=g.filter(k=>k.state==="removed-clean"),ee=g.filter(k=>k.state==="removed-modified"),D=[...T,...G,...ee],de=n.ignored?.length??0;if(i.blank(),i.heading("Change summary"),i.detail(`${K(W.length,"file")} unchanged`),i.detail(`${K(S.length,"new file")}`),i.detail(`${K(C.length,"file")} updated cleanly (no local edits)`),i.detail(`${K(O.length,"file")} you've edited (no upstream change \u2014 left alone)`),i.detail(`${K(P.length,"file")} removed upstream (deleted cleanly)`),i.detail(`${K(T.length,"file")} with conflicts (you edited AND we have a new version)`),i.detail(`${K(G.length,"file")} you've deleted locally (canonical still ships them \u2014 need your decision)`),i.detail(`${K(ee.length,"file")} removed upstream but edited locally (need your decision)`),de>0&&(i.detail(`${K(de,"file")} kept deleted (previously resolved \u2014 skipped)`),de<=10))for(let k of n.ignored)i.detail(` kept deleted: ${k}`);if(S.length===0&&C.length===0&&P.length===0&&D.length===0&&!A){i.blank(),be.outro(gt.green("Already up to date.")),await Ie(r,{recursive:!0,force:!0}).catch(()=>{});return}i.blank(),i.heading("Applying clean updates");for(let k of[...S,...C]){let f=N(y,k.path),h=N(t,k.path);await In(xn(h),{recursive:!0}),await _n(f,h),n.files[k.path]=k.canonicalHash}S.length+C.length>0&&i.success(`Wrote ${K(S.length+C.length,"file")}`);for(let k of P){let f=N(t,k.path);await Ie(f,{force:!0}),delete n.files[k.path]}if(P.length>0&&i.success(`Deleted ${K(P.length,"file")} removed upstream`),D.length>0){i.blank(),i.heading(`${D.length} conflict(s) need resolution`);let k=N(t,".klaudius","incoming");try{await Ie(k,{recursive:!0,force:!0})}catch{}for(let h of[...T,...G]){let m=N(y,h.path),w=N(k,h.path);await In(xn(w),{recursive:!0}),await _n(m,w)}let f=new Map;for(let h of T){let m=await Qt(t,h.path),w=m!==null?await Qe(N(y,h.path),"utf-8"):"";m!==null&&(at(m)||at(w))?f.set(h.path,["_Binary or non-text file \u2014 no text diff available. Compare your copy against the staged `.klaudius/incoming/"+h.path+"` directly._"]):m===null?f.set(h.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._"]):h.manifestHash&&jt(m)!==h.manifestHash?f.set(h.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/"+h.path+"` directly._"]):f.set(h.path,Zt(m,w))}await ht(N(t,".klaudius","conflicts.md"),$i(D,n.templateVersion,Ze,f),"utf-8"),T.length+G.length>0&&i.detail("Staged canonical versions to .klaudius/incoming/"),i.detail("Wrote conflict report to .klaudius/conflicts.md")}n.updatedAt=new Date().toISOString(),D.length===0&&(n.templateVersion=Ze),await Ue(t,n);try{await Ge(t,y,await le(y))}catch{i.detail("(couldn't save the base snapshot \u2014 next update's conflict summaries will be unavailable)")}if(i.blank(),D.length===0)be.outro(gt.green("Update complete."));else{let k=u==="codex"?"Codex":"Claude Code";be.outro(gt.yellow(`${D.length} conflict(s) staged. Open ${k} in this project and ask:
90
90
  "Run /resolve-conflicts"`))}await Ie(r,{recursive:!0,force:!0}).catch(()=>{})}async function Oi(e,t,n){let s=await le(e),o=new Set(s),a=new Set(n.ignored??[]),l=[];for(let c of s){if(a.has(c))continue;let d=await ye(N(e,c)),u=n.files[c],r=N(t,c),y;try{await Cn(r),y=await ye(r)}catch{let g=u!==void 0&&!Kt.has(c)?"locally-deleted":"new";l.push({path:c,state:g,canonicalHash:d,manifestHash:u});continue}d===u?y===u?l.push({path:c,state:"no-change",canonicalHash:d,localHash:y,manifestHash:u}):l.push({path:c,state:"user-only",canonicalHash:d,localHash:y,manifestHash:u}):y===u?l.push({path:c,state:"clean-update",canonicalHash:d,localHash:y,manifestHash:u}):l.push({path:c,state:"conflict",canonicalHash:d,localHash:y,manifestHash:u})}for(let c of Object.keys(n.files)){if(o.has(c))continue;let d=n.files[c],u=N(t,c),r;try{await Cn(u),r=await ye(u)}catch{delete n.files[c];continue}r===d?l.push({path:c,state:"removed-clean",localHash:r,manifestHash:d}):l.push({path:c,state:"removed-modified",localHash:r,manifestHash:d})}return l}function K(e,t){return`${e} ${t}${e===1?"":"s"}`}function vi(e,t){let n=e.includes(`\r
91
91
  `)?`\r
92
92
  `:`
@@ -106,4 +106,4 @@ except Exception as e:
106
106
  `));let a=Xi(process.execPath,[n,"pair","--account",o],{cwd:t,stdio:"inherit"});if(a.status===0){console.log(M.green(`Paired '${o}'.`)),console.log(M.dim(`
107
107
  If you haven't already, add '${o}' to WHATSAPP_ACCOUNTS in .env so /outreach round-robins to it. Example:
108
108
  WHATSAPP_ACCOUNTS=primary,${o}
109
- (Skip this if '${o}' is already there or you set it via the init wizard.)`));return}a.error?console.error(M.red(`Pair failed: ${a.error.message}`)):(console.error(M.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(M.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(M.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(M.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as eo}from"child_process";var kt="--use-system-ca";function Mn(){let e=process.env.NODE_OPTIONS??"";if(e.includes(kt)||!ne().ok)return;let n=e?`${e} ${kt}`:kt,s=eo(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});s.signal&&(process.kill(process.pid,s.signal),process.exit(1)),process.exit(s.status??1)}Mn();var no="0.24.1",Z=new to;Z.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(no);Z.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 Rt({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});Z.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").action(async(e,t)=>{try{await En({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(n){console.error("init failed:",n.message),process.exit(1)}});Z.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 bn({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});Z.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await Sn({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});Z.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await Rn({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});Z.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 $n({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});Z.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 Ln({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});Z.parse(process.argv);
109
+ (Skip this if '${o}' is already there or you set it via the init wizard.)`));return}a.error?console.error(M.red(`Pair failed: ${a.error.message}`)):(console.error(M.red(`Pair did not complete (exit ${a.status??"signalled"}). Common causes:`)),console.error(M.dim(" - QR scan window timed out: re-run and scan promptly.")),console.error(M.dim(" - WhatsApp's 4-linked-device limit: open WhatsApp \u2192 Settings \u2192 Linked Devices, unlink an unused entry, then re-run.")),console.error(M.dim(` - Existing daemon couldn't be stopped: check the log at ~/.klaudius/whatsapp/${o}/daemon.log`))),process.exit(a.status??1)}import{spawnSync as eo}from"child_process";var kt="--use-system-ca";function Mn(){let e=process.env.NODE_OPTIONS??"";if(e.includes(kt)||!ne().ok)return;let n=e?`${e} ${kt}`:kt,s=eo(process.execPath,[...process.execArgv,...process.argv.slice(1)],{env:{...process.env,NODE_OPTIONS:n},stdio:"inherit"});s.signal&&(process.kill(process.pid,s.signal),process.exit(1)),process.exit(s.status??1)}Mn();var no="0.24.2",Z=new to;Z.name("klaudius").description("Scaffold and maintain a Klaudius pipeline project").version(no);Z.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 Rt({})}catch(e){console.error("preflight failed:",e.message),process.exit(1)}});Z.command("init").description("Scaffold a new Klaudius project").argument("[target]","Directory to create (defaults to current directory)",".").option("--license <key>","License key (received in your purchase confirmation email)").option("--skip-install","Skip npm/pip/playwright installation").option("--skip-schema","Skip applying schema.sql to your Supabase project").action(async(e,t)=>{try{await En({target:e,license:t.license,skipInstall:!!t.skipInstall,skipSchema:!!t.skipSchema})}catch(n){console.error("init failed:",n.message),process.exit(1)}});Z.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 bn({target:e})}catch(t){console.error("install failed:",t.message),process.exit(1)}});Z.command("configure").description("Re-run the setup wizard with current values pre-filled").action(async()=>{try{await Sn({})}catch(e){console.error("configure failed:",e.message),process.exit(1)}});Z.command("update").description("Pull latest template; produce a conflicts report for any files you've modified").action(async()=>{try{await Rn({})}catch(e){console.error("update failed:",e.message),process.exit(1)}});Z.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 $n({offline:!!e.offline})}catch(t){console.error("doctor failed:",t.message),process.exit(1)}});Z.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 Ln({label:e.label})}catch(t){console.error("pair-whatsapp failed:",t.message),process.exit(1)}});Z.parse(process.argv);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "klaudius",
3
- "version": "0.24.1",
4
- "description": "Scaffold and maintain a Klaudius project — an autonomous web agency pipeline that runs on Claude Code (find, build, deploy, outreach end-to-end).",
3
+ "version": "0.24.2",
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": {
7
7
  "email": "hello@klaudius.dev"