@seoagent-official/seoagent 1.46.1 → 1.47.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.
Files changed (2) hide show
  1. package/index.js +63 -50
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1,32 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import{Command as sl}from"commander";import{dirname as Vr,relative as Cn}from"path";import{intro as Xr,outro as Qr,text as En,select as St,spinner as Zr,isCancel as se,cancel as ae,confirm as ei}from"@clack/prompts";function lt(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 p(e,t=lt()){return t?`seoagent ${e}`:`npx -y @seoagent-official/seoagent ${e}`}import{randomUUID as Zo}from"crypto";import{existsSync as Jt,mkdirSync as Vt,readFileSync as er,writeFileSync as Xt}from"fs";import{join as pt}from"path";var te=[".env.local",".env.production",".env"],Kt=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];import{homedir as Bo}from"os";import{join as Ue}from"path";var S=".seoagent",Ht=["audit","strategy/clusters","briefs","content","content/images","performance"],z={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},De=".claude/settings.json",zt=".pull-receipt.json",Yt=`# SEOAgent local files
2
+ import{Command as ml}from"commander";import{dirname as Qr,relative as An}from"path";import{intro as Zr,outro as ei,text as In,select as St,spinner as ti,isCancel as se,cancel as ae,confirm as ni}from"@clack/prompts";function lt(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 p(e,t=lt()){return t?`seoagent ${e}`:`npx -y @seoagent-official/seoagent ${e}`}import{randomUUID as tr}from"crypto";import{existsSync as Xt,mkdirSync as Qt,readFileSync as nr,writeFileSync as Zt}from"fs";import{join as pt}from"path";var te=[".env.local",".env.production",".env"],zt=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];import{homedir as Go}from"os";import{join as Ue}from"path";var S=".seoagent",Yt=["audit","strategy/clusters","briefs","content","content/images","performance"],Y={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},De=".claude/settings.json",qt=".pull-receipt.json",Jt=`# SEOAgent local files
3
3
  .legacy/
4
4
  content/images/*
5
5
  !content/images/.gitkeep
6
6
  .pull-receipt.json
7
- `,Wo=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:Ue(Bo(),".config"),N=Ue(Wo,"seoagent"),W=Ue(N,"auth.json"),ct=Ue(N,"state");var fe="https://seoagent.com",ne=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):fe,b={BASE:ne,PRICING:`${ne}/pricing`,LEAD_API:`${ne}/api/cli/lead`,CLI_AUTH_PAGE:`${ne}/cli/auth`,CLI_AUTH_POLL:`${ne}/api/cli/auth/poll`,CLI_SYNC:`${ne}/api/cli/sync`};import{readFileSync as Go}from"fs";import{fileURLToPath as Ko}from"url";import{dirname as Ho,join as zo}from"path";var qt="0.0.0";function Yo(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return qt}function qo(e=t=>Go(t,"utf-8")){try{let t=Ho(Ko(import.meta.url));return Yo(e(zo(t,"package.json")))}catch{return qt}}var oe=qo();import{existsSync as Jo,readFileSync as Vo}from"fs";var Me="---";function Xo(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 ut(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==Me)return{data:{},body:e};let n={},o=1;for(;o<t.length;o++){if(t[o].trim()===Me){o++;break}let r=t[o],i=r.indexOf(":");if(i===-1)continue;let s=r.slice(0,i).trim(),a=r.slice(i+1);s&&(n[s]=Xo(a))}return{data:n,body:t.slice(o).join(`
8
- `)}}function Be(e){if(!Jo(e))return null;try{return ut(Vo(e,"utf-8"))}catch{return null}}function Qo(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 dt(e,t=""){let n=[Me];for(let[r,i]of Object.entries(e))i!==void 0&&n.push(`${r}: ${Qo(i)}`);n.push(Me);let o=t.length===0?"":t.startsWith(`
7
+ `,Ko=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:Ue(Go(),".config"),N=Ue(Ko,"seoagent"),G=Ue(N,"auth.json"),ct=Ue(N,"state");var fe="https://seoagent.com",ne=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):fe,b={BASE:ne,PRICING:`${ne}/pricing`,LEAD_API:`${ne}/api/cli/lead`,CLI_AUTH_PAGE:`${ne}/cli/auth`,CLI_AUTH_POLL:`${ne}/api/cli/auth/poll`,CLI_SYNC:`${ne}/api/cli/sync`};import{readFileSync as Ho}from"fs";import{fileURLToPath as zo}from"url";import{dirname as Yo,join as qo}from"path";var Vt="0.0.0";function Jo(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return Vt}function Vo(e=t=>Ho(t,"utf-8")){try{let t=Yo(zo(import.meta.url));return Jo(e(qo(t,"package.json")))}catch{return Vt}}var oe=Vo();import{existsSync as Xo,readFileSync as Qo}from"fs";var Be="---";function Zo(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 ut(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==Be)return{data:{},body:e};let n={},o=1;for(;o<t.length;o++){if(t[o].trim()===Be){o++;break}let r=t[o],i=r.indexOf(":");if(i===-1)continue;let s=r.slice(0,i).trim(),a=r.slice(i+1);s&&(n[s]=Zo(a))}return{data:n,body:t.slice(o).join(`
8
+ `)}}function Me(e){if(!Xo(e))return null;try{return ut(Qo(e,"utf-8"))}catch{return null}}function er(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 dt(e,t=""){let n=[Be];for(let[r,i]of Object.entries(e))i!==void 0&&n.push(`${r}: ${er(i)}`);n.push(Be);let o=t.length===0?"":t.startsWith(`
9
9
  `)?t:`
10
10
  ${t}`;return n.join(`
11
11
  `)+o+(o.endsWith(`
12
12
  `)?"":`
13
- `)}var tr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function mt(){return Zo()}var nr=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),or="project.md";function ge(e){return pt(e,S)}function We(e){return pt(ge(e),or)}function Qt(e){return Jt(We(e))}function _(e){let t=Be(We(e));if(!t)return null;let n=t.data;if(typeof n.domain!="string"||!n.domain)return null;let o=typeof n.image_provider=="string"?n.image_provider:void 0,r=typeof n.cms=="string"?n.cms:void 0,i=r&&nr.has(r)?r: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:"",install_id:s&&tr.test(s)?s:void 0,image_provider:o==="openai"||o==="fal"||o==="replicate"||o==="none"?o:void 0,cms:i,blog_path:typeof n.blog_path=="string"&&n.blog_path?n.blog_path:void 0}}function Zt(e){let t=_(e);if(!t)return null;if(t.install_id)return t.install_id;let n=mt();return he(e,{install_id:n}),n}function rr(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(`
14
- `)}function ir(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.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 en(e,t){let n=ge(e);Vt(n,{recursive:!0});let o=dt(ir(t),rr(t));Xt(We(e),o,"utf-8")}function he(e,t){let n=We(e);if(!Jt(n))return!1;let o=ut(er(n,"utf-8")),r={...o.data,...t};return Xt(n,dt(r,o.body),"utf-8"),!0}function tn(e){let t=ge(e);for(let n of Ht)Vt(pt(t,n),{recursive:!0})}import{existsSync as Ge,lstatSync as sr,mkdirSync as ye,readFileSync as nn,readdirSync as ar,rmSync as lr,statSync as cr,symlinkSync as ur,writeFileSync as on}from"fs";import{dirname as Ke,join as F,relative as rn}from"path";import{fileURLToPath as dr}from"url";var pr=Ke(dr(import.meta.url));function sn(){return F(pr,"skills")}function mr(){let e=F(sn(),"seoagent.md");if(Ge(e))return nn(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function an(e,t){let n=[];if(!Ge(e))return n;for(let o of ar(e,{withFileTypes:!0})){let r=F(e,o.name),i=F(t,o.name);o.isDirectory()?(ye(i,{recursive:!0}),n.push(...an(r,i))):o.isFile()&&(ye(Ke(i),{recursive:!0}),on(i,nn(r)),n.push(i))}return n}function ln(e,t){let n=Ge(F(e,".agents")),o=F(e,n?z.AGENTS:z.CLAUDE),r=F(o,"SKILL.md");ye(o,{recursive:!0}),on(r,t??mr(),"utf-8");let i=F(sn(),"references"),s=F(o,"references"),a=[];try{Ge(i)&&cr(i).isDirectory()&&(ye(s,{recursive:!0}),a=an(i,s).map(u=>rn(o,u)))}catch{}let l=n?fr(e,o):void 0;return{skillFile:r,referenceFiles:a,claudeSymlink:l}}function fr(e,t){let n=F(e,z.CLAUDE),o=null;try{o=sr(n)}catch{}if(o){if(!o.isSymbolicLink())return;try{lr(n,{force:!0})}catch{return}}try{ye(Ke(n),{recursive:!0});let r=rn(Ke(n),t);return ur(r,n,"dir"),n}catch{return}}import{existsSync as He,mkdirSync as ft,readFileSync as gr,writeFileSync as we}from"fs";import{dirname as cn,join as re}from"path";var hr="npx -y @seoagent-official/seoagent sync --silent";function un(e){let t=re(e,S);ft(t,{recursive:!0});let n=re(t,".gitignore");we(n,Yt,"utf-8");let o=re(t,"content","images",".gitkeep");return ft(cn(o),{recursive:!0}),He(o)||we(o,"","utf-8"),n}function gt(e){if(!He(e))return{};try{let t=gr(e,"utf-8");return JSON.parse(t)}catch{return{}}}function ht(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function dn(e){let t=re(e,De);ft(cn(t),{recursive:!0});let n=gt(t);n.hooks=n.hooks??{};let o=n.hooks.PostToolUse=n.hooks.PostToolUse??[],r=o.find(i=>(i.matcher??"").includes("Write"));return r||(r={matcher:"Write|Edit",hooks:[]},o.push(r)),r.hooks.some(ht)?(we(t,JSON.stringify(n,null,2)+`
15
- `,"utf-8"),{file:t,added:!1}):(r.hooks.push({type:"command",command:hr}),we(t,JSON.stringify(n,null,2)+`
16
- `,"utf-8"),{file:t,added:!0})}function pn(e){let t=re(e,De);if(!He(t))return!1;let n=gt(t).hooks?.PostToolUse;return Array.isArray(n)?n.some(o=>o.hooks?.some(ht)):!1}function mn(e){let t=re(e,De);if(!He(t))return{file:t,removed:!1};let n=gt(t),o=n.hooks?.PostToolUse;if(!Array.isArray(o))return{file:t,removed:!1};let r=!1;for(let i of o){let s=i.hooks.length;i.hooks=i.hooks.filter(a=>!ht(a)),i.hooks.length!==s&&(r=!0)}return r?(n.hooks.PostToolUse=o.filter(i=>i.hooks.length>0),n.hooks.PostToolUse.length===0&&delete n.hooks.PostToolUse,n.hooks&&Object.keys(n.hooks).length===0&&delete n.hooks,we(t,JSON.stringify(n,null,2)+`
17
- `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{readFileSync as Kl,writeFileSync as yr,existsSync as Hl}from"fs";import{join as wr}from"path";function fn(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[r,i]of n){let s=e.business[i];t.push(`- **${r}:** ${s||""}`)}let o=new Set(n.map(([,r])=>r));for(let[r,i]of Object.entries(e.business))if(!o.has(r)&&i){let s=r.charAt(0).toUpperCase()+r.slice(1);t.push(`- **${s}:** ${i}`)}if(t.push(""),t.push("# Writing Instructions"),t.push(""),e.writingInstructions.length>0)for(let r of e.writingInstructions)t.push(`- ${r}`);else t.push("- (Add your content writing guidelines here)");if(t.push(""),t.push("# Reference URLs"),t.push(""),e.referenceUrls.length>0)for(let r of e.referenceUrls)r.description?t.push(`- ${r.url} \u2014 ${r.description}`):t.push(`- ${r.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 r of e.topicsToAvoid)t.push(`- ${r}`);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(`
18
- `)}var kr="context.md";function br(e,t){let n=wr(e,".seoagent",kr),o=fn(t);yr(n,o,"utf-8")}function gn(e,t){br(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as ke,readFileSync as hn,readdirSync as $r,statSync as yn}from"fs";import{join as Y}from"path";var Sr=[{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 vr(e){let t=Y(e,"package.json");if(!ke(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(hn(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function xr(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 _r(e){let t={};for(let n of te){let o=Y(e,n);if(ke(o))try{let r=hn(o,"utf-8");for(let i of r.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 Cr(e,t){let n=Y(e,t.replace(/\/$/,""));if(!ke(n))return!1;if(t.endsWith("/"))try{return yn(n).isDirectory()}catch{return!1}return!0}function Er(e){let t=["content","_posts","posts",Y("src","content")];for(let n of t){let o=Y(e,n);if(ke(o))try{if(!yn(o).isDirectory())continue;let r=[o],i=0;for(;r.length>0&&i<50;){let s=r.pop();for(let a of $r(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&r.length<5){r.push(Y(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 Ar(e){let t=[{marker:"app/blog/page.tsx",path:"/blog"},{marker:"app/blog/page.jsx",path:"/blog"},{marker:"app/blog/page.js",path:"/blog"},{marker:"src/app/blog/page.tsx",path:"/blog"},{marker:"src/app/blog/page.jsx",path:"/blog"},{marker:"pages/blog/index.tsx",path:"/blog"},{marker:"pages/blog/index.jsx",path:"/blog"},{marker:"pages/blog/index.js",path:"/blog"},{marker:"src/pages/blog/index.tsx",path:"/blog"},{marker:"app/(blog)/page.tsx",path:"/blog"},{marker:"app/articles/page.tsx",path:"/articles"},{marker:"pages/articles/index.tsx",path:"/articles"},{marker:"app/posts/page.tsx",path:"/posts"},{marker:"pages/posts/index.tsx",path:"/posts"},{marker:"app/learn/page.tsx",path:"/learn"},{marker:"app/resources/page.tsx",path:"/resources"}];for(let n of t)if(ke(Y(e,n.marker)))return n.path;return null}function wn(e){let t=[],{deps:n}=vr(e),o=_r(e),r="none";for(let s of Sr){let a=[];for(let l of Object.keys(n))if(xr(l,s.deps)){a.push({type:"dep",detail:l,source:"package.json"});break}for(let l of s.envKeys)if(o[l]){a.push({type:"env",detail:l,source:o[l]});break}for(let l of s.fsMarkers)if(Cr(e,l)){let u=l.endsWith("/")?"directory":"file";a.push({type:u,detail:l,source:l});break}if(a.length>0){r=s.cms,t.push(...a);break}}if(r==="none"){let s=Er(e);s&&(r="mdx-local",t.push(s))}let i=Ar(e);return{cms:r,blog_path:i,evidence:t}}import{existsSync as q,readFileSync as yt}from"fs";import{join as J}from"path";function kn(e){try{return new URL(e).hostname}catch{return e}}function bn(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 Ir(e){for(let t of te){let n=J(e,t);if(!q(n))continue;let o=yt(n,"utf-8");for(let r of Kt){let i=o.match(new RegExp(`^${r}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=kn(s);if(bn(a))continue;return{value:a,source:`${t} (${r})`}}}}return null}function Pr(e){let t=J(e,"package.json");if(!q(t))return null;try{let n=JSON.parse(yt(t,"utf-8"));if(!n.homepage)return null;let o=kn(n.homepage);return bn(o)?null:{value:o,source:"package.json (homepage)"}}catch{return null}}function $n(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),q(J(e,"pnpm-workspace.yaml"))&&n.push({field:"context",detail:"Monorepo workspace detected",source:"pnpm-workspace.yaml \u2014 using this directory for project signals"});let o=null;t?.("Scanning .env files for public / site URLs\u2026");let r=Ir(e);if(r)o=r.value,n.push({field:"domain",detail:r.value,source:r.source});else{t?.("Reading package.json homepage (skipping GitHub/GitLab repo URLs)\u2026");let a=Pr(e);a&&(o=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=J(e,"package.json"),s=null;if(q(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(yt(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(m=>l.includes(m));if(u("@shopify/hydrogen","@shopify/polaris")||q(J(e,"shopify.config.js"))||q(J(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":q(J(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"),m=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),f=u("next");d&&(f||m)?(s="saas",n.push({field:"site_type",detail:"saas",source:f?"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:o,siteType:s,evidence:n}}import{existsSync as Rr,readFileSync as Tr,readdirSync as Or,statSync as Lr}from"fs";import{join as V,sep as jr}from"path";var Sn=["tsx","jsx","js","mdx","md"],Nr=["astro","md","mdx"],Fr=5e3;function ze(e,t){let n=new Map,o=0,r=(i,s,a=!1)=>{let l=Ur(i);if(l===null){o++;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:Yr(t,l),in_sitemap:a,source:s})};for(let i of["app",V("src","app")]){let s=V(e,i);if(wt(s))for(let a of kt(s)){let l=bt(s,a),u=l[l.length-1];Gr(u)&&(l.some(d=>d.startsWith("@"))||r(Dr(l.slice(0,-1)),"app router"))}}for(let i of["pages",V("src","pages")]){let s=V(e,i);if(wt(s))for(let a of kt(s)){let l=bt(s,a);if(l[0]==="api")continue;let u=l[l.length-1],d=$t(u),m=Sn.includes(d),f=Nr.includes(d);if(!m&&!f)continue;let x=Ye(u);Kr(x)||r(Mr(l),f?"astro":"pages router")}}for(let i of[".","public"]){let s=V(e,i);if(wt(s))for(let a of kt(s,i==="."?1:1/0)){let l=bt(s,a),u=l[l.length-1];$t(u)==="html"&&(l.some(d=>d==="node_modules"||d.startsWith("."))||r(Br(l),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=V(e,...i.split("/"));if(Rr(s)){for(let a of Hr(s)){let l=Wr(a);l!==null&&r(l,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:o}}function Ur(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function Dr(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function Mr(e){let t=[...e],n=Ye(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Br(e){let t=[...e],n=Ye(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Wr(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function Gr(e){return Ye(e)==="page"&&Sn.includes($t(e))}function Kr(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Hr(e){try{let t=Tr(e,"utf-8"),n=[],o=/<loc>\s*([^<\s]+)\s*<\/loc>/gi,r;for(;(r=o.exec(t))!==null;)n.push(r[1].trim());return n}catch{return[]}}var zr=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function wt(e){try{return Lr(e).isDirectory()}catch{return!1}}function*kt(e,t=1/0){let n=0;function*o(r,i){if(i>t)return;let s;try{s=Or(r,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=Fr)return;if(a.name.startsWith("."))continue;let l=V(r,a.name);if(a.isDirectory()){if(zr.has(a.name))continue;yield*o(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*o(e,1)}function bt(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(jr).filter(Boolean)}function $t(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Ye(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Yr(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as qr,writeFileSync as Jr}from"fs";import{join as vn}from"path";function _n(e,t){if(t.length===0)return;let n=vn(e,S);qr(n,{recursive:!0});let o=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
13
+ `)}var or=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function mt(){return tr()}var rr=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),ir="project.md";function ge(e){return pt(e,S)}function We(e){return pt(ge(e),ir)}function en(e){return Xt(We(e))}function _(e){let t=Me(We(e));if(!t)return null;let n=t.data;if(typeof n.domain!="string"||!n.domain)return null;let o=typeof n.image_provider=="string"?n.image_provider:void 0,r=typeof n.cms=="string"?n.cms:void 0,i=r&&rr.has(r)?r: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:"",install_id:s&&or.test(s)?s:void 0,image_provider:o==="openai"||o==="fal"||o==="replicate"||o==="none"?o:void 0,cms:i,blog_path:typeof n.blog_path=="string"&&n.blog_path?n.blog_path:void 0}}function tn(e){let t=_(e);if(!t)return null;if(t.install_id)return t.install_id;let n=mt();return he(e,{install_id:n}),n}function sr(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(`
14
+ `)}function ar(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.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 nn(e,t){let n=ge(e);Qt(n,{recursive:!0});let o=dt(ar(t),sr(t));Zt(We(e),o,"utf-8")}function he(e,t){let n=We(e);if(!Xt(n))return!1;let o=ut(nr(n,"utf-8")),r={...o.data,...t};return Zt(n,dt(r,o.body),"utf-8"),!0}function on(e){let t=ge(e);for(let n of Yt)Qt(pt(t,n),{recursive:!0})}import{existsSync as Ge,lstatSync as lr,mkdirSync as ye,readFileSync as rn,readdirSync as cr,rmSync as ur,statSync as dr,symlinkSync as pr,writeFileSync as sn}from"fs";import{dirname as Ke,join as F,relative as an}from"path";import{fileURLToPath as mr}from"url";var fr=Ke(mr(import.meta.url));function ln(){return F(fr,"skills")}function gr(){let e=F(ln(),"seoagent.md");if(Ge(e))return rn(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function cn(e,t){let n=[];if(!Ge(e))return n;for(let o of cr(e,{withFileTypes:!0})){let r=F(e,o.name),i=F(t,o.name);o.isDirectory()?(ye(i,{recursive:!0}),n.push(...cn(r,i))):o.isFile()&&(ye(Ke(i),{recursive:!0}),sn(i,rn(r)),n.push(i))}return n}function un(e,t){let n=Ge(F(e,".agents")),o=F(e,n?Y.AGENTS:Y.CLAUDE),r=F(o,"SKILL.md");ye(o,{recursive:!0}),sn(r,t??gr(),"utf-8");let i=F(ln(),"references"),s=F(o,"references"),a=[];try{Ge(i)&&dr(i).isDirectory()&&(ye(s,{recursive:!0}),a=cn(i,s).map(u=>an(o,u)))}catch{}let l=n?hr(e,o):void 0;return{skillFile:r,referenceFiles:a,claudeSymlink:l}}function hr(e,t){let n=F(e,Y.CLAUDE),o=null;try{o=lr(n)}catch{}if(o){if(!o.isSymbolicLink())return;try{ur(n,{force:!0})}catch{return}}try{ye(Ke(n),{recursive:!0});let r=an(Ke(n),t);return pr(r,n,"dir"),n}catch{return}}import{existsSync as He,mkdirSync as ft,readFileSync as yr,writeFileSync as we}from"fs";import{dirname as dn,join as re}from"path";var wr="npx -y @seoagent-official/seoagent sync --silent";function pn(e){let t=re(e,S);ft(t,{recursive:!0});let n=re(t,".gitignore");we(n,Jt,"utf-8");let o=re(t,"content","images",".gitkeep");return ft(dn(o),{recursive:!0}),He(o)||we(o,"","utf-8"),n}function gt(e){if(!He(e))return{};try{let t=yr(e,"utf-8");return JSON.parse(t)}catch{return{}}}function ht(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function mn(e){let t=re(e,De);ft(dn(t),{recursive:!0});let n=gt(t);n.hooks=n.hooks??{};let o=n.hooks.PostToolUse=n.hooks.PostToolUse??[],r=o.find(i=>(i.matcher??"").includes("Write"));return r||(r={matcher:"Write|Edit",hooks:[]},o.push(r)),r.hooks.some(ht)?(we(t,JSON.stringify(n,null,2)+`
15
+ `,"utf-8"),{file:t,added:!1}):(r.hooks.push({type:"command",command:wr}),we(t,JSON.stringify(n,null,2)+`
16
+ `,"utf-8"),{file:t,added:!0})}function fn(e){let t=re(e,De);if(!He(t))return!1;let n=gt(t).hooks?.PostToolUse;return Array.isArray(n)?n.some(o=>o.hooks?.some(ht)):!1}function gn(e){let t=re(e,De);if(!He(t))return{file:t,removed:!1};let n=gt(t),o=n.hooks?.PostToolUse;if(!Array.isArray(o))return{file:t,removed:!1};let r=!1;for(let i of o){let s=i.hooks.length;i.hooks=i.hooks.filter(a=>!ht(a)),i.hooks.length!==s&&(r=!0)}return r?(n.hooks.PostToolUse=o.filter(i=>i.hooks.length>0),n.hooks.PostToolUse.length===0&&delete n.hooks.PostToolUse,n.hooks&&Object.keys(n.hooks).length===0&&delete n.hooks,we(t,JSON.stringify(n,null,2)+`
17
+ `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{readFileSync as Xl,writeFileSync as kr,existsSync as Ql}from"fs";import{join as br}from"path";function hn(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[r,i]of n){let s=e.business[i];t.push(`- **${r}:** ${s||""}`)}let o=new Set(n.map(([,r])=>r));for(let[r,i]of Object.entries(e.business))if(!o.has(r)&&i){let s=r.charAt(0).toUpperCase()+r.slice(1);t.push(`- **${s}:** ${i}`)}if(t.push(""),t.push("# Writing Instructions"),t.push(""),e.writingInstructions.length>0)for(let r of e.writingInstructions)t.push(`- ${r}`);else t.push("- (Add your content writing guidelines here)");if(t.push(""),t.push("# Reference URLs"),t.push(""),e.referenceUrls.length>0)for(let r of e.referenceUrls)r.description?t.push(`- ${r.url} \u2014 ${r.description}`):t.push(`- ${r.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 r of e.topicsToAvoid)t.push(`- ${r}`);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(`
18
+ `)}var $r="context.md";function Sr(e,t){let n=br(e,".seoagent",$r),o=hn(t);kr(n,o,"utf-8")}function yn(e,t){Sr(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as ke,readFileSync as wn,readdirSync as vr,statSync as kn}from"fs";import{join as q}from"path";var xr=[{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 _r(e){let t=q(e,"package.json");if(!ke(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(wn(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Cr(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 Er(e){let t={};for(let n of te){let o=q(e,n);if(ke(o))try{let r=wn(o,"utf-8");for(let i of r.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 Ar(e,t){let n=q(e,t.replace(/\/$/,""));if(!ke(n))return!1;if(t.endsWith("/"))try{return kn(n).isDirectory()}catch{return!1}return!0}function Ir(e){let t=["content","_posts","posts",q("src","content")];for(let n of t){let o=q(e,n);if(ke(o))try{if(!kn(o).isDirectory())continue;let r=[o],i=0;for(;r.length>0&&i<50;){let s=r.pop();for(let a of vr(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&r.length<5){r.push(q(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 Pr(e){let t=[{marker:"app/blog/page.tsx",path:"/blog"},{marker:"app/blog/page.jsx",path:"/blog"},{marker:"app/blog/page.js",path:"/blog"},{marker:"src/app/blog/page.tsx",path:"/blog"},{marker:"src/app/blog/page.jsx",path:"/blog"},{marker:"pages/blog/index.tsx",path:"/blog"},{marker:"pages/blog/index.jsx",path:"/blog"},{marker:"pages/blog/index.js",path:"/blog"},{marker:"src/pages/blog/index.tsx",path:"/blog"},{marker:"app/(blog)/page.tsx",path:"/blog"},{marker:"app/articles/page.tsx",path:"/articles"},{marker:"pages/articles/index.tsx",path:"/articles"},{marker:"app/posts/page.tsx",path:"/posts"},{marker:"pages/posts/index.tsx",path:"/posts"},{marker:"app/learn/page.tsx",path:"/learn"},{marker:"app/resources/page.tsx",path:"/resources"}];for(let n of t)if(ke(q(e,n.marker)))return n.path;return null}function bn(e){let t=[],{deps:n}=_r(e),o=Er(e),r="none";for(let s of xr){let a=[];for(let l of Object.keys(n))if(Cr(l,s.deps)){a.push({type:"dep",detail:l,source:"package.json"});break}for(let l of s.envKeys)if(o[l]){a.push({type:"env",detail:l,source:o[l]});break}for(let l of s.fsMarkers)if(Ar(e,l)){let u=l.endsWith("/")?"directory":"file";a.push({type:u,detail:l,source:l});break}if(a.length>0){r=s.cms,t.push(...a);break}}if(r==="none"){let s=Ir(e);s&&(r="mdx-local",t.push(s))}let i=Pr(e);return{cms:r,blog_path:i,evidence:t}}import{existsSync as J,readFileSync as yt}from"fs";import{join as V}from"path";function $n(e){try{return new URL(e).hostname}catch{return e}}function Sn(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 Rr(e){for(let t of te){let n=V(e,t);if(!J(n))continue;let o=yt(n,"utf-8");for(let r of zt){let i=o.match(new RegExp(`^${r}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=$n(s);if(Sn(a))continue;return{value:a,source:`${t} (${r})`}}}}return null}function Tr(e){let t=V(e,"package.json");if(!J(t))return null;try{let n=JSON.parse(yt(t,"utf-8"));if(!n.homepage)return null;let o=$n(n.homepage);return Sn(o)?null:{value:o,source:"package.json (homepage)"}}catch{return null}}function vn(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),J(V(e,"pnpm-workspace.yaml"))&&n.push({field:"context",detail:"Monorepo workspace detected",source:"pnpm-workspace.yaml \u2014 using this directory for project signals"});let o=null;t?.("Scanning .env files for public / site URLs\u2026");let r=Rr(e);if(r)o=r.value,n.push({field:"domain",detail:r.value,source:r.source});else{t?.("Reading package.json homepage (skipping GitHub/GitLab repo URLs)\u2026");let a=Tr(e);a&&(o=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=V(e,"package.json"),s=null;if(J(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(yt(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(m=>l.includes(m));if(u("@shopify/hydrogen","@shopify/polaris")||J(V(e,"shopify.config.js"))||J(V(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":J(V(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"),m=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),g=u("next");d&&(g||m)?(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"})):!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:o,siteType:s,evidence:n}}import{existsSync as Or,readFileSync as Lr,readdirSync as jr,statSync as Nr}from"fs";import{join as X,sep as Fr}from"path";var xn=["tsx","jsx","js","mdx","md"],Ur=["astro","md","mdx"],Dr=5e3;function ze(e,t){let n=new Map,o=0,r=(i,s,a=!1)=>{let l=Br(i);if(l===null){o++;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:Jr(t,l),in_sitemap:a,source:s})};for(let i of["app",X("src","app")]){let s=X(e,i);if(wt(s))for(let a of kt(s)){let l=bt(s,a),u=l[l.length-1];Hr(u)&&(l.some(d=>d.startsWith("@"))||r(Mr(l.slice(0,-1)),"app router"))}}for(let i of["pages",X("src","pages")]){let s=X(e,i);if(wt(s))for(let a of kt(s)){let l=bt(s,a);if(l[0]==="api")continue;let u=l[l.length-1],d=$t(u),m=xn.includes(d),g=Ur.includes(d);if(!m&&!g)continue;let x=Ye(u);zr(x)||r(Wr(l),g?"astro":"pages router")}}for(let i of[".","public"]){let s=X(e,i);if(wt(s))for(let a of kt(s,i==="."?1:1/0)){let l=bt(s,a),u=l[l.length-1];$t(u)==="html"&&(l.some(d=>d==="node_modules"||d.startsWith("."))||r(Gr(l),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=X(e,...i.split("/"));if(Or(s)){for(let a of Yr(s)){let l=Kr(a);l!==null&&r(l,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:o}}function Br(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function Mr(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function Wr(e){let t=[...e],n=Ye(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Gr(e){let t=[...e],n=Ye(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Kr(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function Hr(e){return Ye(e)==="page"&&xn.includes($t(e))}function zr(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Yr(e){try{let t=Lr(e,"utf-8"),n=[],o=/<loc>\s*([^<\s]+)\s*<\/loc>/gi,r;for(;(r=o.exec(t))!==null;)n.push(r[1].trim());return n}catch{return[]}}var qr=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function wt(e){try{return Nr(e).isDirectory()}catch{return!1}}function*kt(e,t=1/0){let n=0;function*o(r,i){if(i>t)return;let s;try{s=jr(r,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=Dr)return;if(a.name.startsWith("."))continue;let l=X(r,a.name);if(a.isDirectory()){if(qr.has(a.name))continue;yield*o(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*o(e,1)}function bt(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(Fr).filter(Boolean)}function $t(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Ye(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Jr(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as Vr,writeFileSync as Xr}from"fs";import{join as _n}from"path";function En(e,t){if(t.length===0)return;let n=_n(e,S);Vr(n,{recursive:!0});let o=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
19
19
  `),r=["# Pages","","Inventory of pages discovered in your codebase at setup. Status,","rendered, and in-nav are filled in by the Phase 1 audit. Add or remove","rows freely \u2014 this file syncs to the cloud when you log in."].join(`
20
- `),i="| URL | In sitemap | In nav | Status | Rendered | Notes |",s="|---|---|---|---|---|---|",a=t.map(u=>`| ${xn(u.url)} | ${u.in_sitemap?"yes":"no"} | \u2014 | \u2014 | \u2014 | ${xn(u.source)} |`),l=[o,"",r,"",i,s,...a,""].join(`
21
- `);Jr(vn(n,"pages.md"),l,"utf-8")}function xn(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as ie}from"@clack/prompts";var c={info:e=>ie.info(e),warn:e=>ie.warn(e),error:e=>ie.error(e),success:e=>ie.success(e),step:e=>ie.step(e),message:e=>ie.message(e)};function w(e,t,n,o=n){e?e.stop(o):c[t](n)}var An=[{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"}],Pn="unknown",ti=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function ni(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 qe(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return ti.has(t)?t:null}async function be(e={}){let t=process.cwd();if(Qt(t)){c.warn("SEOAgent project already exists in this directory."),c.info(`Run \`${p("status")}\` to see your project state.`),c.info(`To start fresh, run \`${p("uninstall")}\` then init again.`);return}let n=!!e.yes||!process.stdin.isTTY;n||Xr("SEOAgent \u2014 AI SEO Agent");let o=$n(t,a=>c.step(a)),r=()=>{if(o.evidence.length!==0){c.info("Inferred from your project:");for(let a of o.evidence)c.info(` \u2022 ${ni(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||o.domain||null,s=qe(e.siteType)||qe(process.env.SEOAGENT_SITE_TYPE)||o.siteType||null;if(n){e.siteType?.trim()&&qe(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()&&qe(process.env.SEOAGENT_SITE_TYPE)===null&&(c.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),r(),i||(c.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=Pn),s||(s="unknown"),await In(t,i,s);return}if(r(),!i){let a=await En({message:"Website domain",placeholder:"example.com",validate:l=>l.trim()?void 0:"Domain is required"});se(a)&&(ae("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await St({message:"What kind of site is this?",options:[...An]});se(a)&&(ae("Cancelled"),process.exit(0)),s=a}for(;;){let a=await ei({message:`Create .seoagent for ${i} (${s})?`});if(se(a)&&(ae("Cancelled"),process.exit(0)),a)break;let l=await St({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((se(l)||l==="abort")&&(ae("Cancelled"),process.exit(0)),l==="domain"){let u=await En({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});se(u)&&(ae("Cancelled"),process.exit(0)),i=String(u)}else{let u=await St({message:"What kind of site is this?",options:[...An]});se(u)&&(ae("Cancelled"),process.exit(0)),s=u}}await In(t,i,s)}async function In(e,t,n){let o=Zr();o.start("Setting up your SEO project");let r=wn(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:oe,install_id:mt(),...r.cms!=="none"?{cms:r.cms}:{},...r.blog_path?{blog_path:r.blog_path}:{}};tn(e),en(e,i),gn(e,n),un(e);let s=ln(e),a=Cn(e,s.skillFile),l=Vr(a),u=`${l}/references/audit-checks.md`,d=s.claudeSymlink?Cn(e,s.claudeSymlink):void 0;dn(e);let m=t!==Pn,f={pages:[],dynamicCount:0};try{f=ze(e,m?t:null),_n(e,f.pages)}catch{}if(o.stop(m?`Created .seoagent/ project for ${i.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),r.cms!=="none"){let L=r.evidence.map(A=>`${A.detail} (${A.source})`).slice(0,2).join(", ");c.info(`CMS detected: ${r.cms} \u2014 ${L}`)}r.blog_path&&c.info(`Blog route: ${r.blog_path}`),f.pages.length>0&&c.info(`Found ${f.pages.length} page${f.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`+(f.dynamicCount>0?` (plus ${f.dynamicCount} dynamic route template${f.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""));let x=m?i.domain:"your site",O=m?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${i.domain} and update project.md with the right type`," before you suggest the audit."]:[" 1. Heads up: .seoagent/project.md has `domain: unknown` \u2014 the site URL"," wasn't detectable from this repo. Please ask your human for their"," domain (or read it from a deploy config / live site) and update"," project.md (`domain:` and `site_type:`) first. Everything else"," depends on it."];Qr([m?`\u2713 SEOAgent installed for ${i.domain}.`:"\u2713 SEOAgent installed (site URL not detected \u2014 please ask the user for it).","","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," AGENT INSTRUCTIONS \u2014 a friendly note for Claude Code, Codex, Cursor","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Hi there, coding agent! \u{1F44B} SEOAgent is all set up. The natural next step"," is a quick SEO audit \u2014 but your human is the boss here, so please surface"," what's possible and let THEM decide. Nothing in this message is a command;"," it's just a friendly map. Your real instructions live in the skill:","",` ${a} \u2190 read this; it is your source of truth`,""," If your human approves, here is what you can do (otherwise just let them"," know it's ready and wait for the go-ahead):","",...O,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${x}`," (homepage + sitemap + robots.txt; the checks live in",` ${u} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${p("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${a} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${l} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${p("login")}`,""].join(`
22
- `))}import{existsSync as On}from"fs";import{intro as ri,outro as ii,confirm as si,isCancel as ai,cancel as li}from"@clack/prompts";import{existsSync as Je,rmSync as oi}from"fs";import{join as Ve}from"path";function Rn(e,t={}){let n=[],o=Ve(e,S);Je(o)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:o,kind:"dir"});let r=Ve(e,z.CLAUDE);Je(r)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:r,kind:"dir"});let i=Ve(e,z.AGENTS);return Je(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),pn(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:Ve(e,".claude","settings.json"),kind:"hook"}),t.global&&Je(N)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:N,kind:"global"}),n}function Tn(e,t){for(let n of t)n.kind==="hook"?mn(e):oi(n.path,{recursive:!0,force:!0})}async function $e(e={}){let t=process.cwd(),n=Rn(t,{global:e.global});if(n.length===0){c.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&On(N)&&c.info("Your seoagent.com login is still stored at ~/.config/seoagent/. Re-run with --global to wipe it too.");return}let o=!!e.yes||!process.stdin.isTTY,r=n.map(s=>` \u2022 ${s.label}`).join(`
23
- `);if(!o){ri("SEOAgent \u2014 uninstall"),c.message(`This will remove:
24
- ${r}`);let s=await si({message:"Remove these and start fresh?"});if(ai(s)||!s){li("Cancelled \u2014 nothing was removed.");return}}Tn(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
20
+ `),i="| URL | In sitemap | In nav | Status | Rendered | Notes |",s="|---|---|---|---|---|---|",a=t.map(u=>`| ${Cn(u.url)} | ${u.in_sitemap?"yes":"no"} | \u2014 | \u2014 | \u2014 | ${Cn(u.source)} |`),l=[o,"",r,"",i,s,...a,""].join(`
21
+ `);Xr(_n(n,"pages.md"),l,"utf-8")}function Cn(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as ie}from"@clack/prompts";var c={info:e=>ie.info(e),warn:e=>ie.warn(e),error:e=>ie.error(e),success:e=>ie.success(e),step:e=>ie.step(e),message:e=>ie.message(e)};function w(e,t,n,o=n){e?e.stop(o):c[t](n)}var Pn=[{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"}],Tn="unknown",oi=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function ri(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 qe(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return oi.has(t)?t:null}async function be(e={}){let t=process.cwd();if(en(t)){c.warn("SEOAgent project already exists in this directory."),c.info(`Run \`${p("status")}\` to see your project state.`),c.info(`To start fresh, run \`${p("uninstall")}\` then init again.`);return}let n=!!e.yes||!process.stdin.isTTY;n||Zr("SEOAgent \u2014 AI SEO Agent");let o=vn(t,a=>c.step(a)),r=()=>{if(o.evidence.length!==0){c.info("Inferred from your project:");for(let a of o.evidence)c.info(` \u2022 ${ri(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||o.domain||null,s=qe(e.siteType)||qe(process.env.SEOAGENT_SITE_TYPE)||o.siteType||null;if(n){e.siteType?.trim()&&qe(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()&&qe(process.env.SEOAGENT_SITE_TYPE)===null&&(c.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),r(),i||(c.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=Tn),s||(s="unknown"),await Rn(t,i,s);return}if(r(),!i){let a=await In({message:"Website domain",placeholder:"example.com",validate:l=>l.trim()?void 0:"Domain is required"});se(a)&&(ae("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await St({message:"What kind of site is this?",options:[...Pn]});se(a)&&(ae("Cancelled"),process.exit(0)),s=a}for(;;){let a=await ni({message:`Create .seoagent for ${i} (${s})?`});if(se(a)&&(ae("Cancelled"),process.exit(0)),a)break;let l=await St({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((se(l)||l==="abort")&&(ae("Cancelled"),process.exit(0)),l==="domain"){let u=await In({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});se(u)&&(ae("Cancelled"),process.exit(0)),i=String(u)}else{let u=await St({message:"What kind of site is this?",options:[...Pn]});se(u)&&(ae("Cancelled"),process.exit(0)),s=u}}await Rn(t,i,s)}async function Rn(e,t,n){let o=ti();o.start("Setting up your SEO project");let r=bn(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:oe,install_id:mt(),...r.cms!=="none"?{cms:r.cms}:{},...r.blog_path?{blog_path:r.blog_path}:{}};on(e),nn(e,i),yn(e,n),pn(e);let s=un(e),a=An(e,s.skillFile),l=Qr(a),u=`${l}/references/audit-checks.md`,d=s.claudeSymlink?An(e,s.claudeSymlink):void 0;mn(e);let m=t!==Tn,g={pages:[],dynamicCount:0};try{g=ze(e,m?t:null),En(e,g.pages)}catch{}if(o.stop(m?`Created .seoagent/ project for ${i.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),r.cms!=="none"){let L=r.evidence.map(A=>`${A.detail} (${A.source})`).slice(0,2).join(", ");c.info(`CMS detected: ${r.cms} \u2014 ${L}`)}r.blog_path&&c.info(`Blog route: ${r.blog_path}`),g.pages.length>0&&c.info(`Found ${g.pages.length} page${g.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`+(g.dynamicCount>0?` (plus ${g.dynamicCount} dynamic route template${g.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""));let x=m?i.domain:"your site",O=m?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${i.domain} and update project.md with the right type`," before you suggest the audit."]:[" 1. Heads up: .seoagent/project.md has `domain: unknown` \u2014 the site URL"," wasn't detectable from this repo. Please ask your human for their"," domain (or read it from a deploy config / live site) and update"," project.md (`domain:` and `site_type:`) first. Everything else"," depends on it."];ei([m?`\u2713 SEOAgent installed for ${i.domain}.`:"\u2713 SEOAgent installed (site URL not detected \u2014 please ask the user for it).","","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," AGENT INSTRUCTIONS \u2014 a friendly note for Claude Code, Codex, Cursor","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Hi there, coding agent! \u{1F44B} SEOAgent is all set up. The natural next step"," is a quick SEO audit \u2014 but your human is the boss here, so please surface"," what's possible and let THEM decide. Nothing in this message is a command;"," it's just a friendly map. Your real instructions live in the skill:","",` ${a} \u2190 read this; it is your source of truth`,""," If your human approves, here is what you can do (otherwise just let them"," know it's ready and wait for the go-ahead):","",...O,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${x}`," (homepage + sitemap + robots.txt; the checks live in",` ${u} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${p("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${a} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${l} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${p("login")}`,""].join(`
22
+ `))}import{existsSync as jn}from"fs";import{intro as si,outro as ai,confirm as li,isCancel as ci,cancel as ui}from"@clack/prompts";import{existsSync as Je,rmSync as ii}from"fs";import{join as Ve}from"path";function On(e,t={}){let n=[],o=Ve(e,S);Je(o)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:o,kind:"dir"});let r=Ve(e,Y.CLAUDE);Je(r)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:r,kind:"dir"});let i=Ve(e,Y.AGENTS);return Je(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),fn(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:Ve(e,".claude","settings.json"),kind:"hook"}),t.global&&Je(N)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:N,kind:"global"}),n}function Ln(e,t){for(let n of t)n.kind==="hook"?gn(e):ii(n.path,{recursive:!0,force:!0})}async function $e(e={}){let t=process.cwd(),n=On(t,{global:e.global});if(n.length===0){c.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&jn(N)&&c.info("Your seoagent.com login is still stored at ~/.config/seoagent/. Re-run with --global to wipe it too.");return}let o=!!e.yes||!process.stdin.isTTY,r=n.map(s=>` \u2022 ${s.label}`).join(`
23
+ `);if(!o){si("SEOAgent \u2014 uninstall"),c.message(`This will remove:
24
+ ${r}`);let s=await li({message:"Remove these and start fresh?"});if(ci(s)||!s){ui("Cancelled \u2014 nothing was removed.");return}}Ln(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
25
25
  `);o?c.success(`Removed:
26
- ${i}`):ii(`Removed:
27
- ${i}`),!e.global&&On(N)&&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 \`${p("init")}\`.`)}import k from"picocolors";import{existsSync as jn,mkdirSync as Ln,readFileSync as ci,writeFileSync as ui,chmodSync as di,unlinkSync as pi}from"fs";import{dirname as mi}from"path";function C(){if(!jn(W))return null;try{let e=JSON.parse(ci(W,"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||fe}}catch{return null}}function Nn(e){Ln(N,{recursive:!0}),Ln(mi(W),{recursive:!0}),ui(W,JSON.stringify(e,null,2)+`
28
- `,"utf-8");try{di(W,384)}catch{}}function Fn(){if(!jn(W))return!1;try{return pi(W),!0}catch{return!1}}import{existsSync as Se,readdirSync as vt,statSync as fi,readFileSync as Un}from"fs";import{join as le}from"path";function gi(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function hi(e){let t=le(e,"audit","latest.md");if(!Se(t))return null;let n=Be(t);if(!n)return null;let o=Un(t,"utf-8"),r=gi(o);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:r.open}}function yi(e){try{let n=Un(e,"utf-8").split(/\r?\n/),o=!1,r=0;for(let i of n){let s=i.trim();if(s.startsWith("|")&&s.endsWith("|")){if(/^\|\s*-+\s*(\|\s*-+\s*)+\|$/.test(s)){o=!0;continue}o&&r++}else if(o&&s==="")break}return r}catch{return 0}}function wi(e){let t=le(e,"strategy","clusters");if(!Se(t))return null;let n=vt(t).filter(r=>r.endsWith(".md"));if(n.length===0)return null;let o=0;for(let r of n)o+=yi(le(t,r));return{exists:!0,clusterCount:n.length,articleCount:o}}function ki(e){let t=le(e,"briefs");if(!Se(t))return null;let n=vt(t).filter(o=>o.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function bi(e){let t=le(e,"content");if(!Se(t))return null;let n=vt(t).filter(o=>o.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function $i(e){let t=le(e,"roadmap.md");return Se(t)?{exists:!0,updatedAt:fi(t).mtime.toISOString()}:null}function Dn(e){let t=_(e);if(!t)return null;let n=ge(e);return{domain:t.domain,audit:hi(n),strategy:wi(n),briefs:ki(n),content:bi(n),roadmap:$i(n)}}import G from"picocolors";var Si=/\x1b\[[0-9;]*m/g;function Mn(e){return e.replace(Si,"").length}function R(e,t={}){let n=t.width??51,o=n-4,r="\u2500".repeat(n-2),i=vi(n,t.title),s=G.dim(`\u251C${r}\u2524`),a=G.dim(`\u2514${r}\u2518`),l=[i];for(let u of e){if("sep"in u){l.push(s);continue}l.push(xi(u.content,o))}return l.push(a),l.join(`
29
- `)}function vi(e,t){if(!t)return G.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Mn(t),o=e-5-n;return o<1?G.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${G.dim("\u250C\u2500 ")}${t}${G.dim(` ${"\u2500".repeat(o)}\u2510`)}`}function xi(e,t){let n=Mn(e),o;return n<=t?o=e+" ".repeat(t-n):o=e,`${G.dim("\u2502")} ${o} ${G.dim("\u2502")}`}function xt(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n} minutes ago`;let o=Math.floor(n/60);return o<24?`${o} hours ago`:`${Math.floor(o/24)} days ago`}function ve(){let e=Dn(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${p("init")}\` to get started.`);return}c.message(_i(e))}function _i(e){if(!e)return"";let t=11,n=s=>k.dim(s.padEnd(t)),o=[];C()?(o.push({content:`${k.green("\u2713")} ${k.dim("Logged in")}`}),o.push({content:k.dim(` Run \`${p("whoami")}\` for email / plan.`)})):(o.push({content:`${k.dim("\u25CB Not logged in")}`}),o.push({content:k.dim(` Run \`${p("login")}\` to connect.`)})),o.push({sep:!0}),o.push({content:e.audit?.exists?`${n("Audit:")}${k.green(`last run ${xt(e.audit.date??"")}`)} ${k.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${k.dim("not yet run")}`}),o.push({content:e.strategy?.exists?`${n("Strategy:")}${k.bold(k.cyan(String(e.strategy.clusterCount??0)))} ${k.dim("clusters")} \xB7 ${k.bold(k.cyan(String(e.strategy.articleCount??0)))} ${k.dim("ideas")}`:`${n("Strategy:")}${k.dim("not yet created")}`}),o.push({content:e.briefs?.exists?`${n("Briefs:")}${k.bold(k.cyan(String(e.briefs.count??0)))} ${k.dim("ready")}`:`${n("Briefs:")}${k.dim("none created")}`}),o.push({content:e.content?.exists?`${n("Content:")}${k.green("\u2713")} ${k.bold(k.cyan(String(e.content.count??0)))} ${k.dim("articles written")}`:`${n("Content:")}${k.dim("no articles yet")}`}),o.push({content:e.roadmap?.exists?`${n("Roadmap:")}${k.green("updated")} ${k.dim(xt(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${k.dim("not yet created")}`});let i=`${k.bold(k.cyan("SEOAgent"))} ${k.dim("\xB7")} ${k.bold(e.domain)}`;return R(o,{width:78,title:i})}import{exec as Ci,spawn as Ei}from"child_process";import{confirm as Ai,isCancel as Ii}from"@clack/prompts";import P from"picocolors";var Pi="https://registry.npmjs.org/@seoagent-official/seoagent/latest",xe="@seoagent-official/seoagent",_e=["free","starter","pro","scale","enterprise"],Xe={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function Ri(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return _e.includes(t)?t:null}function Ti(e){let t=_e.indexOf(e);return t===-1||t===_e.length-1?null:_e[t+1]}async function Oi(e,t=fetch){if(!e)return null;try{let n=(e.api_base||b.BASE).replace(/\/$/,""),o=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!o.ok)return null;let r=await o.json();return typeof r.plan!="string"||!r.plan?null:{plan:r.plan,email:typeof r.email=="string"&&r.email?r.email:void 0,domain:typeof r.domain=="string"&&r.domain?r.domain:void 0}}catch{return null}}function Li(e){let t=[],o=s=>P.dim(s.padEnd(10)),r=!1;e.email&&(t.push({content:`${o("Email:")}${P.bold(e.email)}`}),r=!0),e.domain&&(t.push({content:`${o("Website:")}${P.cyan(e.domain)}`}),r=!0),r&&t.push({sep:!0});for(let s of _e){let a=Xe[s];s===e.current?t.push({content:`${P.bold(P.green("\u25CF"))} ${P.bold(P.green(a.padEnd(11)))} ${P.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${P.yellow("\u25C6")} ${P.bold(P.yellow(a.padEnd(11)))} ${P.yellow("next tier")}`}):t.push({content:P.dim(` ${a}`)})}let i=`${P.bold(P.cyan("SEOAgent Cloud"))} ${P.dim("\xB7")} ${P.dim("your plan")}`;return R(t,{width:55,title:i})}async function Ce(){let e=C(),t=!!process.stdin.isTTY;if(e&&t){let n=await Oi(e);if(n){let o=Ri(n.plan),r=o?Ti(o):null;if(o&&c.message(Li({email:n.email,domain:n.domain,current:o,next:r})),o&&!r){c.success(`You're on ${Xe[o]} (highest tier).`);return}if(o&&r){let i=await Ai({message:`Upgrade from ${Xe[o]} to ${Xe[r]}?`});if(Ii(i)||!i){c.info("No changes.");return}}}}ji()}function ji(){let e=Ni();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}"`;Ci(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function Ni(){let e=process.cwd(),t=_(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${b.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ee(e={}){let t=oe,n=await Ui();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 ${xe}@latest`);return}if(Fi(t,n)>=0){c.success(`You're on the latest CLI (${t}).`);return}if(!lt()){c.info(`A newer CLI is available: ${t} \u2192 ${n}.`),c.message("You're running via npx \u2014 it already fetches the latest on every run."),c.message(`For a bare \`seoagent <cmd>\` form, install globally once: npm install -g ${xe}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${xe}@latest`);return}c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),await Di()?c.success(`Updated to ${n}.`):c.error(`Update failed. Try manually: npm install -g ${xe}@latest (you may need sudo on Linux/macOS).`)}function Fi(e,t){let n=i=>i.replace(/[-+].*$/,"").split(".").map(s=>Number.parseInt(s,10)||0).slice(0,3),o=n(e),r=n(t);for(let i=0;i<3;i++){let s=(o[i]??0)-(r[i]??0);if(s!==0)return s}return 0}async function Ui(e=fetch){try{let t=await e(Pi,{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 Di(){return new Promise(e=>{let t=Ei("npm",["install","-g",`${xe}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as Mi}from"child_process";import{randomBytes as Bi}from"crypto";import{isCancel as Wi,spinner as Gi,text as Ki}from"@clack/prompts";import K from"picocolors";function Bn(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 o=typeof n.email=="string"&&n.email?n.email:void 0,r=typeof n.domain=="string"&&n.domain?n.domain:void 0;return{status:"ready",user_token:n.user_token,website_token:n.website_token,...o?{email:o}:{},...r?{domain:r}:{}}}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 Hi=1500,zi=300*1e3;function Yi(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;Mi(t,()=>{})}function qi(){return Bi(16).toString("hex")}function Ji(e,t,n){let o=new URLSearchParams({session:t});return n&&n!=="unknown"&&o.set("domain",n),`${e}/cli/auth?${o.toString()}`}function Wn(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 Vi(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,o=await fetch(n,{headers:{Accept:"application/json"}}),r=null;try{r=await o.json()}catch{}return Bn(o.status,r)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Xi(e){return new Promise(t=>setTimeout(t,e))}async function Ae(e={}){let t=process.cwd(),n=_(t),o=(e.apiBase||b.BASE||fe).replace(/\/$/,"");if(C()){c.info(`Already logged in. To switch accounts, run \`${p("logout")}\` first.`);return}let r=n?.domain??null;if(r==="unknown"&&process.stdin.isTTY){let m=await Ki({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(x){if(!String(x??"").trim())return"A site URL is required.";if(!Wn(String(x)))return"Please enter a valid domain like `example.com`."}});if(Wi(m)){c.warn("Login cancelled.");return}let f=Wn(String(m));if(f){r=f;try{he(t,{domain:f}),c.success(`Saved domain: ${f} \u2192 .seoagent/project.md`)}catch{}}}let i=qi(),s=Ji(o,i,r);c.message("Opening seoagent.com to connect this CLI to your account..."),c.info(`If the browser does not open, visit: ${s}`),Yi(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?Gi():null;l?.start(K.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+zi,d=!0;for(;Date.now()<u;){d||await Xi(Hi),d=!1;let m=await Vi(o,i);if(m.status==="ready"){Nn({user_token:m.user_token,website_token:m.website_token,api_base:o});let f=m.email&&m.domain?`Logged in as ${m.email} (${m.domain}). Future SEO work in this repo will sync to your dashboard.`:m.email?`Logged in as ${m.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.",x=m.email&&m.domain?`Logged in as ${K.bold(m.email)} (${K.cyan(m.domain)}).`:m.email?`Logged in as ${K.bold(m.email)}.`:"Logged in.";w(l,"success",f,K.green(x)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(m.status==="expired"){w(l,"warn",`Session expired. Run \`${p("login")}\` again.`,K.red("Session expired.")),l&&c.warn(`Run \`${p("login")}\` again.`);return}if(m.status==="error"){if(m.terminal){w(l,"warn",`Login failed: ${m.message}. Run \`${p("login")}\` again.`,K.red(`Login failed: ${m.message}.`)),l&&c.warn(`Run \`${p("login")}\` again.`);return}continue}}w(l,"warn",`Login timed out. Run \`${p("login")}\` again to retry.`,K.yellow("Login timed out.")),l&&c.warn(`Run \`${p("login")}\` again to retry.`)}function Ie(){Fn()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as Bs}from"@clack/prompts";import Pe from"picocolors";import{existsSync as Pt,mkdirSync as Es,readFileSync as to,readdirSync as As,statSync as Is,writeFileSync as Ps}from"fs";import{join as Rt,relative as Rs,sep as Ts}from"path";var Qi=new Set([502,503,504]);async function ce(e,t,n={}){let o=Math.max(1,n.attempts??3),r=Math.max(0,n.baseDelayMs??500),i=n.fetchImpl??fetch,s=n.sleep??Zi,a=n.transientStatuses??Qi,l=null;for(let u=0;u<o;u++)try{let d=await i(e,t);if(a.has(d.status)&&u<o-1){await s(Gn(r,u));continue}return d}catch(d){if(l=d,u<o-1){await s(Gn(r,u));continue}}throw l instanceof Error?l:new Error(String(l))}function Gn(e,t){return e*Math.pow(3,t)}function Zi(e){return new Promise(t=>setTimeout(t,e))}import{existsSync as Et,mkdirSync as es,readdirSync as Kn,readFileSync as ts,unlinkSync as ns,writeFileSync as Ct}from"fs";import{join as ue}from"path";import j from"picocolors";function B(e){return ue(e,S,"inbox")}function Hn(e){return`${e.action_type}-${e.id}.md`}function os(e,t){let n=0;if(!Et(e))return 0;for(let o of Kn(e)){if(!o.endsWith(".md")||o==="README.md")continue;let r=o.match(/^(?:.+)-(\d+)\.md$/);if(!r)continue;let i=Number.parseInt(r[1],10);if(!Number.isNaN(i)&&!t.has(i))try{ns(ue(e,o)),n++}catch{}}return n}function rs(e){let t=e.payload||{},n=t.articleId??"unknown",o=t.slug??null,r=t.originalTitle??null,i=t.originalUrl??null,s=t.cmsType??null;return`---
26
+ ${i}`):ai(`Removed:
27
+ ${i}`),!e.global&&jn(N)&&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 \`${p("init")}\`.`)}import k from"picocolors";import{existsSync as Fn,mkdirSync as Nn,readFileSync as di,writeFileSync as pi,chmodSync as mi,unlinkSync as fi}from"fs";import{dirname as gi}from"path";function C(){if(!Fn(G))return null;try{let e=JSON.parse(di(G,"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||fe}}catch{return null}}function Un(e){Nn(N,{recursive:!0}),Nn(gi(G),{recursive:!0}),pi(G,JSON.stringify(e,null,2)+`
28
+ `,"utf-8");try{mi(G,384)}catch{}}function Dn(){if(!Fn(G))return!1;try{return fi(G),!0}catch{return!1}}import{existsSync as Se,readdirSync as vt,statSync as hi,readFileSync as Bn}from"fs";import{join as le}from"path";function yi(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function wi(e){let t=le(e,"audit","latest.md");if(!Se(t))return null;let n=Me(t);if(!n)return null;let o=Bn(t,"utf-8"),r=yi(o);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:r.open}}function ki(e){try{let n=Bn(e,"utf-8").split(/\r?\n/),o=!1,r=0;for(let i of n){let s=i.trim();if(s.startsWith("|")&&s.endsWith("|")){if(/^\|\s*-+\s*(\|\s*-+\s*)+\|$/.test(s)){o=!0;continue}o&&r++}else if(o&&s==="")break}return r}catch{return 0}}function bi(e){let t=le(e,"strategy","clusters");if(!Se(t))return null;let n=vt(t).filter(r=>r.endsWith(".md"));if(n.length===0)return null;let o=0;for(let r of n)o+=ki(le(t,r));return{exists:!0,clusterCount:n.length,articleCount:o}}function $i(e){let t=le(e,"briefs");if(!Se(t))return null;let n=vt(t).filter(o=>o.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Si(e){let t=le(e,"content");if(!Se(t))return null;let n=vt(t).filter(o=>o.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function vi(e){let t=le(e,"roadmap.md");return Se(t)?{exists:!0,updatedAt:hi(t).mtime.toISOString()}:null}function Mn(e){let t=_(e);if(!t)return null;let n=ge(e);return{domain:t.domain,audit:wi(n),strategy:bi(n),briefs:$i(n),content:Si(n),roadmap:vi(n)}}import K from"picocolors";var xi=/\x1b\[[0-9;]*m/g;function Wn(e){return e.replace(xi,"").length}function R(e,t={}){let n=t.width??51,o=n-4,r="\u2500".repeat(n-2),i=_i(n,t.title),s=K.dim(`\u251C${r}\u2524`),a=K.dim(`\u2514${r}\u2518`),l=[i];for(let u of e){if("sep"in u){l.push(s);continue}l.push(Ci(u.content,o))}return l.push(a),l.join(`
29
+ `)}function _i(e,t){if(!t)return K.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Wn(t),o=e-5-n;return o<1?K.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${K.dim("\u250C\u2500 ")}${t}${K.dim(` ${"\u2500".repeat(o)}\u2510`)}`}function Ci(e,t){let n=Wn(e),o;return n<=t?o=e+" ".repeat(t-n):o=e,`${K.dim("\u2502")} ${o} ${K.dim("\u2502")}`}function xt(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n} minutes ago`;let o=Math.floor(n/60);return o<24?`${o} hours ago`:`${Math.floor(o/24)} days ago`}function ve(){let e=Mn(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${p("init")}\` to get started.`);return}c.message(Ei(e))}function Ei(e){if(!e)return"";let t=11,n=s=>k.dim(s.padEnd(t)),o=[];C()?(o.push({content:`${k.green("\u2713")} ${k.dim("Logged in")}`}),o.push({content:k.dim(` Run \`${p("whoami")}\` for email / plan.`)})):(o.push({content:`${k.dim("\u25CB Not logged in")}`}),o.push({content:k.dim(` Run \`${p("login")}\` to connect.`)})),o.push({sep:!0}),o.push({content:e.audit?.exists?`${n("Audit:")}${k.green(`last run ${xt(e.audit.date??"")}`)} ${k.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${k.dim("not yet run")}`}),o.push({content:e.strategy?.exists?`${n("Strategy:")}${k.bold(k.cyan(String(e.strategy.clusterCount??0)))} ${k.dim("clusters")} \xB7 ${k.bold(k.cyan(String(e.strategy.articleCount??0)))} ${k.dim("ideas")}`:`${n("Strategy:")}${k.dim("not yet created")}`}),o.push({content:e.briefs?.exists?`${n("Briefs:")}${k.bold(k.cyan(String(e.briefs.count??0)))} ${k.dim("ready")}`:`${n("Briefs:")}${k.dim("none created")}`}),o.push({content:e.content?.exists?`${n("Content:")}${k.green("\u2713")} ${k.bold(k.cyan(String(e.content.count??0)))} ${k.dim("articles written")}`:`${n("Content:")}${k.dim("no articles yet")}`}),o.push({content:e.roadmap?.exists?`${n("Roadmap:")}${k.green("updated")} ${k.dim(xt(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${k.dim("not yet created")}`});let i=`${k.bold(k.cyan("SEOAgent"))} ${k.dim("\xB7")} ${k.bold(e.domain)}`;return R(o,{width:78,title:i})}import{exec as Ai,spawn as Ii}from"child_process";import{confirm as Pi,isCancel as Ri}from"@clack/prompts";import P from"picocolors";var Ti="https://registry.npmjs.org/@seoagent-official/seoagent/latest",xe="@seoagent-official/seoagent",_e=["free","starter","pro","scale","enterprise"],Xe={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function Oi(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return _e.includes(t)?t:null}function Li(e){let t=_e.indexOf(e);return t===-1||t===_e.length-1?null:_e[t+1]}async function ji(e,t=fetch){if(!e)return null;try{let n=(e.api_base||b.BASE).replace(/\/$/,""),o=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!o.ok)return null;let r=await o.json();return typeof r.plan!="string"||!r.plan?null:{plan:r.plan,email:typeof r.email=="string"&&r.email?r.email:void 0,domain:typeof r.domain=="string"&&r.domain?r.domain:void 0}}catch{return null}}function Ni(e){let t=[],o=s=>P.dim(s.padEnd(10)),r=!1;e.email&&(t.push({content:`${o("Email:")}${P.bold(e.email)}`}),r=!0),e.domain&&(t.push({content:`${o("Website:")}${P.cyan(e.domain)}`}),r=!0),r&&t.push({sep:!0});for(let s of _e){let a=Xe[s];s===e.current?t.push({content:`${P.bold(P.green("\u25CF"))} ${P.bold(P.green(a.padEnd(11)))} ${P.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${P.yellow("\u25C6")} ${P.bold(P.yellow(a.padEnd(11)))} ${P.yellow("next tier")}`}):t.push({content:P.dim(` ${a}`)})}let i=`${P.bold(P.cyan("SEOAgent Cloud"))} ${P.dim("\xB7")} ${P.dim("your plan")}`;return R(t,{width:55,title:i})}async function Ce(){let e=C(),t=!!process.stdin.isTTY;if(e&&t){let n=await ji(e);if(n){let o=Oi(n.plan),r=o?Li(o):null;if(o&&c.message(Ni({email:n.email,domain:n.domain,current:o,next:r})),o&&!r){c.success(`You're on ${Xe[o]} (highest tier).`);return}if(o&&r){let i=await Pi({message:`Upgrade from ${Xe[o]} to ${Xe[r]}?`});if(Ri(i)||!i){c.info("No changes.");return}}}}Fi()}function Fi(){let e=Ui();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}"`;Ai(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function Ui(){let e=process.cwd(),t=_(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${b.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ee(e={}){let t=oe,n=await Bi();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 ${xe}@latest`);return}if(Di(t,n)>=0){c.success(`You're on the latest CLI (${t}).`);return}if(!lt()){c.info(`A newer CLI is available: ${t} \u2192 ${n}.`),c.message("You're running via npx \u2014 it already fetches the latest on every run."),c.message(`For a bare \`seoagent <cmd>\` form, install globally once: npm install -g ${xe}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${xe}@latest`);return}c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),await Mi()?c.success(`Updated to ${n}.`):c.error(`Update failed. Try manually: npm install -g ${xe}@latest (you may need sudo on Linux/macOS).`)}function Di(e,t){let n=i=>i.replace(/[-+].*$/,"").split(".").map(s=>Number.parseInt(s,10)||0).slice(0,3),o=n(e),r=n(t);for(let i=0;i<3;i++){let s=(o[i]??0)-(r[i]??0);if(s!==0)return s}return 0}async function Bi(e=fetch){try{let t=await e(Ti,{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 Mi(){return new Promise(e=>{let t=Ii("npm",["install","-g",`${xe}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as Wi}from"child_process";import{randomBytes as Gi}from"crypto";import{isCancel as Ki,spinner as Hi,text as zi}from"@clack/prompts";import H from"picocolors";function Gn(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 o=typeof n.email=="string"&&n.email?n.email:void 0,r=typeof n.domain=="string"&&n.domain?n.domain:void 0;return{status:"ready",user_token:n.user_token,website_token:n.website_token,...o?{email:o}:{},...r?{domain:r}:{}}}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 Yi=1500,qi=300*1e3;function Ji(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;Wi(t,()=>{})}function Vi(){return Gi(16).toString("hex")}function Xi(e,t,n){let o=new URLSearchParams({session:t});return n&&n!=="unknown"&&o.set("domain",n),`${e}/cli/auth?${o.toString()}`}function Kn(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 Qi(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,o=await fetch(n,{headers:{Accept:"application/json"}}),r=null;try{r=await o.json()}catch{}return Gn(o.status,r)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Zi(e){return new Promise(t=>setTimeout(t,e))}async function Ae(e={}){let t=process.cwd(),n=_(t),o=(e.apiBase||b.BASE||fe).replace(/\/$/,"");if(C()){c.info(`Already logged in. To switch accounts, run \`${p("logout")}\` first.`);return}let r=n?.domain??null;if(r==="unknown"&&process.stdin.isTTY){let m=await zi({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(x){if(!String(x??"").trim())return"A site URL is required.";if(!Kn(String(x)))return"Please enter a valid domain like `example.com`."}});if(Ki(m)){c.warn("Login cancelled.");return}let g=Kn(String(m));if(g){r=g;try{he(t,{domain:g}),c.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=Vi(),s=Xi(o,i,r);c.message("Opening seoagent.com to connect this CLI to your account..."),c.info(`If the browser does not open, visit: ${s}`),Ji(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?Hi():null;l?.start(H.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+qi,d=!0;for(;Date.now()<u;){d||await Zi(Yi),d=!1;let m=await Qi(o,i);if(m.status==="ready"){Un({user_token:m.user_token,website_token:m.website_token,api_base:o});let g=m.email&&m.domain?`Logged in as ${m.email} (${m.domain}). Future SEO work in this repo will sync to your dashboard.`:m.email?`Logged in as ${m.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.",x=m.email&&m.domain?`Logged in as ${H.bold(m.email)} (${H.cyan(m.domain)}).`:m.email?`Logged in as ${H.bold(m.email)}.`:"Logged in.";w(l,"success",g,H.green(x)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(m.status==="expired"){w(l,"warn",`Session expired. Run \`${p("login")}\` again.`,H.red("Session expired.")),l&&c.warn(`Run \`${p("login")}\` again.`);return}if(m.status==="error"){if(m.terminal){w(l,"warn",`Login failed: ${m.message}. Run \`${p("login")}\` again.`,H.red(`Login failed: ${m.message}.`)),l&&c.warn(`Run \`${p("login")}\` again.`);return}continue}}w(l,"warn",`Login timed out. Run \`${p("login")}\` again to retry.`,H.yellow("Login timed out.")),l&&c.warn(`Run \`${p("login")}\` again to retry.`)}function Ie(){Dn()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as Gs}from"@clack/prompts";import Pe from"picocolors";import{existsSync as Pt,mkdirSync as Is,readFileSync as oo,readdirSync as Ps,statSync as Rs,writeFileSync as Ts}from"fs";import{join as Rt,relative as Os,sep as Ls}from"path";var es=new Set([502,503,504]);async function ce(e,t,n={}){let o=Math.max(1,n.attempts??3),r=Math.max(0,n.baseDelayMs??500),i=n.fetchImpl??fetch,s=n.sleep??ts,a=n.transientStatuses??es,l=null;for(let u=0;u<o;u++)try{let d=await i(e,t);if(a.has(d.status)&&u<o-1){await s(Hn(r,u));continue}return d}catch(d){if(l=d,u<o-1){await s(Hn(r,u));continue}}throw l instanceof Error?l:new Error(String(l))}function Hn(e,t){return e*Math.pow(3,t)}function ts(e){return new Promise(t=>setTimeout(t,e))}import{existsSync as Et,mkdirSync as ns,readdirSync as zn,readFileSync as os,unlinkSync as rs,writeFileSync as Ct}from"fs";import{join as ue}from"path";import j from"picocolors";function W(e){return ue(e,S,"inbox")}function Yn(e){return`${e.action_type}-${e.id}.md`}function is(e,t){let n=0;if(!Et(e))return 0;for(let o of zn(e)){if(!o.endsWith(".md")||o==="README.md")continue;let r=o.match(/^(?:.+)-(\d+)\.md$/);if(!r)continue;let i=Number.parseInt(r[1],10);if(!Number.isNaN(i)&&!t.has(i))try{rs(ue(e,o)),n++}catch{}}return n}function ss(e){let t=e.payload||{},n=t.articleId??"unknown",o=t.slug??null,r=t.originalTitle??null,i=t.originalUrl??null,s=t.cmsType??null;return`---
30
30
  action_id: ${e.id}
31
31
  action_type: ${e.action_type}
32
32
  article_id: ${n}
@@ -69,8 +69,8 @@ positive, you disagree, etc.), close it out as failed with a reason:
69
69
  \`\`\`bash
70
70
  ${p(`ack ${e.id}`)} --failed --reason "kept; performs well off-search"
71
71
  \`\`\`
72
- `}function is(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(`
73
- `)}}function ss(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 o=(t||"").toLowerCase();return o.includes("robots")||o.includes("ai_bot")||o.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.":o.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 as(e){let t=e.payload||{},n=t.page_url??null,o=t.issue??"other",r=t.check_id??"unknown",i=t.severity??"unknown",s=t.recommended_fix??null;return`---
72
+ `}function as(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(`
73
+ `)}}function ls(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 o=(t||"").toLowerCase();return o.includes("robots")||o.includes("ai_bot")||o.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.":o.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 cs(e){let t=e.payload||{},n=t.page_url??null,o=t.issue??"other",r=t.check_id??"unknown",i=t.severity??"unknown",s=t.recommended_fix??null;return`---
74
74
  action_id: ${e.id}
75
75
  action_type: ${e.action_type}
76
76
  issue: ${o}
@@ -93,8 +93,8 @@ ${s??e.description??"Apply the appropriate fix for this issue."}
93
93
 
94
94
  ## How to apply
95
95
 
96
- 1. ${ss(o,r,n)}
97
- 2. ${is(o)}
96
+ 1. ${ls(o,r,n)}
97
+ 2. ${as(o)}
98
98
  3. Show the user the diff before committing (confirm once per session, then proceed).
99
99
 
100
100
  ## How to close this out
@@ -111,7 +111,7 @@ next \`seoagent sync\`. If you disagree or it's a false positive, decline it:
111
111
  \`\`\`bash
112
112
  ${p(`ack ${e.id}`)} --failed --reason "not applicable; ..."
113
113
  \`\`\`
114
- `}function ls(e){let t=e.payload||{},n=t.brief_slug??null,o=t.primary_keyword??null,r=t.cluster??null,i=t.role??null,s=t.search_intent??null,a=t.priority??"medium";return`---
114
+ `}function us(e){let t=e.payload||{},n=t.brief_slug??null,o=t.primary_keyword??null,r=t.cluster??null,i=t.role??null,s=t.search_intent??null,a=t.priority??"medium";return`---
115
115
  action_id: ${e.id}
116
116
  action_type: ${e.action_type}
117
117
  brief_slug: ${n??""}
@@ -160,7 +160,7 @@ If you decide not to write it (off-strategy, duplicate, etc.), decline it:
160
160
  \`\`\`bash
161
161
  ${p(`ack ${e.id}`)} --failed --reason "skipped; ..."
162
162
  \`\`\`
163
- `}function cs(e){let t=e.payload||{},n=t.page_url??null,o=t.reason??"stale_thin",r=t.metrics??null,i=r?Object.entries(r).map(([s,a])=>`- **${s}**: ${a??"(n/a)"}`).join(`
163
+ `}function ds(e){let t=e.payload||{},n=t.page_url??null,o=t.reason??"stale_thin",r=t.metrics??null,i=r?Object.entries(r).map(([s,a])=>`- **${s}**: ${a??"(n/a)"}`).join(`
164
164
  `):"- (no metrics)";return`---
165
165
  action_id: ${e.id}
166
166
  action_type: ${e.action_type}
@@ -207,7 +207,7 @@ If you disagree (page is fine as-is, intentionally short, etc.), decline it:
207
207
  \`\`\`bash
208
208
  ${p(`ack ${e.id}`)} --failed --reason "kept as-is; ..."
209
209
  \`\`\`
210
- `}function us(e){let t=e.payload||{},n=t.sitemap_url??null,o=t.known_url_count??0,r=Array.isArray(t.urls)?t.urls:[],i=!!t.truncated,s=r.length>0?`\`\`\`
210
+ `}function ps(e){let t=e.payload||{},n=t.sitemap_url??null,o=t.known_url_count??0,r=Array.isArray(t.urls)?t.urls:[],i=!!t.truncated,s=r.length>0?`\`\`\`
211
211
  ${r.join(`
212
212
  `)}
213
213
  \`\`\`${i?`
@@ -253,7 +253,7 @@ SEOAgent re-submits the sitemap to GSC on its schedule. If a sitemap already exi
253
253
  \`\`\`bash
254
254
  ${p(`ack ${e.id}`)} --failed --reason "sitemap already served at /sitemap.xml"
255
255
  \`\`\`
256
- `}function ds(e){let t=e.payload||{},n=t.keyword??null,o=t.opportunity??"easy_win",r=t.volume??null,i=t.difficulty??null,s=t.intent??null,a=o==="competitor_gap"?"competitor gap (a rival ranks top-10 here, you don't)":"easy win (low difficulty, real volume)";return`---
256
+ `}function ms(e){let t=e.payload||{},n=t.keyword??null,o=t.opportunity??"easy_win",r=t.volume??null,i=t.difficulty??null,s=t.intent??null,a=o==="competitor_gap"?"competitor gap (a rival ranks top-10 here, you don't)":"easy win (low difficulty, real volume)";return`---
257
257
  action_id: ${e.id}
258
258
  action_type: ${e.action_type}
259
259
  keyword: ${n??""}
@@ -311,10 +311,10 @@ decline it:
311
311
  \`\`\`bash
312
312
  ${p(`ack ${e.id}`)} --failed --reason "skipped; ..."
313
313
  \`\`\`
314
- `}function ps(e){switch(e.action_type){case"cli_prune_pending":return rs(e);case"cli_technical_fix":return as(e);case"cli_new_content":return ls(e);case"cli_content_update":return cs(e);case"cli_sitemap_update":return us(e);case"cli_new_landing_page":return ds(e);default:return null}}function ms(e){if(e.length===0)return`# SEOAgent Inbox
314
+ `}function fs(e){switch(e.action_type){case"cli_prune_pending":return ss(e);case"cli_technical_fix":return cs(e);case"cli_new_content":return us(e);case"cli_content_update":return ds(e);case"cli_sitemap_update":return ps(e);case"cli_new_landing_page":return ms(e);default:return null}}function gs(e){if(e.length===0)return`# SEOAgent Inbox
315
315
 
316
316
  No pending actions. Run \`seoagent sync\` later to check for new ones.
317
- `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${Hn(n)}\``);return`# SEOAgent Inbox
317
+ `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${Yn(n)}\``);return`# SEOAgent Inbox
318
318
 
319
319
  You have **${e.length}** pending action${e.length===1?"":"s"} from your dashboard.
320
320
 
@@ -326,7 +326,7 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
326
326
 
327
327
  If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
328
328
  skill knows what to do.
329
- `}function X(e){let t=B(e);if(!Et(t))return[];let n=[];for(let o of Kn(t)){if(!o.endsWith(".md")||o==="README.md")continue;let r=o.match(/^(.+)-(\d+)\.md$/);if(!r)continue;let i=r[1],s=Number.parseInt(r[2],10);if(!Number.isFinite(s))continue;let a="no title",l=null,u=null,d=null;try{let m=ts(ue(t,o),"utf-8"),f=m.match(/^---\n([\s\S]*?)\n---/);if(f){let L=f[1];l=_t(L,"severity"),u=_t(L,"issue"),d=_t(L,"page_url")}let O=m.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);O&&(a=O[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:o,severity:l,issue:u,page_url:d})}return n.sort((o,r)=>o.id-r.id)}function de(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=fs[e.severity??""]??j.dim,o=e.severity??"unknown";return[j.dim("\u25B8"),j.bold(`id ${e.id}`),j.dim("\xB7"),j.cyan(t),n(o),j.dim("\u2014"),e.title].join(" ")}var fs={critical:e=>j.red(j.bold(e)),high:e=>j.red(e),medium:e=>j.yellow(e),low:e=>j.dim(e)};function _t(e,t){let n=e.match(new RegExp(`^${t}:[ \\t]*([^\\n]*?)[ \\t]*$`,"m"));if(!n)return null;let o=n[1].replace(/^["']|["']$/g,"").trim();return!o||o==="null"||o==="~"?null:o}function At(e){let t=B(e);if(!Et(t))return;let n=X(e),o=n.length===0?`# SEOAgent Inbox
329
+ `}function Q(e){let t=W(e);if(!Et(t))return[];let n=[];for(let o of zn(t)){if(!o.endsWith(".md")||o==="README.md")continue;let r=o.match(/^(.+)-(\d+)\.md$/);if(!r)continue;let i=r[1],s=Number.parseInt(r[2],10);if(!Number.isFinite(s))continue;let a="no title",l=null,u=null,d=null;try{let m=os(ue(t,o),"utf-8"),g=m.match(/^---\n([\s\S]*?)\n---/);if(g){let L=g[1];l=_t(L,"severity"),u=_t(L,"issue"),d=_t(L,"page_url")}let O=m.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);O&&(a=O[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:o,severity:l,issue:u,page_url:d})}return n.sort((o,r)=>o.id-r.id)}function de(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=hs[e.severity??""]??j.dim,o=e.severity??"unknown";return[j.dim("\u25B8"),j.bold(`id ${e.id}`),j.dim("\xB7"),j.cyan(t),n(o),j.dim("\u2014"),e.title].join(" ")}var hs={critical:e=>j.red(j.bold(e)),high:e=>j.red(e),medium:e=>j.yellow(e),low:e=>j.dim(e)};function _t(e,t){let n=e.match(new RegExp(`^${t}:[ \\t]*([^\\n]*?)[ \\t]*$`,"m"));if(!n)return null;let o=n[1].replace(/^["']|["']$/g,"").trim();return!o||o==="null"||o==="~"?null:o}function At(e){let t=W(e);if(!Et(t))return;let n=Q(e),o=n.length===0?`# SEOAgent Inbox
330
330
 
331
331
  No pending actions. Run \`seoagent sync\` later to check for new ones.
332
332
  `:`# SEOAgent Inbox
@@ -341,19 +341,32 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
341
341
 
342
342
  If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
343
343
  skill knows what to do.
344
- `;Ct(ue(t,"README.md"),o,"utf-8")}function zn(e,t){let n=B(e);es(n,{recursive:!0});let o=new Set(t.map(s=>s.id)),r=os(n,o),i=0;for(let s of t){let a=ps(s);a!==null&&(Ct(ue(n,Hn(s)),a,"utf-8"),i++)}return Ct(ue(n,"README.md"),ms(t),"utf-8"),{wrote:i,removed:r,inboxPath:n}}import{createHash as ys}from"crypto";import{existsSync as Jn,mkdirSync as ws,readFileSync as ks,statSync as Vn,writeFileSync as qn,rmSync as bs}from"fs";import{dirname as $s,join as It,sep as Ss}from"path";function gs(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var hs=[{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 Yn(e,t){let n=gs(e);for(let{cls:o,test:r}of hs)if(r(n))return t&&(o==="keywords"||o==="pages")?"generated-index":o;return"other"}function vs(e){return"sha256:"+ys("sha256").update(e).digest("hex")}function xs(e,t,n={}){let o=[];for(let r of e.artifacts){let i=t[r.path]??{exists:!1,locallyEdited:!1};if(!i.exists){o.push({path:r.path,kind:"write",body:r.body_md});continue}if(i.contentHash===r.content_hash){o.push({path:r.path,kind:"skip"});continue}if(r.generated){o.push({path:r.path,kind:"overwrite",body:r.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){o.push({path:r.path,kind:"conflict",note:"local newer than cloud, keeping local \u2014 use --force to take cloud"});continue}o.push({path:r.path,kind:"overwrite",body:r.body_md})}for(let r of e.deleted){let i=t[r];if(!(!i||!i.exists)){if(i.locallyEdited&&!n.force){o.push({path:r,kind:"delete-skipped",note:"server deleted this but it has local edits \u2014 keeping it (use --force to delete)"});continue}o.push({path:r,kind:"delete"})}}return o}function _s(e,t,n,o){let r=new Map;for(let s of t.artifacts)r.set(s.path,s.generated);let i=[];for(let s of e)s.kind!=="skip"&&i.push({path:s.path,kind:s.kind,class:Yn(s.path,r.get(s.path)??!1),...s.note?{note:s.note}:{}});return i.length===0?null:{pulled_at:o,cursor:n,changes:i}}async function Xn(e){let t=await Zn({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,"/"),o=t.manifest.artifacts.find(r=>r.path===n);return o?{ok:!0,body:o.body_md}:{ok:!1,error:`No cloud artifact found at "${n}"`}}function Qn(e,t){return It(e,t.split("/").join(Ss))}function Cs(e,t,n){let o={};for(let r of t){let i=Qn(e,r);if(!Jn(i)){o[r]={exists:!1,locallyEdited:!1};continue}let s=Vn(i),a=n[r],l=!a||a.mtime!==s.mtimeMs||a.size!==s.size;o[r]={exists:!0,contentHash:vs(ks(i,"utf-8")),locallyEdited:l}}return o}async function Zn(e){let t=e.fetchImpl??fetch,n=`${e.apiBase}/api/cli/sync`+(e.since?`?since=${encodeURIComponent(e.since)}`:"");try{let o=await t(n,{method:"GET",headers:{Authorization:e.authHeader,Accept:"application/json"}});if(!o.ok){let i=await o.text().catch(()=>"");return{ok:!1,error:`${o.status} ${i.slice(0,200)}`.trim()}}let r=await o.json().catch(()=>null);return!r||!Array.isArray(r.artifacts)||typeof r.now!="string"?{ok:!1,error:"Malformed manifest response"}:(Array.isArray(r.deleted)||(r.deleted=[]),{ok:!0,manifest:r})}catch(o){return{ok:!1,error:o.message}}}async function eo(e){let t=It(e.projectDir,S),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!Jn(t))return{...n,ok:!0};let o=await Zn({apiBase:e.apiBase,authHeader:e.authHeader,since:e.since,fetchImpl:e.fetchImpl});if(!o.ok)return{...n,ok:!1,error:o.error};let r=o.manifest,i=[...r.artifacts.map(d=>d.path),...r.deleted],s=Cs(t,i,e.stateFiles),a=xs(r,s,{force:e.force}),l={...n,cursor:r.now};for(let d of a){let m=Qn(t,d.path);try{switch(d.kind){case"skip":l.skipped++;break;case"write":case"overwrite":{ws($s(m),{recursive:!0}),qn(m,d.body??"","utf-8");let f=Vn(m);e.stateFiles[d.path]={mtime:f.mtimeMs,size:f.size},d.kind==="write"?l.written++:l.overwritten++,d.note&&l.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":bs(m,{force:!0}),delete e.stateFiles[d.path],l.deleted++;break;case"delete-skipped":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(f){l.ok=!1,l.error=`${d.path}: ${f.message}`}}(l.conflicts>0||!l.ok)&&(l.cursor=e.since);let u=_s(a,r,l.cursor,new Date().toISOString());if(u)try{qn(It(t,zt),JSON.stringify(u,null,2)+`
345
- `,"utf-8")}catch{}return l}var Os=new Set([".md"]),Ls=new Set(["inbox"]);function js(e){let t=[];function n(o,r){if(Pt(o))for(let i of As(o,{withFileTypes:!0})){if(i.name.startsWith(".")||r===""&&Ls.has(i.name))continue;let s=Rt(o,i.name);if(i.isDirectory())n(s,r?`${r}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),l=a===-1?"":i.name.slice(a);Os.has(l)&&t.push(s)}}}return n(e,""),t}function no(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Rt(ct,`${t}.json`)}function Ns(e){let t=no(e);if(!Pt(t))return{files:{},last_synced_at:null};try{return JSON.parse(to(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Fs(e,t){Es(ct,{recursive:!0}),Ps(no(e),JSON.stringify(t,null,2)+`
346
- `,"utf-8")}function Us(e,t){return Rs(e,t).split(Ts).join("/")}async function Ds(e,t){try{let n=await ce(`${e}/api/cli/actions/fetch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t},body:JSON.stringify({})});if(!n.ok){let r=await n.text().catch(()=>"");return{ok:!1,actions:[],error:`${n.status} ${r.slice(0,200)}`}}let o=await n.json().catch(()=>null);return!o||o.status!=="ok"||!Array.isArray(o.actions)?{ok:!1,actions:[],error:"Malformed response"}:{ok:!0,actions:o.actions}}catch(n){return{ok:!1,actions:[],error:n.message}}}async function Ms(e,t,n){try{let o=await ce(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!o.ok){let r=await o.text().catch(()=>"");return{ok:!1,status:o.status,error:r.slice(0,200)}}return{ok:!0,status:o.status}}catch(o){return{ok:!1,status:0,error:o.message}}}async function oo(e,t={}){let n=C();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let o=_(e);if(!o)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let r=Rt(e,S);if(!Pt(r))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let i=Ns(o.domain),s=js(r),a=n.api_base||b.BASE,l=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,m=[],f=0;if(!t.pullOnly)for(let I of s){let me=Us(r,I);if(t.pathFilter&&!me.endsWith(t.pathFilter))continue;let Fe=Is(I),st=i.files[me];if(!(!st||st.mtime!==Fe.mtimeMs||st.size!==Fe.size)&&!t.force)continue;f++;let Mo=to(I,"utf-8"),at=await Ms(a,{path:me,contents:Mo,domain:o.domain},l);at.ok?(i.files[me]={mtime:Fe.mtimeMs,size:Fe.size},u++):(d++,m.push(`${me}: ${at.status} ${at.error??""}`.trim()))}let x=await Ds(a,l),O=0,L=0;if(x.ok){let I=zn(e,x.actions);O=I.wrote,L=I.removed}else x.error&&m.push(`pull actions: ${x.error}`);let A,it=!1,Wt=i.last_synced_at;if(!t.pushOnly){let I=await eo({projectDir:e,apiBase:a,authHeader:l,since:i.last_synced_at,stateFiles:i.files,force:t.force});I.ok?Wt=I.cursor:(it=!0,I.error&&m.push(`pull: ${I.error}`)),A={written:I.written,overwritten:I.overwritten,skipped:I.skipped,conflicts:I.conflicts,deleted:I.deleted,warnings:I.warnings}}let Do=!!A&&A.written+A.overwritten+A.deleted+A.conflicts>0;if(i.last_synced_at=Wt,Fs(o.domain,i),f===0&&O===0&&L===0&&!Do&&!it&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:m,actionsPulled:0,actionsRemoved:0,pull:A};let Gt=d===0&&!it;return{ok:Gt,reason:Gt?void 0:"error",synced:u,failed:d,errors:m,actionsPulled:O,actionsRemoved:L,pull:A}}async function U(e={}){let t=!e.silent&&!!process.stdout.isTTY,n=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",o=t?Bs():null;o?.start(`${n} ${Pe.dim(".seoagent/")} with your dashboard\u2026`);let r=await oo(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){r.ok||(process.exitCode=0);return}if(r.reason==="no-auth"){w(o,"info",`Not logged in. Run \`${p("login")}\` to enable cloud sync.`,Pe.dim("Not logged in \u2014 cloud sync skipped.")),o&&c.info(`Run \`${p("login")}\` to enable cloud sync.`);return}if(r.reason==="no-project"){w(o,"info",`No SEOAgent project here. Run \`${p("init")}\` first.`,Pe.dim("No SEOAgent project \u2014 sync skipped.")),o&&c.info(`Run \`${p("init")}\` first.`);return}if(r.reason==="no-changes"){w(o,"info","Already in sync.",Pe.green("Already in sync."));return}let i=Ws(r);w(o,"success",i??"Sync complete.",Pe.green(i??"Sync complete.")),r.synced>0&&c.success(`Synced ${r.synced} file${r.synced===1?"":"s"} to your dashboard.`);let s=r.pull;if(s){let a=s.written+s.overwritten;a>0&&c.success(`Pulled ${a} file${a===1?"":"s"} from the cloud`+(s.overwritten>0?` (${s.overwritten} updated)`:"")),s.deleted>0&&c.info(`Removed ${s.deleted} file${s.deleted===1?"":"s"} deleted in the cloud.`),s.conflicts>0&&c.warn(`${s.conflicts} conflict${s.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let l of s.warnings.slice(0,5))c.info(` \u2022 ${l}`)}if(r.actionsPulled&&r.actionsPulled>0&&(c.success(`Pulled ${r.actionsPulled} pending action${r.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.')),r.actionsRemoved&&r.actionsRemoved>0&&c.info(`Cleaned up ${r.actionsRemoved} stale inbox file${r.actionsRemoved===1?"":"s"}.`),r.failed>0){c.warn(`${r.failed} file${r.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let a of r.errors.slice(0,3))c.info(` \u2022 ${a}`)}}function Ws(e){let t=e.synced,n=e.pull?e.pull.written+e.pull.overwritten:0,o=e.actionsPulled??0,r=e.pull?.conflicts??0,i=[];return t>0&&i.push(`${t} pushed`),n>0&&i.push(`${n} pulled`),o>0&&i.push(`${o} action${o===1?"":"s"}`),r>0&&i.push(`${r} conflict${r===1?"":"s"}`),i.length===0&&e.failed===0?null:i.length>0?i.join(" \xB7 "):"Sync complete."}function D(e){let t=_(e);return t||(c.error(`No SEOAgent project here. Run \`${p("init")}\` first.`),process.exitCode=1,null)}async function Q(e={}){if(e.print){let t=C();if(!t){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let n=t.api_base||b.BASE,o=await Xn({apiBase:n,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!o.ok){c.warn(o.error),process.exitCode=1;return}process.stdout.write(o.body),o.body.endsWith(`
344
+ `;Ct(ue(t,"README.md"),o,"utf-8")}function qn(e,t){let n=W(e);ns(n,{recursive:!0});let o=new Set(t.map(s=>s.id)),r=is(n,o),i=0;for(let s of t){let a=fs(s);a!==null&&(Ct(ue(n,Yn(s)),a,"utf-8"),i++)}return Ct(ue(n,"README.md"),gs(t),"utf-8"),{wrote:i,removed:r,inboxPath:n}}import{createHash as ks}from"crypto";import{existsSync as Xn,mkdirSync as bs,readFileSync as $s,statSync as Qn,writeFileSync as Vn,rmSync as Ss}from"fs";import{dirname as vs,join as It,sep as xs}from"path";function ys(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var ws=[{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 Jn(e,t){let n=ys(e);for(let{cls:o,test:r}of ws)if(r(n))return t&&(o==="keywords"||o==="pages")?"generated-index":o;return"other"}function _s(e){return"sha256:"+ks("sha256").update(e).digest("hex")}function Cs(e,t,n={}){let o=[];for(let r of e.artifacts){let i=t[r.path]??{exists:!1,locallyEdited:!1};if(!i.exists){o.push({path:r.path,kind:"write",body:r.body_md});continue}if(i.contentHash===r.content_hash){o.push({path:r.path,kind:"skip"});continue}if(r.generated){o.push({path:r.path,kind:"overwrite",body:r.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){o.push({path:r.path,kind:"conflict",note:"local newer than cloud, keeping local \u2014 use --force to take cloud"});continue}o.push({path:r.path,kind:"overwrite",body:r.body_md})}for(let r of e.deleted){let i=t[r];if(!(!i||!i.exists)){if(i.locallyEdited&&!n.force){o.push({path:r,kind:"delete-skipped",note:"server deleted this but it has local edits \u2014 keeping it (use --force to delete)"});continue}o.push({path:r,kind:"delete"})}}return o}function Es(e,t,n,o){let r=new Map;for(let s of t.artifacts)r.set(s.path,s.generated);let i=[];for(let s of e)s.kind!=="skip"&&i.push({path:s.path,kind:s.kind,class:Jn(s.path,r.get(s.path)??!1),...s.note?{note:s.note}:{}});return i.length===0?null:{pulled_at:o,cursor:n,changes:i}}async function Zn(e){let t=await to({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,"/"),o=t.manifest.artifacts.find(r=>r.path===n);return o?{ok:!0,body:o.body_md}:{ok:!1,error:`No cloud artifact found at "${n}"`}}function eo(e,t){return It(e,t.split("/").join(xs))}function As(e,t,n){let o={};for(let r of t){let i=eo(e,r);if(!Xn(i)){o[r]={exists:!1,locallyEdited:!1};continue}let s=Qn(i),a=n[r],l=!a||a.mtime!==s.mtimeMs||a.size!==s.size;o[r]={exists:!0,contentHash:_s($s(i,"utf-8")),locallyEdited:l}}return o}async function to(e){let t=e.fetchImpl??fetch,n=`${e.apiBase}/api/cli/sync`+(e.since?`?since=${encodeURIComponent(e.since)}`:"");try{let o=await t(n,{method:"GET",headers:{Authorization:e.authHeader,Accept:"application/json"}});if(!o.ok){let i=await o.text().catch(()=>"");return{ok:!1,error:`${o.status} ${i.slice(0,200)}`.trim()}}let r=await o.json().catch(()=>null);return!r||!Array.isArray(r.artifacts)||typeof r.now!="string"?{ok:!1,error:"Malformed manifest response"}:(Array.isArray(r.deleted)||(r.deleted=[]),{ok:!0,manifest:r})}catch(o){return{ok:!1,error:o.message}}}async function no(e){let t=It(e.projectDir,S),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!Xn(t))return{...n,ok:!0};let o=await to({apiBase:e.apiBase,authHeader:e.authHeader,since:e.since,fetchImpl:e.fetchImpl});if(!o.ok)return{...n,ok:!1,error:o.error};let r=o.manifest,i=[...r.artifacts.map(d=>d.path),...r.deleted],s=As(t,i,e.stateFiles),a=Cs(r,s,{force:e.force}),l={...n,cursor:r.now};for(let d of a){let m=eo(t,d.path);try{switch(d.kind){case"skip":l.skipped++;break;case"write":case"overwrite":{bs(vs(m),{recursive:!0}),Vn(m,d.body??"","utf-8");let g=Qn(m);e.stateFiles[d.path]={mtime:g.mtimeMs,size:g.size},d.kind==="write"?l.written++:l.overwritten++,d.note&&l.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":Ss(m,{force:!0}),delete e.stateFiles[d.path],l.deleted++;break;case"delete-skipped":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(g){l.ok=!1,l.error=`${d.path}: ${g.message}`}}(l.conflicts>0||!l.ok)&&(l.cursor=e.since);let u=Es(a,r,l.cursor,new Date().toISOString());if(u)try{Vn(It(t,qt),JSON.stringify(u,null,2)+`
345
+ `,"utf-8")}catch{}return l}var js=new Set([".md"]),Ns=new Set(["inbox"]);function Fs(e){let t=[];function n(o,r){if(Pt(o))for(let i of Ps(o,{withFileTypes:!0})){if(i.name.startsWith(".")||r===""&&Ns.has(i.name))continue;let s=Rt(o,i.name);if(i.isDirectory())n(s,r?`${r}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),l=a===-1?"":i.name.slice(a);js.has(l)&&t.push(s)}}}return n(e,""),t}function ro(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Rt(ct,`${t}.json`)}function Us(e){let t=ro(e);if(!Pt(t))return{files:{},last_synced_at:null};try{return JSON.parse(oo(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Ds(e,t){Is(ct,{recursive:!0}),Ts(ro(e),JSON.stringify(t,null,2)+`
346
+ `,"utf-8")}function Bs(e,t){return Os(e,t).split(Ls).join("/")}async function Ms(e,t){try{let n=await ce(`${e}/api/cli/actions/fetch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t},body:JSON.stringify({})});if(!n.ok){let r=await n.text().catch(()=>"");return{ok:!1,actions:[],error:`${n.status} ${r.slice(0,200)}`}}let o=await n.json().catch(()=>null);return!o||o.status!=="ok"||!Array.isArray(o.actions)?{ok:!1,actions:[],error:"Malformed response"}:{ok:!0,actions:o.actions}}catch(n){return{ok:!1,actions:[],error:n.message}}}async function Ws(e,t,n){try{let o=await ce(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!o.ok){let r=await o.text().catch(()=>"");return{ok:!1,status:o.status,error:r.slice(0,200)}}return{ok:!0,status:o.status}}catch(o){return{ok:!1,status:0,error:o.message}}}async function io(e,t={}){let n=C();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let o=_(e);if(!o)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let r=Rt(e,S);if(!Pt(r))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let i=Us(o.domain),s=Fs(r),a=n.api_base||b.BASE,l=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,m=[],g=0;if(!t.pullOnly)for(let I of s){let me=Bs(r,I);if(t.pathFilter&&!me.endsWith(t.pathFilter))continue;let Fe=Rs(I),st=i.files[me];if(!(!st||st.mtime!==Fe.mtimeMs||st.size!==Fe.size)&&!t.force)continue;g++;let Wo=oo(I,"utf-8"),at=await Ws(a,{path:me,contents:Wo,domain:o.domain},l);at.ok?(i.files[me]={mtime:Fe.mtimeMs,size:Fe.size},u++):(d++,m.push(`${me}: ${at.status} ${at.error??""}`.trim()))}let x=await Ms(a,l),O=0,L=0;if(x.ok){let I=qn(e,x.actions);O=I.wrote,L=I.removed}else x.error&&m.push(`pull actions: ${x.error}`);let A,it=!1,Kt=i.last_synced_at;if(!t.pushOnly){let I=await no({projectDir:e,apiBase:a,authHeader:l,since:i.last_synced_at,stateFiles:i.files,force:t.force});I.ok?Kt=I.cursor:(it=!0,I.error&&m.push(`pull: ${I.error}`)),A={written:I.written,overwritten:I.overwritten,skipped:I.skipped,conflicts:I.conflicts,deleted:I.deleted,warnings:I.warnings}}let Mo=!!A&&A.written+A.overwritten+A.deleted+A.conflicts>0;if(i.last_synced_at=Kt,Ds(o.domain,i),g===0&&O===0&&L===0&&!Mo&&!it&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:m,actionsPulled:0,actionsRemoved:0,pull:A};let Ht=d===0&&!it;return{ok:Ht,reason:Ht?void 0:"error",synced:u,failed:d,errors:m,actionsPulled:O,actionsRemoved:L,pull:A}}async function U(e={}){let t=!e.silent&&!!process.stdout.isTTY,n=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",o=t?Gs():null;o?.start(`${n} ${Pe.dim(".seoagent/")} with your dashboard\u2026`);let r=await io(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){r.ok||(process.exitCode=0);return}if(r.reason==="no-auth"){w(o,"info",`Not logged in. Run \`${p("login")}\` to enable cloud sync.`,Pe.dim("Not logged in \u2014 cloud sync skipped.")),o&&c.info(`Run \`${p("login")}\` to enable cloud sync.`);return}if(r.reason==="no-project"){w(o,"info",`No SEOAgent project here. Run \`${p("init")}\` first.`,Pe.dim("No SEOAgent project \u2014 sync skipped.")),o&&c.info(`Run \`${p("init")}\` first.`);return}if(r.reason==="no-changes"){w(o,"info","Already in sync.",Pe.green("Already in sync."));return}let i=Ks(r);w(o,"success",i??"Sync complete.",Pe.green(i??"Sync complete.")),r.synced>0&&c.success(`Synced ${r.synced} file${r.synced===1?"":"s"} to your dashboard.`);let s=r.pull;if(s){let a=s.written+s.overwritten;a>0&&c.success(`Pulled ${a} file${a===1?"":"s"} from the cloud`+(s.overwritten>0?` (${s.overwritten} updated)`:"")),s.deleted>0&&c.info(`Removed ${s.deleted} file${s.deleted===1?"":"s"} deleted in the cloud.`),s.conflicts>0&&c.warn(`${s.conflicts} conflict${s.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let l of s.warnings.slice(0,5))c.info(` \u2022 ${l}`)}if(r.actionsPulled&&r.actionsPulled>0&&(c.success(`Pulled ${r.actionsPulled} pending action${r.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.')),r.actionsRemoved&&r.actionsRemoved>0&&c.info(`Cleaned up ${r.actionsRemoved} stale inbox file${r.actionsRemoved===1?"":"s"}.`),r.failed>0){c.warn(`${r.failed} file${r.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let a of r.errors.slice(0,3))c.info(` \u2022 ${a}`)}}function Ks(e){let t=e.synced,n=e.pull?e.pull.written+e.pull.overwritten:0,o=e.actionsPulled??0,r=e.pull?.conflicts??0,i=[];return t>0&&i.push(`${t} pushed`),n>0&&i.push(`${n} pulled`),o>0&&i.push(`${o} action${o===1?"":"s"}`),r>0&&i.push(`${r} conflict${r===1?"":"s"}`),i.length===0&&e.failed===0?null:i.length>0?i.join(" \xB7 "):"Sync complete."}function D(e){let t=_(e);return t||(c.error(`No SEOAgent project here. Run \`${p("init")}\` first.`),process.exitCode=1,null)}async function Z(e={}){if(e.print){let t=C();if(!t){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let n=t.api_base||b.BASE,o=await Zn({apiBase:n,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!o.ok){c.warn(o.error),process.exitCode=1;return}process.stdout.write(o.body),o.body.endsWith(`
347
347
  `)||process.stdout.write(`
348
- `);return}await U({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as Gs,readdirSync as Ks,unlinkSync as Hs}from"fs";import{join as io}from"path";import{isCancel as zs,select as Ys}from"@clack/prompts";async function Z(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 qs(),n===null)return;let o=n,r=C();if(!r){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let i=r.api_base||b.BASE,s=`Bearer ${r.user_token}:${r.website_token}`,a=t.failed?"failed":"completed",l;try{l=await fetch(`${i}/api/cli/actions/${o}/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(u){c.error(`Network error: ${u.message}`),process.exitCode=1;return}if(!l.ok){let u=await l.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(l.status===409&&d?.code==="already_acked"){ro(o),At(process.cwd());let m=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||c.success(`Action ${o} was already ${m}.`);return}c.error(`Server rejected ack (${l.status}): ${u.slice(0,200)}`),process.exitCode=1;return}ro(o),At(process.cwd()),!t.silent&&(t.failed?c.success(`Action ${o} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):c.success(`Action ${o} marked completed.`),c.info(` inbox location: ${io(S,"inbox")}`))}function ro(e){let t=B(process.cwd());if(Gs(t)){for(let n of Ks(t))if(n.endsWith(`-${e}.md`))try{Hs(io(t,n))}catch{}}}async function qs(){let e=process.cwd(),t=X(e);if(t.length===0)return c.info("No pending actions in .seoagent/inbox/."),c.message(`Run \`${p("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 \`${p("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await Ys({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(o=>({value:o.id,label:de(o)}))});return zs(n)?(c.info("Cancelled \u2014 no action closed out."),null):n}import Qe from"picocolors";async function Tt(e={}){let t=process.cwd();if(!e.json&&!D(t))return;let n=X(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:B(t),actions:n})+`
349
- `);return}if(n.length===0){c.info(Qe.dim("No pending actions.")),c.message(`Run \`${p("sync")}\` to pull anything autopilot has queued, or \`${p("autopilot status")}\` to check whether autopilot is on.`);return}c.message(`${Qe.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),c.message("");for(let o of n)c.message(de(o));c.message(""),c.message(`Apply one: ${Qe.bold(p("ack <id>"))} \xB7 Interactive picker: ${Qe.bold(p("ack"))} (no id)`)}import{readFileSync as oa}from"fs";import{join as ra,relative as ia}from"path";import{confirm as po,isCancel as et,multiselect as sa,note as go,select as aa}from"@clack/prompts";import h from"picocolors";import{query as la}from"@anthropic-ai/claude-agent-sdk";import{existsSync as Js,readdirSync as Vs}from"fs";import{homedir as Xs}from"os";import{join as Qs}from"path";import{execSync as Ot}from"child_process";function Lt(){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":Zs()?ea()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function Zs(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return Ot(e,{stdio:"ignore"}),!0}catch{return!1}}function ea(){let e=Qs(Xs(),".claude");if(!Js(e))return!1;try{return Vs(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function so(){try{return Ot("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function ao(){try{return Ot("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var Ze={"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 co}from"marked";import{markedTerminal as ta}from"marked-terminal";var lo=!1;function na(){lo||(co.use(ta({reflowText:!1,width:100})),lo=!0)}function uo(e){if(!e)return e;na();try{let t=co.parse(e);return typeof t=="string"?t:e}catch{return e}}async function jt(e={}){let t=process.cwd();if(!D(t))return;if(!process.stdout.isTTY&&!e.yes){c.error(`\`${p("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 ma(e.yes)){process.exitCode=1;return}if(e.yes)await U({embedded:!0});else{let l=await aa({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(et(l)){c.info("Cancelled.");return}l==="sync"?await U({embedded:!0}):l==="pull"&&await Q({embedded:!0})}let o=X(t);if(o.length===0){c.info(h.dim("No pending actions to process. Inbox is empty."));return}let r;if(e.yes)r=o.map(l=>l.id),c.message(`Processing all ${o.length} pending action${o.length===1?"":"s"}\u2026`);else{let l=await sa({message:`Which actions to process? (${o.length} pending \u2014 space to toggle)`,options:o.map(u=>({value:u.id,label:de(u)})),initialValues:o.map(u=>u.id),required:!1});if(et(l)){c.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(l)||l.length===0){c.info("No actions selected. Nothing to do.");return}r=l}let i=0,s=0,a=Date.now();for(let l=0;l<r.length;l++){let u=r[l],d=o.find(A=>A.id===u);if(!d)continue;ca({index:l+1,total:r.length,entry:d});let m=ra(B(t),d.filename),f;try{f=oa(m,"utf-8")}catch(A){c.error(` Could not read ${d.filename}: ${A.message}`),s++;continue}let x=Date.now(),O=await pa({cwd:t,entry:d,actionContent:f,model:e.model}),L=mo(Date.now()-x);if(O)try{await Z(String(u),{silent:!0}),i++,c.message(""),c.message(` ${h.green("\u2713")} id ${u} ${h.dim("\u2014 applied in "+L)}`)}catch(A){c.warn(` Applied but ack failed: ${A.message}. Run \`seoagent ack ${u}\` to retry.`)}else s++,c.message(""),c.message(` ${h.red("\u2717")} id ${u} ${h.dim("\u2014 agent did not converge after "+L)}`)}da({applied:i,failed:s,total:r.length,elapsed:mo(Date.now()-a)})}function ca(e){let{index:t,total:n,entry:o}=e,r=o.issue??o.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=o.severity??"unknown",s=ua[i]??h.dim,a=[h.bold(`[${t}/${n}]`),h.dim("\xB7"),h.bold(`id ${o.id}`),h.dim("\xB7"),h.cyan(r),s(i)].join(" ");go(o.title,a)}var ua={critical:e=>h.red(h.bold(e)),high:h.red,medium:h.yellow,low:h.dim};function da(e){let{applied:t,failed:n,total:o,elapsed:r}=e,i=t===o?h.green(`\u2713 ${t}/${o} applied`):t===0?h.red(`\u2717 0/${o} applied`):h.yellow(`\u25D0 ${t}/${o} applied \xB7 ${n} failed`);go(`${i}
350
- ${h.dim("elapsed: "+r)}`,h.bold("Done"))}function mo(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),o=t%60;if(n<60)return o>0?`${n}m ${o}s`:`${n}m`;let r=Math.floor(n/60),i=n%60;return i>0?`${r}h ${i}m`:`${r}h`}async function pa(e){let{cwd:t,entry:n,actionContent:o,model:r}=e,i=ka(n,o);try{let s=la({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...r?{model:r}:{}}});for await(let a of s)if(a.type==="assistant"){let l=a.message.content;if(Array.isArray(l))for(let u of l)ga(u)}else if(a.type==="user"){let l=a.message.content;if(Array.isArray(l))for(let u of l)ya(u)}else if(a.type==="result")return process.stdout.write(`
351
- `),a.subtype==="success"&&!a.is_error;return!1}catch(s){return process.stdout.write(`
352
- `),c.error(` Agent error: ${s.message}`),!1}}async function ma(e){let t=Lt();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return c.info(h.dim(Ze[t].summary)),!0;if(c.warn(Ze[t].summary),c.message(` ${Ze[t].next}`),e)return!1;if(t==="not-installed"){let n=await po({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(et(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 o=so();if(!o.ok)return c.error(`Install failed: ${o.error}`),c.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=Lt()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await po({message:"Run `claude login` now to sign in?",initialValue:!0});if(et(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 o=ao();if(!o.ok)return c.error(`Login failed: ${o.error}`),!1}return!0}function fa(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function ga(e){if(!e||typeof e!="object")return;let t=e.type;if(t==="text"&&fa(e)){process.stdout.write(uo(e.text));return}if(t==="tool_use"){let n=String(e.name??"unknown"),o=e.input,r=ha[n]??h.cyan,i=wa(n,o);process.stdout.write(`
353
- `+r("\u25CF")+" "+h.bold(n)+h.dim("(")+i+h.dim(")")+`
354
- `);return}if(t==="thinking"){let n=e.thinking;typeof n=="string"&&n.trim()&&process.stdout.write(h.dim(h.italic(" "+ee(n,200)))+`
355
- `)}}var ha={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 ya(e){!e||typeof e!="object"||e.type==="tool_result"&&e.is_error===!0&&process.stdout.write(h.red(` \u21B3 error
356
- `))}function wa(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return h.dim(ee(fo(String(n.file_path??"")),80));case"Bash":return h.dim(ee(String(n.command??""),80));case"Grep":{let o=String(n.pattern??""),r=n.path?` in ${fo(String(n.path))}`:"";return h.dim(ee(o+r,80))}case"Glob":return h.dim(ee(String(n.pattern??""),80));case"WebFetch":return h.dim(ee(String(n.url??""),80));case"WebSearch":return h.dim(ee(String(n.query??""),80));default:return""}}function fo(e){if(!e)return e;let t=process.cwd(),n=ia(t,e);return n.startsWith("..")?e:n||e}function ee(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function ka(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
348
+ `);return}await U({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as Hs,readdirSync as zs,unlinkSync as Ys}from"fs";import{join as ao}from"path";import{isCancel as qs,select as Js}from"@clack/prompts";async function ee(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 Vs(),n===null)return;let o=n,r=C();if(!r){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let i=r.api_base||b.BASE,s=`Bearer ${r.user_token}:${r.website_token}`,a=t.failed?"failed":"completed",l;try{l=await fetch(`${i}/api/cli/actions/${o}/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(u){c.error(`Network error: ${u.message}`),process.exitCode=1;return}if(!l.ok){let u=await l.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(l.status===409&&d?.code==="already_acked"){so(o),At(process.cwd());let m=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||c.success(`Action ${o} was already ${m}.`);return}c.error(`Server rejected ack (${l.status}): ${u.slice(0,200)}`),process.exitCode=1;return}so(o),At(process.cwd()),!t.silent&&(t.failed?c.success(`Action ${o} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):c.success(`Action ${o} marked completed.`),c.info(` inbox location: ${ao(S,"inbox")}`))}function so(e){let t=W(process.cwd());if(Hs(t)){for(let n of zs(t))if(n.endsWith(`-${e}.md`))try{Ys(ao(t,n))}catch{}}}async function Vs(){let e=process.cwd(),t=Q(e);if(t.length===0)return c.info("No pending actions in .seoagent/inbox/."),c.message(`Run \`${p("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 \`${p("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await Js({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(o=>({value:o.id,label:de(o)}))});return qs(n)?(c.info("Cancelled \u2014 no action closed out."),null):n}import Qe from"picocolors";async function Tt(e={}){let t=process.cwd();if(!e.json&&!D(t))return;let n=Q(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:W(t),actions:n})+`
349
+ `);return}if(n.length===0){c.info(Qe.dim("No pending actions.")),c.message(`Run \`${p("sync")}\` to pull anything autopilot has queued, or \`${p("autopilot status")}\` to check whether autopilot is on.`);return}c.message(`${Qe.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),c.message("");for(let o of n)c.message(de(o));c.message(""),c.message(`Apply one: ${Qe.bold(p("ack <id>"))} \xB7 Interactive picker: ${Qe.bold(p("ack"))} (no id)`)}import{readFileSync as sa}from"fs";import{join as aa,relative as la}from"path";import{confirm as fo,isCancel as et,multiselect as ca,note as yo,select as ua}from"@clack/prompts";import f from"picocolors";import{query as da}from"@anthropic-ai/claude-agent-sdk";import{existsSync as Xs,readdirSync as Qs}from"fs";import{homedir as Zs}from"os";import{join as ea}from"path";import{execSync as Ot}from"child_process";function Lt(){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":ta()?na()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function ta(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return Ot(e,{stdio:"ignore"}),!0}catch{return!1}}function na(){let e=ea(Zs(),".claude");if(!Xs(e))return!1;try{return Qs(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function lo(){try{return Ot("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function co(){try{return Ot("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var Ze={"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 po}from"marked";import{markedTerminal as oa}from"marked-terminal";import jt from"picocolors";var uo=!1;function ra(){uo||(po.use(oa({reflowText:!1,width:100})),uo=!0)}function mo(e){if(!e)return e;ra();try{let t=po.parse(e);return typeof t=="string"?ia(t):e}catch{return e}}function ia(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>jt.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>jt.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,o)=>n+jt.italic(o))}async function Ft(e={}){let t=process.cwd();if(!D(t))return;if(!process.stdout.isTTY&&!e.yes){c.error(`\`${p("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 ha(e.yes)){process.exitCode=1;return}if(e.yes)await U({embedded:!0});else{let l=await ua({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(et(l)){c.info("Cancelled.");return}l==="sync"?await U({embedded:!0}):l==="pull"&&await Z({embedded:!0})}let o=Q(t);if(o.length===0){c.info(f.dim("No pending actions to process. Inbox is empty."));return}let r;if(e.yes)r=o.map(l=>l.id),c.message(`Processing all ${o.length} pending action${o.length===1?"":"s"}\u2026`);else{let l=await ca({message:`Which actions to process? (${o.length} pending \u2014 space to toggle)`,options:o.map(u=>({value:u.id,label:de(u)})),initialValues:o.map(u=>u.id),required:!1});if(et(l)){c.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(l)||l.length===0){c.info("No actions selected. Nothing to do.");return}r=l}let i=0,s=0,a=Date.now();for(let l=0;l<r.length;l++){let u=r[l],d=o.find(A=>A.id===u);if(!d)continue;pa({index:l+1,total:r.length,entry:d});let m=aa(W(t),d.filename),g;try{g=sa(m,"utf-8")}catch(A){c.error(` Could not read ${d.filename}: ${A.message}`),s++;continue}let x=Date.now(),O=await ga({cwd:t,entry:d,actionContent:g,model:e.model}),L=go(Date.now()-x);if(O)try{await ee(String(u),{silent:!0}),i++,c.message(""),c.message(` ${f.green("\u2713")} id ${u} ${f.dim("\u2014 applied in "+L)}`)}catch(A){c.warn(` Applied but ack failed: ${A.message}. Run \`seoagent ack ${u}\` to retry.`)}else s++,c.message(""),c.message(` ${f.red("\u2717")} id ${u} ${f.dim("\u2014 agent did not converge after "+L)}`)}fa({applied:i,failed:s,total:r.length,elapsed:go(Date.now()-a)})}function pa(e){let{index:t,total:n,entry:o}=e,r=o.issue??o.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=o.severity??"unknown",s=ma[i]??f.dim,a=[f.bold(`[${t}/${n}]`),f.dim("\xB7"),f.bold(`id ${o.id}`),f.dim("\xB7"),f.cyan(r),s(i)].join(" ");yo(o.title,a)}var ma={critical:e=>f.red(f.bold(e)),high:f.red,medium:f.yellow,low:f.dim};function fa(e){let{applied:t,failed:n,total:o,elapsed:r}=e,i=t===o?f.green(`\u2713 ${t}/${o} applied`):t===0?f.red(`\u2717 0/${o} applied`):f.yellow(`\u25D0 ${t}/${o} applied \xB7 ${n} failed`);yo(`${i}
350
+ ${f.dim("elapsed: "+r)}`,f.bold("Done"))}function go(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),o=t%60;if(n<60)return o>0?`${n}m ${o}s`:`${n}m`;let r=Math.floor(n/60),i=n%60;return i>0?`${r}h ${i}m`:`${r}h`}async function ga(e){let{cwd:t,entry:n,actionContent:o,model:r}=e,i=Ca(n,o);try{let s=da({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...r?{model:r}:{}}}),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 d of u)wa(d,a)}else if(l.type==="user"){let u=l.message.content;if(Array.isArray(u))for(let d of u)$a(d,a)}else if(l.type==="result")return process.stdout.write(`
351
+ `),l.subtype==="success"&&!l.is_error;return!1}catch(s){return process.stdout.write(`
352
+ `),c.error(` Agent error: ${s.message}`),!1}}async function ha(e){let t=Lt();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return c.info(f.dim(Ze[t].summary)),!0;if(c.warn(Ze[t].summary),c.message(` ${Ze[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(et(n)||!n)return c.info("Skipped install. Set up auth and re-run when ready."),!1;c.message(f.dim("Installing @anthropic-ai/claude-code globally\u2026"));let o=lo();if(!o.ok)return c.error(`Install failed: ${o.error}`),c.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=Lt()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await fo({message:"Run `claude login` now to sign in?",initialValue:!0});if(et(n)||!n)return c.info("Skipped login. Run `claude login` when ready and try again."),!1;c.message(f.dim("Launching `claude login`\u2026"));let o=co();if(!o.ok)return c.error(`Login failed: ${o.error}`),!1}return!0}function ya(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function wa(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&ya(e)){process.stdout.write(mo(e.text));return}if(n==="tool_use"){let o=String(e.id??""),r=String(e.name??"unknown"),i=e.input;o&&t.toolUseById.set(o,{name:r,input:i});let s=ba[r]??f.cyan,a=_a(r,i);process.stdout.write(s(ka)+" "+f.bold(r)+f.dim("(")+a+f.dim(")")+`
353
+ `);return}if(n==="thinking"){let o=e.thinking;typeof o=="string"&&o.trim()&&process.stdout.write(f.dim(f.italic(" "+B(o,200)))+`
354
+ `)}}var ka="\u23FA",ho="\u23BF",ba={Read:f.blue,Glob:f.cyan,Grep:f.cyan,Edit:f.yellow,Write:f.magenta,Bash:f.green,WebFetch:f.magenta,WebSearch:f.magenta};function $a(e,t){if(!e||typeof e!="object"||e.type!=="tool_result")return;let n=e.is_error===!0,o=String(e.tool_use_id??""),r=o?t.toolUseById.get(o):void 0,i=r?.name,s=e.content,a=Sa(s);if(n){process.stdout.write(f.red(` ${ho} Error`)+`
355
+ `),a&&process.stdout.write(xa(B(a,500)," ",f.red)+`
356
+ `);return}let l=va(i,a,r?.input);l&&process.stdout.write(f.dim(` ${ho} `)+l+`
357
+ `)}function Sa(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 va(e,t,n){if(!e)return"";switch(e){case"Read":{let o=(t.match(/^\s*\d+→/gm)??[]).length,r=o>0?o:t.split(`
358
+ `).filter(Boolean).length;return f.dim(`Read ${r} line${r===1?"":"s"}`)}case"Glob":{let o=t.split(`
359
+ `).filter(r=>r.trim().length>0).length;return f.dim(`Found ${o} ${o===1?"entry":"entries"}`)}case"Grep":{let o=t.split(`
360
+ `)[0]?.trim()??"";if(/^Found\s+\d+/.test(o))return f.dim(o);let r=t.split(`
361
+ `).filter(i=>i.trim()).length;return f.dim(`${r} result${r===1?"":"s"}`)}case"Edit":case"Write":{let o=n?.file_path,r=e==="Edit"?"Updated":"Created";return f.dim(o?`${r} ${Nt(String(o))}`:r)}case"Bash":{let o=t.split(`
362
+ `),r=o.slice(0,5).map(u=>B(u.trimEnd(),100)),i=o.length-5,s=r.join(`
363
+ `)+(i>0?`
364
+ \u2026 (+${i} more line${i===1?"":"s"})`:""),[a,...l]=s.split(`
365
+ `);return l.length===0?f.dim(a):f.dim(a)+`
366
+ `+f.dim(l.map(u=>" "+u).join(`
367
+ `))}case"WebFetch":case"WebSearch":return f.dim(`Fetched ${B(t.replace(/\s+/g," "),80)}`);default:return""}}function xa(e,t,n){return e.split(`
368
+ `).map(o=>n(t+o)).join(`
369
+ `)}function _a(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return f.dim(B(Nt(String(n.file_path??"")),80));case"Bash":return f.dim(B(String(n.command??""),80));case"Grep":{let o=String(n.pattern??""),r=n.path?` in ${Nt(String(n.path))}`:"";return f.dim(B(o+r,80))}case"Glob":return f.dim(B(String(n.pattern??""),80));case"WebFetch":return f.dim(B(String(n.url??""),80));case"WebSearch":return f.dim(B(String(n.query??""),80));default:return""}}function Nt(e){if(!e)return e;let t=process.cwd(),n=la(t,e);return n.startsWith("..")?e:n||e}function B(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Ca(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
357
370
 
358
371
  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.
359
372
 
@@ -366,19 +379,19 @@ Action file (\`.seoagent/inbox/${e.filename}\`):
366
379
  \`\`\`
367
380
  ${t}
368
381
  \`\`\`
369
- `}import{spinner as ba}from"@clack/prompts";import y from"picocolors";var $a=new Set(["on","off","status"]);async function Re(e,t={}){let n=(e||"").toLowerCase();if(!$a.has(n)){c.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let o=C();if(!o){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let r=t.apiBase||o.api_base||b.BASE,i=`Bearer ${o.user_token}:${o.website_token}`,a=!!process.stdout.isTTY?ba():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(`${r}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(x){w(a,"error",`Network error: ${x.message}`,y.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 O=_(process.cwd())?.domain??"",L=`${b.PRICING}?ref=cli${O?`&domain=${encodeURIComponent(O)}`:""}`;w(a,"warn","CLI autopilot is a paid feature.",y.yellow("Autopilot is a paid feature.")),c.message(Sa(L)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){w(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,y.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:m,delivery_mode:f}=d.autopilot;if(n==="on"){a?.stop(y.green("Autopilot enabled.")),c.message(Nt({enabled:!0,deliveryMode:f,action:n}));return}if(n==="off"){a?.stop(y.dim("Autopilot disabled.")),c.message(Nt({enabled:!1,deliveryMode:f,action:n}));return}a?.stop(y.dim("Status:")),c.message(Nt({enabled:m,deliveryMode:f,action:n}))}function Nt(e){let n=s=>y.dim(s.padEnd(11)),o=e.enabled?`${y.bold(y.green("\u25CF ON"))} ${y.dim("(queueing fixes for your coding agent)")}`:`${y.dim("\u25CB OFF")} ${y.dim("(no new suggestions will be queued)")}`,r=[{content:`${n("Status:")}${o}`}];e.enabled&&e.deliveryMode&&r.push({content:`${n("Mode:")}${y.dim(e.deliveryMode)}`}),r.push({sep:!0}),e.enabled?(r.push({content:`${y.dim("Apply queued fixes:")} ${y.cyan(p("sync"))}`}),r.push({content:`${y.dim("Turn off any time:")} ${y.cyan(p("autopilot off"))}`})):(r.push({content:`${y.dim("Enable (paid):")} ${y.cyan(p("autopilot on"))}`}),r.push({content:y.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${y.bold(y.cyan("SEOAgent"))} ${y.dim("\xB7")} ${y.dim("autopilot")}`;return R(r,{width:78,title:i})}function Sa(e){let t=[{content:y.bold(y.yellow("Autopilot is a paid feature."))},{sep:!0},{content:y.dim("SEOAgent continuously audits your site and queues fixes for")},{content:y.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:y.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${y.dim("Upgrade:")} ${y.cyan(e)}`}],n=`${y.bold(y.cyan("SEOAgent"))} ${y.dim("\xB7")} ${y.dim("autopilot")}`;return R(t,{width:78,title:n})}import{mkdirSync as La,writeFileSync as ja}from"fs";import{join as Ft}from"path";import{readdirSync as va,readFileSync as xa,statSync as ho}from"fs";import{join as _a}from"path";var Ca=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Ea=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"]),Aa=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Ia=5e3,Pa=512*1024;function $o(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 o=n.split("/").pop()||"",r=o.lastIndexOf(".");return r>0&&Ea.has(o.slice(r+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var wo=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,ko=/\]\(\s*([^)\s]+)/g;function Ra(e,t){if(!e)return[];let n=$o(t),o=[],r;for(wo.lastIndex=0;(r=wo.exec(e))!==null;){let i=r[1]??r[2]??r[3]??"",s=yo(i,n);s&&o.push(s)}for(ko.lastIndex=0;(r=ko.exec(e))!==null;){let i=yo(r[1],n);i&&o.push(i)}return o}function Ta(e,t,n=0){let o={};for(let s of e)o[s.route]=0;for(let s of t)s in o&&(o[s]+=1);let r=[],i=[];for(let s of e){if(s.route==="/")continue;let a=o[s.route]??0;a===0?r.push({route:s.route,url:s.url}):a===1&&i.push({route:s.route,url:s.url,inbound:a})}return r.sort((s,a)=>s.route.localeCompare(a.route)),i.sort((s,a)=>s.route.localeCompare(a.route)),{pageCount:e.length,linkOccurrences:t.length,orphans:r,weak:i,inboundByRoute:o,filesScanned:n}}function So(e,t){let n=JSON.stringify(e.orphans.slice(0,100).map(a=>a.url)),o=["---","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(`
370
- `),r=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${$o(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(`
382
+ `}import{spinner as Ea}from"@clack/prompts";import y from"picocolors";var Aa=new Set(["on","off","status"]);async function Re(e,t={}){let n=(e||"").toLowerCase();if(!Aa.has(n)){c.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let o=C();if(!o){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let r=t.apiBase||o.api_base||b.BASE,i=`Bearer ${o.user_token}:${o.website_token}`,a=!!process.stdout.isTTY?Ea():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(`${r}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(x){w(a,"error",`Network error: ${x.message}`,y.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 O=_(process.cwd())?.domain??"",L=`${b.PRICING}?ref=cli${O?`&domain=${encodeURIComponent(O)}`:""}`;w(a,"warn","CLI autopilot is a paid feature.",y.yellow("Autopilot is a paid feature.")),c.message(Ia(L)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){w(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,y.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:m,delivery_mode:g}=d.autopilot;if(n==="on"){a?.stop(y.green("Autopilot enabled.")),c.message(Ut({enabled:!0,deliveryMode:g,action:n}));return}if(n==="off"){a?.stop(y.dim("Autopilot disabled.")),c.message(Ut({enabled:!1,deliveryMode:g,action:n}));return}a?.stop(y.dim("Status:")),c.message(Ut({enabled:m,deliveryMode:g,action:n}))}function Ut(e){let n=s=>y.dim(s.padEnd(11)),o=e.enabled?`${y.bold(y.green("\u25CF ON"))} ${y.dim("(queueing fixes for your coding agent)")}`:`${y.dim("\u25CB OFF")} ${y.dim("(no new suggestions will be queued)")}`,r=[{content:`${n("Status:")}${o}`}];e.enabled&&e.deliveryMode&&r.push({content:`${n("Mode:")}${y.dim(e.deliveryMode)}`}),r.push({sep:!0}),e.enabled?(r.push({content:`${y.dim("Apply queued fixes:")} ${y.cyan(p("sync"))}`}),r.push({content:`${y.dim("Turn off any time:")} ${y.cyan(p("autopilot off"))}`})):(r.push({content:`${y.dim("Enable (paid):")} ${y.cyan(p("autopilot on"))}`}),r.push({content:y.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${y.bold(y.cyan("SEOAgent"))} ${y.dim("\xB7")} ${y.dim("autopilot")}`;return R(r,{width:78,title:i})}function Ia(e){let t=[{content:y.bold(y.yellow("Autopilot is a paid feature."))},{sep:!0},{content:y.dim("SEOAgent continuously audits your site and queues fixes for")},{content:y.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:y.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${y.dim("Upgrade:")} ${y.cyan(e)}`}],n=`${y.bold(y.cyan("SEOAgent"))} ${y.dim("\xB7")} ${y.dim("autopilot")}`;return R(t,{width:78,title:n})}import{mkdirSync as Ma,writeFileSync as Wa}from"fs";import{join as Dt}from"path";import{readdirSync as Pa,readFileSync as Ra,statSync as wo}from"fs";import{join as Ta}from"path";var Oa=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),La=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"]),ja=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Na=5e3,Fa=512*1024;function vo(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function ko(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 o=n.split("/").pop()||"",r=o.lastIndexOf(".");return r>0&&La.has(o.slice(r+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var bo=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,$o=/\]\(\s*([^)\s]+)/g;function Ua(e,t){if(!e)return[];let n=vo(t),o=[],r;for(bo.lastIndex=0;(r=bo.exec(e))!==null;){let i=r[1]??r[2]??r[3]??"",s=ko(i,n);s&&o.push(s)}for($o.lastIndex=0;(r=$o.exec(e))!==null;){let i=ko(r[1],n);i&&o.push(i)}return o}function Da(e,t,n=0){let o={};for(let s of e)o[s.route]=0;for(let s of t)s in o&&(o[s]+=1);let r=[],i=[];for(let s of e){if(s.route==="/")continue;let a=o[s.route]??0;a===0?r.push({route:s.route,url:s.url}):a===1&&i.push({route:s.route,url:s.url,inbound:a})}return r.sort((s,a)=>s.route.localeCompare(a.route)),i.sort((s,a)=>s.route.localeCompare(a.route)),{pageCount:e.length,linkOccurrences:t.length,orphans:r,weak:i,inboundByRoute:o,filesScanned:n}}function xo(e,t){let n=JSON.stringify(e.orphans.slice(0,100).map(a=>a.url)),o=["---","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(`
383
+ `),r=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${vo(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(`
371
384
  `),i=e.orphans.length===0?`## Orphan pages
372
385
 
373
- 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=>`| ${bo(a.url)} | \u2014 |`)].join(`
374
- `),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=>`| ${bo(a.url)} | ${a.inbound} |`)].join(`
386
+ 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=>`| ${So(a.url)} | \u2014 |`)].join(`
387
+ `),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=>`| ${So(a.url)} | ${a.inbound} |`)].join(`
375
388
  `);return[o,"",r,"",i,s,""].join(`
376
- `)}function bo(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*Oa(e){let t=0;function*n(o){let r;try{r=va(o,{withFileTypes:!0})}catch{return}for(let i of r){if(t>=Ia)return;if(i.name.startsWith("."))continue;let s=_a(o,i.name);if(i.isDirectory()){if(Aa.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(!Ca.has(l))continue;t++,yield s}}}yield*n(e)}function vo(e,t){let{pages:n}=ze(e,t),o=[],r=0,i=!1;try{i=ho(e).isDirectory()}catch{i=!1}if(i)for(let s of Oa(e)){let a;try{if(ho(s).size>Pa)continue;a=xa(s,"utf-8")}catch{continue}r++;for(let l of Ra(a,t))o.push(l)}return Ta(n,o,r)}function Te(e={}){let t=process.cwd(),n=D(t);if(!n)return;let o=n.domain&&n.domain!=="unknown"?n.domain:null,r=vo(t,o);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
377
- `);return}let i=Ft(t,S);La(i,{recursive:!0});let s=Ft(i,"internal-links.md");if(ja(s,So(r,o),"utf-8"),c.success(`Analyzed ${r.pageCount} page${r.pageCount===1?"":"s"} across ${r.filesScanned} file${r.filesScanned===1?"":"s"}.`),r.orphans.length===0)c.info("No orphan pages \u2014 every page has an inbound internal link.");else{c.warn(`${r.orphans.length} orphan page${r.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of r.orphans.slice(0,10))c.message(` \u2022 ${a.url}`);r.orphans.length>10&&c.message(` \u2026and ${r.orphans.length-10} more`)}c.info(`Report written to ${Ft(S,"internal-links.md")}`)}import{spinner as Co}from"@clack/prompts";import g from"picocolors";var Eo={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function Na(e){let t=process.cwd(),n=Zt(t);if(!n){c.error(`No .seoagent/project.md found. Run \`${p("init")}\` first.`),process.exitCode=1;return}let o=_(t),r=o?.domain&&o.domain!=="unknown"?o.domain:void 0,i=(e.apiBase||b.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?Co():null;a?.start(`Looking up ${g.bold(`"${e.keyword}"`)} ${g.dim("via DataForSEO (free peek)\u2026")}`);let l;try{l=await ce(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...r?{domain:r}:{}})})}catch(d){w(a,"error",`Network error: ${d.message}`,g.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})+`
378
- `);return}if(l.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}.`,g.yellow(`Daily peek quota reached for ${d}.`)),c.message(xo()),process.exitCode=1;return}if(!l.ok||!u){w(a,"error",`Peek failed (${l.status})${u?.error?`: ${u.error}`:""}`,g.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.",g.yellow("Real keyword data is temporarily unavailable. Try again later.")),c.message(g.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.",g.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){w(a,"warn",`No data returned for "${e.keyword}".`,g.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(g.green("Got it.")),c.message(Fa(u.opportunity)),u.remaining&&c.message(`${g.dim("Peeks remaining today:")} ${g.bold(String(u.remaining.install))} ${g.dim("\u2014 "+xo())}`)}function Fa(e){let n=u=>g.dim(u.padEnd(14)),o=e.volume!=null?g.bold(String(e.volume)):g.dim("n/a"),r=e.difficulty!=null?`${g.bold(String(e.difficulty))} ${g.dim(Ua(e.difficulty))}`:g.dim("n/a"),i=Eo[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?g.bold(g.green(i)):e.opportunity==="striking_distance"?g.bold(g.cyan(i)):e.opportunity==="competitor_gap"?g.bold(g.yellow(i)):g.dim(i),a=[{content:`${g.green("\u25CF")} ${g.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${o} ${g.dim("/mo")}`},{content:`${n("Difficulty:")}${r}`},{content:`${n("Opportunity:")}${s}`}],l=`${g.bold(g.cyan("Keyword peek"))}`;return R(a,{width:55,title:l})}function Ua(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function xo(e=C()){return e?`You're logged in \u2014 run \`${p("keywords")}\` for full enrichment (no quota), or \`${p("keywords --discover")}\` / \`${p("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${p("login")}`}function _o(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){c.message("Top opportunities:");for(let n of t){let o=n.volume!=null?`vol ${n.volume}`:"vol n/a",r=n.difficulty!=null?`KD ${n.difficulty}`:"KD n/a",i=n.our_position!=null?`, you're #${n.our_position}`:", not ranking";c.message(` \u2022 [${Eo[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${o}, ${r}${i}`)}}}function Da(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",o=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",r=t.their_position!=null?`#${t.their_position}`:"top 10";c.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${r}, ${n}, ${o}`)}}}async function H(e={}){if(e.peek&&e.peek.trim().length>0){await Na({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=C();if(!t){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let n=e.apiBase||t.api_base||b.BASE,o=`Bearer ${t.user_token}:${t.website_token}`,r=e.competitors?"competitors":e.discover?"discover":"enrich",i=r==="competitors"?"/api/cli/keywords/competitors":r==="discover"?"/api/cli/keywords/discover":"/api/cli/keywords/enrich",s=r==="competitors"?"Finding keywords your competitors rank for\u2026":r==="discover"?"Discovering new keywords to target\u2026":"Enriching keywords with real volume + difficulty\u2026",l=!!process.stdout.isTTY?Co():null;l?.start(s);let u;try{u=await ce(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o},body:"{}"})}catch(f){w(l,"error",`Network error: ${f.message}`,g.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"){w(l,"warn",r==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",g.yellow("Paid feature \u2014 upgrade to continue.")),c.message(r==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${g.cyan(b.PRICING)}`:`Upgrade to find new keywords to target: ${g.cyan(b.PRICING)}`),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"){w(l,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,g.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}if(d.skipped==="no-keywords"||d.skipped==="no-seeds"){w(l,"warn","No keywords yet. Run the keyword strategy (Phase 2) first, then try again.",g.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.",g.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.",g.yellow("Real keyword data is not enabled on the server yet."));return}if(d.skipped){w(l,"warn",`Skipped: ${d.skipped}`,g.yellow(`Skipped: ${d.skipped}`));return}if(r==="competitors"){let f=d.gaps??0;w(l,"success",`Found ${f} competitor gap${f===1?"":"s"} across ${d.competitors?.length??0} competitor${d.competitors?.length===1?"":"s"} (added as "suggested").`,g.green(`${f} competitor gap${f===1?"":"s"} found.`)),Da(d.topGaps??[]),c.message(`Review them in ${g.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}if(r==="discover"){let f=d.discovered??0;w(l,"success",`Discovered ${f} new keyword${f===1?"":"s"} to target (added as "suggested").`,g.green(`${f} new keyword${f===1?"":"s"} discovered.`)),_o(d.opportunities??[]),c.message(`Review them in ${g.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}let m=d.enriched??0;w(l,"success",`Enriched ${m} keyword${m===1?"":"s"}.`,g.green(`Enriched ${m} keyword${m===1?"":"s"}.`)),_o(d.opportunities??[]),d.paid||c.message(`${g.dim("Free plan:")} enriched up to ${g.bold(String(d.cap??25))} keywords. ${g.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${g.cyan(b.PRICING)}`)}import v from"picocolors";import{existsSync as Ma,readFileSync as Ba}from"fs";import{join as Wa}from"path";var Ao=["openai","fal","replicate"],pe={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Ga(e){let t={};if(!Ma(e))return t;let n=Ba(e,"utf-8");for(let o of n.split(/\r?\n/)){let r=o.trim();if(!r||r.startsWith("#"))continue;let i=r.indexOf("=");if(i===-1)continue;let s=r.slice(0,i).trim(),a=r.slice(i+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return t}function Io(e,t){let n={};for(let o of t){let r=process.env[o];r&&r.trim().length>0&&(n[o]={value:r,source:"process"})}for(let o of te){let r=Wa(e,o),i=Ga(r);for(let s of t){if(n[s])continue;let a=i[s];a&&a.length>0&&(n[s]={value:a,source:o})}}return{found:n}}function tt(e){let t=[].concat(...Ao.map(a=>pe[a])),n=Io(e,t),o=[];for(let a of Ao)pe[a].some(l=>n.found[l])&&o.push(a);if(o.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let r=o[0],i=pe[r].find(a=>n.found[a])??null,s=i?n.found[i].source:null;return{provider:r,matched_key:i,source:s,available_providers:o}}function Po(e,t){let n=Io(e,pe[t]);for(let o of pe[t])if(n.found[o])return{key:n.found[o].value,envName:o};return null}function Ro(){return pe}function Oe(e={}){let t=process.cwd(),n=_(t),o=tt(t);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
379
- `);return}if(c.message(Ka(o)),!n){c.warn(`No SEOAgent project here. Run \`${p("init")}\` first to persist the provider.`);return}he(t,{image_provider:o.provider}),c.info(`Saved to ${v.cyan(".seoagent/project.md")} ${v.dim(`(image_provider: ${o.provider})`)}`)}function Ka(e){let n=i=>v.dim(i.padEnd(12)),o=[];if(e.provider==="none"){o.push({content:`${v.dim("\u25CB")} ${v.bold(v.yellow("No image provider detected"))}`}),o.push({sep:!0}),o.push({content:v.dim("Set ONE of these to enable image generation:")});let i=Ro();for(let s of Object.keys(i))o.push({content:`${n(s+":")}${v.cyan(i[s].join(" or "))}`});o.push({sep:!0}),o.push({content:v.dim("Add to your shell, .env.local, or .env, then re-run:")}),o.push({content:` ${v.cyan(p("env-check"))}`})}else{o.push({content:`${v.green("\u2713")} ${v.dim("Image provider:")} ${v.bold(v.green(e.provider))}`}),o.push({sep:!0}),e.matched_key&&o.push({content:`${n("Key:")}${v.bold(e.matched_key)}`}),e.source&&o.push({content:`${n("Source:")}${v.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&o.push({content:`${n("Available:")}${v.dim(i.join(", "))}`})}let r=`${v.bold(v.cyan("SEOAgent"))} ${v.dim("\xB7")} ${v.dim("env-check")}`;return R(o,{width:64,title:r})}import{existsSync as Dt,mkdirSync as Lo,writeFileSync as jo}from"fs";import{dirname as ot,isAbsolute as Ja,join as nt,resolve as Va}from"path";import{tmpdir as Xa}from"os";import{spinner as Qa}from"@clack/prompts";import E from"picocolors";import{Buffer as To}from"buffer";async function Ut(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 To.from(n)}async function Ha(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 r=(await n.json()).data?.[0];if(!r)throw new Error("OpenAI image API returned no data");if(r.b64_json)return{bytes:To.from(r.b64_json,"base64"),contentType:"image/png"};if(r.url)return{bytes:await Ut(r.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function za(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 r=(await n.json()).images?.[0];if(!r?.url)throw new Error("fal.ai API returned no image url");return{bytes:await Ut(r.url),contentType:r.content_type??"image/png"}}async function Ya(e,t,n=9e4){let o=Date.now(),r=1e3;for(;Date.now()-o<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,r)),r=Math.min(r*1.5,5e3)}throw new Error("Replicate prediction timed out")}async function qa(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 o=await n.json();if(o.status!=="succeeded"&&o.status!=="failed"&&(o=await Ya(o.id,e.apiKey)),o.status!=="succeeded")throw new Error(`Replicate prediction ${o.status}: ${o.error??""}`);let r=Array.isArray(o.output)?o.output[0]:o.output;if(!r)throw new Error("Replicate prediction returned no output");return{bytes:await Ut(r),contentType:"image/png",providerImageId:o.id}}async function Oo(e,t){switch(e){case"openai":return Ha(t);case"fal":return za(t);case"replicate":return qa(t);default:throw new Error(`Unknown image provider: ${e}`)}}function Za(e){return e==="openai"||e==="fal"||e==="replicate"}async function Le(e={}){let t=process.cwd();if(!e.prompt){c.warn(`Missing --prompt. Example: ${p('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),o=null;if(e.provider){if(!Za(e.provider)){c.warn(`Invalid --provider "${e.provider}". Use one of: openai, fal, replicate.`),process.exitCode=1;return}o=e.provider}else n?.image_provider&&n.image_provider!=="none"?o=n.image_provider:o=tt(t).provider;if(!o||o==="none"){c.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${p("env-check")}\`.`),process.exitCode=1;return}let r=Po(t,o);if(!r){c.warn(`Provider "${o}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=Ja(e.out)?e.out:Va(t,e.out),a=!e.silent&&!!process.stdout.isTTY?Qa():null;a?.start(`Generating image with ${E.bold(o)} ${E.dim(`(${r.envName})`)}\u2026`);try{let l=await Oo(o,{prompt:e.prompt,apiKey:r.key,size:e.size});Dt(ot(i))||Lo(ot(i),{recursive:!0}),jo(i,l.bytes),e.silent||w(a,"success",`Wrote ${i} (${l.bytes.length} bytes, ${l.contentType}).`,E.green(`Wrote ${i} ${E.dim(`(${l.bytes.length} bytes, ${l.contentType})`)}`))}catch(l){a?.stop(E.red("Image generation failed."));let u=tl(t,{provider:o,envName:r.envName,prompt:e.prompt,size:e.size,outPath:i,error:l});c.message(el({provider:o,envName:r.envName,prompt:e.prompt,size:e.size,message:l.message})),u&&c.message(`${E.dim("Full error log:")} ${E.cyan(u)}`),process.exitCode=1}}function el(e){let n=d=>E.dim(d.padEnd(10)),r=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${E.red("\u2717")} ${E.bold(E.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${E.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${E.dim(`"${r}"`)}`}];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:E.red(l)});let u=`${E.bold(E.cyan("SEOAgent"))} ${E.dim("\xB7")} ${E.dim("generate-image")}`;return R(i,{width:70,title:u})}function tl(e,t){let o=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,r=nt(e,S),i=nt(r,".errors"),s=Dt(r)?nt(i,o):nt(Xa(),o),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 Dt(ot(s))||Lo(ot(s),{recursive:!0}),jo(s,a.join(`
389
+ `)}function So(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*Ba(e){let t=0;function*n(o){let r;try{r=Pa(o,{withFileTypes:!0})}catch{return}for(let i of r){if(t>=Na)return;if(i.name.startsWith("."))continue;let s=Ta(o,i.name);if(i.isDirectory()){if(ja.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(!Oa.has(l))continue;t++,yield s}}}yield*n(e)}function _o(e,t){let{pages:n}=ze(e,t),o=[],r=0,i=!1;try{i=wo(e).isDirectory()}catch{i=!1}if(i)for(let s of Ba(e)){let a;try{if(wo(s).size>Fa)continue;a=Ra(s,"utf-8")}catch{continue}r++;for(let l of Ua(a,t))o.push(l)}return Da(n,o,r)}function Te(e={}){let t=process.cwd(),n=D(t);if(!n)return;let o=n.domain&&n.domain!=="unknown"?n.domain:null,r=_o(t,o);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
390
+ `);return}let i=Dt(t,S);Ma(i,{recursive:!0});let s=Dt(i,"internal-links.md");if(Wa(s,xo(r,o),"utf-8"),c.success(`Analyzed ${r.pageCount} page${r.pageCount===1?"":"s"} across ${r.filesScanned} file${r.filesScanned===1?"":"s"}.`),r.orphans.length===0)c.info("No orphan pages \u2014 every page has an inbound internal link.");else{c.warn(`${r.orphans.length} orphan page${r.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of r.orphans.slice(0,10))c.message(` \u2022 ${a.url}`);r.orphans.length>10&&c.message(` \u2026and ${r.orphans.length-10} more`)}c.info(`Report written to ${Dt(S,"internal-links.md")}`)}import{spinner as Ao}from"@clack/prompts";import h from"picocolors";var Io={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function Ga(e){let t=process.cwd(),n=tn(t);if(!n){c.error(`No .seoagent/project.md found. Run \`${p("init")}\` first.`),process.exitCode=1;return}let o=_(t),r=o?.domain&&o.domain!=="unknown"?o.domain:void 0,i=(e.apiBase||b.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?Ao():null;a?.start(`Looking up ${h.bold(`"${e.keyword}"`)} ${h.dim("via DataForSEO (free peek)\u2026")}`);let l;try{l=await ce(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...r?{domain:r}:{}})})}catch(d){w(a,"error",`Network error: ${d.message}`,h.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})+`
391
+ `);return}if(l.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}.`)),c.message(Co()),process.exitCode=1;return}if(!l.ok||!u){w(a,"error",`Peek failed (${l.status})${u?.error?`: ${u.error}`:""}`,h.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.",h.yellow("Real keyword data is temporarily unavailable. Try again later.")),c.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.")),c.message(Ka(u.opportunity)),u.remaining&&c.message(`${h.dim("Peeks remaining today:")} ${h.bold(String(u.remaining.install))} ${h.dim("\u2014 "+Co())}`)}function Ka(e){let n=u=>h.dim(u.padEnd(14)),o=e.volume!=null?h.bold(String(e.volume)):h.dim("n/a"),r=e.difficulty!=null?`${h.bold(String(e.difficulty))} ${h.dim(Ha(e.difficulty))}`:h.dim("n/a"),i=Io[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:")}${o} ${h.dim("/mo")}`},{content:`${n("Difficulty:")}${r}`},{content:`${n("Opportunity:")}${s}`}],l=`${h.bold(h.cyan("Keyword peek"))}`;return R(a,{width:55,title:l})}function Ha(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Co(e=C()){return e?`You're logged in \u2014 run \`${p("keywords")}\` for full enrichment (no quota), or \`${p("keywords --discover")}\` / \`${p("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${p("login")}`}function Eo(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){c.message("Top opportunities:");for(let n of t){let o=n.volume!=null?`vol ${n.volume}`:"vol n/a",r=n.difficulty!=null?`KD ${n.difficulty}`:"KD n/a",i=n.our_position!=null?`, you're #${n.our_position}`:", not ranking";c.message(` \u2022 [${Io[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${o}, ${r}${i}`)}}}function za(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",o=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",r=t.their_position!=null?`#${t.their_position}`:"top 10";c.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${r}, ${n}, ${o}`)}}}async function z(e={}){if(e.peek&&e.peek.trim().length>0){await Ga({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=C();if(!t){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let n=e.apiBase||t.api_base||b.BASE,o=`Bearer ${t.user_token}:${t.website_token}`,r=e.competitors?"competitors":e.discover?"discover":"enrich",i=r==="competitors"?"/api/cli/keywords/competitors":r==="discover"?"/api/cli/keywords/discover":"/api/cli/keywords/enrich",s=r==="competitors"?"Finding keywords your competitors rank for\u2026":r==="discover"?"Discovering new keywords to target\u2026":"Enriching keywords with real volume + difficulty\u2026",l=!!process.stdout.isTTY?Ao():null;l?.start(s);let u;try{u=await ce(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o},body:"{}"})}catch(g){w(l,"error",`Network error: ${g.message}`,h.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"){w(l,"warn",r==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",h.yellow("Paid feature \u2014 upgrade to continue.")),c.message(r==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${h.cyan(b.PRICING)}`:`Upgrade to find new keywords to target: ${h.cyan(b.PRICING)}`),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"){w(l,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,h.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}if(d.skipped==="no-keywords"||d.skipped==="no-seeds"){w(l,"warn","No keywords yet. Run the keyword strategy (Phase 2) first, then try again.",h.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.",h.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.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(d.skipped){w(l,"warn",`Skipped: ${d.skipped}`,h.yellow(`Skipped: ${d.skipped}`));return}if(r==="competitors"){let g=d.gaps??0;w(l,"success",`Found ${g} competitor gap${g===1?"":"s"} across ${d.competitors?.length??0} competitor${d.competitors?.length===1?"":"s"} (added as "suggested").`,h.green(`${g} competitor gap${g===1?"":"s"} found.`)),za(d.topGaps??[]),c.message(`Review them in ${h.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}if(r==="discover"){let g=d.discovered??0;w(l,"success",`Discovered ${g} new keyword${g===1?"":"s"} to target (added as "suggested").`,h.green(`${g} new keyword${g===1?"":"s"} discovered.`)),Eo(d.opportunities??[]),c.message(`Review them in ${h.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}let m=d.enriched??0;w(l,"success",`Enriched ${m} keyword${m===1?"":"s"}.`,h.green(`Enriched ${m} keyword${m===1?"":"s"}.`)),Eo(d.opportunities??[]),d.paid||c.message(`${h.dim("Free plan:")} enriched up to ${h.bold(String(d.cap??25))} keywords. ${h.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${h.cyan(b.PRICING)}`)}import v from"picocolors";import{existsSync as Ya,readFileSync as qa}from"fs";import{join as Ja}from"path";var Po=["openai","fal","replicate"],pe={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Va(e){let t={};if(!Ya(e))return t;let n=qa(e,"utf-8");for(let o of n.split(/\r?\n/)){let r=o.trim();if(!r||r.startsWith("#"))continue;let i=r.indexOf("=");if(i===-1)continue;let s=r.slice(0,i).trim(),a=r.slice(i+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return t}function Ro(e,t){let n={};for(let o of t){let r=process.env[o];r&&r.trim().length>0&&(n[o]={value:r,source:"process"})}for(let o of te){let r=Ja(e,o),i=Va(r);for(let s of t){if(n[s])continue;let a=i[s];a&&a.length>0&&(n[s]={value:a,source:o})}}return{found:n}}function tt(e){let t=[].concat(...Po.map(a=>pe[a])),n=Ro(e,t),o=[];for(let a of Po)pe[a].some(l=>n.found[l])&&o.push(a);if(o.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let r=o[0],i=pe[r].find(a=>n.found[a])??null,s=i?n.found[i].source:null;return{provider:r,matched_key:i,source:s,available_providers:o}}function To(e,t){let n=Ro(e,pe[t]);for(let o of pe[t])if(n.found[o])return{key:n.found[o].value,envName:o};return null}function Oo(){return pe}function Oe(e={}){let t=process.cwd(),n=_(t),o=tt(t);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
392
+ `);return}if(c.message(Xa(o)),!n){c.warn(`No SEOAgent project here. Run \`${p("init")}\` first to persist the provider.`);return}he(t,{image_provider:o.provider}),c.info(`Saved to ${v.cyan(".seoagent/project.md")} ${v.dim(`(image_provider: ${o.provider})`)}`)}function Xa(e){let n=i=>v.dim(i.padEnd(12)),o=[];if(e.provider==="none"){o.push({content:`${v.dim("\u25CB")} ${v.bold(v.yellow("No image provider detected"))}`}),o.push({sep:!0}),o.push({content:v.dim("Set ONE of these to enable image generation:")});let i=Oo();for(let s of Object.keys(i))o.push({content:`${n(s+":")}${v.cyan(i[s].join(" or "))}`});o.push({sep:!0}),o.push({content:v.dim("Add to your shell, .env.local, or .env, then re-run:")}),o.push({content:` ${v.cyan(p("env-check"))}`})}else{o.push({content:`${v.green("\u2713")} ${v.dim("Image provider:")} ${v.bold(v.green(e.provider))}`}),o.push({sep:!0}),e.matched_key&&o.push({content:`${n("Key:")}${v.bold(e.matched_key)}`}),e.source&&o.push({content:`${n("Source:")}${v.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&o.push({content:`${n("Available:")}${v.dim(i.join(", "))}`})}let r=`${v.bold(v.cyan("SEOAgent"))} ${v.dim("\xB7")} ${v.dim("env-check")}`;return R(o,{width:64,title:r})}import{existsSync as Mt,mkdirSync as No,writeFileSync as Fo}from"fs";import{dirname as ot,isAbsolute as nl,join as nt,resolve as ol}from"path";import{tmpdir as rl}from"os";import{spinner as il}from"@clack/prompts";import E from"picocolors";import{Buffer as Lo}from"buffer";async function Bt(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 Lo.from(n)}async function Qa(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 r=(await n.json()).data?.[0];if(!r)throw new Error("OpenAI image API returned no data");if(r.b64_json)return{bytes:Lo.from(r.b64_json,"base64"),contentType:"image/png"};if(r.url)return{bytes:await Bt(r.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function Za(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 r=(await n.json()).images?.[0];if(!r?.url)throw new Error("fal.ai API returned no image url");return{bytes:await Bt(r.url),contentType:r.content_type??"image/png"}}async function el(e,t,n=9e4){let o=Date.now(),r=1e3;for(;Date.now()-o<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,r)),r=Math.min(r*1.5,5e3)}throw new Error("Replicate prediction timed out")}async function tl(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 o=await n.json();if(o.status!=="succeeded"&&o.status!=="failed"&&(o=await el(o.id,e.apiKey)),o.status!=="succeeded")throw new Error(`Replicate prediction ${o.status}: ${o.error??""}`);let r=Array.isArray(o.output)?o.output[0]:o.output;if(!r)throw new Error("Replicate prediction returned no output");return{bytes:await Bt(r),contentType:"image/png",providerImageId:o.id}}async function jo(e,t){switch(e){case"openai":return Qa(t);case"fal":return Za(t);case"replicate":return tl(t);default:throw new Error(`Unknown image provider: ${e}`)}}function sl(e){return e==="openai"||e==="fal"||e==="replicate"}async function Le(e={}){let t=process.cwd();if(!e.prompt){c.warn(`Missing --prompt. Example: ${p('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),o=null;if(e.provider){if(!sl(e.provider)){c.warn(`Invalid --provider "${e.provider}". Use one of: openai, fal, replicate.`),process.exitCode=1;return}o=e.provider}else n?.image_provider&&n.image_provider!=="none"?o=n.image_provider:o=tt(t).provider;if(!o||o==="none"){c.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${p("env-check")}\`.`),process.exitCode=1;return}let r=To(t,o);if(!r){c.warn(`Provider "${o}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=nl(e.out)?e.out:ol(t,e.out),a=!e.silent&&!!process.stdout.isTTY?il():null;a?.start(`Generating image with ${E.bold(o)} ${E.dim(`(${r.envName})`)}\u2026`);try{let l=await jo(o,{prompt:e.prompt,apiKey:r.key,size:e.size});Mt(ot(i))||No(ot(i),{recursive:!0}),Fo(i,l.bytes),e.silent||w(a,"success",`Wrote ${i} (${l.bytes.length} bytes, ${l.contentType}).`,E.green(`Wrote ${i} ${E.dim(`(${l.bytes.length} bytes, ${l.contentType})`)}`))}catch(l){a?.stop(E.red("Image generation failed."));let u=ll(t,{provider:o,envName:r.envName,prompt:e.prompt,size:e.size,outPath:i,error:l});c.message(al({provider:o,envName:r.envName,prompt:e.prompt,size:e.size,message:l.message})),u&&c.message(`${E.dim("Full error log:")} ${E.cyan(u)}`),process.exitCode=1}}function al(e){let n=d=>E.dim(d.padEnd(10)),r=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${E.red("\u2717")} ${E.bold(E.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${E.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${E.dim(`"${r}"`)}`}];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:E.red(l)});let u=`${E.bold(E.cyan("SEOAgent"))} ${E.dim("\xB7")} ${E.dim("generate-image")}`;return R(i,{width:70,title:u})}function ll(e,t){let o=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,r=nt(e,S),i=nt(r,".errors"),s=Mt(r)?nt(i,o):nt(rl(),o),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 Mt(ot(s))||No(ot(s),{recursive:!0}),Fo(s,a.join(`
380
393
  `)),s}catch{return null}}import T from"picocolors";async function je(e={}){let t=C();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
381
394
  `):c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||b.BASE).replace(/\/$/,""),o=`Bearer ${t.user_token}:${t.website_token}`,r;try{r=await fetch(`${n}/api/cli/whoami`,{method:"GET",headers:{Authorization:o,Accept:"application/json"}})}catch(s){c.error(`Network error: ${s.message}`),process.exitCode=1;return}if(r.status===404){if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,server_supports_whoami:!1,api_base:n})}
382
395
  `);return}c.warn(`Logged in, but the server at this API base does not support \`/api/cli/whoami\` yet. Update with \`${p("update-cli")}\` (or re-deploy your server).`),c.message(`API base: ${n}`);return}let i=null;try{i=await r.json()}catch{i=null}if(!r.ok||!i||i.status!=="ok"){e.json?process.stdout.write(`${JSON.stringify({logged_in:!0,error:i?.error??`HTTP ${r.status}`})}
383
396
  `):c.error(`Could not fetch your account (HTTP ${r.status})${i?.error?`: ${i.error}`:""}`),process.exitCode=1;return}if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,...i},null,2)}
384
- `);return}c.message(nl(i)),i.paid===!1&&c.message(`${T.dim("Upgrade for autopilot:")} ${T.cyan(b.PRICING)}`)}function nl(e){let n=i=>T.dim(i.padEnd(10)),o=[];if(e.email&&(o.push({content:`${T.green("\u2713")} ${T.dim("Logged in as")} ${T.bold(e.email)}`}),o.push({sep:!0})),e.domain&&o.push({content:`${n("Website:")}${T.cyan(e.domain)}`}),e.plan){let i=e.paid?T.bold(T.green(e.plan)):T.bold(e.plan);o.push({content:`${n("Plan:")}${i}`})}e.api_base&&o.push({content:`${n("API:")}${T.dim(e.api_base)}`});let r=`${T.bold(T.cyan("SEOAgent"))} ${T.dim("\xB7")} ${T.dim("whoami")}`;return R(o,{width:55,title:r})}import{select as Mt,text as Ne,confirm as Uo,isCancel as M,intro as ol,outro as rl}from"@clack/prompts";import rt from"picocolors";function il(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>ve()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await U()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await be()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await Ae()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await je()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await Mt({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(!M(e))if(e==="peek"){let t=await Ne({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(M(t))return;await H({peek:String(t)})}else e==="discover"?await H({discover:!0}):e==="competitors"?await H({competitors:!0}):await H()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>Te({})},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Ne({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(M(e))return;let t=await Ne({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});M(t)||await Le({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Oe({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await Mt({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"}]});M(e)||await Re(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await Q()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Ne({message:"Action ID to close out:",placeholder:"action-abc123",validate:o=>String(o??"").trim()?void 0:"Action ID is required."});if(M(e))return;let t=await Uo({message:"Mark as failed instead of completed?",initialValue:!1});if(M(t))return;let n;if(t===!0){let o=await Ne({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(M(o))return;String(o).trim()&&(n=String(o))}await Z(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 Ce()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest",run:async()=>await Ee({})},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>Ie()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await $e({})}]}var No="__exit__";async function Fo(e=il()){let t=e.map(r=>({value:r.command,label:r.label,hint:r.hint}));t.push({value:No,label:"Exit",hint:"Close the menu"});let n=await Mt({message:"What would you like to do?",options:t});if(M(n)||n===No)return!0;let o=e.find(r=>r.command===n);if(!o)return c.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await o.run()}catch(r){c.error(`\`${o.command}\` failed: ${r.message??String(r)}`)}return!1}async function Bt(){if(!process.stdin.isTTY){c.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}ol(`${rt.bold(rt.cyan("SEOAgent"))} ${rt.dim("\xB7 menu")}`);let e=await Fo();for(;!e;){let t=await Uo({message:"Do another?",initialValue:!0});if(M(t)||t===!1){e=!0;break}e=await Fo()}rl(rt.dim("See you next time."))}var $=new sl;$.name("seoagent").description("AI SEO agent for Claude Code").version(oe).showSuggestionAfterError(!0).showHelpAfterError(!0);$.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").action(e=>{be({yes:e.yes,domain:e.domain,siteType:e.siteType})});$.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=>{$e({yes:e.yes,global:e.global})});$.command("status").description("Show current SEO project state").action(ve);$.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=>{Ae({apiBase:e.apiBase})});$.command("logout").description("Remove stored credentials for seoagent.com").action(Ie);$.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=>{U({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});$.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=>{Q({force:e.force,silent:e.silent,print:e.print})});$.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)=>{Z(e,{failed:t.failed,reason:t.reason})});$.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{Tt({json:e.json})});$.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=>{jt({yes:e.yes,model:e.model})});$.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)=>{Re(e,{apiBase:t.apiBase})});$.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("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{H({peek:e.peek,discover:e.discover,competitors:e.competitors,json:e.json,apiBase:e.apiBase})});$.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=>{Te({json:e.json})});$.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{Oe({json:e.json})});$.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=>{Le({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});$.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=>{je({json:e.json,apiBase:e.apiBase})});$.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(Ce);$.command("update-cli").description("Update the SEOAgent CLI to the latest published npm version").option("--dry-run","Show what would happen without running the install").action(e=>{Ee({dryRun:e.dryRun})});$.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Bt()});process.argv.length===2&&($.outputHelp(),process.exit(0));$.parse();
397
+ `);return}c.message(cl(i)),i.paid===!1&&c.message(`${T.dim("Upgrade for autopilot:")} ${T.cyan(b.PRICING)}`)}function cl(e){let n=i=>T.dim(i.padEnd(10)),o=[];if(e.email&&(o.push({content:`${T.green("\u2713")} ${T.dim("Logged in as")} ${T.bold(e.email)}`}),o.push({sep:!0})),e.domain&&o.push({content:`${n("Website:")}${T.cyan(e.domain)}`}),e.plan){let i=e.paid?T.bold(T.green(e.plan)):T.bold(e.plan);o.push({content:`${n("Plan:")}${i}`})}e.api_base&&o.push({content:`${n("API:")}${T.dim(e.api_base)}`});let r=`${T.bold(T.cyan("SEOAgent"))} ${T.dim("\xB7")} ${T.dim("whoami")}`;return R(o,{width:55,title:r})}import{select as Wt,text as Ne,confirm as Bo,isCancel as M,intro as ul,outro as dl}from"@clack/prompts";import rt from"picocolors";function pl(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>ve()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await U()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await be()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await Ae()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await je()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await Wt({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(!M(e))if(e==="peek"){let t=await Ne({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(M(t))return;await z({peek:String(t)})}else e==="discover"?await z({discover:!0}):e==="competitors"?await z({competitors:!0}):await z()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>Te({})},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Ne({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(M(e))return;let t=await Ne({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});M(t)||await Le({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Oe({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await Wt({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"}]});M(e)||await Re(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await Z()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Ne({message:"Action ID to close out:",placeholder:"action-abc123",validate:o=>String(o??"").trim()?void 0:"Action ID is required."});if(M(e))return;let t=await Bo({message:"Mark as failed instead of completed?",initialValue:!1});if(M(t))return;let n;if(t===!0){let o=await Ne({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(M(o))return;String(o).trim()&&(n=String(o))}await ee(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 Ce()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest",run:async()=>await Ee({})},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>Ie()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await $e({})}]}var Uo="__exit__";async function Do(e=pl()){let t=e.map(r=>({value:r.command,label:r.label,hint:r.hint}));t.push({value:Uo,label:"Exit",hint:"Close the menu"});let n=await Wt({message:"What would you like to do?",options:t});if(M(n)||n===Uo)return!0;let o=e.find(r=>r.command===n);if(!o)return c.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await o.run()}catch(r){c.error(`\`${o.command}\` failed: ${r.message??String(r)}`)}return!1}async function Gt(){if(!process.stdin.isTTY){c.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}ul(`${rt.bold(rt.cyan("SEOAgent"))} ${rt.dim("\xB7 menu")}`);let e=await Do();for(;!e;){let t=await Bo({message:"Do another?",initialValue:!0});if(M(t)||t===!1){e=!0;break}e=await Do()}dl(rt.dim("See you next time."))}var $=new ml;$.name("seoagent").description("AI SEO agent for Claude Code").version(oe).showSuggestionAfterError(!0).showHelpAfterError(!0);$.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").action(e=>{be({yes:e.yes,domain:e.domain,siteType:e.siteType})});$.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=>{$e({yes:e.yes,global:e.global})});$.command("status").description("Show current SEO project state").action(ve);$.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=>{Ae({apiBase:e.apiBase})});$.command("logout").description("Remove stored credentials for seoagent.com").action(Ie);$.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=>{U({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});$.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=>{Z({force:e.force,silent:e.silent,print:e.print})});$.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)=>{ee(e,{failed:t.failed,reason:t.reason})});$.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{Tt({json:e.json})});$.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=>{Ft({yes:e.yes,model:e.model})});$.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)=>{Re(e,{apiBase:t.apiBase})});$.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("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{z({peek:e.peek,discover:e.discover,competitors:e.competitors,json:e.json,apiBase:e.apiBase})});$.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=>{Te({json:e.json})});$.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{Oe({json:e.json})});$.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=>{Le({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});$.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=>{je({json:e.json,apiBase:e.apiBase})});$.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(Ce);$.command("update-cli").description("Update the SEOAgent CLI to the latest published npm version").option("--dry-run","Show what would happen without running the install").action(e=>{Ee({dryRun:e.dryRun})});$.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Gt()});process.argv.length===2&&($.outputHelp(),process.exit(0));$.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seoagent-official/seoagent",
3
- "version": "1.46.1",
3
+ "version": "1.47.0",
4
4
  "description": "Scaffolder for Claude Code's SEOAgent skill. Run once: `npx -y @seoagent-official/seoagent init`. Sets up .seoagent/ for persistent audits, keyword strategy, content planning, and optimized writing. Not a runtime dependency.",
5
5
  "type": "module",
6
6
  "bin": {