@seoagent-official/seoagent 1.59.0 → 1.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,40 +1,40 @@
1
1
  #!/usr/bin/env node
2
- import{Command as pd}from"commander";import{dirname as Gr,relative as xt}from"path";import{intro as Ws,outro as qs,text as Ur,select as rn,spinner as Hs,isCancel as xe,cancel as _e,confirm as Ys}from"@clack/prompts";var he=[".env.local",".env.production",".env"],Bn=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var V="@seoagent-official/seoagent",ct=`${V}@latest`;import{homedir as wi}from"os";import{join as ye}from"path";var k=".seoagent",Gn=["audit","strategy/clusters","briefs","content","content/images","performance"],le={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},ut=".claude/settings.json",dt=".pull-receipt.json",Kn=".ack-queue.json",Wn=".sync.lock",qn=`# SEOAgent local files
2
+ import{Command as Pd}from"commander";import{dirname as Yr,relative as Rt}from"path";import{intro as ta,outro as na,text as Wr,select as dn,spinner as ra,isCancel as Ee,cancel as Ae,confirm as oa}from"@clack/prompts";var ke=[".env.local",".env.production",".env"],Hn=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var Z="@seoagent-official/seoagent",mt=`${Z}@latest`;import{homedir as Ri}from"os";import{join as be}from"path";var k=".seoagent",Yn=["audit","strategy/clusters","briefs","content","content/images","performance"],de={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},gt=".claude/settings.json",ht=".pull-receipt.json",zn=".ack-queue.json",Jn=".sync.lock",Vn=`# 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
- `,ki=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:ye(wi(),".config"),F=ye(ki,"seoagent"),Z=ye(F,"auth.json"),Kt=ye(F,"state"),pt=ye(F,"update-check.json"),ft=ye(F,"projects.json");var Le="https://seoagent.com",we=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):Le,E={BASE:we,PRICING:`${we}/pricing`,LEAD_API:`${we}/api/cli/lead`,CLI_AUTH_PAGE:`${we}/cli/auth`,CLI_AUTH_POLL:`${we}/api/cli/auth/poll`,CLI_SYNC:`${we}/api/cli/sync`};import{readFileSync as bi}from"fs";import{fileURLToPath as $i}from"url";import{dirname as Si,join as vi}from"path";var Hn="0.0.0";function xi(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return Hn}function _i(e=t=>bi(t,"utf-8")){try{let t=Si($i(import.meta.url));return xi(e(vi(t,"package.json")))}catch{return Hn}}var C=_i();function Wt(e=process.argv[1]){let t=process.env.SEOAGENT_INSTALL_FORM;return t==="global"?!0:t==="npx"||!e?!1:(e.split(/[/\\]/).pop()??"").replace(/\.(cmd|ps1|exe)$/i,"").toLowerCase()==="seoagent"}function f(e,t=Wt()){return t?`seoagent ${e}`:`npx -y ${ct} ${e}`}import{randomUUID as Ri}from"crypto";import{existsSync as Yn,mkdirSync as zn,readFileSync as Pi,writeFileSync as Jn}from"fs";import{join as Ht}from"path";import{existsSync as Ci,readFileSync as Ei}from"fs";var mt="---";function Ai(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 Ne(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==mt)return{data:{},body:e};let n={},r=1;for(;r<t.length;r++){if(t[r].trim()===mt){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]=Ai(a))}return{data:n,body:t.slice(r).join(`
10
- `)}}function gt(e){if(!Ci(e))return null;try{return Ne(Ei(e,"utf-8"))}catch{return null}}function Ii(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 qt(e,t=""){let n=[mt];for(let[o,i]of Object.entries(e))i!==void 0&&n.push(`${o}: ${Ii(i)}`);n.push(mt);let r=t.length===0?"":t.startsWith(`
9
+ `,Ii=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:be(Ri(),".config"),U=be(Ii,"seoagent"),re=be(U,"auth.json"),Vt=be(U,"state"),yt=be(U,"update-check.json"),wt=be(U,"projects.json");var De="https://seoagent.com",$e=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):De,A={BASE:$e,PRICING:`${$e}/pricing`,LEAD_API:`${$e}/api/cli/lead`,CLI_AUTH_PAGE:`${$e}/cli/auth`,CLI_AUTH_POLL:`${$e}/api/cli/auth/poll`,CLI_SYNC:`${$e}/api/cli/sync`};import{readFileSync as Pi}from"fs";import{fileURLToPath as Oi}from"url";import{dirname as Ti,join as ji}from"path";var Qn="0.0.0";function Li(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return Qn}function Ni(e=t=>Pi(t,"utf-8")){try{let t=Ti(Oi(import.meta.url));return Li(e(ji(t,"package.json")))}catch{return Qn}}var E=Ni();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 ${mt} ${e}`}import{randomUUID as Bi}from"crypto";import{existsSync as Xn,mkdirSync as Zn,readFileSync as Gi,writeFileSync as er}from"fs";import{join as Zt}from"path";import{existsSync as Fi,readFileSync as Di}from"fs";var kt="---";function Ui(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 Ue(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==kt)return{data:{},body:e};let n={},r=1;for(;r<t.length;r++){if(t[r].trim()===kt){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]=Ui(a))}return{data:n,body:t.slice(r).join(`
10
+ `)}}function bt(e){if(!Fi(e))return null;try{return Ue(Di(e,"utf-8"))}catch{return null}}function Mi(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 Xt(e,t=""){let n=[kt];for(let[o,i]of Object.entries(e))i!==void 0&&n.push(`${o}: ${Mi(i)}`);n.push(kt);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 Oi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Yt(){return Ri()}var Ti=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),ji="project.md";function Fe(e){return Ht(e,k)}function ht(e){return Ht(Fe(e),ji)}function Vn(e){return Yn(ht(e))}function S(e){let t=gt(ht(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&&Ti.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&&Oi.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 Qn(e){let t=S(e);if(!t)return null;if(t.install_id)return t.install_id;let n=Yt();return W(e,{install_id:n}),n}function Li(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 Ni(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 Xn(e,t){let n=Fe(e);zn(n,{recursive:!0});let r=qt(Ni(t),Li(t));Jn(ht(e),r,"utf-8")}function W(e,t){let n=ht(e);if(!Yn(n))return!1;let r=Ne(Pi(n,"utf-8")),o={...r.data,...t};return Jn(n,qt(o,r.body),"utf-8"),!0}function Zn(e){let t=Fe(e);for(let n of Gn)zn(Ht(t,n),{recursive:!0})}import{existsSync as yt,lstatSync as Fi,mkdirSync as De,readFileSync as er,readdirSync as Di,rmSync as Ui,statSync as Mi,symlinkSync as Bi,writeFileSync as tr}from"fs";import{dirname as wt,join as H,relative as nr}from"path";import{fileURLToPath as Gi}from"url";var Ki=wt(Gi(import.meta.url));function rr(){return H(Ki,"skills")}function Wi(){let e=H(rr(),"seoagent.md");if(yt(e))return er(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function or(e,t){let n=[];if(!yt(e))return n;for(let r of Di(e,{withFileTypes:!0})){let o=H(e,r.name),i=H(t,r.name);r.isDirectory()?(De(i,{recursive:!0}),n.push(...or(o,i))):r.isFile()&&(De(wt(i),{recursive:!0}),tr(i,er(o)),n.push(i))}return n}function ke(e,t){let n=yt(H(e,".agents")),r=H(e,n?le.AGENTS:le.CLAUDE),o=H(r,"SKILL.md");De(r,{recursive:!0}),tr(o,t??Wi(),"utf-8");let i=H(rr(),"references"),s=H(r,"references"),a=[];try{yt(i)&&Mi(i).isDirectory()&&(De(s,{recursive:!0}),a=or(i,s).map(u=>nr(r,u)))}catch{}let c=n?qi(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:c}}function qi(e,t){let n=H(e,le.CLAUDE),r=null;try{r=Fi(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{Ui(n,{force:!0})}catch{return}}try{De(wt(n),{recursive:!0});let o=nr(wt(n),t);return Bi(o,n,"dir"),n}catch{return}}import{existsSync as bt,mkdirSync as zt,readFileSync as Hi,writeFileSync as kt}from"fs";import{dirname as sr,join as be}from"path";var Yi=`npx -y ${ct} sync --silent`;function ar(e){let t=be(e,k);zt(t,{recursive:!0});let n=be(t,".gitignore");kt(n,qn,"utf-8");let r=be(t,"content","images",".gitkeep");return zt(sr(r),{recursive:!0}),bt(r)||kt(r,"","utf-8"),n}var lr=["PostToolUse","SessionStart"];function Jt(e){if(!bt(e))return{};try{let t=Hi(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Vt(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function ir(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(Vt)?!1:(r.hooks.push({type:"command",command:Yi}),!0)}function ce(e){let t=be(e,ut);zt(sr(t),{recursive:!0});let n=Jt(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=ir(r,a=>(a.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),i=n.hooks.SessionStart=n.hooks.SessionStart??[],s=ir(i,a=>(a.matcher??"")==="",()=>({hooks:[]}));return kt(t,JSON.stringify(n,null,2)+`
17
- `,"utf-8"),{file:t,added:o||s}}function cr(e){let t=be(e,ut);if(!bt(t))return!1;let n=Jt(t).hooks;return n?lr.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(Vt))}):!1}function ur(e){let t=be(e,ut);if(!bt(t))return{file:t,removed:!1};let n=Jt(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of lr){let s=r[i];if(!Array.isArray(s))continue;for(let c of s){let u=c.hooks.length;c.hooks=c.hooks.filter(d=>!Vt(d)),c.hooks.length!==u&&(o=!0)}let a=s.filter(c=>c.hooks.length>0);a.length===0?delete r[i]:r[i]=a}return o?(Object.keys(r).length===0&&delete n.hooks,kt(t,JSON.stringify(n,null,2)+`
18
- `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as dr,mkdirSync as zi,readFileSync as Ji,writeFileSync as Vi}from"fs";import{join as Qi}from"path";function pr(e){return dr(Qi(e,k,"project.md"))}function fr(){try{if(!dr(ft))return[];let e=JSON.parse(Ji(ft,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function mr(e){try{zi(F,{recursive:!0}),Vi(ft,JSON.stringify({projects:e},null,2)+`
19
- `,"utf-8")}catch{}}function ue(e){try{if(!pr(e))return;let t=fr();if(t.includes(e))return;t.push(e),mr(t)}catch{}}function gr(){let e=fr(),t=e.filter(pr);return t.length!==e.length&&mr(t),t}import{readFileSync as ts,writeFileSync as ns,existsSync as rs}from"fs";import{join as kr}from"path";function yr(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=Xi(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=Zi(o):i==="writing instructions"?t.writingInstructions=hr(o):i==="reference urls"?t.referenceUrls=es(o):i==="topics to avoid"?t.topicsToAvoid=hr(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function wr(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 Xi(e){let t=e.split(`
15
+ `)}var Ki=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function en(){return Bi()}var Wi=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),qi="project.md";function Me(e){return Zt(e,k)}function $t(e){return Zt(Me(e),qi)}function tr(e){return Xn($t(e))}function _(e){let t=bt($t(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&&Wi.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&&Ki.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 nr(e){let t=_(e);if(!t)return null;if(t.install_id)return t.install_id;let n=en();return H(e,{install_id:n}),n}function Hi(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 Yi(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 rr(e,t){let n=Me(e);Zn(n,{recursive:!0});let r=Xt(Yi(t),Hi(t));er($t(e),r,"utf-8")}function H(e,t){let n=$t(e);if(!Xn(n))return!1;let r=Ue(Gi(n,"utf-8")),o={...r.data,...t};return er(n,Xt(o,r.body),"utf-8"),!0}function or(e){let t=Me(e);for(let n of Yn)Zn(Zt(t,n),{recursive:!0})}import{existsSync as St,lstatSync as zi,mkdirSync as Be,readFileSync as ir,readdirSync as Ji,rmSync as Vi,statSync as Qi,symlinkSync as Xi,writeFileSync as sr}from"fs";import{dirname as vt,join as z,relative as ar}from"path";import{fileURLToPath as Zi}from"url";var es=vt(Zi(import.meta.url));function cr(){return z(es,"skills")}function ts(){let e=z(cr(),"seoagent.md");if(St(e))return ir(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function lr(e,t){let n=[];if(!St(e))return n;for(let r of Ji(e,{withFileTypes:!0})){let o=z(e,r.name),i=z(t,r.name);r.isDirectory()?(Be(i,{recursive:!0}),n.push(...lr(o,i))):r.isFile()&&(Be(vt(i),{recursive:!0}),sr(i,ir(o)),n.push(i))}return n}function Se(e,t){let n=St(z(e,".agents")),r=z(e,n?de.AGENTS:de.CLAUDE),o=z(r,"SKILL.md");Be(r,{recursive:!0}),sr(o,t??ts(),"utf-8");let i=z(cr(),"references"),s=z(r,"references"),a=[];try{St(i)&&Qi(i).isDirectory()&&(Be(s,{recursive:!0}),a=lr(i,s).map(u=>ar(r,u)))}catch{}let l=n?ns(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:l}}function ns(e,t){let n=z(e,de.CLAUDE),r=null;try{r=zi(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{Vi(n,{force:!0})}catch{return}}try{Be(vt(n),{recursive:!0});let o=ar(vt(n),t);return Xi(o,n,"dir"),n}catch{return}}import{existsSync as _t,mkdirSync as tn,readFileSync as rs,writeFileSync as xt}from"fs";import{dirname as dr,join as ve}from"path";var os=`npx -y ${mt} sync --silent`;function pr(e){let t=ve(e,k);tn(t,{recursive:!0});let n=ve(t,".gitignore");xt(n,Vn,"utf-8");let r=ve(t,"content","images",".gitkeep");return tn(dr(r),{recursive:!0}),_t(r)||xt(r,"","utf-8"),n}var fr=["PostToolUse","SessionStart"];function nn(e){if(!_t(e))return{};try{let t=rs(e,"utf-8");return JSON.parse(t)}catch{return{}}}function rn(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function ur(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(rn)?!1:(r.hooks.push({type:"command",command:os}),!0)}function pe(e){let t=ve(e,gt);tn(dr(t),{recursive:!0});let n=nn(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=ur(r,a=>(a.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),i=n.hooks.SessionStart=n.hooks.SessionStart??[],s=ur(i,a=>(a.matcher??"")==="",()=>({hooks:[]}));return xt(t,JSON.stringify(n,null,2)+`
17
+ `,"utf-8"),{file:t,added:o||s}}function mr(e){let t=ve(e,gt);if(!_t(t))return!1;let n=nn(t).hooks;return n?fr.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(rn))}):!1}function gr(e){let t=ve(e,gt);if(!_t(t))return{file:t,removed:!1};let n=nn(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of fr){let s=r[i];if(!Array.isArray(s))continue;for(let l of s){let u=l.hooks.length;l.hooks=l.hooks.filter(p=>!rn(p)),l.hooks.length!==u&&(o=!0)}let a=s.filter(l=>l.hooks.length>0);a.length===0?delete r[i]:r[i]=a}return o?(Object.keys(r).length===0&&delete n.hooks,xt(t,JSON.stringify(n,null,2)+`
18
+ `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as hr,mkdirSync as is,readFileSync as ss,writeFileSync as as}from"fs";import{join as cs}from"path";function yr(e){return hr(cs(e,k,"project.md"))}function wr(){try{if(!hr(wt))return[];let e=JSON.parse(ss(wt,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function kr(e){try{is(U,{recursive:!0}),as(wt,JSON.stringify({projects:e},null,2)+`
19
+ `,"utf-8")}catch{}}function fe(e){try{if(!yr(e))return;let t=wr();if(t.includes(e))return;t.push(e),kr(t)}catch{}}function br(){let e=wr(),t=e.filter(yr);return t.length!==e.length&&kr(t),t}import{readFileSync as ps,writeFileSync as fs,existsSync as ms}from"fs";import{join as xr}from"path";function Sr(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=ls(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=us(o):i==="writing instructions"?t.writingInstructions=$r(o):i==="reference urls"?t.referenceUrls=ds(o):i==="topics to avoid"?t.topicsToAvoid=$r(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function vr(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 ls(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 Zi(e){let t={},n=e.split(`
24
- `);for(let r of n){let o=r.match(/^[-*]\s+\*\*(.+?):\*\*\s*(.*)$/);if(o){let i=o[1].toLowerCase().trim(),s=o[2].trim();s&&(t[i]=s)}}return t}function hr(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 es(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 br="context.md";function $r(e){let t=kr(e,".seoagent",br);if(!rs(t))return null;let n=ts(t,"utf-8");return yr(n)}function os(e,t){let n=kr(e,".seoagent",br),r=wr(t);ns(n,r,"utf-8")}function Sr(e,t){os(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as Ue,readFileSync as vr,readdirSync as is,statSync as xr}from"fs";import{join as de}from"path";var ss=[{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 as(e){let t=de(e,"package.json");if(!Ue(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(vr(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function ls(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 cs(e){let t={};for(let n of he){let r=de(e,n);if(Ue(r))try{let o=vr(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 us(e,t){let n=de(e,t.replace(/\/$/,""));if(!Ue(n))return!1;if(t.endsWith("/"))try{return xr(n).isDirectory()}catch{return!1}return!0}function ds(e){let t=["content","_posts","posts",de("src","content")];for(let n of t){let r=de(e,n);if(Ue(r))try{if(!xr(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of is(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(de(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(Ue(de(e,n.marker)))return n.path;return null}function _r(e){let t=[],{deps:n}=as(e),r=cs(e),o="none";for(let s of ss){let a=[];for(let c of Object.keys(n))if(ls(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(us(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=ds(e);s&&(o="mdx-local",t.push(s))}let i=ps(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as fs,readFileSync as ms}from"fs";import{join as gs}from"path";var Cr=["openai","fal","replicate"],$e={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function hs(e){let t={};if(!fs(e))return t;let n=ms(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 Er(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 he){let o=gs(e,r),i=hs(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 ee(e){let t=[].concat(...Cr.map(a=>$e[a])),n=Er(e,t),r=[];for(let a of Cr)$e[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=$e[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 Ar(e,t){let n=Er(e,$e[t]);for(let r of $e[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Ir(){return $e}import{existsSync as pe,readFileSync as Qt}from"fs";import{join as fe}from"path";function Rr(e){try{return new URL(e).hostname}catch{return e}}function Pr(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 ys(e){for(let t of he){let n=fe(e,t);if(!pe(n))continue;let r=Qt(n,"utf-8");for(let o of Bn){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Rr(s);if(Pr(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function ws(e){let t=fe(e,"package.json");if(!pe(t))return null;try{let n=JSON.parse(Qt(t,"utf-8"));if(!n.homepage)return null;let r=Rr(n.homepage);return Pr(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function Or(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),pe(fe(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=ys(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=ws(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=fe(e,"package.json"),s=null;if(pe(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Qt(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>c.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||pe(fe(e,"shopify.config.js"))||pe(fe(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":pe(fe(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),y=u("next");d&&(y||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:y?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:r,siteType:s,evidence:n}}import{existsSync as ks,readFileSync as en,readdirSync as Tr,statSync as bs}from"fs";import{join as B,sep as $s}from"path";var jr=["tsx","jsx","js","mdx","md"],Ss=["astro","md","mdx"],vs=5e3;function Se(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=As(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:Ns(t,c),in_sitemap:a,source:s})};for(let i of _s(e))xs(i,o);return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}function xs(e,t){for(let n of["app",B("src","app")]){let r=B(e,n);if(Me(r))for(let o of Xt(r)){let i=Zt(r,o),s=i[i.length-1];Ts(s)&&(i.some(a=>a.startsWith("@"))||t(Is(i.slice(0,-1)),"app router"))}}for(let n of["pages",B("src","pages")]){let r=B(e,n);if(Me(r))for(let o of Xt(r)){let i=Zt(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=tn(s),c=jr.includes(a),u=Ss.includes(a);if(!c&&!u)continue;let d=$t(s);js(d)||t(Rs(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=B(e,n);if(Me(r))for(let o of Xt(r,n==="."?1:1/0)){let i=Zt(r,o),s=i[i.length-1];tn(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(Ps(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=B(e,...n.split("/"));if(ks(r)){for(let o of Ls(r)){let i=Os(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function _s(e){let t=[e],n=new Set([e]);for(let r of Cs(e))for(let o of Es(e,r))n.has(o)||(n.add(o),t.push(o));return t}function Cs(e){let t=[];try{let n=en(B(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(en(B(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 Es(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=B(e,...n.split("/").filter(Boolean));return Me(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=B(e,...o.split("/").filter(Boolean));if(!Me(i))return[];let s=[];try{for(let a of Tr(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!Lr.has(a.name)&&(s.push(B(i,a.name)),s.length>=200))break}catch{}return s}function As(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function Is(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function Rs(e){let t=[...e],n=$t(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Ps(e){let t=[...e],n=$t(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Os(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function Ts(e){return $t(e)==="page"&&jr.includes(tn(e))}function js(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Ls(e){try{let t=en(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 Lr=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Me(e){try{return bs(e).isDirectory()}catch{return!1}}function*Xt(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=Tr(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=vs)return;if(a.name.startsWith("."))continue;let c=B(o,a.name);if(a.isDirectory()){if(Lr.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function Zt(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split($s).filter(Boolean)}function tn(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function $t(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Ns(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as Fs,mkdirSync as Ds,readFileSync as Us,writeFileSync as Ms}from"fs";import{join as Nr}from"path";function St(e,t){let n=Nr(e,k,"pages.md"),r=Fs(n),o=r?Gs(n):new Map;if(t.length===0&&!r)return{wrote:!1,added:0,total:0,merged:!1};let i=new Map(o),s=0,a=!1;for(let u of t){let d=Dr(u.url),p=i.get(d);p?u.in_sitemap&&p.in_sitemap!=="yes"&&(p.in_sitemap="yes",a=!0):(i.set(d,{url:d,in_sitemap:u.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",notes:Dr(u.source)}),s++,a=!0)}if(r&&!a)return{wrote:!1,added:0,total:i.size,merged:!0};let c=[...i.values()];return Ds(Nr(e,k),{recursive:!0}),Ms(n,Bs(c),"utf-8"),{wrote:!0,added:s,total:c.length,merged:r}}function Bs(e){let t=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
23
+ `)]),n}function us(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 $r(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 ds(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 _r="context.md";function Cr(e){let t=xr(e,".seoagent",_r);if(!ms(t))return null;let n=ps(t,"utf-8");return Sr(n)}function gs(e,t){let n=xr(e,".seoagent",_r),r=vr(t);fs(n,r,"utf-8")}function Er(e,t){gs(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as Ge,readFileSync as Ar,readdirSync as hs,statSync as Rr}from"fs";import{join as me}from"path";var ys=[{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 ws(e){let t=me(e,"package.json");if(!Ge(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Ar(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function ks(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 bs(e){let t={};for(let n of ke){let r=me(e,n);if(Ge(r))try{let o=Ar(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 l=s.slice(0,a).trim();l&&!(l in t)&&(t[l]=n)}}catch{}}return t}function $s(e,t){let n=me(e,t.replace(/\/$/,""));if(!Ge(n))return!1;if(t.endsWith("/"))try{return Rr(n).isDirectory()}catch{return!1}return!0}function Ss(e){let t=["content","_posts","posts",me("src","content")];for(let n of t){let r=me(e,n);if(Ge(r))try{if(!Rr(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of hs(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(me(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 vs(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(Ge(me(e,n.marker)))return n.path;return null}function Ir(e){let t=[],{deps:n}=ws(e),r=bs(e),o="none";for(let s of ys){let a=[];for(let l of Object.keys(n))if(ks(l,s.deps)){a.push({type:"dep",detail:l,source:"package.json"});break}for(let l of s.envKeys)if(r[l]){a.push({type:"env",detail:l,source:r[l]});break}for(let l of s.fsMarkers)if($s(e,l)){let u=l.endsWith("/")?"directory":"file";a.push({type:u,detail:l,source:l});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=Ss(e);s&&(o="mdx-local",t.push(s))}let i=vs(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as xs,readFileSync as _s}from"fs";import{join as Cs}from"path";var Pr=["openai","fal","replicate"],xe={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Es(e){let t={};if(!xs(e))return t;let n=_s(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 Or(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 ke){let o=Cs(e,r),i=Es(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 oe(e){let t=[].concat(...Pr.map(a=>xe[a])),n=Or(e,t),r=[];for(let a of Pr)xe[a].some(l=>n.found[l])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=xe[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 Tr(e,t){let n=Or(e,xe[t]);for(let r of xe[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function jr(){return xe}import{existsSync as ge,readFileSync as on}from"fs";import{join as he}from"path";function Lr(e){try{return new URL(e).hostname}catch{return e}}function Nr(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 As(e){for(let t of ke){let n=he(e,t);if(!ge(n))continue;let r=on(n,"utf-8");for(let o of Hn){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Lr(s);if(Nr(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function Rs(e){let t=he(e,"package.json");if(!ge(t))return null;try{let n=JSON.parse(on(t,"utf-8"));if(!n.homepage)return null;let r=Lr(n.homepage);return Nr(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function Fr(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ge(he(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=As(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=Rs(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=he(e,"package.json"),s=null;if(ge(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(on(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),u=(...p)=>p.some(d=>l.includes(d));if(u("@shopify/hydrogen","@shopify/polaris")||ge(he(e,"shopify.config.js"))||ge(he(e,"shopify.config.ts"))){s="product";let p=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ge(he(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 Is,readFileSync as cn,readdirSync as Dr,statSync as Ps}from"fs";import{join as K,sep as Os}from"path";var Ur=["tsx","jsx","js","mdx","md"],Ts=["astro","md","mdx"],js=5e3;function _e(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let l=Us(i);if(l===null){r++;return}let u=n.get(l);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(l,{route:l,url:Ys(t,l),in_sitemap:a,source:s})};for(let i of Ns(e))Ls(i,o);return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}function Ls(e,t){for(let n of["app",K("src","app")]){let r=K(e,n);if(Ke(r))for(let o of sn(r)){let i=an(r,o),s=i[i.length-1];Ws(s)&&(i.some(a=>a.startsWith("@"))||t(Ms(i.slice(0,-1)),"app router"))}}for(let n of["pages",K("src","pages")]){let r=K(e,n);if(Ke(r))for(let o of sn(r)){let i=an(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=ln(s),l=Ur.includes(a),u=Ts.includes(a);if(!l&&!u)continue;let p=Ct(s);qs(p)||t(Bs(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=K(e,n);if(Ke(r))for(let o of sn(r,n==="."?1:1/0)){let i=an(r,o),s=i[i.length-1];ln(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(Gs(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=K(e,...n.split("/"));if(Is(r)){for(let o of Hs(r)){let i=Ks(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function Ns(e){let t=[e],n=new Set([e]);for(let r of Fs(e))for(let o of Ds(e,r))n.has(o)||(n.add(o),t.push(o));return t}function Fs(e){let t=[];try{let n=cn(K(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(cn(K(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 Ds(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=K(e,...n.split("/").filter(Boolean));return Ke(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=K(e,...o.split("/").filter(Boolean));if(!Ke(i))return[];let s=[];try{for(let a of Dr(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!Mr.has(a.name)&&(s.push(K(i,a.name)),s.length>=200))break}catch{}return s}function Us(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function Ms(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function Bs(e){let t=[...e],n=Ct(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Gs(e){let t=[...e],n=Ct(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Ks(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function Ws(e){return Ct(e)==="page"&&Ur.includes(ln(e))}function qs(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Hs(e){try{let t=cn(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 Mr=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Ke(e){try{return Ps(e).isDirectory()}catch{return!1}}function*sn(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=Dr(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=js)return;if(a.name.startsWith("."))continue;let l=K(o,a.name);if(a.isDirectory()){if(Mr.has(a.name))continue;yield*r(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*r(e,1)}function an(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(Os).filter(Boolean)}function ln(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Ct(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Ys(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as zs,mkdirSync as Js,readFileSync as Vs,writeFileSync as Qs}from"fs";import{join as Br}from"path";function Et(e,t){let n=Br(e,k,"pages.md"),r=zs(n),o=r?Zs(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=Kr(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:Kr(u.source)}),s++,a=!0)}if(r&&!a)return{wrote:!1,added:0,total:i.size,merged:!0};let l=[...i.values()];return Js(Br(e,k),{recursive:!0}),Qs(n,Xs(l),"utf-8"),{wrote:!0,added:s,total:l.length,merged:r}}function Xs(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 Gs(e){let t=new Map,n;try{n=Us(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!nn(r[o])||!Ks(r[o+1]))continue;let i=Fr(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&&nn(r[a]);a++){let c=Fr(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:Be(c,s.in_sitemap),in_nav:Be(c,s.in_nav),status:Be(c,s.status),rendered:Be(c,s.rendered),notes:Be(c,s.notes)})}break}return t}function Be(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function nn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function Ks(e){let t=e.trim();return nn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function Fr(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function Dr(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as ve}from"@clack/prompts";var l={info:e=>ve.info(e),warn:e=>ve.warn(e),error:e=>ve.error(e),success:e=>ve.success(e),step:e=>ve.step(e),message:e=>ve.message(e)};function w(e,t,n,r=n){e?e.stop(r):l[t](n)}var Mr=[{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"}],Kr="unknown",zs=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Js(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 vt(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return zs.has(t)?t:null}async function Ge(e={}){let t=process.cwd();if(Vn(t)){let a=S(t),c=ke(t);ce(t),W(t,{skill_version:C}),ue(t);let u=Gr(xt(t,c.skillFile)),d=c.claudeSymlink?` (symlinked at ${xt(t,c.claudeSymlink)})`:"",p=a?.skill_version&&a.skill_version!==C?`${a.skill_version} \u2192 ${C}`:C;l.success(`Refreshed the SEOAgent skill (${p}).`),l.info("Your `.seoagent/` knowledge was left untouched."),l.info(`Skill at ${u}${d}.`),l.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`);return}let n=!!e.yes||!process.stdin.isTTY;n||Ws("SEOAgent \u2014 AI SEO Agent");let r=Or(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 ${Js(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=vt(e.siteType)||vt(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&vt(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()&&vt(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=Kr),s||(s="unknown"),await Br(t,i,s);return}if(o(),!i){let a=await Ur({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});xe(a)&&(_e("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await rn({message:"What kind of site is this?",options:[...Mr]});xe(a)&&(_e("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Ys({message:`Create .seoagent for ${i} (${s})?`});if(xe(a)&&(_e("Cancelled"),process.exit(0)),a)break;let c=await rn({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((xe(c)||c==="abort")&&(_e("Cancelled"),process.exit(0)),c==="domain"){let u=await Ur({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});xe(u)&&(_e("Cancelled"),process.exit(0)),i=String(u)}else{let u=await rn({message:"What kind of site is this?",options:[...Mr]});xe(u)&&(_e("Cancelled"),process.exit(0)),s=u}}await Br(t,i,s)}async function Br(e,t,n){let r=Hs();r.start("Setting up your SEO project");let o=_r(e),i=ee(e),s={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:C,skill_version:C,install_id:Yt(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{},...i.provider!=="none"?{image_provider:i.provider}:{}};Zn(e),Xn(e,s),ue(e),Sr(e,n),ar(e);let a=ke(e),c=xt(e,a.skillFile),u=Gr(c),d=`${u}/references/audit-checks.md`,p=a.claudeSymlink?xt(e,a.claudeSymlink):void 0;ce(e);let y=t!==Kr,m={pages:[],dynamicCount:0},v={wrote:!1,added:0,total:0,merged:!1};try{m=Se(e,y?t:null),v=St(e,m.pages)}catch{}if(r.stop(y?`Created .seoagent/ project for ${s.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let _=o.evidence.map(M=>`${M.detail} (${M.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${_}`)}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 _=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(_+(m.dynamicCount>0?` (plus ${m.dynamicCount} dynamic route template${m.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let I=y?s.domain:"your site",J=y?[" 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."];qs([y?`\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):","",...J,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${I}`," (homepage + sitemap + robots.txt; the checks live in",` ${d} \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.`,...p?[` Symlinked at ${p} \u2192 ${u} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
30
- `))}import{existsSync as Hr}from"fs";import{intro as Qs,outro as Xs,confirm as Zs,isCancel as ea,cancel as ta}from"@clack/prompts";import{existsSync as _t,rmSync as Vs}from"fs";import{join as Ct}from"path";function Wr(e,t={}){let n=[],r=Ct(e,k);_t(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=Ct(e,le.CLAUDE);_t(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=Ct(e,le.AGENTS);return _t(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),cr(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:Ct(e,".claude","settings.json"),kind:"hook"}),t.global&&_t(F)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:F,kind:"global"}),n}function qr(e,t){for(let n of t)n.kind==="hook"?ur(e):Vs(n.path,{recursive:!0,force:!0})}async function Ke(e={}){let t=process.cwd(),n=Wr(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&Hr(F)&&l.info("Your seoagent.com login is still stored at ~/.config/seoagent/. Re-run with --global to wipe it too.");return}let r=!!e.yes||!process.stdin.isTTY,o=n.map(s=>` \u2022 ${s.label}`).join(`
31
- `);if(!r){Qs("SEOAgent \u2014 uninstall"),l.message(`This will remove:
32
- ${o}`);let s=await Zs({message:"Remove these and start fresh?"});if(ea(s)||!s){ta("Cancelled \u2014 nothing was removed.");return}}qr(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
33
- `);r?l.success(`Removed:
34
- ${i}`):Xs(`Removed:
35
- ${i}`),!e.global&&Hr(F)&&l.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),l.info(`Re-install any time with \`${f("init")}\`.`)}import $ from"picocolors";import{existsSync as zr,mkdirSync as Yr,readFileSync as na,writeFileSync as ra,chmodSync as oa,unlinkSync as ia}from"fs";import{dirname as sa}from"path";function P(){if(!zr(Z))return null;try{let e=JSON.parse(na(Z,"utf-8"));return!e.user_token||!e.website_token?null:{user_token:e.user_token,website_token:e.website_token,api_base:e.api_base||Le}}catch{return null}}function Jr(e){Yr(F,{recursive:!0}),Yr(sa(Z),{recursive:!0}),ra(Z,JSON.stringify(e,null,2)+`
36
- `,"utf-8");try{oa(Z,384)}catch{}}function Vr(){if(!zr(Z))return!1;try{return ia(Z),!0}catch{return!1}}import{existsSync as We,readdirSync as on,statSync as aa,readFileSync as Qr}from"fs";import{join as Ce}from"path";function la(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function ca(e){let t=Ce(e,"audit","latest.md");if(!We(t))return null;let n=gt(t);if(!n)return null;let r=Qr(t,"utf-8"),o=la(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=Qr(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 da(e){let t=Ce(e,"strategy","clusters");if(!We(t))return null;let n=on(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=ua(Ce(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function pa(e){let t=Ce(e,"briefs");if(!We(t))return null;let n=on(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function fa(e){let t=Ce(e,"content");if(!We(t))return null;let n=on(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function ma(e){let t=Ce(e,"roadmap.md");return We(t)?{exists:!0,updatedAt:aa(t).mtime.toISOString()}:null}function Xr(e){let t=S(e);if(!t)return null;let n=Fe(e);return{domain:t.domain,audit:ca(n),strategy:da(n),briefs:pa(n),content:fa(n),roadmap:ma(n)}}import te from"picocolors";var ga=/\x1b\[[0-9;]*m/g;function Zr(e){return e.replace(ga,"").length}function O(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=ha(n,t.title),s=te.dim(`\u251C${o}\u2524`),a=te.dim(`\u2514${o}\u2518`),c=[i];for(let u of e){if("sep"in u){c.push(s);continue}c.push(ya(u.content,r))}return c.push(a),c.join(`
37
- `)}function ha(e,t){if(!t)return te.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Zr(t),r=e-5-n;return r<1?te.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${te.dim("\u250C\u2500 ")}${t}${te.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function ya(e,t){let n=Zr(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${te.dim("\u2502")} ${r} ${te.dim("\u2502")}`}function sn(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 qe(){let e=Xr(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=>$.dim(s.padEnd(t)),r=[];P()?(r.push({content:`${$.green("\u2713")} ${$.dim("Logged in")}`}),r.push({content:$.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${$.dim("\u25CB Not logged in")}`}),r.push({content:$.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${$.green(`last run ${sn(e.audit.date??"")}`)} ${$.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${$.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${$.bold($.cyan(String(e.strategy.clusterCount??0)))} ${$.dim("clusters")} \xB7 ${$.bold($.cyan(String(e.strategy.articleCount??0)))} ${$.dim("ideas")}`:`${n("Strategy:")}${$.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${$.bold($.cyan(String(e.briefs.count??0)))} ${$.dim("ready")}`:`${n("Briefs:")}${$.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${$.green("\u2713")} ${$.bold($.cyan(String(e.content.count??0)))} ${$.dim("articles written")}`:`${n("Content:")}${$.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${$.green("updated")} ${$.dim(sn(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${$.dim("not yet created")}`});let i=`${$.bold($.cyan("SEOAgent"))} ${$.dim("\xB7")} ${$.bold(e.domain)}`;return O(r,{width:78,title:i})}import{exec as ka,spawn as eo}from"child_process";import{confirm as ba,isCancel as $a}from"@clack/prompts";import L from"picocolors";function Ee(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 Sa=`https://registry.npmjs.org/${V}/latest`,He=["free","starter","pro","scale","enterprise"],Et={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function va(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return He.includes(t)?t:null}function xa(e){let t=He.indexOf(e);return t===-1||t===He.length-1?null:He[t+1]}async function _a(e,t=fetch){if(!e)return null;try{let n=(e.api_base||E.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 Ca(e){let t=[],r=s=>L.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${L.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${L.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of He){let a=Et[s];s===e.current?t.push({content:`${L.bold(L.green("\u25CF"))} ${L.bold(L.green(a.padEnd(11)))} ${L.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${L.yellow("\u25C6")} ${L.bold(L.yellow(a.padEnd(11)))} ${L.yellow("next tier")}`}):t.push({content:L.dim(` ${a}`)})}let i=`${L.bold(L.cyan("SEOAgent Cloud"))} ${L.dim("\xB7")} ${L.dim("your plan")}`;return O(t,{width:55,title:i})}async function Ye(){let e=P(),t=!!process.stdin.isTTY;if(e&&t){let n=await _a(e);if(n){let r=va(n.plan),o=r?xa(r):null;if(r&&l.message(Ca({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${Et[r]} (highest tier).`);return}if(r&&o){let i=await ba({message:`Upgrade from ${Et[r]} to ${Et[o]}?`});if($a(i)||!i){l.info("No changes.");return}}}}Ea()}function Ea(){let e=Aa();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}"`;ka(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function Aa(){let e=process.cwd(),t=S(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${E.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function ze(e={}){let t=C,n=await Ra();if(!n){l.warn("Couldn't reach the npm registry to check for a newer version."),l.message(`You're on ${t}. To force-update: npm install -g ${V}@latest`);return}if(Ee(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!Wt()){l.info(`A newer CLI is available: ${t} \u2192 ${n}.`),l.message("You're running via npx, which caches the package \u2014 an unpinned spec won't auto-upgrade."),l.message(`Run the latest now by pinning the tag: npx -y ${V}@latest <cmd>`),l.message(`Still on ${t} after that? Clear the npx cache: rm -rf ~/.npm/_npx`),l.message(`Or install globally once so \`seoagent <cmd>\` + \`update-cli\` work in place: npm install -g ${V}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${V}@latest`);return}if(l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await Pa()){l.error(`Update failed. Try manually: npm install -g ${V}@latest (you may need sudo on Linux/macOS).`);return}if(l.success(`Updated to ${n}.`),e.projects===!1){l.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}l.info("Refreshing your other projects to the new version\u2026"),await Ia()||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 Ia(){return new Promise(e=>{try{let t=eo("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function Ra(e=fetch){try{let t=await e(Sa,{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 Pa(){return new Promise(e=>{let t=eo("npm",["install","-g",`${V}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as Oa}from"child_process";import{randomBytes as Ta}from"crypto";import{isCancel as ja,spinner as La,text as Na}from"@clack/prompts";import ne from"picocolors";function to(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 Fa=1500,Da=300*1e3;function Ua(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;Oa(t,()=>{})}function Ma(){return Ta(16).toString("hex")}function Ba(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function no(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 Ga(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 to(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Ka(e){return new Promise(t=>setTimeout(t,e))}async function Je(e={}){let t=process.cwd(),n=S(t),r=(e.apiBase||E.BASE||Le).replace(/\/$/,"");if(P()){l.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let p=await Na({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(!no(String(m)))return"Please enter a valid domain like `example.com`."}});if(ja(p)){l.warn("Login cancelled.");return}let y=no(String(p));if(y){o=y;try{W(t,{domain:y}),l.success(`Saved domain: ${y} \u2192 .seoagent/project.md`)}catch{}}}let i=Ma(),s=Ba(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}`),Ua(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?La():null;c?.start(ne.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+Da,d=!0;for(;Date.now()<u;){d||await Ka(Fa),d=!1;let p=await Ga(r,i);if(p.status==="ready"){Jr({user_token:p.user_token,website_token:p.website_token,api_base:r});let y=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",m=p.email&&p.domain?`Logged in as ${ne.bold(p.email)} (${ne.cyan(p.domain)}).`:p.email?`Logged in as ${ne.bold(p.email)}.`:"Logged in.";w(c,"success",y,ne.green(m)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){w(c,"warn",`Session expired. Run \`${f("login")}\` again.`,ne.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){w(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,ne.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}w(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,ne.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function Ve(){Vr()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as pc}from"@clack/prompts";import re from"picocolors";import{existsSync as fn,mkdirSync as Ll,readFileSync as Eo,readdirSync as Nl,statSync as Fl,writeFileSync as Dl}from"fs";import{join as mn,relative as Ul,sep as Ml}from"path";var Wa=new Set([502,503,504]),qa=1e4;async function Y(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??qa,s=n.fetchImpl??fetch,a=n.sleep??Ha,c=n.transientStatuses??Wa,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:y}=Ya(t,i);try{let m=await s(e,p);if(c.has(m.status)&&d<r-1){await a(ro(o,d));continue}return m}catch(m){if(u=m,d<r-1){await a(ro(o,d));continue}}finally{y()}}throw u instanceof Error?u:new Error(String(u))}function ro(e,t){return e*Math.pow(3,t)}function Ha(e){return new Promise(t=>setTimeout(t,e))}function Ya(e,t){if(t<=0)return{init:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Request timed out after ${t}ms`)),t),o=e?.signal??void 0,i;o&&(o.aborted?n.abort(o.reason):(i=()=>n.abort(o.reason),o.addEventListener("abort",i,{once:!0})));let s=()=>{clearTimeout(r),o&&i&&o.removeEventListener("abort",i)};return{init:{...e,signal:n.signal},cleanup:s}}import{existsSync as ln,mkdirSync as za,readdirSync as oo,readFileSync as Ja,unlinkSync as Va,writeFileSync as an}from"fs";import{join as Ie}from"path";import R from"picocolors";function Q(e){return Ie(e,k,"inbox")}function io(e){return`${e.action_type}-${e.id}.md`}function Qa(e,t){let n=0;if(!ln(e))return 0;for(let r of oo(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{Va(Ie(e,r)),n++}catch{}}return n}function Xa(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`---
29
+ `)}function Zs(e){let t=new Map,n;try{n=Vs(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!un(r[o])||!ea(r[o+1]))continue;let i=Gr(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&&un(r[a]);a++){let l=Gr(r[a]),u=(l[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:We(l,s.in_sitemap),in_nav:We(l,s.in_nav),status:We(l,s.status),rendered:We(l,s.rendered),notes:We(l,s.notes)})}break}return t}function We(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function un(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function ea(e){let t=e.trim();return un(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function Gr(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function Kr(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as Ce}from"@clack/prompts";var c={info:e=>Ce.info(e),warn:e=>Ce.warn(e),error:e=>Ce.error(e),success:e=>Ce.success(e),step:e=>Ce.step(e),message:e=>Ce.message(e)};function w(e,t,n,r=n){e?e.stop(r):c[t](n)}var qr=[{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"}],zr="unknown",ia=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function sa(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 At(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return ia.has(t)?t:null}async function qe(e={}){let t=process.cwd();if(tr(t)){let a=_(t),l=Se(t);pe(t),H(t,{skill_version:E}),fe(t);let u=Yr(Rt(t,l.skillFile)),p=l.claudeSymlink?` (symlinked at ${Rt(t,l.claudeSymlink)})`:"",d=a?.skill_version&&a.skill_version!==E?`${a.skill_version} \u2192 ${E}`:E;c.success(`Refreshed the SEOAgent skill (${d}).`),c.info("Your `.seoagent/` knowledge was left untouched."),c.info(`Skill at ${u}${p}.`),c.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`);return}let n=!!e.yes||!process.stdin.isTTY;n||ta("SEOAgent \u2014 AI SEO Agent");let r=Fr(t,a=>c.step(a)),o=()=>{if(r.evidence.length!==0){c.info("Inferred from your project:");for(let a of r.evidence)c.info(` \u2022 ${sa(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=At(e.siteType)||At(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&At(e.siteType)===null&&(c.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&At(process.env.SEOAGENT_SITE_TYPE)===null&&(c.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),o(),i||(c.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=zr),s||(s="unknown"),await Hr(t,i,s);return}if(o(),!i){let a=await Wr({message:"Website domain",placeholder:"example.com",validate:l=>l.trim()?void 0:"Domain is required"});Ee(a)&&(Ae("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await dn({message:"What kind of site is this?",options:[...qr]});Ee(a)&&(Ae("Cancelled"),process.exit(0)),s=a}for(;;){let a=await oa({message:`Create .seoagent for ${i} (${s})?`});if(Ee(a)&&(Ae("Cancelled"),process.exit(0)),a)break;let l=await dn({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((Ee(l)||l==="abort")&&(Ae("Cancelled"),process.exit(0)),l==="domain"){let u=await Wr({message:"Website domain",placeholder:"example.com",validate:p=>p.trim()?void 0:"Domain is required"});Ee(u)&&(Ae("Cancelled"),process.exit(0)),i=String(u)}else{let u=await dn({message:"What kind of site is this?",options:[...qr]});Ee(u)&&(Ae("Cancelled"),process.exit(0)),s=u}}await Hr(t,i,s)}async function Hr(e,t,n){let r=ra();r.start("Setting up your SEO project");let o=Ir(e),i=oe(e),s={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:E,skill_version:E,install_id:en(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{},...i.provider!=="none"?{image_provider:i.provider}:{}};or(e),rr(e,s),fe(e),Er(e,n),pr(e);let a=Se(e),l=Rt(e,a.skillFile),u=Yr(l),p=`${u}/references/audit-checks.md`,d=a.claudeSymlink?Rt(e,a.claudeSymlink):void 0;pe(e);let g=t!==zr,m={pages:[],dynamicCount:0},v={wrote:!1,added:0,total:0,merged:!1};try{m=_e(e,g?t:null),v=Et(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(N=>`${N.detail} (${N.source})`).slice(0,2).join(", ");c.info(`CMS detected: ${o.cms} \u2014 ${x}`)}if(o.blog_path&&c.info(`Blog route: ${o.blog_path}`),i.provider!=="none"&&c.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`;c.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",O=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."];na([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:","",` ${l} \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):","",...O,"",` 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 ${l} 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 Qr}from"fs";import{intro as ca,outro as la,confirm as ua,isCancel as da,cancel as pa}from"@clack/prompts";import{existsSync as It,rmSync as aa}from"fs";import{join as Pt}from"path";function Jr(e,t={}){let n=[],r=Pt(e,k);It(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=Pt(e,de.CLAUDE);It(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=Pt(e,de.AGENTS);return It(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),mr(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:Pt(e,".claude","settings.json"),kind:"hook"}),t.global&&It(U)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:U,kind:"global"}),n}function Vr(e,t){for(let n of t)n.kind==="hook"?gr(e):aa(n.path,{recursive:!0,force:!0})}async function He(e={}){let t=process.cwd(),n=Jr(t,{global:e.global});if(n.length===0){c.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&Qr(U)&&c.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"),c.message(`This will remove:
32
+ ${o}`);let s=await ua({message:"Remove these and start fresh?"});if(da(s)||!s){pa("Cancelled \u2014 nothing was removed.");return}}Vr(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
33
+ `);r?c.success(`Removed:
34
+ ${i}`):la(`Removed:
35
+ ${i}`),!e.global&&Qr(U)&&c.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),c.info(`Re-install any time with \`${f("init")}\`.`)}import S from"picocolors";import{existsSync as Zr,mkdirSync as Xr,readFileSync as fa,writeFileSync as ma,chmodSync as ga,unlinkSync as ha}from"fs";import{dirname as ya}from"path";function T(){if(!Zr(re))return null;try{let e=JSON.parse(fa(re,"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||De}}catch{return null}}function eo(e){Xr(U,{recursive:!0}),Xr(ya(re),{recursive:!0}),ma(re,JSON.stringify(e,null,2)+`
36
+ `,"utf-8");try{ga(re,384)}catch{}}function to(){if(!Zr(re))return!1;try{return ha(re),!0}catch{return!1}}import{existsSync as Ye,readdirSync as pn,statSync as wa,readFileSync as no}from"fs";import{join as Re}from"path";function ka(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function ba(e){let t=Re(e,"audit","latest.md");if(!Ye(t))return null;let n=bt(t);if(!n)return null;let r=no(t,"utf-8"),o=ka(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function $a(e){try{let n=no(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 Sa(e){let t=Re(e,"strategy","clusters");if(!Ye(t))return null;let n=pn(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=$a(Re(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function va(e){let t=Re(e,"briefs");if(!Ye(t))return null;let n=pn(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function xa(e){let t=Re(e,"content");if(!Ye(t))return null;let n=pn(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function _a(e){let t=Re(e,"roadmap.md");return Ye(t)?{exists:!0,updatedAt:wa(t).mtime.toISOString()}:null}function ro(e){let t=_(e);if(!t)return null;let n=Me(e);return{domain:t.domain,audit:ba(n),strategy:Sa(n),briefs:va(n),content:xa(n),roadmap:_a(n)}}import ie from"picocolors";var Ca=/\x1b\[[0-9;]*m/g;function oo(e){return e.replace(Ca,"").length}function j(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=Ea(n,t.title),s=ie.dim(`\u251C${o}\u2524`),a=ie.dim(`\u2514${o}\u2518`),l=[i];for(let u of e){if("sep"in u){l.push(s);continue}l.push(Aa(u.content,r))}return l.push(a),l.join(`
37
+ `)}function Ea(e,t){if(!t)return ie.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=oo(t),r=e-5-n;return r<1?ie.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${ie.dim("\u250C\u2500 ")}${t}${ie.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function Aa(e,t){let n=oo(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${ie.dim("\u2502")} ${r} ${ie.dim("\u2502")}`}function fn(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 ze(){let e=ro(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${f("init")}\` to get started.`);return}c.message(Ra(e))}function Ra(e){if(!e)return"";let t=11,n=s=>S.dim(s.padEnd(t)),r=[];T()?(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 ${fn(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(fn(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 j(r,{width:78,title:i})}import{exec as Ia,spawn as io}from"child_process";import{confirm as Pa,isCancel as Oa}from"@clack/prompts";import D from"picocolors";function Ie(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 Ta=`https://registry.npmjs.org/${Z}/latest`,Je=["free","starter","pro","scale","enterprise"],Ot={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function ja(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return Je.includes(t)?t:null}function La(e){let t=Je.indexOf(e);return t===-1||t===Je.length-1?null:Je[t+1]}async function Na(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 Fa(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 Je){let a=Ot[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 j(t,{width:55,title:i})}async function Ve(){let e=T(),t=!!process.stdin.isTTY;if(e&&t){let n=await Na(e);if(n){let r=ja(n.plan),o=r?La(r):null;if(r&&c.message(Fa({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){c.success(`You're on ${Ot[r]} (highest tier).`);return}if(r&&o){let i=await Pa({message:`Upgrade from ${Ot[r]} to ${Ot[o]}?`});if(Oa(i)||!i){c.info("No changes.");return}}}}Da()}function Da(){let e=Ua();c.info("Opening SEOAgent Cloud pricing..."),c.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;Ia(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function Ua(){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 Qe(e={}){let t=E,n=await Ba();if(!n){c.warn("Couldn't reach the npm registry to check for a newer version."),c.message(`You're on ${t}. To force-update: npm install -g ${Z}@latest`);return}if(Ie(t,n)>=0){c.success(`You're on the latest CLI (${t}).`);return}if(!Qt()){c.info(`A newer CLI is available: ${t} \u2192 ${n}.`),c.message("You're running via npx, which caches the package \u2014 an unpinned spec won't auto-upgrade."),c.message(`Run the latest now by pinning the tag: npx -y ${Z}@latest <cmd>`),c.message(`Still on ${t} after that? Clear the npx cache: rm -rf ~/.npm/_npx`),c.message(`Or install globally once so \`seoagent <cmd>\` + \`update-cli\` work in place: npm install -g ${Z}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${Z}@latest`);return}if(c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await Ga()){c.error(`Update failed. Try manually: npm install -g ${Z}@latest (you may need sudo on Linux/macOS).`);return}if(c.success(`Updated to ${n}.`),e.projects===!1){c.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}c.info("Refreshing your other projects to the new version\u2026"),await Ma()||c.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 Ma(){return new Promise(e=>{try{let t=io("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function Ba(e=fetch){try{let t=await e(Ta,{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 Ga(){return new Promise(e=>{let t=io("npm",["install","-g",`${Z}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as Ka}from"child_process";import{randomBytes as Wa}from"crypto";import{isCancel as qa,spinner as Ha,text as Ya}from"@clack/prompts";import se from"picocolors";function so(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 za=1500,Ja=300*1e3;function Va(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;Ka(t,()=>{})}function Qa(){return Wa(16).toString("hex")}function Xa(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function ao(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 Za(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 so(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function ec(e){return new Promise(t=>setTimeout(t,e))}async function Xe(e={}){let t=process.cwd(),n=_(t),r=(e.apiBase||A.BASE||De).replace(/\/$/,"");if(T()){c.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 Ya({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(!ao(String(m)))return"Please enter a valid domain like `example.com`."}});if(qa(d)){c.warn("Login cancelled.");return}let g=ao(String(d));if(g){o=g;try{H(t,{domain:g}),c.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=Qa(),s=Xa(r,i,o);c.message("Opening seoagent.com to connect this CLI to your account..."),c.info(`If the browser does not open, visit: ${s}`),Va(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?Ha():null;l?.start(se.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+Ja,p=!0;for(;Date.now()<u;){p||await ec(za),p=!1;let d=await Za(r,i);if(d.status==="ready"){eo({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 ${se.bold(d.email)} (${se.cyan(d.domain)}).`:d.email?`Logged in as ${se.bold(d.email)}.`:"Logged in.";w(l,"success",g,se.green(m)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(d.status==="expired"){w(l,"warn",`Session expired. Run \`${f("login")}\` again.`,se.red("Session expired.")),l&&c.warn(`Run \`${f("login")}\` again.`);return}if(d.status==="error"){if(d.terminal){w(l,"warn",`Login failed: ${d.message}. Run \`${f("login")}\` again.`,se.red(`Login failed: ${d.message}.`)),l&&c.warn(`Run \`${f("login")}\` again.`);return}continue}}w(l,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,se.yellow("Login timed out.")),l&&c.warn(`Run \`${f("login")}\` again to retry.`)}function Ze(){to()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as vl}from"@clack/prompts";import ae from"picocolors";import{existsSync as bn,mkdirSync as Hc,readFileSync as Oo,readdirSync as Yc,statSync as zc,writeFileSync as Jc}from"fs";import{join as $n,relative as Vc,sep as Qc}from"path";var tc=new Set([502,503,504]),nc=1e4;async function J(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??nc,s=n.fetchImpl??fetch,a=n.sleep??rc,l=n.transientStatuses??tc,u=null;for(let p=0;p<r;p++){let{init:d,cleanup:g}=oc(t,i);try{let m=await s(e,d);if(l.has(m.status)&&p<r-1){await a(co(o,p));continue}return m}catch(m){if(u=m,p<r-1){await a(co(o,p));continue}}finally{g()}}throw u instanceof Error?u:new Error(String(u))}function co(e,t){return e*Math.pow(3,t)}function rc(e){return new Promise(t=>setTimeout(t,e))}function oc(e,t){if(t<=0)return{init:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Request timed out after ${t}ms`)),t),o=e?.signal??void 0,i;o&&(o.aborted?n.abort(o.reason):(i=()=>n.abort(o.reason),o.addEventListener("abort",i,{once:!0})));let s=()=>{clearTimeout(r),o&&i&&o.removeEventListener("abort",i)};return{init:{...e,signal:n.signal},cleanup:s}}import{existsSync as gn,mkdirSync as ic,readdirSync as lo,readFileSync as sc,unlinkSync as ac,writeFileSync as mn}from"fs";import{join as Oe}from"path";import P from"picocolors";function ee(e){return Oe(e,k,"inbox")}function uo(e){return`${e.action_type}-${e.id}.md`}function cc(e,t){let n=0;if(!gn(e))return 0;for(let r of lo(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{ac(Oe(e,r)),n++}catch{}}return n}function lc(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 Za(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 el(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 tl(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 uc(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 dc(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 pc(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. ${el(r,o,n)}
105
- 2. ${Za(r)}
104
+ 1. ${dc(r,o,n)}
105
+ 2. ${uc(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 nl(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 fc(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 rl(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 mc(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 ol(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 gc(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 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`---
264
+ `}function hc(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 sl(e){switch(e.action_type){case"cli_prune_pending":return Xa(e);case"cli_technical_fix":return tl(e);case"cli_new_content":return nl(e);case"cli_content_update":return rl(e);case"cli_sitemap_update":return ol(e);case"cli_new_landing_page":return il(e);default:return null}}function al(e){if(e.length===0)return`# SEOAgent Inbox
322
+ `}function yc(e){switch(e.action_type){case"cli_prune_pending":return lc(e);case"cli_technical_fix":return pc(e);case"cli_new_content":return fc(e);case"cli_content_update":return mc(e);case"cli_sitemap_update":return gc(e);case"cli_new_landing_page":return hc(e);default:return null}}function wc(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 \`${io(n)}\``);return`# SEOAgent Inbox
325
+ `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${uo(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 me(e){let t=Q(e);if(!ln(t))return[];let n=[];for(let r of oo(t)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(.+)-(\d+)\.md$/);if(!o)continue;let i=o[1],s=Number.parseInt(o[2],10);if(!Number.isFinite(s))continue;let a="no title",c=null,u=null,d=null,p=null,y=null,m=null;try{let v=Ja(Ie(t,r),"utf-8"),I=v.match(/^---\n([\s\S]*?)\n---/);if(I){let M=I[1];c=Ae(M,"severity"),u=Ae(M,"issue"),d=Ae(M,"page_url");let ae=Ae(M,"priority");(ae==="high"||ae==="medium"||ae==="low")&&(p=ae),y=Ae(M,"impact_estimate"),m=Ae(M,"effort_estimate")}let _=v.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);_&&(a=_[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:c,issue:u,page_url:d,priority:p,impact_estimate:y,effort_estimate:m})}return n.sort((r,o)=>r.id-o.id)}function Re(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=ll[e.severity??""]??R.dim,r=e.severity??"unknown",o=[R.dim("\u25B8"),R.bold(`id ${e.id}`),R.dim("\xB7"),R.cyan(t),n(r)];if(e.priority){let i=cl[e.priority];o.push(R.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(R.dim("\xB7"),R.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(R.dim("\xB7"),R.dim(`\u23F1 ${e.effort_estimate}`)),o.push(R.dim("\u2014"),e.title),o.join(" ")}var ll={critical:e=>R.red(R.bold(e)),high:e=>R.red(e),medium:e=>R.yellow(e),low:e=>R.dim(e)},cl={high:e=>R.red(R.bold(e)),medium:e=>R.yellow(e),low:e=>R.dim(e)};function Ae(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 At(e){let t=Q(e);if(!ln(t))return;let n=me(e),r=n.length===0?`# SEOAgent Inbox
337
+ `}function ye(e){let t=ee(e);if(!gn(t))return[];let n=[];for(let r of lo(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",l=null,u=null,p=null,d=null,g=null,m=null;try{let v=sc(Oe(t,r),"utf-8"),$=v.match(/^---\n([\s\S]*?)\n---/);if($){let N=$[1];l=Pe(N,"severity"),u=Pe(N,"issue"),p=Pe(N,"page_url");let X=Pe(N,"priority");(X==="high"||X==="medium"||X==="low")&&(d=X),g=Pe(N,"impact_estimate"),m=Pe(N,"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:l,issue:u,page_url:p,priority:d,impact_estimate:g,effort_estimate:m})}return n.sort((r,o)=>r.id-o.id)}function Te(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=kc[e.severity??""]??P.dim,r=e.severity??"unknown",o=[P.dim("\u25B8"),P.bold(`id ${e.id}`),P.dim("\xB7"),P.cyan(t),n(r)];if(e.priority){let i=bc[e.priority];o.push(P.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(P.dim("\xB7"),P.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(P.dim("\xB7"),P.dim(`\u23F1 ${e.effort_estimate}`)),o.push(P.dim("\u2014"),e.title),o.join(" ")}var kc={critical:e=>P.red(P.bold(e)),high:e=>P.red(e),medium:e=>P.yellow(e),low:e=>P.dim(e)},bc={high:e=>P.red(P.bold(e)),medium:e=>P.yellow(e),low:e=>P.dim(e)};function Pe(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 Tt(e){let t=ee(e);if(!gn(t))return;let n=ye(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
- `;an(Ie(t,"README.md"),r,"utf-8")}function so(e,t){let n=Q(e);za(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=Qa(n,r),i=0;for(let s of t){let a=sl(s);a!==null&&(an(Ie(n,io(s)),a,"utf-8"),i++)}return an(Ie(n,"README.md"),al(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as pl}from"crypto";import{existsSync as co,mkdirSync as fl,readFileSync as ml,statSync as uo,writeFileSync as lo,rmSync as gl}from"fs";import{dirname as hl,join as cn,sep as yl}from"path";function ul(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var dl=[{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 ao(e,t){let n=ul(e);for(let{cls:r,test:o}of dl)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function wl(e){return"sha256:"+pl("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 bl(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:ao(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 po(e){let t=await mo({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 fo(e,t){return cn(e,t.split("/").join(yl))}function $l(e,t,n){let r={};for(let o of t){let i=fo(e,o);if(!co(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=uo(i),a=n[o],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:wl(ml(i,"utf-8")),locallyEdited:c}}return r}async function mo(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 go(e){let t=cn(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 mo({apiBase:e.apiBase,authHeader:e.authHeader,since:e.since,fetchImpl:e.fetchImpl});if(!r.ok)return{...n,ok:!1,error:r.error};let o=r.manifest,i=[...o.artifacts.map(d=>d.path),...o.deleted],s=$l(t,i,e.stateFiles),a=kl(o,s,{force:e.force}),c={...n,cursor:o.now};for(let d of a){let p=fo(t,d.path);try{switch(d.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{fl(hl(p),{recursive:!0}),lo(p,d.body??"","utf-8");let y=uo(p);e.stateFiles[d.path]={mtime:y.mtimeMs,size:y.size},d.kind==="write"?c.written++:c.overwritten++,d.note&&c.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":gl(p,{force:!0}),delete e.stateFiles[d.path],c.deleted++;break;case"delete-skipped":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(y){c.ok=!1,c.error=`${d.path}: ${y.message}`}}(c.conflicts>0||!c.ok)&&(c.cursor=e.since);let u=bl(a,o,c.cursor,new Date().toISOString());if(u)try{lo(cn(t,dt),JSON.stringify(u,null,2)+`
353
- `,"utf-8")}catch{}return c}import{existsSync as yo,mkdirSync as wo,readFileSync as Sl,writeFileSync as un}from"fs";import{dirname as ko,join as vl}from"path";var dn=1,ho=500;function pn(e){return vl(e,k,Kn)}function It(e){let t=pn(e);if(!yo(t))return[];try{let n=Sl(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==dn||!Array.isArray(o.entries)?[]:o.entries.filter(xl)}catch{return[]}}function bo(e,t){let n=pn(e),o=It(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>ho?o.slice(-ho):o,s={version:dn,entries:i};try{wo(ko(n),{recursive:!0}),un(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function $o(e,t){if(t.length===0)return;let n=pn(e),r=It(e).filter(i=>!t.includes(i.action_id)),o={version:dn,entries:r};try{if(r.length===0&&yo(n)){un(n,JSON.stringify(o,null,2),"utf-8");return}wo(ko(n),{recursive:!0}),un(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function xl(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 So,readFileSync as _l,unlinkSync as Cl,writeFileSync as El,openSync as Al,closeSync as Il,mkdirSync as Rl}from"fs";import{dirname as Pl,join as Ol}from"path";var Tl=6e4;function vo(e){return Ol(e,k,Wn)}function xo(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??Tl,i=vo(e);if(!So(i))return Rt(i,r,n());let s=Co(i);return!s||n()-s.started_at>o||!jl(s.pid)?Rt(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function _o(e,t={}){let n=t.pid??process.pid,r=vo(e);if(!So(r))return;let o=Co(r);if(!(o&&o.pid!==n))try{Cl(r)}catch{}}function Rt(e,t,n){let r={pid:t,started_at:n};try{Rl(Pl(e),{recursive:!0});let o=Al(e,"w");try{El(o,JSON.stringify(r))}finally{Il(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Co(e){try{let t=_l(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 jl(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var Bl=new Set([".md"]),Gl=new Set(["inbox"]);function Kl(e){let t=[];function n(r,o){if(fn(r))for(let i of Nl(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Gl.has(i.name))continue;let s=mn(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);Bl.has(c)&&t.push(s)}}}return n(e,""),t}function Ao(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return mn(Kt,`${t}.json`)}function Wl(e){let t=Ao(e);if(!fn(t))return{files:{},last_synced_at:null};try{return JSON.parse(Eo(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function ql(e,t){Ll(Kt,{recursive:!0}),Dl(Ao(e),JSON.stringify(t,null,2)+`
354
- `,"utf-8")}function Hl(e,t){return Ul(e,t).split(Ml).join("/")}async function Yl(e,t){try{let n=await Y(`${e}/api/cli/actions/fetch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t},body:JSON.stringify({})});if(!n.ok){let o=await n.text().catch(()=>"");return{ok:!1,actions:[],error:`${n.status} ${o.slice(0,200)}`}}let r=await n.json().catch(()=>null);return!r||r.status!=="ok"||!Array.isArray(r.actions)?{ok:!1,actions:[],error:"Malformed response"}:{ok:!0,actions:r.actions}}catch(n){return{ok:!1,actions:[],error:n.message}}}async function zl(e,t,n){try{let r=await Y(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,status:r.status,error:o.slice(0,200)}}return{ok:!0,status:r.status}}catch(r){return{ok:!1,status:0,error:r.message}}}async function Io(e,t={}){let n=P();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=S(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=mn(e,k);if(!fn(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!xo(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await Jl(e,t,n,r,o)}finally{_o(e)}}async function Jl(e,t,n,r,o){let i=Wl(r.domain),s=Kl(o),a=n.api_base||E.BASE,c=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,p=[],y=0,m=await Vl(e,a,c);if(!t.pullOnly)for(let j of s){let je=Hl(o,j);if(t.pathFilter&&!je.endsWith(t.pathFilter))continue;let lt=Fl(j),Bt=i.files[je];if(!(!Bt||Bt.mtime!==lt.mtimeMs||Bt.size!==lt.size)&&!t.force)continue;y++;let yi=Eo(j,"utf-8"),Gt=await zl(a,{path:je,contents:yi,domain:r.domain},c);Gt.ok?(i.files[je]={mtime:lt.mtimeMs,size:lt.size},u++):(d++,p.push(`${je}: ${Gt.status} ${Gt.error??""}`.trim()))}let v=await Yl(a,c),I=0,J=0;if(v.ok){let j=so(e,v.actions);I=j.wrote,J=j.removed}else v.error&&p.push(`pull actions: ${v.error}`);let _,M=!1,ae=i.last_synced_at;if(!t.pushOnly){let j=await go({projectDir:e,apiBase:a,authHeader:c,since:i.last_synced_at,stateFiles:i.files,force:t.force});j.ok?ae=j.cursor:(M=!0,j.error&&p.push(`pull: ${j.error}`)),_={written:j.written,overwritten:j.overwritten,skipped:j.skipped,conflicts:j.conflicts,deleted:j.deleted,warnings:j.warnings}}let hi=!!_&&_.written+_.overwritten+_.deleted+_.conflicts>0;if(i.last_synced_at=ae,ql(r.domain,i),y===0&&I===0&&J===0&&!hi&&m.flushed===0&&m.dropped===0&&!M&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:p,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:_};let Mn=d===0&&!M;return{ok:Mn,reason:Mn?void 0:"error",synced:u,failed:d,errors:p,actionsPulled:I,actionsRemoved:J,acksFlushed:m.flushed,acksDropped:m.dropped,pull:_}}async function Vl(e,t,n){let r=It(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let c=await Ql(a,t,n);c==="flushed"?(o++,s.push(a.action_id)):c==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&$o(e,s),{flushed:o,dropped:i}}async function Ql(e,t,n){try{let r=await Y(`${t}/api/cli/actions/${e.action_id}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify({status:e.status,error_message:e.status==="failed"?e.reason:null,result:e.status==="failed"?{declined:!0,reason:e.reason}:{applied:!0}})});return r.ok?"flushed":r.status===409||r.status>=400&&r.status<500?"already-settled":"transient"}catch{return"transient"}}function Ro(e){let t;try{t=S(e)}catch{return{refreshed:!1,reason:"error"}}if(!t)return{refreshed:!1,reason:"no-project"};let n=t.skill_version||t.seoagent_version||"0.0.0";if(Ee(C,n)<=0){if(!t.skill_version)try{W(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return ke(e),W(e,{skill_version:C}),{refreshed:!0,from:n,to:C,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function gn(e){let t;try{t=S(e)}catch{return{refreshed:!1,from:null,to:C,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:C,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return ke(e),W(e,{skill_version:C}),{refreshed:!0,from:n,to:C,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:C,reason:"error"}}}import{existsSync as Xl,mkdirSync as Zl,readFileSync as ec,writeFileSync as tc}from"fs";var nc="https://registry.npmjs.org/@seoagent-official/seoagent/latest",rc=1440*60*1e3,oc=720*60*1e3,ic=2e3;function sc(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 ac(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??oc;if(!n||Ee(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 lc(e){let t=e.readCache();if(sc(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=ac({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 cc(){try{return Xl(pt)?JSON.parse(ec(pt,"utf-8")):{}}catch{return{}}}function uc(e){try{Zl(F,{recursive:!0}),tc(pt,JSON.stringify(e,null,2)+`
355
- `,"utf-8")}catch{}}async function dc(){try{let e=await fetch(nc,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(ic)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function Po(e){try{return await lc({current:e,now:new Date,fetchLatest:dc,readCache:cc,writeCache:uc})}catch{return null}}async function G(e={}){let t=Ro(process.cwd());if(t.refreshed){try{ce(process.cwd())}catch{}e.silent||l.info(re.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}ue(process.cwd());let n=await Po(C);n&&l.message(re.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?pc():null;i?.start(`${o} ${re.dim(".seoagent/")} with your dashboard\u2026`);let s=await Io(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.`,re.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.`,re.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.",re.green("Already in sync."));return}if(s.reason==="busy"){w(i,"info","Another sync is in progress \u2014 skipping this run.",re.dim("Another sync is in progress \u2014 skipping this run."));return}let a=fc(s);w(i,"success",a??"Sync complete.",re.green(a??"Sync complete.")),s.synced>0&&l.success(`Synced ${s.synced} file${s.synced===1?"":"s"} to your dashboard.`);let c=s.pull;if(c){let u=c.written+c.overwritten;u>0&&l.success(`Pulled ${u} file${u===1?"":"s"} from the cloud`+(c.overwritten>0?` (${c.overwritten} updated)`:"")),c.deleted>0&&l.info(`Removed ${c.deleted} file${c.deleted===1?"":"s"} deleted in the cloud.`),c.conflicts>0&&l.warn(`${c.conflicts} conflict${c.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let d of c.warnings.slice(0,5))l.info(` \u2022 ${d}`)}if(s.acksFlushed&&s.acksFlushed>0&&l.success(`Flushed ${s.acksFlushed} offline ack${s.acksFlushed===1?"":"s"} from the queue.`),s.acksDropped&&s.acksDropped>0&&l.info(`Dropped ${s.acksDropped} stale ack${s.acksDropped===1?"":"s"} (already settled server-side).`),s.actionsPulled&&s.actionsPulled>0&&(l.success(`Pulled ${s.actionsPulled} pending action${s.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||l.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),s.actionsRemoved&&s.actionsRemoved>0&&l.info(`Cleaned up ${s.actionsRemoved} stale inbox file${s.actionsRemoved===1?"":"s"}.`),s.failed>0){l.warn(`${s.failed} file${s.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let u of s.errors.slice(0,3))l.info(` \u2022 ${u}`)}}function fc(e){let t=e.synced,n=e.pull?e.pull.written+e.pull.overwritten:0,r=e.actionsPulled??0,o=e.acksFlushed??0,i=e.pull?.conflicts??0,s=[];return o>0&&s.push(`${o} ack${o===1?"":"s"} flushed`),t>0&&s.push(`${t} pushed`),n>0&&s.push(`${n} pulled`),r>0&&s.push(`${r} action${r===1?"":"s"}`),i>0&&s.push(`${i} conflict${i===1?"":"s"}`),s.length===0&&e.failed===0?null:s.length>0?s.join(" \xB7 "):"Sync complete."}function D(e){let t=S(e);return t||(l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function ge(e={}){if(e.print){let t=P();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let n=t.api_base||E.BASE,r=await po({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
+ `;mn(Oe(t,"README.md"),r,"utf-8")}function po(e,t){let n=ee(e);ic(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=cc(n,r),i=0;for(let s of t){let a=yc(s);a!==null&&(mn(Oe(n,uo(s)),a,"utf-8"),i++)}return mn(Oe(n,"README.md"),wc(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as vc}from"crypto";import{existsSync as go,mkdirSync as xc,readFileSync as _c,statSync as ho,writeFileSync as mo,rmSync as Cc}from"fs";import{dirname as Ec,join as hn,sep as Ac}from"path";function $c(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Sc=[{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 fo(e,t){let n=$c(e);for(let{cls:r,test:o}of Sc)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function Rc(e){return"sha256:"+vc("sha256").update(e).digest("hex")}function Ic(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 Pc(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:fo(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 yo(e){let t=await ko({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 wo(e,t){return hn(e,t.split("/").join(Ac))}function Oc(e,t,n){let r={};for(let o of t){let i=wo(e,o);if(!go(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=ho(i),a=n[o],l=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:Rc(_c(i,"utf-8")),locallyEdited:l}}return r}async function ko(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 bo(e){let t=hn(e.projectDir,k),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!go(t))return{...n,ok:!0};let r=await ko({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=Oc(t,i,e.stateFiles),a=Ic(o,s,{force:e.force}),l={...n,cursor:o.now};for(let p of a){let d=wo(t,p.path);try{switch(p.kind){case"skip":l.skipped++;break;case"write":case"overwrite":{xc(Ec(d),{recursive:!0}),mo(d,p.body??"","utf-8");let g=ho(d);e.stateFiles[p.path]={mtime:g.mtimeMs,size:g.size},p.kind==="write"?l.written++:l.overwritten++,p.note&&l.warnings.push(`${p.path}: ${p.note}`);break}case"conflict":l.conflicts++,l.warnings.push(`${p.path}: ${p.note??"conflict"}`);break;case"delete":Cc(d,{force:!0}),delete e.stateFiles[p.path],l.deleted++;break;case"delete-skipped":l.conflicts++,l.warnings.push(`${p.path}: ${p.note??"delete skipped"}`);break}}catch(g){l.ok=!1,l.error=`${p.path}: ${g.message}`}}(l.conflicts>0||!l.ok)&&(l.cursor=e.since);let u=Pc(a,o,l.cursor,new Date().toISOString());if(u)try{mo(hn(t,ht),JSON.stringify(u,null,2)+`
353
+ `,"utf-8")}catch{}return l}import{existsSync as So,mkdirSync as vo,readFileSync as Tc,writeFileSync as yn}from"fs";import{dirname as xo,join as jc}from"path";var wn=1,$o=500;function kn(e){return jc(e,k,zn)}function jt(e){let t=kn(e);if(!So(t))return[];try{let n=Tc(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==wn||!Array.isArray(o.entries)?[]:o.entries.filter(Lc)}catch{return[]}}function _o(e,t){let n=kn(e),o=jt(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>$o?o.slice(-$o):o,s={version:wn,entries:i};try{vo(xo(n),{recursive:!0}),yn(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function Co(e,t){if(t.length===0)return;let n=kn(e),r=jt(e).filter(i=>!t.includes(i.action_id)),o={version:wn,entries:r};try{if(r.length===0&&So(n)){yn(n,JSON.stringify(o,null,2),"utf-8");return}vo(xo(n),{recursive:!0}),yn(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function Lc(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 Eo,readFileSync as Nc,unlinkSync as Fc,writeFileSync as Dc,openSync as Uc,closeSync as Mc,mkdirSync as Bc}from"fs";import{dirname as Gc,join as Kc}from"path";var Wc=6e4;function Ao(e){return Kc(e,k,Jn)}function Ro(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??Wc,i=Ao(e);if(!Eo(i))return Lt(i,r,n());let s=Po(i);return!s||n()-s.started_at>o||!qc(s.pid)?Lt(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function Io(e,t={}){let n=t.pid??process.pid,r=Ao(e);if(!Eo(r))return;let o=Po(r);if(!(o&&o.pid!==n))try{Fc(r)}catch{}}function Lt(e,t,n){let r={pid:t,started_at:n};try{Bc(Gc(e),{recursive:!0});let o=Uc(e,"w");try{Dc(o,JSON.stringify(r))}finally{Mc(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Po(e){try{let t=Nc(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 qc(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var Xc=new Set([".md"]),Zc=new Set(["inbox"]);function el(e){let t=[];function n(r,o){if(bn(r))for(let i of Yc(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Zc.has(i.name))continue;let s=$n(r,i.name);if(i.isDirectory())n(s,o?`${o}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),l=a===-1?"":i.name.slice(a);Xc.has(l)&&t.push(s)}}}return n(e,""),t}function To(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return $n(Vt,`${t}.json`)}function tl(e){let t=To(e);if(!bn(t))return{files:{},last_synced_at:null};try{return JSON.parse(Oo(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function nl(e,t){Hc(Vt,{recursive:!0}),Jc(To(e),JSON.stringify(t,null,2)+`
354
+ `,"utf-8")}function rl(e,t){return Vc(e,t).split(Qc).join("/")}async function ol(e,t){try{let n=await J(`${e}/api/cli/actions/fetch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t},body:JSON.stringify({})});if(!n.ok){let o=await n.text().catch(()=>"");return{ok:!1,actions:[],error:`${n.status} ${o.slice(0,200)}`}}let r=await n.json().catch(()=>null);return!r||r.status!=="ok"||!Array.isArray(r.actions)?{ok:!1,actions:[],error:"Malformed response"}:{ok:!0,actions:r.actions}}catch(n){return{ok:!1,actions:[],error:n.message}}}async function il(e,t,n){try{let r=await J(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,status:r.status,error:o.slice(0,200)}}return{ok:!0,status:r.status}}catch(r){return{ok:!1,status:0,error:r.message}}}async function jo(e,t={}){let n=T();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=$n(e,k);if(!bn(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!Ro(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await sl(e,t,n,r,o)}finally{Io(e)}}async function sl(e,t,n,r,o){let i=tl(r.domain),s=el(o),a=n.api_base||A.BASE,l=`Bearer ${n.user_token}:${n.website_token}`,u=0,p=0,d=[],g=0,m=await al(e,a,l);if(!t.pullOnly)for(let F of s){let Fe=rl(o,F);if(t.pathFilter&&!Fe.endsWith(t.pathFilter))continue;let ft=zc(F),zt=i.files[Fe];if(!(!zt||zt.mtime!==ft.mtimeMs||zt.size!==ft.size)&&!t.force)continue;g++;let Ai=Oo(F,"utf-8"),Jt=await il(a,{path:Fe,contents:Ai,domain:r.domain},l);Jt.ok?(i.files[Fe]={mtime:ft.mtimeMs,size:ft.size},u++):(p++,d.push(`${Fe}: ${Jt.status} ${Jt.error??""}`.trim()))}let v=await ol(a,l),$=0,O=0;if(v.ok){let F=po(e,v.actions);$=F.wrote,O=F.removed}else v.error&&d.push(`pull actions: ${v.error}`);let x,N=!1,X=i.last_synced_at;if(!t.pushOnly){let F=await bo({projectDir:e,apiBase:a,authHeader:l,since:i.last_synced_at,stateFiles:i.files,force:t.force});F.ok?X=F.cursor:(N=!0,F.error&&d.push(`pull: ${F.error}`)),x={written:F.written,overwritten:F.overwritten,skipped:F.skipped,conflicts:F.conflicts,deleted:F.deleted,warnings:F.warnings}}let G=!!x&&x.written+x.overwritten+x.deleted+x.conflicts>0;if(i.last_synced_at=X,nl(r.domain,i),g===0&&$===0&&O===0&&!G&&m.flushed===0&&m.dropped===0&&!N&&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 pt=p===0&&!N;return{ok:pt,reason:pt?void 0:"error",synced:u,failed:p,errors:d,actionsPulled:$,actionsRemoved:O,acksFlushed:m.flushed,acksDropped:m.dropped,pull:x}}async function al(e,t,n){let r=jt(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let l=await cl(a,t,n);l==="flushed"?(o++,s.push(a.action_id)):l==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&Co(e,s),{flushed:o,dropped:i}}async function cl(e,t,n){try{let r=await J(`${t}/api/cli/actions/${e.action_id}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify({status:e.status,error_message:e.status==="failed"?e.reason:null,result:e.status==="failed"?{declined:!0,reason:e.reason}:{applied:!0}})});return r.ok?"flushed":r.status===409||r.status>=400&&r.status<500?"already-settled":"transient"}catch{return"transient"}}function Lo(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(Ie(E,n)<=0){if(!t.skill_version)try{H(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return Se(e),H(e,{skill_version:E}),{refreshed:!0,from:n,to:E,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function Sn(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 Se(e),H(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 ll,mkdirSync as ul,readFileSync as dl,writeFileSync as pl}from"fs";var fl="https://registry.npmjs.org/@seoagent-official/seoagent/latest",ml=1440*60*1e3,gl=720*60*1e3,hl=2e3;function yl(e,t,n=ml){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function wl(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??gl;if(!n||Ie(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 kl(e){let t=e.readCache();if(yl(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=wl({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 bl(){try{return ll(yt)?JSON.parse(dl(yt,"utf-8")):{}}catch{return{}}}function $l(e){try{ul(U,{recursive:!0}),pl(yt,JSON.stringify(e,null,2)+`
355
+ `,"utf-8")}catch{}}async function Sl(){try{let e=await fetch(fl,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(hl)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function No(e){try{return await kl({current:e,now:new Date,fetchLatest:Sl,readCache:bl,writeCache:$l})}catch{return null}}async function W(e={}){let t=Lo(process.cwd());if(t.refreshed){try{pe(process.cwd())}catch{}e.silent||c.info(ae.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}fe(process.cwd());let n=await No(E);n&&c.message(ae.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?vl():null;i?.start(`${o} ${ae.dim(".seoagent/")} with your dashboard\u2026`);let s=await jo(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.`,ae.dim("Not logged in \u2014 cloud sync skipped.")),i&&c.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.`,ae.dim("No SEOAgent project \u2014 sync skipped.")),i&&c.info(`Run \`${f("init")}\` first.`);return}if(s.reason==="no-changes"){w(i,"info","Already in sync.",ae.green("Already in sync."));return}if(s.reason==="busy"){w(i,"info","Another sync is in progress \u2014 skipping this run.",ae.dim("Another sync is in progress \u2014 skipping this run."));return}let a=xl(s);w(i,"success",a??"Sync complete.",ae.green(a??"Sync complete.")),s.synced>0&&c.success(`Synced ${s.synced} file${s.synced===1?"":"s"} to your dashboard.`);let l=s.pull;if(l){let u=l.written+l.overwritten;u>0&&c.success(`Pulled ${u} file${u===1?"":"s"} from the cloud`+(l.overwritten>0?` (${l.overwritten} updated)`:"")),l.deleted>0&&c.info(`Removed ${l.deleted} file${l.deleted===1?"":"s"} deleted in the cloud.`),l.conflicts>0&&c.warn(`${l.conflicts} conflict${l.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let p of l.warnings.slice(0,5))c.info(` \u2022 ${p}`)}if(s.acksFlushed&&s.acksFlushed>0&&c.success(`Flushed ${s.acksFlushed} offline ack${s.acksFlushed===1?"":"s"} from the queue.`),s.acksDropped&&s.acksDropped>0&&c.info(`Dropped ${s.acksDropped} stale ack${s.acksDropped===1?"":"s"} (already settled server-side).`),s.actionsPulled&&s.actionsPulled>0&&(c.success(`Pulled ${s.actionsPulled} pending action${s.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||c.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),s.actionsRemoved&&s.actionsRemoved>0&&c.info(`Cleaned up ${s.actionsRemoved} stale inbox file${s.actionsRemoved===1?"":"s"}.`),s.failed>0){c.warn(`${s.failed} file${s.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let u of s.errors.slice(0,3))c.info(` \u2022 ${u}`)}}function xl(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 M(e){let t=_(e);return t||(c.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function we(e={}){if(e.print){let t=T();if(!t){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!M(process.cwd()))return;let n=t.api_base||A.BASE,r=await yo({apiBase:n,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!r.ok){c.warn(r.error),process.exitCode=1;return}process.stdout.write(r.body),r.body.endsWith(`
356
356
  `)||process.stdout.write(`
357
- `);return}await G({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as mc,readdirSync as gc,unlinkSync as hc}from"fs";import{join as Oo}from"path";import{isCancel as yc,select as wc}from"@clack/prompts";async function oe(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 kc(),n===null)return;let r=n,o=P();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let i=o.api_base||E.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",c;try{c=await Y(`${i}/api/cli/actions/${r}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:s},body:JSON.stringify({status:a,error_message:t.failed&&t.reason?t.reason:null,result:t.failed?{declined:!0,reason:t.reason??null}:{applied:!0}})})}catch{bo(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),hn(r),At(process.cwd()),t.silent||l.warn(`Network unavailable \u2014 ack queued locally. Run \`${f("sync")}\` when you're back online; it'll flush automatically.`);return}if(!c.ok){let u=await c.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(c.status===409&&d?.code==="already_acked"){hn(r),At(process.cwd());let v=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||l.success(`Action ${r} was already ${v}.`);return}let p=typeof d?.code=="string"?d.code:null,y=typeof d?.error=="string"?d.error:u,m=p?`, code: ${p}`:"";l.error(`Server rejected ack (${c.status}${m}): ${y.slice(0,200)}`),process.exitCode=1;return}hn(r),At(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: ${Oo(k,"inbox")}`))}function hn(e){let t=Q(process.cwd());if(mc(t)){for(let n of gc(t))if(n.endsWith(`-${e}.md`))try{hc(Oo(t,n))}catch{}}}async function kc(){let e=process.cwd(),t=me(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 wc({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Re(r)}))});return yc(n)?(l.info("Cancelled \u2014 no action closed out."),null):n}import Pt from"picocolors";async function yn(e={}){let t=process.cwd();if(!e.json&&!D(t))return;let n=me(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:Q(t),actions:n})+`
358
- `);return}if(n.length===0){l.info(Pt.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(`${Pt.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(Re(r));l.message(""),l.message(`Apply one: ${Pt.bold(f("ack <id>"))} \xB7 Interactive picker: ${Pt.bold(f("ack"))} (no id)`)}import{readFileSync as Ic}from"fs";import{join as Rc,relative as Pc}from"path";import{confirm as Fo,isCancel as Tt,multiselect as Oc,note as Mo,select as Tc}from"@clack/prompts";import g from"picocolors";import{query as jc}from"@anthropic-ai/claude-agent-sdk";import{existsSync as bc,readdirSync as $c}from"fs";import{homedir as Sc}from"os";import{join as vc}from"path";import{execSync as wn}from"child_process";function Qe(){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":xc()?_c()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function xc(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return wn(e,{stdio:"ignore"}),!0}catch{return!1}}function _c(){let e=vc(Sc(),".claude");if(!bc(e))return!1;try{return $c(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function To(){try{return wn("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function jo(){try{return wn("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var X={"env-key":{summary:"Using ANTHROPIC_API_KEY env var.",next:""},enterprise:{summary:"Using enterprise provider (Bedrock / Vertex / Foundry).",next:""},"claude-session-likely":{summary:"Using your existing `claude login` session.",next:""},"claude-installed-no-session":{summary:"Claude Code is installed but you are not logged in.",next:"Run `claude login` to sign in with your Claude.ai / Pro / Max account, or set `ANTHROPIC_API_KEY` and re-run."},"not-installed":{summary:"Claude Code is not installed on this machine.",next:"Install it with `npm install -g @anthropic-ai/claude-code` then `claude login`, or set `ANTHROPIC_API_KEY` (get one at https://console.anthropic.com/) and re-run."}};import{marked as No}from"marked";import{markedTerminal as Cc}from"marked-terminal";import kn from"picocolors";var Lo=!1;function Ec(){Lo||(No.use(Cc({reflowText:!1,width:100})),Lo=!0)}function Ot(e){if(!e)return e;Ec();try{let t=No.parse(e);return typeof t=="string"?Ac(t):e}catch{return e}}function Ac(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>kn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>kn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+kn.italic(r))}async function $n(e={}){let t=process.cwd();if(!D(t))return;if(!process.stdout.isTTY&&!e.yes){l.error(`\`${f("process")}\` needs an interactive TTY for the sync + selection prompts. Use \`--yes\` to skip prompts and process everything (for CI/CD).`),process.exitCode=1;return}if(!await Mc(e.yes)){process.exitCode=1;return}if(e.yes)await G({embedded:!0});else{let u=await Tc({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(Tt(u)){l.info("Cancelled.");return}u==="sync"?await G({embedded:!0}):u==="pull"&&await ge({embedded:!0})}let r=me(t);if(r.length===0){l.info(g.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),l.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(m=>m.priority!==null),d=u?r.filter(m=>m.priority==="high").map(m=>m.id):r.map(m=>m.id),p=u&&d.length===0?" (no high-priority actions \u2014 toggle to select)":u?` (${d.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",y=await Oc({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(m=>({value:m.id,label:Re(m)})),initialValues:d,required:!1});if(Tt(y)){l.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(y)||y.length===0){l.info("No actions selected. Nothing to do.");return}o=y}let i=0,s=0,a=0,c=Date.now();for(let u=0;u<o.length;u++){let d=o[u],p=r.find(_=>_.id===d);if(!p)continue;Lc({index:u+1,total:o.length,entry:p});let y=Rc(Q(t),p.filename),m;try{m=Ic(y,"utf-8")}catch(_){l.error(` Could not read ${p.filename}: ${_.message}`),a++;continue}let v=Date.now(),I=await Uc({cwd:t,entry:p,actionContent:m,model:e.model}),J=Do(Date.now()-v);if(I.kind==="applied")try{await oe(String(d),{silent:!0}),i++,l.message("");let _=I.summary?`
359
- `+g.dim(" "+I.summary):"";l.message(` ${g.green("\u2713")} id ${d} ${g.dim("\u2014 applied in "+J)}${_}`)}catch(_){l.warn(` Applied but ack failed: ${_.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(I.kind==="declined")try{await oe(String(d),{silent:!0,failed:!0,reason:I.reason}),s++,l.message(""),l.message(` ${g.yellow("\u2298")} id ${d} ${g.dim("\u2014 declined: "+q(I.reason,100))}`)}catch(_){l.warn(` Could not ack decline: ${_.message}. Run \`seoagent ack ${d} --failed --reason "${I.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${g.red("\u2717")} id ${d} ${g.dim("\u2014 agent did not converge after "+J)}`)}Fc({applied:i,declined:s,failed:a,total:o.length,elapsed:Do(Date.now()-c)})}function Lc(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=Nc[i]??g.dim,a=[g.bold(`[${t}/${n}]`),g.dim("\xB7"),g.bold(`id ${r.id}`),g.dim("\xB7"),g.cyan(o),s(i)].join(" ");Mo(r.title,a)}var Nc={critical:e=>g.red(g.bold(e)),high:g.red,medium:g.yellow,low:g.dim};function Fc(e){let{applied:t,declined:n,failed:r,total:o,elapsed:i}=e,s=t+n,a;if(s===o&&r===0)a=n===0?g.green(`\u2713 ${t}/${o} applied`):g.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=g.red(`\u2717 0/${o} applied`);else{let c=[`${t}/${o} applied`];n>0&&c.push(`${n} declined`),r>0&&c.push(`${r} failed`),a=g.yellow(`\u25D0 ${c.join(" \xB7 ")}`)}Mo(`${a}
360
- ${g.dim("elapsed: "+i)}`,g.bold("Done"))}function Do(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 Dc(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 Uc(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=Vc(n,r);try{let s=jc({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...o?{model:o}:{}}}),a={toolUseById:new Map};for await(let c of s)if(c.type==="assistant"){let u=c.message.content;if(Array.isArray(u))for(let d of u)Gc(d,a)}else if(c.type==="user"){let u=c.message.content;if(Array.isArray(u))for(let d of u)qc(d,a)}else if(c.type==="result"){if(process.stdout.write(`
362
- `),!(c.subtype==="success"&&!c.is_error))return{kind:"failed"};let d=Dc(c.result);return d?.kind==="declined"?{kind:"declined",reason:d.reason}:{kind:"applied",summary:d?.kind==="applied"?d.summary:void 0}}return{kind:"failed"}}catch(s){return process.stdout.write(`
363
- `),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function Mc(e){let t=Qe();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return l.info(g.dim(X[t].summary)),!0;if(l.warn(X[t].summary),l.message(` ${X[t].next}`),e)return!1;if(t==="not-installed"){let n=await Fo({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(Tt(n)||!n)return l.info("Skipped install. Set up auth and re-run when ready."),!1;l.message(g.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=To();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=Qe()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await Fo({message:"Run `claude login` now to sign in?",initialValue:!0});if(Tt(n)||!n)return l.info("Skipped login. Run `claude login` when ready and try again."),!1;l.message(g.dim("Launching `claude login`\u2026"));let r=jo();if(!r.ok)return l.error(`Login failed: ${r.error}`),!1}return!0}function Bc(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function Gc(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&Bc(e)){process.stdout.write(Ot(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=Wc[o]??g.cyan,a=Jc(o,i);process.stdout.write(s(Kc)+" "+g.bold(o)+g.dim("(")+a+g.dim(")")+`
364
- `);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(g.dim(g.italic(" "+q(r,200)))+`
365
- `)}}var Kc="\u23FA",Uo="\u23BF",Wc={Read:g.blue,Glob:g.cyan,Grep:g.cyan,Edit:g.yellow,Write:g.magenta,Bash:g.green,WebFetch:g.magenta,WebSearch:g.magenta};function qc(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=Hc(s);if(n){process.stdout.write(g.red(` ${Uo} Error`)+`
366
- `),a&&process.stdout.write(zc(q(a,500)," ",g.red)+`
367
- `);return}let c=Yc(i,a,o?.input);c&&process.stdout.write(g.dim(` ${Uo} `)+c+`
368
- `)}function Hc(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 Yc(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
- `).filter(Boolean).length;return g.dim(`Read ${o} line${o===1?"":"s"}`)}case"Glob":{let r=t.split(`
370
- `).filter(o=>o.trim().length>0).length;return g.dim(`Found ${r} ${r===1?"entry":"entries"}`)}case"Grep":{let r=t.split(`
371
- `)[0]?.trim()??"";if(/^Found\s+\d+/.test(r))return g.dim(r);let o=t.split(`
372
- `).filter(i=>i.trim()).length;return g.dim(`${o} result${o===1?"":"s"}`)}case"Edit":case"Write":{let r=n?.file_path,o=e==="Edit"?"Updated":"Created";return g.dim(r?`${o} ${bn(String(r))}`:o)}case"Bash":{let r=t.split(`
373
- `),o=r.slice(0,5).map(u=>q(u.trimEnd(),100)),i=r.length-5,s=o.join(`
357
+ `);return}await W({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as _l,readdirSync as Cl,unlinkSync as El}from"fs";import{join as Fo}from"path";import{isCancel as Al,select as Rl}from"@clack/prompts";async function ce(e,t={}){let n=null;if(e){let u=Number.parseInt(e,10);if(Number.isNaN(u)||u<=0){c.error(`Invalid action id: "${e}"`),process.exitCode=1;return}n=u}else if(n=await Il(),n===null)return;let r=n,o=T();if(!o){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!M(process.cwd()))return;let i=o.api_base||A.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",l;try{l=await J(`${i}/api/cli/actions/${r}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:s},body:JSON.stringify({status:a,error_message:t.failed&&t.reason?t.reason:null,result:t.failed?{declined:!0,reason:t.reason??null}:{applied:!0}})})}catch{_o(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),vn(r),Tt(process.cwd()),t.silent||c.warn(`Network unavailable \u2014 ack queued locally. Run \`${f("sync")}\` when you're back online; it'll flush automatically.`);return}if(!l.ok){let u=await l.text().catch(()=>""),p=null;try{p=JSON.parse(u)}catch{p=null}if(l.status===409&&p?.code==="already_acked"){vn(r),Tt(process.cwd());let v=typeof p.error=="string"?p.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||c.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}`:"";c.error(`Server rejected ack (${l.status}${m}): ${g.slice(0,200)}`),process.exitCode=1;return}vn(r),Tt(process.cwd()),!t.silent&&(t.failed?c.success(`Action ${r} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):c.success(`Action ${r} marked completed.`),c.info(` inbox location: ${Fo(k,"inbox")}`))}function vn(e){let t=ee(process.cwd());if(_l(t)){for(let n of Cl(t))if(n.endsWith(`-${e}.md`))try{El(Fo(t,n))}catch{}}}async function Il(){let e=process.cwd(),t=ye(e);if(t.length===0)return c.info("No pending actions in .seoagent/inbox/."),c.message(`Run \`${f("sync")}\` to pull anything autopilot has queued.`),null;if(!process.stdout.isTTY)return c.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 Rl({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Te(r)}))});return Al(n)?(c.info("Cancelled \u2014 no action closed out."),null):n}import Nt from"picocolors";async function xn(e={}){let t=process.cwd();if(!e.json&&!M(t))return;let n=ye(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:ee(t),actions:n})+`
358
+ `);return}if(n.length===0){c.info(Nt.dim("No pending actions.")),c.message(`Run \`${f("sync")}\` to pull anything autopilot has queued, or \`${f("autopilot status")}\` to check whether autopilot is on.`);return}c.message(`${Nt.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),c.message("");for(let r of n)c.message(Te(r));c.message(""),c.message(`Apply one: ${Nt.bold(f("ack <id>"))} \xB7 Interactive picker: ${Nt.bold(f("ack"))} (no id)`)}import{readFileSync as Ml}from"fs";import{join as Bl,relative as Gl}from"path";import{confirm as Go,isCancel as Dt,multiselect as Kl,note as qo,select as Wl}from"@clack/prompts";import h from"picocolors";import{query as ql}from"@anthropic-ai/claude-agent-sdk";import{existsSync as Pl,readdirSync as Ol}from"fs";import{homedir as Tl}from"os";import{join as jl}from"path";import{execSync as _n}from"child_process";function et(){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":Ll()?Nl()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function Ll(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return _n(e,{stdio:"ignore"}),!0}catch{return!1}}function Nl(){let e=jl(Tl(),".claude");if(!Pl(e))return!1;try{return Ol(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function Do(){try{return _n("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function Uo(){try{return _n("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var te={"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 Bo}from"marked";import{markedTerminal as Fl}from"marked-terminal";import Cn from"picocolors";var Mo=!1;function Dl(){Mo||(Bo.use(Fl({reflowText:!1,width:100})),Mo=!0)}function Ft(e){if(!e)return e;Dl();try{let t=Bo.parse(e);return typeof t=="string"?Ul(t):e}catch{return e}}function Ul(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>Cn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>Cn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+Cn.italic(r))}async function An(e={}){let t=process.cwd();if(!M(t))return;if(!process.stdout.isTTY&&!e.yes){c.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 Ql(e.yes)){process.exitCode=1;return}if(e.yes)await W({embedded:!0});else{let u=await Wl({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(Dt(u)){c.info("Cancelled.");return}u==="sync"?await W({embedded:!0}):u==="pull"&&await we({embedded:!0})}let r=ye(t);if(r.length===0){c.info(h.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),c.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 Kl({message:`Which actions to process? ${r.length} pending \u2014${d}`,options:r.map(m=>({value:m.id,label:Te(m)})),initialValues:p,required:!1});if(Dt(g)){c.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(g)||g.length===0){c.info("No actions selected. Nothing to do.");return}o=g}let i=0,s=0,a=0,l=Date.now();for(let u=0;u<o.length;u++){let p=o[u],d=r.find(x=>x.id===p);if(!d)continue;Hl({index:u+1,total:o.length,entry:d});let g=Bl(ee(t),d.filename),m;try{m=Ml(g,"utf-8")}catch(x){c.error(` Could not read ${d.filename}: ${x.message}`),a++;continue}let v=Date.now(),$=await Vl({cwd:t,entry:d,actionContent:m,model:e.model}),O=Ko(Date.now()-v);if($.kind==="applied")try{await ce(String(p),{silent:!0}),i++,c.message("");let x=$.summary?`
359
+ `+h.dim(" "+$.summary):"";c.message(` ${h.green("\u2713")} id ${p} ${h.dim("\u2014 applied in "+O)}${x}`)}catch(x){c.warn(` Applied but ack failed: ${x.message}. Run \`seoagent ack ${p}\` to retry.`)}else if($.kind==="declined")try{await ce(String(p),{silent:!0,failed:!0,reason:$.reason}),s++,c.message(""),c.message(` ${h.yellow("\u2298")} id ${p} ${h.dim("\u2014 declined: "+Y($.reason,100))}`)}catch(x){c.warn(` Could not ack decline: ${x.message}. Run \`seoagent ack ${p} --failed --reason "${$.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,c.message(""),c.message(` ${h.red("\u2717")} id ${p} ${h.dim("\u2014 agent did not converge after "+O)}`)}zl({applied:i,declined:s,failed:a,total:o.length,elapsed:Ko(Date.now()-l)})}function Hl(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=Yl[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(" ");qo(r.title,a)}var Yl={critical:e=>h.red(h.bold(e)),high:h.red,medium:h.yellow,low:h.dim};function zl(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 l=[`${t}/${o} applied`];n>0&&l.push(`${n} declined`),r>0&&l.push(`${r} failed`),a=h.yellow(`\u25D0 ${l.join(" \xB7 ")}`)}qo(`${a}
360
+ ${h.dim("elapsed: "+i)}`,h.bold("Done"))}function Ko(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 Jl(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 Vl(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=au(n,r);try{let s=ql({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...o?{model:o}:{}}}),a={toolUseById:new Map};for await(let l of s)if(l.type==="assistant"){let u=l.message.content;if(Array.isArray(u))for(let p of u)Zl(p,a)}else if(l.type==="user"){let u=l.message.content;if(Array.isArray(u))for(let p of u)nu(p,a)}else if(l.type==="result"){if(process.stdout.write(`
362
+ `),!(l.subtype==="success"&&!l.is_error))return{kind:"failed"};let p=Jl(l.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
+ `),c.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function Ql(e){let t=et();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return c.info(h.dim(te[t].summary)),!0;if(c.warn(te[t].summary),c.message(` ${te[t].next}`),e)return!1;if(t==="not-installed"){let n=await Go({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(Dt(n)||!n)return c.info("Skipped install. Set up auth and re-run when ready."),!1;c.message(h.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=Do();if(!r.ok)return c.error(`Install failed: ${r.error}`),c.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=et()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await Go({message:"Run `claude login` now to sign in?",initialValue:!0});if(Dt(n)||!n)return c.info("Skipped login. Run `claude login` when ready and try again."),!1;c.message(h.dim("Launching `claude login`\u2026"));let r=Uo();if(!r.ok)return c.error(`Login failed: ${r.error}`),!1}return!0}function Xl(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function Zl(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&Xl(e)){process.stdout.write(Ft(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=tu[o]??h.cyan,a=su(o,i);process.stdout.write(s(eu)+" "+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(" "+Y(r,200)))+`
365
+ `)}}var eu="\u23FA",Wo="\u23BF",tu={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 nu(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=ru(s);if(n){process.stdout.write(h.red(` ${Wo} Error`)+`
366
+ `),a&&process.stdout.write(iu(Y(a,500)," ",h.red)+`
367
+ `);return}let l=ou(i,a,o?.input);l&&process.stdout.write(h.dim(` ${Wo} `)+l+`
368
+ `)}function ru(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 ou(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
+ `).filter(Boolean).length;return h.dim(`Read ${o} line${o===1?"":"s"}`)}case"Glob":{let r=t.split(`
370
+ `).filter(o=>o.trim().length>0).length;return h.dim(`Found ${r} ${r===1?"entry":"entries"}`)}case"Grep":{let r=t.split(`
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} ${En(String(r))}`:o)}case"Bash":{let r=t.split(`
373
+ `),o=r.slice(0,5).map(u=>Y(u.trimEnd(),100)),i=r.length-5,s=o.join(`
374
374
  `)+(i>0?`
375
- \u2026 (+${i} more line${i===1?"":"s"})`:""),[a,...c]=s.split(`
376
- `);return c.length===0?g.dim(a):g.dim(a)+`
377
- `+g.dim(c.map(u=>" "+u).join(`
378
- `))}case"WebFetch":case"WebSearch":return g.dim(`Fetched ${q(t.replace(/\s+/g," "),80)}`);default:return""}}function zc(e,t,n){return e.split(`
375
+ \u2026 (+${i} more line${i===1?"":"s"})`:""),[a,...l]=s.split(`
376
+ `);return l.length===0?h.dim(a):h.dim(a)+`
377
+ `+h.dim(l.map(u=>" "+u).join(`
378
+ `))}case"WebFetch":case"WebSearch":return h.dim(`Fetched ${Y(t.replace(/\s+/g," "),80)}`);default:return""}}function iu(e,t,n){return e.split(`
379
379
  `).map(r=>n(t+r)).join(`
380
- `)}function Jc(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return g.dim(q(bn(String(n.file_path??"")),80));case"Bash":return g.dim(q(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${bn(String(n.path))}`:"";return g.dim(q(r+o,80))}case"Glob":return g.dim(q(String(n.pattern??""),80));case"WebFetch":return g.dim(q(String(n.url??""),80));case"WebSearch":return g.dim(q(String(n.query??""),80));default:return""}}function bn(e){if(!e)return e;let t=process.cwd(),n=Pc(t,e);return n.startsWith("..")?e:n||e}function q(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Vc(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
380
+ `)}function su(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return h.dim(Y(En(String(n.file_path??"")),80));case"Bash":return h.dim(Y(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${En(String(n.path))}`:"";return h.dim(Y(r+o,80))}case"Glob":return h.dim(Y(String(n.pattern??""),80));case"WebFetch":return h.dim(Y(String(n.url??""),80));case"WebSearch":return h.dim(Y(String(n.query??""),80));default:return""}}function En(e){if(!e)return e;let t=process.cwd(),n=Gl(t,e);return n.startsWith("..")?e:n||e}function Y(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function au(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 Qc}from"@clack/prompts";import b from"picocolors";var Xc=new Set(["on","off","status"]);async function Xe(e,t={}){let n=(e||"").toLowerCase();if(!Xc.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=P();if(!r){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||E.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?Qc():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 d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){let v=S(process.cwd())?.domain??"",I=`${E.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(Zc(I)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){w(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,b.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:y}=d.autopilot;if(n==="on"){a?.stop(b.green("Autopilot enabled.")),l.message(Sn({enabled:!0,deliveryMode:y,action:n}));return}if(n==="off"){a?.stop(b.dim("Autopilot disabled.")),l.message(Sn({enabled:!1,deliveryMode:y,action:n}));return}a?.stop(b.dim("Status:")),l.message(Sn({enabled:p,deliveryMode:y,action:n}))}function Sn(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 O(o,{width:78,title:i})}function Zc(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 O(t,{width:78,title:n})}import{mkdirSync as du,writeFileSync as pu}from"fs";import{join as vn}from"path";import{readdirSync as eu,readFileSync as tu,statSync as Bo}from"fs";import{join as nu}from"path";var ru=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),ou=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"]),iu=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),su=5e3,au=512*1024;function Ho(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function Go(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&&ou.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var Ko=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Wo=/\]\(\s*([^)\s]+)/g;function lu(e,t){if(!e)return[];let n=Ho(t),r=[],o;for(Ko.lastIndex=0;(o=Ko.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=Go(i,n);s&&r.push(s)}for(Wo.lastIndex=0;(o=Wo.exec(e))!==null;){let i=Go(o[1],n);i&&r.push(i)}return r}function cu(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 Yo(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?` (${Ho(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 cu}from"@clack/prompts";import b from"picocolors";var lu=new Set(["on","off","status"]);async function tt(e,t={}){let n=(e||"").toLowerCase();if(!lu.has(n)){c.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=T();if(!r){c.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?cu():null,l=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(l);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.")),c.message(uu($)),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.")),c.message(Rn({enabled:!0,deliveryMode:g,action:n}));return}if(n==="off"){a?.stop(b.dim("Autopilot disabled.")),c.message(Rn({enabled:!1,deliveryMode:g,action:n}));return}a?.stop(b.dim("Status:")),c.message(Rn({enabled:d,deliveryMode:g,action:n}))}function Rn(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 j(o,{width:78,title:i})}function uu(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 j(t,{width:78,title:n})}import{mkdirSync as Su,writeFileSync as vu}from"fs";import{join as In}from"path";import{readdirSync as du,readFileSync as pu,statSync as Ho}from"fs";import{join as fu}from"path";var mu=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),gu=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"]),hu=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),yu=5e3,wu=512*1024;function Qo(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function Yo(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&&gu.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var zo=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Jo=/\]\(\s*([^)\s]+)/g;function ku(e,t){if(!e)return[];let n=Qo(t),r=[],o;for(zo.lastIndex=0;(o=zo.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=Yo(i,n);s&&r.push(s)}for(Jo.lastIndex=0;(o=Jo.exec(e))!==null;){let i=Yo(o[1],n);i&&r.push(i)}return r}function bu(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 Xo(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?` (${Qo(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=>`| ${qo(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=>`| ${qo(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=>`| ${Vo(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=>`| ${Vo(a.url)} | ${a.inbound} |`)].join(`
405
405
  `);return[r,"",o,"",i,s,""].join(`
406
- `)}function qo(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*uu(e){let t=0;function*n(r){let o;try{o=eu(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=su)return;if(i.name.startsWith("."))continue;let s=nu(r,i.name);if(i.isDirectory()){if(iu.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 zo(e,t){let{pages:n}=Se(e,t),r=[],o=0,i=!1;try{i=Bo(e).isDirectory()}catch{i=!1}if(i)for(let s of uu(e)){let a;try{if(Bo(s).size>au)continue;a=tu(s,"utf-8")}catch{continue}o++;for(let c of lu(a,t))r.push(c)}return cu(n,r,o)}function Ze(e={}){let t=process.cwd(),n=D(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=zo(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
407
- `);return}let i=vn(t,k);du(i,{recursive:!0});let s=vn(i,"internal-links.md");if(pu(s,Yo(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 ${vn(k,"internal-links.md")}`)}import{existsSync as fu,mkdirSync as mu,writeFileSync as gu}from"fs";import{join as Jo}from"path";import xn from"picocolors";function hu(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function yu(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 wu(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 Vo(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*$u(e){let t=0;function*n(r){let o;try{o=du(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=yu)return;if(i.name.startsWith("."))continue;let s=fu(r,i.name);if(i.isDirectory()){if(hu.has(i.name))continue;yield*n(s)}else if(i.isFile()){let a=i.name.lastIndexOf("."),l=a===-1?"":i.name.slice(a+1).toLowerCase();if(!mu.has(l))continue;t++,yield s}}}yield*n(e)}function Zo(e,t){let{pages:n}=_e(e,t),r=[],o=0,i=!1;try{i=Ho(e).isDirectory()}catch{i=!1}if(i)for(let s of $u(e)){let a;try{if(Ho(s).size>wu)continue;a=pu(s,"utf-8")}catch{continue}o++;for(let l of ku(a,t))r.push(l)}return bu(n,r,o)}function nt(e={}){let t=process.cwd(),n=M(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Zo(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
407
+ `);return}let i=In(t,k);Su(i,{recursive:!0});let s=In(i,"internal-links.md");if(vu(s,Xo(o,r),"utf-8"),c.success(`Analyzed ${o.pageCount} page${o.pageCount===1?"":"s"} across ${o.filesScanned} file${o.filesScanned===1?"":"s"}.`),o.orphans.length===0)c.info("No orphan pages \u2014 every page has an inbound internal link.");else{c.warn(`${o.orphans.length} orphan page${o.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of o.orphans.slice(0,10))c.message(` \u2022 ${a.url}`);o.orphans.length>10&&c.message(` \u2026and ${o.orphans.length-10} more`)}c.info(`Report written to ${In(k,"internal-links.md")}`)}import{existsSync as xu,mkdirSync as _u,writeFileSync as Cu}from"fs";import{join as ei}from"path";import Pn from"picocolors";function Eu(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Au(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 Ru(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 _n(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=S(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=hu(o);if(!i){l.error("A slug is required: --slug <slug> (or --file <repo-path> to derive it)."),process.exitCode=1;return}let s=yu(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()||ku(i),c=r.cms&&r.cms!=="mdx-local"?"cms":t.file?"repo":"external",u=wu({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()}),d=Jo(n,k,"content");mu(d,{recursive:!0});let p=Jo(d,`${i}.md`),y=fu(p);gu(p,u,"utf-8"),l.success(`${y?"Updated":"Tracked"} ${xn.bold(i)}${s?` \u2192 ${xn.cyan(s)}`:""} in .seoagent/content/.`);try{await G({silent:!0,pushOnly:!0})}catch{}l.message(xn.dim("It will appear on your dashboard after sync (run `seoagent login` if you haven\u2019t)."))}function ku(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}import{existsSync as bu,readFileSync as $u}from"fs";import{join as Su}from"path";import Cn from"picocolors";function vu(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 xu(e){let t=Su(e,k,dt);if(!bu(t))return null;try{let n=JSON.parse($u(t,"utf-8"));return Array.isArray(n.changes)?n.changes.length:0}catch{return 0}}function En(e={}){let t=process.cwd(),n=S(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=ee(t),o=vu({domain:n.domain,siteType:n.site_type,imageProvider:n.image_provider,detectedImageProvider:r.provider,detectedImageKey:r.matched_key,pullReceiptCount:xu(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(Cn.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)l.message(` ${Cn.yellow("\u25CF")} ${s.message}`),s.fix&&l.message(` ${Cn.dim("\u2192 "+s.fix)}`)}import z from"picocolors";import{existsSync as Pe,mkdirSync as jt,readdirSync as _u,readFileSync as Cu,statSync as Th,writeFileSync as Vo}from"fs";import{dirname as Eu,join as ie,relative as Au,resolve as Iu}from"path";var Oe="okf";function Lt(e){return ie(e,k,Oe)}var Ru=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function An(e){let t=[];for(let n of _u(e,{withFileTypes:!0})){let r=ie(e,n.name);n.isDirectory()?t.push(...An(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function Pu(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 Qo(e){let t=[],n=[];if(!Pe(e))return{ok:!1,fileCount:0,errors:[{file:Oe,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=An(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Oe,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Pe(ie(e,"index.md"))||n.push({file:Oe,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=Au(e,i),a;try{a=Ne(Cu(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!==""&&!Ru.test(String(u))&&t.push({file:s,message:`\`timestamp\` is not ISO-8601: "${String(u)}"`});let d=a.data.description;typeof d=="string"&&d.length>200&&n.push({file:s,message:`\`description\` is ${d.length} chars (keep \u2264 200).`});for(let p of Pu(a.body)){let y=p.split("#")[0];if(!y)continue;let m=Iu(Eu(i),y);Pe(m)||t.push({file:s,message:`Broken link \u2192 "${p}" (target does not exist).`})}}return{ok:t.length===0,fileCount:r.length,errors:t,warnings:n}}function Nt(e){let t=Lt(e);if(!Pe(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:An(t).length}}catch{return{exists:!0,fileCount:0}}}function Xo(e,t){let n=Lt(e);jt(n,{recursive:!0}),jt(ie(n,"concepts"),{recursive:!0}),jt(ie(n,"faqs"),{recursive:!0}),jt(ie(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=ie(n,"index.md");Pe(i)||(Vo(i,`---
414
+ `}async function On(e,t={}){if(e!=="track"){c.message(`Usage: ${f("content track")} --slug <slug> --url <live-url> [--file <repo-path>] [--title "..."] [--type <page_type>] [--status published|draft]`),e&&(c.error(`Unknown content action: ${e}. The only action today is \`track\`.`),process.exitCode=1);return}let n=process.cwd(),r=_(n);if(!r){c.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let o=t.slug??(t.file?t.file:""),i=Eu(o);if(!i){c.error("A slug is required: --slug <slug> (or --file <repo-path> to derive it)."),process.exitCode=1;return}let s=Au(i,{url:t.url,domain:r.domain,blogPath:r.blog_path});s||c.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()||Iu(i),l=r.cms&&r.cms!=="mdx-local"?"cms":t.file?"repo":"external",u=Ru({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:l,repo_path:t.file?.trim()||void 0,tracked_at:new Date().toISOString()}),p=ei(n,k,"content");_u(p,{recursive:!0});let d=ei(p,`${i}.md`),g=xu(d);Cu(d,u,"utf-8"),c.success(`${g?"Updated":"Tracked"} ${Pn.bold(i)}${s?` \u2192 ${Pn.cyan(s)}`:""} in .seoagent/content/.`);try{await W({silent:!0,pushOnly:!0})}catch{}c.message(Pn.dim("It will appear on your dashboard after sync (run `seoagent login` if you haven\u2019t)."))}function Iu(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}import{existsSync as Pu,readFileSync as Ou}from"fs";import{join as Tu}from"path";import Tn from"picocolors";function ju(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 Lu(e){let t=Tu(e,k,ht);if(!Pu(t))return null;try{let n=JSON.parse(Ou(t,"utf-8"));return Array.isArray(n.changes)?n.changes.length:0}catch{return 0}}function jn(e={}){let t=process.cwd(),n=_(t);if(!n){if(e.json){process.stdout.write(JSON.stringify({status:"no-project",findings:[]})+`
415
+ `);return}c.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=oe(t),o=ju({domain:n.domain,siteType:n.site_type,imageProvider:n.image_provider,detectedImageProvider:r.provider,detectedImageKey:r.matched_key,pullReceiptCount:Lu(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){c.success("SEOAgent health: everything looks good.");return}c.message(Tn.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)c.message(` ${Tn.yellow("\u25CF")} ${s.message}`),s.fix&&c.message(` ${Tn.dim("\u2192 "+s.fix)}`)}import V from"picocolors";import{existsSync as je,mkdirSync as Ut,readdirSync as Nu,readFileSync as Fu,statSync as Qh,writeFileSync as ti}from"fs";import{dirname as Du,join as le,relative as Uu,resolve as Mu}from"path";var Le="okf";function Mt(e){return le(e,k,Le)}var Bu=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function Ln(e){let t=[];for(let n of Nu(e,{withFileTypes:!0})){let r=le(e,n.name);n.isDirectory()?t.push(...Ln(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function Gu(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 ni(e){let t=[],n=[];if(!je(e))return{ok:!1,fileCount:0,errors:[{file:Le,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=Ln(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Le,message:"OKF directory exists but contains no markdown files."}],warnings:[]};je(le(e,"index.md"))||n.push({file:Le,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=Uu(e,i),a;try{a=Ue(Fu(i,"utf-8"))}catch{t.push({file:s,message:"Could not read or parse file."});continue}let l=a.data.type;(l==null||String(l).trim()==="")&&t.push({file:s,message:"Missing required frontmatter field `type`."});let u=a.data.timestamp;u!=null&&u!==""&&!Bu.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 Gu(a.body)){let g=d.split("#")[0];if(!g)continue;let m=Mu(Du(i),g);je(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 Bt(e){let t=Mt(e);if(!je(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:Ln(t).length}}catch{return{exists:!0,fileCount:0}}}function ri(e,t){let n=Mt(e);Ut(n,{recursive:!0}),Ut(le(n,"concepts"),{recursive:!0}),Ut(le(n,"faqs"),{recursive:!0}),Ut(le(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=le(n,"index.md");je(i)||(ti(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=ie(n,"log.md");return Pe(s)||(Vo(s,`---
443
+ `,"utf-8"),r.push("index.md"));let s=le(n,"log.md");return je(s)||(ti(s,`---
444
444
  type: Log
445
445
  title: Change log
446
446
  description: Chronological history of changes to this OKF bundle.
@@ -449,15 +449,18 @@ 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 In=`${k}/${Oe}`;function et(e,t={}){let n=process.cwd(),r=D(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=Xo(n,i);a.length===0?l.info(`OKF bundle already scaffolded at ${In}/.`):(l.success(`Scaffolded ${In}/ \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=Qo(Lt(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
453
- `);return}for(let c of a.errors)l.message(`${z.red("\u2717")} ${z.dim(c.file)} \u2014 ${c.message}`);for(let c of a.warnings)l.message(`${z.yellow("!")} ${z.dim(c.file)} \u2014 ${c.message}`);a.ok?l.success(`OKF bundle is valid \u2014 ${a.fileCount} file${a.fileCount===1?"":"s"}, ${a.warnings.length} warning${a.warnings.length===1?"":"s"}.`):(l.error(`OKF bundle has ${a.errors.length} error${a.errors.length===1?"":"s"} (see above).`),process.exitCode=1);return}let s=Nt(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
454
- `);return}l.message(O([{content:z.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?z.green(In+"/"):z.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?z.dim("Run `seoagent okf validate` to check it."):z.dim("Run `seoagent okf scaffold` to start one.")}],{title:z.cyan("OKF")}))}import{mkdirSync as Nu,writeFileSync as Fu}from"fs";import N from"picocolors";import{query as Du}from"@anthropic-ai/claude-agent-sdk";import{join as Zo}from"path";var Pn="citations",On="scorecard.md",Ou=6,Tu=1,ju=12,Ft="Claude (web-grounded)";function Tn(e){return Zo(e,k,Pn)}function ei(e){return Zo(Tn(e),On)}function ti(e){return typeof e!="number"||!Number.isFinite(e)?Ou:Math.max(Tu,Math.min(ju,Math.floor(e)))}function jn(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function ni(e,t){return`You are SEOAgent measuring this business's AI-citation visibility (AEO/GEO) \u2014 whether answer engines surface and cite it.
452
+ `,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var Nn=`${k}/${Le}`;function rt(e,t={}){let n=process.cwd(),r=M(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=ri(n,i);a.length===0?c.info(`OKF bundle already scaffolded at ${Nn}/.`):(c.success(`Scaffolded ${Nn}/ \u2014 created ${a.join(", ")}.`),c.info("Now fill the bundle from your .seoagent/ knowledge, then run `seoagent okf validate`."));return}if(o==="validate"){let a=ni(Mt(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
453
+ `);return}for(let l of a.errors)c.message(`${V.red("\u2717")} ${V.dim(l.file)} \u2014 ${l.message}`);for(let l of a.warnings)c.message(`${V.yellow("!")} ${V.dim(l.file)} \u2014 ${l.message}`);a.ok?c.success(`OKF bundle is valid \u2014 ${a.fileCount} file${a.fileCount===1?"":"s"}, ${a.warnings.length} warning${a.warnings.length===1?"":"s"}.`):(c.error(`OKF bundle has ${a.errors.length} error${a.errors.length===1?"":"s"} (see above).`),process.exitCode=1);return}let s=Bt(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
454
+ `);return}c.message(j([{content:V.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?V.green(Nn+"/"):V.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?V.dim("Run `seoagent okf validate` to check it."):V.dim("Run `seoagent okf scaffold` to start one.")}],{title:V.cyan("OKF")}))}import{mkdirSync as mi,writeFileSync as gi,readFileSync as Xu,readdirSync as Zu,existsSync as ed}from"fs";import{join as hi}from"path";import R from"picocolors";import{query as td}from"@anthropic-ai/claude-agent-sdk";import{join as Fn}from"path";var Dn="citations",Un="scorecard.md",Ku="history",Wu=6,qu=1,Hu=12,Yu=5,Gt="Claude (web-grounded)";function Kt(e){return Fn(e,k,Dn)}function ii(e){return Fn(Kt(e),Un)}function si(e){return Fn(Kt(e),Ku)}function ai(e){return`${e.replace(/[:.]/g,"-")}.json`}function ci(e){return typeof e!="number"||!Number.isFinite(e)?Wu:Math.max(qu,Math.min(Hu,Math.floor(e)))}function Wt(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>=Yu))break}return n}function ot(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function Mn(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 li(e,t){let{cited:n,total:r}=ot(e);return{generated_at:t.generatedAt,domain:e.domain,brand:e.brand,cited:n,total:r,competitors:e.competitors,results:e.results}}function ui(e,t){if(!t)return null;let{cited:n}=ot(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 di(e,t){let n=Wt(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(`
455
+ `),o=n.length?`
456
+ 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?`,
457
+ "competitorsSurfaced": [${JSON.stringify(n[0])}]`:`,
458
+ "competitorsSurfaced": []`;return`You are SEOAgent measuring this business's AI-citation visibility (AEO/GEO) \u2014 whether answer engines surface and cite it.
455
459
 
456
460
  Business under audit:
457
- ${[`- Domain: ${e.domain}`,e.name?`- Business name: ${e.name}`:null,e.type?`- Business type: ${e.type}`:null,e.description?`- What it does: ${e.description}`:null,`- OKF knowledge bundle present in repo: ${e.hasOkfBundle?"yes":"no"}`].filter(Boolean).join(`
458
- `)}
461
+ ${r}
459
462
 
460
- Your job has three steps:
463
+ Your job:
461
464
 
462
465
  1. Generate ${t} realistic questions a potential customer would ask an AI assistant (ChatGPT, Claude, Perplexity, Google AI Overviews) where THIS business should ideally be surfaced or cited. Make them DIVERSE and buyer-intent \u2014 mix:
463
466
  - category / "best tool for X" questions,
@@ -467,7 +470,9 @@ Your job has three steps:
467
470
 
468
471
  2. For EACH question, use the WebSearch tool (and WebFetch if you need to read a result) to see what a web-grounded answer engine would actually cite right now. Decide whether "${e.name||e.domain}" / ${e.domain} appears among the sources an answer engine would draw from, and its approximate rank. You MAY Read the local \`.seoagent/okf/\` bundle and \`.seoagent/context.md\` to understand the brand accurately, but the verdict must come from the live web results \u2014 not from what you already know.
469
472
 
470
- 3. Be honest. Mark \`surfaced: false\` when the business does not appear \u2014 a low score is useful signal, a fabricated "cited" is worse than useless. Never invent a source.
473
+ 3. For EACH question, capture the single most-likely-cited URL in \`source\`: YOUR page when you surface, otherwise the page currently winning that answer (so the user knows what to beat). Use a real URL from the live results, or null if genuinely unknown.${o}
474
+
475
+ Be honest. Mark \`surfaced: false\` when the business does not appear \u2014 a low score is useful signal, a fabricated "cited" is worse than useless. Never invent a source.
471
476
 
472
477
  End your reply with EXACTLY ONE fenced \`\`\`json block (and nothing after it) matching this schema:
473
478
 
@@ -475,20 +480,24 @@ End your reply with EXACTLY ONE fenced \`\`\`json block (and nothing after it) m
475
480
  {
476
481
  "brand": "${e.name||e.domain}",
477
482
  "domain": "${e.domain}",
483
+ "competitors": ${JSON.stringify(n)},
478
484
  "results": [
479
485
  {
480
486
  "query": "the question you tested",
481
487
  "surfaced": true,
482
488
  "rank": 2,
483
- "evidence": "one line: which source surfaced it, or why it didn't"
489
+ "source": "https://example.com/the-page-cited",
490
+ "evidence": "one line: which source surfaced it, or why it didn't"${i}
484
491
  }
485
492
  ]
486
493
  }
487
494
  \`\`\`
488
495
 
489
- \`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown.`}function ri(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=Lu(n[o]);if(i)return i}return null}function Lu(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=typeof n.domain=="string"?n.domain.trim():"";if(!r)return null;let o=typeof n.brand=="string"&&n.brand.trim()?n.brand.trim():r;if(!Array.isArray(n.results))return null;let i=[];for(let s of n.results){if(!s||typeof s!="object")continue;let a=s,c=typeof a.query=="string"?a.query.trim():"";if(!c)continue;let u=a.surfaced===!0,d=typeof a.rank=="number"&&Number.isFinite(a.rank)?Math.round(a.rank):null,p=typeof a.evidence=="string"?a.evidence.trim():"";i.push({query:c,surfaced:u,rank:u?d:null,evidence:p})}return i.length===0?null:{brand:o,domain:r,results:i}}function oi(e,t){let{cited:n,total:r}=jn(e),o=t.generatedAt.slice(0,10),i=e.results.map((u,d)=>{let p=u.surfaced?"\u2705":"\u2014",y=u.surfaced&&u.rank?`#${u.rank}`:"\u2014",m=Rn(u.evidence||(u.surfaced?"surfaced":"not found"));return`| ${d+1} | ${Rn(u.query)} | ${p} | ${y} | ${m} |`}).join(`
490
- `),s=e.results.filter(u=>!u.surfaced),a=s.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":s.map(u=>`- **${Rn(u.query)}** \u2014 ${u.evidence||"not surfaced"}`).join(`
491
- `),c=e.results.some(u=>!u.surfaced)?"- Enrich the Open Knowledge Format bundle so answer engines understand the business: run `seoagent okf scaffold` then fill it (the skill maps your `.seoagent/` knowledge into it), and publish it at `/.well-known/okf/`.\n- Cover the missed questions directly in your content (a page or FAQ that answers each one), then re-run `seoagent citations`.":"- Keep the OKF bundle current as the business evolves, and re-run to catch regressions.";return`---
496
+ \`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 pi(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=zu(n[o]);if(i)return i}return null}function zu(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=Wt(Array.isArray(n.competitors)?n.competitors.map(l=>String(l)):[]),s=new Set(i.map(l=>l.toLowerCase()));if(!Array.isArray(n.results))return null;let a=[];for(let l of n.results){if(!l||typeof l!="object")continue;let u=l,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)?Ju(u.competitorsSurfaced.map(O=>typeof O=="string"?O.trim():"").filter(O=>O&&s.has(O.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 Ju(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 fi(e,t){let{cited:n,total:r}=ot(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")),O=d.source?Q(oi(d.source)):"\u2014";return i?`| ${g+1} | ${Q(d.query)} | ${m} | ${v} | ${O} | ${$} |`:`| ${g+1} | ${Q(d.query)} | ${m} | ${v} | ${$} |`}).join(`
497
+ `),a=i?`| # | Query | Cited? | ~Rank | Source cited | Evidence |
498
+ |---|-------|--------|-------|--------------|----------|`:`| # | Query | Cited? | ~Rank | Evidence |
499
+ |---|-------|--------|-------|----------|`,l=e.results.filter(d=>!d.surfaced),u=l.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":l.map(d=>{let g=d.source?` _(currently cited: ${Q(oi(d.source))})_`:"";return`- **${Q(d.query)}** \u2014 ${d.evidence||"not surfaced"}${g}`}).join(`
500
+ `),p=l.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`---
492
501
  type: Report
493
502
  title: AI Citation Scorecard \u2014 ${e.domain}
494
503
  generated_at: ${t.generatedAt}
@@ -502,19 +511,18 @@ engine: claude-web-grounded
502
511
  > measurement half of the AEO/GEO loop \u2014 \`seoagent okf\` makes you citable, this
503
512
  > tells you whether it's working.
504
513
 
505
- **Cited: ${n} / ${r} queries** \xB7 engine: ${Ft} \xB7 ${o}
506
-
507
- | # | Query | Cited? | ~Rank | Evidence |
508
- |---|-------|--------|-------|----------|
509
- ${i}
510
-
514
+ **Cited: ${n} / ${r} queries** \xB7 engine: ${Gt} \xB7 ${o}
515
+ ${Vu(t.trend,n,r)}
516
+ ${a}
517
+ ${s}
518
+ ${Qu(e)}
511
519
  ## Where you're not surfacing (opportunities)
512
520
 
513
- ${a}
521
+ ${u}
514
522
 
515
523
  ### How to improve these
516
524
 
517
- ${c}
525
+ ${p}
518
526
 
519
527
  ## Methodology \u2014 read before quoting the number
520
528
 
@@ -523,22 +531,40 @@ approximates how a web-grounded answer engine (ChatGPT search, Perplexity,
523
531
  Google AI Overviews) synthesizes an answer from current web results.
524
532
 
525
533
  What this **is**: a real, repeatable signal of whether the open web currently
526
- positions ${e.brand} as an answer for these questions.
534
+ positions ${e.brand} as an answer for these questions. Run it on a cadence \u2014
535
+ each run is saved to \`.seoagent/citations/history/\` and the **Trend** line
536
+ above compares against your last run.
527
537
 
528
538
  This is **not a per-engine guarantee**: ChatGPT, Perplexity, and Gemini each
529
539
  rank and cite differently, and tracking them individually is a planned
530
- follow-up. Treat the score as directional \u2014 re-run over time to watch the
531
- trend rather than fixating on a single number.
532
- `}function Rn(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function tt(e={}){let t=process.cwd(),n=D(t);if(!n)return;let r=Qe();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){l.warn(X[r].summary),X[r].next&&l.message(` ${X[r].next}`),process.exitCode=1;return}l.info(N.dim(X[r].summary));let o=$r(t),i=Nt(t),s={domain:n.domain,name:o?.business.name,type:o?.business.type||n.site_type,description:o?.business.description,hasOkfBundle:i.exists&&i.fileCount>0},a=ti(e.queries);l.message(`${N.cyan("\u25C7")} Auditing AI citations for ${N.bold(s.domain)} \u2014 ${a} web-grounded quer${a===1?"y":"ies"} via ${Ft}.`),l.message(N.dim(` This runs live web searches and can take a minute\u2026
533
- `));let c=ni(s,a),u=await Uu({cwd:t,prompt:c,model:e.model});if(u===null){process.exitCode=1;return}let d=ri(u);if(!d){l.error(`Couldn't read a citation report from the agent's reply. Re-run \`${f("citations")}\`, optionally with fewer queries (\`--queries 4\`).`),process.exitCode=1;return}let p=new Date().toISOString(),y=oi(d,{generatedAt:p});Nu(Tn(t),{recursive:!0}),Fu(ei(t),y,"utf-8");let{cited:m,total:v}=jn(d),I=m===0?N.red:m<v?N.yellow:N.green;l.message(O([{content:N.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${N.cyan(d.domain)}`},{content:`Cited: ${I(`${m} / ${v}`)} ${N.dim("queries")}`},{content:`Engine: ${N.dim(Ft)}`},{sep:!0},{content:N.dim(`Saved \u2192 .seoagent/${Pn}/${On}`)},{content:m<v?N.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):N.dim("Surfacing across the board. Re-run periodically to catch drift.")}],{title:N.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(d,null,2)+`
534
- `)}async function Uu(e){let{cwd:t,prompt:n,model:r}=e;try{let o=Du({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)Mu(c)}else if(s.type==="result"){if(process.stdout.write(`
535
- `),!(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(`
536
- `),l.error(` Agent error: ${o.message}`),null}}function Mu(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(Ot(n));return}if(t==="tool_use"){let n=String(e.name??"tool"),r=e.input,o=n==="WebSearch"?String(r?.query??""):n==="WebFetch"?String(r?.url??""):"";process.stdout.write(N.dim(` ${N.magenta("\u{1F50E}")} ${n}${o?` ${Bu(o,70)}`:""}
537
- `))}}function Bu(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}import Te from"picocolors";function nt(e={}){if(e.all){Gu();return}let t=process.cwd();if(!D(t))return;ue(t);let n=gn(t);si(t);let r=ii(t);n.reason==="refreshed"?(l.success(n.from&&n.from!==n.to?`Refreshed the SEOAgent skill ${n.from} \u2192 ${n.to}.`:`Refreshed the SEOAgent skill (now ${n.to}).`),l.info("Your `.seoagent/` knowledge was left untouched.")):(l.error(`Could not refresh the skill (${n.reason}).`),process.exitCode=1),r.added>0?l.success(`Re-scanned the codebase: +${r.added} new page${r.added===1?"":"s"} merged into .seoagent/pages.md (${r.total} total).`):r.total>0&&l.info(`Page inventory already current (${r.total} pages).`)}function ii(e){try{let t=S(e),n=t?.domain&&t.domain!=="unknown"?t.domain:null,{pages:r}=Se(e,n),o=St(e,r);return{added:o.added,total:o.total}}catch{return{added:0,total:0}}}function Gu(){let e=gr();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 ${Te.bold(C)}\u2026`);let t=0,n=0;for(let r of e){let o=gn(r);si(r);let i=ii(r),s=i.added>0?Te.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?Te.dim(` (${o.from} \u2192 ${o.to})`):"";l.message(` ${Te.green("\u2713")} ${r}${a}${s}`)}else n++,l.message(` ${Te.yellow("!")} ${r} ${Te.dim("\u2014 "+o.reason)}${s}`)}l.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${C}.`),n>0&&l.info(`${n} could not be refreshed (see above).`)}function si(e){try{ce(e)}catch{}}import{spinner as Nn,confirm as Ku,isCancel as Wu}from"@clack/prompts";import h from"picocolors";var li={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function qu(e){let t=process.cwd(),n=Qn(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=S(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||E.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?Nn():null;a?.start(`Looking up ${h.bold(`"${e.keyword}"`)} ${h.dim("via DataForSEO (free peek)\u2026")}`);let c;try{c=await Y(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...o?{domain:o}:{}})})}catch(d){w(a,"error",`Network error: ${d.message}`,h.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await c.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:c.status,body:u??null})+`
538
- `);return}if(c.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";w(a,"warn",`Daily peek quota reached for ${d}.`,h.yellow(`Daily peek quota reached for ${d}.`)),l.message(ai()),process.exitCode=1;return}if(!c.ok||!u){w(a,"error",`Peek failed (${c.status})${u?.error?`: ${u.error}`:""}`,h.red(`Peek failed (${c.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){w(a,"warn","Real keyword data is temporarily unavailable. Try again later.",h.yellow("Real keyword data is temporarily unavailable. Try again later.")),l.message(h.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){w(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){w(a,"warn",`No data returned for "${e.keyword}".`,h.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(h.green("Got it.")),l.message(Hu(u.opportunity)),u.remaining&&l.message(`${h.dim("Peeks remaining today:")} ${h.bold(String(u.remaining.install))} ${h.dim("\u2014 "+ai())}`)}function Hu(e){let n=u=>h.dim(u.padEnd(14)),r=e.volume!=null?h.bold(String(e.volume)):h.dim("n/a"),o=e.difficulty!=null?`${h.bold(String(e.difficulty))} ${h.dim(Yu(e.difficulty))}`:h.dim("n/a"),i=li[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?h.bold(h.green(i)):e.opportunity==="striking_distance"?h.bold(h.cyan(i)):e.opportunity==="competitor_gap"?h.bold(h.yellow(i)):h.dim(i),a=[{content:`${h.green("\u25CF")} ${h.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${h.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],c=`${h.bold(h.cyan("Keyword peek"))}`;return O(a,{width:55,title:c})}function Yu(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function ai(e=P()){return e?`You're logged in \u2014 run \`${f("keywords")}\` for full enrichment (no quota), or \`${f("keywords --discover")}\` / \`${f("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${f("login")}`}function Ln(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 [${li[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function zu(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 Ju(e){let t=e.all?"all":"suggested";if(t==="all"&&process.stdin.isTTY){let a=await Ku({message:"Delete ALL keywords for this site from the cloud? This cannot be undone."});if(Wu(a)||!a){l.info("No changes.");return}}let n=e.apiBase||e.auth.api_base||E.BASE,r=process.stdout.isTTY?Nn():null;r?.start(t==="all"?"Purging all keywords\u2026":"Purging suggested keywords\u2026");let o;try{o=await Y(`${n}/api/cli/keywords/purge`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.auth.user_token}:${e.auth.website_token}`},body:JSON.stringify({scope:t})})}catch(a){w(r,"error",`Network error: ${a.message}`,h.red("Network error.")),process.exitCode=1;return}let i=null;try{i=await o.json()}catch{i=null}if(i?.skipped==="no-table"||i?.skipped==="no-columns"){w(r,"warn","Keyword storage isn\u2019t enabled on the server yet.",h.yellow("Nothing to purge yet."));return}if(!o.ok||i?.status!=="ok"){w(r,"error",`Purge failed (${o.status})${i?.error?`: ${i.error}`:""}`,h.red(`Purge failed (${o.status}).`)),process.exitCode=1;return}let s=i.purged??0;w(r,"success",`Purged ${s} ${t==="all"?"":"suggested "}keyword${s===1?"":"s"}.`,h.green(`Purged ${s} keyword${s===1?"":"s"}.`)),l.message(h.dim(t==="all"?"Cleared the cloud inventory. Re-run `seoagent keywords --seed` / strategy to rebuild it.":"Cleared discovery noise. Your clustered keywords were kept."))}async function se(e={}){if(e.peek&&e.peek.trim().length>0){await qu({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=P();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(e.purge){await Ju({all:e.all,apiBase:e.apiBase,auth:t});return}let n=e.apiBase||t.api_base||E.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?Nn():null;c?.start(s);let u=o==="competitors"||o==="discover"||o==="seed",d;try{d=await Y(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"},u?{timeoutMs:6e4,attempts:1}:{})}catch(m){w(c,"error",`Network error: ${m.message}`,h.red("Network error.")),process.exitCode=1;return}let p=null;try{p=await d.json()}catch{p=null}if(d.status===402||p?.code==="upgrade_required"){w(c,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",h.yellow("Paid feature \u2014 upgrade to continue.")),l.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${h.cyan(E.PRICING)}`:`Upgrade to find new keywords to target: ${h.cyan(E.PRICING)}`),process.exitCode=1;return}if(!d.ok||p?.status!=="ok"){w(c,"error",`Server rejected request (${d.status})${p?.error?`: ${p.error}`:""}`,h.red(`Server rejected request (${d.status}).`)),process.exitCode=1;return}if(p.skipped==="no-gsc-data"){w(c,"warn","No Search Console data to seed from yet. Connect Google Search Console (run `seoagent login` and link GSC) \u2014 or wait for impressions to accrue on a new site.",h.yellow("No Search Console data yet."));return}if(p.skipped==="no-keywords"||p.skipped==="no-seeds"){w(c,"warn","No keywords yet. Seed from Search Console with `seoagent keywords --seed`, or run the keyword strategy (Phase 2) first, then try again.",h.yellow("No keywords yet."));return}if(p.skipped==="no-competitors"){w(c,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",h.yellow("No competitors yet."));return}if(p.skipped==="no-creds"||p.skipped==="no-columns"||p.skipped==="no-table"){w(c,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(p.skipped){w(c,"warn",`Skipped: ${p.skipped}`,h.yellow(`Skipped: ${p.skipped}`));return}if(o==="competitors"){let m=p.gaps??0;w(c,"success",`Found ${m} competitor gap${m===1?"":"s"} across ${p.competitors?.length??0} competitor${p.competitors?.length===1?"":"s"} (added as "suggested").`,h.green(`${m} competitor gap${m===1?"":"s"} found.`)),zu(p.topGaps??[]),l.message(`Review them in ${h.cyan(".seoagent/keywords.md")} (a read-only projection \u2014 don't hand-edit it). Keep the on-topic ones for your clusters; clear off-topic noise with \`${f("keywords --purge")}\`.`);return}if(o==="discover"){let m=p.discovered??0;w(c,"success",`Discovered ${m} new keyword${m===1?"":"s"} to target (added as "suggested").`,h.green(`${m} new keyword${m===1?"":"s"} discovered.`)),Ln(p.opportunities??[]),l.message(`Review them in ${h.cyan(".seoagent/keywords.md")} (a read-only projection \u2014 don't hand-edit it). Relevance-check before adopting; clear off-topic noise with \`${f("keywords --purge")}\`.`);return}if(o==="seed"){let m=p.seeded??0;w(c,"success",`Seeded ${m} keyword${m===1?"":"s"} from Search Console (real impressed queries, added as "suggested").`,h.green(`${m} keyword${m===1?"":"s"} seeded from Search Console.`)),Ln(p.opportunities??[]),l.message(`These are queries your site already gets impressions for \u2014 striking-distance wins first. Review in ${h.cyan(".seoagent/keywords.md")} and build clusters from them.`);return}let y=p.enriched??0;w(c,"success",`Enriched ${y} keyword${y===1?"":"s"}.`,h.green(`Enriched ${y} keyword${y===1?"":"s"}.`)),Ln(p.opportunities??[]),p.paid||l.message(`${h.dim("Free plan:")} enriched up to ${h.bold(String(p.cap??25))} keywords. ${h.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${h.cyan(E.PRICING)}`)}import A from"picocolors";function rt(e={}){let t=process.cwd(),n=S(t),r=ee(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
539
- `);return}if(l.message(Vu(r)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}W(t,{image_provider:r.provider}),l.info(`Saved to ${A.cyan(".seoagent/project.md")} ${A.dim(`(image_provider: ${r.provider})`)}`)}function Vu(e){let n=i=>A.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${A.dim("\u25CB")} ${A.bold(A.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:A.dim("Set ONE of these to enable image generation:")});let i=Ir();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${A.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:A.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${A.cyan(f("env-check"))}`})}else{r.push({content:`${A.green("\u2713")} ${A.dim("Image provider:")} ${A.bold(A.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${A.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${A.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${A.dim(i.join(", "))}`})}let o=`${A.bold(A.cyan("SEOAgent"))} ${A.dim("\xB7")} ${A.dim("env-check")}`;return O(r,{width:64,title:o})}import{existsSync as Dn,mkdirSync as di,writeFileSync as pi}from"fs";import{dirname as Ut,isAbsolute as td,join as Dt,resolve as nd}from"path";import{tmpdir as rd}from"os";import{spinner as od}from"@clack/prompts";import T from"picocolors";import{Buffer as ci}from"buffer";async function Fn(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 ci.from(n)}async function Qu(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:ci.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await Fn(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function Xu(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 Fn(o.url),contentType:o.content_type??"image/png"}}async function Zu(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 ed(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 Zu(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 Fn(o),contentType:"image/png",providerImageId:r.id}}async function ui(e,t){switch(e){case"openai":return Qu(t);case"fal":return Xu(t);case"replicate":return ed(t);default:throw new Error(`Unknown image provider: ${e}`)}}function id(e){return e==="openai"||e==="fal"||e==="replicate"}async function ot(e={}){let t=process.cwd();if(!e.prompt){l.warn(`Missing --prompt. Example: ${f('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){l.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=S(t),r=null;if(e.provider){if(!id(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=ee(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=Ar(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=td(e.out)?e.out:nd(t,e.out),a=!e.silent&&!!process.stdout.isTTY?od():null;a?.start(`Generating image with ${T.bold(r)} ${T.dim(`(${o.envName})`)}\u2026`);try{let c=await ui(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Dn(Ut(i))||di(Ut(i),{recursive:!0}),pi(i,c.bytes),e.silent||w(a,"success",`Wrote ${i} (${c.bytes.length} bytes, ${c.contentType}).`,T.green(`Wrote ${i} ${T.dim(`(${c.bytes.length} bytes, ${c.contentType})`)}`))}catch(c){a?.stop(T.red("Image generation failed."));let u=ad(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(sd({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:c.message})),u&&l.message(`${T.dim("Full error log:")} ${T.cyan(u)}`),process.exitCode=1}}function sd(e){let n=d=>T.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${T.red("\u2717")} ${T.bold(T.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${T.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${T.dim(`"${o}"`)}`}];e.size&&i.push({content:`${n("Size:")}${e.size}`}),i.push({sep:!0});let s=e.message.replace(/\s+/g," ").trim(),a=64,c=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:T.red(c)});let u=`${T.bold(T.cyan("SEOAgent"))} ${T.dim("\xB7")} ${T.dim("generate-image")}`;return O(i,{width:70,title:u})}function ad(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=Dt(e,k),i=Dt(o,".errors"),s=Dn(o)?Dt(i,r):Dt(rd(),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 Dn(Ut(s))||di(Ut(s),{recursive:!0}),pi(s,a.join(`
540
- `)),s}catch{return null}}import U from"picocolors";async function it(e={}){let t=P();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
541
- `):l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||E.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})}
542
- `);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}`})}
543
- `):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)}
544
- `);return}l.message(ld(i)),i.paid===!1&&l.message(`${U.dim("Upgrade for autopilot:")} ${U.cyan(E.PRICING)}`)}function ld(e){let n=i=>U.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${U.green("\u2713")} ${U.dim("Logged in as")} ${U.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${U.cyan(e.domain)}`}),e.plan){let i=e.paid?U.bold(U.green(e.plan)):U.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${U.dim(e.api_base)}`});let o=`${U.bold(U.cyan("SEOAgent"))} ${U.dim("\xB7")} ${U.dim("whoami")}`;return O(r,{width:55,title:o})}import{select as at,text as st,confirm as gi,isCancel as K,intro as cd,outro as ud}from"@clack/prompts";import Mt from"picocolors";function dd(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>qe()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await G()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await Ge()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await Je()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await it()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await at({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(!K(e))if(e==="peek"){let t=await st({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(K(t))return;await se({peek:String(t)})}else e==="discover"?await se({discover:!0}):e==="competitors"?await se({competitors:!0}):await se()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>Ze({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await at({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"}]});K(e)||et(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 tt()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await st({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(K(e))return;let t=await st({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});K(t)||await ot({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>rt({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await at({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"}]});K(e)||await Xe(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await ge()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await st({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(K(e))return;let t=await gi({message:"Mark as failed instead of completed?",initialValue:!1});if(K(t))return;let n;if(t===!0){let r=await st({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(K(r))return;String(r).trim()&&(n=String(r))}await oe(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 Ye()},{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 at({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"}]});K(e)||nt({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>Ve()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await Ke({})}]}var fi="__exit__";async function mi(e=dd()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:fi,label:"Exit",hint:"Close the menu"});let n=await at({message:"What would you like to do?",options:t});if(K(n)||n===fi)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 Un(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}cd(`${Mt.bold(Mt.cyan("SEOAgent"))} ${Mt.dim("\xB7 menu")}`);let e=await mi();for(;!e;){let t=await gi({message:"Do another?",initialValue:!0});if(K(t)||t===!1){e=!0;break}e=await mi()}ud(Mt.dim("See you next time."))}var x=new pd;x.name("seoagent").description("AI SEO agent for Claude Code").version(C).showSuggestionAfterError(!0).showHelpAfterError(!0);x.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").action(e=>{Ge({yes:e.yes,domain:e.domain,siteType:e.siteType})});x.command("uninstall").description("Remove SEOAgent from this project \u2014 deletes .seoagent/, the skill bundle, and the sync hook").option("-y, --yes","Skip the confirmation prompt (also implied in a non-TTY shell)").option("--global","Also wipe ~/.config/seoagent (login + sync state, all projects)").action(e=>{Ke({yes:e.yes,global:e.global})});x.command("status").description("Show current SEO project state").action(qe);x.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=>{En({json:e.json})});x.command("login").description("Connect this CLI to your seoagent.com account (browser flow)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{Je({apiBase:e.apiBase})});x.command("logout").description("Remove stored credentials for seoagent.com").action(Ve);x.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force","Re-send every artifact on push; take cloud on every pull conflict").option("--path <relpath>","Push only files matching this path suffix").option("--push-only","Skip the cloud \u2192 local pull pass").option("--pull-only","Skip the local \u2192 cloud push pass (same as `seoagent pull`)").action(e=>{G({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});x.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force","Take the cloud version on every conflict (discards local edits)").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{ge({force:e.force,silent:e.silent,print:e.print})});x.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{oe(e,{failed:t.failed,reason:t.reason})});x.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{yn({json:e.json})});x.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{$n({yes:e.yes,model:e.model})});x.command("autopilot <action>").description("Turn CLI autopilot on|off or show status (paid; queues fixes for your agent)").option("--api-base <url>","Override API base URL (for testing)").action((e,t)=>{Xe(e,{apiBase:t.apiBase})});x.command("keywords").description("Enrich keywords with real volume + difficulty + opportunity labels (requires login)").option("--peek <keyword>","Free one-keyword DataForSEO lookup (no login required; daily quota)").option("--seed","Add the queries your site already ranks for (Google Search Console) to the inventory \u2014 additive, keeps existing keywords (requires login + GSC)").option("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--purge","Delete suggested keywords (discover/competitors noise) from the cloud inventory").option("--all","With --purge: clear EVERY keyword for this site, not just suggested").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{se({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});x.command("internal-links").description("Analyze the repo for orphan pages (no inbound internal links) \u2192 .seoagent/internal-links.md").option("--json","Print the analysis as JSON instead of writing the report").action(e=>{Ze({json:e.json})});x.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)=>{_n(e,{slug:t.slug,url:t.url,file:t.file,title:t.title,type:t.type,status:t.status,primaryKeyword:t.primaryKeyword})});x.command("okf [action]").description("Manage the Open Knowledge Format bundle for AI agents \u2014 [validate|scaffold] \u2192 .seoagent/okf/").option("--json","Output result as JSON").action((e,t)=>{et(e,{json:t.json})});x.command("citations").description("Measure whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{tt({queries:e.queries,model:e.model,json:e.json})});x.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{rt({json:e.json})});x.command("generate-image").description("Generate an image via the detected (or explicit) provider").requiredOption("--prompt <text>","Image prompt").requiredOption("--out <path>","Output file path (relative to cwd or absolute)").option("--provider <name>","Force provider: openai | fal | replicate").option("--size <wxh>","Pixel size hint, e.g. 1024x1024").option("--silent","Suppress progress output").action(e=>{ot({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});x.command("whoami").description("Show the logged-in account: email, bound website, plan, and API base").option("--json","Output as JSON (handy for scripting / `jq`)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{it({json:e.json,apiBase:e.apiBase})});x.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(Ye);x.command("update-cli").description("Update the SEOAgent CLI to the latest npm version, then refresh every project on this machine").option("--dry-run","Show what would happen without running the install").option("--no-projects","Skip refreshing your other projects after the update").action(e=>{ze({dryRun:e.dryRun,projects:e.projects})});x.command("refresh").description("Refresh the installed skill + re-scan the codebase for new pages. `--all` sweeps every project on this machine.").option("--all","Refresh every registered project, not just this one").action(e=>{nt({all:e.all})});x.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Un()});process.argv.length===2&&(x.outputHelp(),process.exit(0));x.parse();
540
+ follow-up. Treat the score as directional \u2014 watch the trend rather than fixating
541
+ on a single number.
542
+ `}function Vu(e,t,n){if(!e)return`
543
+ _First run \u2014 re-run on a cadence to start tracking the trend._
544
+ `;let r=e.scoreDelta>0?`\u25B2 up ${e.scoreDelta}`:e.scoreDelta<0?`\u25BC down ${Math.abs(e.scoreDelta)}`:"\u25AA no change",o=`
545
+ **Trend:** ${t}/${n} this run \u2014 ${r} from ${e.prevCited}/${e.prevTotal} on ${e.prevDate}.`;return e.newlyCited.length&&(o+=`
546
+ - \u2705 Newly cited: ${e.newlyCited.map(i=>`_${Q(i)}_`).join("; ")}`),e.newlyDropped.length&&(o+=`
547
+ - \u26A0\uFE0F Dropped: ${e.newlyDropped.map(i=>`_${Q(i)}_`).join("; ")}`),o+`
548
+ `}function Qu(e){if(!e.competitors.length)return"";let t=Mn(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
+ `);return`
550
+ ## Share of voice
551
+
552
+ How often each brand surfaces across the same ${e.results.length} queries.
553
+
554
+ | Brand | Surfaced | Rate |
555
+ |-------|----------|------|
556
+ ${t}
557
+ `}function oi(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 it(e={}){let t=process.cwd(),n=M(t);if(!n)return;let r=et();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){c.warn(te[r].summary),te[r].next&&c.message(` ${te[r].next}`),process.exitCode=1;return}c.info(R.dim(te[r].summary));let o=Cr(t),i=Bt(t),s=Wt(e.competitors&&e.competitors.length?e.competitors:id(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},l=ci(e.queries);c.message(`${R.cyan("\u25C7")} Auditing AI citations for ${R.bold(a.domain)} \u2014 ${l} web-grounded quer${l===1?"y":"ies"} via ${Gt}.`),c.message(R.dim(` This runs live web searches and can take a minute\u2026
558
+ `));let u=di(a,l),p=await nd({cwd:t,prompt:u,model:e.model});if(p===null){process.exitCode=1;return}let d=pi(p);if(!d){c.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=si(t),v=sd(m),$=ui(d,v),O=fi(d,{generatedAt:g,trend:$});mi(Kt(t),{recursive:!0}),gi(ii(t),O,"utf-8"),mi(m,{recursive:!0}),gi(hi(m,ai(g)),JSON.stringify(li(d,{generatedAt:g}),null,2)+`
559
+ `,"utf-8");let{cited:x,total:N}=ot(d),X=x===0?R.red:x<N?R.yellow:R.green,G=[{content:R.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${R.cyan(d.domain)}`},{content:`Cited: ${X(`${x} / ${N}`)} ${R.dim("queries")}`}];if($){let ne=$.scoreDelta>0?R.green(`\u25B2 +${$.scoreDelta}`):$.scoreDelta<0?R.red(`\u25BC ${$.scoreDelta}`):R.dim("\u25AA 0");G.push({content:`Trend: ${ne} ${R.dim(`vs ${$.prevCited}/${$.prevTotal} on ${$.prevDate}`)}`})}else G.push({content:R.dim("Trend: first run \u2014 re-run to start tracking")});if(G.push({content:`Engine: ${R.dim(Gt)}`}),d.competitors.length){G.push({sep:!0}),G.push({content:R.dim("Share of voice:")});for(let ne of Mn(d)){let pt=ne.isYou?R.bold(`${ne.brand} (you)`):ne.brand;G.push({content:` ${pt}: ${ne.surfaced}/${ne.total}`})}}G.push({sep:!0}),G.push({content:R.dim(`Saved \u2192 .seoagent/${Dn}/${Un}`)}),G.push({content:x<N?R.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):R.dim("Surfacing across the board. Re-run periodically to catch drift.")}),c.message(j(G,{title:R.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(d,null,2)+`
560
+ `)}async function nd(e){let{cwd:t,prompt:n,model:r}=e;try{let o=td({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 l of a)rd(l)}else if(s.type==="result"){if(process.stdout.write(`
561
+ `),!(s.subtype==="success"&&!s.is_error))return c.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(`
562
+ `),c.error(` Agent error: ${o.message}`),null}}function rd(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(Ft(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?` ${od(o,70)}`:""}
563
+ `))}}function od(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function id(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function sd(e){try{if(!ed(e))return null;let t=Zu(e).filter(o=>o.endsWith(".json")).sort();if(t.length===0)return null;let n=t[t.length-1],r=JSON.parse(Xu(hi(e,n),"utf-8"));return r&&typeof r=="object"&&Array.isArray(r.results)&&typeof r.generated_at=="string"?r:null}catch{return null}}import Ne from"picocolors";function st(e={}){if(e.all){ad();return}let t=process.cwd();if(!M(t))return;fe(t);let n=Sn(t);wi(t);let r=yi(t);n.reason==="refreshed"?(c.success(n.from&&n.from!==n.to?`Refreshed the SEOAgent skill ${n.from} \u2192 ${n.to}.`:`Refreshed the SEOAgent skill (now ${n.to}).`),c.info("Your `.seoagent/` knowledge was left untouched.")):(c.error(`Could not refresh the skill (${n.reason}).`),process.exitCode=1),r.added>0?c.success(`Re-scanned the codebase: +${r.added} new page${r.added===1?"":"s"} merged into .seoagent/pages.md (${r.total} total).`):r.total>0&&c.info(`Page inventory already current (${r.total} pages).`)}function yi(e){try{let t=_(e),n=t?.domain&&t.domain!=="unknown"?t.domain:null,{pages:r}=_e(e,n),o=Et(e,r);return{added:o.added,total:o.total}}catch{return{added:0,total:0}}}function ad(){let e=br();if(e.length===0){c.info("No SEOAgent projects are registered on this machine yet. They register themselves on `init` / `sync`.");return}c.message(`Refreshing ${e.length} project${e.length===1?"":"s"} to SEOAgent ${Ne.bold(E)}\u2026`);let t=0,n=0;for(let r of e){let o=Sn(r);wi(r);let i=yi(r),s=i.added>0?Ne.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?Ne.dim(` (${o.from} \u2192 ${o.to})`):"";c.message(` ${Ne.green("\u2713")} ${r}${a}${s}`)}else n++,c.message(` ${Ne.yellow("!")} ${r} ${Ne.dim("\u2014 "+o.reason)}${s}`)}c.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${E}.`),n>0&&c.info(`${n} could not be refreshed (see above).`)}function wi(e){try{pe(e)}catch{}}import{spinner as Gn,confirm as cd,isCancel as ld}from"@clack/prompts";import y from"picocolors";var bi={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function ud(e){let t=process.cwd(),n=nr(t);if(!n){c.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?Gn():null;a?.start(`Looking up ${y.bold(`"${e.keyword}"`)} ${y.dim("via DataForSEO (free peek)\u2026")}`);let l;try{l=await J(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...o?{domain:o}:{}})})}catch(p){w(a,"error",`Network error: ${p.message}`,y.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await l.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:l.status,body:u??null})+`
564
+ `);return}if(l.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}.`)),c.message(ki()),process.exitCode=1;return}if(!l.ok||!u){w(a,"error",`Peek failed (${l.status})${u?.error?`: ${u.error}`:""}`,y.red(`Peek failed (${l.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.")),c.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.")),c.message(dd(u.opportunity)),u.remaining&&c.message(`${y.dim("Peeks remaining today:")} ${y.bold(String(u.remaining.install))} ${y.dim("\u2014 "+ki())}`)}function dd(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(pd(e.difficulty))}`:y.dim("n/a"),i=bi[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}`}],l=`${y.bold(y.cyan("Keyword peek"))}`;return j(a,{width:55,title:l})}function pd(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function ki(e=T()){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 Bn(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){c.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";c.message(` \u2022 [${bi[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function fd(e){if(e.length!==0){c.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";c.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${o}, ${n}, ${r}`)}}}async function md(e){let t=e.all?"all":"suggested";if(t==="all"&&process.stdin.isTTY){let a=await cd({message:"Delete ALL keywords for this site from the cloud? This cannot be undone."});if(ld(a)||!a){c.info("No changes.");return}}let n=e.apiBase||e.auth.api_base||A.BASE,r=process.stdout.isTTY?Gn():null;r?.start(t==="all"?"Purging all keywords\u2026":"Purging suggested keywords\u2026");let o;try{o=await J(`${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"}.`)),c.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 ue(e={}){if(e.peek&&e.peek.trim().length>0){await ud({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=T();if(!t){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(e.purge){await md({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",l=!!process.stdout.isTTY?Gn():null;l?.start(s);let u=o==="competitors"||o==="discover"||o==="seed",p;try{p=await J(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"},u?{timeoutMs:6e4,attempts:1}:{})}catch(m){w(l,"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(l,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",y.yellow("Paid feature \u2014 upgrade to continue.")),c.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(l,"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(l,"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(l,"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(l,"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(l,"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(l,"warn",`Skipped: ${d.skipped}`,y.yellow(`Skipped: ${d.skipped}`));return}if(o==="competitors"){let m=d.gaps??0;w(l,"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.`)),fd(d.topGaps??[]),c.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(l,"success",`Discovered ${m} new keyword${m===1?"":"s"} to target (added as "suggested").`,y.green(`${m} new keyword${m===1?"":"s"} discovered.`)),Bn(d.opportunities??[]),c.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(l,"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.`)),Bn(d.opportunities??[]),c.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(l,"success",`Enriched ${g} keyword${g===1?"":"s"}.`,y.green(`Enriched ${g} keyword${g===1?"":"s"}.`)),Bn(d.opportunities??[]),d.paid||c.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 I from"picocolors";function at(e={}){let t=process.cwd(),n=_(t),r=oe(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
565
+ `);return}if(c.message(gd(r)),!n){c.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}H(t,{image_provider:r.provider}),c.info(`Saved to ${I.cyan(".seoagent/project.md")} ${I.dim(`(image_provider: ${r.provider})`)}`)}function gd(e){let n=i=>I.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${I.dim("\u25CB")} ${I.bold(I.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:I.dim("Set ONE of these to enable image generation:")});let i=jr();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${I.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:I.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${I.cyan(f("env-check"))}`})}else{r.push({content:`${I.green("\u2713")} ${I.dim("Image provider:")} ${I.bold(I.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${I.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${I.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${I.dim(i.join(", "))}`})}let o=`${I.bold(I.cyan("SEOAgent"))} ${I.dim("\xB7")} ${I.dim("env-check")}`;return j(r,{width:64,title:o})}import{existsSync as Wn,mkdirSync as vi,writeFileSync as xi}from"fs";import{dirname as Ht,isAbsolute as bd,join as qt,resolve as $d}from"path";import{tmpdir as Sd}from"os";import{spinner as vd}from"@clack/prompts";import L from"picocolors";import{Buffer as $i}from"buffer";async function Kn(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 $i.from(n)}async function hd(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:$i.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await Kn(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function yd(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 Kn(o.url),contentType:o.content_type??"image/png"}}async function wd(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 kd(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 wd(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 Kn(o),contentType:"image/png",providerImageId:r.id}}async function Si(e,t){switch(e){case"openai":return hd(t);case"fal":return yd(t);case"replicate":return kd(t);default:throw new Error(`Unknown image provider: ${e}`)}}function xd(e){return e==="openai"||e==="fal"||e==="replicate"}async function ct(e={}){let t=process.cwd();if(!e.prompt){c.warn(`Missing --prompt. Example: ${f('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){c.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=_(t),r=null;if(e.provider){if(!xd(e.provider)){c.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=oe(t).provider;if(!r||r==="none"){c.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=Tr(t,r);if(!o){c.warn(`Provider "${r}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=bd(e.out)?e.out:$d(t,e.out),a=!e.silent&&!!process.stdout.isTTY?vd():null;a?.start(`Generating image with ${L.bold(r)} ${L.dim(`(${o.envName})`)}\u2026`);try{let l=await Si(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Wn(Ht(i))||vi(Ht(i),{recursive:!0}),xi(i,l.bytes),e.silent||w(a,"success",`Wrote ${i} (${l.bytes.length} bytes, ${l.contentType}).`,L.green(`Wrote ${i} ${L.dim(`(${l.bytes.length} bytes, ${l.contentType})`)}`))}catch(l){a?.stop(L.red("Image generation failed."));let u=Cd(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:l});c.message(_d({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:l.message})),u&&c.message(`${L.dim("Full error log:")} ${L.cyan(u)}`),process.exitCode=1}}function _d(e){let n=p=>L.dim(p.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${L.red("\u2717")} ${L.bold(L.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${L.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${L.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,l=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:L.red(l)});let u=`${L.bold(L.cyan("SEOAgent"))} ${L.dim("\xB7")} ${L.dim("generate-image")}`;return j(i,{width:70,title:u})}function Cd(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=qt(e,k),i=qt(o,".errors"),s=Wn(o)?qt(i,r):qt(Sd(),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 Wn(Ht(s))||vi(Ht(s),{recursive:!0}),xi(s,a.join(`
566
+ `)),s}catch{return null}}import B from"picocolors";async function lt(e={}){let t=T();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
567
+ `):c.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){c.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})}
568
+ `);return}c.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).`),c.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}`})}
569
+ `):c.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)}
570
+ `);return}c.message(Ed(i)),i.paid===!1&&c.message(`${B.dim("Upgrade for autopilot:")} ${B.cyan(A.PRICING)}`)}function Ed(e){let n=i=>B.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${B.green("\u2713")} ${B.dim("Logged in as")} ${B.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${B.cyan(e.domain)}`}),e.plan){let i=e.paid?B.bold(B.green(e.plan)):B.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${B.dim(e.api_base)}`});let o=`${B.bold(B.cyan("SEOAgent"))} ${B.dim("\xB7")} ${B.dim("whoami")}`;return j(r,{width:55,title:o})}import{select as dt,text as ut,confirm as Ei,isCancel as q,intro as Ad,outro as Rd}from"@clack/prompts";import Yt from"picocolors";function Id(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>ze()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await W()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await qe()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await Xe()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await lt()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await dt({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(!q(e))if(e==="peek"){let t=await ut({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(q(t))return;await ue({peek:String(t)})}else e==="discover"?await ue({discover:!0}):e==="competitors"?await ue({competitors:!0}):await ue()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>nt({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await dt({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"}]});q(e)||rt(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 it()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await ut({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(q(e))return;let t=await ut({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});q(t)||await ct({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>at({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await dt({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"}]});q(e)||await tt(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await we()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await ut({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(q(e))return;let t=await Ei({message:"Mark as failed instead of completed?",initialValue:!1});if(q(t))return;let n;if(t===!0){let r=await ut({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(q(r))return;String(r).trim()&&(n=String(r))}await ce(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 Ve()},{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 Qe({})},{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 dt({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"}]});q(e)||st({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>Ze()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await He({})}]}var _i="__exit__";async function Ci(e=Id()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:_i,label:"Exit",hint:"Close the menu"});let n=await dt({message:"What would you like to do?",options:t});if(q(n)||n===_i)return!0;let r=e.find(o=>o.command===n);if(!r)return c.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){c.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function qn(){if(!process.stdin.isTTY){c.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}Ad(`${Yt.bold(Yt.cyan("SEOAgent"))} ${Yt.dim("\xB7 menu")}`);let e=await Ci();for(;!e;){let t=await Ei({message:"Do another?",initialValue:!0});if(q(t)||t===!1){e=!0;break}e=await Ci()}Rd(Yt.dim("See you next time."))}var C=new Pd;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=>{qe({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=>{He({yes:e.yes,global:e.global})});C.command("status").description("Show current SEO project state").action(ze);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=>{jn({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=>{Xe({apiBase:e.apiBase})});C.command("logout").description("Remove stored credentials for seoagent.com").action(Ze);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=>{W({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=>{we({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)=>{ce(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=>{xn({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=>{An({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)=>{tt(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=>{ue({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=>{nt({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)=>{On(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)=>{rt(e,{json:t.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=>{it({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=>{at({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=>{ct({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=>{lt({json:e.json,apiBase:e.apiBase})});C.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(Ve);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=>{Qe({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=>{st({all:e.all})});C.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{qn()});process.argv.length===2&&(C.outputHelp(),process.exit(0));C.parse();