@seoagent-official/seoagent 1.61.0 → 1.61.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +81 -81
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1,40 +1,40 @@
1
1
  #!/usr/bin/env node
2
- import{Command as Kd}from"commander";import{dirname as no,relative as Ot}from"path";import{intro as ha,outro as ya,text as Zr,select as hn,spinner as wa,isCancel as Re,cancel as Ie,confirm as ka}from"@clack/prompts";var Se=[".env.local",".env.production",".env"],Qn=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var ee="@seoagent-official/seoagent",ht=`${ee}@latest`;import{homedir as Fi}from"os";import{join as ve}from"path";var k=".seoagent",Zn=["audit","strategy/clusters","briefs","content","content/images","performance"],fe={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},yt=".claude/settings.json",wt=".pull-receipt.json",er=".ack-queue.json",tr=".sync.lock",nr=`# SEOAgent local files
2
+ import{Command as Yd}from"commander";import{dirname as io,relative as Pt}from"path";import{intro as ka,outro as ba,text as no,select as mn,spinner as $a,isCancel as Re,cancel as Ie,confirm as Sa}from"@clack/prompts";var Se=[".env.local",".env.production",".env"],Zn=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var ee="@seoagent-official/seoagent",gt=`${ee}@latest`;import{homedir as Ui}from"os";import{join as ve}from"path";var k=".seoagent",er=["audit","strategy/clusters","briefs","content","content/images","performance"],fe={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},ht=".claude/settings.json",yt=".pull-receipt.json",tr=".ack-queue.json",nr=".sync.lock",rr=`# 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
- `,Di=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:ve(Fi(),".config"),M=ve(Di,"seoagent"),oe=ve(M,"auth.json"),Zt=ve(M,"state"),kt=ve(M,"update-check.json"),bt=ve(M,"projects.json");var Me="https://seoagent.com",xe=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):Me,A={BASE:xe,PRICING:`${xe}/pricing`,LEAD_API:`${xe}/api/cli/lead`,CLI_AUTH_PAGE:`${xe}/cli/auth`,CLI_AUTH_POLL:`${xe}/api/cli/auth/poll`,CLI_SYNC:`${xe}/api/cli/sync`};import{readFileSync as Ui}from"fs";import{fileURLToPath as Mi}from"url";import{dirname as Bi,join as Gi}from"path";var rr="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 rr}function Wi(e=t=>Ui(t,"utf-8")){try{let t=Bi(Mi(import.meta.url));return Ki(e(Gi(t,"package.json")))}catch{return rr}}var E=Wi();function en(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=en()){return t?`seoagent ${e}`:`npx -y ${ht} ${e}`}import{randomUUID as Vi}from"crypto";import{existsSync as or,mkdirSync as ir,readFileSync as Ji,writeFileSync as sr}from"fs";import{join as nn}from"path";import{existsSync as qi,readFileSync as Hi}from"fs";var $t="---";function Yi(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 Be(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==$t)return{data:{},body:e};let n={},r=1;for(;r<t.length;r++){if(t[r].trim()===$t){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]=Yi(a))}return{data:n,body:t.slice(r).join(`
10
- `)}}function St(e){if(!qi(e))return null;try{return Be(Hi(e,"utf-8"))}catch{return null}}function zi(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 tn(e,t=""){let n=[$t];for(let[o,i]of Object.entries(e))i!==void 0&&n.push(`${o}: ${zi(i)}`);n.push($t);let r=t.length===0?"":t.startsWith(`
9
+ `,Mi=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:ve(Ui(),".config"),M=ve(Mi,"seoagent"),oe=ve(M,"auth.json"),Xt=ve(M,"state"),wt=ve(M,"update-check.json"),kt=ve(M,"projects.json");var Me="https://seoagent.com",xe=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):Me,A={BASE:xe,PRICING:`${xe}/pricing`,LEAD_API:`${xe}/api/cli/lead`,CLI_AUTH_PAGE:`${xe}/cli/auth`,CLI_AUTH_POLL:`${xe}/api/cli/auth/poll`,CLI_SYNC:`${xe}/api/cli/sync`};import{readFileSync as Bi}from"fs";import{fileURLToPath as Gi}from"url";import{dirname as Wi,join as Ki}from"path";var or="0.0.0";function qi(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return or}function Hi(e=t=>Bi(t,"utf-8")){try{let t=Wi(Gi(import.meta.url));return qi(e(Ki(t,"package.json")))}catch{return or}}var E=Hi();function Qt(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=Qt()){return t?`seoagent ${e}`:`npx -y ${gt} ${e}`}import{randomUUID as Qi}from"crypto";import{existsSync as ar,mkdirSync as lr,readFileSync as Zi,writeFileSync as cr}from"fs";import{join as en}from"path";import{existsSync as Yi,readFileSync as Vi}from"fs";var bt="---";function zi(e){let t=e.trim();return 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 Ji(e){let t=[];for(let n of e){let r=n.trim();if(r===""||r.startsWith("#"))continue;let o=n.indexOf(":");if(o===-1)continue;let i=n.slice(0,o).trim();if(!i)continue;let s=n.slice(o+1),a=n.length-n.replace(/^\s+/,"").length;t.push({indent:a,key:i,valueRaw:s,value:s.trim()})}return t}function ir(e,t,n){let r={},o=t;for(;o<e.length;){let i=e[o];if(i.indent<n)break;if(i.indent>n){o++;continue}if(i.value===""){let s=e[o+1];if(s&&s.indent>n){let[a,c]=ir(e,o+1,s.indent);r[i.key]=a,o=c}else r[i.key]="",o++}else r[i.key]=zi(i.valueRaw),o++}return[r,o]}function Be(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==bt)return{data:{},body:e};let n=-1;for(let c=1;c<t.length;c++)if(t[c].trim()===bt){n=c;break}let r=n===-1?t.slice(1):t.slice(1,n),o=n===-1?"":t.slice(n+1).join(`
10
+ `),i=Ji(r),s=i.length>0?i[0].indent:0,[a]=ir(i,0,s);return{data:a,body:o}}function $t(e){if(!Yi(e))return null;try{return Be(Vi(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 sr(e,t,n){let r=" ".repeat(t);for(let[o,i]of Object.entries(e))i!==void 0&&(i!==null&&typeof i=="object"?(n.push(`${r}${o}:`),sr(i,t+1,n)):n.push(`${r}${o}: ${Xi(i)}`))}function Zt(e,t=""){let n=[bt];sr(e,0,n),n.push(bt);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 Xi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rn(){return Vi()}var Qi=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),Zi="project.md";function Ge(e){return nn(e,k)}function vt(e){return nn(Ge(e),Zi)}function ar(e){return or(vt(e))}function _(e){let t=St(vt(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&&Qi.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&&Xi.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 lr(e){let t=_(e);if(!t)return null;if(t.install_id)return t.install_id;let n=rn();return z(e,{install_id:n}),n}function es(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 ts(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 cr(e,t){let n=Ge(e);ir(n,{recursive:!0});let r=tn(ts(t),es(t));sr(vt(e),r,"utf-8")}function z(e,t){let n=vt(e);if(!or(n))return!1;let r=Be(Ji(n,"utf-8")),o={...r.data,...t};return sr(n,tn(o,r.body),"utf-8"),!0}function ur(e){let t=Ge(e);for(let n of Zn)ir(nn(t,n),{recursive:!0})}import{existsSync as xt,lstatSync as ns,mkdirSync as Ke,readFileSync as dr,readdirSync as rs,rmSync as os,statSync as is,symlinkSync as ss,writeFileSync as pr}from"fs";import{dirname as _t,join as J,relative as fr}from"path";import{fileURLToPath as as}from"url";var ls=_t(as(import.meta.url));function mr(){return J(ls,"skills")}function cs(){let e=J(mr(),"seoagent.md");if(xt(e))return dr(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function gr(e,t){let n=[];if(!xt(e))return n;for(let r of rs(e,{withFileTypes:!0})){let o=J(e,r.name),i=J(t,r.name);r.isDirectory()?(Ke(i,{recursive:!0}),n.push(...gr(o,i))):r.isFile()&&(Ke(_t(i),{recursive:!0}),pr(i,dr(o)),n.push(i))}return n}function _e(e,t){let n=xt(J(e,".agents")),r=J(e,n?fe.AGENTS:fe.CLAUDE),o=J(r,"SKILL.md");Ke(r,{recursive:!0}),pr(o,t??cs(),"utf-8");let i=J(mr(),"references"),s=J(r,"references"),a=[];try{xt(i)&&is(i).isDirectory()&&(Ke(s,{recursive:!0}),a=gr(i,s).map(u=>fr(r,u)))}catch{}let c=n?us(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:c}}function us(e,t){let n=J(e,fe.CLAUDE),r=null;try{r=ns(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{os(n,{force:!0})}catch{return}}try{Ke(_t(n),{recursive:!0});let o=fr(_t(n),t);return ss(o,n,"dir"),n}catch{return}}import{existsSync as Et,mkdirSync as on,readFileSync as ds,writeFileSync as Ct}from"fs";import{dirname as yr,join as Ce}from"path";var ps=`npx -y ${ht} sync --silent`;function wr(e){let t=Ce(e,k);on(t,{recursive:!0});let n=Ce(t,".gitignore");Ct(n,nr,"utf-8");let r=Ce(t,"content","images",".gitkeep");return on(yr(r),{recursive:!0}),Et(r)||Ct(r,"","utf-8"),n}var kr=["PostToolUse","SessionStart"];function sn(e){if(!Et(e))return{};try{let t=ds(e,"utf-8");return JSON.parse(t)}catch{return{}}}function an(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function hr(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(an)?!1:(r.hooks.push({type:"command",command:ps}),!0)}function me(e){let t=Ce(e,yt);on(yr(t),{recursive:!0});let n=sn(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=hr(r,a=>(a.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),i=n.hooks.SessionStart=n.hooks.SessionStart??[],s=hr(i,a=>(a.matcher??"")==="",()=>({hooks:[]}));return Ct(t,JSON.stringify(n,null,2)+`
17
- `,"utf-8"),{file:t,added:o||s}}function br(e){let t=Ce(e,yt);if(!Et(t))return!1;let n=sn(t).hooks;return n?kr.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(an))}):!1}function $r(e){let t=Ce(e,yt);if(!Et(t))return{file:t,removed:!1};let n=sn(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of kr){let s=r[i];if(!Array.isArray(s))continue;for(let c of s){let u=c.hooks.length;c.hooks=c.hooks.filter(p=>!an(p)),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,Ct(t,JSON.stringify(n,null,2)+`
18
- `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as Sr,mkdirSync as fs,readFileSync as ms,writeFileSync as gs}from"fs";import{join as hs}from"path";function vr(e){return Sr(hs(e,k,"project.md"))}function xr(){try{if(!Sr(bt))return[];let e=JSON.parse(ms(bt,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function _r(e){try{fs(M,{recursive:!0}),gs(bt,JSON.stringify({projects:e},null,2)+`
19
- `,"utf-8")}catch{}}function ge(e){try{if(!vr(e))return;let t=xr();if(t.includes(e))return;t.push(e),_r(t)}catch{}}function Cr(){let e=xr(),t=e.filter(vr);return t.length!==e.length&&_r(t),t}import{readFileSync as bs,writeFileSync as $s,existsSync as Ss}from"fs";import{join as Ir}from"path";function Ar(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=ys(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=ws(o):i==="writing instructions"?t.writingInstructions=Er(o):i==="reference urls"?t.referenceUrls=ks(o):i==="topics to avoid"?t.topicsToAvoid=Er(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function Rr(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
- `)}function ys(e){let t=e.split(`
15
+ `)}var es=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function tn(){return Qi()}var ts=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),ns="project.md";function Ge(e){return en(e,k)}function St(e){return en(Ge(e),ns)}function ur(e){return ar(St(e))}function _(e){let t=$t(St(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&&ts.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&&es.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 dr(e){let t=_(e);if(!t)return null;if(t.install_id)return t.install_id;let n=tn();return V(e,{install_id:n}),n}function rs(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 os(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 pr(e,t){let n=Ge(e);lr(n,{recursive:!0});let r=Zt(os(t),rs(t));cr(St(e),r,"utf-8")}function V(e,t){let n=St(e);if(!ar(n))return!1;let r=Be(Zi(n,"utf-8")),o={...r.data,...t};return cr(n,Zt(o,r.body),"utf-8"),!0}function fr(e){let t=Ge(e);for(let n of er)lr(en(t,n),{recursive:!0})}import{existsSync as vt,lstatSync as is,mkdirSync as We,readFileSync as mr,readdirSync as ss,rmSync as as,statSync as ls,symlinkSync as cs,writeFileSync as gr}from"fs";import{dirname as xt,join as J,relative as hr}from"path";import{fileURLToPath as us}from"url";var ds=xt(us(import.meta.url));function yr(){return J(ds,"skills")}function ps(){let e=J(yr(),"seoagent.md");if(vt(e))return mr(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function wr(e,t){let n=[];if(!vt(e))return n;for(let r of ss(e,{withFileTypes:!0})){let o=J(e,r.name),i=J(t,r.name);r.isDirectory()?(We(i,{recursive:!0}),n.push(...wr(o,i))):r.isFile()&&(We(xt(i),{recursive:!0}),gr(i,mr(o)),n.push(i))}return n}function _e(e,t){let n=vt(J(e,".agents")),r=J(e,n?fe.AGENTS:fe.CLAUDE),o=J(r,"SKILL.md");We(r,{recursive:!0}),gr(o,t??ps(),"utf-8");let i=J(yr(),"references"),s=J(r,"references"),a=[];try{vt(i)&&ls(i).isDirectory()&&(We(s,{recursive:!0}),a=wr(i,s).map(u=>hr(r,u)))}catch{}let c=n?fs(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:c}}function fs(e,t){let n=J(e,fe.CLAUDE),r=null;try{r=is(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{as(n,{force:!0})}catch{return}}try{We(xt(n),{recursive:!0});let o=hr(xt(n),t);return cs(o,n,"dir"),n}catch{return}}import{existsSync as Ct,mkdirSync as nn,readFileSync as ms,writeFileSync as _t}from"fs";import{dirname as br,join as Ce}from"path";var gs=`npx -y ${gt} sync --silent`;function $r(e){let t=Ce(e,k);nn(t,{recursive:!0});let n=Ce(t,".gitignore");_t(n,rr,"utf-8");let r=Ce(t,"content","images",".gitkeep");return nn(br(r),{recursive:!0}),Ct(r)||_t(r,"","utf-8"),n}var Sr=["PostToolUse","SessionStart"];function rn(e){if(!Ct(e))return{};try{let t=ms(e,"utf-8");return JSON.parse(t)}catch{return{}}}function on(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function kr(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(on)?!1:(r.hooks.push({type:"command",command:gs}),!0)}function me(e){let t=Ce(e,ht);nn(br(t),{recursive:!0});let n=rn(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=kr(r,a=>(a.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),i=n.hooks.SessionStart=n.hooks.SessionStart??[],s=kr(i,a=>(a.matcher??"")==="",()=>({hooks:[]}));return _t(t,JSON.stringify(n,null,2)+`
17
+ `,"utf-8"),{file:t,added:o||s}}function vr(e){let t=Ce(e,ht);if(!Ct(t))return!1;let n=rn(t).hooks;return n?Sr.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(on))}):!1}function xr(e){let t=Ce(e,ht);if(!Ct(t))return{file:t,removed:!1};let n=rn(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of Sr){let s=r[i];if(!Array.isArray(s))continue;for(let c of s){let u=c.hooks.length;c.hooks=c.hooks.filter(p=>!on(p)),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,_t(t,JSON.stringify(n,null,2)+`
18
+ `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as _r,mkdirSync as hs,readFileSync as ys,writeFileSync as ws}from"fs";import{join as ks}from"path";function Cr(e){return _r(ks(e,k,"project.md"))}function Er(){try{if(!_r(kt))return[];let e=JSON.parse(ys(kt,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function Ar(e){try{hs(M,{recursive:!0}),ws(kt,JSON.stringify({projects:e},null,2)+`
19
+ `,"utf-8")}catch{}}function ge(e){try{if(!Cr(e))return;let t=Er();if(t.includes(e))return;t.push(e),Ar(t)}catch{}}function Rr(){let e=Er(),t=e.filter(Cr);return t.length!==e.length&&Ar(t),t}import{readFileSync as vs,writeFileSync as xs,existsSync as _s}from"fs";import{join as Tr}from"path";function Pr(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=bs(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=$s(o):i==="writing instructions"?t.writingInstructions=Ir(o):i==="reference urls"?t.referenceUrls=Ss(o):i==="topics to avoid"?t.topicsToAvoid=Ir(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function Or(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
+ `)}function bs(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
- `)]),n}function ws(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 Er(e){let t=[],n=e.split(`
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 ks(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 Pr="context.md";function Or(e){let t=Ir(e,".seoagent",Pr);if(!Ss(t))return null;let n=bs(t,"utf-8");return Ar(n)}function vs(e,t){let n=Ir(e,".seoagent",Pr),r=Rr(t);$s(n,r,"utf-8")}function Tr(e,t){vs(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as We,readFileSync as jr,readdirSync as xs,statSync as Lr}from"fs";import{join as he}from"path";var _s=[{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 Cs(e){let t=he(e,"package.json");if(!We(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(jr(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Es(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 As(e){let t={};for(let n of Se){let r=he(e,n);if(We(r))try{let o=jr(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 Rs(e,t){let n=he(e,t.replace(/\/$/,""));if(!We(n))return!1;if(t.endsWith("/"))try{return Lr(n).isDirectory()}catch{return!1}return!0}function Is(e){let t=["content","_posts","posts",he("src","content")];for(let n of t){let r=he(e,n);if(We(r))try{if(!Lr(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of xs(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(he(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 Ps(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(We(he(e,n.marker)))return n.path;return null}function Nr(e){let t=[],{deps:n}=Cs(e),r=As(e),o="none";for(let s of _s){let a=[];for(let c of Object.keys(n))if(Es(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(Rs(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=Is(e);s&&(o="mdx-local",t.push(s))}let i=Ps(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as Os,readFileSync as Ts}from"fs";import{join as js}from"path";var Fr=["openai","fal","replicate"],Ee={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Ls(e){let t={};if(!Os(e))return t;let n=Ts(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 Dr(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 Se){let o=js(e,r),i=Ls(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 ie(e){let t=[].concat(...Fr.map(a=>Ee[a])),n=Dr(e,t),r=[];for(let a of Fr)Ee[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=Ee[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 Ur(e,t){let n=Dr(e,Ee[t]);for(let r of Ee[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Mr(){return Ee}import{existsSync as ye,readFileSync as ln}from"fs";import{join as we}from"path";function Br(e){try{return new URL(e).hostname}catch{return e}}function Gr(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 Ns(e){for(let t of Se){let n=we(e,t);if(!ye(n))continue;let r=ln(n,"utf-8");for(let o of Qn){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Br(s);if(Gr(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function Fs(e){let t=we(e,"package.json");if(!ye(t))return null;try{let n=JSON.parse(ln(t,"utf-8"));if(!n.homepage)return null;let r=Br(n.homepage);return Gr(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function Kr(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ye(we(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=Ns(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=Fs(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=we(e,"package.json"),s=null;if(ye(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(ln(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...p)=>p.some(d=>c.includes(d));if(u("@shopify/hydrogen","@shopify/polaris")||ye(we(e,"shopify.config.js"))||ye(we(e,"shopify.config.ts"))){s="product";let p=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ye(we(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:p})}else{let p=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),d=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),g=u("next");p&&(g||d)?(s="saas",n.push({field:"site_type",detail:"saas",source:g?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!p&&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 qs,readFileSync as fn,readdirSync as Hr,statSync as Hs}from"fs";import{join as q,sep as Ys}from"path";var Ds=new Set([502,503,504]),Us=1e4;async function K(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??Us,s=n.fetchImpl??fetch,a=n.sleep??Ms,c=n.transientStatuses??Ds,u=null;for(let p=0;p<r;p++){let{init:d,cleanup:g}=Bs(t,i);try{let m=await s(e,d);if(c.has(m.status)&&p<r-1){await a(Wr(o,p));continue}return m}catch(m){if(u=m,p<r-1){await a(Wr(o,p));continue}}finally{g()}}throw u instanceof Error?u:new Error(String(u))}function Wr(e,t){return e*Math.pow(3,t)}function Ms(e){return new Promise(t=>setTimeout(t,e))}function Bs(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}}var Gs=[/^\/admin(\/|$)/i,/^\/account(s)?(\/|$)/i,/^\/dashboard(\/|$)/i,/^\/settings(\/|$)/i,/^\/login(\/|$)/i,/^\/logout(\/|$)/i,/^\/sign[-_]?in(\/|$)/i,/^\/sign[-_]?up(\/|$)/i,/^\/register(\/|$)/i,/^\/reset[-_]?password(\/|$)/i,/^\/verify(\/|$)/i,/^\/api(\/|$)/i,/^\/_next(\/|$)/i,/^\/checkout(\/|$)/i,/^\/cart(\/|$)/i];function cn(e){let t=[],n=/<loc>\s*([^<\s][^<]*?)\s*<\/loc>/gi,r;for(;(r=n.exec(e))!==null;){let o=r[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#39;/g,"'").replace(/&quot;/g,'"').trim();o&&t.push(o)}return t}function ke(e){let t=e;try{t=new URL(e).pathname}catch{let n=t.indexOf("#");n!==-1&&(t=t.slice(0,n));let r=t.indexOf("?");r!==-1&&(t=t.slice(0,r))}return t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t||"/"}function At(e){return Gs.some(t=>t.test(e))}function Ks(e){return e.filter(t=>At(ke(t)))}function Ws(e,t){let n=new Set(e.map(ke)),r=[],o=new Set;for(let i of t){let s=ke(i);At(s)||n.has(s)||o.has(s)||(o.add(s),r.push(s))}return r}function un(e){return`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`}async function qr(e){let t=e.sitemapUrl||un(e.domain),n=[],r={ok:!1,sitemapUrl:t,fetched:!1,status:null,urls:[],privateUrls:[],missing:[],hasLastmod:!1,issues:n},o="";try{let i=await K(t,{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:2,timeoutMs:1e4,fetchImpl:e.fetchImpl});if(r.status=i.status,r.fetched=!0,!i.ok)return n.push({level:"error",message:`Sitemap returned HTTP ${i.status} \u2014 Google can't fetch it. Make sure ${t} serves 200.`}),r;o=await i.text()}catch(i){return n.push({level:"error",message:`Could not reach ${t} (${i instanceof Error?i.message:String(i)}). If the site isn't deployed yet, that's expected.`}),r}return/<urlset|<sitemapindex/i.test(o)?(r.urls=cn(o),r.hasLastmod=/<lastmod>/i.test(o),r.urls.length===0?(n.push({level:"error",message:"Sitemap is valid XML but contains zero <loc> URLs."}),r):(/<sitemapindex/i.test(o)&&n.push({level:"info",message:`Sitemap index with ${r.urls.length} child sitemap(s). Child URLs are not expanded by this check.`}),r.privateUrls=Ks(r.urls),r.privateUrls.length>0&&n.push({level:"warning",message:`${r.privateUrls.length} private/noindex URL(s) leaked into the sitemap (e.g. ${r.privateUrls.slice(0,3).map(ke).join(", ")}). Remove auth/admin/api routes from the generator.`}),r.hasLastmod||n.push({level:"info",message:"No <lastmod> dates \u2014 adding them helps crawlers prioritize changed pages."}),e.knownUrls&&e.knownUrls.length>0&&(r.missing=Ws(r.urls,e.knownUrls),r.missing.length>0&&n.push({level:"warning",message:`${r.missing.length} public page(s) in the repo are missing from the sitemap (e.g. ${r.missing.slice(0,3).join(", ")}). Add them to the generator so Google can find them.`})),r.ok=!n.some(i=>i.level==="error"),r)):(n.push({level:"error",message:`Response is not a valid XML sitemap (no <urlset>/<sitemapindex>). Got ${o.length} bytes.`}),r)}var Yr=["tsx","jsx","js","mdx","md"],zs=["astro","md","mdx"],Vs=5e3;function se(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=ea(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:la(t,c),in_sitemap:a,source:s})};for(let i of Xs(e))Js(i,o);return{pages:[...n.values()].filter(i=>!At(i.route)).sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}async function zr(e,t,n){let r=[];try{let s=await K(un(t),{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:1,timeoutMs:5e3,fetchImpl:n});if(!s.ok)return{checked:!1,liveCount:0,flipped:0};r=cn(await s.text())}catch{return{checked:!1,liveCount:0,flipped:0}}if(r.length===0)return{checked:!1,liveCount:0,flipped:0};let o=new Set(r.map(ke)),i=0;for(let s of e)!s.in_sitemap&&o.has(ke(s.url||s.route))&&(s.in_sitemap=!0,i++,s.source.includes("live-sitemap")||(s.source+=", live-sitemap"));return{checked:!0,liveCount:r.length,flipped:i}}function Js(e,t){for(let n of["app",q("src","app")]){let r=q(e,n);if(qe(r))for(let o of dn(r)){let i=pn(r,o),s=i[i.length-1];ia(s)&&(i.some(a=>a.startsWith("@"))||t(ta(i.slice(0,-1)),"app router"))}}for(let n of["pages",q("src","pages")]){let r=q(e,n);if(qe(r))for(let o of dn(r)){let i=pn(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=mn(s),c=Yr.includes(a),u=zs.includes(a);if(!c&&!u)continue;let p=Rt(s);sa(p)||t(na(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=q(e,n);if(qe(r))for(let o of dn(r,n==="."?1:1/0)){let i=pn(r,o),s=i[i.length-1];mn(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(ra(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=q(e,...n.split("/"));if(qs(r)){for(let o of aa(r)){let i=oa(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function Xs(e){let t=[e],n=new Set([e]);for(let r of Qs(e))for(let o of Zs(e,r))n.has(o)||(n.add(o),t.push(o));return t}function Qs(e){let t=[];try{let n=fn(q(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(fn(q(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 Zs(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=q(e,...n.split("/").filter(Boolean));return qe(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=q(e,...o.split("/").filter(Boolean));if(!qe(i))return[];let s=[];try{for(let a of Hr(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!Vr.has(a.name)&&(s.push(q(i,a.name)),s.length>=200))break}catch{}return s}function ea(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function ta(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function na(e){let t=[...e],n=Rt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function ra(e){let t=[...e],n=Rt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function oa(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function ia(e){return Rt(e)==="page"&&Yr.includes(mn(e))}function sa(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function aa(e){try{let t=fn(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 Vr=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function qe(e){try{return Hs(e).isDirectory()}catch{return!1}}function*dn(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=Hr(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=Vs)return;if(a.name.startsWith("."))continue;let c=q(o,a.name);if(a.isDirectory()){if(Vr.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function pn(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(Ys).filter(Boolean)}function mn(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Rt(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function la(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as ca,mkdirSync as ua,readFileSync as da,writeFileSync as pa}from"fs";import{join as Jr}from"path";function It(e,t){let n=Jr(e,k,"pages.md"),r=ca(n),o=r?ma(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 p=Qr(u.url),d=i.get(p);d?u.in_sitemap&&d.in_sitemap!=="yes"&&(d.in_sitemap="yes",a=!0):(i.set(p,{url:p,in_sitemap:u.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",notes:Qr(u.source)}),s++,a=!0)}if(r&&!a)return{wrote:!1,added:0,total:i.size,merged:!0};let c=[...i.values()];return ua(Jr(e,k),{recursive:!0}),pa(n,fa(c),"utf-8"),{wrote:!0,added:s,total:c.length,merged:r}}function fa(e){let t=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
23
+ `)]),n}function $s(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 Ir(e){let t=[],n=e.split(`
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 Ss(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 jr="context.md";function Lr(e){let t=Tr(e,".seoagent",jr);if(!_s(t))return null;let n=vs(t,"utf-8");return Pr(n)}function Cs(e,t){let n=Tr(e,".seoagent",jr),r=Or(t);xs(n,r,"utf-8")}function Nr(e,t){Cs(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as Ke,readFileSync as Fr,readdirSync as Es,statSync as Dr}from"fs";import{join as he}from"path";var As=[{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 Rs(e){let t=he(e,"package.json");if(!Ke(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Fr(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Is(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 Ps(e){let t={};for(let n of Se){let r=he(e,n);if(Ke(r))try{let o=Fr(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 Os(e,t){let n=he(e,t.replace(/\/$/,""));if(!Ke(n))return!1;if(t.endsWith("/"))try{return Dr(n).isDirectory()}catch{return!1}return!0}function Ts(e){let t=["content","_posts","posts",he("src","content")];for(let n of t){let r=he(e,n);if(Ke(r))try{if(!Dr(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(he(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 js(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(Ke(he(e,n.marker)))return n.path;return null}function Ur(e){let t=[],{deps:n}=Rs(e),r=Ps(e),o="none";for(let s of As){let a=[];for(let c of Object.keys(n))if(Is(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(Os(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=Ts(e);s&&(o="mdx-local",t.push(s))}let i=js(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as Ls,readFileSync as Ns}from"fs";import{join as Fs}from"path";var Mr=["openai","fal","replicate"],Ee={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Ds(e){let t={};if(!Ls(e))return t;let n=Ns(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 Br(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 Se){let o=Fs(e,r),i=Ds(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 ie(e){let t=[].concat(...Mr.map(a=>Ee[a])),n=Br(e,t),r=[];for(let a of Mr)Ee[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=Ee[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 Gr(e,t){let n=Br(e,Ee[t]);for(let r of Ee[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Wr(){return Ee}import{existsSync as ye,readFileSync as sn}from"fs";import{join as we}from"path";function Kr(e){try{return new URL(e).hostname}catch{return e}}function qr(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 Us(e){for(let t of Se){let n=we(e,t);if(!ye(n))continue;let r=sn(n,"utf-8");for(let o of Zn){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Kr(s);if(qr(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function Ms(e){let t=we(e,"package.json");if(!ye(t))return null;try{let n=JSON.parse(sn(t,"utf-8"));if(!n.homepage)return null;let r=Kr(n.homepage);return qr(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function Hr(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ye(we(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=Us(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=Ms(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=we(e,"package.json"),s=null;if(ye(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(sn(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...p)=>p.some(d=>c.includes(d));if(u("@shopify/hydrogen","@shopify/polaris")||ye(we(e,"shopify.config.js"))||ye(we(e,"shopify.config.ts"))){s="product";let p=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ye(we(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:p})}else{let p=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),d=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),g=u("next");p&&(g||d)?(s="saas",n.push({field:"site_type",detail:"saas",source:g?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!p&&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 Vs,readFileSync as dn,readdirSync as zr,statSync as zs}from"fs";import{join as q,sep as Js}from"path";var Bs=new Set([502,503,504]),Gs=1e4;async function W(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??Gs,s=n.fetchImpl??fetch,a=n.sleep??Ws,c=n.transientStatuses??Bs,u=null;for(let p=0;p<r;p++){let{init:d,cleanup:g}=Ks(t,i);try{let m=await s(e,d);if(c.has(m.status)&&p<r-1){await a(Yr(o,p));continue}return m}catch(m){if(u=m,p<r-1){await a(Yr(o,p));continue}}finally{g()}}throw u instanceof Error?u:new Error(String(u))}function Yr(e,t){return e*Math.pow(3,t)}function Ws(e){return new Promise(t=>setTimeout(t,e))}function Ks(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}}var qs=[/^\/admin(\/|$)/i,/^\/account(s)?(\/|$)/i,/^\/dashboard(\/|$)/i,/^\/settings(\/|$)/i,/^\/login(\/|$)/i,/^\/logout(\/|$)/i,/^\/sign[-_]?in(\/|$)/i,/^\/sign[-_]?up(\/|$)/i,/^\/register(\/|$)/i,/^\/reset[-_]?password(\/|$)/i,/^\/verify(\/|$)/i,/^\/api(\/|$)/i,/^\/_next(\/|$)/i,/^\/checkout(\/|$)/i,/^\/cart(\/|$)/i];function an(e){let t=[],n=/<loc>\s*([^<\s][^<]*?)\s*<\/loc>/gi,r;for(;(r=n.exec(e))!==null;){let o=r[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#39;/g,"'").replace(/&quot;/g,'"').trim();o&&t.push(o)}return t}function ke(e){let t=e;try{t=new URL(e).pathname}catch{let n=t.indexOf("#");n!==-1&&(t=t.slice(0,n));let r=t.indexOf("?");r!==-1&&(t=t.slice(0,r))}return t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t||"/"}function Et(e){return qs.some(t=>t.test(e))}function Hs(e){return e.filter(t=>Et(ke(t)))}function Ys(e,t){let n=new Set(e.map(ke)),r=[],o=new Set;for(let i of t){let s=ke(i);Et(s)||n.has(s)||o.has(s)||(o.add(s),r.push(s))}return r}function ln(e){return`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`}async function Vr(e){let t=e.sitemapUrl||ln(e.domain),n=[],r={ok:!1,sitemapUrl:t,fetched:!1,status:null,urls:[],privateUrls:[],missing:[],hasLastmod:!1,issues:n},o="";try{let i=await W(t,{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:2,timeoutMs:1e4,fetchImpl:e.fetchImpl});if(r.status=i.status,r.fetched=!0,!i.ok)return n.push({level:"error",message:`Sitemap returned HTTP ${i.status} \u2014 Google can't fetch it. Make sure ${t} serves 200.`}),r;o=await i.text()}catch(i){return n.push({level:"error",message:`Could not reach ${t} (${i instanceof Error?i.message:String(i)}). If the site isn't deployed yet, that's expected.`}),r}return/<urlset|<sitemapindex/i.test(o)?(r.urls=an(o),r.hasLastmod=/<lastmod>/i.test(o),r.urls.length===0?(n.push({level:"error",message:"Sitemap is valid XML but contains zero <loc> URLs."}),r):(/<sitemapindex/i.test(o)&&n.push({level:"info",message:`Sitemap index with ${r.urls.length} child sitemap(s). Child URLs are not expanded by this check.`}),r.privateUrls=Hs(r.urls),r.privateUrls.length>0&&n.push({level:"warning",message:`${r.privateUrls.length} private/noindex URL(s) leaked into the sitemap (e.g. ${r.privateUrls.slice(0,3).map(ke).join(", ")}). Remove auth/admin/api routes from the generator.`}),r.hasLastmod||n.push({level:"info",message:"No <lastmod> dates \u2014 adding them helps crawlers prioritize changed pages."}),e.knownUrls&&e.knownUrls.length>0&&(r.missing=Ys(r.urls,e.knownUrls),r.missing.length>0&&n.push({level:"warning",message:`${r.missing.length} public page(s) in the repo are missing from the sitemap (e.g. ${r.missing.slice(0,3).join(", ")}). Add them to the generator so Google can find them.`})),r.ok=!n.some(i=>i.level==="error"),r)):(n.push({level:"error",message:`Response is not a valid XML sitemap (no <urlset>/<sitemapindex>). Got ${o.length} bytes.`}),r)}var Jr=["tsx","jsx","js","mdx","md"],Xs=["astro","md","mdx"],Qs=5e3;function se(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=ra(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:da(t,c),in_sitemap:a,source:s})};for(let i of ea(e))Zs(i,o);return{pages:[...n.values()].filter(i=>!Et(i.route)).sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}async function Xr(e,t,n){let r=[];try{let s=await W(ln(t),{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:1,timeoutMs:5e3,fetchImpl:n});if(!s.ok)return{checked:!1,liveCount:0,flipped:0};r=an(await s.text())}catch{return{checked:!1,liveCount:0,flipped:0}}if(r.length===0)return{checked:!1,liveCount:0,flipped:0};let o=new Set(r.map(ke)),i=0;for(let s of e)!s.in_sitemap&&o.has(ke(s.url||s.route))&&(s.in_sitemap=!0,i++,s.source.includes("live-sitemap")||(s.source+=", live-sitemap"));return{checked:!0,liveCount:r.length,flipped:i}}function Zs(e,t){for(let n of["app",q("src","app")]){let r=q(e,n);if(qe(r))for(let o of cn(r)){let i=un(r,o),s=i[i.length-1];la(s)&&(i.some(a=>a.startsWith("@"))||t(oa(i.slice(0,-1)),"app router"))}}for(let n of["pages",q("src","pages")]){let r=q(e,n);if(qe(r))for(let o of cn(r)){let i=un(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=pn(s),c=Jr.includes(a),u=Xs.includes(a);if(!c&&!u)continue;let p=At(s);ca(p)||t(ia(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=q(e,n);if(qe(r))for(let o of cn(r,n==="."?1:1/0)){let i=un(r,o),s=i[i.length-1];pn(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(sa(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=q(e,...n.split("/"));if(Vs(r)){for(let o of ua(r)){let i=aa(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function ea(e){let t=[e],n=new Set([e]);for(let r of ta(e))for(let o of na(e,r))n.has(o)||(n.add(o),t.push(o));return t}function ta(e){let t=[];try{let n=dn(q(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(dn(q(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 na(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=q(e,...n.split("/").filter(Boolean));return qe(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=q(e,...o.split("/").filter(Boolean));if(!qe(i))return[];let s=[];try{for(let a of zr(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!Qr.has(a.name)&&(s.push(q(i,a.name)),s.length>=200))break}catch{}return s}function ra(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function oa(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function ia(e){let t=[...e],n=At(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function sa(e){let t=[...e],n=At(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function aa(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function la(e){return At(e)==="page"&&Jr.includes(pn(e))}function ca(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function ua(e){try{let t=dn(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 Qr=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function qe(e){try{return zs(e).isDirectory()}catch{return!1}}function*cn(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=zr(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=Qs)return;if(a.name.startsWith("."))continue;let c=q(o,a.name);if(a.isDirectory()){if(Qr.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function un(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(Js).filter(Boolean)}function pn(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function At(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function da(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as pa,mkdirSync as fa,readFileSync as ma,writeFileSync as ga}from"fs";import{join as Zr}from"path";function Rt(e,t){let n=Zr(e,k,"pages.md"),r=pa(n),o=r?ya(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 p=to(u.url),d=i.get(p);d?u.in_sitemap&&d.in_sitemap!=="yes"&&(d.in_sitemap="yes",a=!0):(i.set(p,{url:p,in_sitemap:u.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",notes:to(u.source)}),s++,a=!0)}if(r&&!a)return{wrote:!1,added:0,total:i.size,merged:!0};let c=[...i.values()];return fa(Zr(e,k),{recursive:!0}),ga(n,ha(c),"utf-8"),{wrote:!0,added:s,total:c.length,merged:r}}function ha(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 ma(e){let t=new Map,n;try{n=da(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!gn(r[o])||!ga(r[o+1]))continue;let i=Xr(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&&gn(r[a]);a++){let c=Xr(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:He(c,s.in_sitemap),in_nav:He(c,s.in_nav),status:He(c,s.status),rendered:He(c,s.rendered),notes:He(c,s.notes)})}break}return t}function He(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function gn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function ga(e){let t=e.trim();return gn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function Xr(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function Qr(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as Ae}from"@clack/prompts";var l={info:e=>Ae.info(e),warn:e=>Ae.warn(e),error:e=>Ae.error(e),success:e=>Ae.success(e),step:e=>Ae.step(e),message:e=>Ae.message(e)};function w(e,t,n,r=n){e?e.stop(r):l[t](n)}var eo=[{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"}],ro="unknown",ba=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function $a(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 Pt(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return ba.has(t)?t:null}async function Ye(e={}){let t=process.cwd();if(ar(t)){let a=_(t),c=_e(t);me(t),z(t,{skill_version:E}),ge(t);let u=no(Ot(t,c.skillFile)),p=c.claudeSymlink?` (symlinked at ${Ot(t,c.claudeSymlink)})`:"",d=a?.skill_version&&a.skill_version!==E?`${a.skill_version} \u2192 ${E}`:E;l.success(`Refreshed the SEOAgent skill (${d}).`),l.info("Your `.seoagent/` knowledge was left untouched."),l.info(`Skill at ${u}${p}.`),l.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`);return}let n=!!e.yes||!process.stdin.isTTY;n||ha("SEOAgent \u2014 AI SEO Agent");let r=Kr(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 ${$a(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=Pt(e.siteType)||Pt(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&Pt(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()&&Pt(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=ro),s||(s="unknown"),await to(t,i,s);return}if(o(),!i){let a=await Zr({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});Re(a)&&(Ie("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await hn({message:"What kind of site is this?",options:[...eo]});Re(a)&&(Ie("Cancelled"),process.exit(0)),s=a}for(;;){let a=await ka({message:`Create .seoagent for ${i} (${s})?`});if(Re(a)&&(Ie("Cancelled"),process.exit(0)),a)break;let c=await hn({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((Re(c)||c==="abort")&&(Ie("Cancelled"),process.exit(0)),c==="domain"){let u=await Zr({message:"Website domain",placeholder:"example.com",validate:p=>p.trim()?void 0:"Domain is required"});Re(u)&&(Ie("Cancelled"),process.exit(0)),i=String(u)}else{let u=await hn({message:"What kind of site is this?",options:[...eo]});Re(u)&&(Ie("Cancelled"),process.exit(0)),s=u}}await to(t,i,s)}async function to(e,t,n){let r=wa();r.start("Setting up your SEO project");let o=Nr(e),i=ie(e),s={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:E,skill_version:E,install_id:rn(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{},...i.provider!=="none"?{image_provider:i.provider}:{}};ur(e),cr(e,s),ge(e),Tr(e,n),wr(e);let a=_e(e),c=Ot(e,a.skillFile),u=no(c),p=`${u}/references/audit-checks.md`,d=a.claudeSymlink?Ot(e,a.claudeSymlink):void 0;me(e);let g=t!==ro,m={pages:[],dynamicCount:0},v={wrote:!1,added:0,total:0,merged:!1};try{m=se(e,g?t:null),v=It(e,m.pages)}catch{}if(r.stop(g?`Created .seoagent/ project for ${s.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let x=o.evidence.map(F=>`${F.detail} (${F.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${x}`)}if(o.blog_path&&l.info(`Blog route: ${o.blog_path}`),i.provider!=="none"&&l.info(`Image generation: ${i.provider} (detected ${i.matched_key}) \u2014 articles can get AI hero images.`),m.pages.length>0){let x=v.merged?v.added>0?`Re-scanned your codebase: +${v.added} new page${v.added===1?"":"s"} merged into .seoagent/pages.md (${v.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${v.total} pages)`:`Found ${m.pages.length} page${m.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;l.info(x+(m.dynamicCount>0?` (plus ${m.dynamicCount} dynamic route template${m.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let $=g?s.domain:"your site",T=g?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${s.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."];ya([g?`\u2713 SEOAgent installed for ${s.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:","",` ${c} \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):","",...T,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${$}`," (homepage + sitemap + robots.txt; the checks live in",` ${p} \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 ${c} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${u} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
30
- `))}import{existsSync as so}from"fs";import{intro as va,outro as xa,confirm as _a,isCancel as Ca,cancel as Ea}from"@clack/prompts";import{existsSync as Tt,rmSync as Sa}from"fs";import{join as jt}from"path";function oo(e,t={}){let n=[],r=jt(e,k);Tt(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=jt(e,fe.CLAUDE);Tt(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=jt(e,fe.AGENTS);return Tt(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),br(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:jt(e,".claude","settings.json"),kind:"hook"}),t.global&&Tt(M)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:M,kind:"global"}),n}function io(e,t){for(let n of t)n.kind==="hook"?$r(e):Sa(n.path,{recursive:!0,force:!0})}async function ze(e={}){let t=process.cwd(),n=oo(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&so(M)&&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
- `);if(!r){va("SEOAgent \u2014 uninstall"),l.message(`This will remove:
32
- ${o}`);let s=await _a({message:"Remove these and start fresh?"});if(Ca(s)||!s){Ea("Cancelled \u2014 nothing was removed.");return}}io(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
29
+ `)}function ya(e){let t=new Map,n;try{n=ma(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!fn(r[o])||!wa(r[o+1]))continue;let i=eo(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&&fn(r[a]);a++){let c=eo(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:He(c,s.in_sitemap),in_nav:He(c,s.in_nav),status:He(c,s.status),rendered:He(c,s.rendered),notes:He(c,s.notes)})}break}return t}function He(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function fn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function wa(e){let t=e.trim();return fn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function eo(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function to(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as Ae}from"@clack/prompts";var l={info:e=>Ae.info(e),warn:e=>Ae.warn(e),error:e=>Ae.error(e),success:e=>Ae.success(e),step:e=>Ae.step(e),message:e=>Ae.message(e)};function w(e,t,n,r=n){e?e.stop(r):l[t](n)}var ro=[{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"}],so="unknown",va=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function xa(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 It(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return va.has(t)?t:null}async function Ye(e={}){let t=process.cwd();if(ur(t)){let a=_(t),c=_e(t);me(t),V(t,{skill_version:E}),ge(t);let u=io(Pt(t,c.skillFile)),p=c.claudeSymlink?` (symlinked at ${Pt(t,c.claudeSymlink)})`:"",d=a?.skill_version&&a.skill_version!==E?`${a.skill_version} \u2192 ${E}`:E;l.success(`Refreshed the SEOAgent skill (${d}).`),l.info("Your `.seoagent/` knowledge was left untouched."),l.info(`Skill at ${u}${p}.`),l.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`);return}let n=!!e.yes||!process.stdin.isTTY;n||ka("SEOAgent \u2014 AI SEO Agent");let r=Hr(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 ${xa(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=It(e.siteType)||It(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&It(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()&&It(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=so),s||(s="unknown"),await oo(t,i,s);return}if(o(),!i){let a=await no({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});Re(a)&&(Ie("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await mn({message:"What kind of site is this?",options:[...ro]});Re(a)&&(Ie("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Sa({message:`Create .seoagent for ${i} (${s})?`});if(Re(a)&&(Ie("Cancelled"),process.exit(0)),a)break;let c=await mn({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((Re(c)||c==="abort")&&(Ie("Cancelled"),process.exit(0)),c==="domain"){let u=await no({message:"Website domain",placeholder:"example.com",validate:p=>p.trim()?void 0:"Domain is required"});Re(u)&&(Ie("Cancelled"),process.exit(0)),i=String(u)}else{let u=await mn({message:"What kind of site is this?",options:[...ro]});Re(u)&&(Ie("Cancelled"),process.exit(0)),s=u}}await oo(t,i,s)}async function oo(e,t,n){let r=$a();r.start("Setting up your SEO project");let o=Ur(e),i=ie(e),s={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:E,skill_version:E,install_id:tn(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{},...i.provider!=="none"?{image_provider:i.provider}:{}};fr(e),pr(e,s),ge(e),Nr(e,n),$r(e);let a=_e(e),c=Pt(e,a.skillFile),u=io(c),p=`${u}/references/audit-checks.md`,d=a.claudeSymlink?Pt(e,a.claudeSymlink):void 0;me(e);let g=t!==so,m={pages:[],dynamicCount:0},v={wrote:!1,added:0,total:0,merged:!1};try{m=se(e,g?t:null),v=Rt(e,m.pages)}catch{}if(r.stop(g?`Created .seoagent/ project for ${s.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let x=o.evidence.map(F=>`${F.detail} (${F.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${x}`)}if(o.blog_path&&l.info(`Blog route: ${o.blog_path}`),i.provider!=="none"&&l.info(`Image generation: ${i.provider} (detected ${i.matched_key}) \u2014 articles can get AI hero images.`),m.pages.length>0){let x=v.merged?v.added>0?`Re-scanned your codebase: +${v.added} new page${v.added===1?"":"s"} merged into .seoagent/pages.md (${v.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${v.total} pages)`:`Found ${m.pages.length} page${m.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;l.info(x+(m.dynamicCount>0?` (plus ${m.dynamicCount} dynamic route template${m.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let $=g?s.domain:"your site",T=g?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${s.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."];ba([g?`\u2713 SEOAgent installed for ${s.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:","",` ${c} \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):","",...T,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${$}`," (homepage + sitemap + robots.txt; the checks live in",` ${p} \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 ${c} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${u} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
30
+ `))}import{existsSync as co}from"fs";import{intro as Ca,outro as Ea,confirm as Aa,isCancel as Ra,cancel as Ia}from"@clack/prompts";import{existsSync as Ot,rmSync as _a}from"fs";import{join as Tt}from"path";function ao(e,t={}){let n=[],r=Tt(e,k);Ot(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=Tt(e,fe.CLAUDE);Ot(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=Tt(e,fe.AGENTS);return Ot(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),vr(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:Tt(e,".claude","settings.json"),kind:"hook"}),t.global&&Ot(M)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:M,kind:"global"}),n}function lo(e,t){for(let n of t)n.kind==="hook"?xr(e):_a(n.path,{recursive:!0,force:!0})}async function Ve(e={}){let t=process.cwd(),n=ao(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&co(M)&&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
+ `);if(!r){Ca("SEOAgent \u2014 uninstall"),l.message(`This will remove:
32
+ ${o}`);let s=await Aa({message:"Remove these and start fresh?"});if(Ra(s)||!s){Ia("Cancelled \u2014 nothing was removed.");return}}lo(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
33
33
  `);r?l.success(`Removed:
34
- ${i}`):xa(`Removed:
35
- ${i}`),!e.global&&so(M)&&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 S from"picocolors";import{existsSync as lo,mkdirSync as ao,readFileSync as Aa,writeFileSync as Ra,chmodSync as Ia,unlinkSync as Pa}from"fs";import{dirname as Oa}from"path";function j(){if(!lo(oe))return null;try{let e=JSON.parse(Aa(oe,"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||Me}}catch{return null}}function co(e){ao(M,{recursive:!0}),ao(Oa(oe),{recursive:!0}),Ra(oe,JSON.stringify(e,null,2)+`
36
- `,"utf-8");try{Ia(oe,384)}catch{}}function uo(){if(!lo(oe))return!1;try{return Pa(oe),!0}catch{return!1}}import{existsSync as Ve,readdirSync as yn,statSync as Ta,readFileSync as po}from"fs";import{join as Pe}from"path";function ja(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function La(e){let t=Pe(e,"audit","latest.md");if(!Ve(t))return null;let n=St(t);if(!n)return null;let r=po(t,"utf-8"),o=ja(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function Na(e){try{let n=po(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 Fa(e){let t=Pe(e,"strategy","clusters");if(!Ve(t))return null;let n=yn(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=Na(Pe(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function Da(e){let t=Pe(e,"briefs");if(!Ve(t))return null;let n=yn(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Ua(e){let t=Pe(e,"content");if(!Ve(t))return null;let n=yn(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function Ma(e){let t=Pe(e,"roadmap.md");return Ve(t)?{exists:!0,updatedAt:Ta(t).mtime.toISOString()}:null}function fo(e){let t=_(e);if(!t)return null;let n=Ge(e);return{domain:t.domain,audit:La(n),strategy:Fa(n),briefs:Da(n),content:Ua(n),roadmap:Ma(n)}}import ae from"picocolors";var Ba=/\x1b\[[0-9;]*m/g;function mo(e){return e.replace(Ba,"").length}function I(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=Ga(n,t.title),s=ae.dim(`\u251C${o}\u2524`),a=ae.dim(`\u2514${o}\u2518`),c=[i];for(let u of e){if("sep"in u){c.push(s);continue}c.push(Ka(u.content,r))}return c.push(a),c.join(`
37
- `)}function Ga(e,t){if(!t)return ae.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=mo(t),r=e-5-n;return r<1?ae.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${ae.dim("\u250C\u2500 ")}${t}${ae.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function Ka(e,t){let n=mo(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${ae.dim("\u2502")} ${r} ${ae.dim("\u2502")}`}function wn(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 Je(){let e=fo(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(Wa(e))}function Wa(e){if(!e)return"";let t=11,n=s=>S.dim(s.padEnd(t)),r=[];j()?(r.push({content:`${S.green("\u2713")} ${S.dim("Logged in")}`}),r.push({content:S.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${S.dim("\u25CB Not logged in")}`}),r.push({content:S.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${S.green(`last run ${wn(e.audit.date??"")}`)} ${S.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${S.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${S.bold(S.cyan(String(e.strategy.clusterCount??0)))} ${S.dim("clusters")} \xB7 ${S.bold(S.cyan(String(e.strategy.articleCount??0)))} ${S.dim("ideas")}`:`${n("Strategy:")}${S.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${S.bold(S.cyan(String(e.briefs.count??0)))} ${S.dim("ready")}`:`${n("Briefs:")}${S.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${S.green("\u2713")} ${S.bold(S.cyan(String(e.content.count??0)))} ${S.dim("articles written")}`:`${n("Content:")}${S.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${S.green("updated")} ${S.dim(wn(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${S.dim("not yet created")}`});let i=`${S.bold(S.cyan("SEOAgent"))} ${S.dim("\xB7")} ${S.bold(e.domain)}`;return I(r,{width:78,title:i})}import{exec as qa,spawn as go}from"child_process";import{confirm as Ha,isCancel as Ya}from"@clack/prompts";import U from"picocolors";function Oe(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 za=`https://registry.npmjs.org/${ee}/latest`,Xe=["free","starter","pro","scale","enterprise"],Lt={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function Va(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return Xe.includes(t)?t:null}function Ja(e){let t=Xe.indexOf(e);return t===-1||t===Xe.length-1?null:Xe[t+1]}async function Xa(e,t=fetch){if(!e)return null;try{let n=(e.api_base||A.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 Qa(e){let t=[],r=s=>U.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${U.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${U.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of Xe){let a=Lt[s];s===e.current?t.push({content:`${U.bold(U.green("\u25CF"))} ${U.bold(U.green(a.padEnd(11)))} ${U.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${U.yellow("\u25C6")} ${U.bold(U.yellow(a.padEnd(11)))} ${U.yellow("next tier")}`}):t.push({content:U.dim(` ${a}`)})}let i=`${U.bold(U.cyan("SEOAgent Cloud"))} ${U.dim("\xB7")} ${U.dim("your plan")}`;return I(t,{width:55,title:i})}async function Qe(){let e=j(),t=!!process.stdin.isTTY;if(e&&t){let n=await Xa(e);if(n){let r=Va(n.plan),o=r?Ja(r):null;if(r&&l.message(Qa({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${Lt[r]} (highest tier).`);return}if(r&&o){let i=await Ha({message:`Upgrade from ${Lt[r]} to ${Lt[o]}?`});if(Ya(i)||!i){l.info("No changes.");return}}}}Za()}function Za(){let e=el();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}"`;qa(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function el(){let e=process.cwd(),t=_(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${A.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ze(e={}){let t=E,n=await nl();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 ${ee}@latest`);return}if(Oe(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!en()){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 ${ee}@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 ${ee}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${ee}@latest`);return}if(l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await rl()){l.error(`Update failed. Try manually: npm install -g ${ee}@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 tl()||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 tl(){return new Promise(e=>{try{let t=go("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function nl(e=fetch){try{let t=await e(za,{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 rl(){return new Promise(e=>{let t=go("npm",["install","-g",`${ee}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as ol}from"child_process";import{randomBytes as il}from"crypto";import{isCancel as sl,spinner as al,text as ll}from"@clack/prompts";import le from"picocolors";function ho(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 cl=1500,ul=300*1e3;function dl(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;ol(t,()=>{})}function pl(){return il(16).toString("hex")}function fl(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function yo(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 ml(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 ho(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function gl(e){return new Promise(t=>setTimeout(t,e))}async function et(e={}){let t=process.cwd(),n=_(t),r=(e.apiBase||A.BASE||Me).replace(/\/$/,"");if(j()){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 d=await ll({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(!yo(String(m)))return"Please enter a valid domain like `example.com`."}});if(sl(d)){l.warn("Login cancelled.");return}let g=yo(String(d));if(g){o=g;try{z(t,{domain:g}),l.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=pl(),s=fl(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}`),dl(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?al():null;c?.start(le.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+ul,p=!0;for(;Date.now()<u;){p||await gl(cl),p=!1;let d=await ml(r,i);if(d.status==="ready"){co({user_token:d.user_token,website_token:d.website_token,api_base:r});let g=d.email&&d.domain?`Logged in as ${d.email} (${d.domain}). Future SEO work in this repo will sync to your dashboard.`:d.email?`Logged in as ${d.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=d.email&&d.domain?`Logged in as ${le.bold(d.email)} (${le.cyan(d.domain)}).`:d.email?`Logged in as ${le.bold(d.email)}.`:"Logged in.";w(c,"success",g,le.green(m)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(d.status==="expired"){w(c,"warn",`Session expired. Run \`${f("login")}\` again.`,le.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(d.status==="error"){if(d.terminal){w(c,"warn",`Login failed: ${d.message}. Run \`${f("login")}\` again.`,le.red(`Login failed: ${d.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}w(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,le.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function tt(){uo()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as jc}from"@clack/prompts";import ce from"picocolors";import{existsSync as _n,mkdirSync as rc,readFileSync as Mo,readdirSync as oc,statSync as ic,writeFileSync as sc}from"fs";import{join as Cn,relative as ac,sep as lc}from"path";import{existsSync as bn,mkdirSync as hl,readdirSync as wo,readFileSync as yl,unlinkSync as wl,writeFileSync as kn}from"fs";import{join as je}from"path";import O from"picocolors";function te(e){return je(e,k,"inbox")}function ko(e){return`${e.action_type}-${e.id}.md`}function kl(e,t){let n=0;if(!bn(e))return 0;for(let r of wo(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{wl(je(e,r)),n++}catch{}}return n}function bl(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`---
34
+ ${i}`):Ea(`Removed:
35
+ ${i}`),!e.global&&co(M)&&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 S from"picocolors";import{existsSync as po,mkdirSync as uo,readFileSync as Pa,writeFileSync as Oa,chmodSync as Ta,unlinkSync as ja}from"fs";import{dirname as La}from"path";function j(){if(!po(oe))return null;try{let e=JSON.parse(Pa(oe,"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||Me}}catch{return null}}function fo(e){uo(M,{recursive:!0}),uo(La(oe),{recursive:!0}),Oa(oe,JSON.stringify(e,null,2)+`
36
+ `,"utf-8");try{Ta(oe,384)}catch{}}function mo(){if(!po(oe))return!1;try{return ja(oe),!0}catch{return!1}}import{existsSync as ze,readdirSync as gn,statSync as Na,readFileSync as go}from"fs";import{join as Pe}from"path";function Fa(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function Da(e){let t=Pe(e,"audit","latest.md");if(!ze(t))return null;let n=$t(t);if(!n)return null;let r=go(t,"utf-8"),o=Fa(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function Ua(e){try{let n=go(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 Ma(e){let t=Pe(e,"strategy","clusters");if(!ze(t))return null;let n=gn(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=Ua(Pe(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function Ba(e){let t=Pe(e,"briefs");if(!ze(t))return null;let n=gn(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Ga(e){let t=Pe(e,"content");if(!ze(t))return null;let n=gn(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function Wa(e){let t=Pe(e,"roadmap.md");return ze(t)?{exists:!0,updatedAt:Na(t).mtime.toISOString()}:null}function ho(e){let t=_(e);if(!t)return null;let n=Ge(e);return{domain:t.domain,audit:Da(n),strategy:Ma(n),briefs:Ba(n),content:Ga(n),roadmap:Wa(n)}}import ae from"picocolors";var Ka=/\x1b\[[0-9;]*m/g;function yo(e){return e.replace(Ka,"").length}function I(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=qa(n,t.title),s=ae.dim(`\u251C${o}\u2524`),a=ae.dim(`\u2514${o}\u2518`),c=[i];for(let u of e){if("sep"in u){c.push(s);continue}c.push(Ha(u.content,r))}return c.push(a),c.join(`
37
+ `)}function qa(e,t){if(!t)return ae.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=yo(t),r=e-5-n;return r<1?ae.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${ae.dim("\u250C\u2500 ")}${t}${ae.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function Ha(e,t){let n=yo(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${ae.dim("\u2502")} ${r} ${ae.dim("\u2502")}`}function hn(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 Je(){let e=ho(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(Ya(e))}function Ya(e){if(!e)return"";let t=11,n=s=>S.dim(s.padEnd(t)),r=[];j()?(r.push({content:`${S.green("\u2713")} ${S.dim("Logged in")}`}),r.push({content:S.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${S.dim("\u25CB Not logged in")}`}),r.push({content:S.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${S.green(`last run ${hn(e.audit.date??"")}`)} ${S.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${S.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${S.bold(S.cyan(String(e.strategy.clusterCount??0)))} ${S.dim("clusters")} \xB7 ${S.bold(S.cyan(String(e.strategy.articleCount??0)))} ${S.dim("ideas")}`:`${n("Strategy:")}${S.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${S.bold(S.cyan(String(e.briefs.count??0)))} ${S.dim("ready")}`:`${n("Briefs:")}${S.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${S.green("\u2713")} ${S.bold(S.cyan(String(e.content.count??0)))} ${S.dim("articles written")}`:`${n("Content:")}${S.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${S.green("updated")} ${S.dim(hn(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${S.dim("not yet created")}`});let i=`${S.bold(S.cyan("SEOAgent"))} ${S.dim("\xB7")} ${S.bold(e.domain)}`;return I(r,{width:78,title:i})}import{exec as Va,spawn as wo}from"child_process";import{confirm as za,isCancel as Ja}from"@clack/prompts";import D from"picocolors";function Oe(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 Xa=`https://registry.npmjs.org/${ee}/latest`,Xe=["free","starter","pro","scale","enterprise"],jt={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function Qa(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return Xe.includes(t)?t:null}function Za(e){let t=Xe.indexOf(e);return t===-1||t===Xe.length-1?null:Xe[t+1]}async function el(e,t=fetch){if(!e)return null;try{let n=(e.api_base||A.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 tl(e){let t=[],r=s=>D.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${D.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${D.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of Xe){let a=jt[s];s===e.current?t.push({content:`${D.bold(D.green("\u25CF"))} ${D.bold(D.green(a.padEnd(11)))} ${D.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${D.yellow("\u25C6")} ${D.bold(D.yellow(a.padEnd(11)))} ${D.yellow("next tier")}`}):t.push({content:D.dim(` ${a}`)})}let i=`${D.bold(D.cyan("SEOAgent Cloud"))} ${D.dim("\xB7")} ${D.dim("your plan")}`;return I(t,{width:55,title:i})}async function Qe(){let e=j(),t=!!process.stdin.isTTY;if(e&&t){let n=await el(e);if(n){let r=Qa(n.plan),o=r?Za(r):null;if(r&&l.message(tl({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${jt[r]} (highest tier).`);return}if(r&&o){let i=await za({message:`Upgrade from ${jt[r]} to ${jt[o]}?`});if(Ja(i)||!i){l.info("No changes.");return}}}}nl()}function nl(){let e=rl();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}"`;Va(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function rl(){let e=process.cwd(),t=_(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${A.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ze(e={}){let t=E,n=await il();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 ${ee}@latest`);return}if(Oe(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!Qt()){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 ${ee}@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 ${ee}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${ee}@latest`);return}if(l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await sl()){l.error(`Update failed. Try manually: npm install -g ${ee}@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 ol()||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 ol(){return new Promise(e=>{try{let t=wo("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function il(e=fetch){try{let t=await e(Xa,{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 sl(){return new Promise(e=>{let t=wo("npm",["install","-g",`${ee}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as al}from"child_process";import{randomBytes as ll}from"crypto";import{isCancel as cl,spinner as ul,text as dl}from"@clack/prompts";import le from"picocolors";function ko(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 pl=1500,fl=300*1e3;function ml(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;al(t,()=>{})}function gl(){return ll(16).toString("hex")}function hl(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function bo(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 yl(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 ko(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function wl(e){return new Promise(t=>setTimeout(t,e))}async function et(e={}){let t=process.cwd(),n=_(t),r=(e.apiBase||A.BASE||Me).replace(/\/$/,"");if(j()){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 d=await dl({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(!bo(String(m)))return"Please enter a valid domain like `example.com`."}});if(cl(d)){l.warn("Login cancelled.");return}let g=bo(String(d));if(g){o=g;try{V(t,{domain:g}),l.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=gl(),s=hl(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}`),ml(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?ul():null;c?.start(le.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+fl,p=!0;for(;Date.now()<u;){p||await wl(pl),p=!1;let d=await yl(r,i);if(d.status==="ready"){fo({user_token:d.user_token,website_token:d.website_token,api_base:r});let g=d.email&&d.domain?`Logged in as ${d.email} (${d.domain}). Future SEO work in this repo will sync to your dashboard.`:d.email?`Logged in as ${d.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=d.email&&d.domain?`Logged in as ${le.bold(d.email)} (${le.cyan(d.domain)}).`:d.email?`Logged in as ${le.bold(d.email)}.`:"Logged in.";w(c,"success",g,le.green(m)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(d.status==="expired"){w(c,"warn",`Session expired. Run \`${f("login")}\` again.`,le.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(d.status==="error"){if(d.terminal){w(c,"warn",`Login failed: ${d.message}. Run \`${f("login")}\` again.`,le.red(`Login failed: ${d.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}w(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,le.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function tt(){mo()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as Dc}from"@clack/prompts";import ce from"picocolors";import{existsSync as vn,mkdirSync as sc,readFileSync as Wo,readdirSync as ac,writeFileSync as lc}from"fs";import{createHash as cc}from"crypto";import{join as xn,relative as uc,sep as dc}from"path";import{existsSync as wn,mkdirSync as kl,readdirSync as $o,readFileSync as bl,unlinkSync as $l,writeFileSync as yn}from"fs";import{join as je}from"path";import O from"picocolors";function te(e){return je(e,k,"inbox")}function So(e){return`${e.action_type}-${e.id}.md`}function Sl(e,t){let n=0;if(!wn(e))return 0;for(let r of $o(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{$l(je(e,r)),n++}catch{}}return n}function vl(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}
@@ -77,8 +77,8 @@ positive, you disagree, etc.), close it out as failed with a reason:
77
77
  \`\`\`bash
78
78
  ${f(`ack ${e.id}`)} --failed --reason "kept; performs well off-search"
79
79
  \`\`\`
80
- `}function $l(e){switch(e){case"meta":return"Apply the **meta** fix \u2014 set the page's `<title>` / `<meta name=\"description\">` (or the framework's metadata API / frontmatter).";case"schema":return"Apply the **schema** fix \u2014 add or correct the JSON-LD structured data on the page.";case"canonical":return'Apply the **canonical** fix \u2014 set the correct `<link rel="canonical">` on the page.';case"internal_link":return"Apply the **internal_link** fix \u2014 add relevant internal links from related pages (look for high-authority pages on the same topic).";default:return["Apply the change for this issue:",' - **meta** \u2014 fix the `<title>` / `<meta name="description">` (or the framework\'s metadata API / frontmatter).'," - **schema** \u2014 add or correct JSON-LD structured data.",' - **canonical** \u2014 set the correct `<link rel="canonical">`.'," - **internal_link** \u2014 add relevant internal links (fix orphan/low-link pages)."," - **other** \u2014 follow the recommendation above."].join(`
81
- `)}}function Sl(e,t,n){if(n)return`Locate the page's source. It renders at \`${n}\` \u2014 find the matching route/template/markdown in this repo (look under \`app/\`, \`pages/\`, \`src/\`, \`content/\`).`;let r=(t||"").toLowerCase();return r.includes("robots")||r.includes("ai_bot")||r.includes("bot_policy")?"This is a site-wide policy issue. Edit `robots.txt` at the site root (or its generator \u2014 `app/robots.ts`, `public/robots.txt`, etc.) to add the appropriate `User-agent:` / `Allow:` / `Disallow:` rules.":r.includes("sitemap")?"This is a sitemap configuration issue. Edit your sitemap generator \u2014 `app/sitemap.ts`, `pages/sitemap.xml.ts`, `next-sitemap.config.js`, or the static `public/sitemap.xml`.":e==="canonical"?'This is a site-wide canonical pattern. Look in the layout/template that wraps your pages (e.g. `app/layout.tsx`, `_app.tsx`, theme `head` partial) \u2014 that\'s where the `<link rel="canonical">` is set for every page.':e==="schema"?"This is a site-wide schema gap. Apply JSON-LD to the layout/template (for Organization-level schema) or to specific page templates (for Article / Product / FAQPage etc.).":e==="meta"?"This is a site-wide metadata convention. Look at the page-template metadata \u2014 Next.js `generateMetadata()` / `metadata` export, Nuxt `useHead()`, Astro frontmatter, etc.":e==="internal_link"?"No specific page on file. Identify pages on the same topic/cluster from `.seoagent/strategy/clusters/` and add inbound links to the target page.":"This issue does not name a single page. Read the recommendation above, identify the relevant template/config in this repo, and apply the change there."}function vl(e){let t=e.payload||{},n=t.page_url??null,r=t.issue??"other",o=t.check_id??"unknown",i=t.severity??"unknown",s=t.recommended_fix??null;return`---
80
+ `}function xl(e){switch(e){case"meta":return"Apply the **meta** fix \u2014 set the page's `<title>` / `<meta name=\"description\">` (or the framework's metadata API / frontmatter).";case"schema":return"Apply the **schema** fix \u2014 add or correct the JSON-LD structured data on the page.";case"canonical":return'Apply the **canonical** fix \u2014 set the correct `<link rel="canonical">` on the page.';case"internal_link":return"Apply the **internal_link** fix \u2014 add relevant internal links from related pages (look for high-authority pages on the same topic).";default:return["Apply the change for this issue:",' - **meta** \u2014 fix the `<title>` / `<meta name="description">` (or the framework\'s metadata API / frontmatter).'," - **schema** \u2014 add or correct JSON-LD structured data.",' - **canonical** \u2014 set the correct `<link rel="canonical">`.'," - **internal_link** \u2014 add relevant internal links (fix orphan/low-link pages)."," - **other** \u2014 follow the recommendation above."].join(`
81
+ `)}}function _l(e,t,n){if(n)return`Locate the page's source. It renders at \`${n}\` \u2014 find the matching route/template/markdown in this repo (look under \`app/\`, \`pages/\`, \`src/\`, \`content/\`).`;let r=(t||"").toLowerCase();return r.includes("robots")||r.includes("ai_bot")||r.includes("bot_policy")?"This is a site-wide policy issue. Edit `robots.txt` at the site root (or its generator \u2014 `app/robots.ts`, `public/robots.txt`, etc.) to add the appropriate `User-agent:` / `Allow:` / `Disallow:` rules.":r.includes("sitemap")?"This is a sitemap configuration issue. Edit your sitemap generator \u2014 `app/sitemap.ts`, `pages/sitemap.xml.ts`, `next-sitemap.config.js`, or the static `public/sitemap.xml`.":e==="canonical"?'This is a site-wide canonical pattern. Look in the layout/template that wraps your pages (e.g. `app/layout.tsx`, `_app.tsx`, theme `head` partial) \u2014 that\'s where the `<link rel="canonical">` is set for every page.':e==="schema"?"This is a site-wide schema gap. Apply JSON-LD to the layout/template (for Organization-level schema) or to specific page templates (for Article / Product / FAQPage etc.).":e==="meta"?"This is a site-wide metadata convention. Look at the page-template metadata \u2014 Next.js `generateMetadata()` / `metadata` export, Nuxt `useHead()`, Astro frontmatter, etc.":e==="internal_link"?"No specific page on file. Identify pages on the same topic/cluster from `.seoagent/strategy/clusters/` and add inbound links to the target page.":"This issue does not name a single page. Read the recommendation above, identify the relevant template/config in this repo, and apply the change there."}function Cl(e){let t=e.payload||{},n=t.page_url??null,r=t.issue??"other",o=t.check_id??"unknown",i=t.severity??"unknown",s=t.recommended_fix??null;return`---
82
82
  action_id: ${e.id}
83
83
  action_type: ${e.action_type}
84
84
  issue: ${r}
@@ -101,8 +101,8 @@ ${s??e.description??"Apply the appropriate fix for this issue."}
101
101
 
102
102
  ## How to apply
103
103
 
104
- 1. ${Sl(r,o,n)}
105
- 2. ${$l(r)}
104
+ 1. ${_l(r,o,n)}
105
+ 2. ${xl(r)}
106
106
  3. Show the user the diff before committing (confirm once per session, then proceed).
107
107
 
108
108
  ## How to close this out
@@ -119,7 +119,7 @@ next \`seoagent sync\`. If you disagree or it's a false positive, decline it:
119
119
  \`\`\`bash
120
120
  ${f(`ack ${e.id}`)} --failed --reason "not applicable; ..."
121
121
  \`\`\`
122
- `}function xl(e){let t=e.payload||{},n=t.brief_slug??null,r=t.primary_keyword??null,o=t.cluster??null,i=t.role??null,s=t.search_intent??null,a=t.priority??"medium";return`---
122
+ `}function El(e){let t=e.payload||{},n=t.brief_slug??null,r=t.primary_keyword??null,o=t.cluster??null,i=t.role??null,s=t.search_intent??null,a=t.priority??"medium";return`---
123
123
  action_id: ${e.id}
124
124
  action_type: ${e.action_type}
125
125
  brief_slug: ${n??""}
@@ -168,7 +168,7 @@ If you decide not to write it (off-strategy, duplicate, etc.), decline it:
168
168
  \`\`\`bash
169
169
  ${f(`ack ${e.id}`)} --failed --reason "skipped; ..."
170
170
  \`\`\`
171
- `}function _l(e){let t=e.payload||{},n=t.page_url??null,r=t.reason??"stale_thin",o=t.metrics??null,i=o?Object.entries(o).map(([s,a])=>`- **${s}**: ${a??"(n/a)"}`).join(`
171
+ `}function Al(e){let t=e.payload||{},n=t.page_url??null,r=t.reason??"stale_thin",o=t.metrics??null,i=o?Object.entries(o).map(([s,a])=>`- **${s}**: ${a??"(n/a)"}`).join(`
172
172
  `):"- (no metrics)";return`---
173
173
  action_id: ${e.id}
174
174
  action_type: ${e.action_type}
@@ -215,7 +215,7 @@ If you disagree (page is fine as-is, intentionally short, etc.), decline it:
215
215
  \`\`\`bash
216
216
  ${f(`ack ${e.id}`)} --failed --reason "kept as-is; ..."
217
217
  \`\`\`
218
- `}function Cl(e){let t=e.payload||{},n=t.sitemap_url??null,r=t.known_url_count??0,o=Array.isArray(t.urls)?t.urls:[],i=!!t.truncated,s=o.length>0?`\`\`\`
218
+ `}function Rl(e){let t=e.payload||{},n=t.sitemap_url??null,r=t.known_url_count??0,o=Array.isArray(t.urls)?t.urls:[],i=!!t.truncated,s=o.length>0?`\`\`\`
219
219
  ${o.join(`
220
220
  `)}
221
221
  \`\`\`${i?`
@@ -261,7 +261,7 @@ SEOAgent re-submits the sitemap to GSC on its schedule. If a sitemap already exi
261
261
  \`\`\`bash
262
262
  ${f(`ack ${e.id}`)} --failed --reason "sitemap already served at /sitemap.xml"
263
263
  \`\`\`
264
- `}function El(e){let t=e.payload||{},n=t.keyword??null,r=t.opportunity??"easy_win",o=t.volume??null,i=t.difficulty??null,s=t.intent??null,a=r==="competitor_gap"?"competitor gap (a rival ranks top-10 here, you don't)":"easy win (low difficulty, real volume)";return`---
264
+ `}function Il(e){let t=e.payload||{},n=t.keyword??null,r=t.opportunity??"easy_win",o=t.volume??null,i=t.difficulty??null,s=t.intent??null,a=r==="competitor_gap"?"competitor gap (a rival ranks top-10 here, you don't)":"easy win (low difficulty, real volume)";return`---
265
265
  action_id: ${e.id}
266
266
  action_type: ${e.action_type}
267
267
  keyword: ${n??""}
@@ -319,10 +319,10 @@ decline it:
319
319
  \`\`\`bash
320
320
  ${f(`ack ${e.id}`)} --failed --reason "skipped; ..."
321
321
  \`\`\`
322
- `}function Al(e){switch(e.action_type){case"cli_prune_pending":return bl(e);case"cli_technical_fix":return vl(e);case"cli_new_content":return xl(e);case"cli_content_update":return _l(e);case"cli_sitemap_update":return Cl(e);case"cli_new_landing_page":return El(e);default:return null}}function Rl(e){if(e.length===0)return`# SEOAgent Inbox
322
+ `}function Pl(e){switch(e.action_type){case"cli_prune_pending":return vl(e);case"cli_technical_fix":return Cl(e);case"cli_new_content":return El(e);case"cli_content_update":return Al(e);case"cli_sitemap_update":return Rl(e);case"cli_new_landing_page":return Il(e);default:return null}}function Ol(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 \`${ko(n)}\``);return`# SEOAgent Inbox
325
+ `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${So(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 be(e){let t=te(e);if(!bn(t))return[];let n=[];for(let r of wo(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,p=null,d=null,g=null,m=null;try{let v=yl(je(t,r),"utf-8"),$=v.match(/^---\n([\s\S]*?)\n---/);if($){let F=$[1];c=Te(F,"severity"),u=Te(F,"issue"),p=Te(F,"page_url");let Z=Te(F,"priority");(Z==="high"||Z==="medium"||Z==="low")&&(d=Z),g=Te(F,"impact_estimate"),m=Te(F,"effort_estimate")}let x=v.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);x&&(a=x[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:c,issue:u,page_url:p,priority:d,impact_estimate:g,effort_estimate:m})}return n.sort((r,o)=>r.id-o.id)}function Le(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Il[e.severity??""]??O.dim,r=e.severity??"unknown",o=[O.dim("\u25B8"),O.bold(`id ${e.id}`),O.dim("\xB7"),O.cyan(t),n(r)];if(e.priority){let i=Pl[e.priority];o.push(O.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(O.dim("\xB7"),O.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(O.dim("\xB7"),O.dim(`\u23F1 ${e.effort_estimate}`)),o.push(O.dim("\u2014"),e.title),o.join(" ")}var Il={critical:e=>O.red(O.bold(e)),high:e=>O.red(e),medium:e=>O.yellow(e),low:e=>O.dim(e)},Pl={high:e=>O.red(O.bold(e)),medium:e=>O.yellow(e),low:e=>O.dim(e)};function Te(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 Nt(e){let t=te(e);if(!bn(t))return;let n=be(e),r=n.length===0?`# SEOAgent Inbox
337
+ `}function be(e){let t=te(e);if(!wn(t))return[];let n=[];for(let r of $o(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,p=null,d=null,g=null,m=null;try{let v=bl(je(t,r),"utf-8"),$=v.match(/^---\n([\s\S]*?)\n---/);if($){let F=$[1];c=Te(F,"severity"),u=Te(F,"issue"),p=Te(F,"page_url");let Z=Te(F,"priority");(Z==="high"||Z==="medium"||Z==="low")&&(d=Z),g=Te(F,"impact_estimate"),m=Te(F,"effort_estimate")}let x=v.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);x&&(a=x[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:c,issue:u,page_url:p,priority:d,impact_estimate:g,effort_estimate:m})}return n.sort((r,o)=>r.id-o.id)}function Le(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Tl[e.severity??""]??O.dim,r=e.severity??"unknown",o=[O.dim("\u25B8"),O.bold(`id ${e.id}`),O.dim("\xB7"),O.cyan(t),n(r)];if(e.priority){let i=jl[e.priority];o.push(O.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(O.dim("\xB7"),O.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(O.dim("\xB7"),O.dim(`\u23F1 ${e.effort_estimate}`)),o.push(O.dim("\u2014"),e.title),o.join(" ")}var Tl={critical:e=>O.red(O.bold(e)),high:e=>O.red(e),medium:e=>O.yellow(e),low:e=>O.dim(e)},jl={high:e=>O.red(O.bold(e)),medium:e=>O.yellow(e),low:e=>O.dim(e)};function Te(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 Lt(e){let t=te(e);if(!wn(t))return;let n=be(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,35 +349,35 @@ 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
- `;kn(je(t,"README.md"),r,"utf-8")}function bo(e,t){let n=te(e);hl(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=kl(n,r),i=0;for(let s of t){let a=Al(s);a!==null&&(kn(je(n,ko(s)),a,"utf-8"),i++)}return kn(je(n,"README.md"),Rl(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as jl}from"crypto";import{existsSync as vo,mkdirSync as Ll,readFileSync as Nl,statSync as xo,writeFileSync as So,rmSync as Fl}from"fs";import{dirname as Dl,join as $n,sep as Ul}from"path";function Ol(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Tl=[{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 $o(e,t){let n=Ol(e);for(let{cls:r,test:o}of Tl)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function Ml(e){return"sha256:"+jl("sha256").update(e).digest("hex")}function Bl(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 Gl(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:$o(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 _o(e){let t=await Eo({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 Co(e,t){return $n(e,t.split("/").join(Ul))}function Kl(e,t,n){let r={};for(let o of t){let i=Co(e,o);if(!vo(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=xo(i),a=n[o],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:Ml(Nl(i,"utf-8")),locallyEdited:c}}return r}async function Eo(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 Ao(e){let t=$n(e.projectDir,k),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!vo(t))return{...n,ok:!0};let r=await Eo({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(p=>p.path),...o.deleted],s=Kl(t,i,e.stateFiles),a=Bl(o,s,{force:e.force}),c={...n,cursor:o.now};for(let p of a){let d=Co(t,p.path);try{switch(p.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{Ll(Dl(d),{recursive:!0}),So(d,p.body??"","utf-8");let g=xo(d);e.stateFiles[p.path]={mtime:g.mtimeMs,size:g.size},p.kind==="write"?c.written++:c.overwritten++,p.note&&c.warnings.push(`${p.path}: ${p.note}`);break}case"conflict":c.conflicts++,c.warnings.push(`${p.path}: ${p.note??"conflict"}`);break;case"delete":Fl(d,{force:!0}),delete e.stateFiles[p.path],c.deleted++;break;case"delete-skipped":c.conflicts++,c.warnings.push(`${p.path}: ${p.note??"delete skipped"}`);break}}catch(g){c.ok=!1,c.error=`${p.path}: ${g.message}`}}(c.conflicts>0||!c.ok)&&(c.cursor=e.since);let u=Gl(a,o,c.cursor,new Date().toISOString());if(u)try{So($n(t,wt),JSON.stringify(u,null,2)+`
353
- `,"utf-8")}catch{}return c}import{existsSync as Io,mkdirSync as Po,readFileSync as Wl,writeFileSync as Sn}from"fs";import{dirname as Oo,join as ql}from"path";var vn=1,Ro=500;function xn(e){return ql(e,k,er)}function Ft(e){let t=xn(e);if(!Io(t))return[];try{let n=Wl(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==vn||!Array.isArray(o.entries)?[]:o.entries.filter(Hl)}catch{return[]}}function To(e,t){let n=xn(e),o=Ft(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>Ro?o.slice(-Ro):o,s={version:vn,entries:i};try{Po(Oo(n),{recursive:!0}),Sn(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function jo(e,t){if(t.length===0)return;let n=xn(e),r=Ft(e).filter(i=>!t.includes(i.action_id)),o={version:vn,entries:r};try{if(r.length===0&&Io(n)){Sn(n,JSON.stringify(o,null,2),"utf-8");return}Po(Oo(n),{recursive:!0}),Sn(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function Hl(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 Lo,readFileSync as Yl,unlinkSync as zl,writeFileSync as Vl,openSync as Jl,closeSync as Xl,mkdirSync as Ql}from"fs";import{dirname as Zl,join as ec}from"path";var tc=6e4;function No(e){return ec(e,k,tr)}function Fo(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??tc,i=No(e);if(!Lo(i))return Dt(i,r,n());let s=Uo(i);return!s||n()-s.started_at>o||!nc(s.pid)?Dt(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function Do(e,t={}){let n=t.pid??process.pid,r=No(e);if(!Lo(r))return;let o=Uo(r);if(!(o&&o.pid!==n))try{zl(r)}catch{}}function Dt(e,t,n){let r={pid:t,started_at:n};try{Ql(Zl(e),{recursive:!0});let o=Jl(e,"w");try{Vl(o,JSON.stringify(r))}finally{Xl(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Uo(e){try{let t=Yl(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 nc(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var cc=new Set([".md"]),uc=new Set(["inbox"]);function dc(e){let t=[];function n(r,o){if(_n(r))for(let i of oc(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&uc.has(i.name))continue;let s=Cn(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);cc.has(c)&&t.push(s)}}}return n(e,""),t}function Bo(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Cn(Zt,`${t}.json`)}function pc(e){let t=Bo(e);if(!_n(t))return{files:{},last_synced_at:null};try{return JSON.parse(Mo(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function fc(e,t){rc(Zt,{recursive:!0}),sc(Bo(e),JSON.stringify(t,null,2)+`
354
- `,"utf-8")}function mc(e,t){return ac(e,t).split(lc).join("/")}async function gc(e,t){try{let n=await K(`${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 hc(e,t,n){try{let r=await K(`${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 Go(e,t={}){let n=j();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=_(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=Cn(e,k);if(!_n(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!Fo(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await yc(e,t,n,r,o)}finally{Do(e)}}async function yc(e,t,n,r,o){let i=pc(r.domain),s=dc(o),a=n.api_base||A.BASE,c=`Bearer ${n.user_token}:${n.website_token}`,u=0,p=0,d=[],g=0,m=await wc(e,a,c);if(!t.pullOnly)for(let D of s){let Ue=mc(o,D);if(t.pathFilter&&!Ue.endsWith(t.pathFilter))continue;let gt=ic(D),Xt=i.files[Ue];if(!(!Xt||Xt.mtime!==gt.mtimeMs||Xt.size!==gt.size)&&!t.force)continue;g++;let Ni=Mo(D,"utf-8"),Qt=await hc(a,{path:Ue,contents:Ni,domain:r.domain},c);Qt.ok?(i.files[Ue]={mtime:gt.mtimeMs,size:gt.size},u++):(p++,d.push(`${Ue}: ${Qt.status} ${Qt.error??""}`.trim()))}let v=await gc(a,c),$=0,T=0;if(v.ok){let D=bo(e,v.actions);$=D.wrote,T=D.removed}else v.error&&d.push(`pull actions: ${v.error}`);let x,F=!1,Z=i.last_synced_at;if(!t.pushOnly){let D=await Ao({projectDir:e,apiBase:a,authHeader:c,since:i.last_synced_at,stateFiles:i.files,force:t.force});D.ok?Z=D.cursor:(F=!0,D.error&&d.push(`pull: ${D.error}`)),x={written:D.written,overwritten:D.overwritten,skipped:D.skipped,conflicts:D.conflicts,deleted:D.deleted,warnings:D.warnings}}let W=!!x&&x.written+x.overwritten+x.deleted+x.conflicts>0;if(i.last_synced_at=Z,fc(r.domain,i),g===0&&$===0&&T===0&&!W&&m.flushed===0&&m.dropped===0&&!F&&p===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:d,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:x};let mt=p===0&&!F;return{ok:mt,reason:mt?void 0:"error",synced:u,failed:p,errors:d,actionsPulled:$,actionsRemoved:T,acksFlushed:m.flushed,acksDropped:m.dropped,pull:x}}async function wc(e,t,n){let r=Ft(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let c=await kc(a,t,n);c==="flushed"?(o++,s.push(a.action_id)):c==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&jo(e,s),{flushed:o,dropped:i}}async function kc(e,t,n){try{let r=await K(`${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 Ko(e){let t;try{t=_(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(Oe(E,n)<=0){if(!t.skill_version)try{z(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return _e(e),z(e,{skill_version:E}),{refreshed:!0,from:n,to:E,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function En(e){let t;try{t=_(e)}catch{return{refreshed:!1,from:null,to:E,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:E,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return _e(e),z(e,{skill_version:E}),{refreshed:!0,from:n,to:E,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:E,reason:"error"}}}import{existsSync as bc,mkdirSync as $c,readFileSync as Sc,writeFileSync as vc}from"fs";var xc="https://registry.npmjs.org/@seoagent-official/seoagent/latest",_c=1440*60*1e3,Cc=720*60*1e3,Ec=2e3;function Ac(e,t,n=_c){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function Rc(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??Cc;if(!n||Oe(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 Ic(e){let t=e.readCache();if(Ac(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=Rc({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 Pc(){try{return bc(kt)?JSON.parse(Sc(kt,"utf-8")):{}}catch{return{}}}function Oc(e){try{$c(M,{recursive:!0}),vc(kt,JSON.stringify(e,null,2)+`
355
- `,"utf-8")}catch{}}async function Tc(){try{let e=await fetch(xc,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(Ec)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function Wo(e){try{return await Ic({current:e,now:new Date,fetchLatest:Tc,readCache:Pc,writeCache:Oc})}catch{return null}}async function H(e={}){let t=Ko(process.cwd());if(t.refreshed){try{me(process.cwd())}catch{}e.silent||l.info(ce.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}ge(process.cwd());let n=await Wo(E);n&&l.message(ce.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?jc():null;i?.start(`${o} ${ce.dim(".seoagent/")} with your dashboard\u2026`);let s=await Go(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.`,ce.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.`,ce.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.",ce.green("Already in sync."));return}if(s.reason==="busy"){w(i,"info","Another sync is in progress \u2014 skipping this run.",ce.dim("Another sync is in progress \u2014 skipping this run."));return}let a=Lc(s);w(i,"success",a??"Sync complete.",ce.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 p of c.warnings.slice(0,5))l.info(` \u2022 ${p}`)}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 Lc(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 L(e){let t=_(e);return t||(l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function $e(e={}){if(e.print){let t=j();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!L(process.cwd()))return;let n=t.api_base||A.BASE,r=await _o({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
+ `;yn(je(t,"README.md"),r,"utf-8")}function vo(e,t){let n=te(e);kl(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=Sl(n,r),i=0;for(let s of t){let a=Pl(s);a!==null&&(yn(je(n,So(s)),a,"utf-8"),i++)}return yn(je(n,"README.md"),Ol(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as Fl}from"crypto";import{existsSync as Co,mkdirSync as Dl,readFileSync as Ul,statSync as Eo,writeFileSync as _o,rmSync as Ml}from"fs";import{dirname as Bl,join as kn,sep as Gl}from"path";function Ll(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 xo(e,t){let n=Ll(e);for(let{cls:r,test:o}of Nl)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function Wl(e){return"sha256:"+Fl("sha256").update(e).digest("hex")}function Kl(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 ql(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:xo(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 Ao(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 Ro(e,t){return kn(e,t.split("/").join(Gl))}function Hl(e,t,n){let r={};for(let o of t){let i=Ro(e,o);if(!Co(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=Eo(i),a=n[o],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:Wl(Ul(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 Po(e){let t=kn(e.projectDir,k),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!Co(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(p=>p.path),...o.deleted],s=Hl(t,i,e.stateFiles),a=Kl(o,s,{force:e.force}),c={...n,cursor:o.now};for(let p of a){let d=Ro(t,p.path);try{switch(p.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{Dl(Bl(d),{recursive:!0}),_o(d,p.body??"","utf-8");let g=Eo(d);e.stateFiles[p.path]={mtime:g.mtimeMs,size:g.size},p.kind==="write"?c.written++:c.overwritten++,p.note&&c.warnings.push(`${p.path}: ${p.note}`);break}case"conflict":c.conflicts++,c.warnings.push(`${p.path}: ${p.note??"conflict"}`);break;case"delete":Ml(d,{force:!0}),delete e.stateFiles[p.path],c.deleted++;break;case"delete-skipped":c.conflicts++,c.warnings.push(`${p.path}: ${p.note??"delete skipped"}`);break}}catch(g){c.ok=!1,c.error=`${p.path}: ${g.message}`}}(c.conflicts>0||!c.ok)&&(c.cursor=e.since);let u=ql(a,o,c.cursor,new Date().toISOString());if(u)try{_o(kn(t,yt),JSON.stringify(u,null,2)+`
353
+ `,"utf-8")}catch{}return c}import{existsSync as To,mkdirSync as jo,readFileSync as Yl,writeFileSync as bn}from"fs";import{dirname as Lo,join as Vl}from"path";var $n=1,Oo=500;function Sn(e){return Vl(e,k,tr)}function Nt(e){let t=Sn(e);if(!To(t))return[];try{let n=Yl(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==$n||!Array.isArray(o.entries)?[]:o.entries.filter(zl)}catch{return[]}}function No(e,t){let n=Sn(e),o=Nt(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>Oo?o.slice(-Oo):o,s={version:$n,entries:i};try{jo(Lo(n),{recursive:!0}),bn(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function Fo(e,t){if(t.length===0)return;let n=Sn(e),r=Nt(e).filter(i=>!t.includes(i.action_id)),o={version:$n,entries:r};try{if(r.length===0&&To(n)){bn(n,JSON.stringify(o,null,2),"utf-8");return}jo(Lo(n),{recursive:!0}),bn(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function zl(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 Do,readFileSync as Jl,unlinkSync as Xl,writeFileSync as Ql,openSync as Zl,closeSync as ec,mkdirSync as tc}from"fs";import{dirname as nc,join as rc}from"path";var oc=6e4;function Uo(e){return rc(e,k,nr)}function Mo(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??oc,i=Uo(e);if(!Do(i))return Ft(i,r,n());let s=Go(i);return!s||n()-s.started_at>o||!ic(s.pid)?Ft(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function Bo(e,t={}){let n=t.pid??process.pid,r=Uo(e);if(!Do(r))return;let o=Go(r);if(!(o&&o.pid!==n))try{Xl(r)}catch{}}function Ft(e,t,n){let r={pid:t,started_at:n};try{tc(nc(e),{recursive:!0});let o=Zl(e,"w");try{Ql(o,JSON.stringify(r))}finally{ec(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Go(e){try{let t=Jl(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 ic(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var pc=new Set([".md"]),fc=new Set(["inbox"]);function mc(e){let t=[];function n(r,o){if(vn(r))for(let i of ac(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&fc.has(i.name))continue;let s=xn(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);pc.has(c)&&t.push(s)}}}return n(e,""),t}function Ko(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return xn(Xt,`${t}.json`)}function gc(e){return cc("sha256").update(e,"utf-8").digest("hex")}function hc(e){let t=Ko(e);if(!vn(t))return{files:{},last_synced_at:null};try{return JSON.parse(Wo(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function yc(e,t){sc(Xt,{recursive:!0}),lc(Ko(e),JSON.stringify(t,null,2)+`
354
+ `,"utf-8")}function wc(e,t){return uc(e,t).split(dc).join("/")}async function kc(e,t){try{let n=await W(`${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 bc(e,t,n){try{let r=await W(`${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 qo(e,t={}){let n=j();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=_(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=xn(e,k);if(!vn(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!Mo(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await $c(e,t,n,r,o)}finally{Bo(e)}}async function $c(e,t,n,r,o){let i=hc(r.domain),s=mc(o),a=n.api_base||A.BASE,c=`Bearer ${n.user_token}:${n.website_token}`,u=0,p=0,d=[],g=0,m=await Sc(e,a,c);if(!t.pullOnly)for(let U of s){let Ue=wc(o,U);if(t.pathFilter&&!Ue.endsWith(t.pathFilter))continue;let Jn=Wo(U,"utf-8"),Xn=gc(Jn),Qn=i.files[Ue];if(!(!Qn||Qn.hash!==Xn)&&!t.force)continue;g++;let Jt=await bc(a,{path:Ue,contents:Jn,domain:r.domain},c);Jt.ok?(i.files[Ue]={hash:Xn},u++):(p++,d.push(`${Ue}: ${Jt.status} ${Jt.error??""}`.trim()))}let v=await kc(a,c),$=0,T=0;if(v.ok){let U=vo(e,v.actions);$=U.wrote,T=U.removed}else v.error&&d.push(`pull actions: ${v.error}`);let x,F=!1,Z=i.last_synced_at;if(!t.pushOnly){let U=await Po({projectDir:e,apiBase:a,authHeader:c,since:i.last_synced_at,stateFiles:i.files,force:t.force});U.ok?Z=U.cursor:(F=!0,U.error&&d.push(`pull: ${U.error}`)),x={written:U.written,overwritten:U.overwritten,skipped:U.skipped,conflicts:U.conflicts,deleted:U.deleted,warnings:U.warnings}}let K=!!x&&x.written+x.overwritten+x.deleted+x.conflicts>0;if(i.last_synced_at=Z,yc(r.domain,i),g===0&&$===0&&T===0&&!K&&m.flushed===0&&m.dropped===0&&!F&&p===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:d,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:x};let mt=p===0&&!F;return{ok:mt,reason:mt?void 0:"error",synced:u,failed:p,errors:d,actionsPulled:$,actionsRemoved:T,acksFlushed:m.flushed,acksDropped:m.dropped,pull:x}}async function Sc(e,t,n){let r=Nt(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let c=await vc(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 vc(e,t,n){try{let r=await W(`${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 Ho(e){let t;try{t=_(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(Oe(E,n)<=0){if(!t.skill_version)try{V(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return _e(e),V(e,{skill_version:E}),{refreshed:!0,from:n,to:E,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function _n(e){let t;try{t=_(e)}catch{return{refreshed:!1,from:null,to:E,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:E,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return _e(e),V(e,{skill_version:E}),{refreshed:!0,from:n,to:E,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:E,reason:"error"}}}import{existsSync as xc,mkdirSync as _c,readFileSync as Cc,writeFileSync as Ec}from"fs";var Ac="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Rc=1440*60*1e3,Ic=720*60*1e3,Pc=2e3;function Oc(e,t,n=Rc){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function Tc(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??Ic;if(!n||Oe(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 jc(e){let t=e.readCache();if(Oc(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=Tc({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 Lc(){try{return xc(wt)?JSON.parse(Cc(wt,"utf-8")):{}}catch{return{}}}function Nc(e){try{_c(M,{recursive:!0}),Ec(wt,JSON.stringify(e,null,2)+`
355
+ `,"utf-8")}catch{}}async function Fc(){try{let e=await fetch(Ac,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(Pc)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function Yo(e){try{return await jc({current:e,now:new Date,fetchLatest:Fc,readCache:Lc,writeCache:Nc})}catch{return null}}async function H(e={}){let t=Ho(process.cwd());if(t.refreshed){try{me(process.cwd())}catch{}e.silent||l.info(ce.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}ge(process.cwd());let n=await Yo(E);n&&l.message(ce.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?Dc():null;i?.start(`${o} ${ce.dim(".seoagent/")} with your dashboard\u2026`);let s=await qo(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.`,ce.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.`,ce.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.",ce.green("Already in sync."));return}if(s.reason==="busy"){w(i,"info","Another sync is in progress \u2014 skipping this run.",ce.dim("Another sync is in progress \u2014 skipping this run."));return}let a=Uc(s);w(i,"success",a??"Sync complete.",ce.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 p of c.warnings.slice(0,5))l.info(` \u2022 ${p}`)}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 Uc(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 L(e){let t=_(e);return t||(l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function $e(e={}){if(e.print){let t=j();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!L(process.cwd()))return;let n=t.api_base||A.BASE,r=await Ao({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 H({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as Nc,readdirSync as Fc,unlinkSync as Dc}from"fs";import{join as qo}from"path";import{isCancel as Uc,select as Mc}from"@clack/prompts";async function ue(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 Bc(),n===null)return;let r=n,o=j();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!L(process.cwd()))return;let i=o.api_base||A.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",c;try{c=await K(`${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{To(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),An(r),Nt(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(()=>""),p=null;try{p=JSON.parse(u)}catch{p=null}if(c.status===409&&p?.code==="already_acked"){An(r),Nt(process.cwd());let v=typeof p.error=="string"?p.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||l.success(`Action ${r} was already ${v}.`);return}let d=typeof p?.code=="string"?p.code:null,g=typeof p?.error=="string"?p.error:u,m=d?`, code: ${d}`:"";l.error(`Server rejected ack (${c.status}${m}): ${g.slice(0,200)}`),process.exitCode=1;return}An(r),Nt(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: ${qo(k,"inbox")}`))}function An(e){let t=te(process.cwd());if(Nc(t)){for(let n of Fc(t))if(n.endsWith(`-${e}.md`))try{Dc(qo(t,n))}catch{}}}async function Bc(){let e=process.cwd(),t=be(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 Mc({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Le(r)}))});return Uc(n)?(l.info("Cancelled \u2014 no action closed out."),null):n}import Ut from"picocolors";async function Rn(e={}){let t=process.cwd();if(!e.json&&!L(t))return;let n=be(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:te(t),actions:n})+`
358
- `);return}if(n.length===0){l.info(Ut.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(`${Ut.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(Le(r));l.message(""),l.message(`Apply one: ${Ut.bold(f("ack <id>"))} \xB7 Interactive picker: ${Ut.bold(f("ack"))} (no id)`)}import{readFileSync as Xc}from"fs";import{join as Qc,relative as Zc}from"path";import{confirm as Jo,isCancel as Bt,multiselect as eu,note as Zo,select as tu}from"@clack/prompts";import h from"picocolors";import{query as nu}from"@anthropic-ai/claude-agent-sdk";import{existsSync as Gc,readdirSync as Kc}from"fs";import{homedir as Wc}from"os";import{join as qc}from"path";import{execSync as In}from"child_process";function nt(){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":Hc()?Yc()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function Hc(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return In(e,{stdio:"ignore"}),!0}catch{return!1}}function Yc(){let e=qc(Wc(),".claude");if(!Gc(e))return!1;try{return Kc(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function Ho(){try{return In("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function Yo(){try{return In("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var ne={"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 Vo}from"marked";import{markedTerminal as zc}from"marked-terminal";import Pn from"picocolors";var zo=!1;function Vc(){zo||(Vo.use(zc({reflowText:!1,width:100})),zo=!0)}function Mt(e){if(!e)return e;Vc();try{let t=Vo.parse(e);return typeof t=="string"?Jc(t):e}catch{return e}}function Jc(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>Pn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>Pn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+Pn.italic(r))}async function Tn(e={}){let t=process.cwd();if(!L(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 lu(e.yes)){process.exitCode=1;return}if(e.yes)await H({embedded:!0});else{let u=await tu({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(Bt(u)){l.info("Cancelled.");return}u==="sync"?await H({embedded:!0}):u==="pull"&&await $e({embedded:!0})}let r=be(t);if(r.length===0){l.info(h.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),p=u?r.filter(m=>m.priority==="high").map(m=>m.id):r.map(m=>m.id),d=u&&p.length===0?" (no high-priority actions \u2014 toggle to select)":u?` (${p.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",g=await eu({message:`Which actions to process? ${r.length} pending \u2014${d}`,options:r.map(m=>({value:m.id,label:Le(m)})),initialValues:p,required:!1});if(Bt(g)){l.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(g)||g.length===0){l.info("No actions selected. Nothing to do.");return}o=g}let i=0,s=0,a=0,c=Date.now();for(let u=0;u<o.length;u++){let p=o[u],d=r.find(x=>x.id===p);if(!d)continue;ru({index:u+1,total:o.length,entry:d});let g=Qc(te(t),d.filename),m;try{m=Xc(g,"utf-8")}catch(x){l.error(` Could not read ${d.filename}: ${x.message}`),a++;continue}let v=Date.now(),$=await au({cwd:t,entry:d,actionContent:m,model:e.model}),T=Xo(Date.now()-v);if($.kind==="applied")try{await ue(String(p),{silent:!0}),i++,l.message("");let x=$.summary?`
359
- `+h.dim(" "+$.summary):"";l.message(` ${h.green("\u2713")} id ${p} ${h.dim("\u2014 applied in "+T)}${x}`)}catch(x){l.warn(` Applied but ack failed: ${x.message}. Run \`seoagent ack ${p}\` to retry.`)}else if($.kind==="declined")try{await ue(String(p),{silent:!0,failed:!0,reason:$.reason}),s++,l.message(""),l.message(` ${h.yellow("\u2298")} id ${p} ${h.dim("\u2014 declined: "+V($.reason,100))}`)}catch(x){l.warn(` Could not ack decline: ${x.message}. Run \`seoagent ack ${p} --failed --reason "${$.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${h.red("\u2717")} id ${p} ${h.dim("\u2014 agent did not converge after "+T)}`)}iu({applied:i,declined:s,failed:a,total:o.length,elapsed:Xo(Date.now()-c)})}function ru(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=ou[i]??h.dim,a=[h.bold(`[${t}/${n}]`),h.dim("\xB7"),h.bold(`id ${r.id}`),h.dim("\xB7"),h.cyan(o),s(i)].join(" ");Zo(r.title,a)}var ou={critical:e=>h.red(h.bold(e)),high:h.red,medium:h.yellow,low:h.dim};function iu(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?h.green(`\u2713 ${t}/${o} applied`):h.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=h.red(`\u2717 0/${o} applied`);else{let c=[`${t}/${o} applied`];n>0&&c.push(`${n} declined`),r>0&&c.push(`${r} failed`),a=h.yellow(`\u25D0 ${c.join(" \xB7 ")}`)}Zo(`${a}
360
- ${h.dim("elapsed: "+i)}`,h.bold("Done"))}function Xo(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 su(e){if(typeof e!="string"||!e)return null;let t=e.split(`
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 au(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=wu(n,r);try{let s=nu({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 p of u)uu(p,a)}else if(c.type==="user"){let u=c.message.content;if(Array.isArray(u))for(let p of u)fu(p,a)}else if(c.type==="result"){if(process.stdout.write(`
362
- `),!(c.subtype==="success"&&!c.is_error))return{kind:"failed"};let p=su(c.result);return p?.kind==="declined"?{kind:"declined",reason:p.reason}:{kind:"applied",summary:p?.kind==="applied"?p.summary:void 0}}return{kind:"failed"}}catch(s){return process.stdout.write(`
363
- `),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function lu(e){let t=nt();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return l.info(h.dim(ne[t].summary)),!0;if(l.warn(ne[t].summary),l.message(` ${ne[t].next}`),e)return!1;if(t==="not-installed"){let n=await Jo({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(Bt(n)||!n)return l.info("Skipped install. Set up auth and re-run when ready."),!1;l.message(h.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=Ho();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=nt()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await Jo({message:"Run `claude login` now to sign in?",initialValue:!0});if(Bt(n)||!n)return l.info("Skipped login. Run `claude login` when ready and try again."),!1;l.message(h.dim("Launching `claude login`\u2026"));let r=Yo();if(!r.ok)return l.error(`Login failed: ${r.error}`),!1}return!0}function cu(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function uu(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&cu(e)){process.stdout.write(Mt(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=pu[o]??h.cyan,a=yu(o,i);process.stdout.write(s(du)+" "+h.bold(o)+h.dim("(")+a+h.dim(")")+`
364
- `);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(h.dim(h.italic(" "+V(r,200)))+`
365
- `)}}var du="\u23FA",Qo="\u23BF",pu={Read:h.blue,Glob:h.cyan,Grep:h.cyan,Edit:h.yellow,Write:h.magenta,Bash:h.green,WebFetch:h.magenta,WebSearch:h.magenta};function fu(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=mu(s);if(n){process.stdout.write(h.red(` ${Qo} Error`)+`
366
- `),a&&process.stdout.write(hu(V(a,500)," ",h.red)+`
367
- `);return}let c=gu(i,a,o?.input);c&&process.stdout.write(h.dim(` ${Qo} `)+c+`
368
- `)}function mu(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 gu(e,t,n){if(!e)return"";switch(e){case"Read":{let r=(t.match(/^\s*\d+→/gm)??[]).length,o=r>0?r:t.split(`
357
+ `);return}await H({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as Mc,readdirSync as Bc,unlinkSync as Gc}from"fs";import{join as Vo}from"path";import{isCancel as Wc,select as Kc}from"@clack/prompts";async function ue(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 qc(),n===null)return;let r=n,o=j();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!L(process.cwd()))return;let i=o.api_base||A.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",c;try{c=await W(`${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{No(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),Cn(r),Lt(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(()=>""),p=null;try{p=JSON.parse(u)}catch{p=null}if(c.status===409&&p?.code==="already_acked"){Cn(r),Lt(process.cwd());let v=typeof p.error=="string"?p.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||l.success(`Action ${r} was already ${v}.`);return}let d=typeof p?.code=="string"?p.code:null,g=typeof p?.error=="string"?p.error:u,m=d?`, code: ${d}`:"";l.error(`Server rejected ack (${c.status}${m}): ${g.slice(0,200)}`),process.exitCode=1;return}Cn(r),Lt(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(k,"inbox")}`))}function Cn(e){let t=te(process.cwd());if(Mc(t)){for(let n of Bc(t))if(n.endsWith(`-${e}.md`))try{Gc(Vo(t,n))}catch{}}}async function qc(){let e=process.cwd(),t=be(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 Kc({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Le(r)}))});return Wc(n)?(l.info("Cancelled \u2014 no action closed out."),null):n}import Dt from"picocolors";async function En(e={}){let t=process.cwd();if(!e.json&&!L(t))return;let n=be(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:te(t),actions:n})+`
358
+ `);return}if(n.length===0){l.info(Dt.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(`${Dt.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(Le(r));l.message(""),l.message(`Apply one: ${Dt.bold(f("ack <id>"))} \xB7 Interactive picker: ${Dt.bold(f("ack"))} (no id)`)}import{readFileSync as tu}from"fs";import{join as nu,relative as ru}from"path";import{confirm as Zo,isCancel as Mt,multiselect as ou,note as ni,select as iu}from"@clack/prompts";import h from"picocolors";import{query as su}from"@anthropic-ai/claude-agent-sdk";import{existsSync as Hc,readdirSync as Yc}from"fs";import{homedir as Vc}from"os";import{join as zc}from"path";import{execSync as An}from"child_process";function nt(){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":Jc()?Xc()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function Jc(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return An(e,{stdio:"ignore"}),!0}catch{return!1}}function Xc(){let e=zc(Vc(),".claude");if(!Hc(e))return!1;try{return Yc(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function zo(){try{return An("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function Jo(){try{return An("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var ne={"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 Qo}from"marked";import{markedTerminal as Qc}from"marked-terminal";import Rn from"picocolors";var Xo=!1;function Zc(){Xo||(Qo.use(Qc({reflowText:!1,width:100})),Xo=!0)}function Ut(e){if(!e)return e;Zc();try{let t=Qo.parse(e);return typeof t=="string"?eu(t):e}catch{return e}}function eu(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>Rn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>Rn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+Rn.italic(r))}async function Pn(e={}){let t=process.cwd();if(!L(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 pu(e.yes)){process.exitCode=1;return}if(e.yes)await H({embedded:!0});else{let u=await iu({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(Mt(u)){l.info("Cancelled.");return}u==="sync"?await H({embedded:!0}):u==="pull"&&await $e({embedded:!0})}let r=be(t);if(r.length===0){l.info(h.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),p=u?r.filter(m=>m.priority==="high").map(m=>m.id):r.map(m=>m.id),d=u&&p.length===0?" (no high-priority actions \u2014 toggle to select)":u?` (${p.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",g=await ou({message:`Which actions to process? ${r.length} pending \u2014${d}`,options:r.map(m=>({value:m.id,label:Le(m)})),initialValues:p,required:!1});if(Mt(g)){l.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(g)||g.length===0){l.info("No actions selected. Nothing to do.");return}o=g}let i=0,s=0,a=0,c=Date.now();for(let u=0;u<o.length;u++){let p=o[u],d=r.find(x=>x.id===p);if(!d)continue;au({index:u+1,total:o.length,entry:d});let g=nu(te(t),d.filename),m;try{m=tu(g,"utf-8")}catch(x){l.error(` Could not read ${d.filename}: ${x.message}`),a++;continue}let v=Date.now(),$=await du({cwd:t,entry:d,actionContent:m,model:e.model}),T=ei(Date.now()-v);if($.kind==="applied")try{await ue(String(p),{silent:!0}),i++,l.message("");let x=$.summary?`
359
+ `+h.dim(" "+$.summary):"";l.message(` ${h.green("\u2713")} id ${p} ${h.dim("\u2014 applied in "+T)}${x}`)}catch(x){l.warn(` Applied but ack failed: ${x.message}. Run \`seoagent ack ${p}\` to retry.`)}else if($.kind==="declined")try{await ue(String(p),{silent:!0,failed:!0,reason:$.reason}),s++,l.message(""),l.message(` ${h.yellow("\u2298")} id ${p} ${h.dim("\u2014 declined: "+z($.reason,100))}`)}catch(x){l.warn(` Could not ack decline: ${x.message}. Run \`seoagent ack ${p} --failed --reason "${$.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${h.red("\u2717")} id ${p} ${h.dim("\u2014 agent did not converge after "+T)}`)}cu({applied:i,declined:s,failed:a,total:o.length,elapsed:ei(Date.now()-c)})}function au(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=lu[i]??h.dim,a=[h.bold(`[${t}/${n}]`),h.dim("\xB7"),h.bold(`id ${r.id}`),h.dim("\xB7"),h.cyan(o),s(i)].join(" ");ni(r.title,a)}var lu={critical:e=>h.red(h.bold(e)),high:h.red,medium:h.yellow,low:h.dim};function cu(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?h.green(`\u2713 ${t}/${o} applied`):h.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=h.red(`\u2717 0/${o} applied`);else{let c=[`${t}/${o} applied`];n>0&&c.push(`${n} declined`),r>0&&c.push(`${r} failed`),a=h.yellow(`\u25D0 ${c.join(" \xB7 ")}`)}ni(`${a}
360
+ ${h.dim("elapsed: "+i)}`,h.bold("Done"))}function ei(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 uu(e){if(typeof e!="string"||!e)return null;let t=e.split(`
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 du(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=Su(n,r);try{let s=su({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 p of u)mu(p,a)}else if(c.type==="user"){let u=c.message.content;if(Array.isArray(u))for(let p of u)yu(p,a)}else if(c.type==="result"){if(process.stdout.write(`
362
+ `),!(c.subtype==="success"&&!c.is_error))return{kind:"failed"};let p=uu(c.result);return p?.kind==="declined"?{kind:"declined",reason:p.reason}:{kind:"applied",summary:p?.kind==="applied"?p.summary:void 0}}return{kind:"failed"}}catch(s){return process.stdout.write(`
363
+ `),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function pu(e){let t=nt();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return l.info(h.dim(ne[t].summary)),!0;if(l.warn(ne[t].summary),l.message(` ${ne[t].next}`),e)return!1;if(t==="not-installed"){let n=await Zo({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(Mt(n)||!n)return l.info("Skipped install. Set up auth and re-run when ready."),!1;l.message(h.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=zo();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=nt()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await Zo({message:"Run `claude login` now to sign in?",initialValue:!0});if(Mt(n)||!n)return l.info("Skipped login. Run `claude login` when ready and try again."),!1;l.message(h.dim("Launching `claude login`\u2026"));let r=Jo();if(!r.ok)return l.error(`Login failed: ${r.error}`),!1}return!0}function fu(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function mu(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&fu(e)){process.stdout.write(Ut(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=hu[o]??h.cyan,a=$u(o,i);process.stdout.write(s(gu)+" "+h.bold(o)+h.dim("(")+a+h.dim(")")+`
364
+ `);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(h.dim(h.italic(" "+z(r,200)))+`
365
+ `)}}var gu="\u23FA",ti="\u23BF",hu={Read:h.blue,Glob:h.cyan,Grep:h.cyan,Edit:h.yellow,Write:h.magenta,Bash:h.green,WebFetch:h.magenta,WebSearch:h.magenta};function yu(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=wu(s);if(n){process.stdout.write(h.red(` ${ti} Error`)+`
366
+ `),a&&process.stdout.write(bu(z(a,500)," ",h.red)+`
367
+ `);return}let c=ku(i,a,o?.input);c&&process.stdout.write(h.dim(` ${ti} `)+c+`
368
+ `)}function wu(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 ku(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 h.dim(`Read ${o} line${o===1?"":"s"}`)}case"Glob":{let r=t.split(`
370
370
  `).filter(o=>o.trim().length>0).length;return h.dim(`Found ${r} ${r===1?"entry":"entries"}`)}case"Grep":{let r=t.split(`
371
371
  `)[0]?.trim()??"";if(/^Found\s+\d+/.test(r))return h.dim(r);let o=t.split(`
372
- `).filter(i=>i.trim()).length;return h.dim(`${o} result${o===1?"":"s"}`)}case"Edit":case"Write":{let r=n?.file_path,o=e==="Edit"?"Updated":"Created";return h.dim(r?`${o} ${On(String(r))}`:o)}case"Bash":{let r=t.split(`
373
- `),o=r.slice(0,5).map(u=>V(u.trimEnd(),100)),i=r.length-5,s=o.join(`
372
+ `).filter(i=>i.trim()).length;return h.dim(`${o} result${o===1?"":"s"}`)}case"Edit":case"Write":{let r=n?.file_path,o=e==="Edit"?"Updated":"Created";return h.dim(r?`${o} ${In(String(r))}`:o)}case"Bash":{let r=t.split(`
373
+ `),o=r.slice(0,5).map(u=>z(u.trimEnd(),100)),i=r.length-5,s=o.join(`
374
374
  `)+(i>0?`
375
375
  \u2026 (+${i} more line${i===1?"":"s"})`:""),[a,...c]=s.split(`
376
376
  `);return c.length===0?h.dim(a):h.dim(a)+`
377
377
  `+h.dim(c.map(u=>" "+u).join(`
378
- `))}case"WebFetch":case"WebSearch":return h.dim(`Fetched ${V(t.replace(/\s+/g," "),80)}`);default:return""}}function hu(e,t,n){return e.split(`
378
+ `))}case"WebFetch":case"WebSearch":return h.dim(`Fetched ${z(t.replace(/\s+/g," "),80)}`);default:return""}}function bu(e,t,n){return e.split(`
379
379
  `).map(r=>n(t+r)).join(`
380
- `)}function yu(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return h.dim(V(On(String(n.file_path??"")),80));case"Bash":return h.dim(V(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${On(String(n.path))}`:"";return h.dim(V(r+o,80))}case"Glob":return h.dim(V(String(n.pattern??""),80));case"WebFetch":return h.dim(V(String(n.url??""),80));case"WebSearch":return h.dim(V(String(n.query??""),80));default:return""}}function On(e){if(!e)return e;let t=process.cwd(),n=Zc(t,e);return n.startsWith("..")?e:n||e}function V(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function wu(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
380
+ `)}function $u(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return h.dim(z(In(String(n.file_path??"")),80));case"Bash":return h.dim(z(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${In(String(n.path))}`:"";return h.dim(z(r+o,80))}case"Glob":return h.dim(z(String(n.pattern??""),80));case"WebFetch":return h.dim(z(String(n.url??""),80));case"WebSearch":return h.dim(z(String(n.query??""),80));default:return""}}function In(e){if(!e)return e;let t=process.cwd(),n=ru(t,e);return n.startsWith("..")?e:n||e}function z(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Su(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
381
381
 
382
382
  Your job: apply the change this action describes to the codebase at the current working directory. Read the "How to apply" section in the action file \u2014 it tells you what to do and where to look. Make the edit, then briefly state what you changed.
383
383
 
@@ -396,24 +396,24 @@ Action file (\`.seoagent/inbox/${e.filename}\`):
396
396
  \`\`\`
397
397
  ${t}
398
398
  \`\`\`
399
- `}import{spinner as ku}from"@clack/prompts";import b from"picocolors";var bu=new Set(["on","off","status"]);async function rt(e,t={}){let n=(e||"").toLowerCase();if(!bu.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=j();if(!r){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||A.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?ku():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}`,b.red("Network error.")),process.exitCode=1;return}let p=null;try{p=await u.json()}catch{p=null}if(u.status===402||p?.code==="upgrade_required"){let v=_(process.cwd())?.domain??"",$=`${A.PRICING}?ref=cli${v?`&domain=${encodeURIComponent(v)}`:""}`;w(a,"warn","CLI autopilot is a paid feature.",b.yellow("Autopilot is a paid feature.")),l.message($u($)),process.exitCode=1;return}if(!u.ok||p?.status!=="ok"||!p.autopilot){w(a,"error",`Server rejected request (${u.status})${p?.error?`: ${p.error}`:""}`,b.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:d,delivery_mode:g}=p.autopilot;if(n==="on"){a?.stop(b.green("Autopilot enabled.")),l.message(jn({enabled:!0,deliveryMode:g,action:n}));return}if(n==="off"){a?.stop(b.dim("Autopilot disabled.")),l.message(jn({enabled:!1,deliveryMode:g,action:n}));return}a?.stop(b.dim("Status:")),l.message(jn({enabled:d,deliveryMode:g,action:n}))}function jn(e){let n=s=>b.dim(s.padEnd(11)),r=e.enabled?`${b.bold(b.green("\u25CF ON"))} ${b.dim("(queueing fixes for your coding agent)")}`:`${b.dim("\u25CB OFF")} ${b.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${b.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${b.dim("Apply queued fixes:")} ${b.cyan(f("sync"))}`}),o.push({content:`${b.dim("Turn off any time:")} ${b.cyan(f("autopilot off"))}`})):(o.push({content:`${b.dim("Enable (paid):")} ${b.cyan(f("autopilot on"))}`}),o.push({content:b.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${b.bold(b.cyan("SEOAgent"))} ${b.dim("\xB7")} ${b.dim("autopilot")}`;return I(o,{width:78,title:i})}function $u(e){let t=[{content:b.bold(b.yellow("Autopilot is a paid feature."))},{sep:!0},{content:b.dim("SEOAgent continuously audits your site and queues fixes for")},{content:b.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:b.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${b.dim("Upgrade:")} ${b.cyan(e)}`}],n=`${b.bold(b.cyan("SEOAgent"))} ${b.dim("\xB7")} ${b.dim("autopilot")}`;return I(t,{width:78,title:n})}import{mkdirSync as Tu,writeFileSync as ju}from"fs";import{join as Ln}from"path";import{readdirSync as Su,readFileSync as vu,statSync as ei}from"fs";import{join as xu}from"path";var _u=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Cu=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"]),Eu=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Au=5e3,Ru=512*1024;function ii(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function ti(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&&Cu.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var ni=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,ri=/\]\(\s*([^)\s]+)/g;function Iu(e,t){if(!e)return[];let n=ii(t),r=[],o;for(ni.lastIndex=0;(o=ni.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=ti(i,n);s&&r.push(s)}for(ri.lastIndex=0;(o=ri.exec(e))!==null;){let i=ti(o[1],n);i&&r.push(i)}return r}function Pu(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 si(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?` (${ii(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 vu}from"@clack/prompts";import b from"picocolors";var xu=new Set(["on","off","status"]);async function rt(e,t={}){let n=(e||"").toLowerCase();if(!xu.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=j();if(!r){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||A.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?vu():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}`,b.red("Network error.")),process.exitCode=1;return}let p=null;try{p=await u.json()}catch{p=null}if(u.status===402||p?.code==="upgrade_required"){let v=_(process.cwd())?.domain??"",$=`${A.PRICING}?ref=cli${v?`&domain=${encodeURIComponent(v)}`:""}`;w(a,"warn","CLI autopilot is a paid feature.",b.yellow("Autopilot is a paid feature.")),l.message(_u($)),process.exitCode=1;return}if(!u.ok||p?.status!=="ok"||!p.autopilot){w(a,"error",`Server rejected request (${u.status})${p?.error?`: ${p.error}`:""}`,b.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:d,delivery_mode:g}=p.autopilot;if(n==="on"){a?.stop(b.green("Autopilot enabled.")),l.message(On({enabled:!0,deliveryMode:g,action:n}));return}if(n==="off"){a?.stop(b.dim("Autopilot disabled.")),l.message(On({enabled:!1,deliveryMode:g,action:n}));return}a?.stop(b.dim("Status:")),l.message(On({enabled:d,deliveryMode:g,action:n}))}function On(e){let n=s=>b.dim(s.padEnd(11)),r=e.enabled?`${b.bold(b.green("\u25CF ON"))} ${b.dim("(queueing fixes for your coding agent)")}`:`${b.dim("\u25CB OFF")} ${b.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${b.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${b.dim("Apply queued fixes:")} ${b.cyan(f("sync"))}`}),o.push({content:`${b.dim("Turn off any time:")} ${b.cyan(f("autopilot off"))}`})):(o.push({content:`${b.dim("Enable (paid):")} ${b.cyan(f("autopilot on"))}`}),o.push({content:b.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${b.bold(b.cyan("SEOAgent"))} ${b.dim("\xB7")} ${b.dim("autopilot")}`;return I(o,{width:78,title:i})}function _u(e){let t=[{content:b.bold(b.yellow("Autopilot is a paid feature."))},{sep:!0},{content:b.dim("SEOAgent continuously audits your site and queues fixes for")},{content:b.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:b.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${b.dim("Upgrade:")} ${b.cyan(e)}`}],n=`${b.bold(b.cyan("SEOAgent"))} ${b.dim("\xB7")} ${b.dim("autopilot")}`;return I(t,{width:78,title:n})}import{mkdirSync as Fu,writeFileSync as Du}from"fs";import{join as Tn}from"path";import{readdirSync as Cu,readFileSync as Eu,statSync as ri}from"fs";import{join as Au}from"path";var Ru=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Iu=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"]),Pu=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Ou=5e3,Tu=512*1024;function li(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function oi(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&&Iu.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var ii=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,si=/\]\(\s*([^)\s]+)/g;function ju(e,t){if(!e)return[];let n=li(t),r=[],o;for(ii.lastIndex=0;(o=ii.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=oi(i,n);s&&r.push(s)}for(si.lastIndex=0;(o=si.exec(e))!==null;){let i=oi(o[1],n);i&&r.push(i)}return r}function Lu(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 ci(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?` (${li(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=>`| ${oi(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=>`| ${oi(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=>`| ${ai(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=>`| ${ai(a.url)} | ${a.inbound} |`)].join(`
405
405
  `);return[r,"",o,"",i,s,""].join(`
406
- `)}function oi(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*Ou(e){let t=0;function*n(r){let o;try{o=Su(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=Au)return;if(i.name.startsWith("."))continue;let s=xu(r,i.name);if(i.isDirectory()){if(Eu.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(!_u.has(c))continue;t++,yield s}}}yield*n(e)}function ai(e,t){let{pages:n}=se(e,t),r=[],o=0,i=!1;try{i=ei(e).isDirectory()}catch{i=!1}if(i)for(let s of Ou(e)){let a;try{if(ei(s).size>Ru)continue;a=vu(s,"utf-8")}catch{continue}o++;for(let c of Iu(a,t))r.push(c)}return Pu(n,r,o)}function ot(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=ai(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
407
- `);return}let i=Ln(t,k);Tu(i,{recursive:!0});let s=Ln(i,"internal-links.md");if(ju(s,si(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 ${Ln(k,"internal-links.md")}`)}import{existsSync as Lu,mkdirSync as Nu,writeFileSync as Fu}from"fs";import{join as li}from"path";import Nn from"picocolors";function Du(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Uu(e,t){if(t.url&&t.url.trim())return t.url.trim().replace(/\/+$/,"");if(!t.domain||t.domain==="unknown")return null;let n=t.domain.replace(/^https?:\/\//,"").replace(/\/$/,""),r=(t.blogPath||"").replace(/\/+$/,"");return`https://${n}${r}/${e}`}function Mu(e){let t=["---",`slug: ${e.slug}`,`title: ${JSON.stringify(e.title)}`];e.page_type&&t.push(`page_type: ${e.page_type}`),e.canonical&&t.push(`canonical: ${e.canonical}`),t.push(`status: ${e.status}`),t.push(`source: ${e.source}`),e.repo_path&&t.push(`repo_path: ${e.repo_path}`),e.primary_keyword&&t.push(`primary_keyword: ${JSON.stringify(e.primary_keyword)}`),t.push(`tracked_at: ${e.tracked_at}`),t.push("---");let n=e.repo_path?`rendered from \`${e.repo_path}\` (the source of truth for its body)`:"rendered from its source (repo or CMS)",r=e.canonical?`
406
+ `)}function ai(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*Nu(e){let t=0;function*n(r){let o;try{o=Cu(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=Ou)return;if(i.name.startsWith("."))continue;let s=Au(r,i.name);if(i.isDirectory()){if(Pu.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(!Ru.has(c))continue;t++,yield s}}}yield*n(e)}function ui(e,t){let{pages:n}=se(e,t),r=[],o=0,i=!1;try{i=ri(e).isDirectory()}catch{i=!1}if(i)for(let s of Nu(e)){let a;try{if(ri(s).size>Tu)continue;a=Eu(s,"utf-8")}catch{continue}o++;for(let c of ju(a,t))r.push(c)}return Lu(n,r,o)}function ot(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=ui(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
407
+ `);return}let i=Tn(t,k);Fu(i,{recursive:!0});let s=Tn(i,"internal-links.md");if(Du(s,ci(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 ${Tn(k,"internal-links.md")}`)}import{existsSync as Uu,mkdirSync as Mu,writeFileSync as Bu}from"fs";import{join as di}from"path";import jn from"picocolors";function Gu(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Wu(e,t){if(t.url&&t.url.trim())return t.url.trim().replace(/\/+$/,"");if(!t.domain||t.domain==="unknown")return null;let n=t.domain.replace(/^https?:\/\//,"").replace(/\/$/,""),r=(t.blogPath||"").replace(/\/+$/,"");return`https://${n}${r}/${e}`}function Ku(e){let t=["---",`slug: ${e.slug}`,`title: ${JSON.stringify(e.title)}`];e.page_type&&t.push(`page_type: ${e.page_type}`),e.canonical&&t.push(`canonical: ${e.canonical}`),t.push(`status: ${e.status}`),t.push(`source: ${e.source}`),e.repo_path&&t.push(`repo_path: ${e.repo_path}`),e.primary_keyword&&t.push(`primary_keyword: ${JSON.stringify(e.primary_keyword)}`),t.push(`tracked_at: ${e.tracked_at}`),t.push("---");let n=e.repo_path?`rendered from \`${e.repo_path}\` (the source of truth for its body)`:"rendered from its source (repo or CMS)",r=e.canonical?`
408
408
 
409
409
  Live: ${e.canonical}`:"",o=[`# ${e.title}`,"",`Tracked record \u2014 this article is **${e.status}** and ${n}.`,"This is a pointer so the cloud dashboard can track it without duplicating","the body. Edit the source file to change the article."+r,""].join(`
410
410
  `);return`${t.join(`
411
411
  `)}
412
412
 
413
413
  ${o}
414
- `}async function Fn(e,t={}){if(e!=="track"){l.message(`Usage: ${f("content track")} --slug <slug> --url <live-url> [--file <repo-path>] [--title "..."] [--type <page_type>] [--status published|draft]`),e&&(l.error(`Unknown content action: ${e}. The only action today is \`track\`.`),process.exitCode=1);return}let n=process.cwd(),r=_(n);if(!r){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let o=t.slug??(t.file?t.file:""),i=Du(o);if(!i){l.error("A slug is required: --slug <slug> (or --file <repo-path> to derive it)."),process.exitCode=1;return}let s=Uu(i,{url:t.url,domain:r.domain,blogPath:r.blog_path});s||l.warn("No live URL \u2014 pass --url, or set domain + blog_path in project.md. Tracking without a canonical URL.");let a=t.title?.trim()||Bu(i),c=r.cms&&r.cms!=="mdx-local"?"cms":t.file?"repo":"external",u=Mu({slug:i,title:a,canonical:s,status:t.status?.trim()||"published",page_type:t.type?.trim()||void 0,primary_keyword:t.primaryKeyword?.trim()||void 0,source:c,repo_path:t.file?.trim()||void 0,tracked_at:new Date().toISOString()}),p=li(n,k,"content");Nu(p,{recursive:!0});let d=li(p,`${i}.md`),g=Lu(d);Fu(d,u,"utf-8"),l.success(`${g?"Updated":"Tracked"} ${Nn.bold(i)}${s?` \u2192 ${Nn.cyan(s)}`:""} in .seoagent/content/.`);try{await H({silent:!0,pushOnly:!0})}catch{}l.message(Nn.dim("It will appear on your dashboard after sync (run `seoagent login` if you haven\u2019t)."))}function Bu(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}import{existsSync as Gu,readFileSync as Ku}from"fs";import{join as Wu}from"path";import Dn from"picocolors";function qu(e){let t=[];return e.pullReceiptCount!=null&&t.push({level:"action",code:"pull_receipt",message:`${e.pullReceiptCount} cloud change${e.pullReceiptCount===1?"":"s"} pulled but not triaged yet.`,fix:"Triage them (skill \xA7 Pull Receipt Triage), then delete .seoagent/.pull-receipt.json."}),(e.domain==="unknown"||!e.domain)&&t.push({level:"action",code:"domain_unknown",message:"Site URL is unknown \u2014 nothing works without a real domain.",fix:"Ask the user for their site URL, then set `domain:` in .seoagent/project.md."}),(e.siteType==="unknown"||!e.siteType)&&t.push({level:"action",code:"site_type_unknown",message:"Site type is unknown \u2014 strategy/briefs make worse calls without it.",fix:"WebFetch the homepage, infer the type, set `site_type:` in project.md."}),!(e.imageProvider&&e.imageProvider!=="none")&&e.detectedImageProvider!=="none"&&t.push({level:"action",code:"image_provider_unset",message:`Image generation is available (${e.detectedImageKey} found) but not enabled.`,fix:`Run \`${f("env-check")}\` to record image_provider, then articles can get AI hero images.`}),t.length===0&&t.push({level:"ok",code:"healthy",message:"Everything looks healthy."}),t}function Hu(e){let t=Wu(e,k,wt);if(!Gu(t))return null;try{let n=JSON.parse(Ku(t,"utf-8"));return Array.isArray(n.changes)?n.changes.length:0}catch{return 0}}function Un(e={}){let t=process.cwd(),n=_(t);if(!n){if(e.json){process.stdout.write(JSON.stringify({status:"no-project",findings:[]})+`
415
- `);return}l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=ie(t),o=qu({domain:n.domain,siteType:n.site_type,imageProvider:n.image_provider,detectedImageProvider:r.provider,detectedImageKey:r.matched_key,pullReceiptCount:Hu(t)});if(e.json){process.stdout.write(JSON.stringify({status:"ok",findings:o})+`
416
- `);return}let i=o.filter(s=>s.level==="action");if(i.length===0){l.success("SEOAgent health: everything looks good.");return}l.message(Dn.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)l.message(` ${Dn.yellow("\u25CF")} ${s.message}`),s.fix&&l.message(` ${Dn.dim("\u2192 "+s.fix)}`)}import X from"picocolors";import{existsSync as Ne,mkdirSync as Gt,readdirSync as Yu,readFileSync as zu,statSync as fy,writeFileSync as ci}from"fs";import{dirname as Vu,join as de,relative as Ju,resolve as Xu}from"path";var Fe="okf";function Kt(e){return de(e,k,Fe)}var Qu=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function Mn(e){let t=[];for(let n of Yu(e,{withFileTypes:!0})){let r=de(e,n.name);n.isDirectory()?t.push(...Mn(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function Zu(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 ui(e){let t=[],n=[];if(!Ne(e))return{ok:!1,fileCount:0,errors:[{file:Fe,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=Mn(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Fe,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Ne(de(e,"index.md"))||n.push({file:Fe,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=Ju(e,i),a;try{a=Be(zu(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!==""&&!Qu.test(String(u))&&t.push({file:s,message:`\`timestamp\` is not ISO-8601: "${String(u)}"`});let p=a.data.description;typeof p=="string"&&p.length>200&&n.push({file:s,message:`\`description\` is ${p.length} chars (keep \u2264 200).`});for(let d of Zu(a.body)){let g=d.split("#")[0];if(!g)continue;let m=Xu(Vu(i),g);Ne(m)||t.push({file:s,message:`Broken link \u2192 "${d}" (target does not exist).`})}}return{ok:t.length===0,fileCount:r.length,errors:t,warnings:n}}function Wt(e){let t=Kt(e);if(!Ne(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:Mn(t).length}}catch{return{exists:!0,fileCount:0}}}function di(e,t){let n=Kt(e);Gt(n,{recursive:!0}),Gt(de(n,"concepts"),{recursive:!0}),Gt(de(n,"faqs"),{recursive:!0}),Gt(de(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=de(n,"index.md");Ne(i)||(ci(i,`---
414
+ `}async function Ln(e,t={}){if(e!=="track"){l.message(`Usage: ${f("content track")} --slug <slug> --url <live-url> [--file <repo-path>] [--title "..."] [--type <page_type>] [--status published|draft]`),e&&(l.error(`Unknown content action: ${e}. The only action today is \`track\`.`),process.exitCode=1);return}let n=process.cwd(),r=_(n);if(!r){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let o=t.slug??(t.file?t.file:""),i=Gu(o);if(!i){l.error("A slug is required: --slug <slug> (or --file <repo-path> to derive it)."),process.exitCode=1;return}let s=Wu(i,{url:t.url,domain:r.domain,blogPath:r.blog_path});s||l.warn("No live URL \u2014 pass --url, or set domain + blog_path in project.md. Tracking without a canonical URL.");let a=t.title?.trim()||qu(i),c=r.cms&&r.cms!=="mdx-local"?"cms":t.file?"repo":"external",u=Ku({slug:i,title:a,canonical:s,status:t.status?.trim()||"published",page_type:t.type?.trim()||void 0,primary_keyword:t.primaryKeyword?.trim()||void 0,source:c,repo_path:t.file?.trim()||void 0,tracked_at:new Date().toISOString()}),p=di(n,k,"content");Mu(p,{recursive:!0});let d=di(p,`${i}.md`),g=Uu(d);Bu(d,u,"utf-8"),l.success(`${g?"Updated":"Tracked"} ${jn.bold(i)}${s?` \u2192 ${jn.cyan(s)}`:""} in .seoagent/content/.`);try{await H({silent:!0,pushOnly:!0})}catch{}l.message(jn.dim("It will appear on your dashboard after sync (run `seoagent login` if you haven\u2019t)."))}function qu(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}import{existsSync as Hu,readFileSync as Yu}from"fs";import{join as Vu}from"path";import Nn from"picocolors";function zu(e){let t=[];return e.pullReceiptCount!=null&&t.push({level:"action",code:"pull_receipt",message:`${e.pullReceiptCount} cloud change${e.pullReceiptCount===1?"":"s"} pulled but not triaged yet.`,fix:"Triage them (skill \xA7 Pull Receipt Triage), then delete .seoagent/.pull-receipt.json."}),(e.domain==="unknown"||!e.domain)&&t.push({level:"action",code:"domain_unknown",message:"Site URL is unknown \u2014 nothing works without a real domain.",fix:"Ask the user for their site URL, then set `domain:` in .seoagent/project.md."}),(e.siteType==="unknown"||!e.siteType)&&t.push({level:"action",code:"site_type_unknown",message:"Site type is unknown \u2014 strategy/briefs make worse calls without it.",fix:"WebFetch the homepage, infer the type, set `site_type:` in project.md."}),!(e.imageProvider&&e.imageProvider!=="none")&&e.detectedImageProvider!=="none"&&t.push({level:"action",code:"image_provider_unset",message:`Image generation is available (${e.detectedImageKey} found) but not enabled.`,fix:`Run \`${f("env-check")}\` to record image_provider, then articles can get AI hero images.`}),t.length===0&&t.push({level:"ok",code:"healthy",message:"Everything looks healthy."}),t}function Ju(e){let t=Vu(e,k,yt);if(!Hu(t))return null;try{let n=JSON.parse(Yu(t,"utf-8"));return Array.isArray(n.changes)?n.changes.length:0}catch{return 0}}function Fn(e={}){let t=process.cwd(),n=_(t);if(!n){if(e.json){process.stdout.write(JSON.stringify({status:"no-project",findings:[]})+`
415
+ `);return}l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=ie(t),o=zu({domain:n.domain,siteType:n.site_type,imageProvider:n.image_provider,detectedImageProvider:r.provider,detectedImageKey:r.matched_key,pullReceiptCount:Ju(t)});if(e.json){process.stdout.write(JSON.stringify({status:"ok",findings:o})+`
416
+ `);return}let i=o.filter(s=>s.level==="action");if(i.length===0){l.success("SEOAgent health: everything looks good.");return}l.message(Nn.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)l.message(` ${Nn.yellow("\u25CF")} ${s.message}`),s.fix&&l.message(` ${Nn.dim("\u2192 "+s.fix)}`)}import X from"picocolors";import{existsSync as Ne,mkdirSync as Bt,readdirSync as Xu,readFileSync as Qu,statSync as wy,writeFileSync as pi}from"fs";import{dirname as Zu,join as de,relative as ed,resolve as td}from"path";var Fe="okf";function Gt(e){return de(e,k,Fe)}var nd=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function Dn(e){let t=[];for(let n of Xu(e,{withFileTypes:!0})){let r=de(e,n.name);n.isDirectory()?t.push(...Dn(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function rd(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 fi(e){let t=[],n=[];if(!Ne(e))return{ok:!1,fileCount:0,errors:[{file:Fe,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=Dn(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Fe,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Ne(de(e,"index.md"))||n.push({file:Fe,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=ed(e,i),a;try{a=Be(Qu(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!==""&&!nd.test(String(u))&&t.push({file:s,message:`\`timestamp\` is not ISO-8601: "${String(u)}"`});let p=a.data.description;typeof p=="string"&&p.length>200&&n.push({file:s,message:`\`description\` is ${p.length} chars (keep \u2264 200).`});for(let d of rd(a.body)){let g=d.split("#")[0];if(!g)continue;let m=td(Zu(i),g);Ne(m)||t.push({file:s,message:`Broken link \u2192 "${d}" (target does not exist).`})}}return{ok:t.length===0,fileCount:r.length,errors:t,warnings:n}}function Wt(e){let t=Gt(e);if(!Ne(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:Dn(t).length}}catch{return{exists:!0,fileCount:0}}}function mi(e,t){let n=Gt(e);Bt(n,{recursive:!0}),Bt(de(n,"concepts"),{recursive:!0}),Bt(de(n,"faqs"),{recursive:!0}),Bt(de(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=de(n,"index.md");Ne(i)||(pi(i,`---
417
417
  type: Organization
418
418
  title: ${o}
419
419
  description: Knowledge bundle describing ${o} for AI agents and answer engines.
@@ -440,7 +440,7 @@ _Describe the business in 2\u20134 sentences (pull from \`.seoagent/context.md\`
440
440
  ## Published articles
441
441
 
442
442
  - _Link article files here, e.g._ \`articles/guide-to-x.md\`
443
- `,"utf-8"),r.push("index.md"));let s=de(n,"log.md");return Ne(s)||(ci(s,`---
443
+ `,"utf-8"),r.push("index.md"));let s=de(n,"log.md");return Ne(s)||(pi(s,`---
444
444
  type: Log
445
445
  title: Change log
446
446
  description: Chronological history of changes to this OKF bundle.
@@ -449,10 +449,10 @@ description: Chronological history of changes to this OKF bundle.
449
449
  # Change log
450
450
 
451
451
  - Bundle scaffolded.
452
- `,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var Bn=`${k}/${Fe}`;function it(e,t={}){let n=process.cwd(),r=L(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=di(n,i);a.length===0?l.info(`OKF bundle already scaffolded at ${Bn}/.`):(l.success(`Scaffolded ${Bn}/ \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=ui(Kt(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
452
+ `,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var Un=`${k}/${Fe}`;function it(e,t={}){let n=process.cwd(),r=L(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=mi(n,i);a.length===0?l.info(`OKF bundle already scaffolded at ${Un}/.`):(l.success(`Scaffolded ${Un}/ \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=fi(Gt(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
453
453
  `);return}for(let c of a.errors)l.message(`${X.red("\u2717")} ${X.dim(c.file)} \u2014 ${c.message}`);for(let c of a.warnings)l.message(`${X.yellow("!")} ${X.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=Wt(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
454
- `);return}l.message(I([{content:X.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?X.green(Bn+"/"):X.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?X.dim("Run `seoagent okf validate` to check it."):X.dim("Run `seoagent okf scaffold` to start one.")}],{title:X.cyan("OKF")}))}import B from"picocolors";async function Gn(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null;if(!r&&!e.url){l.error("No domain set in .seoagent/project.md \u2014 set `domain:` (or pass `--url <sitemap-url>`) so I know which sitemap to check."),process.exitCode=1;return}let o=r?se(t,r).pages.map(s=>s.url||s.route):[],i=await qr({domain:r||"",sitemapUrl:e.url,knownUrls:o});if(e.json){process.stdout.write(JSON.stringify(i,null,2)+`
455
- `),i.ok||(process.exitCode=1);return}ed(i),i.ok||(process.exitCode=1)}function ed(e){let t=e.fetched?e.status===200?B.green(`200 \xB7 ${e.urls.length} URL${e.urls.length===1?"":"s"}`):B.red(String(e.status)):B.red("unreachable");l.message(I([{content:B.bold("Sitemap check")},{sep:!0},{content:`URL: ${B.dim(e.sitemapUrl)}`},{content:`Status: ${t}`},...e.fetched&&e.status===200?[{content:`Private leaked: ${e.privateUrls.length===0?B.green("none"):B.yellow(String(e.privateUrls.length))}`},{content:`Missing public: ${e.missing.length===0?B.green("none"):B.yellow(String(e.missing.length))}`},{content:`<lastmod>: ${e.hasLastmod?B.green("present"):B.dim("absent")}`}]:[]],{title:e.ok?B.cyan("Sitemap"):B.red("Sitemap")}));for(let n of e.issues){let r=n.level==="error"?B.red("\u2717"):n.level==="warning"?B.yellow("!"):B.dim("\xB7");l.message(`${r} ${n.message}`)}e.ok?l.success("Sitemap looks healthy."):l.error("Sitemap has errors (see above).")}import{mkdirSync as Si,writeFileSync as vi,readFileSync as ud,readdirSync as dd,existsSync as pd}from"fs";import{join as xi}from"path";import R from"picocolors";import{query as fd}from"@anthropic-ai/claude-agent-sdk";import{join as Kn}from"path";var Wn="citations",qn="scorecard.md",td="history",nd=6,rd=1,od=12,id=5,qt="Claude (web-grounded)";function Ht(e){return Kn(e,k,Wn)}function fi(e){return Kn(Ht(e),qn)}function mi(e){return Kn(Ht(e),td)}function gi(e){return`${e.replace(/[:.]/g,"-")}.json`}function hi(e){return typeof e!="number"||!Number.isFinite(e)?nd:Math.max(rd,Math.min(od,Math.floor(e)))}function Yt(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e){let o=typeof r=="string"?r.trim():"";if(!o)continue;let i=o.toLowerCase();if(!t.has(i)&&(t.add(i),n.push(o),n.length>=id))break}return n}function st(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function Hn(e){let t=e.results.length,n={brand:e.brand,isYou:!0,surfaced:e.results.filter(o=>o.surfaced).length,total:t},r=e.competitors.map(o=>({brand:o,isYou:!1,surfaced:e.results.filter(i=>i.competitorsSurfaced.some(s=>s.toLowerCase()===o.toLowerCase())).length,total:t}));return r.sort((o,i)=>i.surfaced-o.surfaced||o.brand.localeCompare(i.brand)),[n,...r]}function yi(e,t){let{cited:n,total:r}=st(e);return{generated_at:t.generatedAt,domain:e.domain,brand:e.brand,cited:n,total:r,competitors:e.competitors,results:e.results}}function wi(e,t){if(!t)return null;let{cited:n}=st(e),r=new Map(t.results.map(s=>[s.query.toLowerCase(),s.surfaced])),o=[],i=[];for(let s of e.results){let a=r.get(s.query.toLowerCase());a!==void 0&&(s.surfaced&&!a&&o.push(s.query),!s.surfaced&&a&&i.push(s.query))}return{scoreDelta:n-t.cited,prevCited:t.cited,prevTotal:t.total,prevDate:t.generated_at.slice(0,10),newlyCited:o,newlyDropped:i}}function ki(e,t){let n=Yt(e.competitors),r=[`- 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"}`,n.length?`- Competitors to track: ${n.join(", ")}`:null].filter(Boolean).join(`
454
+ `);return}l.message(I([{content:X.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?X.green(Un+"/"):X.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?X.dim("Run `seoagent okf validate` to check it."):X.dim("Run `seoagent okf scaffold` to start one.")}],{title:X.cyan("OKF")}))}import B from"picocolors";async function Mn(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null;if(!r&&!e.url){l.error("No domain set in .seoagent/project.md \u2014 set `domain:` (or pass `--url <sitemap-url>`) so I know which sitemap to check."),process.exitCode=1;return}let o=r?se(t,r).pages.map(s=>s.url||s.route):[],i=await Vr({domain:r||"",sitemapUrl:e.url,knownUrls:o});if(e.json){process.stdout.write(JSON.stringify(i,null,2)+`
455
+ `),i.ok||(process.exitCode=1);return}od(i),i.ok||(process.exitCode=1)}function od(e){let t=e.fetched?e.status===200?B.green(`200 \xB7 ${e.urls.length} URL${e.urls.length===1?"":"s"}`):B.red(String(e.status)):B.red("unreachable");l.message(I([{content:B.bold("Sitemap check")},{sep:!0},{content:`URL: ${B.dim(e.sitemapUrl)}`},{content:`Status: ${t}`},...e.fetched&&e.status===200?[{content:`Private leaked: ${e.privateUrls.length===0?B.green("none"):B.yellow(String(e.privateUrls.length))}`},{content:`Missing public: ${e.missing.length===0?B.green("none"):B.yellow(String(e.missing.length))}`},{content:`<lastmod>: ${e.hasLastmod?B.green("present"):B.dim("absent")}`}]:[]],{title:e.ok?B.cyan("Sitemap"):B.red("Sitemap")}));for(let n of e.issues){let r=n.level==="error"?B.red("\u2717"):n.level==="warning"?B.yellow("!"):B.dim("\xB7");l.message(`${r} ${n.message}`)}e.ok?l.success("Sitemap looks healthy."):l.error("Sitemap has errors (see above).")}import{mkdirSync as _i,writeFileSync as Ci,readFileSync as md,readdirSync as gd,existsSync as hd}from"fs";import{join as Ei}from"path";import R from"picocolors";import{query as yd}from"@anthropic-ai/claude-agent-sdk";import{join as Bn}from"path";var Gn="citations",Wn="scorecard.md",id="history",sd=6,ad=1,ld=12,cd=5,Kt="Claude (web-grounded)";function qt(e){return Bn(e,k,Gn)}function hi(e){return Bn(qt(e),Wn)}function yi(e){return Bn(qt(e),id)}function wi(e){return`${e.replace(/[:.]/g,"-")}.json`}function ki(e){return typeof e!="number"||!Number.isFinite(e)?sd:Math.max(ad,Math.min(ld,Math.floor(e)))}function Ht(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e){let o=typeof r=="string"?r.trim():"";if(!o)continue;let i=o.toLowerCase();if(!t.has(i)&&(t.add(i),n.push(o),n.length>=cd))break}return n}function st(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function Kn(e){let t=e.results.length,n={brand:e.brand,isYou:!0,surfaced:e.results.filter(o=>o.surfaced).length,total:t},r=e.competitors.map(o=>({brand:o,isYou:!1,surfaced:e.results.filter(i=>i.competitorsSurfaced.some(s=>s.toLowerCase()===o.toLowerCase())).length,total:t}));return r.sort((o,i)=>i.surfaced-o.surfaced||o.brand.localeCompare(i.brand)),[n,...r]}function bi(e,t){let{cited:n,total:r}=st(e);return{generated_at:t.generatedAt,domain:e.domain,brand:e.brand,cited:n,total:r,competitors:e.competitors,results:e.results}}function $i(e,t){if(!t)return null;let{cited:n}=st(e),r=new Map(t.results.map(s=>[s.query.toLowerCase(),s.surfaced])),o=[],i=[];for(let s of e.results){let a=r.get(s.query.toLowerCase());a!==void 0&&(s.surfaced&&!a&&o.push(s.query),!s.surfaced&&a&&i.push(s.query))}return{scoreDelta:n-t.cited,prevCited:t.cited,prevTotal:t.total,prevDate:t.generated_at.slice(0,10),newlyCited:o,newlyDropped:i}}function Si(e,t){let n=Ht(e.competitors),r=[`- 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"}`,n.length?`- Competitors to track: ${n.join(", ")}`:null].filter(Boolean).join(`
456
456
  `),o=n.length?`
457
457
  4. For EACH question, also record which of these competitor brands appear in the cited sources: ${n.join(", ")}. Use these EXACT names in \`competitorsSurfaced\` (only the ones that actually appear; empty array if none). This powers a share-of-voice comparison.`:"",i=n.length?`,
458
458
  "competitorsSurfaced": [${JSON.stringify(n[0])}]`:`,
@@ -494,10 +494,10 @@ End your reply with EXACTLY ONE fenced \`\`\`json block (and nothing after it) m
494
494
  }
495
495
  \`\`\`
496
496
 
497
- \`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown. \`competitors\` must echo the tracked list exactly (${n.length?n.join(", "):"empty when none were given"}).`}function bi(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=sd(n[o]);if(i)return i}return null}function sd(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,i=Yt(Array.isArray(n.competitors)?n.competitors.map(c=>String(c)):[]),s=new Set(i.map(c=>c.toLowerCase()));if(!Array.isArray(n.results))return null;let a=[];for(let c of n.results){if(!c||typeof c!="object")continue;let u=c,p=typeof u.query=="string"?u.query.trim():"";if(!p)continue;let d=u.surfaced===!0,g=typeof u.rank=="number"&&Number.isFinite(u.rank)?Math.round(u.rank):null,m=typeof u.evidence=="string"?u.evidence.trim():"",v=typeof u.source=="string"&&u.source.trim()?u.source.trim():null,$=Array.isArray(u.competitorsSurfaced)?ad(u.competitorsSurfaced.map(T=>typeof T=="string"?T.trim():"").filter(T=>T&&s.has(T.toLowerCase()))):[];a.push({query:p,surfaced:d,rank:d?g:null,evidence:m,source:v,competitorsSurfaced:$})}return a.length===0?null:{brand:o,domain:r,competitors:i,results:a}}function ad(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}function $i(e,t){let{cited:n,total:r}=st(e),o=t.generatedAt.slice(0,10),i=e.results.some(d=>d.source),s=e.results.map((d,g)=>{let m=d.surfaced?"\u2705":"\u2014",v=d.surfaced&&d.rank?`#${d.rank}`:"\u2014",$=Q(d.evidence||(d.surfaced?"surfaced":"not found")),T=d.source?Q(pi(d.source)):"\u2014";return i?`| ${g+1} | ${Q(d.query)} | ${m} | ${v} | ${T} | ${$} |`:`| ${g+1} | ${Q(d.query)} | ${m} | ${v} | ${$} |`}).join(`
497
+ \`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown. \`competitors\` must echo the tracked list exactly (${n.length?n.join(", "):"empty when none were given"}).`}function vi(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=ud(n[o]);if(i)return i}return null}function ud(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,i=Ht(Array.isArray(n.competitors)?n.competitors.map(c=>String(c)):[]),s=new Set(i.map(c=>c.toLowerCase()));if(!Array.isArray(n.results))return null;let a=[];for(let c of n.results){if(!c||typeof c!="object")continue;let u=c,p=typeof u.query=="string"?u.query.trim():"";if(!p)continue;let d=u.surfaced===!0,g=typeof u.rank=="number"&&Number.isFinite(u.rank)?Math.round(u.rank):null,m=typeof u.evidence=="string"?u.evidence.trim():"",v=typeof u.source=="string"&&u.source.trim()?u.source.trim():null,$=Array.isArray(u.competitorsSurfaced)?dd(u.competitorsSurfaced.map(T=>typeof T=="string"?T.trim():"").filter(T=>T&&s.has(T.toLowerCase()))):[];a.push({query:p,surfaced:d,rank:d?g:null,evidence:m,source:v,competitorsSurfaced:$})}return a.length===0?null:{brand:o,domain:r,competitors:i,results:a}}function dd(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}function xi(e,t){let{cited:n,total:r}=st(e),o=t.generatedAt.slice(0,10),i=e.results.some(d=>d.source),s=e.results.map((d,g)=>{let m=d.surfaced?"\u2705":"\u2014",v=d.surfaced&&d.rank?`#${d.rank}`:"\u2014",$=Q(d.evidence||(d.surfaced?"surfaced":"not found")),T=d.source?Q(gi(d.source)):"\u2014";return i?`| ${g+1} | ${Q(d.query)} | ${m} | ${v} | ${T} | ${$} |`:`| ${g+1} | ${Q(d.query)} | ${m} | ${v} | ${$} |`}).join(`
498
498
  `),a=i?`| # | Query | Cited? | ~Rank | Source cited | Evidence |
499
499
  |---|-------|--------|-------|--------------|----------|`:`| # | Query | Cited? | ~Rank | Evidence |
500
- |---|-------|--------|-------|----------|`,c=e.results.filter(d=>!d.surfaced),u=c.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":c.map(d=>{let g=d.source?` _(currently cited: ${Q(pi(d.source))})_`:"";return`- **${Q(d.query)}** \u2014 ${d.evidence||"not surfaced"}${g}`}).join(`
500
+ |---|-------|--------|-------|----------|`,c=e.results.filter(d=>!d.surfaced),u=c.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":c.map(d=>{let g=d.source?` _(currently cited: ${Q(gi(d.source))})_`:"";return`- **${Q(d.query)}** \u2014 ${d.evidence||"not surfaced"}${g}`}).join(`
501
501
  `),p=c.length?"- 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`---
502
502
  type: Report
503
503
  title: AI Citation Scorecard \u2014 ${e.domain}
@@ -512,11 +512,11 @@ engine: claude-web-grounded
512
512
  > measurement half of the AEO/GEO loop \u2014 \`seoagent okf\` makes you citable, this
513
513
  > tells you whether it's working.
514
514
 
515
- **Cited: ${n} / ${r} queries** \xB7 engine: ${qt} \xB7 ${o}
516
- ${ld(t.trend,n,r)}
515
+ **Cited: ${n} / ${r} queries** \xB7 engine: ${Kt} \xB7 ${o}
516
+ ${pd(t.trend,n,r)}
517
517
  ${a}
518
518
  ${s}
519
- ${cd(e)}
519
+ ${fd(e)}
520
520
  ## Where you're not surfacing (opportunities)
521
521
 
522
522
  ${u}
@@ -540,13 +540,13 @@ This is **not a per-engine guarantee**: ChatGPT, Perplexity, and Gemini each
540
540
  rank and cite differently, and tracking them individually is a planned
541
541
  follow-up. Treat the score as directional \u2014 watch the trend rather than fixating
542
542
  on a single number.
543
- `}function ld(e,t,n){if(!e)return`
543
+ `}function pd(e,t,n){if(!e)return`
544
544
  _First run \u2014 re-run on a cadence to start tracking the trend._
545
545
  `;let r=e.scoreDelta>0?`\u25B2 up ${e.scoreDelta}`:e.scoreDelta<0?`\u25BC down ${Math.abs(e.scoreDelta)}`:"\u25AA no change",o=`
546
546
  **Trend:** ${t}/${n} this run \u2014 ${r} from ${e.prevCited}/${e.prevTotal} on ${e.prevDate}.`;return e.newlyCited.length&&(o+=`
547
547
  - \u2705 Newly cited: ${e.newlyCited.map(i=>`_${Q(i)}_`).join("; ")}`),e.newlyDropped.length&&(o+=`
548
548
  - \u26A0\uFE0F Dropped: ${e.newlyDropped.map(i=>`_${Q(i)}_`).join("; ")}`),o+`
549
- `}function cd(e){if(!e.competitors.length)return"";let t=Hn(e).map(n=>{let r=n.isYou?`**${Q(n.brand)} (you)**`:Q(n.brand),o=n.total>0?`${Math.round(n.surfaced/n.total*100)}%`:"\u2014";return`| ${r} | ${n.surfaced} / ${n.total} | ${o} |`}).join(`
549
+ `}function fd(e){if(!e.competitors.length)return"";let t=Kn(e).map(n=>{let r=n.isYou?`**${Q(n.brand)} (you)**`:Q(n.brand),o=n.total>0?`${Math.round(n.surfaced/n.total*100)}%`:"\u2014";return`| ${r} | ${n.surfaced} / ${n.total} | ${o} |`}).join(`
550
550
  `);return`
551
551
  ## Share of voice
552
552
 
@@ -555,17 +555,17 @@ How often each brand surfaces across the same ${e.results.length} queries.
555
555
  | Brand | Surfaced | Rate |
556
556
  |-------|----------|------|
557
557
  ${t}
558
- `}function pi(e){let t=e.replace(/^https?:\/\//i,"").replace(/\/$/,"");return t.length<=48?t:t.slice(0,47)+"\u2026"}function Q(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function at(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=nt();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){l.warn(ne[r].summary),ne[r].next&&l.message(` ${ne[r].next}`),process.exitCode=1;return}l.info(R.dim(ne[r].summary));let o=Or(t),i=Wt(t),s=Yt(e.competitors&&e.competitors.length?e.competitors:yd(o?.business.competitors)),a={domain:n.domain,name:o?.business.name,type:o?.business.type||n.site_type,description:o?.business.description,hasOkfBundle:i.exists&&i.fileCount>0,competitors:s},c=hi(e.queries);l.message(`${R.cyan("\u25C7")} Auditing AI citations for ${R.bold(a.domain)} \u2014 ${c} web-grounded quer${c===1?"y":"ies"} via ${qt}.`),l.message(R.dim(` This runs live web searches and can take a minute\u2026
559
- `));let u=ki(a,c),p=await md({cwd:t,prompt:u,model:e.model});if(p===null){process.exitCode=1;return}let d=bi(p);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 g=new Date().toISOString(),m=mi(t),v=wd(m),$=wi(d,v),T=$i(d,{generatedAt:g,trend:$});Si(Ht(t),{recursive:!0}),vi(fi(t),T,"utf-8"),Si(m,{recursive:!0}),vi(xi(m,gi(g)),JSON.stringify(yi(d,{generatedAt:g}),null,2)+`
560
- `,"utf-8");let{cited:x,total:F}=st(d),Z=x===0?R.red:x<F?R.yellow:R.green,W=[{content:R.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${R.cyan(d.domain)}`},{content:`Cited: ${Z(`${x} / ${F}`)} ${R.dim("queries")}`}];if($){let re=$.scoreDelta>0?R.green(`\u25B2 +${$.scoreDelta}`):$.scoreDelta<0?R.red(`\u25BC ${$.scoreDelta}`):R.dim("\u25AA 0");W.push({content:`Trend: ${re} ${R.dim(`vs ${$.prevCited}/${$.prevTotal} on ${$.prevDate}`)}`})}else W.push({content:R.dim("Trend: first run \u2014 re-run to start tracking")});if(W.push({content:`Engine: ${R.dim(qt)}`}),d.competitors.length){W.push({sep:!0}),W.push({content:R.dim("Share of voice:")});for(let re of Hn(d)){let mt=re.isYou?R.bold(`${re.brand} (you)`):re.brand;W.push({content:` ${mt}: ${re.surfaced}/${re.total}`})}}W.push({sep:!0}),W.push({content:R.dim(`Saved \u2192 .seoagent/${Wn}/${qn}`)}),W.push({content:x<F?R.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):R.dim("Surfacing across the board. Re-run periodically to catch drift.")}),l.message(I(W,{title:R.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(d,null,2)+`
561
- `)}async function md(e){let{cwd:t,prompt:n,model:r}=e;try{let o=fd({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)gd(c)}else if(s.type==="result"){if(process.stdout.write(`
558
+ `}function gi(e){let t=e.replace(/^https?:\/\//i,"").replace(/\/$/,"");return t.length<=48?t:t.slice(0,47)+"\u2026"}function Q(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function at(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=nt();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){l.warn(ne[r].summary),ne[r].next&&l.message(` ${ne[r].next}`),process.exitCode=1;return}l.info(R.dim(ne[r].summary));let o=Lr(t),i=Wt(t),s=Ht(e.competitors&&e.competitors.length?e.competitors:$d(o?.business.competitors)),a={domain:n.domain,name:o?.business.name,type:o?.business.type||n.site_type,description:o?.business.description,hasOkfBundle:i.exists&&i.fileCount>0,competitors:s},c=ki(e.queries);l.message(`${R.cyan("\u25C7")} Auditing AI citations for ${R.bold(a.domain)} \u2014 ${c} web-grounded quer${c===1?"y":"ies"} via ${Kt}.`),l.message(R.dim(` This runs live web searches and can take a minute\u2026
559
+ `));let u=Si(a,c),p=await wd({cwd:t,prompt:u,model:e.model});if(p===null){process.exitCode=1;return}let d=vi(p);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 g=new Date().toISOString(),m=yi(t),v=Sd(m),$=$i(d,v),T=xi(d,{generatedAt:g,trend:$});_i(qt(t),{recursive:!0}),Ci(hi(t),T,"utf-8"),_i(m,{recursive:!0}),Ci(Ei(m,wi(g)),JSON.stringify(bi(d,{generatedAt:g}),null,2)+`
560
+ `,"utf-8");let{cited:x,total:F}=st(d),Z=x===0?R.red:x<F?R.yellow:R.green,K=[{content:R.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${R.cyan(d.domain)}`},{content:`Cited: ${Z(`${x} / ${F}`)} ${R.dim("queries")}`}];if($){let re=$.scoreDelta>0?R.green(`\u25B2 +${$.scoreDelta}`):$.scoreDelta<0?R.red(`\u25BC ${$.scoreDelta}`):R.dim("\u25AA 0");K.push({content:`Trend: ${re} ${R.dim(`vs ${$.prevCited}/${$.prevTotal} on ${$.prevDate}`)}`})}else K.push({content:R.dim("Trend: first run \u2014 re-run to start tracking")});if(K.push({content:`Engine: ${R.dim(Kt)}`}),d.competitors.length){K.push({sep:!0}),K.push({content:R.dim("Share of voice:")});for(let re of Kn(d)){let mt=re.isYou?R.bold(`${re.brand} (you)`):re.brand;K.push({content:` ${mt}: ${re.surfaced}/${re.total}`})}}K.push({sep:!0}),K.push({content:R.dim(`Saved \u2192 .seoagent/${Gn}/${Wn}`)}),K.push({content:x<F?R.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):R.dim("Surfacing across the board. Re-run periodically to catch drift.")}),l.message(I(K,{title:R.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(d,null,2)+`
561
+ `)}async function wd(e){let{cwd:t,prompt:n,model:r}=e;try{let o=yd({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)kd(c)}else if(s.type==="result"){if(process.stdout.write(`
562
562
  `),!(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(`
563
- `),l.error(` Agent error: ${o.message}`),null}}function gd(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(Mt(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(R.dim(` ${R.magenta("\u{1F50E}")} ${n}${o?` ${hd(o,70)}`:""}
564
- `))}}function hd(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function yd(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function wd(e){try{if(!pd(e))return null;let t=dd(e).filter(o=>o.endsWith(".json")).sort();if(t.length===0)return null;let n=t[t.length-1],r=JSON.parse(ud(xi(e,n),"utf-8"));return r&&typeof r=="object"&&Array.isArray(r.results)&&typeof r.generated_at=="string"?r:null}catch{return null}}import De from"picocolors";async function lt(e={}){if(e.all){await kd();return}let t=process.cwd();if(!L(t))return;ge(t);let n=En(t);Ci(t);let r=await _i(t,{enrichSitemap:!0});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).`)}async function _i(e,t={}){try{let n=_(e),r=n?.domain&&n.domain!=="unknown"?n.domain:null,{pages:o}=se(e,r);t.enrichSitemap&&r&&await zr(o,r);let i=It(e,o);return{added:i.added,total:i.total}}catch{return{added:0,total:0}}}async function kd(){let e=Cr();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 ${De.bold(E)}\u2026`);let t=0,n=0;for(let r of e){let o=En(r);Ci(r);let i=await _i(r),s=i.added>0?De.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?De.dim(` (${o.from} \u2192 ${o.to})`):"";l.message(` ${De.green("\u2713")} ${r}${a}${s}`)}else n++,l.message(` ${De.yellow("!")} ${r} ${De.dim("\u2014 "+o.reason)}${s}`)}l.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${E}.`),n>0&&l.info(`${n} could not be refreshed (see above).`)}function Ci(e){try{me(e)}catch{}}import{spinner as zn,confirm as bd,isCancel as $d}from"@clack/prompts";import y from"picocolors";var Ai={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function Sd(e){let t=process.cwd(),n=lr(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=_(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||A.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?zn():null;a?.start(`Looking up ${y.bold(`"${e.keyword}"`)} ${y.dim("via DataForSEO (free peek)\u2026")}`);let c;try{c=await K(`${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(p){w(a,"error",`Network error: ${p.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})+`
565
- `);return}if(c.status===429||u?.skipped?.startsWith("rate-limited")){let p=u?.skipped==="rate-limited:ip"?"this network":"this install";w(a,"warn",`Daily peek quota reached for ${p}.`,y.yellow(`Daily peek quota reached for ${p}.`)),l.message(Ei()),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(vd(u.opportunity)),u.remaining&&l.message(`${y.dim("Peeks remaining today:")} ${y.bold(String(u.remaining.install))} ${y.dim("\u2014 "+Ei())}`)}function vd(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(xd(e.difficulty))}`:y.dim("n/a"),i=Ai[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 I(a,{width:55,title:c})}function xd(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Ei(e=j()){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 Yn(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 [${Ai[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function _d(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 Cd(e){let t=e.all?"all":"suggested";if(t==="all"&&process.stdin.isTTY){let a=await bd({message:"Delete ALL keywords for this site from the cloud? This cannot be undone."});if($d(a)||!a){l.info("No changes.");return}}let n=e.apiBase||e.auth.api_base||A.BASE,r=process.stdout.isTTY?zn():null;r?.start(t==="all"?"Purging all keywords\u2026":"Purging suggested keywords\u2026");let o;try{o=await K(`${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}`,y.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.",y.yellow("Nothing to purge yet."));return}if(!o.ok||i?.status!=="ok"){w(r,"error",`Purge failed (${o.status})${i?.error?`: ${i.error}`:""}`,y.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"}.`,y.green(`Purged ${s} keyword${s===1?"":"s"}.`)),l.message(y.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 pe(e={}){if(e.peek&&e.peek.trim().length>0){await Sd({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=j();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(e.purge){await Cd({all:e.all,apiBase:e.apiBase,auth:t});return}let n=e.apiBase||t.api_base||A.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?zn():null;c?.start(s);let u=o==="competitors"||o==="discover"||o==="seed",p;try{p=await K(`${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 d=null;try{d=await p.json()}catch{d=null}if(p.status===402||d?.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(A.PRICING)}`:`Upgrade to find new keywords to target: ${y.cyan(A.PRICING)}`),process.exitCode=1;return}if(!p.ok||d?.status!=="ok"){w(c,"error",`Server rejected request (${p.status})${d?.error?`: ${d.error}`:""}`,y.red(`Server rejected request (${p.status}).`)),process.exitCode=1;return}if(d.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(d.skipped==="no-keywords"||d.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(d.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(d.skipped==="no-creds"||d.skipped==="no-columns"||d.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(d.skipped){w(c,"warn",`Skipped: ${d.skipped}`,y.yellow(`Skipped: ${d.skipped}`));return}if(o==="competitors"){let m=d.gaps??0;w(c,"success",`Found ${m} competitor gap${m===1?"":"s"} across ${d.competitors?.length??0} competitor${d.competitors?.length===1?"":"s"} (added as "suggested").`,y.green(`${m} competitor gap${m===1?"":"s"} found.`)),_d(d.topGaps??[]),l.message(`Review them in ${y.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=d.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.`)),Yn(d.opportunities??[]),l.message(`Review them in ${y.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=d.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.`)),Yn(d.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 g=d.enriched??0;w(c,"success",`Enriched ${g} keyword${g===1?"":"s"}.`,y.green(`Enriched ${g} keyword${g===1?"":"s"}.`)),Yn(d.opportunities??[]),d.paid||l.message(`${y.dim("Free plan:")} enriched up to ${y.bold(String(d.cap??25))} keywords. ${y.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${y.cyan(A.PRICING)}`)}import P from"picocolors";function ct(e={}){let t=process.cwd(),n=_(t),r=ie(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
566
- `);return}if(l.message(Ed(r)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}z(t,{image_provider:r.provider}),l.info(`Saved to ${P.cyan(".seoagent/project.md")} ${P.dim(`(image_provider: ${r.provider})`)}`)}function Ed(e){let n=i=>P.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${P.dim("\u25CB")} ${P.bold(P.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:P.dim("Set ONE of these to enable image generation:")});let i=Mr();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${P.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:P.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${P.cyan(f("env-check"))}`})}else{r.push({content:`${P.green("\u2713")} ${P.dim("Image provider:")} ${P.bold(P.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${P.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${P.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${P.dim(i.join(", "))}`})}let o=`${P.bold(P.cyan("SEOAgent"))} ${P.dim("\xB7")} ${P.dim("env-check")}`;return I(r,{width:64,title:o})}import{existsSync as Jn,mkdirSync as Pi,writeFileSync as Oi}from"fs";import{dirname as Vt,isAbsolute as Od,join as zt,resolve as Td}from"path";import{tmpdir as jd}from"os";import{spinner as Ld}from"@clack/prompts";import N from"picocolors";import{Buffer as Ri}from"buffer";async function Vn(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 Ri.from(n)}async function Ad(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:Ri.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await Vn(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function Rd(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 Vn(o.url),contentType:o.content_type??"image/png"}}async function Id(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 Pd(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 Id(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 Vn(o),contentType:"image/png",providerImageId:r.id}}async function Ii(e,t){switch(e){case"openai":return Ad(t);case"fal":return Rd(t);case"replicate":return Pd(t);default:throw new Error(`Unknown image provider: ${e}`)}}function Nd(e){return e==="openai"||e==="fal"||e==="replicate"}async function ut(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=_(t),r=null;if(e.provider){if(!Nd(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=ie(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=Ur(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=Od(e.out)?e.out:Td(t,e.out),a=!e.silent&&!!process.stdout.isTTY?Ld():null;a?.start(`Generating image with ${N.bold(r)} ${N.dim(`(${o.envName})`)}\u2026`);try{let c=await Ii(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Jn(Vt(i))||Pi(Vt(i),{recursive:!0}),Oi(i,c.bytes),e.silent||w(a,"success",`Wrote ${i} (${c.bytes.length} bytes, ${c.contentType}).`,N.green(`Wrote ${i} ${N.dim(`(${c.bytes.length} bytes, ${c.contentType})`)}`))}catch(c){a?.stop(N.red("Image generation failed."));let u=Dd(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(Fd({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:c.message})),u&&l.message(`${N.dim("Full error log:")} ${N.cyan(u)}`),process.exitCode=1}}function Fd(e){let n=p=>N.dim(p.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${N.red("\u2717")} ${N.bold(N.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${N.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${N.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:N.red(c)});let u=`${N.bold(N.cyan("SEOAgent"))} ${N.dim("\xB7")} ${N.dim("generate-image")}`;return I(i,{width:70,title:u})}function Dd(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=zt(e,k),i=zt(o,".errors"),s=Jn(o)?zt(i,r):zt(jd(),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 Jn(Vt(s))||Pi(Vt(s),{recursive:!0}),Oi(s,a.join(`
563
+ `),l.error(` Agent error: ${o.message}`),null}}function kd(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(Ut(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(R.dim(` ${R.magenta("\u{1F50E}")} ${n}${o?` ${bd(o,70)}`:""}
564
+ `))}}function bd(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function $d(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function Sd(e){try{if(!hd(e))return null;let t=gd(e).filter(o=>o.endsWith(".json")).sort();if(t.length===0)return null;let n=t[t.length-1],r=JSON.parse(md(Ei(e,n),"utf-8"));return r&&typeof r=="object"&&Array.isArray(r.results)&&typeof r.generated_at=="string"?r:null}catch{return null}}import De from"picocolors";async function lt(e={}){if(e.all){await vd();return}let t=process.cwd();if(!L(t))return;ge(t);let n=_n(t);Ri(t);let r=await Ai(t,{enrichSitemap:!0});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).`)}async function Ai(e,t={}){try{let n=_(e),r=n?.domain&&n.domain!=="unknown"?n.domain:null,{pages:o}=se(e,r);t.enrichSitemap&&r&&await Xr(o,r);let i=Rt(e,o);return{added:i.added,total:i.total}}catch{return{added:0,total:0}}}async function vd(){let e=Rr();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 ${De.bold(E)}\u2026`);let t=0,n=0;for(let r of e){let o=_n(r);Ri(r);let i=await Ai(r),s=i.added>0?De.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?De.dim(` (${o.from} \u2192 ${o.to})`):"";l.message(` ${De.green("\u2713")} ${r}${a}${s}`)}else n++,l.message(` ${De.yellow("!")} ${r} ${De.dim("\u2014 "+o.reason)}${s}`)}l.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${E}.`),n>0&&l.info(`${n} could not be refreshed (see above).`)}function Ri(e){try{me(e)}catch{}}import{spinner as Hn,confirm as xd,isCancel as _d}from"@clack/prompts";import y from"picocolors";var Pi={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function Cd(e){let t=process.cwd(),n=dr(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=_(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||A.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?Hn():null;a?.start(`Looking up ${y.bold(`"${e.keyword}"`)} ${y.dim("via DataForSEO (free peek)\u2026")}`);let c;try{c=await W(`${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(p){w(a,"error",`Network error: ${p.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})+`
565
+ `);return}if(c.status===429||u?.skipped?.startsWith("rate-limited")){let p=u?.skipped==="rate-limited:ip"?"this network":"this install";w(a,"warn",`Daily peek quota reached for ${p}.`,y.yellow(`Daily peek quota reached for ${p}.`)),l.message(Ii()),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(Ed(u.opportunity)),u.remaining&&l.message(`${y.dim("Peeks remaining today:")} ${y.bold(String(u.remaining.install))} ${y.dim("\u2014 "+Ii())}`)}function Ed(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(Ad(e.difficulty))}`:y.dim("n/a"),i=Pi[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 I(a,{width:55,title:c})}function Ad(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Ii(e=j()){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 qn(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 [${Pi[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function Rd(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 Id(e){let t=e.all?"all":"suggested";if(t==="all"&&process.stdin.isTTY){let a=await xd({message:"Delete ALL keywords for this site from the cloud? This cannot be undone."});if(_d(a)||!a){l.info("No changes.");return}}let n=e.apiBase||e.auth.api_base||A.BASE,r=process.stdout.isTTY?Hn():null;r?.start(t==="all"?"Purging all keywords\u2026":"Purging suggested keywords\u2026");let o;try{o=await W(`${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}`,y.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.",y.yellow("Nothing to purge yet."));return}if(!o.ok||i?.status!=="ok"){w(r,"error",`Purge failed (${o.status})${i?.error?`: ${i.error}`:""}`,y.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"}.`,y.green(`Purged ${s} keyword${s===1?"":"s"}.`)),l.message(y.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 pe(e={}){if(e.peek&&e.peek.trim().length>0){await Cd({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=j();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(e.purge){await Id({all:e.all,apiBase:e.apiBase,auth:t});return}let n=e.apiBase||t.api_base||A.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?Hn():null;c?.start(s);let u=o==="competitors"||o==="discover"||o==="seed",p;try{p=await W(`${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 d=null;try{d=await p.json()}catch{d=null}if(p.status===402||d?.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(A.PRICING)}`:`Upgrade to find new keywords to target: ${y.cyan(A.PRICING)}`),process.exitCode=1;return}if(!p.ok||d?.status!=="ok"){w(c,"error",`Server rejected request (${p.status})${d?.error?`: ${d.error}`:""}`,y.red(`Server rejected request (${p.status}).`)),process.exitCode=1;return}if(d.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(d.skipped==="no-keywords"||d.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(d.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(d.skipped==="no-creds"||d.skipped==="no-columns"||d.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(d.skipped){w(c,"warn",`Skipped: ${d.skipped}`,y.yellow(`Skipped: ${d.skipped}`));return}if(o==="competitors"){let m=d.gaps??0;w(c,"success",`Found ${m} competitor gap${m===1?"":"s"} across ${d.competitors?.length??0} competitor${d.competitors?.length===1?"":"s"} (added as "suggested").`,y.green(`${m} competitor gap${m===1?"":"s"} found.`)),Rd(d.topGaps??[]),l.message(`Review them in ${y.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=d.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.`)),qn(d.opportunities??[]),l.message(`Review them in ${y.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=d.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.`)),qn(d.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 g=d.enriched??0;w(c,"success",`Enriched ${g} keyword${g===1?"":"s"}.`,y.green(`Enriched ${g} keyword${g===1?"":"s"}.`)),qn(d.opportunities??[]),d.paid||l.message(`${y.dim("Free plan:")} enriched up to ${y.bold(String(d.cap??25))} keywords. ${y.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${y.cyan(A.PRICING)}`)}import P from"picocolors";function ct(e={}){let t=process.cwd(),n=_(t),r=ie(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
566
+ `);return}if(l.message(Pd(r)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}V(t,{image_provider:r.provider}),l.info(`Saved to ${P.cyan(".seoagent/project.md")} ${P.dim(`(image_provider: ${r.provider})`)}`)}function Pd(e){let n=i=>P.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${P.dim("\u25CB")} ${P.bold(P.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:P.dim("Set ONE of these to enable image generation:")});let i=Wr();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${P.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:P.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${P.cyan(f("env-check"))}`})}else{r.push({content:`${P.green("\u2713")} ${P.dim("Image provider:")} ${P.bold(P.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${P.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${P.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${P.dim(i.join(", "))}`})}let o=`${P.bold(P.cyan("SEOAgent"))} ${P.dim("\xB7")} ${P.dim("env-check")}`;return I(r,{width:64,title:o})}import{existsSync as Vn,mkdirSync as ji,writeFileSync as Li}from"fs";import{dirname as Vt,isAbsolute as Nd,join as Yt,resolve as Fd}from"path";import{tmpdir as Dd}from"os";import{spinner as Ud}from"@clack/prompts";import N from"picocolors";import{Buffer as Oi}from"buffer";async function Yn(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 Od(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 Yn(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function Td(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 Yn(o.url),contentType:o.content_type??"image/png"}}async function jd(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 Ld(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 jd(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 Yn(o),contentType:"image/png",providerImageId:r.id}}async function Ti(e,t){switch(e){case"openai":return Od(t);case"fal":return Td(t);case"replicate":return Ld(t);default:throw new Error(`Unknown image provider: ${e}`)}}function Md(e){return e==="openai"||e==="fal"||e==="replicate"}async function ut(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=_(t),r=null;if(e.provider){if(!Md(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=ie(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=Gr(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=Nd(e.out)?e.out:Fd(t,e.out),a=!e.silent&&!!process.stdout.isTTY?Ud():null;a?.start(`Generating image with ${N.bold(r)} ${N.dim(`(${o.envName})`)}\u2026`);try{let c=await Ti(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Vn(Vt(i))||ji(Vt(i),{recursive:!0}),Li(i,c.bytes),e.silent||w(a,"success",`Wrote ${i} (${c.bytes.length} bytes, ${c.contentType}).`,N.green(`Wrote ${i} ${N.dim(`(${c.bytes.length} bytes, ${c.contentType})`)}`))}catch(c){a?.stop(N.red("Image generation failed."));let u=Gd(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(Bd({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:c.message})),u&&l.message(`${N.dim("Full error log:")} ${N.cyan(u)}`),process.exitCode=1}}function Bd(e){let n=p=>N.dim(p.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${N.red("\u2717")} ${N.bold(N.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${N.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${N.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:N.red(c)});let u=`${N.bold(N.cyan("SEOAgent"))} ${N.dim("\xB7")} ${N.dim("generate-image")}`;return I(i,{width:70,title:u})}function Gd(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=Yt(e,k),i=Yt(o,".errors"),s=Vn(o)?Yt(i,r):Yt(Dd(),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 Vn(Vt(s))||ji(Vt(s),{recursive:!0}),Li(s,a.join(`
567
567
  `)),s}catch{return null}}import G from"picocolors";async function dt(e={}){let t=j();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
568
568
  `):l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||A.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})}
569
569
  `);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}`})}
570
570
  `):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)}
571
- `);return}l.message(Ud(i)),i.paid===!1&&l.message(`${G.dim("Upgrade for autopilot:")} ${G.cyan(A.PRICING)}`)}function Ud(e){let n=i=>G.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${G.green("\u2713")} ${G.dim("Logged in as")} ${G.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${G.cyan(e.domain)}`}),e.plan){let i=e.paid?G.bold(G.green(e.plan)):G.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${G.dim(e.api_base)}`});let o=`${G.bold(G.cyan("SEOAgent"))} ${G.dim("\xB7")} ${G.dim("whoami")}`;return I(r,{width:55,title:o})}import{select as ft,text as pt,confirm as Li,isCancel as Y,intro as Md,outro as Bd}from"@clack/prompts";import Jt from"picocolors";function Gd(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>Je()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await H()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await Ye()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await et()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await dt()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await ft({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(!Y(e))if(e==="peek"){let t=await pt({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(Y(t))return;await pe({peek:String(t)})}else e==="discover"?await pe({discover:!0}):e==="competitors"?await pe({competitors:!0}):await pe()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>ot({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await ft({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"}]});Y(e)||it(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 at()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await pt({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(Y(e))return;let t=await pt({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});Y(t)||await ut({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>ct({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await ft({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"}]});Y(e)||await rt(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await $e()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await pt({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(Y(e))return;let t=await Li({message:"Mark as failed instead of completed?",initialValue:!1});if(Y(t))return;let n;if(t===!0){let r=await pt({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(Y(r))return;String(r).trim()&&(n=String(r))}await ue(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 Qe()},{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 Ze({})},{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 ft({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"}]});Y(e)||lt({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>tt()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await ze({})}]}var Ti="__exit__";async function ji(e=Gd()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:Ti,label:"Exit",hint:"Close the menu"});let n=await ft({message:"What would you like to do?",options:t});if(Y(n)||n===Ti)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 Xn(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}Md(`${Jt.bold(Jt.cyan("SEOAgent"))} ${Jt.dim("\xB7 menu")}`);let e=await ji();for(;!e;){let t=await Li({message:"Do another?",initialValue:!0});if(Y(t)||t===!1){e=!0;break}e=await ji()}Bd(Jt.dim("See you next time."))}var C=new Kd;C.name("seoagent").description("AI SEO agent for Claude Code").version(E).showSuggestionAfterError(!0).showHelpAfterError(!0);C.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=>{Ye({yes:e.yes,domain:e.domain,siteType:e.siteType})});C.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=>{ze({yes:e.yes,global:e.global})});C.command("status").description("Show current SEO project state").action(Je);C.command("doctor").description("Session-start health check \u2014 surfaces untriaged pull receipts, unknown domain/site_type, and an image key that needs enabling").option("--json","Output findings as JSON (for scripting / the agent)").action(e=>{Un({json:e.json})});C.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=>{et({apiBase:e.apiBase})});C.command("logout").description("Remove stored credentials for seoagent.com").action(tt);C.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=>{H({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});C.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=>{$e({force:e.force,silent:e.silent,print:e.print})});C.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)=>{ue(e,{failed:t.failed,reason:t.reason})});C.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{Rn({json:e.json})});C.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=>{Tn({yes:e.yes,model:e.model})});C.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)=>{rt(e,{apiBase:t.apiBase})});C.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=>{pe({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});C.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=>{ot({json:e.json})});C.command("content [action]").description("Track a published article so the dashboard sees it \u2014 `content track --slug <s> --url <live-url> [--file <repo-path>]` (no body duplication)").option("--slug <slug>","Article slug (or derive from --file)").option("--url <url>","Live/canonical URL (else built from project domain + blog_path + slug)").option("--file <path>","Repo/CMS source file that renders this article (the body source of truth)").option("--title <title>","Article title (else derived from the slug)").option("--type <page_type>","page_type: landing | pillar | sub_pillar | long_tail | programmatic | blog").option("--status <status>","published (default) | draft").option("--primary-keyword <kw>","Primary keyword for the article").action((e,t)=>{Fn(e,{slug:t.slug,url:t.url,file:t.file,title:t.title,type:t.type,status:t.status,primaryKeyword:t.primaryKeyword})});C.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)=>{it(e,{json:t.json})});C.command("sitemap").description("Validate the site\u2019s live sitemap \u2014 reachability, private-route leakage, freshness, and which public repo pages are missing").option("--url <url>","Override the sitemap URL (default https://{domain}/sitemap.xml)").option("--json","Output result as JSON").action(e=>{Gn({url:e.url,json:e.json})});C.command("citations").description("Track whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK, with history, share-of-voice + source-attribution \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--competitors <list>","Comma-separated competitor brands to track for share-of-voice").option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{at({queries:e.queries,competitors:typeof e.competitors=="string"?e.competitors.split(",").map(t=>t.trim()).filter(Boolean):void 0,model:e.model,json:e.json})});C.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{ct({json:e.json})});C.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=>{ut({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});C.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=>{dt({json:e.json,apiBase:e.apiBase})});C.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(Qe);C.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=>{Ze({dryRun:e.dryRun,projects:e.projects})});C.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=>{lt({all:e.all})});C.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Xn()});process.argv.length===2&&(C.outputHelp(),process.exit(0));C.parse();
571
+ `);return}l.message(Wd(i)),i.paid===!1&&l.message(`${G.dim("Upgrade for autopilot:")} ${G.cyan(A.PRICING)}`)}function Wd(e){let n=i=>G.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${G.green("\u2713")} ${G.dim("Logged in as")} ${G.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${G.cyan(e.domain)}`}),e.plan){let i=e.paid?G.bold(G.green(e.plan)):G.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${G.dim(e.api_base)}`});let o=`${G.bold(G.cyan("SEOAgent"))} ${G.dim("\xB7")} ${G.dim("whoami")}`;return I(r,{width:55,title:o})}import{select as ft,text as pt,confirm as Di,isCancel as Y,intro as Kd,outro as qd}from"@clack/prompts";import zt from"picocolors";function Hd(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>Je()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await H()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await Ye()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await et()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await dt()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await ft({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(!Y(e))if(e==="peek"){let t=await pt({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(Y(t))return;await pe({peek:String(t)})}else e==="discover"?await pe({discover:!0}):e==="competitors"?await pe({competitors:!0}):await pe()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>ot({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await ft({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"}]});Y(e)||it(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 at()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await pt({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(Y(e))return;let t=await pt({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});Y(t)||await ut({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>ct({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await ft({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"}]});Y(e)||await rt(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await $e()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await pt({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(Y(e))return;let t=await Di({message:"Mark as failed instead of completed?",initialValue:!1});if(Y(t))return;let n;if(t===!0){let r=await pt({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(Y(r))return;String(r).trim()&&(n=String(r))}await ue(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 Qe()},{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 Ze({})},{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 ft({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"}]});Y(e)||lt({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>tt()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await Ve({})}]}var Ni="__exit__";async function Fi(e=Hd()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:Ni,label:"Exit",hint:"Close the menu"});let n=await ft({message:"What would you like to do?",options:t});if(Y(n)||n===Ni)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 zn(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}Kd(`${zt.bold(zt.cyan("SEOAgent"))} ${zt.dim("\xB7 menu")}`);let e=await Fi();for(;!e;){let t=await Di({message:"Do another?",initialValue:!0});if(Y(t)||t===!1){e=!0;break}e=await Fi()}qd(zt.dim("See you next time."))}var C=new Yd;C.name("seoagent").description("AI SEO agent for Claude Code").version(E).showSuggestionAfterError(!0).showHelpAfterError(!0);C.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=>{Ye({yes:e.yes,domain:e.domain,siteType:e.siteType})});C.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=>{Ve({yes:e.yes,global:e.global})});C.command("status").description("Show current SEO project state").action(Je);C.command("doctor").description("Session-start health check \u2014 surfaces untriaged pull receipts, unknown domain/site_type, and an image key that needs enabling").option("--json","Output findings as JSON (for scripting / the agent)").action(e=>{Fn({json:e.json})});C.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=>{et({apiBase:e.apiBase})});C.command("logout").description("Remove stored credentials for seoagent.com").action(tt);C.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=>{H({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});C.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=>{$e({force:e.force,silent:e.silent,print:e.print})});C.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)=>{ue(e,{failed:t.failed,reason:t.reason})});C.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{En({json:e.json})});C.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=>{Pn({yes:e.yes,model:e.model})});C.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)=>{rt(e,{apiBase:t.apiBase})});C.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=>{pe({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});C.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=>{ot({json:e.json})});C.command("content [action]").description("Track a published article so the dashboard sees it \u2014 `content track --slug <s> --url <live-url> [--file <repo-path>]` (no body duplication)").option("--slug <slug>","Article slug (or derive from --file)").option("--url <url>","Live/canonical URL (else built from project domain + blog_path + slug)").option("--file <path>","Repo/CMS source file that renders this article (the body source of truth)").option("--title <title>","Article title (else derived from the slug)").option("--type <page_type>","page_type: landing | pillar | sub_pillar | long_tail | programmatic | blog").option("--status <status>","published (default) | draft").option("--primary-keyword <kw>","Primary keyword for the article").action((e,t)=>{Ln(e,{slug:t.slug,url:t.url,file:t.file,title:t.title,type:t.type,status:t.status,primaryKeyword:t.primaryKeyword})});C.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)=>{it(e,{json:t.json})});C.command("sitemap").description("Validate the site\u2019s live sitemap \u2014 reachability, private-route leakage, freshness, and which public repo pages are missing").option("--url <url>","Override the sitemap URL (default https://{domain}/sitemap.xml)").option("--json","Output result as JSON").action(e=>{Mn({url:e.url,json:e.json})});C.command("citations").description("Track whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK, with history, share-of-voice + source-attribution \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--competitors <list>","Comma-separated competitor brands to track for share-of-voice").option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{at({queries:e.queries,competitors:typeof e.competitors=="string"?e.competitors.split(",").map(t=>t.trim()).filter(Boolean):void 0,model:e.model,json:e.json})});C.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{ct({json:e.json})});C.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=>{ut({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});C.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=>{dt({json:e.json,apiBase:e.apiBase})});C.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(Qe);C.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=>{Ze({dryRun:e.dryRun,projects:e.projects})});C.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=>{lt({all:e.all})});C.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{zn()});process.argv.length===2&&(C.outputHelp(),process.exit(0));C.parse();