@seoagent-official/seoagent 1.56.2 → 1.56.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,40 +1,40 @@
1
1
  #!/usr/bin/env node
2
- import{Command as Hu}from"commander";import{dirname as Tr,relative as St}from"path";import{intro as Ls,outro as Ns,text as Rr,select as nn,spinner as Fs,isCancel as Se,cancel as ve,confirm as Ds}from"@clack/prompts";var ge=[".env.local",".env.production",".env"],Ln=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var V="@seoagent-official/seoagent",lt=`${V}@latest`;import{homedir as fi}from"os";import{join as he}from"path";var b=".seoagent",Nn=["audit","strategy/clusters","briefs","content","content/images","performance"],ae={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},ct=".claude/settings.json",Fn=".pull-receipt.json",Dn=".ack-queue.json",Un=".sync.lock",Mn=`# SEOAgent local files
2
+ import{Command as Vu}from"commander";import{dirname as jr,relative as St}from"path";import{intro as Ls,outro as Ns,text as Pr,select as nn,spinner as Fs,isCancel as Se,cancel as ve,confirm as Ds}from"@clack/prompts";var ge=[".env.local",".env.production",".env"],Nn=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var J="@seoagent-official/seoagent",lt=`${J}@latest`;import{homedir as fi}from"os";import{join as he}from"path";var b=".seoagent",Fn=["audit","strategy/clusters","briefs","content","content/images","performance"],ae={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},ct=".claude/settings.json",Dn=".pull-receipt.json",Un=".ack-queue.json",Mn=".sync.lock",Bn=`# SEOAgent local files
3
3
  .legacy/
4
4
  content/images/*
5
5
  !content/images/.gitkeep
6
6
  .pull-receipt.json
7
7
  .ack-queue.json
8
8
  .sync.lock
9
- `,mi=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:he(fi(),".config"),F=he(mi,"seoagent"),Z=he(F,"auth.json"),Gt=he(F,"state"),ut=he(F,"update-check.json"),dt=he(F,"projects.json");var je="https://seoagent.com",ye=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):je,C={BASE:ye,PRICING:`${ye}/pricing`,LEAD_API:`${ye}/api/cli/lead`,CLI_AUTH_PAGE:`${ye}/cli/auth`,CLI_AUTH_POLL:`${ye}/api/cli/auth/poll`,CLI_SYNC:`${ye}/api/cli/sync`};import{readFileSync as gi}from"fs";import{fileURLToPath as hi}from"url";import{dirname as yi,join as wi}from"path";var Bn="0.0.0";function ki(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return Bn}function bi(e=t=>gi(t,"utf-8")){try{let t=yi(hi(import.meta.url));return ki(e(wi(t,"package.json")))}catch{return Bn}}var v=bi();function Wt(e=process.argv[1]){let t=process.env.SEOAGENT_INSTALL_FORM;return t==="global"?!0:t==="npx"||!e?!1:(e.split(/[/\\]/).pop()??"").replace(/\.(cmd|ps1|exe)$/i,"").toLowerCase()==="seoagent"}function f(e,t=Wt()){return t?`seoagent ${e}`:`npx -y ${lt} ${e}`}import{randomUUID as _i}from"crypto";import{existsSync as Gn,mkdirSync as Wn,readFileSync as Ci,writeFileSync as Kn}from"fs";import{join as qt}from"path";import{existsSync as $i,readFileSync as Si}from"fs";var pt="---";function vi(e){let t=e.trim();return t===""?"":t==="null"||t==="~"?null:t==="true"?!0:t==="false"?!1:t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):/^-?\d+$/.test(t)||/^-?\d+\.\d+$/.test(t)?Number(t):t}function Le(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==pt)return{data:{},body:e};let n={},r=1;for(;r<t.length;r++){if(t[r].trim()===pt){r++;break}let o=t[r],i=o.indexOf(":");if(i===-1)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1);s&&(n[s]=vi(a))}return{data:n,body:t.slice(r).join(`
9
+ `,mi=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:he(fi(),".config"),F=he(mi,"seoagent"),Z=he(F,"auth.json"),Gt=he(F,"state"),ut=he(F,"update-check.json"),dt=he(F,"projects.json");var je="https://seoagent.com",ye=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):je,C={BASE:ye,PRICING:`${ye}/pricing`,LEAD_API:`${ye}/api/cli/lead`,CLI_AUTH_PAGE:`${ye}/cli/auth`,CLI_AUTH_POLL:`${ye}/api/cli/auth/poll`,CLI_SYNC:`${ye}/api/cli/sync`};import{readFileSync as gi}from"fs";import{fileURLToPath as hi}from"url";import{dirname as yi,join as wi}from"path";var Gn="0.0.0";function ki(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return Gn}function bi(e=t=>gi(t,"utf-8")){try{let t=yi(hi(import.meta.url));return ki(e(wi(t,"package.json")))}catch{return Gn}}var v=bi();function Wt(e=process.argv[1]){let t=process.env.SEOAGENT_INSTALL_FORM;return t==="global"?!0:t==="npx"||!e?!1:(e.split(/[/\\]/).pop()??"").replace(/\.(cmd|ps1|exe)$/i,"").toLowerCase()==="seoagent"}function f(e,t=Wt()){return t?`seoagent ${e}`:`npx -y ${lt} ${e}`}import{randomUUID as _i}from"crypto";import{existsSync as Wn,mkdirSync as Kn,readFileSync as Ci,writeFileSync as qn}from"fs";import{join as qt}from"path";import{existsSync as $i,readFileSync as Si}from"fs";var pt="---";function vi(e){let t=e.trim();return t===""?"":t==="null"||t==="~"?null:t==="true"?!0:t==="false"?!1:t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):/^-?\d+$/.test(t)||/^-?\d+\.\d+$/.test(t)?Number(t):t}function Le(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==pt)return{data:{},body:e};let n={},r=1;for(;r<t.length;r++){if(t[r].trim()===pt){r++;break}let o=t[r],i=o.indexOf(":");if(i===-1)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1);s&&(n[s]=vi(a))}return{data:n,body:t.slice(r).join(`
10
10
  `)}}function ft(e){if(!$i(e))return null;try{return Le(Si(e,"utf-8"))}catch{return null}}function xi(e){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return String(e);let t=String(e);return t===""||/[:#\[\]{}&*!|>'"%@`,]/.test(t)||/^\s|\s$/.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function Kt(e,t=""){let n=[pt];for(let[o,i]of Object.entries(e))i!==void 0&&n.push(`${o}: ${xi(i)}`);n.push(pt);let r=t.length===0?"":t.startsWith(`
11
11
  `)?t:`
12
12
  ${t}`;return n.join(`
13
13
  `)+r+(r.endsWith(`
14
14
  `)?"":`
15
- `)}var Ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ht(){return _i()}var Ai=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),Ii="project.md";function Ne(e){return qt(e,b)}function mt(e){return qt(Ne(e),Ii)}function qn(e){return Gn(mt(e))}function S(e){let t=ft(mt(e));if(!t)return null;let n=t.data;if(typeof n.domain!="string"||!n.domain)return null;let r=typeof n.image_provider=="string"?n.image_provider:void 0,o=typeof n.cms=="string"?n.cms:void 0,i=o&&Ai.has(o)?o:void 0,s=typeof n.install_id=="string"?n.install_id:void 0;return{domain:n.domain,site_type:typeof n.site_type=="string"?n.site_type:"unknown",language:typeof n.language=="string"?n.language:"en",initialized_at:typeof n.initialized_at=="string"?n.initialized_at:"",seoagent_version:typeof n.seoagent_version=="string"?n.seoagent_version:"",skill_version:typeof n.skill_version=="string"&&n.skill_version?n.skill_version:void 0,install_id:s&&Ei.test(s)?s:void 0,image_provider:r==="openai"||r==="fal"||r==="replicate"||r==="none"?r:void 0,cms:i,blog_path:typeof n.blog_path=="string"&&n.blog_path?n.blog_path:void 0}}function Hn(e){let t=S(e);if(!t)return null;if(t.install_id)return t.install_id;let n=Ht();return W(e,{install_id:n}),n}function Ri(e){return["",`# SEOAgent Project \u2014 ${e.domain}`,"","This file holds project-level configuration for the SEOAgent skill.","The skill reads it on every session to know which domain it is working on.","",`Initialized ${e.initialized_at} with seoagent ${e.seoagent_version}.`,""].join(`
16
- `)}function Pi(e){let t={domain:e.domain,site_type:e.site_type,language:e.language,initialized_at:e.initialized_at,seoagent_version:e.seoagent_version};return e.skill_version&&(t.skill_version=e.skill_version),e.install_id&&(t.install_id=e.install_id),e.image_provider&&(t.image_provider=e.image_provider),e.cms&&(t.cms=e.cms),e.blog_path&&(t.blog_path=e.blog_path),t}function Yn(e,t){let n=Ne(e);Wn(n,{recursive:!0});let r=Kt(Pi(t),Ri(t));Kn(mt(e),r,"utf-8")}function W(e,t){let n=mt(e);if(!Gn(n))return!1;let r=Le(Ci(n,"utf-8")),o={...r.data,...t};return Kn(n,Kt(o,r.body),"utf-8"),!0}function zn(e){let t=Ne(e);for(let n of Nn)Wn(qt(t,n),{recursive:!0})}import{existsSync as gt,lstatSync as Oi,mkdirSync as Fe,readFileSync as Vn,readdirSync as Ti,rmSync as ji,statSync as Li,symlinkSync as Ni,writeFileSync as Jn}from"fs";import{dirname as ht,join as H,relative as Qn}from"path";import{fileURLToPath as Fi}from"url";var Di=ht(Fi(import.meta.url));function Xn(){return H(Di,"skills")}function Ui(){let e=H(Xn(),"seoagent.md");if(gt(e))return Vn(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function Zn(e,t){let n=[];if(!gt(e))return n;for(let r of Ti(e,{withFileTypes:!0})){let o=H(e,r.name),i=H(t,r.name);r.isDirectory()?(Fe(i,{recursive:!0}),n.push(...Zn(o,i))):r.isFile()&&(Fe(ht(i),{recursive:!0}),Jn(i,Vn(o)),n.push(i))}return n}function we(e,t){let n=gt(H(e,".agents")),r=H(e,n?ae.AGENTS:ae.CLAUDE),o=H(r,"SKILL.md");Fe(r,{recursive:!0}),Jn(o,t??Ui(),"utf-8");let i=H(Xn(),"references"),s=H(r,"references"),a=[];try{gt(i)&&Li(i).isDirectory()&&(Fe(s,{recursive:!0}),a=Zn(i,s).map(u=>Qn(r,u)))}catch{}let c=n?Mi(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:c}}function Mi(e,t){let n=H(e,ae.CLAUDE),r=null;try{r=Oi(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{ji(n,{force:!0})}catch{return}}try{Fe(ht(n),{recursive:!0});let o=Qn(ht(n),t);return Ni(o,n,"dir"),n}catch{return}}import{existsSync as wt,mkdirSync as Yt,readFileSync as Bi,writeFileSync as yt}from"fs";import{dirname as tr,join as ke}from"path";var Gi=`npx -y ${lt} sync --silent`;function nr(e){let t=ke(e,b);Yt(t,{recursive:!0});let n=ke(t,".gitignore");yt(n,Mn,"utf-8");let r=ke(t,"content","images",".gitkeep");return Yt(tr(r),{recursive:!0}),wt(r)||yt(r,"","utf-8"),n}var rr=["PostToolUse","SessionStart"];function zt(e){if(!wt(e))return{};try{let t=Bi(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Vt(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function er(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(Vt)?!1:(r.hooks.push({type:"command",command:Gi}),!0)}function le(e){let t=ke(e,ct);Yt(tr(t),{recursive:!0});let n=zt(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=er(r,a=>(a.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),i=n.hooks.SessionStart=n.hooks.SessionStart??[],s=er(i,a=>(a.matcher??"")==="",()=>({hooks:[]}));return yt(t,JSON.stringify(n,null,2)+`
17
- `,"utf-8"),{file:t,added:o||s}}function or(e){let t=ke(e,ct);if(!wt(t))return!1;let n=zt(t).hooks;return n?rr.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(Vt))}):!1}function ir(e){let t=ke(e,ct);if(!wt(t))return{file:t,removed:!1};let n=zt(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of rr){let s=r[i];if(!Array.isArray(s))continue;for(let c of s){let u=c.hooks.length;c.hooks=c.hooks.filter(d=>!Vt(d)),c.hooks.length!==u&&(o=!0)}let a=s.filter(c=>c.hooks.length>0);a.length===0?delete r[i]:r[i]=a}return o?(Object.keys(r).length===0&&delete n.hooks,yt(t,JSON.stringify(n,null,2)+`
18
- `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as sr,mkdirSync as Wi,readFileSync as Ki,writeFileSync as qi}from"fs";import{join as Hi}from"path";function ar(e){return sr(Hi(e,b,"project.md"))}function lr(){try{if(!sr(dt))return[];let e=JSON.parse(Ki(dt,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function cr(e){try{Wi(F,{recursive:!0}),qi(dt,JSON.stringify({projects:e},null,2)+`
19
- `,"utf-8")}catch{}}function ce(e){try{if(!ar(e))return;let t=lr();if(t.includes(e))return;t.push(e),cr(t)}catch{}}function ur(){let e=lr(),t=e.filter(ar);return t.length!==e.length&&cr(t),t}import{readFileSync as Ji,writeFileSync as Qi,existsSync as Xi}from"fs";import{join as mr}from"path";function pr(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=Yi(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=zi(o):i==="writing instructions"?t.writingInstructions=dr(o):i==="reference urls"?t.referenceUrls=Vi(o):i==="topics to avoid"?t.topicsToAvoid=dr(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function fr(e){let t=[];t.push("# Business Context"),t.push("");let n=[["Name","name"],["Type","type"],["Audience","audience"],["Industry","industry"],["Location","location"],["Description","description"]];for(let[o,i]of n){let s=e.business[i];t.push(`- **${o}:** ${s||""}`)}let r=new Set(n.map(([,o])=>o));for(let[o,i]of Object.entries(e.business))if(!r.has(o)&&i){let s=o.charAt(0).toUpperCase()+o.slice(1);t.push(`- **${s}:** ${i}`)}if(t.push(""),t.push("# Writing Instructions"),t.push(""),e.writingInstructions.length>0)for(let o of e.writingInstructions)t.push(`- ${o}`);else t.push("- (Add your content writing guidelines here)");if(t.push(""),t.push("# Reference URLs"),t.push(""),e.referenceUrls.length>0)for(let o of e.referenceUrls)o.description?t.push(`- ${o.url} \u2014 ${o.description}`):t.push(`- ${o.url}`);else t.push("- (Add URLs the agent should reference for tone/style)");if(t.push(""),t.push("# Topics to Avoid"),t.push(""),e.topicsToAvoid.length>0)for(let o of e.topicsToAvoid)t.push(`- ${o}`);else t.push("- (Add topics the agent should never write about)");return t.push(""),t.push("# Content Tone"),t.push(""),t.push(e.contentTone||"professional"),t.push(""),t.push("# Additional Notes"),t.push(""),t.push(e.additionalNotes||"(Any other context you want the agent to know about your business, products, or audience.)"),t.push(""),t.join(`
15
+ `)}var Ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ht(){return _i()}var Ai=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),Ii="project.md";function Ne(e){return qt(e,b)}function mt(e){return qt(Ne(e),Ii)}function Hn(e){return Wn(mt(e))}function S(e){let t=ft(mt(e));if(!t)return null;let n=t.data;if(typeof n.domain!="string"||!n.domain)return null;let r=typeof n.image_provider=="string"?n.image_provider:void 0,o=typeof n.cms=="string"?n.cms:void 0,i=o&&Ai.has(o)?o:void 0,s=typeof n.install_id=="string"?n.install_id:void 0;return{domain:n.domain,site_type:typeof n.site_type=="string"?n.site_type:"unknown",language:typeof n.language=="string"?n.language:"en",initialized_at:typeof n.initialized_at=="string"?n.initialized_at:"",seoagent_version:typeof n.seoagent_version=="string"?n.seoagent_version:"",skill_version:typeof n.skill_version=="string"&&n.skill_version?n.skill_version:void 0,install_id:s&&Ei.test(s)?s:void 0,image_provider:r==="openai"||r==="fal"||r==="replicate"||r==="none"?r:void 0,cms:i,blog_path:typeof n.blog_path=="string"&&n.blog_path?n.blog_path:void 0}}function Yn(e){let t=S(e);if(!t)return null;if(t.install_id)return t.install_id;let n=Ht();return W(e,{install_id:n}),n}function Ri(e){return["",`# SEOAgent Project \u2014 ${e.domain}`,"","This file holds project-level configuration for the SEOAgent skill.","The skill reads it on every session to know which domain it is working on.","",`Initialized ${e.initialized_at} with seoagent ${e.seoagent_version}.`,""].join(`
16
+ `)}function Pi(e){let t={domain:e.domain,site_type:e.site_type,language:e.language,initialized_at:e.initialized_at,seoagent_version:e.seoagent_version};return e.skill_version&&(t.skill_version=e.skill_version),e.install_id&&(t.install_id=e.install_id),e.image_provider&&(t.image_provider=e.image_provider),e.cms&&(t.cms=e.cms),e.blog_path&&(t.blog_path=e.blog_path),t}function zn(e,t){let n=Ne(e);Kn(n,{recursive:!0});let r=Kt(Pi(t),Ri(t));qn(mt(e),r,"utf-8")}function W(e,t){let n=mt(e);if(!Wn(n))return!1;let r=Le(Ci(n,"utf-8")),o={...r.data,...t};return qn(n,Kt(o,r.body),"utf-8"),!0}function Vn(e){let t=Ne(e);for(let n of Fn)Kn(qt(t,n),{recursive:!0})}import{existsSync as gt,lstatSync as Oi,mkdirSync as Fe,readFileSync as Jn,readdirSync as Ti,rmSync as ji,statSync as Li,symlinkSync as Ni,writeFileSync as Qn}from"fs";import{dirname as ht,join as H,relative as Xn}from"path";import{fileURLToPath as Fi}from"url";var Di=ht(Fi(import.meta.url));function Zn(){return H(Di,"skills")}function Ui(){let e=H(Zn(),"seoagent.md");if(gt(e))return Jn(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function er(e,t){let n=[];if(!gt(e))return n;for(let r of Ti(e,{withFileTypes:!0})){let o=H(e,r.name),i=H(t,r.name);r.isDirectory()?(Fe(i,{recursive:!0}),n.push(...er(o,i))):r.isFile()&&(Fe(ht(i),{recursive:!0}),Qn(i,Jn(o)),n.push(i))}return n}function we(e,t){let n=gt(H(e,".agents")),r=H(e,n?ae.AGENTS:ae.CLAUDE),o=H(r,"SKILL.md");Fe(r,{recursive:!0}),Qn(o,t??Ui(),"utf-8");let i=H(Zn(),"references"),s=H(r,"references"),a=[];try{gt(i)&&Li(i).isDirectory()&&(Fe(s,{recursive:!0}),a=er(i,s).map(u=>Xn(r,u)))}catch{}let c=n?Mi(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:c}}function Mi(e,t){let n=H(e,ae.CLAUDE),r=null;try{r=Oi(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{ji(n,{force:!0})}catch{return}}try{Fe(ht(n),{recursive:!0});let o=Xn(ht(n),t);return Ni(o,n,"dir"),n}catch{return}}import{existsSync as wt,mkdirSync as Yt,readFileSync as Bi,writeFileSync as yt}from"fs";import{dirname as nr,join as ke}from"path";var Gi=`npx -y ${lt} sync --silent`;function rr(e){let t=ke(e,b);Yt(t,{recursive:!0});let n=ke(t,".gitignore");yt(n,Bn,"utf-8");let r=ke(t,"content","images",".gitkeep");return Yt(nr(r),{recursive:!0}),wt(r)||yt(r,"","utf-8"),n}var or=["PostToolUse","SessionStart"];function zt(e){if(!wt(e))return{};try{let t=Bi(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Vt(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function tr(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(Vt)?!1:(r.hooks.push({type:"command",command:Gi}),!0)}function le(e){let t=ke(e,ct);Yt(nr(t),{recursive:!0});let n=zt(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=tr(r,a=>(a.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),i=n.hooks.SessionStart=n.hooks.SessionStart??[],s=tr(i,a=>(a.matcher??"")==="",()=>({hooks:[]}));return yt(t,JSON.stringify(n,null,2)+`
17
+ `,"utf-8"),{file:t,added:o||s}}function ir(e){let t=ke(e,ct);if(!wt(t))return!1;let n=zt(t).hooks;return n?or.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(Vt))}):!1}function sr(e){let t=ke(e,ct);if(!wt(t))return{file:t,removed:!1};let n=zt(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of or){let s=r[i];if(!Array.isArray(s))continue;for(let c of s){let u=c.hooks.length;c.hooks=c.hooks.filter(d=>!Vt(d)),c.hooks.length!==u&&(o=!0)}let a=s.filter(c=>c.hooks.length>0);a.length===0?delete r[i]:r[i]=a}return o?(Object.keys(r).length===0&&delete n.hooks,yt(t,JSON.stringify(n,null,2)+`
18
+ `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as ar,mkdirSync as Wi,readFileSync as Ki,writeFileSync as qi}from"fs";import{join as Hi}from"path";function lr(e){return ar(Hi(e,b,"project.md"))}function cr(){try{if(!ar(dt))return[];let e=JSON.parse(Ki(dt,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function ur(e){try{Wi(F,{recursive:!0}),qi(dt,JSON.stringify({projects:e},null,2)+`
19
+ `,"utf-8")}catch{}}function ce(e){try{if(!lr(e))return;let t=cr();if(t.includes(e))return;t.push(e),ur(t)}catch{}}function dr(){let e=cr(),t=e.filter(lr);return t.length!==e.length&&ur(t),t}import{readFileSync as Ji,writeFileSync as Qi,existsSync as Xi}from"fs";import{join as gr}from"path";function fr(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=Yi(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=zi(o):i==="writing instructions"?t.writingInstructions=pr(o):i==="reference urls"?t.referenceUrls=Vi(o):i==="topics to avoid"?t.topicsToAvoid=pr(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function mr(e){let t=[];t.push("# Business Context"),t.push("");let n=[["Name","name"],["Type","type"],["Audience","audience"],["Industry","industry"],["Location","location"],["Description","description"]];for(let[o,i]of n){let s=e.business[i];t.push(`- **${o}:** ${s||""}`)}let r=new Set(n.map(([,o])=>o));for(let[o,i]of Object.entries(e.business))if(!r.has(o)&&i){let s=o.charAt(0).toUpperCase()+o.slice(1);t.push(`- **${s}:** ${i}`)}if(t.push(""),t.push("# Writing Instructions"),t.push(""),e.writingInstructions.length>0)for(let o of e.writingInstructions)t.push(`- ${o}`);else t.push("- (Add your content writing guidelines here)");if(t.push(""),t.push("# Reference URLs"),t.push(""),e.referenceUrls.length>0)for(let o of e.referenceUrls)o.description?t.push(`- ${o.url} \u2014 ${o.description}`):t.push(`- ${o.url}`);else t.push("- (Add URLs the agent should reference for tone/style)");if(t.push(""),t.push("# Topics to Avoid"),t.push(""),e.topicsToAvoid.length>0)for(let o of e.topicsToAvoid)t.push(`- ${o}`);else t.push("- (Add topics the agent should never write about)");return t.push(""),t.push("# Content Tone"),t.push(""),t.push(e.contentTone||"professional"),t.push(""),t.push("# Additional Notes"),t.push(""),t.push(e.additionalNotes||"(Any other context you want the agent to know about your business, products, or audience.)"),t.push(""),t.join(`
20
20
  `)}function Yi(e){let t=e.split(`
21
21
  `),n=[],r="",o=[];for(let i of t){let s=i.match(/^#\s+(.+)$/);s?(r&&n.push([r,o.join(`
22
22
  `)]),r=s[1],o=[]):o.push(i)}return r&&n.push([r,o.join(`
23
23
  `)]),n}function zi(e){let t={},n=e.split(`
24
- `);for(let r of n){let o=r.match(/^[-*]\s+\*\*(.+?):\*\*\s*(.*)$/);if(o){let i=o[1].toLowerCase().trim(),s=o[2].trim();s&&(t[i]=s)}}return t}function dr(e){let t=[],n=e.split(`
24
+ `);for(let r of n){let o=r.match(/^[-*]\s+\*\*(.+?):\*\*\s*(.*)$/);if(o){let i=o[1].toLowerCase().trim(),s=o[2].trim();s&&(t[i]=s)}}return t}function pr(e){let t=[],n=e.split(`
25
25
  `);for(let r of n){let o=r.match(/^[-*]\s+(.+)$/);if(o){let i=o[1].trim();(!i.startsWith("(")||!i.endsWith(")"))&&t.push(i)}}return t}function Vi(e){let t=[],n=e.split(`
26
- `);for(let r of n){let o=r.match(/^[-*]\s+(https?:\/\/\S+)(?:\s+[—–-]\s+(.+))?$/);o&&t.push({url:o[1].trim(),description:o[2]?.trim()||""})}return t}var gr="context.md";function hr(e){let t=mr(e,".seoagent",gr);if(!Xi(t))return null;let n=Ji(t,"utf-8");return pr(n)}function Zi(e,t){let n=mr(e,".seoagent",gr),r=fr(t);Qi(n,r,"utf-8")}function yr(e,t){Zi(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as De,readFileSync as wr,readdirSync as es,statSync as kr}from"fs";import{join as ue}from"path";var ts=[{cms:"strapi",deps:["strapi","@strapi/strapi","@strapi/"],envKeys:["STRAPI_URL","STRAPI_API_URL","NEXT_PUBLIC_STRAPI_URL","STRAPI_API_TOKEN"],fsMarkers:["strapi/","apps/strapi/","packages/strapi/","cms/"]},{cms:"wordpress",deps:["wpapi","wp-graphql","@wordpress/api-fetch","@wordpress/"],envKeys:["WORDPRESS_API_URL","WP_API_URL","NEXT_PUBLIC_WORDPRESS_URL"],fsMarkers:[]},{cms:"sanity",deps:["@sanity/client","next-sanity","sanity"],envKeys:["SANITY_PROJECT_ID","NEXT_PUBLIC_SANITY_PROJECT_ID","SANITY_API_TOKEN"],fsMarkers:["sanity/","studio/","sanity.config.ts","sanity.config.js"]},{cms:"contentful",deps:["contentful","@contentful/rich-text-react-renderer","@contentful/"],envKeys:["CONTENTFUL_SPACE_ID","CONTENTFUL_ACCESS_TOKEN","NEXT_PUBLIC_CONTENTFUL_SPACE_ID"],fsMarkers:[]},{cms:"ghost",deps:["@tryghost/content-api","@tryghost/"],envKeys:["GHOST_URL","GHOST_API_KEY","NEXT_PUBLIC_GHOST_URL"],fsMarkers:[]},{cms:"webflow",deps:["webflow-api"],envKeys:["WEBFLOW_API_TOKEN","WEBFLOW_SITE_ID"],fsMarkers:[]},{cms:"shopify",deps:["@shopify/hydrogen","@shopify/storefront-api-client","@shopify/shopify-api","@shopify/"],envKeys:["SHOPIFY_STOREFRONT_TOKEN","SHOPIFY_STORE_DOMAIN","SHOPIFY_ADMIN_API_TOKEN"],fsMarkers:["shopify.config.ts","shopify.config.js"]},{cms:"payload",deps:["payload","@payloadcms/next","@payloadcms/"],envKeys:["PAYLOAD_SECRET","PAYLOAD_PUBLIC_SERVER_URL"],fsMarkers:["payload.config.ts","payload.config.js"]},{cms:"directus",deps:["@directus/sdk","directus"],envKeys:["DIRECTUS_URL","DIRECTUS_TOKEN"],fsMarkers:[]}];function ns(e){let t=ue(e,"package.json");if(!De(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(wr(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function rs(e,t){for(let n of t)if(n.endsWith("/")){if(e.startsWith(n))return!0}else if(e===n)return!0;return!1}function os(e){let t={};for(let n of ge){let r=ue(e,n);if(De(r))try{let o=wr(r,"utf-8");for(let i of o.split(/\r?\n/)){let s=i.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a===-1)continue;let c=s.slice(0,a).trim();c&&!(c in t)&&(t[c]=n)}}catch{}}return t}function is(e,t){let n=ue(e,t.replace(/\/$/,""));if(!De(n))return!1;if(t.endsWith("/"))try{return kr(n).isDirectory()}catch{return!1}return!0}function ss(e){let t=["content","_posts","posts",ue("src","content")];for(let n of t){let r=ue(e,n);if(De(r))try{if(!kr(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of es(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(ue(s,a.name));continue}if(a.isFile()&&/\.(md|mdx)$/i.test(a.name))return{type:"directory",detail:n,source:`${n}/${a.name}`}}}}catch{}}return null}function as(e){let t=[{marker:"app/blog/page.tsx",path:"/blog"},{marker:"app/blog/page.jsx",path:"/blog"},{marker:"app/blog/page.js",path:"/blog"},{marker:"src/app/blog/page.tsx",path:"/blog"},{marker:"src/app/blog/page.jsx",path:"/blog"},{marker:"pages/blog/index.tsx",path:"/blog"},{marker:"pages/blog/index.jsx",path:"/blog"},{marker:"pages/blog/index.js",path:"/blog"},{marker:"src/pages/blog/index.tsx",path:"/blog"},{marker:"app/(blog)/page.tsx",path:"/blog"},{marker:"app/articles/page.tsx",path:"/articles"},{marker:"pages/articles/index.tsx",path:"/articles"},{marker:"app/posts/page.tsx",path:"/posts"},{marker:"pages/posts/index.tsx",path:"/posts"},{marker:"app/learn/page.tsx",path:"/learn"},{marker:"app/resources/page.tsx",path:"/resources"}];for(let n of t)if(De(ue(e,n.marker)))return n.path;return null}function br(e){let t=[],{deps:n}=ns(e),r=os(e),o="none";for(let s of ts){let a=[];for(let c of Object.keys(n))if(rs(c,s.deps)){a.push({type:"dep",detail:c,source:"package.json"});break}for(let c of s.envKeys)if(r[c]){a.push({type:"env",detail:c,source:r[c]});break}for(let c of s.fsMarkers)if(is(e,c)){let u=c.endsWith("/")?"directory":"file";a.push({type:u,detail:c,source:c});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=ss(e);s&&(o="mdx-local",t.push(s))}let i=as(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as de,readFileSync as Jt}from"fs";import{join as pe}from"path";function $r(e){try{return new URL(e).hostname}catch{return e}}function Sr(e){let t=e.toLowerCase();return!!(t==="github.com"||t.endsWith(".github.com")||t==="gitlab.com"||t.endsWith(".gitlab.com")||t==="bitbucket.org"||t.endsWith(".bitbucket.org")||t==="dev.azure.com"||t==="visualstudio.com"||t.endsWith(".visualstudio.com")||t==="npmjs.com"||t.endsWith(".npmjs.com"))}function ls(e){for(let t of ge){let n=pe(e,t);if(!de(n))continue;let r=Jt(n,"utf-8");for(let o of Ln){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=$r(s);if(Sr(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function cs(e){let t=pe(e,"package.json");if(!de(t))return null;try{let n=JSON.parse(Jt(t,"utf-8"));if(!n.homepage)return null;let r=$r(n.homepage);return Sr(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function vr(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),de(pe(e,"pnpm-workspace.yaml"))&&n.push({field:"context",detail:"Monorepo workspace detected",source:"pnpm-workspace.yaml \u2014 using this directory for project signals"});let r=null;t?.("Scanning .env files for public / site URLs\u2026");let o=ls(e);if(o)r=o.value,n.push({field:"domain",detail:o.value,source:o.source});else{t?.("Reading package.json homepage (skipping GitHub/GitLab repo URLs)\u2026");let a=cs(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=pe(e,"package.json"),s=null;if(de(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Jt(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>c.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||de(pe(e,"shopify.config.js"))||de(pe(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":de(pe(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),h=u("next");d&&(h||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:h?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:r,siteType:s,evidence:n}}import{existsSync as us,readFileSync as Zt,readdirSync as xr,statSync as ds}from"fs";import{join as M,sep as ps}from"path";var _r=["tsx","jsx","js","mdx","md"],fs=["astro","md","mdx"],ms=5e3;function be(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=ks(i);if(c===null){r++;return}let u=n.get(c);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(c,{route:c,url:Es(t,c),in_sitemap:a,source:s})};for(let i of hs(e))gs(i,o);return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}function gs(e,t){for(let n of["app",M("src","app")]){let r=M(e,n);if(Ue(r))for(let o of Qt(r)){let i=Xt(r,o),s=i[i.length-1];xs(s)&&(i.some(a=>a.startsWith("@"))||t(bs(i.slice(0,-1)),"app router"))}}for(let n of["pages",M("src","pages")]){let r=M(e,n);if(Ue(r))for(let o of Qt(r)){let i=Xt(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=en(s),c=_r.includes(a),u=fs.includes(a);if(!c&&!u)continue;let d=kt(s);_s(d)||t($s(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=M(e,n);if(Ue(r))for(let o of Qt(r,n==="."?1:1/0)){let i=Xt(r,o),s=i[i.length-1];en(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(Ss(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=M(e,...n.split("/"));if(us(r)){for(let o of Cs(r)){let i=vs(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function hs(e){let t=[e],n=new Set([e]);for(let r of ys(e))for(let o of ws(e,r))n.has(o)||(n.add(o),t.push(o));return t}function ys(e){let t=[];try{let n=Zt(M(e,"pnpm-workspace.yaml"),"utf-8"),r=!1;for(let o of n.split(/\r?\n/)){let i=o.replace(/#.*$/,"");if(/^\s*packages\s*:/.test(i)){r=!0;continue}if(r){let s=i.match(/^\s*-\s*['"]?([^'"\s]+)['"]?\s*$/);s?t.push(s[1]):/^\S/.test(i)&&(r=!1)}}}catch{}try{let r=JSON.parse(Zt(M(e,"package.json"),"utf-8")).workspaces,o=Array.isArray(r)?r:Array.isArray(r?.packages)?r.packages:[];for(let i of o??[])typeof i=="string"&&t.push(i)}catch{}return t}function ws(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=M(e,...n.split("/").filter(Boolean));return Ue(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=M(e,...o.split("/").filter(Boolean));if(!Ue(i))return[];let s=[];try{for(let a of xr(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!Cr.has(a.name)&&(s.push(M(i,a.name)),s.length>=200))break}catch{}return s}function ks(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function bs(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function $s(e){let t=[...e],n=kt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Ss(e){let t=[...e],n=kt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function vs(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function xs(e){return kt(e)==="page"&&_r.includes(en(e))}function _s(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Cs(e){try{let t=Zt(e,"utf-8"),n=[],r=/<loc>\s*([^<\s]+)\s*<\/loc>/gi,o;for(;(o=r.exec(t))!==null;)n.push(o[1].trim());return n}catch{return[]}}var Cr=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Ue(e){try{return ds(e).isDirectory()}catch{return!1}}function*Qt(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=xr(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=ms)return;if(a.name.startsWith("."))continue;let c=M(o,a.name);if(a.isDirectory()){if(Cr.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function Xt(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(ps).filter(Boolean)}function en(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function kt(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Es(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as As,mkdirSync as Is,readFileSync as Rs,writeFileSync as Ps}from"fs";import{join as Er}from"path";function bt(e,t){let n=Er(e,b,"pages.md"),r=As(n),o=r?Ts(n):new Map;if(t.length===0&&!r)return{wrote:!1,added:0,total:0,merged:!1};let i=new Map(o),s=0,a=!1;for(let u of t){let d=Ir(u.url),p=i.get(d);p?u.in_sitemap&&p.in_sitemap!=="yes"&&(p.in_sitemap="yes",a=!0):(i.set(d,{url:d,in_sitemap:u.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",notes:Ir(u.source)}),s++,a=!0)}if(r&&!a)return{wrote:!1,added:0,total:i.size,merged:!0};let c=[...i.values()];return Is(Er(e,b),{recursive:!0}),Ps(n,Os(c),"utf-8"),{wrote:!0,added:s,total:c.length,merged:r}}function Os(e){let t=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
26
+ `);for(let r of n){let o=r.match(/^[-*]\s+(https?:\/\/\S+)(?:\s+[—–-]\s+(.+))?$/);o&&t.push({url:o[1].trim(),description:o[2]?.trim()||""})}return t}var hr="context.md";function yr(e){let t=gr(e,".seoagent",hr);if(!Xi(t))return null;let n=Ji(t,"utf-8");return fr(n)}function Zi(e,t){let n=gr(e,".seoagent",hr),r=mr(t);Qi(n,r,"utf-8")}function wr(e,t){Zi(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as De,readFileSync as kr,readdirSync as es,statSync as br}from"fs";import{join as ue}from"path";var ts=[{cms:"strapi",deps:["strapi","@strapi/strapi","@strapi/"],envKeys:["STRAPI_URL","STRAPI_API_URL","NEXT_PUBLIC_STRAPI_URL","STRAPI_API_TOKEN"],fsMarkers:["strapi/","apps/strapi/","packages/strapi/","cms/"]},{cms:"wordpress",deps:["wpapi","wp-graphql","@wordpress/api-fetch","@wordpress/"],envKeys:["WORDPRESS_API_URL","WP_API_URL","NEXT_PUBLIC_WORDPRESS_URL"],fsMarkers:[]},{cms:"sanity",deps:["@sanity/client","next-sanity","sanity"],envKeys:["SANITY_PROJECT_ID","NEXT_PUBLIC_SANITY_PROJECT_ID","SANITY_API_TOKEN"],fsMarkers:["sanity/","studio/","sanity.config.ts","sanity.config.js"]},{cms:"contentful",deps:["contentful","@contentful/rich-text-react-renderer","@contentful/"],envKeys:["CONTENTFUL_SPACE_ID","CONTENTFUL_ACCESS_TOKEN","NEXT_PUBLIC_CONTENTFUL_SPACE_ID"],fsMarkers:[]},{cms:"ghost",deps:["@tryghost/content-api","@tryghost/"],envKeys:["GHOST_URL","GHOST_API_KEY","NEXT_PUBLIC_GHOST_URL"],fsMarkers:[]},{cms:"webflow",deps:["webflow-api"],envKeys:["WEBFLOW_API_TOKEN","WEBFLOW_SITE_ID"],fsMarkers:[]},{cms:"shopify",deps:["@shopify/hydrogen","@shopify/storefront-api-client","@shopify/shopify-api","@shopify/"],envKeys:["SHOPIFY_STOREFRONT_TOKEN","SHOPIFY_STORE_DOMAIN","SHOPIFY_ADMIN_API_TOKEN"],fsMarkers:["shopify.config.ts","shopify.config.js"]},{cms:"payload",deps:["payload","@payloadcms/next","@payloadcms/"],envKeys:["PAYLOAD_SECRET","PAYLOAD_PUBLIC_SERVER_URL"],fsMarkers:["payload.config.ts","payload.config.js"]},{cms:"directus",deps:["@directus/sdk","directus"],envKeys:["DIRECTUS_URL","DIRECTUS_TOKEN"],fsMarkers:[]}];function ns(e){let t=ue(e,"package.json");if(!De(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(kr(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function rs(e,t){for(let n of t)if(n.endsWith("/")){if(e.startsWith(n))return!0}else if(e===n)return!0;return!1}function os(e){let t={};for(let n of ge){let r=ue(e,n);if(De(r))try{let o=kr(r,"utf-8");for(let i of o.split(/\r?\n/)){let s=i.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a===-1)continue;let c=s.slice(0,a).trim();c&&!(c in t)&&(t[c]=n)}}catch{}}return t}function is(e,t){let n=ue(e,t.replace(/\/$/,""));if(!De(n))return!1;if(t.endsWith("/"))try{return br(n).isDirectory()}catch{return!1}return!0}function ss(e){let t=["content","_posts","posts",ue("src","content")];for(let n of t){let r=ue(e,n);if(De(r))try{if(!br(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of es(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(ue(s,a.name));continue}if(a.isFile()&&/\.(md|mdx)$/i.test(a.name))return{type:"directory",detail:n,source:`${n}/${a.name}`}}}}catch{}}return null}function as(e){let t=[{marker:"app/blog/page.tsx",path:"/blog"},{marker:"app/blog/page.jsx",path:"/blog"},{marker:"app/blog/page.js",path:"/blog"},{marker:"src/app/blog/page.tsx",path:"/blog"},{marker:"src/app/blog/page.jsx",path:"/blog"},{marker:"pages/blog/index.tsx",path:"/blog"},{marker:"pages/blog/index.jsx",path:"/blog"},{marker:"pages/blog/index.js",path:"/blog"},{marker:"src/pages/blog/index.tsx",path:"/blog"},{marker:"app/(blog)/page.tsx",path:"/blog"},{marker:"app/articles/page.tsx",path:"/articles"},{marker:"pages/articles/index.tsx",path:"/articles"},{marker:"app/posts/page.tsx",path:"/posts"},{marker:"pages/posts/index.tsx",path:"/posts"},{marker:"app/learn/page.tsx",path:"/learn"},{marker:"app/resources/page.tsx",path:"/resources"}];for(let n of t)if(De(ue(e,n.marker)))return n.path;return null}function $r(e){let t=[],{deps:n}=ns(e),r=os(e),o="none";for(let s of ts){let a=[];for(let c of Object.keys(n))if(rs(c,s.deps)){a.push({type:"dep",detail:c,source:"package.json"});break}for(let c of s.envKeys)if(r[c]){a.push({type:"env",detail:c,source:r[c]});break}for(let c of s.fsMarkers)if(is(e,c)){let u=c.endsWith("/")?"directory":"file";a.push({type:u,detail:c,source:c});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=ss(e);s&&(o="mdx-local",t.push(s))}let i=as(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as de,readFileSync as Jt}from"fs";import{join as pe}from"path";function Sr(e){try{return new URL(e).hostname}catch{return e}}function vr(e){let t=e.toLowerCase();return!!(t==="github.com"||t.endsWith(".github.com")||t==="gitlab.com"||t.endsWith(".gitlab.com")||t==="bitbucket.org"||t.endsWith(".bitbucket.org")||t==="dev.azure.com"||t==="visualstudio.com"||t.endsWith(".visualstudio.com")||t==="npmjs.com"||t.endsWith(".npmjs.com"))}function ls(e){for(let t of ge){let n=pe(e,t);if(!de(n))continue;let r=Jt(n,"utf-8");for(let o of Nn){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Sr(s);if(vr(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function cs(e){let t=pe(e,"package.json");if(!de(t))return null;try{let n=JSON.parse(Jt(t,"utf-8"));if(!n.homepage)return null;let r=Sr(n.homepage);return vr(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function xr(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),de(pe(e,"pnpm-workspace.yaml"))&&n.push({field:"context",detail:"Monorepo workspace detected",source:"pnpm-workspace.yaml \u2014 using this directory for project signals"});let r=null;t?.("Scanning .env files for public / site URLs\u2026");let o=ls(e);if(o)r=o.value,n.push({field:"domain",detail:o.value,source:o.source});else{t?.("Reading package.json homepage (skipping GitHub/GitLab repo URLs)\u2026");let a=cs(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=pe(e,"package.json"),s=null;if(de(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Jt(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>c.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||de(pe(e,"shopify.config.js"))||de(pe(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":de(pe(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),y=u("next");d&&(y||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:y?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:r,siteType:s,evidence:n}}import{existsSync as us,readFileSync as Zt,readdirSync as _r,statSync as ds}from"fs";import{join as M,sep as ps}from"path";var Cr=["tsx","jsx","js","mdx","md"],fs=["astro","md","mdx"],ms=5e3;function be(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=ks(i);if(c===null){r++;return}let u=n.get(c);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(c,{route:c,url:Es(t,c),in_sitemap:a,source:s})};for(let i of hs(e))gs(i,o);return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}function gs(e,t){for(let n of["app",M("src","app")]){let r=M(e,n);if(Ue(r))for(let o of Qt(r)){let i=Xt(r,o),s=i[i.length-1];xs(s)&&(i.some(a=>a.startsWith("@"))||t(bs(i.slice(0,-1)),"app router"))}}for(let n of["pages",M("src","pages")]){let r=M(e,n);if(Ue(r))for(let o of Qt(r)){let i=Xt(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=en(s),c=Cr.includes(a),u=fs.includes(a);if(!c&&!u)continue;let d=kt(s);_s(d)||t($s(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=M(e,n);if(Ue(r))for(let o of Qt(r,n==="."?1:1/0)){let i=Xt(r,o),s=i[i.length-1];en(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(Ss(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=M(e,...n.split("/"));if(us(r)){for(let o of Cs(r)){let i=vs(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function hs(e){let t=[e],n=new Set([e]);for(let r of ys(e))for(let o of ws(e,r))n.has(o)||(n.add(o),t.push(o));return t}function ys(e){let t=[];try{let n=Zt(M(e,"pnpm-workspace.yaml"),"utf-8"),r=!1;for(let o of n.split(/\r?\n/)){let i=o.replace(/#.*$/,"");if(/^\s*packages\s*:/.test(i)){r=!0;continue}if(r){let s=i.match(/^\s*-\s*['"]?([^'"\s]+)['"]?\s*$/);s?t.push(s[1]):/^\S/.test(i)&&(r=!1)}}}catch{}try{let r=JSON.parse(Zt(M(e,"package.json"),"utf-8")).workspaces,o=Array.isArray(r)?r:Array.isArray(r?.packages)?r.packages:[];for(let i of o??[])typeof i=="string"&&t.push(i)}catch{}return t}function ws(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=M(e,...n.split("/").filter(Boolean));return Ue(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=M(e,...o.split("/").filter(Boolean));if(!Ue(i))return[];let s=[];try{for(let a of _r(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!Er.has(a.name)&&(s.push(M(i,a.name)),s.length>=200))break}catch{}return s}function ks(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function bs(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function $s(e){let t=[...e],n=kt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Ss(e){let t=[...e],n=kt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function vs(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function xs(e){return kt(e)==="page"&&Cr.includes(en(e))}function _s(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Cs(e){try{let t=Zt(e,"utf-8"),n=[],r=/<loc>\s*([^<\s]+)\s*<\/loc>/gi,o;for(;(o=r.exec(t))!==null;)n.push(o[1].trim());return n}catch{return[]}}var Er=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Ue(e){try{return ds(e).isDirectory()}catch{return!1}}function*Qt(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=_r(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=ms)return;if(a.name.startsWith("."))continue;let c=M(o,a.name);if(a.isDirectory()){if(Er.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function Xt(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(ps).filter(Boolean)}function en(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function kt(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Es(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as As,mkdirSync as Is,readFileSync as Rs,writeFileSync as Ps}from"fs";import{join as Ar}from"path";function bt(e,t){let n=Ar(e,b,"pages.md"),r=As(n),o=r?Ts(n):new Map;if(t.length===0&&!r)return{wrote:!1,added:0,total:0,merged:!1};let i=new Map(o),s=0,a=!1;for(let u of t){let d=Rr(u.url),p=i.get(d);p?u.in_sitemap&&p.in_sitemap!=="yes"&&(p.in_sitemap="yes",a=!0):(i.set(d,{url:d,in_sitemap:u.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",notes:Rr(u.source)}),s++,a=!0)}if(r&&!a)return{wrote:!1,added:0,total:i.size,merged:!0};let c=[...i.values()];return Is(Ar(e,b),{recursive:!0}),Ps(n,Os(c),"utf-8"),{wrote:!0,added:s,total:c.length,merged:r}}function Os(e){let t=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
27
27
  `),n=["# Pages","","Inventory of pages discovered in your codebase. Re-running `seoagent init`","or `seoagent refresh` re-scans and merges in newly-added pages without","touching rows you or the audit have edited. Status, rendered, and in-nav","are filled in by the Phase 1 audit. This file syncs to the cloud on login."].join(`
28
28
  `),r="| URL | In sitemap | In nav | Status | Rendered | Notes |",o="|---|---|---|---|---|---|",i=e.map(s=>`| ${s.url} | ${s.in_sitemap} | ${s.in_nav} | ${s.status} | ${s.rendered} | ${s.notes} |`);return[t,"",n,"",r,o,...i,""].join(`
29
- `)}function Ts(e){let t=new Map,n;try{n=Rs(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!tn(r[o])||!js(r[o+1]))continue;let i=Ar(r[o]).map(a=>a.toLowerCase()),s={url:i.findIndex(a=>a.includes("url")),in_sitemap:i.findIndex(a=>a.includes("sitemap")),in_nav:i.findIndex(a=>a.includes("nav")),status:i.findIndex(a=>a.includes("status")||a.includes("http")),rendered:i.findIndex(a=>a.includes("render")),notes:i.findIndex(a=>a.includes("note"))};if(s.url===-1)return t;for(let a=o+2;a<r.length&&tn(r[a]);a++){let c=Ar(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:Me(c,s.in_sitemap),in_nav:Me(c,s.in_nav),status:Me(c,s.status),rendered:Me(c,s.rendered),notes:Me(c,s.notes)})}break}return t}function Me(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function tn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function js(e){let t=e.trim();return tn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function Ar(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function Ir(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as $e}from"@clack/prompts";var l={info:e=>$e.info(e),warn:e=>$e.warn(e),error:e=>$e.error(e),success:e=>$e.success(e),step:e=>$e.step(e),message:e=>$e.message(e)};function w(e,t,n,r=n){e?e.stop(r):l[t](n)}var Pr=[{value:"saas",label:"SaaS / App"},{value:"service",label:"Service business"},{value:"product",label:"E-commerce / Product"},{value:"content",label:"Content / Blog"},{value:"marketplace",label:"Marketplace"},{value:"tool",label:"Tool / Utility"},{value:"nonprofit",label:"Nonprofit / Community"},{value:"unknown",label:"Not sure"}],jr="unknown",Us=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Ms(e){return e.field==="context"?`${e.detail} \u2014 ${e.source}`:e.field==="domain"?`Domain: ${e.detail} \u2014 ${e.source}`:`Site type: ${e.detail} \u2014 ${e.source}`}function $t(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return Us.has(t)?t:null}async function Be(e={}){let t=process.cwd();if(qn(t)){let a=S(t),c=we(t);le(t),W(t,{skill_version:v}),ce(t);let u=Tr(St(t,c.skillFile)),d=c.claudeSymlink?` (symlinked at ${St(t,c.claudeSymlink)})`:"",p=a?.skill_version&&a.skill_version!==v?`${a.skill_version} \u2192 ${v}`:v;l.success(`Refreshed the SEOAgent skill (${p}).`),l.info("Your `.seoagent/` knowledge was left untouched."),l.info(`Skill at ${u}${d}.`),l.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`);return}let n=!!e.yes||!process.stdin.isTTY;n||Ls("SEOAgent \u2014 AI SEO Agent");let r=vr(t,a=>l.step(a)),o=()=>{if(r.evidence.length!==0){l.info("Inferred from your project:");for(let a of r.evidence)l.info(` \u2022 ${Ms(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=$t(e.siteType)||$t(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&$t(e.siteType)===null&&(l.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&$t(process.env.SEOAGENT_SITE_TYPE)===null&&(l.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),o(),i||(l.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=jr),s||(s="unknown"),await Or(t,i,s);return}if(o(),!i){let a=await Rr({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});Se(a)&&(ve("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await nn({message:"What kind of site is this?",options:[...Pr]});Se(a)&&(ve("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Ds({message:`Create .seoagent for ${i} (${s})?`});if(Se(a)&&(ve("Cancelled"),process.exit(0)),a)break;let c=await nn({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((Se(c)||c==="abort")&&(ve("Cancelled"),process.exit(0)),c==="domain"){let u=await Rr({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});Se(u)&&(ve("Cancelled"),process.exit(0)),i=String(u)}else{let u=await nn({message:"What kind of site is this?",options:[...Pr]});Se(u)&&(ve("Cancelled"),process.exit(0)),s=u}}await Or(t,i,s)}async function Or(e,t,n){let r=Fs();r.start("Setting up your SEO project");let o=br(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:v,skill_version:v,install_id:Ht(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{}};zn(e),Yn(e,i),ce(e),yr(e,n),nr(e);let s=we(e),a=St(e,s.skillFile),c=Tr(a),u=`${c}/references/audit-checks.md`,d=s.claudeSymlink?St(e,s.claudeSymlink):void 0;le(e);let p=t!==jr,h={pages:[],dynamicCount:0},m={wrote:!1,added:0,total:0,merged:!1};try{h=be(e,p?t:null),m=bt(e,h.pages)}catch{}if(r.stop(p?`Created .seoagent/ project for ${i.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let G=o.evidence.map(_=>`${_.detail} (${_.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${G}`)}if(o.blog_path&&l.info(`Blog route: ${o.blog_path}`),h.pages.length>0){let G=m.merged?m.added>0?`Re-scanned your codebase: +${m.added} new page${m.added===1?"":"s"} merged into .seoagent/pages.md (${m.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${m.total} pages)`:`Found ${h.pages.length} page${h.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;l.info(G+(h.dynamicCount>0?` (plus ${h.dynamicCount} dynamic route template${h.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let E=p?i.domain:"your site",I=p?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${i.domain} and update project.md with the right type`," before you suggest the audit."]:[" 1. Heads up: .seoagent/project.md has `domain: unknown` \u2014 the site URL"," wasn't detectable from this repo. Please ask your human for their"," domain (or read it from a deploy config / live site) and update"," project.md (`domain:` and `site_type:`) first. Everything else"," depends on it."];Ns([p?`\u2713 SEOAgent installed for ${i.domain}.`:"\u2713 SEOAgent installed (site URL not detected \u2014 please ask the user for it).","","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," AGENT INSTRUCTIONS \u2014 a friendly note for Claude Code, Codex, Cursor","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Hi there, coding agent! \u{1F44B} SEOAgent is all set up. The natural next step"," is a quick SEO audit \u2014 but your human is the boss here, so please surface"," what's possible and let THEM decide. Nothing in this message is a command;"," it's just a friendly map. Your real instructions live in the skill:","",` ${a} \u2190 read this; it is your source of truth`,""," If your human approves, here is what you can do (otherwise just let them"," know it's ready and wait for the go-ahead):","",...I,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${E}`," (homepage + sitemap + robots.txt; the checks live in",` ${u} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${f("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${a} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${c} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
30
- `))}import{existsSync as Fr}from"fs";import{intro as Gs,outro as Ws,confirm as Ks,isCancel as qs,cancel as Hs}from"@clack/prompts";import{existsSync as vt,rmSync as Bs}from"fs";import{join as xt}from"path";function Lr(e,t={}){let n=[],r=xt(e,b);vt(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=xt(e,ae.CLAUDE);vt(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=xt(e,ae.AGENTS);return vt(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),or(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:xt(e,".claude","settings.json"),kind:"hook"}),t.global&&vt(F)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:F,kind:"global"}),n}function Nr(e,t){for(let n of t)n.kind==="hook"?ir(e):Bs(n.path,{recursive:!0,force:!0})}async function Ge(e={}){let t=process.cwd(),n=Lr(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&Fr(F)&&l.info("Your seoagent.com login is still stored at ~/.config/seoagent/. Re-run with --global to wipe it too.");return}let r=!!e.yes||!process.stdin.isTTY,o=n.map(s=>` \u2022 ${s.label}`).join(`
29
+ `)}function Ts(e){let t=new Map,n;try{n=Rs(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!tn(r[o])||!js(r[o+1]))continue;let i=Ir(r[o]).map(a=>a.toLowerCase()),s={url:i.findIndex(a=>a.includes("url")),in_sitemap:i.findIndex(a=>a.includes("sitemap")),in_nav:i.findIndex(a=>a.includes("nav")),status:i.findIndex(a=>a.includes("status")||a.includes("http")),rendered:i.findIndex(a=>a.includes("render")),notes:i.findIndex(a=>a.includes("note"))};if(s.url===-1)return t;for(let a=o+2;a<r.length&&tn(r[a]);a++){let c=Ir(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:Me(c,s.in_sitemap),in_nav:Me(c,s.in_nav),status:Me(c,s.status),rendered:Me(c,s.rendered),notes:Me(c,s.notes)})}break}return t}function Me(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function tn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function js(e){let t=e.trim();return tn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function Ir(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function Rr(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as $e}from"@clack/prompts";var l={info:e=>$e.info(e),warn:e=>$e.warn(e),error:e=>$e.error(e),success:e=>$e.success(e),step:e=>$e.step(e),message:e=>$e.message(e)};function w(e,t,n,r=n){e?e.stop(r):l[t](n)}var Or=[{value:"saas",label:"SaaS / App"},{value:"service",label:"Service business"},{value:"product",label:"E-commerce / Product"},{value:"content",label:"Content / Blog"},{value:"marketplace",label:"Marketplace"},{value:"tool",label:"Tool / Utility"},{value:"nonprofit",label:"Nonprofit / Community"},{value:"unknown",label:"Not sure"}],Lr="unknown",Us=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Ms(e){return e.field==="context"?`${e.detail} \u2014 ${e.source}`:e.field==="domain"?`Domain: ${e.detail} \u2014 ${e.source}`:`Site type: ${e.detail} \u2014 ${e.source}`}function $t(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return Us.has(t)?t:null}async function Be(e={}){let t=process.cwd();if(Hn(t)){let a=S(t),c=we(t);le(t),W(t,{skill_version:v}),ce(t);let u=jr(St(t,c.skillFile)),d=c.claudeSymlink?` (symlinked at ${St(t,c.claudeSymlink)})`:"",p=a?.skill_version&&a.skill_version!==v?`${a.skill_version} \u2192 ${v}`:v;l.success(`Refreshed the SEOAgent skill (${p}).`),l.info("Your `.seoagent/` knowledge was left untouched."),l.info(`Skill at ${u}${d}.`),l.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`);return}let n=!!e.yes||!process.stdin.isTTY;n||Ls("SEOAgent \u2014 AI SEO Agent");let r=xr(t,a=>l.step(a)),o=()=>{if(r.evidence.length!==0){l.info("Inferred from your project:");for(let a of r.evidence)l.info(` \u2022 ${Ms(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=$t(e.siteType)||$t(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&$t(e.siteType)===null&&(l.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&$t(process.env.SEOAGENT_SITE_TYPE)===null&&(l.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),o(),i||(l.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=Lr),s||(s="unknown"),await Tr(t,i,s);return}if(o(),!i){let a=await Pr({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});Se(a)&&(ve("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await nn({message:"What kind of site is this?",options:[...Or]});Se(a)&&(ve("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Ds({message:`Create .seoagent for ${i} (${s})?`});if(Se(a)&&(ve("Cancelled"),process.exit(0)),a)break;let c=await nn({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((Se(c)||c==="abort")&&(ve("Cancelled"),process.exit(0)),c==="domain"){let u=await Pr({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});Se(u)&&(ve("Cancelled"),process.exit(0)),i=String(u)}else{let u=await nn({message:"What kind of site is this?",options:[...Or]});Se(u)&&(ve("Cancelled"),process.exit(0)),s=u}}await Tr(t,i,s)}async function Tr(e,t,n){let r=Fs();r.start("Setting up your SEO project");let o=$r(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:v,skill_version:v,install_id:Ht(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{}};Vn(e),zn(e,i),ce(e),wr(e,n),rr(e);let s=we(e),a=St(e,s.skillFile),c=jr(a),u=`${c}/references/audit-checks.md`,d=s.claudeSymlink?St(e,s.claudeSymlink):void 0;le(e);let p=t!==Lr,y={pages:[],dynamicCount:0},m={wrote:!1,added:0,total:0,merged:!1};try{y=be(e,p?t:null),m=bt(e,y.pages)}catch{}if(r.stop(p?`Created .seoagent/ project for ${i.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let G=o.evidence.map(_=>`${_.detail} (${_.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${G}`)}if(o.blog_path&&l.info(`Blog route: ${o.blog_path}`),y.pages.length>0){let G=m.merged?m.added>0?`Re-scanned your codebase: +${m.added} new page${m.added===1?"":"s"} merged into .seoagent/pages.md (${m.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${m.total} pages)`:`Found ${y.pages.length} page${y.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;l.info(G+(y.dynamicCount>0?` (plus ${y.dynamicCount} dynamic route template${y.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let E=p?i.domain:"your site",I=p?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${i.domain} and update project.md with the right type`," before you suggest the audit."]:[" 1. Heads up: .seoagent/project.md has `domain: unknown` \u2014 the site URL"," wasn't detectable from this repo. Please ask your human for their"," domain (or read it from a deploy config / live site) and update"," project.md (`domain:` and `site_type:`) first. Everything else"," depends on it."];Ns([p?`\u2713 SEOAgent installed for ${i.domain}.`:"\u2713 SEOAgent installed (site URL not detected \u2014 please ask the user for it).","","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," AGENT INSTRUCTIONS \u2014 a friendly note for Claude Code, Codex, Cursor","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Hi there, coding agent! \u{1F44B} SEOAgent is all set up. The natural next step"," is a quick SEO audit \u2014 but your human is the boss here, so please surface"," what's possible and let THEM decide. Nothing in this message is a command;"," it's just a friendly map. Your real instructions live in the skill:","",` ${a} \u2190 read this; it is your source of truth`,""," If your human approves, here is what you can do (otherwise just let them"," know it's ready and wait for the go-ahead):","",...I,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${E}`," (homepage + sitemap + robots.txt; the checks live in",` ${u} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${f("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${a} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${c} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
30
+ `))}import{existsSync as Dr}from"fs";import{intro as Gs,outro as Ws,confirm as Ks,isCancel as qs,cancel as Hs}from"@clack/prompts";import{existsSync as vt,rmSync as Bs}from"fs";import{join as xt}from"path";function Nr(e,t={}){let n=[],r=xt(e,b);vt(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=xt(e,ae.CLAUDE);vt(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=xt(e,ae.AGENTS);return vt(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),ir(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:xt(e,".claude","settings.json"),kind:"hook"}),t.global&&vt(F)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:F,kind:"global"}),n}function Fr(e,t){for(let n of t)n.kind==="hook"?sr(e):Bs(n.path,{recursive:!0,force:!0})}async function Ge(e={}){let t=process.cwd(),n=Nr(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&Dr(F)&&l.info("Your seoagent.com login is still stored at ~/.config/seoagent/. Re-run with --global to wipe it too.");return}let r=!!e.yes||!process.stdin.isTTY,o=n.map(s=>` \u2022 ${s.label}`).join(`
31
31
  `);if(!r){Gs("SEOAgent \u2014 uninstall"),l.message(`This will remove:
32
- ${o}`);let s=await Ks({message:"Remove these and start fresh?"});if(qs(s)||!s){Hs("Cancelled \u2014 nothing was removed.");return}}Nr(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
32
+ ${o}`);let s=await Ks({message:"Remove these and start fresh?"});if(qs(s)||!s){Hs("Cancelled \u2014 nothing was removed.");return}}Fr(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
33
33
  `);r?l.success(`Removed:
34
34
  ${i}`):Ws(`Removed:
35
- ${i}`),!e.global&&Fr(F)&&l.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),l.info(`Re-install any time with \`${f("init")}\`.`)}import $ from"picocolors";import{existsSync as Ur,mkdirSync as Dr,readFileSync as Ys,writeFileSync as zs,chmodSync as Vs,unlinkSync as Js}from"fs";import{dirname as Qs}from"path";function P(){if(!Ur(Z))return null;try{let e=JSON.parse(Ys(Z,"utf-8"));return!e.user_token||!e.website_token?null:{user_token:e.user_token,website_token:e.website_token,api_base:e.api_base||je}}catch{return null}}function Mr(e){Dr(F,{recursive:!0}),Dr(Qs(Z),{recursive:!0}),zs(Z,JSON.stringify(e,null,2)+`
36
- `,"utf-8");try{Vs(Z,384)}catch{}}function Br(){if(!Ur(Z))return!1;try{return Js(Z),!0}catch{return!1}}import{existsSync as We,readdirSync as rn,statSync as Xs,readFileSync as Gr}from"fs";import{join as xe}from"path";function Zs(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function ea(e){let t=xe(e,"audit","latest.md");if(!We(t))return null;let n=ft(t);if(!n)return null;let r=Gr(t,"utf-8"),o=Zs(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function ta(e){try{let n=Gr(e,"utf-8").split(/\r?\n/),r=!1,o=0;for(let i of n){let s=i.trim();if(s.startsWith("|")&&s.endsWith("|")){if(/^\|\s*-+\s*(\|\s*-+\s*)+\|$/.test(s)){r=!0;continue}r&&o++}else if(r&&s==="")break}return o}catch{return 0}}function na(e){let t=xe(e,"strategy","clusters");if(!We(t))return null;let n=rn(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=ta(xe(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function ra(e){let t=xe(e,"briefs");if(!We(t))return null;let n=rn(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function oa(e){let t=xe(e,"content");if(!We(t))return null;let n=rn(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function ia(e){let t=xe(e,"roadmap.md");return We(t)?{exists:!0,updatedAt:Xs(t).mtime.toISOString()}:null}function Wr(e){let t=S(e);if(!t)return null;let n=Ne(e);return{domain:t.domain,audit:ea(n),strategy:na(n),briefs:ra(n),content:oa(n),roadmap:ia(n)}}import ee from"picocolors";var sa=/\x1b\[[0-9;]*m/g;function Kr(e){return e.replace(sa,"").length}function O(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=aa(n,t.title),s=ee.dim(`\u251C${o}\u2524`),a=ee.dim(`\u2514${o}\u2518`),c=[i];for(let u of e){if("sep"in u){c.push(s);continue}c.push(la(u.content,r))}return c.push(a),c.join(`
37
- `)}function aa(e,t){if(!t)return ee.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Kr(t),r=e-5-n;return r<1?ee.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${ee.dim("\u250C\u2500 ")}${t}${ee.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function la(e,t){let n=Kr(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${ee.dim("\u2502")} ${r} ${ee.dim("\u2502")}`}function on(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n} minutes ago`;let r=Math.floor(n/60);return r<24?`${r} hours ago`:`${Math.floor(r/24)} days ago`}function Ke(){let e=Wr(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(ca(e))}function ca(e){if(!e)return"";let t=11,n=s=>$.dim(s.padEnd(t)),r=[];P()?(r.push({content:`${$.green("\u2713")} ${$.dim("Logged in")}`}),r.push({content:$.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${$.dim("\u25CB Not logged in")}`}),r.push({content:$.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${$.green(`last run ${on(e.audit.date??"")}`)} ${$.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${$.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${$.bold($.cyan(String(e.strategy.clusterCount??0)))} ${$.dim("clusters")} \xB7 ${$.bold($.cyan(String(e.strategy.articleCount??0)))} ${$.dim("ideas")}`:`${n("Strategy:")}${$.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${$.bold($.cyan(String(e.briefs.count??0)))} ${$.dim("ready")}`:`${n("Briefs:")}${$.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${$.green("\u2713")} ${$.bold($.cyan(String(e.content.count??0)))} ${$.dim("articles written")}`:`${n("Content:")}${$.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${$.green("updated")} ${$.dim(on(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${$.dim("not yet created")}`});let i=`${$.bold($.cyan("SEOAgent"))} ${$.dim("\xB7")} ${$.bold(e.domain)}`;return O(r,{width:78,title:i})}import{exec as ua,spawn as qr}from"child_process";import{confirm as da,isCancel as pa}from"@clack/prompts";import L from"picocolors";function _e(e,t){let n=i=>i.replace(/[-+].*$/,"").split(".").map(s=>Number.parseInt(s,10)||0).slice(0,3),r=n(e),o=n(t);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s}return 0}var fa=`https://registry.npmjs.org/${V}/latest`,qe=["free","starter","pro","scale","enterprise"],_t={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function ma(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return qe.includes(t)?t:null}function ga(e){let t=qe.indexOf(e);return t===-1||t===qe.length-1?null:qe[t+1]}async function ha(e,t=fetch){if(!e)return null;try{let n=(e.api_base||C.BASE).replace(/\/$/,""),r=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!r.ok)return null;let o=await r.json();return typeof o.plan!="string"||!o.plan?null:{plan:o.plan,email:typeof o.email=="string"&&o.email?o.email:void 0,domain:typeof o.domain=="string"&&o.domain?o.domain:void 0}}catch{return null}}function ya(e){let t=[],r=s=>L.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${L.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${L.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of qe){let a=_t[s];s===e.current?t.push({content:`${L.bold(L.green("\u25CF"))} ${L.bold(L.green(a.padEnd(11)))} ${L.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${L.yellow("\u25C6")} ${L.bold(L.yellow(a.padEnd(11)))} ${L.yellow("next tier")}`}):t.push({content:L.dim(` ${a}`)})}let i=`${L.bold(L.cyan("SEOAgent Cloud"))} ${L.dim("\xB7")} ${L.dim("your plan")}`;return O(t,{width:55,title:i})}async function He(){let e=P(),t=!!process.stdin.isTTY;if(e&&t){let n=await ha(e);if(n){let r=ma(n.plan),o=r?ga(r):null;if(r&&l.message(ya({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${_t[r]} (highest tier).`);return}if(r&&o){let i=await da({message:`Upgrade from ${_t[r]} to ${_t[o]}?`});if(pa(i)||!i){l.info("No changes.");return}}}}wa()}function wa(){let e=ka();l.info("Opening SEOAgent Cloud pricing..."),l.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;ua(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function ka(){let e=process.cwd(),t=S(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${C.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ye(e={}){let t=v,n=await $a();if(!n){l.warn("Couldn't reach the npm registry to check for a newer version."),l.message(`You're on ${t}. To force-update: npm install -g ${V}@latest`);return}if(_e(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!Wt()){l.info(`A newer CLI is available: ${t} \u2192 ${n}.`),l.message("You're running via npx, which caches the package \u2014 an unpinned spec won't auto-upgrade."),l.message(`Run the latest now by pinning the tag: npx -y ${V}@latest <cmd>`),l.message(`Still on ${t} after that? Clear the npx cache: rm -rf ~/.npm/_npx`),l.message(`Or install globally once so \`seoagent <cmd>\` + \`update-cli\` work in place: npm install -g ${V}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${V}@latest`);return}if(l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await Sa()){l.error(`Update failed. Try manually: npm install -g ${V}@latest (you may need sudo on Linux/macOS).`);return}if(l.success(`Updated to ${n}.`),e.projects===!1){l.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}l.info("Refreshing your other projects to the new version\u2026"),await ba()||l.info("Could not run the project sweep automatically \u2014 run `seoagent refresh --all` to update all projects now (otherwise each updates itself the next time you open it in Claude Code).")}function ba(){return new Promise(e=>{try{let t=qr("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function $a(e=fetch){try{let t=await e(fa,{headers:{Accept:"application/json"}});if(!t.ok)return null;let n=await t.json();return typeof n.version=="string"?n.version:null}catch{return null}}function Sa(){return new Promise(e=>{let t=qr("npm",["install","-g",`${V}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as va}from"child_process";import{randomBytes as xa}from"crypto";import{isCancel as _a,spinner as Ca,text as Ea}from"@clack/prompts";import te from"picocolors";function Hr(e,t){if(e>=500)return{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e>=400)return{status:"error",terminal:!0,message:`HTTP ${e} (client error)`};if(!t||typeof t!="object")return{status:"error",terminal:!0,message:`Malformed response: expected an object, got ${typeof t}`};let n=t;if(n.status==="ready"){if(typeof n.user_token=="string"&&typeof n.website_token=="string"){let r=typeof n.email=="string"&&n.email?n.email:void 0,o=typeof n.domain=="string"&&n.domain?n.domain:void 0;return{status:"ready",user_token:n.user_token,website_token:n.website_token,...r?{email:r}:{},...o?{domain:o}:{}}}return{status:"error",terminal:!0,message:"Malformed response: status=ready without user_token+website_token"}}return n.status==="pending"?{status:"pending"}:n.status==="expired"?{status:"expired"}:{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}var Aa=1500,Ia=300*1e3;function Ra(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;va(t,()=>{})}function Pa(){return xa(16).toString("hex")}function Oa(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function Yr(e){let t=e.trim().replace(/^https?:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"");return!t||!/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(t)?null:t.toLowerCase()}async function Ta(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,r=await fetch(n,{headers:{Accept:"application/json"}}),o=null;try{o=await r.json()}catch{}return Hr(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function ja(e){return new Promise(t=>setTimeout(t,e))}async function ze(e={}){let t=process.cwd(),n=S(t),r=(e.apiBase||C.BASE||je).replace(/\/$/,"");if(P()){l.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let p=await Ea({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(m){if(!String(m??"").trim())return"A site URL is required.";if(!Yr(String(m)))return"Please enter a valid domain like `example.com`."}});if(_a(p)){l.warn("Login cancelled.");return}let h=Yr(String(p));if(h){o=h;try{W(t,{domain:h}),l.success(`Saved domain: ${h} \u2192 .seoagent/project.md`)}catch{}}}let i=Pa(),s=Oa(r,i,o);l.message("Opening seoagent.com to connect this CLI to your account..."),l.info(`If the browser does not open, visit: ${s}`),Ra(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?Ca():null;c?.start(te.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+Ia,d=!0;for(;Date.now()<u;){d||await ja(Aa),d=!1;let p=await Ta(r,i);if(p.status==="ready"){Mr({user_token:p.user_token,website_token:p.website_token,api_base:r});let h=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",m=p.email&&p.domain?`Logged in as ${te.bold(p.email)} (${te.cyan(p.domain)}).`:p.email?`Logged in as ${te.bold(p.email)}.`:"Logged in.";w(c,"success",h,te.green(m)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){w(c,"warn",`Session expired. Run \`${f("login")}\` again.`,te.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){w(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,te.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}w(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,te.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function Ve(){Br()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as rc}from"@clack/prompts";import ne from"picocolors";import{existsSync as pn,mkdirSync as Cl,readFileSync as wo,readdirSync as El,statSync as Al,writeFileSync as Il}from"fs";import{join as fn,relative as Rl,sep as Pl}from"path";var La=new Set([502,503,504]),Na=1e4;async function J(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??Na,s=n.fetchImpl??fetch,a=n.sleep??Fa,c=n.transientStatuses??La,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:h}=Da(t,i);try{let m=await s(e,p);if(c.has(m.status)&&d<r-1){await a(zr(o,d));continue}return m}catch(m){if(u=m,d<r-1){await a(zr(o,d));continue}}finally{h()}}throw u instanceof Error?u:new Error(String(u))}function zr(e,t){return e*Math.pow(3,t)}function Fa(e){return new Promise(t=>setTimeout(t,e))}function Da(e,t){if(t<=0)return{init:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Request timed out after ${t}ms`)),t),o=e?.signal??void 0,i;o&&(o.aborted?n.abort(o.reason):(i=()=>n.abort(o.reason),o.addEventListener("abort",i,{once:!0})));let s=()=>{clearTimeout(r),o&&i&&o.removeEventListener("abort",i)};return{init:{...e,signal:n.signal},cleanup:s}}import{existsSync as an,mkdirSync as Ua,readdirSync as Vr,readFileSync as Ma,unlinkSync as Ba,writeFileSync as sn}from"fs";import{join as Ee}from"path";import R from"picocolors";function Q(e){return Ee(e,b,"inbox")}function Jr(e){return`${e.action_type}-${e.id}.md`}function Ga(e,t){let n=0;if(!an(e))return 0;for(let r of Vr(e)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(?:.+)-(\d+)\.md$/);if(!o)continue;let i=Number.parseInt(o[1],10);if(!Number.isNaN(i)&&!t.has(i))try{Ba(Ee(e,r)),n++}catch{}}return n}function Wa(e){let t=e.payload||{},n=t.articleId??"unknown",r=t.slug??null,o=t.originalTitle??null,i=t.originalUrl??null,s=t.cmsType??null;return`---
35
+ ${i}`),!e.global&&Dr(F)&&l.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),l.info(`Re-install any time with \`${f("init")}\`.`)}import $ from"picocolors";import{existsSync as Mr,mkdirSync as Ur,readFileSync as Ys,writeFileSync as zs,chmodSync as Vs,unlinkSync as Js}from"fs";import{dirname as Qs}from"path";function P(){if(!Mr(Z))return null;try{let e=JSON.parse(Ys(Z,"utf-8"));return!e.user_token||!e.website_token?null:{user_token:e.user_token,website_token:e.website_token,api_base:e.api_base||je}}catch{return null}}function Br(e){Ur(F,{recursive:!0}),Ur(Qs(Z),{recursive:!0}),zs(Z,JSON.stringify(e,null,2)+`
36
+ `,"utf-8");try{Vs(Z,384)}catch{}}function Gr(){if(!Mr(Z))return!1;try{return Js(Z),!0}catch{return!1}}import{existsSync as We,readdirSync as rn,statSync as Xs,readFileSync as Wr}from"fs";import{join as xe}from"path";function Zs(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function ea(e){let t=xe(e,"audit","latest.md");if(!We(t))return null;let n=ft(t);if(!n)return null;let r=Wr(t,"utf-8"),o=Zs(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function ta(e){try{let n=Wr(e,"utf-8").split(/\r?\n/),r=!1,o=0;for(let i of n){let s=i.trim();if(s.startsWith("|")&&s.endsWith("|")){if(/^\|\s*-+\s*(\|\s*-+\s*)+\|$/.test(s)){r=!0;continue}r&&o++}else if(r&&s==="")break}return o}catch{return 0}}function na(e){let t=xe(e,"strategy","clusters");if(!We(t))return null;let n=rn(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=ta(xe(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function ra(e){let t=xe(e,"briefs");if(!We(t))return null;let n=rn(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function oa(e){let t=xe(e,"content");if(!We(t))return null;let n=rn(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function ia(e){let t=xe(e,"roadmap.md");return We(t)?{exists:!0,updatedAt:Xs(t).mtime.toISOString()}:null}function Kr(e){let t=S(e);if(!t)return null;let n=Ne(e);return{domain:t.domain,audit:ea(n),strategy:na(n),briefs:ra(n),content:oa(n),roadmap:ia(n)}}import ee from"picocolors";var sa=/\x1b\[[0-9;]*m/g;function qr(e){return e.replace(sa,"").length}function O(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=aa(n,t.title),s=ee.dim(`\u251C${o}\u2524`),a=ee.dim(`\u2514${o}\u2518`),c=[i];for(let u of e){if("sep"in u){c.push(s);continue}c.push(la(u.content,r))}return c.push(a),c.join(`
37
+ `)}function aa(e,t){if(!t)return ee.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=qr(t),r=e-5-n;return r<1?ee.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${ee.dim("\u250C\u2500 ")}${t}${ee.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function la(e,t){let n=qr(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${ee.dim("\u2502")} ${r} ${ee.dim("\u2502")}`}function on(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n} minutes ago`;let r=Math.floor(n/60);return r<24?`${r} hours ago`:`${Math.floor(r/24)} days ago`}function Ke(){let e=Kr(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(ca(e))}function ca(e){if(!e)return"";let t=11,n=s=>$.dim(s.padEnd(t)),r=[];P()?(r.push({content:`${$.green("\u2713")} ${$.dim("Logged in")}`}),r.push({content:$.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${$.dim("\u25CB Not logged in")}`}),r.push({content:$.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${$.green(`last run ${on(e.audit.date??"")}`)} ${$.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${$.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${$.bold($.cyan(String(e.strategy.clusterCount??0)))} ${$.dim("clusters")} \xB7 ${$.bold($.cyan(String(e.strategy.articleCount??0)))} ${$.dim("ideas")}`:`${n("Strategy:")}${$.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${$.bold($.cyan(String(e.briefs.count??0)))} ${$.dim("ready")}`:`${n("Briefs:")}${$.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${$.green("\u2713")} ${$.bold($.cyan(String(e.content.count??0)))} ${$.dim("articles written")}`:`${n("Content:")}${$.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${$.green("updated")} ${$.dim(on(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${$.dim("not yet created")}`});let i=`${$.bold($.cyan("SEOAgent"))} ${$.dim("\xB7")} ${$.bold(e.domain)}`;return O(r,{width:78,title:i})}import{exec as ua,spawn as Hr}from"child_process";import{confirm as da,isCancel as pa}from"@clack/prompts";import L from"picocolors";function _e(e,t){let n=i=>i.replace(/[-+].*$/,"").split(".").map(s=>Number.parseInt(s,10)||0).slice(0,3),r=n(e),o=n(t);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s}return 0}var fa=`https://registry.npmjs.org/${J}/latest`,qe=["free","starter","pro","scale","enterprise"],_t={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function ma(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return qe.includes(t)?t:null}function ga(e){let t=qe.indexOf(e);return t===-1||t===qe.length-1?null:qe[t+1]}async function ha(e,t=fetch){if(!e)return null;try{let n=(e.api_base||C.BASE).replace(/\/$/,""),r=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!r.ok)return null;let o=await r.json();return typeof o.plan!="string"||!o.plan?null:{plan:o.plan,email:typeof o.email=="string"&&o.email?o.email:void 0,domain:typeof o.domain=="string"&&o.domain?o.domain:void 0}}catch{return null}}function ya(e){let t=[],r=s=>L.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${L.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${L.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of qe){let a=_t[s];s===e.current?t.push({content:`${L.bold(L.green("\u25CF"))} ${L.bold(L.green(a.padEnd(11)))} ${L.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${L.yellow("\u25C6")} ${L.bold(L.yellow(a.padEnd(11)))} ${L.yellow("next tier")}`}):t.push({content:L.dim(` ${a}`)})}let i=`${L.bold(L.cyan("SEOAgent Cloud"))} ${L.dim("\xB7")} ${L.dim("your plan")}`;return O(t,{width:55,title:i})}async function He(){let e=P(),t=!!process.stdin.isTTY;if(e&&t){let n=await ha(e);if(n){let r=ma(n.plan),o=r?ga(r):null;if(r&&l.message(ya({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${_t[r]} (highest tier).`);return}if(r&&o){let i=await da({message:`Upgrade from ${_t[r]} to ${_t[o]}?`});if(pa(i)||!i){l.info("No changes.");return}}}}wa()}function wa(){let e=ka();l.info("Opening SEOAgent Cloud pricing..."),l.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;ua(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function ka(){let e=process.cwd(),t=S(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${C.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ye(e={}){let t=v,n=await $a();if(!n){l.warn("Couldn't reach the npm registry to check for a newer version."),l.message(`You're on ${t}. To force-update: npm install -g ${J}@latest`);return}if(_e(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!Wt()){l.info(`A newer CLI is available: ${t} \u2192 ${n}.`),l.message("You're running via npx, which caches the package \u2014 an unpinned spec won't auto-upgrade."),l.message(`Run the latest now by pinning the tag: npx -y ${J}@latest <cmd>`),l.message(`Still on ${t} after that? Clear the npx cache: rm -rf ~/.npm/_npx`),l.message(`Or install globally once so \`seoagent <cmd>\` + \`update-cli\` work in place: npm install -g ${J}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${J}@latest`);return}if(l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await Sa()){l.error(`Update failed. Try manually: npm install -g ${J}@latest (you may need sudo on Linux/macOS).`);return}if(l.success(`Updated to ${n}.`),e.projects===!1){l.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}l.info("Refreshing your other projects to the new version\u2026"),await ba()||l.info("Could not run the project sweep automatically \u2014 run `seoagent refresh --all` to update all projects now (otherwise each updates itself the next time you open it in Claude Code).")}function ba(){return new Promise(e=>{try{let t=Hr("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function $a(e=fetch){try{let t=await e(fa,{headers:{Accept:"application/json"}});if(!t.ok)return null;let n=await t.json();return typeof n.version=="string"?n.version:null}catch{return null}}function Sa(){return new Promise(e=>{let t=Hr("npm",["install","-g",`${J}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as va}from"child_process";import{randomBytes as xa}from"crypto";import{isCancel as _a,spinner as Ca,text as Ea}from"@clack/prompts";import te from"picocolors";function Yr(e,t){if(e>=500)return{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e>=400)return{status:"error",terminal:!0,message:`HTTP ${e} (client error)`};if(!t||typeof t!="object")return{status:"error",terminal:!0,message:`Malformed response: expected an object, got ${typeof t}`};let n=t;if(n.status==="ready"){if(typeof n.user_token=="string"&&typeof n.website_token=="string"){let r=typeof n.email=="string"&&n.email?n.email:void 0,o=typeof n.domain=="string"&&n.domain?n.domain:void 0;return{status:"ready",user_token:n.user_token,website_token:n.website_token,...r?{email:r}:{},...o?{domain:o}:{}}}return{status:"error",terminal:!0,message:"Malformed response: status=ready without user_token+website_token"}}return n.status==="pending"?{status:"pending"}:n.status==="expired"?{status:"expired"}:{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}var Aa=1500,Ia=300*1e3;function Ra(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;va(t,()=>{})}function Pa(){return xa(16).toString("hex")}function Oa(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function zr(e){let t=e.trim().replace(/^https?:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"");return!t||!/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(t)?null:t.toLowerCase()}async function Ta(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,r=await fetch(n,{headers:{Accept:"application/json"}}),o=null;try{o=await r.json()}catch{}return Yr(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function ja(e){return new Promise(t=>setTimeout(t,e))}async function ze(e={}){let t=process.cwd(),n=S(t),r=(e.apiBase||C.BASE||je).replace(/\/$/,"");if(P()){l.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let p=await Ea({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(m){if(!String(m??"").trim())return"A site URL is required.";if(!zr(String(m)))return"Please enter a valid domain like `example.com`."}});if(_a(p)){l.warn("Login cancelled.");return}let y=zr(String(p));if(y){o=y;try{W(t,{domain:y}),l.success(`Saved domain: ${y} \u2192 .seoagent/project.md`)}catch{}}}let i=Pa(),s=Oa(r,i,o);l.message("Opening seoagent.com to connect this CLI to your account..."),l.info(`If the browser does not open, visit: ${s}`),Ra(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?Ca():null;c?.start(te.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+Ia,d=!0;for(;Date.now()<u;){d||await ja(Aa),d=!1;let p=await Ta(r,i);if(p.status==="ready"){Br({user_token:p.user_token,website_token:p.website_token,api_base:r});let y=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",m=p.email&&p.domain?`Logged in as ${te.bold(p.email)} (${te.cyan(p.domain)}).`:p.email?`Logged in as ${te.bold(p.email)}.`:"Logged in.";w(c,"success",y,te.green(m)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){w(c,"warn",`Session expired. Run \`${f("login")}\` again.`,te.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){w(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,te.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}w(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,te.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function Ve(){Gr()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as rc}from"@clack/prompts";import ne from"picocolors";import{existsSync as pn,mkdirSync as Cl,readFileSync as ko,readdirSync as El,statSync as Al,writeFileSync as Il}from"fs";import{join as fn,relative as Rl,sep as Pl}from"path";var La=new Set([502,503,504]),Na=1e4;async function Y(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??Na,s=n.fetchImpl??fetch,a=n.sleep??Fa,c=n.transientStatuses??La,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:y}=Da(t,i);try{let m=await s(e,p);if(c.has(m.status)&&d<r-1){await a(Vr(o,d));continue}return m}catch(m){if(u=m,d<r-1){await a(Vr(o,d));continue}}finally{y()}}throw u instanceof Error?u:new Error(String(u))}function Vr(e,t){return e*Math.pow(3,t)}function Fa(e){return new Promise(t=>setTimeout(t,e))}function Da(e,t){if(t<=0)return{init:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Request timed out after ${t}ms`)),t),o=e?.signal??void 0,i;o&&(o.aborted?n.abort(o.reason):(i=()=>n.abort(o.reason),o.addEventListener("abort",i,{once:!0})));let s=()=>{clearTimeout(r),o&&i&&o.removeEventListener("abort",i)};return{init:{...e,signal:n.signal},cleanup:s}}import{existsSync as an,mkdirSync as Ua,readdirSync as Jr,readFileSync as Ma,unlinkSync as Ba,writeFileSync as sn}from"fs";import{join as Ee}from"path";import R from"picocolors";function Q(e){return Ee(e,b,"inbox")}function Qr(e){return`${e.action_type}-${e.id}.md`}function Ga(e,t){let n=0;if(!an(e))return 0;for(let r of Jr(e)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(?:.+)-(\d+)\.md$/);if(!o)continue;let i=Number.parseInt(o[1],10);if(!Number.isNaN(i)&&!t.has(i))try{Ba(Ee(e,r)),n++}catch{}}return n}function Wa(e){let t=e.payload||{},n=t.articleId??"unknown",r=t.slug??null,o=t.originalTitle??null,i=t.originalUrl??null,s=t.cmsType??null;return`---
38
38
  action_id: ${e.id}
39
39
  action_type: ${e.action_type}
40
40
  article_id: ${n}
@@ -322,7 +322,7 @@ ${f(`ack ${e.id}`)} --failed --reason "skipped; ..."
322
322
  `}function Qa(e){switch(e.action_type){case"cli_prune_pending":return Wa(e);case"cli_technical_fix":return Ha(e);case"cli_new_content":return Ya(e);case"cli_content_update":return za(e);case"cli_sitemap_update":return Va(e);case"cli_new_landing_page":return Ja(e);default:return null}}function Xa(e){if(e.length===0)return`# SEOAgent Inbox
323
323
 
324
324
  No pending actions. Run \`seoagent sync\` later to check for new ones.
325
- `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${Jr(n)}\``);return`# SEOAgent Inbox
325
+ `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${Qr(n)}\``);return`# SEOAgent Inbox
326
326
 
327
327
  You have **${e.length}** pending action${e.length===1?"":"s"} from your dashboard.
328
328
 
@@ -334,7 +334,7 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
334
334
 
335
335
  If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
336
336
  skill knows what to do.
337
- `}function fe(e){let t=Q(e);if(!an(t))return[];let n=[];for(let r of Vr(t)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(.+)-(\d+)\.md$/);if(!o)continue;let i=o[1],s=Number.parseInt(o[2],10);if(!Number.isFinite(s))continue;let a="no title",c=null,u=null,d=null,p=null,h=null,m=null;try{let E=Ma(Ee(t,r),"utf-8"),I=E.match(/^---\n([\s\S]*?)\n---/);if(I){let q=I[1];c=Ce(q,"severity"),u=Ce(q,"issue"),d=Ce(q,"page_url");let se=Ce(q,"priority");(se==="high"||se==="medium"||se==="low")&&(p=se),h=Ce(q,"impact_estimate"),m=Ce(q,"effort_estimate")}let _=E.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);_&&(a=_[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:c,issue:u,page_url:d,priority:p,impact_estimate:h,effort_estimate:m})}return n.sort((r,o)=>r.id-o.id)}function Ae(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Za[e.severity??""]??R.dim,r=e.severity??"unknown",o=[R.dim("\u25B8"),R.bold(`id ${e.id}`),R.dim("\xB7"),R.cyan(t),n(r)];if(e.priority){let i=el[e.priority];o.push(R.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(R.dim("\xB7"),R.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(R.dim("\xB7"),R.dim(`\u23F1 ${e.effort_estimate}`)),o.push(R.dim("\u2014"),e.title),o.join(" ")}var Za={critical:e=>R.red(R.bold(e)),high:e=>R.red(e),medium:e=>R.yellow(e),low:e=>R.dim(e)},el={high:e=>R.red(R.bold(e)),medium:e=>R.yellow(e),low:e=>R.dim(e)};function Ce(e,t){let n=e.match(new RegExp(`^${t}:[ \\t]*([^\\n]*?)[ \\t]*$`,"m"));if(!n)return null;let r=n[1].replace(/^["']|["']$/g,"").trim();return!r||r==="null"||r==="~"?null:r}function Ct(e){let t=Q(e);if(!an(t))return;let n=fe(e),r=n.length===0?`# SEOAgent Inbox
337
+ `}function fe(e){let t=Q(e);if(!an(t))return[];let n=[];for(let r of Jr(t)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(.+)-(\d+)\.md$/);if(!o)continue;let i=o[1],s=Number.parseInt(o[2],10);if(!Number.isFinite(s))continue;let a="no title",c=null,u=null,d=null,p=null,y=null,m=null;try{let E=Ma(Ee(t,r),"utf-8"),I=E.match(/^---\n([\s\S]*?)\n---/);if(I){let q=I[1];c=Ce(q,"severity"),u=Ce(q,"issue"),d=Ce(q,"page_url");let se=Ce(q,"priority");(se==="high"||se==="medium"||se==="low")&&(p=se),y=Ce(q,"impact_estimate"),m=Ce(q,"effort_estimate")}let _=E.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);_&&(a=_[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:c,issue:u,page_url:d,priority:p,impact_estimate:y,effort_estimate:m})}return n.sort((r,o)=>r.id-o.id)}function Ae(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Za[e.severity??""]??R.dim,r=e.severity??"unknown",o=[R.dim("\u25B8"),R.bold(`id ${e.id}`),R.dim("\xB7"),R.cyan(t),n(r)];if(e.priority){let i=el[e.priority];o.push(R.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(R.dim("\xB7"),R.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(R.dim("\xB7"),R.dim(`\u23F1 ${e.effort_estimate}`)),o.push(R.dim("\u2014"),e.title),o.join(" ")}var Za={critical:e=>R.red(R.bold(e)),high:e=>R.red(e),medium:e=>R.yellow(e),low:e=>R.dim(e)},el={high:e=>R.red(R.bold(e)),medium:e=>R.yellow(e),low:e=>R.dim(e)};function Ce(e,t){let n=e.match(new RegExp(`^${t}:[ \\t]*([^\\n]*?)[ \\t]*$`,"m"));if(!n)return null;let r=n[1].replace(/^["']|["']$/g,"").trim();return!r||r==="null"||r==="~"?null:r}function Ct(e){let t=Q(e);if(!an(t))return;let n=fe(e),r=n.length===0?`# SEOAgent Inbox
338
338
 
339
339
  No pending actions. Run \`seoagent sync\` later to check for new ones.
340
340
  `:`# SEOAgent Inbox
@@ -349,22 +349,22 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
349
349
 
350
350
  If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
351
351
  skill knows what to do.
352
- `;sn(Ee(t,"README.md"),r,"utf-8")}function Qr(e,t){let n=Q(e);Ua(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=Ga(n,r),i=0;for(let s of t){let a=Qa(s);a!==null&&(sn(Ee(n,Jr(s)),a,"utf-8"),i++)}return sn(Ee(n,"README.md"),Xa(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as rl}from"crypto";import{existsSync as eo,mkdirSync as ol,readFileSync as il,statSync as to,writeFileSync as Zr,rmSync as sl}from"fs";import{dirname as al,join as ln,sep as ll}from"path";function tl(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var nl=[{cls:"project",test:e=>e==="project.md"},{cls:"audit",test:e=>e==="audit/latest.md"||/^audit\/(critical|high|medium|low)\.md$/.test(e)},{cls:"brief",test:e=>/^briefs\/[^/]+\.md$/.test(e)},{cls:"article",test:e=>/^content\/[^/]+\.md$/.test(e)},{cls:"cluster",test:e=>/^strategy\/clusters\/[^/]+\.md$/.test(e)},{cls:"keywords",test:e=>e==="keywords.md"||/^strategy\/keywords\/[^/]+\.md$/.test(e)},{cls:"pages",test:e=>e==="pages.md"||/^pages\/[^/]+\.md$/.test(e)},{cls:"competitors",test:e=>e==="competitors.md"},{cls:"changelog",test:e=>e==="changelog.md"}];function Xr(e,t){let n=tl(e);for(let{cls:r,test:o}of nl)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function cl(e){return"sha256:"+rl("sha256").update(e).digest("hex")}function ul(e,t,n={}){let r=[];for(let o of e.artifacts){let i=t[o.path]??{exists:!1,locallyEdited:!1};if(!i.exists){r.push({path:o.path,kind:"write",body:o.body_md});continue}if(i.contentHash===o.content_hash){r.push({path:o.path,kind:"skip"});continue}if(o.generated){r.push({path:o.path,kind:"overwrite",body:o.body_md,note:i.locallyEdited?"discarded local edits \u2014 this is a cloud-generated file (edit it in the dashboard)":void 0});continue}if(i.locallyEdited&&!n.force){r.push({path:o.path,kind:"conflict",note:"local newer than cloud, keeping local \u2014 use --force to take cloud"});continue}r.push({path:o.path,kind:"overwrite",body:o.body_md})}for(let o of e.deleted){let i=t[o];if(!(!i||!i.exists)){if(i.locallyEdited&&!n.force){r.push({path:o,kind:"delete-skipped",note:"server deleted this but it has local edits \u2014 keeping it (use --force to delete)"});continue}r.push({path:o,kind:"delete"})}}return r}function dl(e,t,n,r){let o=new Map;for(let s of t.artifacts)o.set(s.path,s.generated);let i=[];for(let s of e)s.kind!=="skip"&&i.push({path:s.path,kind:s.kind,class:Xr(s.path,o.get(s.path)??!1),...s.note?{note:s.note}:{}});return i.length===0?null:{pulled_at:r,cursor:n,changes:i}}async function no(e){let t=await oo({apiBase:e.apiBase,authHeader:e.authHeader,since:null,fetchImpl:e.fetchImpl});if(!t.ok)return{ok:!1,error:t.error};let n=e.path.replace(/^\/+/,"").replace(/\\/g,"/"),r=t.manifest.artifacts.find(o=>o.path===n);return r?{ok:!0,body:r.body_md}:{ok:!1,error:`No cloud artifact found at "${n}"`}}function ro(e,t){return ln(e,t.split("/").join(ll))}function pl(e,t,n){let r={};for(let o of t){let i=ro(e,o);if(!eo(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=to(i),a=n[o],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:cl(il(i,"utf-8")),locallyEdited:c}}return r}async function oo(e){let t=e.fetchImpl??fetch,n=`${e.apiBase}/api/cli/sync`+(e.since?`?since=${encodeURIComponent(e.since)}`:"");try{let r=await t(n,{method:"GET",headers:{Authorization:e.authHeader,Accept:"application/json"}});if(!r.ok){let i=await r.text().catch(()=>"");return{ok:!1,error:`${r.status} ${i.slice(0,200)}`.trim()}}let o=await r.json().catch(()=>null);return!o||!Array.isArray(o.artifacts)||typeof o.now!="string"?{ok:!1,error:"Malformed manifest response"}:(Array.isArray(o.deleted)||(o.deleted=[]),{ok:!0,manifest:o})}catch(r){return{ok:!1,error:r.message}}}async function io(e){let t=ln(e.projectDir,b),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!eo(t))return{...n,ok:!0};let r=await oo({apiBase:e.apiBase,authHeader:e.authHeader,since:e.since,fetchImpl:e.fetchImpl});if(!r.ok)return{...n,ok:!1,error:r.error};let o=r.manifest,i=[...o.artifacts.map(d=>d.path),...o.deleted],s=pl(t,i,e.stateFiles),a=ul(o,s,{force:e.force}),c={...n,cursor:o.now};for(let d of a){let p=ro(t,d.path);try{switch(d.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{ol(al(p),{recursive:!0}),Zr(p,d.body??"","utf-8");let h=to(p);e.stateFiles[d.path]={mtime:h.mtimeMs,size:h.size},d.kind==="write"?c.written++:c.overwritten++,d.note&&c.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":sl(p,{force:!0}),delete e.stateFiles[d.path],c.deleted++;break;case"delete-skipped":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(h){c.ok=!1,c.error=`${d.path}: ${h.message}`}}(c.conflicts>0||!c.ok)&&(c.cursor=e.since);let u=dl(a,o,c.cursor,new Date().toISOString());if(u)try{Zr(ln(t,Fn),JSON.stringify(u,null,2)+`
353
- `,"utf-8")}catch{}return c}import{existsSync as ao,mkdirSync as lo,readFileSync as fl,writeFileSync as cn}from"fs";import{dirname as co,join as ml}from"path";var un=1,so=500;function dn(e){return ml(e,b,Dn)}function Et(e){let t=dn(e);if(!ao(t))return[];try{let n=fl(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==un||!Array.isArray(o.entries)?[]:o.entries.filter(gl)}catch{return[]}}function uo(e,t){let n=dn(e),o=Et(e).filter(a=>a.action_id!==t.action_id);o.push({action_id:t.action_id,status:t.status,reason:t.reason,queued_at:new Date().toISOString()});let i=o.length>so?o.slice(-so):o,s={version:un,entries:i};try{lo(co(n),{recursive:!0}),cn(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function po(e,t){if(t.length===0)return;let n=dn(e),r=Et(e).filter(i=>!t.includes(i.action_id)),o={version:un,entries:r};try{if(r.length===0&&ao(n)){cn(n,JSON.stringify(o,null,2),"utf-8");return}lo(co(n),{recursive:!0}),cn(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function gl(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.action_id=="number"&&(t.status==="completed"||t.status==="failed")&&(t.reason===null||typeof t.reason=="string")&&typeof t.queued_at=="string"}import{existsSync as fo,readFileSync as hl,unlinkSync as yl,writeFileSync as wl,openSync as kl,closeSync as bl,mkdirSync as $l}from"fs";import{dirname as Sl,join as vl}from"path";var xl=6e4;function mo(e){return vl(e,b,Un)}function go(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??xl,i=mo(e);if(!fo(i))return At(i,r,n());let s=yo(i);return!s||n()-s.started_at>o||!_l(s.pid)?At(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function ho(e,t={}){let n=t.pid??process.pid,r=mo(e);if(!fo(r))return;let o=yo(r);if(!(o&&o.pid!==n))try{yl(r)}catch{}}function At(e,t,n){let r={pid:t,started_at:n};try{$l(Sl(e),{recursive:!0});let o=kl(e,"w");try{wl(o,JSON.stringify(r))}finally{bl(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function yo(e){try{let t=hl(e,"utf-8"),n=JSON.parse(t);return n&&typeof n=="object"&&typeof n.pid=="number"&&typeof n.started_at=="number"?n:null}catch{return null}}function _l(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var Ol=new Set([".md"]),Tl=new Set(["inbox"]);function jl(e){let t=[];function n(r,o){if(pn(r))for(let i of El(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Tl.has(i.name))continue;let s=fn(r,i.name);if(i.isDirectory())n(s,o?`${o}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a);Ol.has(c)&&t.push(s)}}}return n(e,""),t}function ko(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return fn(Gt,`${t}.json`)}function Ll(e){let t=ko(e);if(!pn(t))return{files:{},last_synced_at:null};try{return JSON.parse(wo(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Nl(e,t){Cl(Gt,{recursive:!0}),Il(ko(e),JSON.stringify(t,null,2)+`
354
- `,"utf-8")}function Fl(e,t){return Rl(e,t).split(Pl).join("/")}async function Dl(e,t){try{let n=await J(`${e}/api/cli/actions/fetch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t},body:JSON.stringify({})});if(!n.ok){let o=await n.text().catch(()=>"");return{ok:!1,actions:[],error:`${n.status} ${o.slice(0,200)}`}}let r=await n.json().catch(()=>null);return!r||r.status!=="ok"||!Array.isArray(r.actions)?{ok:!1,actions:[],error:"Malformed response"}:{ok:!0,actions:r.actions}}catch(n){return{ok:!1,actions:[],error:n.message}}}async function Ul(e,t,n){try{let r=await J(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,status:r.status,error:o.slice(0,200)}}return{ok:!0,status:r.status}}catch(r){return{ok:!1,status:0,error:r.message}}}async function bo(e,t={}){let n=P();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=S(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=fn(e,b);if(!pn(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!go(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await Ml(e,t,n,r,o)}finally{ho(e)}}async function Ml(e,t,n,r,o){let i=Ll(r.domain),s=jl(o),a=n.api_base||C.BASE,c=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,p=[],h=0,m=await Bl(e,a,c);if(!t.pullOnly)for(let j of s){let Te=Fl(o,j);if(t.pathFilter&&!Te.endsWith(t.pathFilter))continue;let at=Al(j),Mt=i.files[Te];if(!(!Mt||Mt.mtime!==at.mtimeMs||Mt.size!==at.size)&&!t.force)continue;h++;let pi=wo(j,"utf-8"),Bt=await Ul(a,{path:Te,contents:pi,domain:r.domain},c);Bt.ok?(i.files[Te]={mtime:at.mtimeMs,size:at.size},u++):(d++,p.push(`${Te}: ${Bt.status} ${Bt.error??""}`.trim()))}let E=await Dl(a,c),I=0,G=0;if(E.ok){let j=Qr(e,E.actions);I=j.wrote,G=j.removed}else E.error&&p.push(`pull actions: ${E.error}`);let _,q=!1,se=i.last_synced_at;if(!t.pushOnly){let j=await io({projectDir:e,apiBase:a,authHeader:c,since:i.last_synced_at,stateFiles:i.files,force:t.force});j.ok?se=j.cursor:(q=!0,j.error&&p.push(`pull: ${j.error}`)),_={written:j.written,overwritten:j.overwritten,skipped:j.skipped,conflicts:j.conflicts,deleted:j.deleted,warnings:j.warnings}}let di=!!_&&_.written+_.overwritten+_.deleted+_.conflicts>0;if(i.last_synced_at=se,Nl(r.domain,i),h===0&&I===0&&G===0&&!di&&m.flushed===0&&m.dropped===0&&!q&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:p,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:_};let jn=d===0&&!q;return{ok:jn,reason:jn?void 0:"error",synced:u,failed:d,errors:p,actionsPulled:I,actionsRemoved:G,acksFlushed:m.flushed,acksDropped:m.dropped,pull:_}}async function Bl(e,t,n){let r=Et(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let c=await Gl(a,t,n);c==="flushed"?(o++,s.push(a.action_id)):c==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&po(e,s),{flushed:o,dropped:i}}async function Gl(e,t,n){try{let r=await J(`${t}/api/cli/actions/${e.action_id}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify({status:e.status,error_message:e.status==="failed"?e.reason:null,result:e.status==="failed"?{declined:!0,reason:e.reason}:{applied:!0}})});return r.ok?"flushed":r.status===409||r.status>=400&&r.status<500?"already-settled":"transient"}catch{return"transient"}}function $o(e){let t;try{t=S(e)}catch{return{refreshed:!1,reason:"error"}}if(!t)return{refreshed:!1,reason:"no-project"};let n=t.skill_version||t.seoagent_version||"0.0.0";if(_e(v,n)<=0){if(!t.skill_version)try{W(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return we(e),W(e,{skill_version:v}),{refreshed:!0,from:n,to:v,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function mn(e){let t;try{t=S(e)}catch{return{refreshed:!1,from:null,to:v,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:v,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return we(e),W(e,{skill_version:v}),{refreshed:!0,from:n,to:v,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:v,reason:"error"}}}import{existsSync as Wl,mkdirSync as Kl,readFileSync as ql,writeFileSync as Hl}from"fs";var Yl="https://registry.npmjs.org/@seoagent-official/seoagent/latest",zl=1440*60*1e3,Vl=720*60*1e3,Jl=2e3;function Ql(e,t,n=zl){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function Xl(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??Vl;if(!n||_e(n,t)<=0)return null;if(r.notifiedVersion===n&&r.notifiedAt){let s=Date.parse(r.notifiedAt);if(!Number.isNaN(s)&&o.getTime()-s<i)return null}return`\u2191 SEOAgent ${n} is available (you have ${t}). Ask me to run \`seoagent update-cli\`, or run it yourself, to upgrade the CLI + all your projects.`}async function Zl(e){let t=e.readCache();if(Ql(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=Xl({current:e.current,latest:t.latest,cache:t,now:e.now,notifyIntervalMs:e.notifyIntervalMs});return n&&t.latest&&e.writeCache({...t,notifiedVersion:t.latest,notifiedAt:e.now.toISOString()}),n}function ec(){try{return Wl(ut)?JSON.parse(ql(ut,"utf-8")):{}}catch{return{}}}function tc(e){try{Kl(F,{recursive:!0}),Hl(ut,JSON.stringify(e,null,2)+`
355
- `,"utf-8")}catch{}}async function nc(){try{let e=await fetch(Yl,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(Jl)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function So(e){try{return await Zl({current:e,now:new Date,fetchLatest:nc,readCache:ec,writeCache:tc})}catch{return null}}async function Y(e={}){let t=$o(process.cwd());if(t.refreshed){try{le(process.cwd())}catch{}e.silent||l.info(ne.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}ce(process.cwd());let n=await So(v);n&&l.message(ne.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?rc():null;i?.start(`${o} ${ne.dim(".seoagent/")} with your dashboard\u2026`);let s=await bo(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){s.ok||(process.exitCode=0);return}if(s.reason==="no-auth"){w(i,"info",`Not logged in. Run \`${f("login")}\` to enable cloud sync.`,ne.dim("Not logged in \u2014 cloud sync skipped.")),i&&l.info(`Run \`${f("login")}\` to enable cloud sync.`);return}if(s.reason==="no-project"){w(i,"info",`No SEOAgent project here. Run \`${f("init")}\` first.`,ne.dim("No SEOAgent project \u2014 sync skipped.")),i&&l.info(`Run \`${f("init")}\` first.`);return}if(s.reason==="no-changes"){w(i,"info","Already in sync.",ne.green("Already in sync."));return}if(s.reason==="busy"){w(i,"info","Another sync is in progress \u2014 skipping this run.",ne.dim("Another sync is in progress \u2014 skipping this run."));return}let a=oc(s);w(i,"success",a??"Sync complete.",ne.green(a??"Sync complete.")),s.synced>0&&l.success(`Synced ${s.synced} file${s.synced===1?"":"s"} to your dashboard.`);let c=s.pull;if(c){let u=c.written+c.overwritten;u>0&&l.success(`Pulled ${u} file${u===1?"":"s"} from the cloud`+(c.overwritten>0?` (${c.overwritten} updated)`:"")),c.deleted>0&&l.info(`Removed ${c.deleted} file${c.deleted===1?"":"s"} deleted in the cloud.`),c.conflicts>0&&l.warn(`${c.conflicts} conflict${c.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let d of c.warnings.slice(0,5))l.info(` \u2022 ${d}`)}if(s.acksFlushed&&s.acksFlushed>0&&l.success(`Flushed ${s.acksFlushed} offline ack${s.acksFlushed===1?"":"s"} from the queue.`),s.acksDropped&&s.acksDropped>0&&l.info(`Dropped ${s.acksDropped} stale ack${s.acksDropped===1?"":"s"} (already settled server-side).`),s.actionsPulled&&s.actionsPulled>0&&(l.success(`Pulled ${s.actionsPulled} pending action${s.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||l.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),s.actionsRemoved&&s.actionsRemoved>0&&l.info(`Cleaned up ${s.actionsRemoved} stale inbox file${s.actionsRemoved===1?"":"s"}.`),s.failed>0){l.warn(`${s.failed} file${s.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let u of s.errors.slice(0,3))l.info(` \u2022 ${u}`)}}function oc(e){let t=e.synced,n=e.pull?e.pull.written+e.pull.overwritten:0,r=e.actionsPulled??0,o=e.acksFlushed??0,i=e.pull?.conflicts??0,s=[];return o>0&&s.push(`${o} ack${o===1?"":"s"} flushed`),t>0&&s.push(`${t} pushed`),n>0&&s.push(`${n} pulled`),r>0&&s.push(`${r} action${r===1?"":"s"}`),i>0&&s.push(`${i} conflict${i===1?"":"s"}`),s.length===0&&e.failed===0?null:s.length>0?s.join(" \xB7 "):"Sync complete."}function D(e){let t=S(e);return t||(l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function me(e={}){if(e.print){let t=P();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let n=t.api_base||C.BASE,r=await no({apiBase:n,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!r.ok){l.warn(r.error),process.exitCode=1;return}process.stdout.write(r.body),r.body.endsWith(`
352
+ `;sn(Ee(t,"README.md"),r,"utf-8")}function Xr(e,t){let n=Q(e);Ua(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=Ga(n,r),i=0;for(let s of t){let a=Qa(s);a!==null&&(sn(Ee(n,Qr(s)),a,"utf-8"),i++)}return sn(Ee(n,"README.md"),Xa(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as rl}from"crypto";import{existsSync as to,mkdirSync as ol,readFileSync as il,statSync as no,writeFileSync as eo,rmSync as sl}from"fs";import{dirname as al,join as ln,sep as ll}from"path";function tl(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var nl=[{cls:"project",test:e=>e==="project.md"},{cls:"audit",test:e=>e==="audit/latest.md"||/^audit\/(critical|high|medium|low)\.md$/.test(e)},{cls:"brief",test:e=>/^briefs\/[^/]+\.md$/.test(e)},{cls:"article",test:e=>/^content\/[^/]+\.md$/.test(e)},{cls:"cluster",test:e=>/^strategy\/clusters\/[^/]+\.md$/.test(e)},{cls:"keywords",test:e=>e==="keywords.md"||/^strategy\/keywords\/[^/]+\.md$/.test(e)},{cls:"pages",test:e=>e==="pages.md"||/^pages\/[^/]+\.md$/.test(e)},{cls:"competitors",test:e=>e==="competitors.md"},{cls:"changelog",test:e=>e==="changelog.md"}];function Zr(e,t){let n=tl(e);for(let{cls:r,test:o}of nl)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function cl(e){return"sha256:"+rl("sha256").update(e).digest("hex")}function ul(e,t,n={}){let r=[];for(let o of e.artifacts){let i=t[o.path]??{exists:!1,locallyEdited:!1};if(!i.exists){r.push({path:o.path,kind:"write",body:o.body_md});continue}if(i.contentHash===o.content_hash){r.push({path:o.path,kind:"skip"});continue}if(o.generated){r.push({path:o.path,kind:"overwrite",body:o.body_md,note:i.locallyEdited?"discarded local edits \u2014 this is a cloud-generated file (edit it in the dashboard)":void 0});continue}if(i.locallyEdited&&!n.force){r.push({path:o.path,kind:"conflict",note:"local newer than cloud, keeping local \u2014 use --force to take cloud"});continue}r.push({path:o.path,kind:"overwrite",body:o.body_md})}for(let o of e.deleted){let i=t[o];if(!(!i||!i.exists)){if(i.locallyEdited&&!n.force){r.push({path:o,kind:"delete-skipped",note:"server deleted this but it has local edits \u2014 keeping it (use --force to delete)"});continue}r.push({path:o,kind:"delete"})}}return r}function dl(e,t,n,r){let o=new Map;for(let s of t.artifacts)o.set(s.path,s.generated);let i=[];for(let s of e)s.kind!=="skip"&&i.push({path:s.path,kind:s.kind,class:Zr(s.path,o.get(s.path)??!1),...s.note?{note:s.note}:{}});return i.length===0?null:{pulled_at:r,cursor:n,changes:i}}async function ro(e){let t=await io({apiBase:e.apiBase,authHeader:e.authHeader,since:null,fetchImpl:e.fetchImpl});if(!t.ok)return{ok:!1,error:t.error};let n=e.path.replace(/^\/+/,"").replace(/\\/g,"/"),r=t.manifest.artifacts.find(o=>o.path===n);return r?{ok:!0,body:r.body_md}:{ok:!1,error:`No cloud artifact found at "${n}"`}}function oo(e,t){return ln(e,t.split("/").join(ll))}function pl(e,t,n){let r={};for(let o of t){let i=oo(e,o);if(!to(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=no(i),a=n[o],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:cl(il(i,"utf-8")),locallyEdited:c}}return r}async function io(e){let t=e.fetchImpl??fetch,n=`${e.apiBase}/api/cli/sync`+(e.since?`?since=${encodeURIComponent(e.since)}`:"");try{let r=await t(n,{method:"GET",headers:{Authorization:e.authHeader,Accept:"application/json"}});if(!r.ok){let i=await r.text().catch(()=>"");return{ok:!1,error:`${r.status} ${i.slice(0,200)}`.trim()}}let o=await r.json().catch(()=>null);return!o||!Array.isArray(o.artifacts)||typeof o.now!="string"?{ok:!1,error:"Malformed manifest response"}:(Array.isArray(o.deleted)||(o.deleted=[]),{ok:!0,manifest:o})}catch(r){return{ok:!1,error:r.message}}}async function so(e){let t=ln(e.projectDir,b),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!to(t))return{...n,ok:!0};let r=await io({apiBase:e.apiBase,authHeader:e.authHeader,since:e.since,fetchImpl:e.fetchImpl});if(!r.ok)return{...n,ok:!1,error:r.error};let o=r.manifest,i=[...o.artifacts.map(d=>d.path),...o.deleted],s=pl(t,i,e.stateFiles),a=ul(o,s,{force:e.force}),c={...n,cursor:o.now};for(let d of a){let p=oo(t,d.path);try{switch(d.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{ol(al(p),{recursive:!0}),eo(p,d.body??"","utf-8");let y=no(p);e.stateFiles[d.path]={mtime:y.mtimeMs,size:y.size},d.kind==="write"?c.written++:c.overwritten++,d.note&&c.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":sl(p,{force:!0}),delete e.stateFiles[d.path],c.deleted++;break;case"delete-skipped":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(y){c.ok=!1,c.error=`${d.path}: ${y.message}`}}(c.conflicts>0||!c.ok)&&(c.cursor=e.since);let u=dl(a,o,c.cursor,new Date().toISOString());if(u)try{eo(ln(t,Dn),JSON.stringify(u,null,2)+`
353
+ `,"utf-8")}catch{}return c}import{existsSync as lo,mkdirSync as co,readFileSync as fl,writeFileSync as cn}from"fs";import{dirname as uo,join as ml}from"path";var un=1,ao=500;function dn(e){return ml(e,b,Un)}function Et(e){let t=dn(e);if(!lo(t))return[];try{let n=fl(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==un||!Array.isArray(o.entries)?[]:o.entries.filter(gl)}catch{return[]}}function po(e,t){let n=dn(e),o=Et(e).filter(a=>a.action_id!==t.action_id);o.push({action_id:t.action_id,status:t.status,reason:t.reason,queued_at:new Date().toISOString()});let i=o.length>ao?o.slice(-ao):o,s={version:un,entries:i};try{co(uo(n),{recursive:!0}),cn(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function fo(e,t){if(t.length===0)return;let n=dn(e),r=Et(e).filter(i=>!t.includes(i.action_id)),o={version:un,entries:r};try{if(r.length===0&&lo(n)){cn(n,JSON.stringify(o,null,2),"utf-8");return}co(uo(n),{recursive:!0}),cn(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function gl(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.action_id=="number"&&(t.status==="completed"||t.status==="failed")&&(t.reason===null||typeof t.reason=="string")&&typeof t.queued_at=="string"}import{existsSync as mo,readFileSync as hl,unlinkSync as yl,writeFileSync as wl,openSync as kl,closeSync as bl,mkdirSync as $l}from"fs";import{dirname as Sl,join as vl}from"path";var xl=6e4;function go(e){return vl(e,b,Mn)}function ho(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??xl,i=go(e);if(!mo(i))return At(i,r,n());let s=wo(i);return!s||n()-s.started_at>o||!_l(s.pid)?At(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function yo(e,t={}){let n=t.pid??process.pid,r=go(e);if(!mo(r))return;let o=wo(r);if(!(o&&o.pid!==n))try{yl(r)}catch{}}function At(e,t,n){let r={pid:t,started_at:n};try{$l(Sl(e),{recursive:!0});let o=kl(e,"w");try{wl(o,JSON.stringify(r))}finally{bl(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function wo(e){try{let t=hl(e,"utf-8"),n=JSON.parse(t);return n&&typeof n=="object"&&typeof n.pid=="number"&&typeof n.started_at=="number"?n:null}catch{return null}}function _l(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var Ol=new Set([".md"]),Tl=new Set(["inbox"]);function jl(e){let t=[];function n(r,o){if(pn(r))for(let i of El(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Tl.has(i.name))continue;let s=fn(r,i.name);if(i.isDirectory())n(s,o?`${o}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a);Ol.has(c)&&t.push(s)}}}return n(e,""),t}function bo(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return fn(Gt,`${t}.json`)}function Ll(e){let t=bo(e);if(!pn(t))return{files:{},last_synced_at:null};try{return JSON.parse(ko(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Nl(e,t){Cl(Gt,{recursive:!0}),Il(bo(e),JSON.stringify(t,null,2)+`
354
+ `,"utf-8")}function Fl(e,t){return Rl(e,t).split(Pl).join("/")}async function Dl(e,t){try{let n=await Y(`${e}/api/cli/actions/fetch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t},body:JSON.stringify({})});if(!n.ok){let o=await n.text().catch(()=>"");return{ok:!1,actions:[],error:`${n.status} ${o.slice(0,200)}`}}let r=await n.json().catch(()=>null);return!r||r.status!=="ok"||!Array.isArray(r.actions)?{ok:!1,actions:[],error:"Malformed response"}:{ok:!0,actions:r.actions}}catch(n){return{ok:!1,actions:[],error:n.message}}}async function Ul(e,t,n){try{let r=await Y(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,status:r.status,error:o.slice(0,200)}}return{ok:!0,status:r.status}}catch(r){return{ok:!1,status:0,error:r.message}}}async function $o(e,t={}){let n=P();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=S(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=fn(e,b);if(!pn(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!ho(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await Ml(e,t,n,r,o)}finally{yo(e)}}async function Ml(e,t,n,r,o){let i=Ll(r.domain),s=jl(o),a=n.api_base||C.BASE,c=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,p=[],y=0,m=await Bl(e,a,c);if(!t.pullOnly)for(let j of s){let Te=Fl(o,j);if(t.pathFilter&&!Te.endsWith(t.pathFilter))continue;let at=Al(j),Mt=i.files[Te];if(!(!Mt||Mt.mtime!==at.mtimeMs||Mt.size!==at.size)&&!t.force)continue;y++;let pi=ko(j,"utf-8"),Bt=await Ul(a,{path:Te,contents:pi,domain:r.domain},c);Bt.ok?(i.files[Te]={mtime:at.mtimeMs,size:at.size},u++):(d++,p.push(`${Te}: ${Bt.status} ${Bt.error??""}`.trim()))}let E=await Dl(a,c),I=0,G=0;if(E.ok){let j=Xr(e,E.actions);I=j.wrote,G=j.removed}else E.error&&p.push(`pull actions: ${E.error}`);let _,q=!1,se=i.last_synced_at;if(!t.pushOnly){let j=await so({projectDir:e,apiBase:a,authHeader:c,since:i.last_synced_at,stateFiles:i.files,force:t.force});j.ok?se=j.cursor:(q=!0,j.error&&p.push(`pull: ${j.error}`)),_={written:j.written,overwritten:j.overwritten,skipped:j.skipped,conflicts:j.conflicts,deleted:j.deleted,warnings:j.warnings}}let di=!!_&&_.written+_.overwritten+_.deleted+_.conflicts>0;if(i.last_synced_at=se,Nl(r.domain,i),y===0&&I===0&&G===0&&!di&&m.flushed===0&&m.dropped===0&&!q&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:p,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:_};let Ln=d===0&&!q;return{ok:Ln,reason:Ln?void 0:"error",synced:u,failed:d,errors:p,actionsPulled:I,actionsRemoved:G,acksFlushed:m.flushed,acksDropped:m.dropped,pull:_}}async function Bl(e,t,n){let r=Et(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let c=await Gl(a,t,n);c==="flushed"?(o++,s.push(a.action_id)):c==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&fo(e,s),{flushed:o,dropped:i}}async function Gl(e,t,n){try{let r=await Y(`${t}/api/cli/actions/${e.action_id}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify({status:e.status,error_message:e.status==="failed"?e.reason:null,result:e.status==="failed"?{declined:!0,reason:e.reason}:{applied:!0}})});return r.ok?"flushed":r.status===409||r.status>=400&&r.status<500?"already-settled":"transient"}catch{return"transient"}}function So(e){let t;try{t=S(e)}catch{return{refreshed:!1,reason:"error"}}if(!t)return{refreshed:!1,reason:"no-project"};let n=t.skill_version||t.seoagent_version||"0.0.0";if(_e(v,n)<=0){if(!t.skill_version)try{W(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return we(e),W(e,{skill_version:v}),{refreshed:!0,from:n,to:v,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function mn(e){let t;try{t=S(e)}catch{return{refreshed:!1,from:null,to:v,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:v,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return we(e),W(e,{skill_version:v}),{refreshed:!0,from:n,to:v,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:v,reason:"error"}}}import{existsSync as Wl,mkdirSync as Kl,readFileSync as ql,writeFileSync as Hl}from"fs";var Yl="https://registry.npmjs.org/@seoagent-official/seoagent/latest",zl=1440*60*1e3,Vl=720*60*1e3,Jl=2e3;function Ql(e,t,n=zl){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function Xl(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??Vl;if(!n||_e(n,t)<=0)return null;if(r.notifiedVersion===n&&r.notifiedAt){let s=Date.parse(r.notifiedAt);if(!Number.isNaN(s)&&o.getTime()-s<i)return null}return`\u2191 SEOAgent ${n} is available (you have ${t}). Ask me to run \`seoagent update-cli\`, or run it yourself, to upgrade the CLI + all your projects.`}async function Zl(e){let t=e.readCache();if(Ql(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=Xl({current:e.current,latest:t.latest,cache:t,now:e.now,notifyIntervalMs:e.notifyIntervalMs});return n&&t.latest&&e.writeCache({...t,notifiedVersion:t.latest,notifiedAt:e.now.toISOString()}),n}function ec(){try{return Wl(ut)?JSON.parse(ql(ut,"utf-8")):{}}catch{return{}}}function tc(e){try{Kl(F,{recursive:!0}),Hl(ut,JSON.stringify(e,null,2)+`
355
+ `,"utf-8")}catch{}}async function nc(){try{let e=await fetch(Yl,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(Jl)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function vo(e){try{return await Zl({current:e,now:new Date,fetchLatest:nc,readCache:ec,writeCache:tc})}catch{return null}}async function z(e={}){let t=So(process.cwd());if(t.refreshed){try{le(process.cwd())}catch{}e.silent||l.info(ne.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}ce(process.cwd());let n=await vo(v);n&&l.message(ne.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?rc():null;i?.start(`${o} ${ne.dim(".seoagent/")} with your dashboard\u2026`);let s=await $o(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){s.ok||(process.exitCode=0);return}if(s.reason==="no-auth"){w(i,"info",`Not logged in. Run \`${f("login")}\` to enable cloud sync.`,ne.dim("Not logged in \u2014 cloud sync skipped.")),i&&l.info(`Run \`${f("login")}\` to enable cloud sync.`);return}if(s.reason==="no-project"){w(i,"info",`No SEOAgent project here. Run \`${f("init")}\` first.`,ne.dim("No SEOAgent project \u2014 sync skipped.")),i&&l.info(`Run \`${f("init")}\` first.`);return}if(s.reason==="no-changes"){w(i,"info","Already in sync.",ne.green("Already in sync."));return}if(s.reason==="busy"){w(i,"info","Another sync is in progress \u2014 skipping this run.",ne.dim("Another sync is in progress \u2014 skipping this run."));return}let a=oc(s);w(i,"success",a??"Sync complete.",ne.green(a??"Sync complete.")),s.synced>0&&l.success(`Synced ${s.synced} file${s.synced===1?"":"s"} to your dashboard.`);let c=s.pull;if(c){let u=c.written+c.overwritten;u>0&&l.success(`Pulled ${u} file${u===1?"":"s"} from the cloud`+(c.overwritten>0?` (${c.overwritten} updated)`:"")),c.deleted>0&&l.info(`Removed ${c.deleted} file${c.deleted===1?"":"s"} deleted in the cloud.`),c.conflicts>0&&l.warn(`${c.conflicts} conflict${c.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let d of c.warnings.slice(0,5))l.info(` \u2022 ${d}`)}if(s.acksFlushed&&s.acksFlushed>0&&l.success(`Flushed ${s.acksFlushed} offline ack${s.acksFlushed===1?"":"s"} from the queue.`),s.acksDropped&&s.acksDropped>0&&l.info(`Dropped ${s.acksDropped} stale ack${s.acksDropped===1?"":"s"} (already settled server-side).`),s.actionsPulled&&s.actionsPulled>0&&(l.success(`Pulled ${s.actionsPulled} pending action${s.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||l.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),s.actionsRemoved&&s.actionsRemoved>0&&l.info(`Cleaned up ${s.actionsRemoved} stale inbox file${s.actionsRemoved===1?"":"s"}.`),s.failed>0){l.warn(`${s.failed} file${s.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let u of s.errors.slice(0,3))l.info(` \u2022 ${u}`)}}function oc(e){let t=e.synced,n=e.pull?e.pull.written+e.pull.overwritten:0,r=e.actionsPulled??0,o=e.acksFlushed??0,i=e.pull?.conflicts??0,s=[];return o>0&&s.push(`${o} ack${o===1?"":"s"} flushed`),t>0&&s.push(`${t} pushed`),n>0&&s.push(`${n} pulled`),r>0&&s.push(`${r} action${r===1?"":"s"}`),i>0&&s.push(`${i} conflict${i===1?"":"s"}`),s.length===0&&e.failed===0?null:s.length>0?s.join(" \xB7 "):"Sync complete."}function D(e){let t=S(e);return t||(l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function me(e={}){if(e.print){let t=P();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let n=t.api_base||C.BASE,r=await ro({apiBase:n,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!r.ok){l.warn(r.error),process.exitCode=1;return}process.stdout.write(r.body),r.body.endsWith(`
356
356
  `)||process.stdout.write(`
357
- `);return}await Y({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as ic,readdirSync as sc,unlinkSync as ac}from"fs";import{join as vo}from"path";import{isCancel as lc,select as cc}from"@clack/prompts";async function re(e,t={}){let n=null;if(e){let u=Number.parseInt(e,10);if(Number.isNaN(u)||u<=0){l.error(`Invalid action id: "${e}"`),process.exitCode=1;return}n=u}else if(n=await uc(),n===null)return;let r=n,o=P();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let i=o.api_base||C.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",c;try{c=await J(`${i}/api/cli/actions/${r}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:s},body:JSON.stringify({status:a,error_message:t.failed&&t.reason?t.reason:null,result:t.failed?{declined:!0,reason:t.reason??null}:{applied:!0}})})}catch{uo(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),gn(r),Ct(process.cwd()),t.silent||l.warn(`Network unavailable \u2014 ack queued locally. Run \`${f("sync")}\` when you're back online; it'll flush automatically.`);return}if(!c.ok){let u=await c.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(c.status===409&&d?.code==="already_acked"){gn(r),Ct(process.cwd());let E=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||l.success(`Action ${r} was already ${E}.`);return}let p=typeof d?.code=="string"?d.code:null,h=typeof d?.error=="string"?d.error:u,m=p?`, code: ${p}`:"";l.error(`Server rejected ack (${c.status}${m}): ${h.slice(0,200)}`),process.exitCode=1;return}gn(r),Ct(process.cwd()),!t.silent&&(t.failed?l.success(`Action ${r} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):l.success(`Action ${r} marked completed.`),l.info(` inbox location: ${vo(b,"inbox")}`))}function gn(e){let t=Q(process.cwd());if(ic(t)){for(let n of sc(t))if(n.endsWith(`-${e}.md`))try{ac(vo(t,n))}catch{}}}async function uc(){let e=process.cwd(),t=fe(e);if(t.length===0)return l.info("No pending actions in .seoagent/inbox/."),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued.`),null;if(!process.stdout.isTTY)return l.error(`Cannot show interactive picker in non-TTY mode. Pass an action id explicitly, or run \`${f("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await cc({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Ae(r)}))});return lc(n)?(l.info("Cancelled \u2014 no action closed out."),null):n}import It from"picocolors";async function hn(e={}){let t=process.cwd();if(!e.json&&!D(t))return;let n=fe(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:Q(t),actions:n})+`
358
- `);return}if(n.length===0){l.info(It.dim("No pending actions.")),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued, or \`${f("autopilot status")}\` to check whether autopilot is on.`);return}l.message(`${It.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(Ae(r));l.message(""),l.message(`Apply one: ${It.bold(f("ack <id>"))} \xB7 Interactive picker: ${It.bold(f("ack"))} (no id)`)}import{readFileSync as bc}from"fs";import{join as $c,relative as Sc}from"path";import{confirm as Ao,isCancel as Pt,multiselect as vc,note as Po,select as xc}from"@clack/prompts";import g from"picocolors";import{query as _c}from"@anthropic-ai/claude-agent-sdk";import{existsSync as dc,readdirSync as pc}from"fs";import{homedir as fc}from"os";import{join as mc}from"path";import{execSync as yn}from"child_process";function Je(){return process.env.ANTHROPIC_API_KEY?"env-key":process.env.CLAUDE_CODE_USE_BEDROCK==="1"||process.env.CLAUDE_CODE_USE_VERTEX==="1"||process.env.CLAUDE_CODE_USE_FOUNDRY==="1"||process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS==="1"?"enterprise":gc()?hc()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function gc(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return yn(e,{stdio:"ignore"}),!0}catch{return!1}}function hc(){let e=mc(fc(),".claude");if(!dc(e))return!1;try{return pc(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function xo(){try{return yn("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function _o(){try{return yn("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var X={"env-key":{summary:"Using ANTHROPIC_API_KEY env var.",next:""},enterprise:{summary:"Using enterprise provider (Bedrock / Vertex / Foundry).",next:""},"claude-session-likely":{summary:"Using your existing `claude login` session.",next:""},"claude-installed-no-session":{summary:"Claude Code is installed but you are not logged in.",next:"Run `claude login` to sign in with your Claude.ai / Pro / Max account, or set `ANTHROPIC_API_KEY` and re-run."},"not-installed":{summary:"Claude Code is not installed on this machine.",next:"Install it with `npm install -g @anthropic-ai/claude-code` then `claude login`, or set `ANTHROPIC_API_KEY` (get one at https://console.anthropic.com/) and re-run."}};import{marked as Eo}from"marked";import{markedTerminal as yc}from"marked-terminal";import wn from"picocolors";var Co=!1;function wc(){Co||(Eo.use(yc({reflowText:!1,width:100})),Co=!0)}function Rt(e){if(!e)return e;wc();try{let t=Eo.parse(e);return typeof t=="string"?kc(t):e}catch{return e}}function kc(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>wn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>wn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+wn.italic(r))}async function bn(e={}){let t=process.cwd();if(!D(t))return;if(!process.stdout.isTTY&&!e.yes){l.error(`\`${f("process")}\` needs an interactive TTY for the sync + selection prompts. Use \`--yes\` to skip prompts and process everything (for CI/CD).`),process.exitCode=1;return}if(!await Pc(e.yes)){process.exitCode=1;return}if(e.yes)await Y({embedded:!0});else{let u=await xc({message:"Sync the inbox before processing?",options:[{value:"sync",label:"Sync (recommended) \u2014 pull pending actions + push local changes"},{value:"pull",label:"Pull only \u2014 get new actions, skip pushing your local changes"},{value:"skip",label:"Skip \u2014 use the current local inbox state"}],initialValue:"sync"});if(Pt(u)){l.info("Cancelled.");return}u==="sync"?await Y({embedded:!0}):u==="pull"&&await me({embedded:!0})}let r=fe(t);if(r.length===0){l.info(g.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),l.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(m=>m.priority!==null),d=u?r.filter(m=>m.priority==="high").map(m=>m.id):r.map(m=>m.id),p=u&&d.length===0?" (no high-priority actions \u2014 toggle to select)":u?` (${d.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",h=await vc({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(m=>({value:m.id,label:Ae(m)})),initialValues:d,required:!1});if(Pt(h)){l.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(h)||h.length===0){l.info("No actions selected. Nothing to do.");return}o=h}let i=0,s=0,a=0,c=Date.now();for(let u=0;u<o.length;u++){let d=o[u],p=r.find(_=>_.id===d);if(!p)continue;Cc({index:u+1,total:o.length,entry:p});let h=$c(Q(t),p.filename),m;try{m=bc(h,"utf-8")}catch(_){l.error(` Could not read ${p.filename}: ${_.message}`),a++;continue}let E=Date.now(),I=await Rc({cwd:t,entry:p,actionContent:m,model:e.model}),G=Io(Date.now()-E);if(I.kind==="applied")try{await re(String(d),{silent:!0}),i++,l.message("");let _=I.summary?`
359
- `+g.dim(" "+I.summary):"";l.message(` ${g.green("\u2713")} id ${d} ${g.dim("\u2014 applied in "+G)}${_}`)}catch(_){l.warn(` Applied but ack failed: ${_.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(I.kind==="declined")try{await re(String(d),{silent:!0,failed:!0,reason:I.reason}),s++,l.message(""),l.message(` ${g.yellow("\u2298")} id ${d} ${g.dim("\u2014 declined: "+K(I.reason,100))}`)}catch(_){l.warn(` Could not ack decline: ${_.message}. Run \`seoagent ack ${d} --failed --reason "${I.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${g.red("\u2717")} id ${d} ${g.dim("\u2014 agent did not converge after "+G)}`)}Ac({applied:i,declined:s,failed:a,total:o.length,elapsed:Io(Date.now()-c)})}function Cc(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=Ec[i]??g.dim,a=[g.bold(`[${t}/${n}]`),g.dim("\xB7"),g.bold(`id ${r.id}`),g.dim("\xB7"),g.cyan(o),s(i)].join(" ");Po(r.title,a)}var Ec={critical:e=>g.red(g.bold(e)),high:g.red,medium:g.yellow,low:g.dim};function Ac(e){let{applied:t,declined:n,failed:r,total:o,elapsed:i}=e,s=t+n,a;if(s===o&&r===0)a=n===0?g.green(`\u2713 ${t}/${o} applied`):g.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=g.red(`\u2717 0/${o} applied`);else{let c=[`${t}/${o} applied`];n>0&&c.push(`${n} declined`),r>0&&c.push(`${r} failed`),a=g.yellow(`\u25D0 ${c.join(" \xB7 ")}`)}Po(`${a}
360
- ${g.dim("elapsed: "+i)}`,g.bold("Done"))}function Io(e){if(e<1e3)return`${e}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;if(n<60)return r>0?`${n}m ${r}s`:`${n}m`;let o=Math.floor(n/60),i=n%60;return i>0?`${o}h ${i}m`:`${o}h`}function Ic(e){if(typeof e!="string"||!e)return null;let t=e.split(`
357
+ `);return}await z({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as ic,readdirSync as sc,unlinkSync as ac}from"fs";import{join as xo}from"path";import{isCancel as lc,select as cc}from"@clack/prompts";async function re(e,t={}){let n=null;if(e){let u=Number.parseInt(e,10);if(Number.isNaN(u)||u<=0){l.error(`Invalid action id: "${e}"`),process.exitCode=1;return}n=u}else if(n=await uc(),n===null)return;let r=n,o=P();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let i=o.api_base||C.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",c;try{c=await Y(`${i}/api/cli/actions/${r}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:s},body:JSON.stringify({status:a,error_message:t.failed&&t.reason?t.reason:null,result:t.failed?{declined:!0,reason:t.reason??null}:{applied:!0}})})}catch{po(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),gn(r),Ct(process.cwd()),t.silent||l.warn(`Network unavailable \u2014 ack queued locally. Run \`${f("sync")}\` when you're back online; it'll flush automatically.`);return}if(!c.ok){let u=await c.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(c.status===409&&d?.code==="already_acked"){gn(r),Ct(process.cwd());let E=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||l.success(`Action ${r} was already ${E}.`);return}let p=typeof d?.code=="string"?d.code:null,y=typeof d?.error=="string"?d.error:u,m=p?`, code: ${p}`:"";l.error(`Server rejected ack (${c.status}${m}): ${y.slice(0,200)}`),process.exitCode=1;return}gn(r),Ct(process.cwd()),!t.silent&&(t.failed?l.success(`Action ${r} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):l.success(`Action ${r} marked completed.`),l.info(` inbox location: ${xo(b,"inbox")}`))}function gn(e){let t=Q(process.cwd());if(ic(t)){for(let n of sc(t))if(n.endsWith(`-${e}.md`))try{ac(xo(t,n))}catch{}}}async function uc(){let e=process.cwd(),t=fe(e);if(t.length===0)return l.info("No pending actions in .seoagent/inbox/."),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued.`),null;if(!process.stdout.isTTY)return l.error(`Cannot show interactive picker in non-TTY mode. Pass an action id explicitly, or run \`${f("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await cc({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Ae(r)}))});return lc(n)?(l.info("Cancelled \u2014 no action closed out."),null):n}import It from"picocolors";async function hn(e={}){let t=process.cwd();if(!e.json&&!D(t))return;let n=fe(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:Q(t),actions:n})+`
358
+ `);return}if(n.length===0){l.info(It.dim("No pending actions.")),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued, or \`${f("autopilot status")}\` to check whether autopilot is on.`);return}l.message(`${It.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(Ae(r));l.message(""),l.message(`Apply one: ${It.bold(f("ack <id>"))} \xB7 Interactive picker: ${It.bold(f("ack"))} (no id)`)}import{readFileSync as bc}from"fs";import{join as $c,relative as Sc}from"path";import{confirm as Io,isCancel as Pt,multiselect as vc,note as Oo,select as xc}from"@clack/prompts";import g from"picocolors";import{query as _c}from"@anthropic-ai/claude-agent-sdk";import{existsSync as dc,readdirSync as pc}from"fs";import{homedir as fc}from"os";import{join as mc}from"path";import{execSync as yn}from"child_process";function Je(){return process.env.ANTHROPIC_API_KEY?"env-key":process.env.CLAUDE_CODE_USE_BEDROCK==="1"||process.env.CLAUDE_CODE_USE_VERTEX==="1"||process.env.CLAUDE_CODE_USE_FOUNDRY==="1"||process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS==="1"?"enterprise":gc()?hc()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function gc(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return yn(e,{stdio:"ignore"}),!0}catch{return!1}}function hc(){let e=mc(fc(),".claude");if(!dc(e))return!1;try{return pc(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function _o(){try{return yn("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function Co(){try{return yn("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var X={"env-key":{summary:"Using ANTHROPIC_API_KEY env var.",next:""},enterprise:{summary:"Using enterprise provider (Bedrock / Vertex / Foundry).",next:""},"claude-session-likely":{summary:"Using your existing `claude login` session.",next:""},"claude-installed-no-session":{summary:"Claude Code is installed but you are not logged in.",next:"Run `claude login` to sign in with your Claude.ai / Pro / Max account, or set `ANTHROPIC_API_KEY` and re-run."},"not-installed":{summary:"Claude Code is not installed on this machine.",next:"Install it with `npm install -g @anthropic-ai/claude-code` then `claude login`, or set `ANTHROPIC_API_KEY` (get one at https://console.anthropic.com/) and re-run."}};import{marked as Ao}from"marked";import{markedTerminal as yc}from"marked-terminal";import wn from"picocolors";var Eo=!1;function wc(){Eo||(Ao.use(yc({reflowText:!1,width:100})),Eo=!0)}function Rt(e){if(!e)return e;wc();try{let t=Ao.parse(e);return typeof t=="string"?kc(t):e}catch{return e}}function kc(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>wn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>wn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+wn.italic(r))}async function bn(e={}){let t=process.cwd();if(!D(t))return;if(!process.stdout.isTTY&&!e.yes){l.error(`\`${f("process")}\` needs an interactive TTY for the sync + selection prompts. Use \`--yes\` to skip prompts and process everything (for CI/CD).`),process.exitCode=1;return}if(!await Pc(e.yes)){process.exitCode=1;return}if(e.yes)await z({embedded:!0});else{let u=await xc({message:"Sync the inbox before processing?",options:[{value:"sync",label:"Sync (recommended) \u2014 pull pending actions + push local changes"},{value:"pull",label:"Pull only \u2014 get new actions, skip pushing your local changes"},{value:"skip",label:"Skip \u2014 use the current local inbox state"}],initialValue:"sync"});if(Pt(u)){l.info("Cancelled.");return}u==="sync"?await z({embedded:!0}):u==="pull"&&await me({embedded:!0})}let r=fe(t);if(r.length===0){l.info(g.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),l.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(m=>m.priority!==null),d=u?r.filter(m=>m.priority==="high").map(m=>m.id):r.map(m=>m.id),p=u&&d.length===0?" (no high-priority actions \u2014 toggle to select)":u?` (${d.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",y=await vc({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(m=>({value:m.id,label:Ae(m)})),initialValues:d,required:!1});if(Pt(y)){l.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(y)||y.length===0){l.info("No actions selected. Nothing to do.");return}o=y}let i=0,s=0,a=0,c=Date.now();for(let u=0;u<o.length;u++){let d=o[u],p=r.find(_=>_.id===d);if(!p)continue;Cc({index:u+1,total:o.length,entry:p});let y=$c(Q(t),p.filename),m;try{m=bc(y,"utf-8")}catch(_){l.error(` Could not read ${p.filename}: ${_.message}`),a++;continue}let E=Date.now(),I=await Rc({cwd:t,entry:p,actionContent:m,model:e.model}),G=Ro(Date.now()-E);if(I.kind==="applied")try{await re(String(d),{silent:!0}),i++,l.message("");let _=I.summary?`
359
+ `+g.dim(" "+I.summary):"";l.message(` ${g.green("\u2713")} id ${d} ${g.dim("\u2014 applied in "+G)}${_}`)}catch(_){l.warn(` Applied but ack failed: ${_.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(I.kind==="declined")try{await re(String(d),{silent:!0,failed:!0,reason:I.reason}),s++,l.message(""),l.message(` ${g.yellow("\u2298")} id ${d} ${g.dim("\u2014 declined: "+K(I.reason,100))}`)}catch(_){l.warn(` Could not ack decline: ${_.message}. Run \`seoagent ack ${d} --failed --reason "${I.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${g.red("\u2717")} id ${d} ${g.dim("\u2014 agent did not converge after "+G)}`)}Ac({applied:i,declined:s,failed:a,total:o.length,elapsed:Ro(Date.now()-c)})}function Cc(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=Ec[i]??g.dim,a=[g.bold(`[${t}/${n}]`),g.dim("\xB7"),g.bold(`id ${r.id}`),g.dim("\xB7"),g.cyan(o),s(i)].join(" ");Oo(r.title,a)}var Ec={critical:e=>g.red(g.bold(e)),high:g.red,medium:g.yellow,low:g.dim};function Ac(e){let{applied:t,declined:n,failed:r,total:o,elapsed:i}=e,s=t+n,a;if(s===o&&r===0)a=n===0?g.green(`\u2713 ${t}/${o} applied`):g.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=g.red(`\u2717 0/${o} applied`);else{let c=[`${t}/${o} applied`];n>0&&c.push(`${n} declined`),r>0&&c.push(`${r} failed`),a=g.yellow(`\u25D0 ${c.join(" \xB7 ")}`)}Oo(`${a}
360
+ ${g.dim("elapsed: "+i)}`,g.bold("Done"))}function Ro(e){if(e<1e3)return`${e}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;if(n<60)return r>0?`${n}m ${r}s`:`${n}m`;let o=Math.floor(n/60),i=n%60;return i>0?`${o}h ${i}m`:`${o}h`}function Ic(e){if(typeof e!="string"||!e)return null;let t=e.split(`
361
361
  `);for(let n=t.length-1;n>=0;n--){let r=t[n].match(/^__(APPLIED|DECLINED)__:\s*(.*)$/);if(!r)continue;let o=r[2].trim();return r[1]==="APPLIED"?{kind:"applied",summary:o}:{kind:"declined",reason:o}}return null}async function Rc(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=Bc(n,r);try{let s=_c({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...o?{model:o}:{}}}),a={toolUseById:new Map};for await(let c of s)if(c.type==="assistant"){let u=c.message.content;if(Array.isArray(u))for(let d of u)Tc(d,a)}else if(c.type==="user"){let u=c.message.content;if(Array.isArray(u))for(let d of u)Nc(d,a)}else if(c.type==="result"){if(process.stdout.write(`
362
362
  `),!(c.subtype==="success"&&!c.is_error))return{kind:"failed"};let d=Ic(c.result);return d?.kind==="declined"?{kind:"declined",reason:d.reason}:{kind:"applied",summary:d?.kind==="applied"?d.summary:void 0}}return{kind:"failed"}}catch(s){return process.stdout.write(`
363
- `),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function Pc(e){let t=Je();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return l.info(g.dim(X[t].summary)),!0;if(l.warn(X[t].summary),l.message(` ${X[t].next}`),e)return!1;if(t==="not-installed"){let n=await Ao({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(Pt(n)||!n)return l.info("Skipped install. Set up auth and re-run when ready."),!1;l.message(g.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=xo();if(!r.ok)return l.error(`Install failed: ${r.error}`),l.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=Je()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await Ao({message:"Run `claude login` now to sign in?",initialValue:!0});if(Pt(n)||!n)return l.info("Skipped login. Run `claude login` when ready and try again."),!1;l.message(g.dim("Launching `claude login`\u2026"));let r=_o();if(!r.ok)return l.error(`Login failed: ${r.error}`),!1}return!0}function Oc(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function Tc(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&Oc(e)){process.stdout.write(Rt(e.text));return}if(n==="tool_use"){let r=String(e.id??""),o=String(e.name??"unknown"),i=e.input;r&&t.toolUseById.set(r,{name:o,input:i});let s=Lc[o]??g.cyan,a=Mc(o,i);process.stdout.write(s(jc)+" "+g.bold(o)+g.dim("(")+a+g.dim(")")+`
363
+ `),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function Pc(e){let t=Je();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return l.info(g.dim(X[t].summary)),!0;if(l.warn(X[t].summary),l.message(` ${X[t].next}`),e)return!1;if(t==="not-installed"){let n=await Io({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(Pt(n)||!n)return l.info("Skipped install. Set up auth and re-run when ready."),!1;l.message(g.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=_o();if(!r.ok)return l.error(`Install failed: ${r.error}`),l.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=Je()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await Io({message:"Run `claude login` now to sign in?",initialValue:!0});if(Pt(n)||!n)return l.info("Skipped login. Run `claude login` when ready and try again."),!1;l.message(g.dim("Launching `claude login`\u2026"));let r=Co();if(!r.ok)return l.error(`Login failed: ${r.error}`),!1}return!0}function Oc(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function Tc(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&Oc(e)){process.stdout.write(Rt(e.text));return}if(n==="tool_use"){let r=String(e.id??""),o=String(e.name??"unknown"),i=e.input;r&&t.toolUseById.set(r,{name:o,input:i});let s=Lc[o]??g.cyan,a=Mc(o,i);process.stdout.write(s(jc)+" "+g.bold(o)+g.dim("(")+a+g.dim(")")+`
364
364
  `);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(g.dim(g.italic(" "+K(r,200)))+`
365
- `)}}var jc="\u23FA",Ro="\u23BF",Lc={Read:g.blue,Glob:g.cyan,Grep:g.cyan,Edit:g.yellow,Write:g.magenta,Bash:g.green,WebFetch:g.magenta,WebSearch:g.magenta};function Nc(e,t){if(!e||typeof e!="object"||e.type!=="tool_result")return;let n=e.is_error===!0,r=String(e.tool_use_id??""),o=r?t.toolUseById.get(r):void 0,i=o?.name,s=e.content,a=Fc(s);if(n){process.stdout.write(g.red(` ${Ro} Error`)+`
365
+ `)}}var jc="\u23FA",Po="\u23BF",Lc={Read:g.blue,Glob:g.cyan,Grep:g.cyan,Edit:g.yellow,Write:g.magenta,Bash:g.green,WebFetch:g.magenta,WebSearch:g.magenta};function Nc(e,t){if(!e||typeof e!="object"||e.type!=="tool_result")return;let n=e.is_error===!0,r=String(e.tool_use_id??""),o=r?t.toolUseById.get(r):void 0,i=o?.name,s=e.content,a=Fc(s);if(n){process.stdout.write(g.red(` ${Po} Error`)+`
366
366
  `),a&&process.stdout.write(Uc(K(a,500)," ",g.red)+`
367
- `);return}let c=Dc(i,a,o?.input);c&&process.stdout.write(g.dim(` ${Ro} `)+c+`
367
+ `);return}let c=Dc(i,a,o?.input);c&&process.stdout.write(g.dim(` ${Po} `)+c+`
368
368
  `)}function Fc(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:t&&typeof t=="object"&&typeof t.text=="string"?t.text:"").join(""):""}function Dc(e,t,n){if(!e)return"";switch(e){case"Read":{let r=(t.match(/^\s*\d+→/gm)??[]).length,o=r>0?r:t.split(`
369
369
  `).filter(Boolean).length;return g.dim(`Read ${o} line${o===1?"":"s"}`)}case"Glob":{let r=t.split(`
370
370
  `).filter(o=>o.trim().length>0).length;return g.dim(`Found ${r} ${r===1?"entry":"entries"}`)}case"Grep":{let r=t.split(`
@@ -396,15 +396,15 @@ Action file (\`.seoagent/inbox/${e.filename}\`):
396
396
  \`\`\`
397
397
  ${t}
398
398
  \`\`\`
399
- `}import{spinner as Gc}from"@clack/prompts";import k from"picocolors";var Wc=new Set(["on","off","status"]);async function Qe(e,t={}){let n=(e||"").toLowerCase();if(!Wc.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=P();if(!r){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||C.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?Gc():null,c=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(c);let u;try{u=await fetch(`${o}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(m){w(a,"error",`Network error: ${m.message}`,k.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){let E=S(process.cwd())?.domain??"",I=`${C.PRICING}?ref=cli${E?`&domain=${encodeURIComponent(E)}`:""}`;w(a,"warn","CLI autopilot is a paid feature.",k.yellow("Autopilot is a paid feature.")),l.message(Kc(I)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){w(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,k.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:h}=d.autopilot;if(n==="on"){a?.stop(k.green("Autopilot enabled.")),l.message($n({enabled:!0,deliveryMode:h,action:n}));return}if(n==="off"){a?.stop(k.dim("Autopilot disabled.")),l.message($n({enabled:!1,deliveryMode:h,action:n}));return}a?.stop(k.dim("Status:")),l.message($n({enabled:p,deliveryMode:h,action:n}))}function $n(e){let n=s=>k.dim(s.padEnd(11)),r=e.enabled?`${k.bold(k.green("\u25CF ON"))} ${k.dim("(queueing fixes for your coding agent)")}`:`${k.dim("\u25CB OFF")} ${k.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${k.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${k.dim("Apply queued fixes:")} ${k.cyan(f("sync"))}`}),o.push({content:`${k.dim("Turn off any time:")} ${k.cyan(f("autopilot off"))}`})):(o.push({content:`${k.dim("Enable (paid):")} ${k.cyan(f("autopilot on"))}`}),o.push({content:k.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${k.bold(k.cyan("SEOAgent"))} ${k.dim("\xB7")} ${k.dim("autopilot")}`;return O(o,{width:78,title:i})}function Kc(e){let t=[{content:k.bold(k.yellow("Autopilot is a paid feature."))},{sep:!0},{content:k.dim("SEOAgent continuously audits your site and queues fixes for")},{content:k.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:k.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${k.dim("Upgrade:")} ${k.cyan(e)}`}],n=`${k.bold(k.cyan("SEOAgent"))} ${k.dim("\xB7")} ${k.dim("autopilot")}`;return O(t,{width:78,title:n})}import{mkdirSync as nu,writeFileSync as ru}from"fs";import{join as Sn}from"path";import{readdirSync as qc,readFileSync as Hc,statSync as Oo}from"fs";import{join as Yc}from"path";var zc=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Vc=new Set(["png","jpg","jpeg","gif","svg","webp","avif","ico","bmp","css","js","mjs","json","xml","txt","pdf","zip","gz","woff","woff2","ttf","eot","mp4","webm","mp3","wav","csv"]),Jc=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Qc=5e3,Xc=512*1024;function Fo(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function To(e,t){let n=(e||"").trim();if(!n||(n=n.replace(/[?#].*$/,""),!n)||/^(mailto:|tel:|javascript:|data:)/i.test(n)||n.startsWith("//"))return null;if(/^https?:\/\//i.test(n))try{let i=new URL(n),s=i.hostname.toLowerCase().replace(/^www\./,"");if(!t||s!==t)return null;n=i.pathname||"/"}catch{return null}if(!n.startsWith("/")||n.startsWith("/api/")||n==="/api")return null;let r=n.split("/").pop()||"",o=r.lastIndexOf(".");return o>0&&Vc.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var jo=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Lo=/\]\(\s*([^)\s]+)/g;function Zc(e,t){if(!e)return[];let n=Fo(t),r=[],o;for(jo.lastIndex=0;(o=jo.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=To(i,n);s&&r.push(s)}for(Lo.lastIndex=0;(o=Lo.exec(e))!==null;){let i=To(o[1],n);i&&r.push(i)}return r}function eu(e,t,n=0){let r={};for(let s of e)r[s.route]=0;for(let s of t)s in r&&(r[s]+=1);let o=[],i=[];for(let s of e){if(s.route==="/")continue;let a=r[s.route]??0;a===0?o.push({route:s.route,url:s.url}):a===1&&i.push({route:s.route,url:s.url,inbound:a})}return o.sort((s,a)=>s.route.localeCompare(a.route)),i.sort((s,a)=>s.route.localeCompare(a.route)),{pageCount:e.length,linkOccurrences:t.length,orphans:o,weak:i,inboundByRoute:r,filesScanned:n}}function Do(e,t){let n=JSON.stringify(e.orphans.slice(0,100).map(a=>a.url)),r=["---","generated: false",`analyzed_at: ${new Date().toISOString()}`,`page_count: ${e.pageCount}`,`orphan_count: ${e.orphans.length}`,`weak_count: ${e.weak.length}`,`orphans_json: ${n}`,"---"].join(`
400
- `),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${Fo(t)})`:""}. **Orphans** are pages no other page links to \u2014 they're hard for crawlers`,"and users to reach and tend to underperform. Add relevant internal links","pointing at them (from related, higher-authority pages).","",`Scanned ${e.filesScanned} file${e.filesScanned===1?"":"s"}, ${e.linkOccurrences} internal link${e.linkOccurrences===1?"":"s"}, ${e.pageCount} page${e.pageCount===1?"":"s"}.`,"","_Note: this scans the repo, so links inside CMS-hosted content aren't counted._"].join(`
399
+ `}import{spinner as Gc}from"@clack/prompts";import k from"picocolors";var Wc=new Set(["on","off","status"]);async function Qe(e,t={}){let n=(e||"").toLowerCase();if(!Wc.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=P();if(!r){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||C.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?Gc():null,c=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(c);let u;try{u=await fetch(`${o}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(m){w(a,"error",`Network error: ${m.message}`,k.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){let E=S(process.cwd())?.domain??"",I=`${C.PRICING}?ref=cli${E?`&domain=${encodeURIComponent(E)}`:""}`;w(a,"warn","CLI autopilot is a paid feature.",k.yellow("Autopilot is a paid feature.")),l.message(Kc(I)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){w(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,k.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:y}=d.autopilot;if(n==="on"){a?.stop(k.green("Autopilot enabled.")),l.message($n({enabled:!0,deliveryMode:y,action:n}));return}if(n==="off"){a?.stop(k.dim("Autopilot disabled.")),l.message($n({enabled:!1,deliveryMode:y,action:n}));return}a?.stop(k.dim("Status:")),l.message($n({enabled:p,deliveryMode:y,action:n}))}function $n(e){let n=s=>k.dim(s.padEnd(11)),r=e.enabled?`${k.bold(k.green("\u25CF ON"))} ${k.dim("(queueing fixes for your coding agent)")}`:`${k.dim("\u25CB OFF")} ${k.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${k.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${k.dim("Apply queued fixes:")} ${k.cyan(f("sync"))}`}),o.push({content:`${k.dim("Turn off any time:")} ${k.cyan(f("autopilot off"))}`})):(o.push({content:`${k.dim("Enable (paid):")} ${k.cyan(f("autopilot on"))}`}),o.push({content:k.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${k.bold(k.cyan("SEOAgent"))} ${k.dim("\xB7")} ${k.dim("autopilot")}`;return O(o,{width:78,title:i})}function Kc(e){let t=[{content:k.bold(k.yellow("Autopilot is a paid feature."))},{sep:!0},{content:k.dim("SEOAgent continuously audits your site and queues fixes for")},{content:k.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:k.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${k.dim("Upgrade:")} ${k.cyan(e)}`}],n=`${k.bold(k.cyan("SEOAgent"))} ${k.dim("\xB7")} ${k.dim("autopilot")}`;return O(t,{width:78,title:n})}import{mkdirSync as nu,writeFileSync as ru}from"fs";import{join as Sn}from"path";import{readdirSync as qc,readFileSync as Hc,statSync as To}from"fs";import{join as Yc}from"path";var zc=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Vc=new Set(["png","jpg","jpeg","gif","svg","webp","avif","ico","bmp","css","js","mjs","json","xml","txt","pdf","zip","gz","woff","woff2","ttf","eot","mp4","webm","mp3","wav","csv"]),Jc=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Qc=5e3,Xc=512*1024;function Do(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function jo(e,t){let n=(e||"").trim();if(!n||(n=n.replace(/[?#].*$/,""),!n)||/^(mailto:|tel:|javascript:|data:)/i.test(n)||n.startsWith("//"))return null;if(/^https?:\/\//i.test(n))try{let i=new URL(n),s=i.hostname.toLowerCase().replace(/^www\./,"");if(!t||s!==t)return null;n=i.pathname||"/"}catch{return null}if(!n.startsWith("/")||n.startsWith("/api/")||n==="/api")return null;let r=n.split("/").pop()||"",o=r.lastIndexOf(".");return o>0&&Vc.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var Lo=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,No=/\]\(\s*([^)\s]+)/g;function Zc(e,t){if(!e)return[];let n=Do(t),r=[],o;for(Lo.lastIndex=0;(o=Lo.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=jo(i,n);s&&r.push(s)}for(No.lastIndex=0;(o=No.exec(e))!==null;){let i=jo(o[1],n);i&&r.push(i)}return r}function eu(e,t,n=0){let r={};for(let s of e)r[s.route]=0;for(let s of t)s in r&&(r[s]+=1);let o=[],i=[];for(let s of e){if(s.route==="/")continue;let a=r[s.route]??0;a===0?o.push({route:s.route,url:s.url}):a===1&&i.push({route:s.route,url:s.url,inbound:a})}return o.sort((s,a)=>s.route.localeCompare(a.route)),i.sort((s,a)=>s.route.localeCompare(a.route)),{pageCount:e.length,linkOccurrences:t.length,orphans:o,weak:i,inboundByRoute:r,filesScanned:n}}function Uo(e,t){let n=JSON.stringify(e.orphans.slice(0,100).map(a=>a.url)),r=["---","generated: false",`analyzed_at: ${new Date().toISOString()}`,`page_count: ${e.pageCount}`,`orphan_count: ${e.orphans.length}`,`weak_count: ${e.weak.length}`,`orphans_json: ${n}`,"---"].join(`
400
+ `),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${Do(t)})`:""}. **Orphans** are pages no other page links to \u2014 they're hard for crawlers`,"and users to reach and tend to underperform. Add relevant internal links","pointing at them (from related, higher-authority pages).","",`Scanned ${e.filesScanned} file${e.filesScanned===1?"":"s"}, ${e.linkOccurrences} internal link${e.linkOccurrences===1?"":"s"}, ${e.pageCount} page${e.pageCount===1?"":"s"}.`,"","_Note: this scans the repo, so links inside CMS-hosted content aren't counted._"].join(`
401
401
  `),i=e.orphans.length===0?`## Orphan pages
402
402
 
403
- None \u2014 every page has at least one inbound internal link. \u{1F389}`:[`## Orphan pages (${e.orphans.length})`,"","No internal links point to these. Add links from related pages.","","| Page | Suggested link source (fill in) |","|---|---|",...e.orphans.map(a=>`| ${No(a.url)} | \u2014 |`)].join(`
404
- `),s=e.weak.length===0?"":["",`## Weakly linked (${e.weak.length})`,"","Exactly one inbound internal link \u2014 fragile. Consider adding more.","","| Page | Inbound |","|---|---|",...e.weak.map(a=>`| ${No(a.url)} | ${a.inbound} |`)].join(`
403
+ None \u2014 every page has at least one inbound internal link. \u{1F389}`:[`## Orphan pages (${e.orphans.length})`,"","No internal links point to these. Add links from related pages.","","| Page | Suggested link source (fill in) |","|---|---|",...e.orphans.map(a=>`| ${Fo(a.url)} | \u2014 |`)].join(`
404
+ `),s=e.weak.length===0?"":["",`## Weakly linked (${e.weak.length})`,"","Exactly one inbound internal link \u2014 fragile. Consider adding more.","","| Page | Inbound |","|---|---|",...e.weak.map(a=>`| ${Fo(a.url)} | ${a.inbound} |`)].join(`
405
405
  `);return[r,"",o,"",i,s,""].join(`
406
- `)}function No(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*tu(e){let t=0;function*n(r){let o;try{o=qc(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=Qc)return;if(i.name.startsWith("."))continue;let s=Yc(r,i.name);if(i.isDirectory()){if(Jc.has(i.name))continue;yield*n(s)}else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a+1).toLowerCase();if(!zc.has(c))continue;t++,yield s}}}yield*n(e)}function Uo(e,t){let{pages:n}=be(e,t),r=[],o=0,i=!1;try{i=Oo(e).isDirectory()}catch{i=!1}if(i)for(let s of tu(e)){let a;try{if(Oo(s).size>Xc)continue;a=Hc(s,"utf-8")}catch{continue}o++;for(let c of Zc(a,t))r.push(c)}return eu(n,r,o)}function Xe(e={}){let t=process.cwd(),n=D(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Uo(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
407
- `);return}let i=Sn(t,b);nu(i,{recursive:!0});let s=Sn(i,"internal-links.md");if(ru(s,Do(o,r),"utf-8"),l.success(`Analyzed ${o.pageCount} page${o.pageCount===1?"":"s"} across ${o.filesScanned} file${o.filesScanned===1?"":"s"}.`),o.orphans.length===0)l.info("No orphan pages \u2014 every page has an inbound internal link.");else{l.warn(`${o.orphans.length} orphan page${o.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of o.orphans.slice(0,10))l.message(` \u2022 ${a.url}`);o.orphans.length>10&&l.message(` \u2026and ${o.orphans.length-10} more`)}l.info(`Report written to ${Sn(b,"internal-links.md")}`)}import z from"picocolors";import{existsSync as Ie,mkdirSync as Ot,readdirSync as ou,readFileSync as iu,statSync as Kg,writeFileSync as Mo}from"fs";import{dirname as su,join as oe,relative as au,resolve as lu}from"path";var Re="okf";function Tt(e){return oe(e,b,Re)}var cu=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function vn(e){let t=[];for(let n of ou(e,{withFileTypes:!0})){let r=oe(e,n.name);n.isDirectory()?t.push(...vn(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function uu(e){let t=[],n=/\[[^\]]*\]\(([^)]+)\)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1].trim().split(/\s+/)[0];o&&(/^[a-z][a-z0-9+.-]*:/i.test(o)||o.startsWith("#")||t.push(o))}return t}function Bo(e){let t=[],n=[];if(!Ie(e))return{ok:!1,fileCount:0,errors:[{file:Re,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=vn(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Re,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Ie(oe(e,"index.md"))||n.push({file:Re,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=au(e,i),a;try{a=Le(iu(i,"utf-8"))}catch{t.push({file:s,message:"Could not read or parse file."});continue}let c=a.data.type;(c==null||String(c).trim()==="")&&t.push({file:s,message:"Missing required frontmatter field `type`."});let u=a.data.timestamp;u!=null&&u!==""&&!cu.test(String(u))&&t.push({file:s,message:`\`timestamp\` is not ISO-8601: "${String(u)}"`});let d=a.data.description;typeof d=="string"&&d.length>200&&n.push({file:s,message:`\`description\` is ${d.length} chars (keep \u2264 200).`});for(let p of uu(a.body)){let h=p.split("#")[0];if(!h)continue;let m=lu(su(i),h);Ie(m)||t.push({file:s,message:`Broken link \u2192 "${p}" (target does not exist).`})}}return{ok:t.length===0,fileCount:r.length,errors:t,warnings:n}}function jt(e){let t=Tt(e);if(!Ie(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:vn(t).length}}catch{return{exists:!0,fileCount:0}}}function Go(e,t){let n=Tt(e);Ot(n,{recursive:!0}),Ot(oe(n,"concepts"),{recursive:!0}),Ot(oe(n,"faqs"),{recursive:!0}),Ot(oe(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=oe(n,"index.md");Ie(i)||(Mo(i,`---
406
+ `)}function Fo(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*tu(e){let t=0;function*n(r){let o;try{o=qc(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=Qc)return;if(i.name.startsWith("."))continue;let s=Yc(r,i.name);if(i.isDirectory()){if(Jc.has(i.name))continue;yield*n(s)}else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a+1).toLowerCase();if(!zc.has(c))continue;t++,yield s}}}yield*n(e)}function Mo(e,t){let{pages:n}=be(e,t),r=[],o=0,i=!1;try{i=To(e).isDirectory()}catch{i=!1}if(i)for(let s of tu(e)){let a;try{if(To(s).size>Xc)continue;a=Hc(s,"utf-8")}catch{continue}o++;for(let c of Zc(a,t))r.push(c)}return eu(n,r,o)}function Xe(e={}){let t=process.cwd(),n=D(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Mo(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
407
+ `);return}let i=Sn(t,b);nu(i,{recursive:!0});let s=Sn(i,"internal-links.md");if(ru(s,Uo(o,r),"utf-8"),l.success(`Analyzed ${o.pageCount} page${o.pageCount===1?"":"s"} across ${o.filesScanned} file${o.filesScanned===1?"":"s"}.`),o.orphans.length===0)l.info("No orphan pages \u2014 every page has an inbound internal link.");else{l.warn(`${o.orphans.length} orphan page${o.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of o.orphans.slice(0,10))l.message(` \u2022 ${a.url}`);o.orphans.length>10&&l.message(` \u2026and ${o.orphans.length-10} more`)}l.info(`Report written to ${Sn(b,"internal-links.md")}`)}import V from"picocolors";import{existsSync as Ie,mkdirSync as Ot,readdirSync as ou,readFileSync as iu,statSync as Yg,writeFileSync as Bo}from"fs";import{dirname as su,join as oe,relative as au,resolve as lu}from"path";var Re="okf";function Tt(e){return oe(e,b,Re)}var cu=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function vn(e){let t=[];for(let n of ou(e,{withFileTypes:!0})){let r=oe(e,n.name);n.isDirectory()?t.push(...vn(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function uu(e){let t=[],n=/\[[^\]]*\]\(([^)]+)\)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1].trim().split(/\s+/)[0];o&&(/^[a-z][a-z0-9+.-]*:/i.test(o)||o.startsWith("#")||t.push(o))}return t}function Go(e){let t=[],n=[];if(!Ie(e))return{ok:!1,fileCount:0,errors:[{file:Re,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=vn(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Re,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Ie(oe(e,"index.md"))||n.push({file:Re,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=au(e,i),a;try{a=Le(iu(i,"utf-8"))}catch{t.push({file:s,message:"Could not read or parse file."});continue}let c=a.data.type;(c==null||String(c).trim()==="")&&t.push({file:s,message:"Missing required frontmatter field `type`."});let u=a.data.timestamp;u!=null&&u!==""&&!cu.test(String(u))&&t.push({file:s,message:`\`timestamp\` is not ISO-8601: "${String(u)}"`});let d=a.data.description;typeof d=="string"&&d.length>200&&n.push({file:s,message:`\`description\` is ${d.length} chars (keep \u2264 200).`});for(let p of uu(a.body)){let y=p.split("#")[0];if(!y)continue;let m=lu(su(i),y);Ie(m)||t.push({file:s,message:`Broken link \u2192 "${p}" (target does not exist).`})}}return{ok:t.length===0,fileCount:r.length,errors:t,warnings:n}}function jt(e){let t=Tt(e);if(!Ie(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:vn(t).length}}catch{return{exists:!0,fileCount:0}}}function Wo(e,t){let n=Tt(e);Ot(n,{recursive:!0}),Ot(oe(n,"concepts"),{recursive:!0}),Ot(oe(n,"faqs"),{recursive:!0}),Ot(oe(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=oe(n,"index.md");Ie(i)||(Bo(i,`---
408
408
  type: Organization
409
409
  title: ${o}
410
410
  description: Knowledge bundle describing ${o} for AI agents and answer engines.
@@ -431,7 +431,7 @@ _Describe the business in 2\u20134 sentences (pull from \`.seoagent/context.md\`
431
431
  ## Published articles
432
432
 
433
433
  - _Link article files here, e.g._ \`articles/guide-to-x.md\`
434
- `,"utf-8"),r.push("index.md"));let s=oe(n,"log.md");return Ie(s)||(Mo(s,`---
434
+ `,"utf-8"),r.push("index.md"));let s=oe(n,"log.md");return Ie(s)||(Bo(s,`---
435
435
  type: Log
436
436
  title: Change log
437
437
  description: Chronological history of changes to this OKF bundle.
@@ -440,9 +440,9 @@ description: Chronological history of changes to this OKF bundle.
440
440
  # Change log
441
441
 
442
442
  - Bundle scaffolded.
443
- `,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var xn=`${b}/${Re}`;function Ze(e,t={}){let n=process.cwd(),r=D(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=Go(n,i);a.length===0?l.info(`OKF bundle already scaffolded at ${xn}/.`):(l.success(`Scaffolded ${xn}/ \u2014 created ${a.join(", ")}.`),l.info("Now fill the bundle from your .seoagent/ knowledge, then run `seoagent okf validate`."));return}if(o==="validate"){let a=Bo(Tt(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
444
- `);return}for(let c of a.errors)l.message(`${z.red("\u2717")} ${z.dim(c.file)} \u2014 ${c.message}`);for(let c of a.warnings)l.message(`${z.yellow("!")} ${z.dim(c.file)} \u2014 ${c.message}`);a.ok?l.success(`OKF bundle is valid \u2014 ${a.fileCount} file${a.fileCount===1?"":"s"}, ${a.warnings.length} warning${a.warnings.length===1?"":"s"}.`):(l.error(`OKF bundle has ${a.errors.length} error${a.errors.length===1?"":"s"} (see above).`),process.exitCode=1);return}let s=jt(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
445
- `);return}l.message(O([{content:z.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?z.green(xn+"/"):z.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?z.dim("Run `seoagent okf validate` to check it."):z.dim("Run `seoagent okf scaffold` to start one.")}],{title:z.cyan("OKF")}))}import{mkdirSync as gu,writeFileSync as hu}from"fs";import N from"picocolors";import{query as yu}from"@anthropic-ai/claude-agent-sdk";import{join as Wo}from"path";var Cn="citations",En="scorecard.md",du=6,pu=1,fu=12,Lt="Claude (web-grounded)";function An(e){return Wo(e,b,Cn)}function Ko(e){return Wo(An(e),En)}function qo(e){return typeof e!="number"||!Number.isFinite(e)?du:Math.max(pu,Math.min(fu,Math.floor(e)))}function In(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function Ho(e,t){return`You are SEOAgent measuring this business's AI-citation visibility (AEO/GEO) \u2014 whether answer engines surface and cite it.
443
+ `,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var xn=`${b}/${Re}`;function Ze(e,t={}){let n=process.cwd(),r=D(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=Wo(n,i);a.length===0?l.info(`OKF bundle already scaffolded at ${xn}/.`):(l.success(`Scaffolded ${xn}/ \u2014 created ${a.join(", ")}.`),l.info("Now fill the bundle from your .seoagent/ knowledge, then run `seoagent okf validate`."));return}if(o==="validate"){let a=Go(Tt(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
444
+ `);return}for(let c of a.errors)l.message(`${V.red("\u2717")} ${V.dim(c.file)} \u2014 ${c.message}`);for(let c of a.warnings)l.message(`${V.yellow("!")} ${V.dim(c.file)} \u2014 ${c.message}`);a.ok?l.success(`OKF bundle is valid \u2014 ${a.fileCount} file${a.fileCount===1?"":"s"}, ${a.warnings.length} warning${a.warnings.length===1?"":"s"}.`):(l.error(`OKF bundle has ${a.errors.length} error${a.errors.length===1?"":"s"} (see above).`),process.exitCode=1);return}let s=jt(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
445
+ `);return}l.message(O([{content:V.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?V.green(xn+"/"):V.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?V.dim("Run `seoagent okf validate` to check it."):V.dim("Run `seoagent okf scaffold` to start one.")}],{title:V.cyan("OKF")}))}import{mkdirSync as gu,writeFileSync as hu}from"fs";import N from"picocolors";import{query as yu}from"@anthropic-ai/claude-agent-sdk";import{join as Ko}from"path";var Cn="citations",En="scorecard.md",du=6,pu=1,fu=12,Lt="Claude (web-grounded)";function An(e){return Ko(e,b,Cn)}function qo(e){return Ko(An(e),En)}function Ho(e){return typeof e!="number"||!Number.isFinite(e)?du:Math.max(pu,Math.min(fu,Math.floor(e)))}function In(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function Yo(e,t){return`You are SEOAgent measuring this business's AI-citation visibility (AEO/GEO) \u2014 whether answer engines surface and cite it.
446
446
 
447
447
  Business under audit:
448
448
  ${[`- Domain: ${e.domain}`,e.name?`- Business name: ${e.name}`:null,e.type?`- Business type: ${e.type}`:null,e.description?`- What it does: ${e.description}`:null,`- OKF knowledge bundle present in repo: ${e.hasOkfBundle?"yes":"no"}`].filter(Boolean).join(`
@@ -477,7 +477,7 @@ End your reply with EXACTLY ONE fenced \`\`\`json block (and nothing after it) m
477
477
  }
478
478
  \`\`\`
479
479
 
480
- \`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown.`}function Yo(e){if(typeof e!="string"||!e.trim())return null;let t=/```json\s*([\s\S]*?)```/gi,n=[],r;for(;(r=t.exec(e))!==null;)r[1].trim()&&n.push(r[1].trim());if(n.length===0)return null;for(let o=n.length-1;o>=0;o--){let i=mu(n[o]);if(i)return i}return null}function mu(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=typeof n.domain=="string"?n.domain.trim():"";if(!r)return null;let o=typeof n.brand=="string"&&n.brand.trim()?n.brand.trim():r;if(!Array.isArray(n.results))return null;let i=[];for(let s of n.results){if(!s||typeof s!="object")continue;let a=s,c=typeof a.query=="string"?a.query.trim():"";if(!c)continue;let u=a.surfaced===!0,d=typeof a.rank=="number"&&Number.isFinite(a.rank)?Math.round(a.rank):null,p=typeof a.evidence=="string"?a.evidence.trim():"";i.push({query:c,surfaced:u,rank:u?d:null,evidence:p})}return i.length===0?null:{brand:o,domain:r,results:i}}function zo(e,t){let{cited:n,total:r}=In(e),o=t.generatedAt.slice(0,10),i=e.results.map((u,d)=>{let p=u.surfaced?"\u2705":"\u2014",h=u.surfaced&&u.rank?`#${u.rank}`:"\u2014",m=_n(u.evidence||(u.surfaced?"surfaced":"not found"));return`| ${d+1} | ${_n(u.query)} | ${p} | ${h} | ${m} |`}).join(`
480
+ \`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown.`}function zo(e){if(typeof e!="string"||!e.trim())return null;let t=/```json\s*([\s\S]*?)```/gi,n=[],r;for(;(r=t.exec(e))!==null;)r[1].trim()&&n.push(r[1].trim());if(n.length===0)return null;for(let o=n.length-1;o>=0;o--){let i=mu(n[o]);if(i)return i}return null}function mu(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=typeof n.domain=="string"?n.domain.trim():"";if(!r)return null;let o=typeof n.brand=="string"&&n.brand.trim()?n.brand.trim():r;if(!Array.isArray(n.results))return null;let i=[];for(let s of n.results){if(!s||typeof s!="object")continue;let a=s,c=typeof a.query=="string"?a.query.trim():"";if(!c)continue;let u=a.surfaced===!0,d=typeof a.rank=="number"&&Number.isFinite(a.rank)?Math.round(a.rank):null,p=typeof a.evidence=="string"?a.evidence.trim():"";i.push({query:c,surfaced:u,rank:u?d:null,evidence:p})}return i.length===0?null:{brand:o,domain:r,results:i}}function Vo(e,t){let{cited:n,total:r}=In(e),o=t.generatedAt.slice(0,10),i=e.results.map((u,d)=>{let p=u.surfaced?"\u2705":"\u2014",y=u.surfaced&&u.rank?`#${u.rank}`:"\u2014",m=_n(u.evidence||(u.surfaced?"surfaced":"not found"));return`| ${d+1} | ${_n(u.query)} | ${p} | ${y} | ${m} |`}).join(`
481
481
  `),s=e.results.filter(u=>!u.surfaced),a=s.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":s.map(u=>`- **${_n(u.query)}** \u2014 ${u.evidence||"not surfaced"}`).join(`
482
482
  `),c=e.results.some(u=>!u.surfaced)?"- Enrich the Open Knowledge Format bundle so answer engines understand the business: run `seoagent okf scaffold` then fill it (the skill maps your `.seoagent/` knowledge into it), and publish it at `/.well-known/okf/`.\n- Cover the missed questions directly in your content (a page or FAQ that answers each one), then re-run `seoagent citations`.":"- Keep the OKF bundle current as the business evolves, and re-run to catch regressions.";return`---
483
483
  type: Report
@@ -520,16 +520,16 @@ This is **not a per-engine guarantee**: ChatGPT, Perplexity, and Gemini each
520
520
  rank and cite differently, and tracking them individually is a planned
521
521
  follow-up. Treat the score as directional \u2014 re-run over time to watch the
522
522
  trend rather than fixating on a single number.
523
- `}function _n(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function et(e={}){let t=process.cwd(),n=D(t);if(!n)return;let r=Je();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){l.warn(X[r].summary),X[r].next&&l.message(` ${X[r].next}`),process.exitCode=1;return}l.info(N.dim(X[r].summary));let o=hr(t),i=jt(t),s={domain:n.domain,name:o?.business.name,type:o?.business.type||n.site_type,description:o?.business.description,hasOkfBundle:i.exists&&i.fileCount>0},a=qo(e.queries);l.message(`${N.cyan("\u25C7")} Auditing AI citations for ${N.bold(s.domain)} \u2014 ${a} web-grounded quer${a===1?"y":"ies"} via ${Lt}.`),l.message(N.dim(` This runs live web searches and can take a minute\u2026
524
- `));let c=Ho(s,a),u=await wu({cwd:t,prompt:c,model:e.model});if(u===null){process.exitCode=1;return}let d=Yo(u);if(!d){l.error(`Couldn't read a citation report from the agent's reply. Re-run \`${f("citations")}\`, optionally with fewer queries (\`--queries 4\`).`),process.exitCode=1;return}let p=new Date().toISOString(),h=zo(d,{generatedAt:p});gu(An(t),{recursive:!0}),hu(Ko(t),h,"utf-8");let{cited:m,total:E}=In(d),I=m===0?N.red:m<E?N.yellow:N.green;l.message(O([{content:N.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${N.cyan(d.domain)}`},{content:`Cited: ${I(`${m} / ${E}`)} ${N.dim("queries")}`},{content:`Engine: ${N.dim(Lt)}`},{sep:!0},{content:N.dim(`Saved \u2192 .seoagent/${Cn}/${En}`)},{content:m<E?N.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):N.dim("Surfacing across the board. Re-run periodically to catch drift.")}],{title:N.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(d,null,2)+`
523
+ `}function _n(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function et(e={}){let t=process.cwd(),n=D(t);if(!n)return;let r=Je();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){l.warn(X[r].summary),X[r].next&&l.message(` ${X[r].next}`),process.exitCode=1;return}l.info(N.dim(X[r].summary));let o=yr(t),i=jt(t),s={domain:n.domain,name:o?.business.name,type:o?.business.type||n.site_type,description:o?.business.description,hasOkfBundle:i.exists&&i.fileCount>0},a=Ho(e.queries);l.message(`${N.cyan("\u25C7")} Auditing AI citations for ${N.bold(s.domain)} \u2014 ${a} web-grounded quer${a===1?"y":"ies"} via ${Lt}.`),l.message(N.dim(` This runs live web searches and can take a minute\u2026
524
+ `));let c=Yo(s,a),u=await wu({cwd:t,prompt:c,model:e.model});if(u===null){process.exitCode=1;return}let d=zo(u);if(!d){l.error(`Couldn't read a citation report from the agent's reply. Re-run \`${f("citations")}\`, optionally with fewer queries (\`--queries 4\`).`),process.exitCode=1;return}let p=new Date().toISOString(),y=Vo(d,{generatedAt:p});gu(An(t),{recursive:!0}),hu(qo(t),y,"utf-8");let{cited:m,total:E}=In(d),I=m===0?N.red:m<E?N.yellow:N.green;l.message(O([{content:N.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${N.cyan(d.domain)}`},{content:`Cited: ${I(`${m} / ${E}`)} ${N.dim("queries")}`},{content:`Engine: ${N.dim(Lt)}`},{sep:!0},{content:N.dim(`Saved \u2192 .seoagent/${Cn}/${En}`)},{content:m<E?N.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):N.dim("Surfacing across the board. Re-run periodically to catch drift.")}],{title:N.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(d,null,2)+`
525
525
  `)}async function wu(e){let{cwd:t,prompt:n,model:r}=e;try{let o=yu({prompt:n,options:{cwd:t,allowedTools:["WebSearch","WebFetch","Read","Grep","Glob"],permissionMode:"acceptEdits",...r?{model:r}:{}}}),i="";for await(let s of o)if(s.type==="assistant"){let a=s.message.content;if(Array.isArray(a))for(let c of a)ku(c)}else if(s.type==="result"){if(process.stdout.write(`
526
526
  `),!(s.subtype==="success"&&!s.is_error))return l.error(" Agent did not complete the citation audit (rate limit, auth, or network)."),null;i=String(s.result??"")}return i}catch(o){return process.stdout.write(`
527
527
  `),l.error(` Agent error: ${o.message}`),null}}function ku(e){if(!e||typeof e!="object")return;let t=e.type;if(t==="text"){let n=e.text;typeof n=="string"&&n&&process.stdout.write(Rt(n));return}if(t==="tool_use"){let n=String(e.name??"tool"),r=e.input,o=n==="WebSearch"?String(r?.query??""):n==="WebFetch"?String(r?.url??""):"";process.stdout.write(N.dim(` ${N.magenta("\u{1F50E}")} ${n}${o?` ${bu(o,70)}`:""}
528
- `))}}function bu(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}import Pe from"picocolors";function tt(e={}){if(e.all){$u();return}let t=process.cwd();if(!D(t))return;ce(t);let n=mn(t);Jo(t);let r=Vo(t);n.reason==="refreshed"?(l.success(n.from&&n.from!==n.to?`Refreshed the SEOAgent skill ${n.from} \u2192 ${n.to}.`:`Refreshed the SEOAgent skill (now ${n.to}).`),l.info("Your `.seoagent/` knowledge was left untouched.")):(l.error(`Could not refresh the skill (${n.reason}).`),process.exitCode=1),r.added>0?l.success(`Re-scanned the codebase: +${r.added} new page${r.added===1?"":"s"} merged into .seoagent/pages.md (${r.total} total).`):r.total>0&&l.info(`Page inventory already current (${r.total} pages).`)}function Vo(e){try{let t=S(e),n=t?.domain&&t.domain!=="unknown"?t.domain:null,{pages:r}=be(e,n),o=bt(e,r);return{added:o.added,total:o.total}}catch{return{added:0,total:0}}}function $u(){let e=ur();if(e.length===0){l.info("No SEOAgent projects are registered on this machine yet. They register themselves on `init` / `sync`.");return}l.message(`Refreshing ${e.length} project${e.length===1?"":"s"} to SEOAgent ${Pe.bold(v)}\u2026`);let t=0,n=0;for(let r of e){let o=mn(r);Jo(r);let i=Vo(r),s=i.added>0?Pe.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?Pe.dim(` (${o.from} \u2192 ${o.to})`):"";l.message(` ${Pe.green("\u2713")} ${r}${a}${s}`)}else n++,l.message(` ${Pe.yellow("!")} ${r} ${Pe.dim("\u2014 "+o.reason)}${s}`)}l.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${v}.`),n>0&&l.info(`${n} could not be refreshed (see above).`)}function Jo(e){try{le(e)}catch{}}import{spinner as Xo}from"@clack/prompts";import y from"picocolors";var Zo={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function Su(e){let t=process.cwd(),n=Hn(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=S(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||C.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?Xo():null;a?.start(`Looking up ${y.bold(`"${e.keyword}"`)} ${y.dim("via DataForSEO (free peek)\u2026")}`);let c;try{c=await J(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...o?{domain:o}:{}})})}catch(d){w(a,"error",`Network error: ${d.message}`,y.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await c.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:c.status,body:u??null})+`
529
- `);return}if(c.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";w(a,"warn",`Daily peek quota reached for ${d}.`,y.yellow(`Daily peek quota reached for ${d}.`)),l.message(Qo()),process.exitCode=1;return}if(!c.ok||!u){w(a,"error",`Peek failed (${c.status})${u?.error?`: ${u.error}`:""}`,y.red(`Peek failed (${c.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){w(a,"warn","Real keyword data is temporarily unavailable. Try again later.",y.yellow("Real keyword data is temporarily unavailable. Try again later.")),l.message(y.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){w(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",y.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){w(a,"warn",`No data returned for "${e.keyword}".`,y.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(y.green("Got it.")),l.message(vu(u.opportunity)),u.remaining&&l.message(`${y.dim("Peeks remaining today:")} ${y.bold(String(u.remaining.install))} ${y.dim("\u2014 "+Qo())}`)}function vu(e){let n=u=>y.dim(u.padEnd(14)),r=e.volume!=null?y.bold(String(e.volume)):y.dim("n/a"),o=e.difficulty!=null?`${y.bold(String(e.difficulty))} ${y.dim(xu(e.difficulty))}`:y.dim("n/a"),i=Zo[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?y.bold(y.green(i)):e.opportunity==="striking_distance"?y.bold(y.cyan(i)):e.opportunity==="competitor_gap"?y.bold(y.yellow(i)):y.dim(i),a=[{content:`${y.green("\u25CF")} ${y.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${y.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],c=`${y.bold(y.cyan("Keyword peek"))}`;return O(a,{width:55,title:c})}function xu(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Qo(e=P()){return e?`You're logged in \u2014 run \`${f("keywords")}\` for full enrichment (no quota), or \`${f("keywords --discover")}\` / \`${f("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${f("login")}`}function Rn(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){l.message("Top opportunities:");for(let n of t){let r=n.volume!=null?`vol ${n.volume}`:"vol n/a",o=n.difficulty!=null?`KD ${n.difficulty}`:"KD n/a",i=n.our_position!=null?`, you're #${n.our_position}`:", not ranking";l.message(` \u2022 [${Zo[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function _u(e){if(e.length!==0){l.message("Top competitor gaps:");for(let t of e){let n=t.volume!=null?`vol ${t.volume}`:"vol n/a",r=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",o=t.their_position!=null?`#${t.their_position}`:"top 10";l.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${o}, ${n}, ${r}`)}}}async function ie(e={}){if(e.peek&&e.peek.trim().length>0){await Su({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=P();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=e.apiBase||t.api_base||C.BASE,r=`Bearer ${t.user_token}:${t.website_token}`,o=e.competitors?"competitors":e.discover?"discover":e.seed?"seed":"enrich",i=o==="competitors"?"/api/cli/keywords/competitors":o==="discover"?"/api/cli/keywords/discover":o==="seed"?"/api/cli/keywords/seed":"/api/cli/keywords/enrich",s=o==="competitors"?"Finding keywords your competitors rank for\u2026":o==="discover"?"Discovering new keywords to target\u2026":o==="seed"?"Seeding keywords from your Search Console data\u2026":"Enriching keywords with real volume + difficulty\u2026",c=!!process.stdout.isTTY?Xo():null;c?.start(s);let u=o==="competitors"||o==="discover"||o==="seed",d;try{d=await J(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"},u?{timeoutMs:6e4,attempts:1}:{})}catch(m){w(c,"error",`Network error: ${m.message}`,y.red("Network error.")),process.exitCode=1;return}let p=null;try{p=await d.json()}catch{p=null}if(d.status===402||p?.code==="upgrade_required"){w(c,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",y.yellow("Paid feature \u2014 upgrade to continue.")),l.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${y.cyan(C.PRICING)}`:`Upgrade to find new keywords to target: ${y.cyan(C.PRICING)}`),process.exitCode=1;return}if(!d.ok||p?.status!=="ok"){w(c,"error",`Server rejected request (${d.status})${p?.error?`: ${p.error}`:""}`,y.red(`Server rejected request (${d.status}).`)),process.exitCode=1;return}if(p.skipped==="no-gsc-data"){w(c,"warn","No Search Console data to seed from yet. Connect Google Search Console (run `seoagent login` and link GSC) \u2014 or wait for impressions to accrue on a new site.",y.yellow("No Search Console data yet."));return}if(p.skipped==="no-keywords"||p.skipped==="no-seeds"){w(c,"warn","No keywords yet. Seed from Search Console with `seoagent keywords --seed`, or run the keyword strategy (Phase 2) first, then try again.",y.yellow("No keywords yet."));return}if(p.skipped==="no-competitors"){w(c,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",y.yellow("No competitors yet."));return}if(p.skipped==="no-creds"||p.skipped==="no-columns"||p.skipped==="no-table"){w(c,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",y.yellow("Real keyword data is not enabled on the server yet."));return}if(p.skipped){w(c,"warn",`Skipped: ${p.skipped}`,y.yellow(`Skipped: ${p.skipped}`));return}if(o==="competitors"){let m=p.gaps??0;w(c,"success",`Found ${m} competitor gap${m===1?"":"s"} across ${p.competitors?.length??0} competitor${p.competitors?.length===1?"":"s"} (added as "suggested").`,y.green(`${m} competitor gap${m===1?"":"s"} found.`)),_u(p.topGaps??[]),l.message(`Review them in ${y.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}if(o==="discover"){let m=p.discovered??0;w(c,"success",`Discovered ${m} new keyword${m===1?"":"s"} to target (added as "suggested").`,y.green(`${m} new keyword${m===1?"":"s"} discovered.`)),Rn(p.opportunities??[]),l.message(`Review them in ${y.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}if(o==="seed"){let m=p.seeded??0;w(c,"success",`Seeded ${m} keyword${m===1?"":"s"} from Search Console (real impressed queries, added as "suggested").`,y.green(`${m} keyword${m===1?"":"s"} seeded from Search Console.`)),Rn(p.opportunities??[]),l.message(`These are queries your site already gets impressions for \u2014 striking-distance wins first. Review in ${y.cyan(".seoagent/keywords.md")} and build clusters from them.`);return}let h=p.enriched??0;w(c,"success",`Enriched ${h} keyword${h===1?"":"s"}.`,y.green(`Enriched ${h} keyword${h===1?"":"s"}.`)),Rn(p.opportunities??[]),p.paid||l.message(`${y.dim("Free plan:")} enriched up to ${y.bold(String(p.cap??25))} keywords. ${y.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${y.cyan(C.PRICING)}`)}import A from"picocolors";import{existsSync as Cu,readFileSync as Eu}from"fs";import{join as Au}from"path";var ei=["openai","fal","replicate"],Oe={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Iu(e){let t={};if(!Cu(e))return t;let n=Eu(e,"utf-8");for(let r of n.split(/\r?\n/)){let o=r.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i===-1)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return t}function ti(e,t){let n={};for(let r of t){let o=process.env[r];o&&o.trim().length>0&&(n[r]={value:o,source:"process"})}for(let r of ge){let o=Au(e,r),i=Iu(o);for(let s of t){if(n[s])continue;let a=i[s];a&&a.length>0&&(n[s]={value:a,source:r})}}return{found:n}}function Nt(e){let t=[].concat(...ei.map(a=>Oe[a])),n=ti(e,t),r=[];for(let a of ei)Oe[a].some(c=>n.found[c])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=Oe[o].find(a=>n.found[a])??null,s=i?n.found[i].source:null;return{provider:o,matched_key:i,source:s,available_providers:r}}function ni(e,t){let n=ti(e,Oe[t]);for(let r of Oe[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function ri(){return Oe}function nt(e={}){let t=process.cwd(),n=S(t),r=Nt(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
530
- `);return}if(l.message(Ru(r)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}W(t,{image_provider:r.provider}),l.info(`Saved to ${A.cyan(".seoagent/project.md")} ${A.dim(`(image_provider: ${r.provider})`)}`)}function Ru(e){let n=i=>A.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${A.dim("\u25CB")} ${A.bold(A.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:A.dim("Set ONE of these to enable image generation:")});let i=ri();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${A.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:A.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${A.cyan(f("env-check"))}`})}else{r.push({content:`${A.green("\u2713")} ${A.dim("Image provider:")} ${A.bold(A.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${A.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${A.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${A.dim(i.join(", "))}`})}let o=`${A.bold(A.cyan("SEOAgent"))} ${A.dim("\xB7")} ${A.dim("env-check")}`;return O(r,{width:64,title:o})}import{existsSync as On,mkdirSync as si,writeFileSync as ai}from"fs";import{dirname as Dt,isAbsolute as Lu,join as Ft,resolve as Nu}from"path";import{tmpdir as Fu}from"os";import{spinner as Du}from"@clack/prompts";import T from"picocolors";import{Buffer as oi}from"buffer";async function Pn(e){let t=await fetch(e);if(!t.ok)throw new Error(`Image download failed: ${t.status} ${t.statusText}`);let n=await t.arrayBuffer();return oi.from(n)}async function Pu(e){let t=e.size??"1024x1024",n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:"gpt-image-1",prompt:e.prompt,size:t,n:1})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`OpenAI image API ${n.status}: ${i.slice(0,300)}`)}let o=(await n.json()).data?.[0];if(!o)throw new Error("OpenAI image API returned no data");if(o.b64_json)return{bytes:oi.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await Pn(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function Ou(e){let t=process.env.FAL_MODEL||"fal-ai/flux/schnell",n=await fetch(`https://fal.run/${t}`,{method:"POST",headers:{Authorization:`Key ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({prompt:e.prompt,image_size:"landscape_16_9",num_images:1})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`fal.ai API ${n.status}: ${s.slice(0,300)}`)}let o=(await n.json()).images?.[0];if(!o?.url)throw new Error("fal.ai API returned no image url");return{bytes:await Pn(o.url),contentType:o.content_type??"image/png"}}async function Tu(e,t,n=9e4){let r=Date.now(),o=1e3;for(;Date.now()-r<n;){let i=await fetch(`https://api.replicate.com/v1/predictions/${e}`,{headers:{Authorization:`Token ${t}`}});if(!i.ok)throw new Error(`Replicate poll failed: ${i.status}`);let s=await i.json();if(s.status==="succeeded"||s.status==="failed"||s.status==="canceled")return s;await new Promise(a=>setTimeout(a,o)),o=Math.min(o*1.5,5e3)}throw new Error("Replicate prediction timed out")}async function ju(e){let t=process.env.REPLICATE_MODEL||"black-forest-labs/flux-schnell",n=await fetch(`https://api.replicate.com/v1/models/${t}/predictions`,{method:"POST",headers:{Authorization:`Token ${e.apiKey}`,"Content-Type":"application/json",Prefer:"wait"},body:JSON.stringify({input:{prompt:e.prompt,aspect_ratio:"16:9"}})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Replicate API ${n.status}: ${s.slice(0,300)}`)}let r=await n.json();if(r.status!=="succeeded"&&r.status!=="failed"&&(r=await Tu(r.id,e.apiKey)),r.status!=="succeeded")throw new Error(`Replicate prediction ${r.status}: ${r.error??""}`);let o=Array.isArray(r.output)?r.output[0]:r.output;if(!o)throw new Error("Replicate prediction returned no output");return{bytes:await Pn(o),contentType:"image/png",providerImageId:r.id}}async function ii(e,t){switch(e){case"openai":return Pu(t);case"fal":return Ou(t);case"replicate":return ju(t);default:throw new Error(`Unknown image provider: ${e}`)}}function Uu(e){return e==="openai"||e==="fal"||e==="replicate"}async function rt(e={}){let t=process.cwd();if(!e.prompt){l.warn(`Missing --prompt. Example: ${f('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){l.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=S(t),r=null;if(e.provider){if(!Uu(e.provider)){l.warn(`Invalid --provider "${e.provider}". Use one of: openai, fal, replicate.`),process.exitCode=1;return}r=e.provider}else n?.image_provider&&n.image_provider!=="none"?r=n.image_provider:r=Nt(t).provider;if(!r||r==="none"){l.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${f("env-check")}\`.`),process.exitCode=1;return}let o=ni(t,r);if(!o){l.warn(`Provider "${r}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=Lu(e.out)?e.out:Nu(t,e.out),a=!e.silent&&!!process.stdout.isTTY?Du():null;a?.start(`Generating image with ${T.bold(r)} ${T.dim(`(${o.envName})`)}\u2026`);try{let c=await ii(r,{prompt:e.prompt,apiKey:o.key,size:e.size});On(Dt(i))||si(Dt(i),{recursive:!0}),ai(i,c.bytes),e.silent||w(a,"success",`Wrote ${i} (${c.bytes.length} bytes, ${c.contentType}).`,T.green(`Wrote ${i} ${T.dim(`(${c.bytes.length} bytes, ${c.contentType})`)}`))}catch(c){a?.stop(T.red("Image generation failed."));let u=Bu(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(Mu({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:c.message})),u&&l.message(`${T.dim("Full error log:")} ${T.cyan(u)}`),process.exitCode=1}}function Mu(e){let n=d=>T.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${T.red("\u2717")} ${T.bold(T.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${T.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${T.dim(`"${o}"`)}`}];e.size&&i.push({content:`${n("Size:")}${e.size}`}),i.push({sep:!0});let s=e.message.replace(/\s+/g," ").trim(),a=64,c=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:T.red(c)});let u=`${T.bold(T.cyan("SEOAgent"))} ${T.dim("\xB7")} ${T.dim("generate-image")}`;return O(i,{width:70,title:u})}function Bu(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=Ft(e,b),i=Ft(o,".errors"),s=On(o)?Ft(i,r):Ft(Fu(),r),a=["# SEOAgent generate-image error",`# ${new Date().toISOString()}`,"","## Request",`provider: ${t.provider}`,`env_var: ${t.envName}`,`prompt: ${JSON.stringify(t.prompt)}`,`size: ${t.size??"(default)"}`,`out_path: ${t.outPath}`,`cwd: ${e}`,"","## Error",`message: ${t.error.message}`,"","## Stack",t.error.stack??"(no stack)",""];t.error.cause&&a.push("## Cause",String(t.error.cause),"");try{return On(Dt(s))||si(Dt(s),{recursive:!0}),ai(s,a.join(`
528
+ `))}}function bu(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}import Pe from"picocolors";function tt(e={}){if(e.all){$u();return}let t=process.cwd();if(!D(t))return;ce(t);let n=mn(t);Qo(t);let r=Jo(t);n.reason==="refreshed"?(l.success(n.from&&n.from!==n.to?`Refreshed the SEOAgent skill ${n.from} \u2192 ${n.to}.`:`Refreshed the SEOAgent skill (now ${n.to}).`),l.info("Your `.seoagent/` knowledge was left untouched.")):(l.error(`Could not refresh the skill (${n.reason}).`),process.exitCode=1),r.added>0?l.success(`Re-scanned the codebase: +${r.added} new page${r.added===1?"":"s"} merged into .seoagent/pages.md (${r.total} total).`):r.total>0&&l.info(`Page inventory already current (${r.total} pages).`)}function Jo(e){try{let t=S(e),n=t?.domain&&t.domain!=="unknown"?t.domain:null,{pages:r}=be(e,n),o=bt(e,r);return{added:o.added,total:o.total}}catch{return{added:0,total:0}}}function $u(){let e=dr();if(e.length===0){l.info("No SEOAgent projects are registered on this machine yet. They register themselves on `init` / `sync`.");return}l.message(`Refreshing ${e.length} project${e.length===1?"":"s"} to SEOAgent ${Pe.bold(v)}\u2026`);let t=0,n=0;for(let r of e){let o=mn(r);Qo(r);let i=Jo(r),s=i.added>0?Pe.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?Pe.dim(` (${o.from} \u2192 ${o.to})`):"";l.message(` ${Pe.green("\u2713")} ${r}${a}${s}`)}else n++,l.message(` ${Pe.yellow("!")} ${r} ${Pe.dim("\u2014 "+o.reason)}${s}`)}l.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${v}.`),n>0&&l.info(`${n} could not be refreshed (see above).`)}function Qo(e){try{le(e)}catch{}}import{spinner as Pn,confirm as Su,isCancel as vu}from"@clack/prompts";import h from"picocolors";var Zo={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function xu(e){let t=process.cwd(),n=Yn(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=S(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||C.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?Pn():null;a?.start(`Looking up ${h.bold(`"${e.keyword}"`)} ${h.dim("via DataForSEO (free peek)\u2026")}`);let c;try{c=await Y(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...o?{domain:o}:{}})})}catch(d){w(a,"error",`Network error: ${d.message}`,h.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await c.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:c.status,body:u??null})+`
529
+ `);return}if(c.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";w(a,"warn",`Daily peek quota reached for ${d}.`,h.yellow(`Daily peek quota reached for ${d}.`)),l.message(Xo()),process.exitCode=1;return}if(!c.ok||!u){w(a,"error",`Peek failed (${c.status})${u?.error?`: ${u.error}`:""}`,h.red(`Peek failed (${c.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){w(a,"warn","Real keyword data is temporarily unavailable. Try again later.",h.yellow("Real keyword data is temporarily unavailable. Try again later.")),l.message(h.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){w(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){w(a,"warn",`No data returned for "${e.keyword}".`,h.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(h.green("Got it.")),l.message(_u(u.opportunity)),u.remaining&&l.message(`${h.dim("Peeks remaining today:")} ${h.bold(String(u.remaining.install))} ${h.dim("\u2014 "+Xo())}`)}function _u(e){let n=u=>h.dim(u.padEnd(14)),r=e.volume!=null?h.bold(String(e.volume)):h.dim("n/a"),o=e.difficulty!=null?`${h.bold(String(e.difficulty))} ${h.dim(Cu(e.difficulty))}`:h.dim("n/a"),i=Zo[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?h.bold(h.green(i)):e.opportunity==="striking_distance"?h.bold(h.cyan(i)):e.opportunity==="competitor_gap"?h.bold(h.yellow(i)):h.dim(i),a=[{content:`${h.green("\u25CF")} ${h.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${h.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],c=`${h.bold(h.cyan("Keyword peek"))}`;return O(a,{width:55,title:c})}function Cu(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Xo(e=P()){return e?`You're logged in \u2014 run \`${f("keywords")}\` for full enrichment (no quota), or \`${f("keywords --discover")}\` / \`${f("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${f("login")}`}function Rn(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){l.message("Top opportunities:");for(let n of t){let r=n.volume!=null?`vol ${n.volume}`:"vol n/a",o=n.difficulty!=null?`KD ${n.difficulty}`:"KD n/a",i=n.our_position!=null?`, you're #${n.our_position}`:", not ranking";l.message(` \u2022 [${Zo[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function Eu(e){if(e.length!==0){l.message("Top competitor gaps:");for(let t of e){let n=t.volume!=null?`vol ${t.volume}`:"vol n/a",r=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",o=t.their_position!=null?`#${t.their_position}`:"top 10";l.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${o}, ${n}, ${r}`)}}}async function Au(e){let t=e.all?"all":"suggested";if(t==="all"&&process.stdin.isTTY){let a=await Su({message:"Delete ALL keywords for this site from the cloud? This cannot be undone."});if(vu(a)||!a){l.info("No changes.");return}}let n=e.apiBase||e.auth.api_base||C.BASE,r=process.stdout.isTTY?Pn():null;r?.start(t==="all"?"Purging all keywords\u2026":"Purging suggested keywords\u2026");let o;try{o=await Y(`${n}/api/cli/keywords/purge`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.auth.user_token}:${e.auth.website_token}`},body:JSON.stringify({scope:t})})}catch(a){w(r,"error",`Network error: ${a.message}`,h.red("Network error.")),process.exitCode=1;return}let i=null;try{i=await o.json()}catch{i=null}if(i?.skipped==="no-table"||i?.skipped==="no-columns"){w(r,"warn","Keyword storage isn\u2019t enabled on the server yet.",h.yellow("Nothing to purge yet."));return}if(!o.ok||i?.status!=="ok"){w(r,"error",`Purge failed (${o.status})${i?.error?`: ${i.error}`:""}`,h.red(`Purge failed (${o.status}).`)),process.exitCode=1;return}let s=i.purged??0;w(r,"success",`Purged ${s} ${t==="all"?"":"suggested "}keyword${s===1?"":"s"}.`,h.green(`Purged ${s} keyword${s===1?"":"s"}.`)),l.message(h.dim(t==="all"?"Cleared the cloud inventory. Re-run `seoagent keywords --seed` / strategy to rebuild it.":"Cleared discovery noise. Your clustered keywords were kept."))}async function ie(e={}){if(e.peek&&e.peek.trim().length>0){await xu({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=P();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(e.purge){await Au({all:e.all,apiBase:e.apiBase,auth:t});return}let n=e.apiBase||t.api_base||C.BASE,r=`Bearer ${t.user_token}:${t.website_token}`,o=e.competitors?"competitors":e.discover?"discover":e.seed?"seed":"enrich",i=o==="competitors"?"/api/cli/keywords/competitors":o==="discover"?"/api/cli/keywords/discover":o==="seed"?"/api/cli/keywords/seed":"/api/cli/keywords/enrich",s=o==="competitors"?"Finding keywords your competitors rank for\u2026":o==="discover"?"Discovering new keywords to target\u2026":o==="seed"?"Seeding keywords from your Search Console data\u2026":"Enriching keywords with real volume + difficulty\u2026",c=!!process.stdout.isTTY?Pn():null;c?.start(s);let u=o==="competitors"||o==="discover"||o==="seed",d;try{d=await Y(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"},u?{timeoutMs:6e4,attempts:1}:{})}catch(m){w(c,"error",`Network error: ${m.message}`,h.red("Network error.")),process.exitCode=1;return}let p=null;try{p=await d.json()}catch{p=null}if(d.status===402||p?.code==="upgrade_required"){w(c,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",h.yellow("Paid feature \u2014 upgrade to continue.")),l.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${h.cyan(C.PRICING)}`:`Upgrade to find new keywords to target: ${h.cyan(C.PRICING)}`),process.exitCode=1;return}if(!d.ok||p?.status!=="ok"){w(c,"error",`Server rejected request (${d.status})${p?.error?`: ${p.error}`:""}`,h.red(`Server rejected request (${d.status}).`)),process.exitCode=1;return}if(p.skipped==="no-gsc-data"){w(c,"warn","No Search Console data to seed from yet. Connect Google Search Console (run `seoagent login` and link GSC) \u2014 or wait for impressions to accrue on a new site.",h.yellow("No Search Console data yet."));return}if(p.skipped==="no-keywords"||p.skipped==="no-seeds"){w(c,"warn","No keywords yet. Seed from Search Console with `seoagent keywords --seed`, or run the keyword strategy (Phase 2) first, then try again.",h.yellow("No keywords yet."));return}if(p.skipped==="no-competitors"){w(c,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",h.yellow("No competitors yet."));return}if(p.skipped==="no-creds"||p.skipped==="no-columns"||p.skipped==="no-table"){w(c,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(p.skipped){w(c,"warn",`Skipped: ${p.skipped}`,h.yellow(`Skipped: ${p.skipped}`));return}if(o==="competitors"){let m=p.gaps??0;w(c,"success",`Found ${m} competitor gap${m===1?"":"s"} across ${p.competitors?.length??0} competitor${p.competitors?.length===1?"":"s"} (added as "suggested").`,h.green(`${m} competitor gap${m===1?"":"s"} found.`)),Eu(p.topGaps??[]),l.message(`Review them in ${h.cyan(".seoagent/keywords.md")} (a read-only projection \u2014 don't hand-edit it). Keep the on-topic ones for your clusters; clear off-topic noise with \`${f("keywords --purge")}\`.`);return}if(o==="discover"){let m=p.discovered??0;w(c,"success",`Discovered ${m} new keyword${m===1?"":"s"} to target (added as "suggested").`,h.green(`${m} new keyword${m===1?"":"s"} discovered.`)),Rn(p.opportunities??[]),l.message(`Review them in ${h.cyan(".seoagent/keywords.md")} (a read-only projection \u2014 don't hand-edit it). Relevance-check before adopting; clear off-topic noise with \`${f("keywords --purge")}\`.`);return}if(o==="seed"){let m=p.seeded??0;w(c,"success",`Seeded ${m} keyword${m===1?"":"s"} from Search Console (real impressed queries, added as "suggested").`,h.green(`${m} keyword${m===1?"":"s"} seeded from Search Console.`)),Rn(p.opportunities??[]),l.message(`These are queries your site already gets impressions for \u2014 striking-distance wins first. Review in ${h.cyan(".seoagent/keywords.md")} and build clusters from them.`);return}let y=p.enriched??0;w(c,"success",`Enriched ${y} keyword${y===1?"":"s"}.`,h.green(`Enriched ${y} keyword${y===1?"":"s"}.`)),Rn(p.opportunities??[]),p.paid||l.message(`${h.dim("Free plan:")} enriched up to ${h.bold(String(p.cap??25))} keywords. ${h.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${h.cyan(C.PRICING)}`)}import A from"picocolors";import{existsSync as Iu,readFileSync as Ru}from"fs";import{join as Pu}from"path";var ei=["openai","fal","replicate"],Oe={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Ou(e){let t={};if(!Iu(e))return t;let n=Ru(e,"utf-8");for(let r of n.split(/\r?\n/)){let o=r.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i===-1)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return t}function ti(e,t){let n={};for(let r of t){let o=process.env[r];o&&o.trim().length>0&&(n[r]={value:o,source:"process"})}for(let r of ge){let o=Pu(e,r),i=Ou(o);for(let s of t){if(n[s])continue;let a=i[s];a&&a.length>0&&(n[s]={value:a,source:r})}}return{found:n}}function Nt(e){let t=[].concat(...ei.map(a=>Oe[a])),n=ti(e,t),r=[];for(let a of ei)Oe[a].some(c=>n.found[c])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=Oe[o].find(a=>n.found[a])??null,s=i?n.found[i].source:null;return{provider:o,matched_key:i,source:s,available_providers:r}}function ni(e,t){let n=ti(e,Oe[t]);for(let r of Oe[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function ri(){return Oe}function nt(e={}){let t=process.cwd(),n=S(t),r=Nt(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
530
+ `);return}if(l.message(Tu(r)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}W(t,{image_provider:r.provider}),l.info(`Saved to ${A.cyan(".seoagent/project.md")} ${A.dim(`(image_provider: ${r.provider})`)}`)}function Tu(e){let n=i=>A.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${A.dim("\u25CB")} ${A.bold(A.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:A.dim("Set ONE of these to enable image generation:")});let i=ri();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${A.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:A.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${A.cyan(f("env-check"))}`})}else{r.push({content:`${A.green("\u2713")} ${A.dim("Image provider:")} ${A.bold(A.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${A.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${A.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${A.dim(i.join(", "))}`})}let o=`${A.bold(A.cyan("SEOAgent"))} ${A.dim("\xB7")} ${A.dim("env-check")}`;return O(r,{width:64,title:o})}import{existsSync as Tn,mkdirSync as si,writeFileSync as ai}from"fs";import{dirname as Dt,isAbsolute as Du,join as Ft,resolve as Uu}from"path";import{tmpdir as Mu}from"os";import{spinner as Bu}from"@clack/prompts";import T from"picocolors";import{Buffer as oi}from"buffer";async function On(e){let t=await fetch(e);if(!t.ok)throw new Error(`Image download failed: ${t.status} ${t.statusText}`);let n=await t.arrayBuffer();return oi.from(n)}async function ju(e){let t=e.size??"1024x1024",n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:"gpt-image-1",prompt:e.prompt,size:t,n:1})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`OpenAI image API ${n.status}: ${i.slice(0,300)}`)}let o=(await n.json()).data?.[0];if(!o)throw new Error("OpenAI image API returned no data");if(o.b64_json)return{bytes:oi.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await On(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function Lu(e){let t=process.env.FAL_MODEL||"fal-ai/flux/schnell",n=await fetch(`https://fal.run/${t}`,{method:"POST",headers:{Authorization:`Key ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({prompt:e.prompt,image_size:"landscape_16_9",num_images:1})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`fal.ai API ${n.status}: ${s.slice(0,300)}`)}let o=(await n.json()).images?.[0];if(!o?.url)throw new Error("fal.ai API returned no image url");return{bytes:await On(o.url),contentType:o.content_type??"image/png"}}async function Nu(e,t,n=9e4){let r=Date.now(),o=1e3;for(;Date.now()-r<n;){let i=await fetch(`https://api.replicate.com/v1/predictions/${e}`,{headers:{Authorization:`Token ${t}`}});if(!i.ok)throw new Error(`Replicate poll failed: ${i.status}`);let s=await i.json();if(s.status==="succeeded"||s.status==="failed"||s.status==="canceled")return s;await new Promise(a=>setTimeout(a,o)),o=Math.min(o*1.5,5e3)}throw new Error("Replicate prediction timed out")}async function Fu(e){let t=process.env.REPLICATE_MODEL||"black-forest-labs/flux-schnell",n=await fetch(`https://api.replicate.com/v1/models/${t}/predictions`,{method:"POST",headers:{Authorization:`Token ${e.apiKey}`,"Content-Type":"application/json",Prefer:"wait"},body:JSON.stringify({input:{prompt:e.prompt,aspect_ratio:"16:9"}})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Replicate API ${n.status}: ${s.slice(0,300)}`)}let r=await n.json();if(r.status!=="succeeded"&&r.status!=="failed"&&(r=await Nu(r.id,e.apiKey)),r.status!=="succeeded")throw new Error(`Replicate prediction ${r.status}: ${r.error??""}`);let o=Array.isArray(r.output)?r.output[0]:r.output;if(!o)throw new Error("Replicate prediction returned no output");return{bytes:await On(o),contentType:"image/png",providerImageId:r.id}}async function ii(e,t){switch(e){case"openai":return ju(t);case"fal":return Lu(t);case"replicate":return Fu(t);default:throw new Error(`Unknown image provider: ${e}`)}}function Gu(e){return e==="openai"||e==="fal"||e==="replicate"}async function rt(e={}){let t=process.cwd();if(!e.prompt){l.warn(`Missing --prompt. Example: ${f('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){l.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=S(t),r=null;if(e.provider){if(!Gu(e.provider)){l.warn(`Invalid --provider "${e.provider}". Use one of: openai, fal, replicate.`),process.exitCode=1;return}r=e.provider}else n?.image_provider&&n.image_provider!=="none"?r=n.image_provider:r=Nt(t).provider;if(!r||r==="none"){l.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${f("env-check")}\`.`),process.exitCode=1;return}let o=ni(t,r);if(!o){l.warn(`Provider "${r}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=Du(e.out)?e.out:Uu(t,e.out),a=!e.silent&&!!process.stdout.isTTY?Bu():null;a?.start(`Generating image with ${T.bold(r)} ${T.dim(`(${o.envName})`)}\u2026`);try{let c=await ii(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Tn(Dt(i))||si(Dt(i),{recursive:!0}),ai(i,c.bytes),e.silent||w(a,"success",`Wrote ${i} (${c.bytes.length} bytes, ${c.contentType}).`,T.green(`Wrote ${i} ${T.dim(`(${c.bytes.length} bytes, ${c.contentType})`)}`))}catch(c){a?.stop(T.red("Image generation failed."));let u=Ku(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(Wu({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:c.message})),u&&l.message(`${T.dim("Full error log:")} ${T.cyan(u)}`),process.exitCode=1}}function Wu(e){let n=d=>T.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${T.red("\u2717")} ${T.bold(T.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${T.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${T.dim(`"${o}"`)}`}];e.size&&i.push({content:`${n("Size:")}${e.size}`}),i.push({sep:!0});let s=e.message.replace(/\s+/g," ").trim(),a=64,c=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:T.red(c)});let u=`${T.bold(T.cyan("SEOAgent"))} ${T.dim("\xB7")} ${T.dim("generate-image")}`;return O(i,{width:70,title:u})}function Ku(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=Ft(e,b),i=Ft(o,".errors"),s=Tn(o)?Ft(i,r):Ft(Mu(),r),a=["# SEOAgent generate-image error",`# ${new Date().toISOString()}`,"","## Request",`provider: ${t.provider}`,`env_var: ${t.envName}`,`prompt: ${JSON.stringify(t.prompt)}`,`size: ${t.size??"(default)"}`,`out_path: ${t.outPath}`,`cwd: ${e}`,"","## Error",`message: ${t.error.message}`,"","## Stack",t.error.stack??"(no stack)",""];t.error.cause&&a.push("## Cause",String(t.error.cause),"");try{return Tn(Dt(s))||si(Dt(s),{recursive:!0}),ai(s,a.join(`
531
531
  `)),s}catch{return null}}import U from"picocolors";async function ot(e={}){let t=P();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
532
532
  `):l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||C.BASE).replace(/\/$/,""),r=`Bearer ${t.user_token}:${t.website_token}`,o;try{o=await fetch(`${n}/api/cli/whoami`,{method:"GET",headers:{Authorization:r,Accept:"application/json"}})}catch(s){l.error(`Network error: ${s.message}`),process.exitCode=1;return}if(o.status===404){if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,server_supports_whoami:!1,api_base:n})}
533
533
  `);return}l.warn(`Logged in, but the server at this API base does not support \`/api/cli/whoami\` yet. Update with \`${f("update-cli")}\` (or re-deploy your server).`),l.message(`API base: ${n}`);return}let i=null;try{i=await o.json()}catch{i=null}if(!o.ok||!i||i.status!=="ok"){e.json?process.stdout.write(`${JSON.stringify({logged_in:!0,error:i?.error??`HTTP ${o.status}`})}
534
534
  `):l.error(`Could not fetch your account (HTTP ${o.status})${i?.error?`: ${i.error}`:""}`),process.exitCode=1;return}if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,...i},null,2)}
535
- `);return}l.message(Gu(i)),i.paid===!1&&l.message(`${U.dim("Upgrade for autopilot:")} ${U.cyan(C.PRICING)}`)}function Gu(e){let n=i=>U.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${U.green("\u2713")} ${U.dim("Logged in as")} ${U.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${U.cyan(e.domain)}`}),e.plan){let i=e.paid?U.bold(U.green(e.plan)):U.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${U.dim(e.api_base)}`});let o=`${U.bold(U.cyan("SEOAgent"))} ${U.dim("\xB7")} ${U.dim("whoami")}`;return O(r,{width:55,title:o})}import{select as st,text as it,confirm as ui,isCancel as B,intro as Wu,outro as Ku}from"@clack/prompts";import Ut from"picocolors";function qu(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>Ke()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await Y()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await Be()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await ze()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await ot()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await st({message:"Which mode?",options:[{value:"peek",label:"peek",hint:"Free, one keyword, no login required"},{value:"enrich",label:"enrich (default)",hint:"Enrich your full strategy (requires login)"},{value:"discover",label:"discover",hint:"Find new keywords to target (paid)"},{value:"competitors",label:"competitors",hint:"Find competitor keyword gaps (paid)"}]});if(!B(e))if(e==="peek"){let t=await it({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(B(t))return;await ie({peek:String(t)})}else e==="discover"?await ie({discover:!0}):e==="competitors"?await ie({competitors:!0}):await ie()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>Xe({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await st({message:"Which OKF action?",options:[{value:"status",label:"status",hint:"Is a bundle present?"},{value:"scaffold",label:"scaffold",hint:"Create the starter bundle"},{value:"validate",label:"validate",hint:"Check type fields, timestamps, links"}]});B(e)||Ze(e==="status"?void 0:String(e))}},{command:"citations",label:"Measure AI citations (AEO/GEO)",hint:"Are answer engines citing you? Web-grounded \u2192 .seoagent/citations/scorecard.md",run:async()=>await et()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await it({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(B(e))return;let t=await it({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});B(t)||await rt({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>nt({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await st({message:"Autopilot action:",options:[{value:"status",label:"status",hint:"Show current state"},{value:"on",label:"on",hint:"Turn autopilot ON (paid)"},{value:"off",label:"off",hint:"Turn autopilot OFF"}]});B(e)||await Qe(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await me()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await it({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(B(e))return;let t=await ui({message:"Mark as failed instead of completed?",initialValue:!1});if(B(t))return;let n;if(t===!0){let r=await it({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(B(r))return;String(r).trim()&&(n=String(r))}await re(String(e),{failed:t===!0,reason:n})}},{command:"upgrade",label:"Upgrade your SEOAgent plan",hint:"Open the pricing page; contextual prompt if logged in.",run:async()=>await He()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest + refresh your projects",run:async()=>await Ye({})},{command:"refresh",label:"Refresh the skill to your CLI version",hint:"This project \u2014 or every project on the machine via `refresh --all`.",run:async()=>{let e=await st({message:"Refresh which?",options:[{value:"this",label:"This project",hint:"Just the current directory"},{value:"all",label:"All projects",hint:"Every SEOAgent project on this machine"}]});B(e)||tt({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>Ve()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await Ge({})}]}var li="__exit__";async function ci(e=qu()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:li,label:"Exit",hint:"Close the menu"});let n=await st({message:"What would you like to do?",options:t});if(B(n)||n===li)return!0;let r=e.find(o=>o.command===n);if(!r)return l.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){l.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function Tn(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}Wu(`${Ut.bold(Ut.cyan("SEOAgent"))} ${Ut.dim("\xB7 menu")}`);let e=await ci();for(;!e;){let t=await ui({message:"Do another?",initialValue:!0});if(B(t)||t===!1){e=!0;break}e=await ci()}Ku(Ut.dim("See you next time."))}var x=new Hu;x.name("seoagent").description("AI SEO agent for Claude Code").version(v).showSuggestionAfterError(!0).showHelpAfterError(!0);x.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").action(e=>{Be({yes:e.yes,domain:e.domain,siteType:e.siteType})});x.command("uninstall").description("Remove SEOAgent from this project \u2014 deletes .seoagent/, the skill bundle, and the sync hook").option("-y, --yes","Skip the confirmation prompt (also implied in a non-TTY shell)").option("--global","Also wipe ~/.config/seoagent (login + sync state, all projects)").action(e=>{Ge({yes:e.yes,global:e.global})});x.command("status").description("Show current SEO project state").action(Ke);x.command("login").description("Connect this CLI to your seoagent.com account (browser flow)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{ze({apiBase:e.apiBase})});x.command("logout").description("Remove stored credentials for seoagent.com").action(Ve);x.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force","Re-send every artifact on push; take cloud on every pull conflict").option("--path <relpath>","Push only files matching this path suffix").option("--push-only","Skip the cloud \u2192 local pull pass").option("--pull-only","Skip the local \u2192 cloud push pass (same as `seoagent pull`)").action(e=>{Y({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});x.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force","Take the cloud version on every conflict (discards local edits)").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{me({force:e.force,silent:e.silent,print:e.print})});x.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{re(e,{failed:t.failed,reason:t.reason})});x.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{hn({json:e.json})});x.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{bn({yes:e.yes,model:e.model})});x.command("autopilot <action>").description("Turn CLI autopilot on|off or show status (paid; queues fixes for your agent)").option("--api-base <url>","Override API base URL (for testing)").action((e,t)=>{Qe(e,{apiBase:t.apiBase})});x.command("keywords").description("Enrich keywords with real volume + difficulty + opportunity labels (requires login)").option("--peek <keyword>","Free one-keyword DataForSEO lookup (no login required; daily quota)").option("--seed","Add the queries your site already ranks for (Google Search Console) to the inventory \u2014 additive, keeps existing keywords (requires login + GSC)").option("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{ie({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,json:e.json,apiBase:e.apiBase})});x.command("internal-links").description("Analyze the repo for orphan pages (no inbound internal links) \u2192 .seoagent/internal-links.md").option("--json","Print the analysis as JSON instead of writing the report").action(e=>{Xe({json:e.json})});x.command("okf [action]").description("Manage the Open Knowledge Format bundle for AI agents \u2014 [validate|scaffold] \u2192 .seoagent/okf/").option("--json","Output result as JSON").action((e,t)=>{Ze(e,{json:t.json})});x.command("citations").description("Measure whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{et({queries:e.queries,model:e.model,json:e.json})});x.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{nt({json:e.json})});x.command("generate-image").description("Generate an image via the detected (or explicit) provider").requiredOption("--prompt <text>","Image prompt").requiredOption("--out <path>","Output file path (relative to cwd or absolute)").option("--provider <name>","Force provider: openai | fal | replicate").option("--size <wxh>","Pixel size hint, e.g. 1024x1024").option("--silent","Suppress progress output").action(e=>{rt({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});x.command("whoami").description("Show the logged-in account: email, bound website, plan, and API base").option("--json","Output as JSON (handy for scripting / `jq`)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{ot({json:e.json,apiBase:e.apiBase})});x.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(He);x.command("update-cli").description("Update the SEOAgent CLI to the latest npm version, then refresh every project on this machine").option("--dry-run","Show what would happen without running the install").option("--no-projects","Skip refreshing your other projects after the update").action(e=>{Ye({dryRun:e.dryRun,projects:e.projects})});x.command("refresh").description("Refresh the installed skill + re-scan the codebase for new pages. `--all` sweeps every project on this machine.").option("--all","Refresh every registered project, not just this one").action(e=>{tt({all:e.all})});x.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Tn()});process.argv.length===2&&(x.outputHelp(),process.exit(0));x.parse();
535
+ `);return}l.message(qu(i)),i.paid===!1&&l.message(`${U.dim("Upgrade for autopilot:")} ${U.cyan(C.PRICING)}`)}function qu(e){let n=i=>U.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${U.green("\u2713")} ${U.dim("Logged in as")} ${U.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${U.cyan(e.domain)}`}),e.plan){let i=e.paid?U.bold(U.green(e.plan)):U.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${U.dim(e.api_base)}`});let o=`${U.bold(U.cyan("SEOAgent"))} ${U.dim("\xB7")} ${U.dim("whoami")}`;return O(r,{width:55,title:o})}import{select as st,text as it,confirm as ui,isCancel as B,intro as Hu,outro as Yu}from"@clack/prompts";import Ut from"picocolors";function zu(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>Ke()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await z()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await Be()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await ze()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await ot()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await st({message:"Which mode?",options:[{value:"peek",label:"peek",hint:"Free, one keyword, no login required"},{value:"enrich",label:"enrich (default)",hint:"Enrich your full strategy (requires login)"},{value:"discover",label:"discover",hint:"Find new keywords to target (paid)"},{value:"competitors",label:"competitors",hint:"Find competitor keyword gaps (paid)"}]});if(!B(e))if(e==="peek"){let t=await it({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(B(t))return;await ie({peek:String(t)})}else e==="discover"?await ie({discover:!0}):e==="competitors"?await ie({competitors:!0}):await ie()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>Xe({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await st({message:"Which OKF action?",options:[{value:"status",label:"status",hint:"Is a bundle present?"},{value:"scaffold",label:"scaffold",hint:"Create the starter bundle"},{value:"validate",label:"validate",hint:"Check type fields, timestamps, links"}]});B(e)||Ze(e==="status"?void 0:String(e))}},{command:"citations",label:"Measure AI citations (AEO/GEO)",hint:"Are answer engines citing you? Web-grounded \u2192 .seoagent/citations/scorecard.md",run:async()=>await et()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await it({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(B(e))return;let t=await it({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});B(t)||await rt({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>nt({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await st({message:"Autopilot action:",options:[{value:"status",label:"status",hint:"Show current state"},{value:"on",label:"on",hint:"Turn autopilot ON (paid)"},{value:"off",label:"off",hint:"Turn autopilot OFF"}]});B(e)||await Qe(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await me()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await it({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(B(e))return;let t=await ui({message:"Mark as failed instead of completed?",initialValue:!1});if(B(t))return;let n;if(t===!0){let r=await it({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(B(r))return;String(r).trim()&&(n=String(r))}await re(String(e),{failed:t===!0,reason:n})}},{command:"upgrade",label:"Upgrade your SEOAgent plan",hint:"Open the pricing page; contextual prompt if logged in.",run:async()=>await He()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest + refresh your projects",run:async()=>await Ye({})},{command:"refresh",label:"Refresh the skill to your CLI version",hint:"This project \u2014 or every project on the machine via `refresh --all`.",run:async()=>{let e=await st({message:"Refresh which?",options:[{value:"this",label:"This project",hint:"Just the current directory"},{value:"all",label:"All projects",hint:"Every SEOAgent project on this machine"}]});B(e)||tt({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>Ve()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await Ge({})}]}var li="__exit__";async function ci(e=zu()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:li,label:"Exit",hint:"Close the menu"});let n=await st({message:"What would you like to do?",options:t});if(B(n)||n===li)return!0;let r=e.find(o=>o.command===n);if(!r)return l.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){l.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function jn(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}Hu(`${Ut.bold(Ut.cyan("SEOAgent"))} ${Ut.dim("\xB7 menu")}`);let e=await ci();for(;!e;){let t=await ui({message:"Do another?",initialValue:!0});if(B(t)||t===!1){e=!0;break}e=await ci()}Yu(Ut.dim("See you next time."))}var x=new Vu;x.name("seoagent").description("AI SEO agent for Claude Code").version(v).showSuggestionAfterError(!0).showHelpAfterError(!0);x.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").action(e=>{Be({yes:e.yes,domain:e.domain,siteType:e.siteType})});x.command("uninstall").description("Remove SEOAgent from this project \u2014 deletes .seoagent/, the skill bundle, and the sync hook").option("-y, --yes","Skip the confirmation prompt (also implied in a non-TTY shell)").option("--global","Also wipe ~/.config/seoagent (login + sync state, all projects)").action(e=>{Ge({yes:e.yes,global:e.global})});x.command("status").description("Show current SEO project state").action(Ke);x.command("login").description("Connect this CLI to your seoagent.com account (browser flow)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{ze({apiBase:e.apiBase})});x.command("logout").description("Remove stored credentials for seoagent.com").action(Ve);x.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force","Re-send every artifact on push; take cloud on every pull conflict").option("--path <relpath>","Push only files matching this path suffix").option("--push-only","Skip the cloud \u2192 local pull pass").option("--pull-only","Skip the local \u2192 cloud push pass (same as `seoagent pull`)").action(e=>{z({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});x.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force","Take the cloud version on every conflict (discards local edits)").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{me({force:e.force,silent:e.silent,print:e.print})});x.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{re(e,{failed:t.failed,reason:t.reason})});x.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{hn({json:e.json})});x.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{bn({yes:e.yes,model:e.model})});x.command("autopilot <action>").description("Turn CLI autopilot on|off or show status (paid; queues fixes for your agent)").option("--api-base <url>","Override API base URL (for testing)").action((e,t)=>{Qe(e,{apiBase:t.apiBase})});x.command("keywords").description("Enrich keywords with real volume + difficulty + opportunity labels (requires login)").option("--peek <keyword>","Free one-keyword DataForSEO lookup (no login required; daily quota)").option("--seed","Add the queries your site already ranks for (Google Search Console) to the inventory \u2014 additive, keeps existing keywords (requires login + GSC)").option("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--purge","Delete suggested keywords (discover/competitors noise) from the cloud inventory").option("--all","With --purge: clear EVERY keyword for this site, not just suggested").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{ie({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});x.command("internal-links").description("Analyze the repo for orphan pages (no inbound internal links) \u2192 .seoagent/internal-links.md").option("--json","Print the analysis as JSON instead of writing the report").action(e=>{Xe({json:e.json})});x.command("okf [action]").description("Manage the Open Knowledge Format bundle for AI agents \u2014 [validate|scaffold] \u2192 .seoagent/okf/").option("--json","Output result as JSON").action((e,t)=>{Ze(e,{json:t.json})});x.command("citations").description("Measure whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{et({queries:e.queries,model:e.model,json:e.json})});x.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{nt({json:e.json})});x.command("generate-image").description("Generate an image via the detected (or explicit) provider").requiredOption("--prompt <text>","Image prompt").requiredOption("--out <path>","Output file path (relative to cwd or absolute)").option("--provider <name>","Force provider: openai | fal | replicate").option("--size <wxh>","Pixel size hint, e.g. 1024x1024").option("--silent","Suppress progress output").action(e=>{rt({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});x.command("whoami").description("Show the logged-in account: email, bound website, plan, and API base").option("--json","Output as JSON (handy for scripting / `jq`)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{ot({json:e.json,apiBase:e.apiBase})});x.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(He);x.command("update-cli").description("Update the SEOAgent CLI to the latest npm version, then refresh every project on this machine").option("--dry-run","Show what would happen without running the install").option("--no-projects","Skip refreshing your other projects after the update").action(e=>{Ye({dryRun:e.dryRun,projects:e.projects})});x.command("refresh").description("Refresh the installed skill + re-scan the codebase for new pages. `--all` sweeps every project on this machine.").option("--all","Refresh every registered project, not just this one").action(e=>{tt({all:e.all})});x.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{jn()});process.argv.length===2&&(x.outputHelp(),process.exit(0));x.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seoagent-official/seoagent",
3
- "version": "1.56.2",
3
+ "version": "1.56.3",
4
4
  "description": "The persistent AI SEO agent for Claude Code. Audits, keyword strategy, briefs, articles, and the autopilot loop (cloud detects → CLI executes → ack closes) — other SEO tools write the prompt, SEOAgent runs it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -135,6 +135,8 @@ backlog: 26
135
135
  - "technical seo audit checklist" — backlog under technical-seo cluster
136
136
  ```
137
137
 
138
+ > **⚠️ `keywords.md` is parsed by a strict machine format — write keyword phrases ONLY.** After each `**…:**` label, write a plain comma-separated list of keyword *phrases* and nothing else. **Do NOT inline volume, KD/difficulty, intent, stars, or notes into this file** — the parser splits on commas and persists every fragment as a keyword, so `**Pillar keyword:** ai seo tools — vol 2400, KD 10` becomes the junk keywords `KD 10` and `ai seo tools — vol 2400` in the cloud. Put all metrics, analysis, and commentary in `strategy/discovery.md` or the cluster files instead. In the Unclustered list, a short ` — annotation` after the phrase is fine (it's stripped), but keep the phrase itself clean. Once you've run `seoagent keywords` (cloud enrichment), `keywords.md` becomes a **read-only projection** (`generated: true`) — don't hand-edit it then; clear discovery noise with `seoagent keywords --purge`.
139
+
138
140
  ### Step 6: Cluster the Keywords
139
141
 
140
142
  Group keywords into clusters with role assignments:
@@ -468,6 +468,8 @@ A **free SEOAgent Cloud account** unlocks **real volume + difficulty + opportuni
468
468
  - `keywords --discover` — DataForSEO `keyword_ideas` seeded from your clusters/audience, classified, with worthwhile new targets added to `seoagent_keywords` as `status='suggested'` for the agent to triage.
469
469
  - `keywords --competitors` — finds keywords your competitors rank top-10 for that you don't track (discovers competitors via `competitors_domain`, merges with your tracked competitors, pulls each rival's `ranked_keywords`, excludes anything you already track). Gap keywords land in `seoagent_keywords` as `status='suggested'`, `opportunity='competitor_gap'`.
470
470
 
471
+ > **Cleaning up suggested noise.** `--discover` / `--competitors` add `status='suggested'` rows; on a thin or new site some are off-topic. **Relevance-check every suggested keyword and drop anything off-topic** — high volume / low difficulty is not enough. To clear the noise from the cloud inventory, run `seoagent keywords --purge` (removes only `suggested` rows; your clustered keywords are kept). `--purge --all` resets the whole inventory.
472
+
471
473
  **Sequencing matters — do NOT lead with these.** They expand an existing topic signal; on a new/thin site they return generic noise. Do WebSearch research first, write `.seoagent/keywords.md` + `.seoagent/competitors.md` (real domains in the headings) and `seoagent sync`, THEN run `keywords` → `--discover` → `--competitors`. Always relevance-check every `status='suggested'` result and drop anything off-topic before adding it to the strategy — high volume / low difficulty is not enough. See `references/keyword-research.md` § "Use the Pro discovery commands correctly." For one-off real numbers, `keywords --peek "<kw>"` is the reliable path.
472
474
 
473
475
  After research without enrichment, mention once: "These priorities are estimates from search. A free login enriches your top ~25 keywords with real DataForSEO volume + difficulty (`keywords`); upgrade unlocks discovery of new targets (`--discover`) and competitor-gap analysis (`--competitors`)."
@@ -475,10 +477,12 @@ After research without enrichment, mention once: "These priorities are estimates
475
477
  ### Outputs
476
478
 
477
479
  - `.seoagent/strategy/clusters/{cluster-slug}.md` — one per cluster, includes article table + link graph
478
- - `.seoagent/strategy/discovery.md` — top opportunities, competitor gaps, cluster index
480
+ - `.seoagent/strategy/discovery.md` — top opportunities, competitor gaps, cluster index. **All metrics + analysis go here**, not in `keywords.md`.
479
481
  - `.seoagent/competitors.md` — competitor profiles persisted across sessions
480
482
  - `.seoagent/keywords.md` — master keyword inventory (assigned + backlog)
481
483
 
484
+ > **⚠️ `keywords.md` is a strict machine-parsed file — keyword phrases ONLY.** After each `**Pillar keyword:** / **Sub-pillar keywords:** / **Long-tail (...):**` label, write a plain comma-separated list of keyword phrases. **Never inline volume / KD / difficulty / intent / notes / stars into this file** — the parser splits on commas and turns every fragment into a keyword, so `ai seo tools — vol 2400, KD 10` is persisted as the junk keywords `KD 10` etc. Put numbers and commentary in `strategy/discovery.md` or the cluster files. After you run `seoagent keywords` (cloud enrichment), `keywords.md` becomes a **read-only projection** — stop hand-editing it; clear discovery noise with `seoagent keywords --purge`. See `references/keyword-research.md` Step 5.
485
+
482
486
  After writing, run `seoagent sync`.
483
487
 
484
488
  ---
@@ -798,6 +802,8 @@ Append-only log. One line per action.
798
802
 
799
803
  Persisted research artifacts so each phase compounds. Format: frontmatter with `last_updated_at`, body with markdown tables / sections.
800
804
 
805
+ > **`keywords.md` + `pages.md` are machine-parsed — and become cloud-owned.** `keywords.md` uses the strict `## Cluster:` / `**Pillar keyword:** kw1, kw2` format (keyword phrases only — no inline metrics; see Phase 2 Outputs). After the first `seoagent keywords` enrichment (and for `pages.md`, after the cloud regenerates it), these files carry `generated: true` and are **read-only projections of cloud state** — edits get overwritten on the next `seoagent pull`. Don't hand-edit a `generated: true` file; use the dashboard, or `seoagent keywords --purge` to clear keyword noise.
806
+
801
807
  ### Authentication
802
808
 
803
809
  The CLI manages credentials at `~/.config/seoagent/auth.json` — outside the project tree. Never write tokens into `.seoagent/`. Tell the user to run `seoagent login` if they want sync.