@seoagent-official/seoagent 1.39.0 → 1.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +37 -36
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as
|
|
2
|
+
import{Command as Ds}from"commander";import{dirname as lr,relative as ur}from"path";import{intro as dr,outro as pr,text as tn,select as He,spinner as fr,isCancel as q,cancel as V,confirm as mr}from"@clack/prompts";function Te(e=process.argv[1]){return e?(e.split(/[/\\]/).pop()??"").replace(/\.(cmd|ps1|exe)$/i,"").toLowerCase()==="seoagent":!1}function f(e,t=Te()){return t?`seoagent ${e}`:`npx -y @seoagent-official/seoagent ${e}`}import{randomUUID as mo}from"crypto";import{existsSync as _t,mkdirSync as Et,readFileSync as go,writeFileSync as Ct}from"fs";import{join as Ne}from"path";var W=[".env.local",".env.production",".env"],$t=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];import{homedir as to}from"os";import{join as de}from"path";var b=".seoagent",bt=["audit","strategy/clusters","briefs","content","content/images","performance"],K={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},pe=".claude/settings.json",St=".pull-receipt.json",vt=`# SEOAgent local files
|
|
3
3
|
.legacy/
|
|
4
4
|
content/images/*
|
|
5
5
|
!content/images/.gitkeep
|
|
6
6
|
.pull-receipt.json
|
|
7
|
-
`,
|
|
8
|
-
`)}}function
|
|
7
|
+
`,no=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:de(to(),".config"),R=de(no,"seoagent"),N=de(R,"auth.json"),Oe=de(R,"state");var ee="https://seoagent.com",z=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):ee,k={BASE:z,PRICING:`${z}/pricing`,LEAD_API:`${z}/api/cli/lead`,CLI_AUTH_PAGE:`${z}/cli/auth`,CLI_AUTH_POLL:`${z}/api/cli/auth/poll`,CLI_SYNC:`${z}/api/cli/sync`};import{readFileSync as oo}from"fs";import{fileURLToPath as ro}from"url";import{dirname as io,join as so}from"path";var xt="0.0.0";function ao(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return xt}function co(e=t=>oo(t,"utf-8")){try{let t=io(ro(import.meta.url));return ao(e(so(t,"package.json")))}catch{return xt}}var H=co();import{existsSync as lo,readFileSync as uo}from"fs";var fe="---";function po(e){let t=e.trim();return t===""?"":t==="null"||t==="~"?null:t==="true"?!0:t==="false"?!1:t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):/^-?\d+$/.test(t)||/^-?\d+\.\d+$/.test(t)?Number(t):t}function Le(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==fe)return{data:{},body:e};let n={},o=1;for(;o<t.length;o++){if(t[o].trim()===fe){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]=po(a))}return{data:n,body:t.slice(o).join(`
|
|
8
|
+
`)}}function me(e){if(!lo(e))return null;try{return Le(uo(e,"utf-8"))}catch{return null}}function fo(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 je(e,t=""){let n=[fe];for(let[r,i]of Object.entries(e))i!==void 0&&n.push(`${r}: ${fo(i)}`);n.push(fe);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
|
|
14
|
-
`)}function
|
|
15
|
-
`,"utf-8"),{file:t,added:!1}):(r.hooks.push({type:"command",command:
|
|
16
|
-
`,"utf-8"),{file:t,added:!0})}function
|
|
17
|
-
`,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{readFileSync as
|
|
18
|
-
`)}var Co="context.md";function Ao(e,t){let n=Eo(e,".seoagent",Co),o=Dt(t);_o(n,o,"utf-8")}function Bt(e,t){Ao(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as ne,readFileSync as Mt,readdirSync as Io,statSync as Gt}from"fs";import{join as F}from"path";var Po=[{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 Ro(e){let t=F(e,"package.json");if(!ne(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Mt(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function To(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 Oo(e){let t={};for(let n of M){let o=F(e,n);if(ne(o))try{let r=Mt(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 c=s.slice(0,a).trim();c&&!(c in t)&&(t[c]=n)}}catch{}}return t}function jo(e,t){let n=F(e,t.replace(/\/$/,""));if(!ne(n))return!1;if(t.endsWith("/"))try{return Gt(n).isDirectory()}catch{return!1}return!0}function Lo(e){let t=["content","_posts","posts",F("src","content")];for(let n of t){let o=F(e,n);if(ne(o))try{if(!Gt(o).isDirectory())continue;let r=[o],i=0;for(;r.length>0&&i<50;){let s=r.pop();for(let a of Io(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&r.length<5){r.push(F(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 No(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(ne(F(e,n.marker)))return n.path;return null}function Wt(e){let t=[],{deps:n}=Ro(e),o=Oo(e),r="none";for(let s of Po){let a=[];for(let c of Object.keys(n))if(To(c,s.deps)){a.push({type:"dep",detail:c,source:"package.json"});break}for(let c of s.envKeys)if(o[c]){a.push({type:"env",detail:c,source:o[c]});break}for(let c of s.fsMarkers)if(jo(e,c)){let d=c.endsWith("/")?"directory":"file";a.push({type:d,detail:c,source:c});break}if(a.length>0){r=s.cms,t.push(...a);break}}if(r==="none"){let s=Lo(e);s&&(r="mdx-local",t.push(s))}let i=No(e);return{cms:r,blog_path:i,evidence:t}}import{existsSync as U,readFileSync as Ue}from"fs";import{join as D}from"path";function Kt(e){try{return new URL(e).hostname}catch{return e}}function Ht(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 Fo(e){for(let t of M){let n=D(e,t);if(!U(n))continue;let o=Ue(n,"utf-8");for(let r of ht){let i=o.match(new RegExp(`^${r}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Kt(s);if(Ht(a))continue;return{value:a,source:`${t} (${r})`}}}}return null}function Uo(e){let t=D(e,"package.json");if(!U(t))return null;try{let n=JSON.parse(Ue(t,"utf-8"));if(!n.homepage)return null;let o=Kt(n.homepage);return Ht(o)?null:{value:o,source:"package.json (homepage)"}}catch{return null}}function zt(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),U(D(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=Fo(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=Uo(e);a&&(o=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=D(e,"package.json"),s=null;if(U(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Ue(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),d=(...u)=>u.some(p=>c.includes(p));if(d("@shopify/hydrogen","@shopify/polaris")||U(D(e,"shopify.config.js"))||U(D(e,"shopify.config.ts"))){s="product";let u=d("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":U(D(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:u})}else{let u=d("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=d("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),g=d("next");u&&(g||p)?(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"})):!u&&d("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:d("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 Do,readFileSync as Bo,readdirSync as Mo,statSync as Go}from"fs";import{join as B,sep as Wo}from"path";var Yt=["tsx","jsx","js","mdx","md"],Ko=["astro","md","mdx"],Ho=5e3;function we(e,t){let n=new Map,o=0,r=(i,s,a=!1)=>{let c=zo(i);if(c===null){o++;return}let d=n.get(c);if(d){d.in_sitemap=d.in_sitemap||a,d.source.includes(s)||(d.source+=`, ${s}`);return}n.set(c,{route:c,url:tr(t,c),in_sitemap:a,source:s})};for(let i of["app",B("src","app")]){let s=B(e,i);if(De(s))for(let a of Be(s)){let c=Me(s,a),d=c[c.length-1];Xo(d)&&(c.some(u=>u.startsWith("@"))||r(Yo(c.slice(0,-1)),"app router"))}}for(let i of["pages",B("src","pages")]){let s=B(e,i);if(De(s))for(let a of Be(s)){let c=Me(s,a);if(c[0]==="api")continue;let d=c[c.length-1],u=Ge(d),p=Yt.includes(u),g=Ko.includes(u);if(!p&&!g)continue;let E=ke(d);Qo(E)||r(Jo(c),g?"astro":"pages router")}}for(let i of[".","public"]){let s=B(e,i);if(De(s))for(let a of Be(s,i==="."?1:1/0)){let c=Me(s,a),d=c[c.length-1];Ge(d)==="html"&&(c.some(u=>u==="node_modules"||u.startsWith("."))||r(qo(c),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=B(e,...i.split("/"));if(Do(s)){for(let a of Zo(s)){let c=Vo(a);c!==null&&r(c,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:o}}function zo(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function Yo(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function Jo(e){let t=[...e],n=ke(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function qo(e){let t=[...e],n=ke(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Vo(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function Xo(e){return ke(e)==="page"&&Yt.includes(Ge(e))}function Qo(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Zo(e){try{let t=Bo(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 er=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function De(e){try{return Go(e).isDirectory()}catch{return!1}}function*Be(e,t=1/0){let n=0;function*o(r,i){if(i>t)return;let s;try{s=Mo(r,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=Ho)return;if(a.name.startsWith("."))continue;let c=B(r,a.name);if(a.isDirectory()){if(er.has(a.name))continue;yield*o(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*o(e,1)}function Me(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(Wo).filter(Boolean)}function Ge(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function ke(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function tr(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as nr,writeFileSync as or}from"fs";import{join as Jt}from"path";function Vt(e,t){if(t.length===0)return;let n=Jt(e,b);nr(n,{recursive:!0});let o=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
|
|
13
|
+
`)}var ho=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fe(){return mo()}var yo=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),wo="project.md";function te(e){return Ne(e,b)}function ge(e){return Ne(te(e),wo)}function At(e){return _t(ge(e))}function $(e){let t=me(ge(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&&yo.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&&ho.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 Pt(e){let t=$(e);if(!t)return null;if(t.install_id)return t.install_id;let n=Fe();return ne(e,{install_id:n}),n}function ko(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 $o(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 It(e,t){let n=te(e);Et(n,{recursive:!0});let o=je($o(t),ko(t));Ct(ge(e),o,"utf-8")}function ne(e,t){let n=ge(e);if(!_t(n))return!1;let o=Le(go(n,"utf-8")),r={...o.data,...t};return Ct(n,je(r,o.body),"utf-8"),!0}function Rt(e){let t=te(e);for(let n of bt)Et(Ne(t,n),{recursive:!0})}import{existsSync as he,mkdirSync as ye,writeFileSync as Tt,readFileSync as Ot,readdirSync as bo,statSync as So}from"fs";import{join as O,dirname as Lt,relative as vo}from"path";import{fileURLToPath as xo}from"url";var _o=Lt(xo(import.meta.url));function jt(){return O(_o,"skills")}function Eo(){let e=O(jt(),"seoagent.md");if(he(e))return Ot(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function Nt(e,t){let n=[];if(!he(e))return n;for(let o of bo(e,{withFileTypes:!0})){let r=O(e,o.name),i=O(t,o.name);o.isDirectory()?(ye(i,{recursive:!0}),n.push(...Nt(r,i))):o.isFile()&&(ye(Lt(i),{recursive:!0}),Tt(i,Ot(r)),n.push(i))}return n}function Ft(e,t){return Co(e,t).skillFile}function Co(e,t){let n=he(O(e,".agents")),o=O(e,n?K.AGENTS:K.CLAUDE),r=O(o,"SKILL.md");ye(o,{recursive:!0}),Tt(r,t??Eo(),"utf-8");let i=O(jt(),"references"),s=O(o,"references"),a=[];try{he(i)&&So(i).isDirectory()&&(ye(s,{recursive:!0}),a=Nt(i,s).map(c=>vo(o,c)))}catch{}return{skillFile:r,referenceFiles:a}}import{existsSync as we,mkdirSync as Ue,readFileSync as Ao,writeFileSync as oe}from"fs";import{dirname as Ut,join as Y}from"path";var Po="npx -y @seoagent-official/seoagent sync --silent";function Dt(e){let t=Y(e,b);Ue(t,{recursive:!0});let n=Y(t,".gitignore");oe(n,vt,"utf-8");let o=Y(t,"content","images",".gitkeep");return Ue(Ut(o),{recursive:!0}),we(o)||oe(o,"","utf-8"),n}function De(e){if(!we(e))return{};try{let t=Ao(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Be(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function Bt(e){let t=Y(e,pe);Ue(Ut(t),{recursive:!0});let n=De(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(Be)?(oe(t,JSON.stringify(n,null,2)+`
|
|
15
|
+
`,"utf-8"),{file:t,added:!1}):(r.hooks.push({type:"command",command:Po}),oe(t,JSON.stringify(n,null,2)+`
|
|
16
|
+
`,"utf-8"),{file:t,added:!0})}function Mt(e){let t=Y(e,pe);if(!we(t))return!1;let n=De(t).hooks?.PostToolUse;return Array.isArray(n)?n.some(o=>o.hooks?.some(Be)):!1}function Gt(e){let t=Y(e,pe);if(!we(t))return{file:t,removed:!1};let n=De(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=>!Be(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,oe(t,JSON.stringify(n,null,2)+`
|
|
17
|
+
`,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{readFileSync as va,writeFileSync as Io,existsSync as xa}from"fs";import{join as Ro}from"path";function Wt(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 To="context.md";function Oo(e,t){let n=Ro(e,".seoagent",To),o=Wt(t);Io(n,o,"utf-8")}function Kt(e,t){Oo(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as re,readFileSync as zt,readdirSync as Lo,statSync as Ht}from"fs";import{join as D}from"path";var jo=[{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 No(e){let t=D(e,"package.json");if(!re(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(zt(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Fo(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 Uo(e){let t={};for(let n of W){let o=D(e,n);if(re(o))try{let r=zt(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 c=s.slice(0,a).trim();c&&!(c in t)&&(t[c]=n)}}catch{}}return t}function Do(e,t){let n=D(e,t.replace(/\/$/,""));if(!re(n))return!1;if(t.endsWith("/"))try{return Ht(n).isDirectory()}catch{return!1}return!0}function Bo(e){let t=["content","_posts","posts",D("src","content")];for(let n of t){let o=D(e,n);if(re(o))try{if(!Ht(o).isDirectory())continue;let r=[o],i=0;for(;r.length>0&&i<50;){let s=r.pop();for(let a of Lo(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&r.length<5){r.push(D(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 Mo(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(re(D(e,n.marker)))return n.path;return null}function Yt(e){let t=[],{deps:n}=No(e),o=Uo(e),r="none";for(let s of jo){let a=[];for(let c of Object.keys(n))if(Fo(c,s.deps)){a.push({type:"dep",detail:c,source:"package.json"});break}for(let c of s.envKeys)if(o[c]){a.push({type:"env",detail:c,source:o[c]});break}for(let c of s.fsMarkers)if(Do(e,c)){let d=c.endsWith("/")?"directory":"file";a.push({type:d,detail:c,source:c});break}if(a.length>0){r=s.cms,t.push(...a);break}}if(r==="none"){let s=Bo(e);s&&(r="mdx-local",t.push(s))}let i=Mo(e);return{cms:r,blog_path:i,evidence:t}}import{existsSync as B,readFileSync as Me}from"fs";import{join as M}from"path";function Jt(e){try{return new URL(e).hostname}catch{return e}}function qt(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 Go(e){for(let t of W){let n=M(e,t);if(!B(n))continue;let o=Me(n,"utf-8");for(let r of $t){let i=o.match(new RegExp(`^${r}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Jt(s);if(qt(a))continue;return{value:a,source:`${t} (${r})`}}}}return null}function Wo(e){let t=M(e,"package.json");if(!B(t))return null;try{let n=JSON.parse(Me(t,"utf-8"));if(!n.homepage)return null;let o=Jt(n.homepage);return qt(o)?null:{value:o,source:"package.json (homepage)"}}catch{return null}}function Vt(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),B(M(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=Go(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=Wo(e);a&&(o=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=M(e,"package.json"),s=null;if(B(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Me(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),d=(...u)=>u.some(p=>c.includes(p));if(d("@shopify/hydrogen","@shopify/polaris")||B(M(e,"shopify.config.js"))||B(M(e,"shopify.config.ts"))){s="product";let u=d("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":B(M(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:u})}else{let u=d("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=d("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),g=d("next");u&&(g||p)?(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"})):!u&&d("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:d("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 Ko,readFileSync as zo,readdirSync as Ho,statSync as Yo}from"fs";import{join as G,sep as Jo}from"path";var Xt=["tsx","jsx","js","mdx","md"],qo=["astro","md","mdx"],Vo=5e3;function ke(e,t){let n=new Map,o=0,r=(i,s,a=!1)=>{let c=Xo(i);if(c===null){o++;return}let d=n.get(c);if(d){d.in_sitemap=d.in_sitemap||a,d.source.includes(s)||(d.source+=`, ${s}`);return}n.set(c,{route:c,url:sr(t,c),in_sitemap:a,source:s})};for(let i of["app",G("src","app")]){let s=G(e,i);if(Ge(s))for(let a of We(s)){let c=Ke(s,a),d=c[c.length-1];nr(d)&&(c.some(u=>u.startsWith("@"))||r(Qo(c.slice(0,-1)),"app router"))}}for(let i of["pages",G("src","pages")]){let s=G(e,i);if(Ge(s))for(let a of We(s)){let c=Ke(s,a);if(c[0]==="api")continue;let d=c[c.length-1],u=ze(d),p=Xt.includes(u),g=qo.includes(u);if(!p&&!g)continue;let A=$e(d);or(A)||r(Zo(c),g?"astro":"pages router")}}for(let i of[".","public"]){let s=G(e,i);if(Ge(s))for(let a of We(s,i==="."?1:1/0)){let c=Ke(s,a),d=c[c.length-1];ze(d)==="html"&&(c.some(u=>u==="node_modules"||u.startsWith("."))||r(er(c),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=G(e,...i.split("/"));if(Ko(s)){for(let a of rr(s)){let c=tr(a);c!==null&&r(c,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:o}}function Xo(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function Qo(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function Zo(e){let t=[...e],n=$e(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function er(e){let t=[...e],n=$e(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function tr(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function nr(e){return $e(e)==="page"&&Xt.includes(ze(e))}function or(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function rr(e){try{let t=zo(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 ir=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Ge(e){try{return Yo(e).isDirectory()}catch{return!1}}function*We(e,t=1/0){let n=0;function*o(r,i){if(i>t)return;let s;try{s=Ho(r,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=Vo)return;if(a.name.startsWith("."))continue;let c=G(r,a.name);if(a.isDirectory()){if(ir.has(a.name))continue;yield*o(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*o(e,1)}function Ke(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(Jo).filter(Boolean)}function ze(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function $e(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function sr(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as ar,writeFileSync as cr}from"fs";import{join as Qt}from"path";function en(e,t){if(t.length===0)return;let n=Qt(e,b);ar(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(d=>`| ${
|
|
21
|
-
`);
|
|
22
|
-
`))}import{existsSync as
|
|
23
|
-
`);if(!o){
|
|
24
|
-
${r}`);let s=await
|
|
20
|
+
`),i="| URL | In sitemap | In nav | Status | Rendered | Notes |",s="|---|---|---|---|---|---|",a=t.map(d=>`| ${Zt(d.url)} | ${d.in_sitemap?"yes":"no"} | \u2014 | \u2014 | \u2014 | ${Zt(d.source)} |`),c=[o,"",r,"",i,s,...a,""].join(`
|
|
21
|
+
`);cr(Qt(n,"pages.md"),c,"utf-8")}function Zt(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as J}from"@clack/prompts";var l={info:e=>J.info(e),warn:e=>J.warn(e),error:e=>J.error(e),success:e=>J.success(e),step:e=>J.step(e),message:e=>J.message(e)};function y(e,t,n,o=n){e?e.stop(o):l[t](n)}var nn=[{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"}],rn="unknown",gr=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function hr(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 be(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return gr.has(t)?t:null}async function Ye(e={}){let t=process.cwd();if(At(t)){l.warn("SEOAgent project already exists in this directory."),l.info(`Run \`${f("status")}\` to see your project state.`),l.info(`To start fresh, run \`${f("uninstall")}\` then init again.`);return}let n=!!e.yes||!process.stdin.isTTY;n||dr("SEOAgent \u2014 AI SEO Agent");let o=Vt(t,a=>l.step(a)),r=()=>{if(o.evidence.length!==0){l.info("Inferred from your project:");for(let a of o.evidence)l.info(` \u2022 ${hr(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||o.domain||null,s=be(e.siteType)||be(process.env.SEOAGENT_SITE_TYPE)||o.siteType||null;if(n){e.siteType?.trim()&&be(e.siteType)===null&&(l.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&be(process.env.SEOAGENT_SITE_TYPE)===null&&(l.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),r(),i||(l.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=rn),s||(s="unknown"),await on(t,i,s);return}if(r(),!i){let a=await tn({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});q(a)&&(V("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await He({message:"What kind of site is this?",options:[...nn]});q(a)&&(V("Cancelled"),process.exit(0)),s=a}for(;;){let a=await mr({message:`Create .seoagent for ${i} (${s})?`});if(q(a)&&(V("Cancelled"),process.exit(0)),a)break;let c=await He({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((q(c)||c==="abort")&&(V("Cancelled"),process.exit(0)),c==="domain"){let d=await tn({message:"Website domain",placeholder:"example.com",validate:u=>u.trim()?void 0:"Domain is required"});q(d)&&(V("Cancelled"),process.exit(0)),i=String(d)}else{let d=await He({message:"What kind of site is this?",options:[...nn]});q(d)&&(V("Cancelled"),process.exit(0)),s=d}}await on(t,i,s)}async function on(e,t,n){let o=fr();o.start("Setting up your SEO project");let r=Yt(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:H,install_id:Fe(),...r.cms!=="none"?{cms:r.cms}:{},...r.blog_path?{blog_path:r.blog_path}:{}};Rt(e),It(e,i),Kt(e,n),Dt(e);let s=Ft(e),a=ur(e,s),d=`${lr(a)}/references/audit-checks.md`;Bt(e);let u=t!==rn,p={pages:[],dynamicCount:0};try{p=ke(e,u?t:null),en(e,p.pages)}catch{}if(o.stop(u?`Created .seoagent/ project for ${i.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),r.cms!=="none"){let T=r.evidence.map(L=>`${L.detail} (${L.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${r.cms} \u2014 ${T}`)}r.blog_path&&l.info(`Blog route: ${r.blog_path}`),p.pages.length>0&&l.info(`Found ${p.pages.length} page${p.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`+(p.dynamicCount>0?` (plus ${p.dynamicCount} dynamic route template${p.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""));let g=u?i.domain:"your site",A=u?[" 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."];pr([u?`\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):","",...A,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${g}`," (homepage + sitemap + robots.txt; the checks live in",` ${d} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${f("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${a} is picked up automatically.`,""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
|
|
22
|
+
`))}import{existsSync as cn}from"fs";import{intro as wr,outro as kr,confirm as $r,isCancel as br,cancel as Sr}from"@clack/prompts";import{existsSync as Se,rmSync as yr}from"fs";import{join as ve}from"path";function sn(e,t={}){let n=[],o=ve(e,b);Se(o)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:o,kind:"dir"});let r=ve(e,K.CLAUDE);Se(r)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:r,kind:"dir"});let i=ve(e,K.AGENTS);return Se(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),Mt(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:ve(e,".claude","settings.json"),kind:"hook"}),t.global&&Se(R)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:R,kind:"global"}),n}function an(e,t){for(let n of t)n.kind==="hook"?Gt(e):yr(n.path,{recursive:!0,force:!0})}async function Je(e={}){let t=process.cwd(),n=sn(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&cn(R)&&l.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){wr("SEOAgent \u2014 uninstall"),l.message(`This will remove:
|
|
24
|
+
${r}`);let s=await $r({message:"Remove these and start fresh?"});if(br(s)||!s){Sr("Cancelled \u2014 nothing was removed.");return}}an(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
|
|
25
25
|
`);o?l.success(`Removed:
|
|
26
|
-
${i}`):
|
|
27
|
-
${i}`),!e.global&&
|
|
28
|
-
`,"utf-8");try{
|
|
29
|
-
`)}function Tr(e,t){if(!t)return L.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=dn(t),o=e-5-n;return o<1?L.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${L.dim("\u250C\u2500 ")}${t}${L.dim(` ${"\u2500".repeat(o)}\u2510`)}`}function Or(e,t){let n=dn(e),o;return n<=t?o=e+" ".repeat(t-n):o=e,`${L.dim("\u2502")} ${o} ${L.dim("\u2502")}`}function Ye(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 Je(){let e=un(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(jr(e))}function jr(e){if(!e)return"";let t=11,n=s=>w.dim(s.padEnd(t)),o=[];S()?(o.push({content:`${w.green("\u2713")} ${w.dim("Logged in")}`}),o.push({content:w.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(o.push({content:`${w.dim("\u25CB Not logged in")}`}),o.push({content:w.dim(` Run \`${f("login")}\` to connect.`)})),o.push({sep:!0}),o.push({content:e.audit?.exists?`${n("Audit:")}${w.green(`last run ${Ye(e.audit.date??"")}`)} ${w.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${w.dim("not yet run")}`}),o.push({content:e.strategy?.exists?`${n("Strategy:")}${w.bold(w.cyan(String(e.strategy.clusterCount??0)))} ${w.dim("clusters")} \xB7 ${w.bold(w.cyan(String(e.strategy.articleCount??0)))} ${w.dim("ideas")}`:`${n("Strategy:")}${w.dim("not yet created")}`}),o.push({content:e.briefs?.exists?`${n("Briefs:")}${w.bold(w.cyan(String(e.briefs.count??0)))} ${w.dim("ready")}`:`${n("Briefs:")}${w.dim("none created")}`}),o.push({content:e.content?.exists?`${n("Content:")}${w.green("\u2713")} ${w.bold(w.cyan(String(e.content.count??0)))} ${w.dim("articles written")}`:`${n("Content:")}${w.dim("no articles yet")}`}),o.push({content:e.roadmap?.exists?`${n("Roadmap:")}${w.green("updated")} ${w.dim(Ye(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${w.dim("not yet created")}`});let i=`${w.bold(w.cyan("SEOAgent"))} ${w.dim("\xB7")} ${w.bold(e.domain)}`;return A(o,{width:78,title:i})}import{exec as Lr,spawn as Nr}from"child_process";import{confirm as Fr,isCancel as Ur}from"@clack/prompts";import _ from"picocolors";var Dr="https://registry.npmjs.org/@seoagent-official/seoagent/latest",re="@seoagent-official/seoagent",ie=["free","starter","pro","scale","enterprise"],ve={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function Br(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return ie.includes(t)?t:null}function Mr(e){let t=ie.indexOf(e);return t===-1||t===ie.length-1?null:ie[t+1]}async function Gr(e,t=fetch){if(!e)return null;try{let n=(e.api_base||k.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 Wr(e){let t=[],o=s=>_.dim(s.padEnd(10)),r=!1;e.email&&(t.push({content:`${o("Email:")}${_.bold(e.email)}`}),r=!0),e.domain&&(t.push({content:`${o("Website:")}${_.cyan(e.domain)}`}),r=!0),r&&t.push({sep:!0});for(let s of ie){let a=ve[s];s===e.current?t.push({content:`${_.bold(_.green("\u25CF"))} ${_.bold(_.green(a.padEnd(11)))} ${_.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${_.yellow("\u25C6")} ${_.bold(_.yellow(a.padEnd(11)))} ${_.yellow("next tier")}`}):t.push({content:_.dim(` ${a}`)})}let i=`${_.bold(_.cyan("SEOAgent Cloud"))} ${_.dim("\xB7")} ${_.dim("your plan")}`;return A(t,{width:55,title:i})}async function qe(){let e=S(),t=!!process.stdin.isTTY;if(e&&t){let n=await Gr(e);if(n){let o=Br(n.plan),r=o?Mr(o):null;if(o&&l.message(Wr({email:n.email,domain:n.domain,current:o,next:r})),o&&!r){l.success(`You're on ${ve[o]} (highest tier).`);return}if(o&&r){let i=await Fr({message:`Upgrade from ${ve[o]} to ${ve[r]}?`});if(Ur(i)||!i){l.info("No changes.");return}}}}Kr()}function Kr(){let e=Hr();l.info("Opening SEOAgent Cloud pricing..."),l.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;Lr(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function Hr(){let e=process.cwd(),t=$(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${k.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ve(e={}){let t=K,n=await Yr();if(!n){l.warn("Couldn't reach the npm registry to check for a newer version."),l.message(`You're on ${t}. To force-update: npm install -g ${re}@latest`);return}if(zr(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!Ie()){l.info(`A newer CLI is available: ${t} \u2192 ${n}.`),l.message("You're running via npx \u2014 it already fetches the latest on every run."),l.message(`For a bare \`seoagent <cmd>\` form, install globally once: npm install -g ${re}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${re}@latest`);return}l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),await Jr()?l.success(`Updated to ${n}.`):l.error(`Update failed. Try manually: npm install -g ${re}@latest (you may need sudo on Linux/macOS).`)}function zr(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 Yr(e=fetch){try{let t=await e(Dr,{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 Jr(){return new Promise(e=>{let t=Nr("npm",["install","-g",`${re}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as qr}from"child_process";import{randomBytes as Vr}from"crypto";import{isCancel as Xr,spinner as Qr,text as Zr}from"@clack/prompts";import N from"picocolors";function pn(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 ei=1500,ti=300*1e3;function ni(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;qr(t,()=>{})}function oi(){return Vr(16).toString("hex")}function ri(e,t,n){let o=new URLSearchParams({session:t});return n&&n!=="unknown"&&o.set("domain",n),`${e}/cli/auth?${o.toString()}`}function fn(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 ii(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 pn(o.status,r)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function si(e){return new Promise(t=>setTimeout(t,e))}async function Xe(e={}){let t=process.cwd(),n=$(t),o=(e.apiBase||k.BASE||Q).replace(/\/$/,"");if(S()){l.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let r=n?.domain??null;if(r==="unknown"&&process.stdin.isTTY){let p=await Zr({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(E){if(!String(E??"").trim())return"A site URL is required.";if(!fn(String(E)))return"Please enter a valid domain like `example.com`."}});if(Xr(p)){l.warn("Login cancelled.");return}let g=fn(String(p));if(g){r=g;try{ee(t,{domain:g}),l.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=oi(),s=ri(o,i,r);l.message("Opening seoagent.com to connect this CLI to your account..."),l.info(`If the browser does not open, visit: ${s}`),ni(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?Qr():null;c?.start(N.dim("Waiting for browser confirmation\u2026"));let d=Date.now()+ti,u=!0;for(;Date.now()<d;){u||await si(ei),u=!1;let p=await ii(o,i);if(p.status==="ready"){an({user_token:p.user_token,website_token:p.website_token,api_base:o});let g=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",E=p.email&&p.domain?`Logged in as ${N.bold(p.email)} (${N.cyan(p.domain)}).`:p.email?`Logged in as ${N.bold(p.email)}.`:"Logged in.";y(c,"success",g,N.green(E)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){y(c,"warn",`Session expired. Run \`${f("login")}\` again.`,N.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){y(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,N.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}y(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,N.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function Qe(){cn()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as zi}from"@clack/prompts";import se from"picocolors";import{existsSync as tt,mkdirSync as Ti,readFileSync as _n,readdirSync as Oi,statSync as ji,writeFileSync as Li}from"fs";import{join as nt,relative as Ni,sep as Fi}from"path";import{existsSync as ai,mkdirSync as ci,readdirSync as li,unlinkSync as ui,writeFileSync as mn}from"fs";import{join as xe}from"path";function Ze(e){return xe(e,b,"inbox")}function gn(e){return`${e.action_type}-${e.id}.md`}function di(e,t){let n=0;if(!ai(e))return 0;for(let o of li(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{ui(xe(e,o)),n++}catch{}}return n}function pi(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}`):kr(`Removed:
|
|
27
|
+
${i}`),!e.global&&cn(R)&&l.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),l.info(`Re-install any time with \`${f("init")}\`.`)}import w from"picocolors";import{existsSync as un,mkdirSync as ln,readFileSync as vr,writeFileSync as xr,chmodSync as _r,unlinkSync as Er}from"fs";import{dirname as Cr}from"path";function v(){if(!un(N))return null;try{let e=JSON.parse(vr(N,"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||ee}}catch{return null}}function dn(e){ln(R,{recursive:!0}),ln(Cr(N),{recursive:!0}),xr(N,JSON.stringify(e,null,2)+`
|
|
28
|
+
`,"utf-8");try{_r(N,384)}catch{}}function pn(){if(!un(N))return!1;try{return Er(N),!0}catch{return!1}}import{existsSync as ie,readdirSync as qe,statSync as Ar,readFileSync as fn}from"fs";import{join as X}from"path";function Pr(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function Ir(e){let t=X(e,"audit","latest.md");if(!ie(t))return null;let n=me(t);if(!n)return null;let o=fn(t,"utf-8"),r=Pr(o);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:r.open}}function Rr(e){try{let n=fn(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 Tr(e){let t=X(e,"strategy","clusters");if(!ie(t))return null;let n=qe(t).filter(r=>r.endsWith(".md"));if(n.length===0)return null;let o=0;for(let r of n)o+=Rr(X(t,r));return{exists:!0,clusterCount:n.length,articleCount:o}}function Or(e){let t=X(e,"briefs");if(!ie(t))return null;let n=qe(t).filter(o=>o.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Lr(e){let t=X(e,"content");if(!ie(t))return null;let n=qe(t).filter(o=>o.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function jr(e){let t=X(e,"roadmap.md");return ie(t)?{exists:!0,updatedAt:Ar(t).mtime.toISOString()}:null}function mn(e){let t=$(e);if(!t)return null;let n=te(e);return{domain:t.domain,audit:Ir(n),strategy:Tr(n),briefs:Or(n),content:Lr(n),roadmap:jr(n)}}import F from"picocolors";var Nr=/\x1b\[[0-9;]*m/g;function gn(e){return e.replace(Nr,"").length}function P(e,t={}){let n=t.width??51,o=n-4,r="\u2500".repeat(n-2),i=Fr(n,t.title),s=F.dim(`\u251C${r}\u2524`),a=F.dim(`\u2514${r}\u2518`),c=[i];for(let d of e){if("sep"in d){c.push(s);continue}c.push(Ur(d.content,o))}return c.push(a),c.join(`
|
|
29
|
+
`)}function Fr(e,t){if(!t)return F.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=gn(t),o=e-5-n;return o<1?F.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${F.dim("\u250C\u2500 ")}${t}${F.dim(` ${"\u2500".repeat(o)}\u2510`)}`}function Ur(e,t){let n=gn(e),o;return n<=t?o=e+" ".repeat(t-n):o=e,`${F.dim("\u2502")} ${o} ${F.dim("\u2502")}`}function Ve(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 Xe(){let e=mn(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(Dr(e))}function Dr(e){if(!e)return"";let t=11,n=s=>w.dim(s.padEnd(t)),o=[];v()?(o.push({content:`${w.green("\u2713")} ${w.dim("Logged in")}`}),o.push({content:w.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(o.push({content:`${w.dim("\u25CB Not logged in")}`}),o.push({content:w.dim(` Run \`${f("login")}\` to connect.`)})),o.push({sep:!0}),o.push({content:e.audit?.exists?`${n("Audit:")}${w.green(`last run ${Ve(e.audit.date??"")}`)} ${w.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${w.dim("not yet run")}`}),o.push({content:e.strategy?.exists?`${n("Strategy:")}${w.bold(w.cyan(String(e.strategy.clusterCount??0)))} ${w.dim("clusters")} \xB7 ${w.bold(w.cyan(String(e.strategy.articleCount??0)))} ${w.dim("ideas")}`:`${n("Strategy:")}${w.dim("not yet created")}`}),o.push({content:e.briefs?.exists?`${n("Briefs:")}${w.bold(w.cyan(String(e.briefs.count??0)))} ${w.dim("ready")}`:`${n("Briefs:")}${w.dim("none created")}`}),o.push({content:e.content?.exists?`${n("Content:")}${w.green("\u2713")} ${w.bold(w.cyan(String(e.content.count??0)))} ${w.dim("articles written")}`:`${n("Content:")}${w.dim("no articles yet")}`}),o.push({content:e.roadmap?.exists?`${n("Roadmap:")}${w.green("updated")} ${w.dim(Ve(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${w.dim("not yet created")}`});let i=`${w.bold(w.cyan("SEOAgent"))} ${w.dim("\xB7")} ${w.bold(e.domain)}`;return P(o,{width:78,title:i})}import{exec as Br,spawn as Mr}from"child_process";import{confirm as Gr,isCancel as Wr}from"@clack/prompts";import C from"picocolors";var Kr="https://registry.npmjs.org/@seoagent-official/seoagent/latest",se="@seoagent-official/seoagent",ae=["free","starter","pro","scale","enterprise"],xe={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function zr(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return ae.includes(t)?t:null}function Hr(e){let t=ae.indexOf(e);return t===-1||t===ae.length-1?null:ae[t+1]}async function Yr(e,t=fetch){if(!e)return null;try{let n=(e.api_base||k.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 Jr(e){let t=[],o=s=>C.dim(s.padEnd(10)),r=!1;e.email&&(t.push({content:`${o("Email:")}${C.bold(e.email)}`}),r=!0),e.domain&&(t.push({content:`${o("Website:")}${C.cyan(e.domain)}`}),r=!0),r&&t.push({sep:!0});for(let s of ae){let a=xe[s];s===e.current?t.push({content:`${C.bold(C.green("\u25CF"))} ${C.bold(C.green(a.padEnd(11)))} ${C.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${C.yellow("\u25C6")} ${C.bold(C.yellow(a.padEnd(11)))} ${C.yellow("next tier")}`}):t.push({content:C.dim(` ${a}`)})}let i=`${C.bold(C.cyan("SEOAgent Cloud"))} ${C.dim("\xB7")} ${C.dim("your plan")}`;return P(t,{width:55,title:i})}async function Qe(){let e=v(),t=!!process.stdin.isTTY;if(e&&t){let n=await Yr(e);if(n){let o=zr(n.plan),r=o?Hr(o):null;if(o&&l.message(Jr({email:n.email,domain:n.domain,current:o,next:r})),o&&!r){l.success(`You're on ${xe[o]} (highest tier).`);return}if(o&&r){let i=await Gr({message:`Upgrade from ${xe[o]} to ${xe[r]}?`});if(Wr(i)||!i){l.info("No changes.");return}}}}qr()}function qr(){let e=Vr();l.info("Opening SEOAgent Cloud pricing..."),l.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;Br(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function Vr(){let e=process.cwd(),t=$(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${k.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ze(e={}){let t=H,n=await Qr();if(!n){l.warn("Couldn't reach the npm registry to check for a newer version."),l.message(`You're on ${t}. To force-update: npm install -g ${se}@latest`);return}if(Xr(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!Te()){l.info(`A newer CLI is available: ${t} \u2192 ${n}.`),l.message("You're running via npx \u2014 it already fetches the latest on every run."),l.message(`For a bare \`seoagent <cmd>\` form, install globally once: npm install -g ${se}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${se}@latest`);return}l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),await Zr()?l.success(`Updated to ${n}.`):l.error(`Update failed. Try manually: npm install -g ${se}@latest (you may need sudo on Linux/macOS).`)}function Xr(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 Qr(e=fetch){try{let t=await e(Kr,{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 Zr(){return new Promise(e=>{let t=Mr("npm",["install","-g",`${se}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as ei}from"child_process";import{randomBytes as ti}from"crypto";import{isCancel as ni,spinner as oi,text as ri}from"@clack/prompts";import U from"picocolors";function hn(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 ii=1500,si=300*1e3;function ai(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;ei(t,()=>{})}function ci(){return ti(16).toString("hex")}function li(e,t,n){let o=new URLSearchParams({session:t});return n&&n!=="unknown"&&o.set("domain",n),`${e}/cli/auth?${o.toString()}`}function yn(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 ui(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 hn(o.status,r)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function di(e){return new Promise(t=>setTimeout(t,e))}async function et(e={}){let t=process.cwd(),n=$(t),o=(e.apiBase||k.BASE||ee).replace(/\/$/,"");if(v()){l.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let r=n?.domain??null;if(r==="unknown"&&process.stdin.isTTY){let p=await ri({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(A){if(!String(A??"").trim())return"A site URL is required.";if(!yn(String(A)))return"Please enter a valid domain like `example.com`."}});if(ni(p)){l.warn("Login cancelled.");return}let g=yn(String(p));if(g){r=g;try{ne(t,{domain:g}),l.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=ci(),s=li(o,i,r);l.message("Opening seoagent.com to connect this CLI to your account..."),l.info(`If the browser does not open, visit: ${s}`),ai(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?oi():null;c?.start(U.dim("Waiting for browser confirmation\u2026"));let d=Date.now()+si,u=!0;for(;Date.now()<d;){u||await di(ii),u=!1;let p=await ui(o,i);if(p.status==="ready"){dn({user_token:p.user_token,website_token:p.website_token,api_base:o});let g=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",A=p.email&&p.domain?`Logged in as ${U.bold(p.email)} (${U.cyan(p.domain)}).`:p.email?`Logged in as ${U.bold(p.email)}.`:"Logged in.";y(c,"success",g,U.green(A)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){y(c,"warn",`Session expired. Run \`${f("login")}\` again.`,U.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){y(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,U.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}y(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,U.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function tt(){pn()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as Xi}from"@clack/prompts";import ce from"picocolors";import{existsSync as rt,mkdirSync as Fi,readFileSync as Pn,readdirSync as Ui,statSync as Di,writeFileSync as Bi}from"fs";import{join as it,relative as Mi,sep as Gi}from"path";import{existsSync as pi,mkdirSync as fi,readdirSync as mi,unlinkSync as gi,writeFileSync as wn}from"fs";import{join as _e}from"path";function nt(e){return _e(e,b,"inbox")}function kn(e){return`${e.action_type}-${e.id}.md`}function hi(e,t){let n=0;if(!pi(e))return 0;for(let o of mi(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{gi(_e(e,o)),n++}catch{}}return n}function yi(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,7 +69,7 @@ positive, you disagree, etc.), close it out as failed with a reason:
|
|
|
69
69
|
\`\`\`bash
|
|
70
70
|
npx @seoagent-official/seoagent ack ${e.id} --failed --reason "kept; performs well off-search"
|
|
71
71
|
\`\`\`
|
|
72
|
-
`}function
|
|
72
|
+
`}function wi(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`---
|
|
73
73
|
action_id: ${e.id}
|
|
74
74
|
action_type: ${e.action_type}
|
|
75
75
|
issue: ${o}
|
|
@@ -115,7 +115,7 @@ next \`seoagent sync\`. If you disagree or it's a false positive, decline it:
|
|
|
115
115
|
\`\`\`bash
|
|
116
116
|
npx @seoagent-official/seoagent ack ${e.id} --failed --reason "not applicable; ..."
|
|
117
117
|
\`\`\`
|
|
118
|
-
`}function
|
|
118
|
+
`}function ki(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`---
|
|
119
119
|
action_id: ${e.id}
|
|
120
120
|
action_type: ${e.action_type}
|
|
121
121
|
brief_slug: ${n??""}
|
|
@@ -164,7 +164,7 @@ If you decide not to write it (off-strategy, duplicate, etc.), decline it:
|
|
|
164
164
|
\`\`\`bash
|
|
165
165
|
npx @seoagent-official/seoagent ack ${e.id} --failed --reason "skipped; ..."
|
|
166
166
|
\`\`\`
|
|
167
|
-
`}function
|
|
167
|
+
`}function $i(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(`
|
|
168
168
|
`):"- (no metrics)";return`---
|
|
169
169
|
action_id: ${e.id}
|
|
170
170
|
action_type: ${e.action_type}
|
|
@@ -211,7 +211,7 @@ If you disagree (page is fine as-is, intentionally short, etc.), decline it:
|
|
|
211
211
|
\`\`\`bash
|
|
212
212
|
npx @seoagent-official/seoagent ack ${e.id} --failed --reason "kept as-is; ..."
|
|
213
213
|
\`\`\`
|
|
214
|
-
`}function
|
|
214
|
+
`}function bi(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?`\`\`\`
|
|
215
215
|
${r.join(`
|
|
216
216
|
`)}
|
|
217
217
|
\`\`\`${i?`
|
|
@@ -257,7 +257,7 @@ SEOAgent re-submits the sitemap to GSC on its schedule. If a sitemap already exi
|
|
|
257
257
|
\`\`\`bash
|
|
258
258
|
npx @seoagent-official/seoagent ack ${e.id} --failed --reason "sitemap already served at /sitemap.xml"
|
|
259
259
|
\`\`\`
|
|
260
|
-
`}function
|
|
260
|
+
`}function Si(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`---
|
|
261
261
|
action_id: ${e.id}
|
|
262
262
|
action_type: ${e.action_type}
|
|
263
263
|
keyword: ${n??""}
|
|
@@ -315,10 +315,10 @@ decline it:
|
|
|
315
315
|
\`\`\`bash
|
|
316
316
|
npx @seoagent-official/seoagent ack ${e.id} --failed --reason "skipped; ..."
|
|
317
317
|
\`\`\`
|
|
318
|
-
`}function
|
|
318
|
+
`}function vi(e){switch(e.action_type){case"cli_prune_pending":return yi(e);case"cli_technical_fix":return wi(e);case"cli_new_content":return ki(e);case"cli_content_update":return $i(e);case"cli_sitemap_update":return bi(e);case"cli_new_landing_page":return Si(e);default:return null}}function xi(e){if(e.length===0)return`# SEOAgent Inbox
|
|
319
319
|
|
|
320
320
|
No pending actions. Run \`seoagent sync\` later to check for new ones.
|
|
321
|
-
`;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${
|
|
321
|
+
`;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${kn(n)}\``);return`# SEOAgent Inbox
|
|
322
322
|
|
|
323
323
|
You have **${e.length}** pending action${e.length===1?"":"s"} from your dashboard.
|
|
324
324
|
|
|
@@ -330,21 +330,22 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
|
|
|
330
330
|
|
|
331
331
|
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
332
332
|
skill knows what to do.
|
|
333
|
-
`}function
|
|
334
|
-
`,"utf-8")}catch{}return c}var
|
|
335
|
-
`,"utf-8")}function
|
|
333
|
+
`}function $n(e,t){let n=nt(e);fi(n,{recursive:!0});let o=new Set(t.map(s=>s.id)),r=hi(n,o),i=0;for(let s of t){let a=vi(s);a!==null&&(wn(_e(n,kn(s)),a,"utf-8"),i++)}return wn(_e(n,"README.md"),xi(t),"utf-8"),{wrote:i,removed:r,inboxPath:n}}import{createHash as Ci}from"crypto";import{existsSync as vn,mkdirSync as Ai,readFileSync as Pi,statSync as xn,writeFileSync as Sn,rmSync as Ii}from"fs";import{dirname as Ri,join as ot,sep as Ti}from"path";function _i(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Ei=[{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 bn(e,t){let n=_i(e);for(let{cls:o,test:r}of Ei)if(r(n))return t&&(o==="keywords"||o==="pages")?"generated-index":o;return"other"}function Oi(e){return"sha256:"+Ci("sha256").update(e).digest("hex")}function Li(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 ji(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:bn(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 _n(e){let t=await Cn({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 En(e,t){return ot(e,t.split("/").join(Ti))}function Ni(e,t,n){let o={};for(let r of t){let i=En(e,r);if(!vn(i)){o[r]={exists:!1,locallyEdited:!1};continue}let s=xn(i),a=n[r],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;o[r]={exists:!0,contentHash:Oi(Pi(i,"utf-8")),locallyEdited:c}}return o}async function Cn(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 An(e){let t=ot(e.projectDir,b),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!vn(t))return{...n,ok:!0};let o=await Cn({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(u=>u.path),...r.deleted],s=Ni(t,i,e.stateFiles),a=Li(r,s,{force:e.force}),c={...n,cursor:r.now};for(let u of a){let p=En(t,u.path);try{switch(u.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{Ai(Ri(p),{recursive:!0}),Sn(p,u.body??"","utf-8");let g=xn(p);e.stateFiles[u.path]={mtime:g.mtimeMs,size:g.size},u.kind==="write"?c.written++:c.overwritten++,u.note&&c.warnings.push(`${u.path}: ${u.note}`);break}case"conflict":c.conflicts++,c.warnings.push(`${u.path}: ${u.note??"conflict"}`);break;case"delete":Ii(p,{force:!0}),delete e.stateFiles[u.path],c.deleted++;break;case"delete-skipped":c.conflicts++,c.warnings.push(`${u.path}: ${u.note??"delete skipped"}`);break}}catch(g){c.ok=!1,c.error=`${u.path}: ${g.message}`}}(c.conflicts>0||!c.ok)&&(c.cursor=e.since);let d=ji(a,r,c.cursor,new Date().toISOString());if(d)try{Sn(ot(t,St),JSON.stringify(d,null,2)+`
|
|
334
|
+
`,"utf-8")}catch{}return c}var Wi=new Set([".md"]),Ki=new Set(["inbox"]);function zi(e){let t=[];function n(o,r){if(rt(o))for(let i of Ui(o,{withFileTypes:!0})){if(i.name.startsWith(".")||r===""&&Ki.has(i.name))continue;let s=it(o,i.name);if(i.isDirectory())n(s,r?`${r}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a);Wi.has(c)&&t.push(s)}}}return n(e,""),t}function In(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return it(Oe,`${t}.json`)}function Hi(e){let t=In(e);if(!rt(t))return{files:{},last_synced_at:null};try{return JSON.parse(Pn(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Yi(e,t){Fi(Oe,{recursive:!0}),Bi(In(e),JSON.stringify(t,null,2)+`
|
|
335
|
+
`,"utf-8")}function Ji(e,t){return Mi(e,t).split(Gi).join("/")}async function qi(e,t){try{let n=await fetch(`${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 Vi(e,t,n){try{let o=await fetch(`${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 Rn(e,t={}){let n=v();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=it(e,b);if(!rt(r))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let i=Hi(o.domain),s=zi(r),a=n.api_base||k.BASE,c=`Bearer ${n.user_token}:${n.website_token}`,d=0,u=0,p=[],g=0;if(!t.pullOnly)for(let E of s){let Z=Ji(r,E);if(t.pathFilter&&!Z.endsWith(t.pathFilter))continue;let ue=Di(E),Ie=i.files[Z];if(!(!Ie||Ie.mtime!==ue.mtimeMs||Ie.size!==ue.size)&&!t.force)continue;g++;let eo=Pn(E,"utf-8"),Re=await Vi(a,{path:Z,contents:eo,domain:o.domain},c);Re.ok?(i.files[Z]={mtime:ue.mtimeMs,size:ue.size},d++):(u++,p.push(`${Z}: ${Re.status} ${Re.error??""}`.trim()))}let A=await qi(a,c),T=0,L=0;if(A.ok){let E=$n(e,A.actions);T=E.wrote,L=E.removed}else A.error&&p.push(`pull actions: ${A.error}`);let j,Pe=!1,wt=i.last_synced_at;if(!t.pushOnly){let E=await An({projectDir:e,apiBase:a,authHeader:c,since:i.last_synced_at,stateFiles:i.files,force:t.force});E.ok?wt=E.cursor:(Pe=!0,E.error&&p.push(`pull: ${E.error}`)),j={written:E.written,overwritten:E.overwritten,skipped:E.skipped,conflicts:E.conflicts,deleted:E.deleted,warnings:E.warnings}}let Zn=!!j&&j.written+j.overwritten+j.deleted+j.conflicts>0;if(i.last_synced_at=wt,Yi(o.domain,i),g===0&&T===0&&L===0&&!Zn&&!Pe&&u===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:p,actionsPulled:0,actionsRemoved:0,pull:j};let kt=u===0&&!Pe;return{ok:kt,reason:kt?void 0:"error",synced:d,failed:u,errors:p,actionsPulled:T,actionsRemoved:L,pull:j}}async function le(e={}){let t=!e.silent&&!!process.stdout.isTTY,n=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",o=t?Xi():null;o?.start(`${n} ${ce.dim(".seoagent/")} with your dashboard\u2026`);let r=await Rn(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"){y(o,"info",`Not logged in. Run \`${f("login")}\` to enable cloud sync.`,ce.dim("Not logged in \u2014 cloud sync skipped.")),o&&l.info(`Run \`${f("login")}\` to enable cloud sync.`);return}if(r.reason==="no-project"){y(o,"info",`No SEOAgent project here. Run \`${f("init")}\` first.`,ce.dim("No SEOAgent project \u2014 sync skipped.")),o&&l.info(`Run \`${f("init")}\` first.`);return}if(r.reason==="no-changes"){y(o,"info","Already in sync.",ce.green("Already in sync."));return}let i=Qi(r);y(o,"success",i??"Sync complete.",ce.green(i??"Sync complete.")),r.synced>0&&l.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&&l.success(`Pulled ${a} file${a===1?"":"s"} from the cloud`+(s.overwritten>0?` (${s.overwritten} updated)`:"")),s.deleted>0&&l.info(`Removed ${s.deleted} file${s.deleted===1?"":"s"} deleted in the cloud.`),s.conflicts>0&&l.warn(`${s.conflicts} conflict${s.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let c of s.warnings.slice(0,5))l.info(` \u2022 ${c}`)}if(r.actionsPulled&&r.actionsPulled>0&&(l.success(`Pulled ${r.actionsPulled} pending action${r.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),l.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),r.actionsRemoved&&r.actionsRemoved>0&&l.info(`Cleaned up ${r.actionsRemoved} stale inbox file${r.actionsRemoved===1?"":"s"}.`),r.failed>0){l.warn(`${r.failed} file${r.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let a of r.errors.slice(0,3))l.info(` \u2022 ${a}`)}}function Qi(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."}async function st(e={}){if(e.print){let t=v();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!$(process.cwd())){l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1;return}let o=t.api_base||k.BASE,r=await _n({apiBase:o,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!r.ok){l.warn(r.error),process.exitCode=1;return}process.stdout.write(r.body),r.body.endsWith(`
|
|
336
336
|
`)||process.stdout.write(`
|
|
337
|
-
`);return}await
|
|
338
|
-
`),r=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${
|
|
337
|
+
`);return}await le({pullOnly:!0,force:e.force,silent:e.silent})}import{existsSync as Zi,readdirSync as es,unlinkSync as ts}from"fs";import{join as Tn}from"path";async function at(e,t={}){let n=Number.parseInt(e,10);if(Number.isNaN(n)||n<=0){l.error(`Invalid action id: "${e}"`),process.exitCode=1;return}let o=v();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!$(process.cwd())){l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1;return}let i=o.api_base||k.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",c;try{c=await fetch(`${i}/api/cli/actions/${n}/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){l.error(`Network error: ${u.message}`),process.exitCode=1;return}if(!c.ok){let u=await c.text().catch(()=>"");l.error(`Server rejected ack (${c.status}): ${u.slice(0,200)}`),process.exitCode=1;return}let d=nt(process.cwd());if(Zi(d)){for(let u of es(d))if(u.endsWith(`-${n}.md`))try{ts(Tn(d,u))}catch{}}t.failed?l.success(`Action ${n} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):l.success(`Action ${n} marked completed.`),l.info(` inbox location: ${Tn(b,"inbox")}`)}import{spinner as ns}from"@clack/prompts";import h from"picocolors";var os=new Set(["on","off","status"]);async function lt(e,t={}){let n=(e||"").toLowerCase();if(!os.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let o=v();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let r=t.apiBase||o.api_base||k.BASE,i=`Bearer ${o.user_token}:${o.website_token}`,a=!!process.stdout.isTTY?ns():null,c=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(c);let d;try{d=await fetch(`${r}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(A){y(a,"error",`Network error: ${A.message}`,h.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await d.json()}catch{u=null}if(d.status===402||u?.code==="upgrade_required"){let T=$(process.cwd())?.domain??"",L=`${k.PRICING}?ref=cli${T?`&domain=${encodeURIComponent(T)}`:""}`;y(a,"warn","CLI autopilot is a paid feature.",h.yellow("Autopilot is a paid feature.")),l.message(rs(L)),process.exitCode=1;return}if(!d.ok||u?.status!=="ok"||!u.autopilot){y(a,"error",`Server rejected request (${d.status})${u?.error?`: ${u.error}`:""}`,h.red(`Server rejected request (${d.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:g}=u.autopilot;if(n==="on"){a?.stop(h.green("Autopilot enabled.")),l.message(ct({enabled:!0,deliveryMode:g,action:n}));return}if(n==="off"){a?.stop(h.dim("Autopilot disabled.")),l.message(ct({enabled:!1,deliveryMode:g,action:n}));return}a?.stop(h.dim("Status:")),l.message(ct({enabled:p,deliveryMode:g,action:n}))}function ct(e){let n=s=>h.dim(s.padEnd(11)),o=e.enabled?`${h.bold(h.green("\u25CF ON"))} ${h.dim("(queueing fixes for your coding agent)")}`:`${h.dim("\u25CB OFF")} ${h.dim("(no new suggestions will be queued)")}`,r=[{content:`${n("Status:")}${o}`}];e.enabled&&e.deliveryMode&&r.push({content:`${n("Mode:")}${h.dim(e.deliveryMode)}`}),r.push({sep:!0}),e.enabled?(r.push({content:`${h.dim("Apply queued fixes:")} ${h.cyan(f("sync"))}`}),r.push({content:`${h.dim("Turn off any time:")} ${h.cyan(f("autopilot off"))}`})):(r.push({content:`${h.dim("Enable (paid):")} ${h.cyan(f("autopilot on"))}`}),r.push({content:h.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${h.bold(h.cyan("SEOAgent"))} ${h.dim("\xB7")} ${h.dim("autopilot")}`;return P(r,{width:78,title:i})}function rs(e){let t=[{content:h.bold(h.yellow("Autopilot is a paid feature."))},{sep:!0},{content:h.dim("SEOAgent continuously audits your site and queues fixes for")},{content:h.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:h.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${h.dim("Upgrade:")} ${h.cyan(e)}`}],n=`${h.bold(h.cyan("SEOAgent"))} ${h.dim("\xB7")} ${h.dim("autopilot")}`;return P(t,{width:78,title:n})}import{mkdirSync as hs,writeFileSync as ys}from"fs";import{join as ut}from"path";import{readdirSync as is,readFileSync as ss,statSync as On}from"fs";import{join as as}from"path";var cs=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),ls=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"]),us=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),ds=5e3,ps=512*1024;function Un(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function Ln(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&&ls.has(o.slice(r+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var jn=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Nn=/\]\(\s*([^)\s]+)/g;function fs(e,t){if(!e)return[];let n=Un(t),o=[],r;for(jn.lastIndex=0;(r=jn.exec(e))!==null;){let i=r[1]??r[2]??r[3]??"",s=Ln(i,n);s&&o.push(s)}for(Nn.lastIndex=0;(r=Nn.exec(e))!==null;){let i=Ln(r[1],n);i&&o.push(i)}return o}function ms(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 Dn(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(`
|
|
338
|
+
`),r=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${Un(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(`
|
|
339
339
|
`),i=e.orphans.length===0?`## Orphan pages
|
|
340
340
|
|
|
341
|
-
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=>`| ${
|
|
342
|
-
`),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=>`| ${
|
|
341
|
+
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=>`| ${Fn(a.url)} | \u2014 |`)].join(`
|
|
342
|
+
`),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=>`| ${Fn(a.url)} | ${a.inbound} |`)].join(`
|
|
343
343
|
`);return[o,"",r,"",i,s,""].join(`
|
|
344
|
-
`)}function
|
|
345
|
-
`);return}let i=
|
|
346
|
-
`);return}if(l.message(
|
|
344
|
+
`)}function Fn(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*gs(e){let t=0;function*n(o){let r;try{r=is(o,{withFileTypes:!0})}catch{return}for(let i of r){if(t>=ds)return;if(i.name.startsWith("."))continue;let s=as(o,i.name);if(i.isDirectory()){if(us.has(i.name))continue;yield*n(s)}else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a+1).toLowerCase();if(!cs.has(c))continue;t++,yield s}}}yield*n(e)}function Bn(e,t){let{pages:n}=ke(e,t),o=[],r=0,i=!1;try{i=On(e).isDirectory()}catch{i=!1}if(i)for(let s of gs(e)){let a;try{if(On(s).size>ps)continue;a=ss(s,"utf-8")}catch{continue}r++;for(let c of fs(a,t))o.push(c)}return ms(n,o,r)}function dt(e={}){let t=process.cwd(),n=$(t);if(!n){l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1;return}let o=n.domain&&n.domain!=="unknown"?n.domain:null,r=Bn(t,o);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
|
|
345
|
+
`);return}let i=ut(t,b);hs(i,{recursive:!0});let s=ut(i,"internal-links.md");if(ys(s,Dn(r,o),"utf-8"),l.success(`Analyzed ${r.pageCount} page${r.pageCount===1?"":"s"} across ${r.filesScanned} file${r.filesScanned===1?"":"s"}.`),r.orphans.length===0)l.info("No orphan pages \u2014 every page has an inbound internal link.");else{l.warn(`${r.orphans.length} orphan page${r.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of r.orphans.slice(0,10))l.message(` \u2022 ${a.url}`);r.orphans.length>10&&l.message(` \u2026and ${r.orphans.length-10} more`)}l.info(`Report written to ${ut(b,"internal-links.md")}`)}import{spinner as Wn}from"@clack/prompts";import m from"picocolors";var Kn={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function ws(e){let t=process.cwd(),n=Pt(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let o=$(t),r=o?.domain&&o.domain!=="unknown"?o.domain:void 0,i=(e.apiBase||k.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY?Wn():null;a?.start(`Looking up ${m.bold(`"${e.keyword}"`)} ${m.dim("via DataForSEO (free peek)\u2026")}`);let c;try{c=await fetch(`${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(u){y(a,"error",`Network error: ${u.message}`,m.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await c.json()}catch{d=null}if(c.status===429||d?.skipped?.startsWith("rate-limited")){let u=d?.skipped==="rate-limited:ip"?"this network":"this install";y(a,"warn",`Daily peek quota reached for ${u}.`,m.yellow(`Daily peek quota reached for ${u}.`)),l.message(Mn()),process.exitCode=1;return}if(!c.ok||!d){y(a,"error",`Peek failed (${c.status})${d?.error?`: ${d.error}`:""}`,m.red(`Peek failed (${c.status}).`)),process.exitCode=1;return}if(d.skipped==="no-creds"||d.skipped==="no-table"){y(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",m.yellow("Real keyword data is not enabled on the server yet."));return}if(!d.opportunity){y(a,"warn",`No data returned for "${e.keyword}".`,m.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(m.green("Got it.")),l.message(ks(d.opportunity)),d.remaining&&l.message(`${m.dim("Peeks remaining today:")} ${m.bold(String(d.remaining.install))} ${m.dim("\u2014 "+Mn())}`)}function ks(e){let n=d=>m.dim(d.padEnd(14)),o=e.volume!=null?m.bold(String(e.volume)):m.dim("n/a"),r=e.difficulty!=null?`${m.bold(String(e.difficulty))} ${m.dim($s(e.difficulty))}`:m.dim("n/a"),i=Kn[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?m.bold(m.green(i)):e.opportunity==="striking_distance"?m.bold(m.cyan(i)):e.opportunity==="competitor_gap"?m.bold(m.yellow(i)):m.dim(i),a=[{content:`${m.green("\u25CF")} ${m.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${o} ${m.dim("/mo")}`},{content:`${n("Difficulty:")}${r}`},{content:`${n("Opportunity:")}${s}`}],c=`${m.bold(m.cyan("Keyword peek"))}`;return P(a,{width:55,title:c})}function $s(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Mn(e=v()){return e?`You're logged in \u2014 run \`${f("keywords")}\` for full enrichment (no quota), or \`${f("keywords --discover")}\` / \`${f("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${f("login")}`}function Gn(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){l.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";l.message(` \u2022 [${Kn[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${o}, ${r}${i}`)}}}function bs(e){if(e.length!==0){l.message("Top competitor gaps:");for(let t of e){let n=t.volume!=null?`vol ${t.volume}`:"vol n/a",o=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",r=t.their_position!=null?`#${t.their_position}`:"top 10";l.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${r}, ${n}, ${o}`)}}}async function pt(e={}){if(e.peek&&e.peek.trim().length>0){await ws({keyword:e.peek.trim(),apiBase:e.apiBase});return}let t=v();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=e.apiBase||t.api_base||k.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",c=!!process.stdout.isTTY?Wn():null;c?.start(s);let d;try{d=await fetch(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o},body:"{}"})}catch(g){y(c,"error",`Network error: ${g.message}`,m.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await d.json()}catch{u=null}if(d.status===402||u?.code==="upgrade_required"){y(c,"warn",r==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",m.yellow("Paid feature \u2014 upgrade to continue.")),l.message(r==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${m.cyan(k.PRICING)}`:`Upgrade to find new keywords to target: ${m.cyan(k.PRICING)}`),process.exitCode=1;return}if(!d.ok||u?.status!=="ok"){y(c,"error",`Server rejected request (${d.status})${u?.error?`: ${u.error}`:""}`,m.red(`Server rejected request (${d.status}).`)),process.exitCode=1;return}if(u.skipped==="no-keywords"||u.skipped==="no-seeds"){y(c,"warn","No keywords yet. Run the keyword strategy (Phase 2) first, then try again.",m.yellow("No keywords yet."));return}if(u.skipped==="no-competitors"){y(c,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",m.yellow("No competitors yet."));return}if(u.skipped==="no-creds"||u.skipped==="no-columns"||u.skipped==="no-table"){y(c,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",m.yellow("Real keyword data is not enabled on the server yet."));return}if(u.skipped){y(c,"warn",`Skipped: ${u.skipped}`,m.yellow(`Skipped: ${u.skipped}`));return}if(r==="competitors"){let g=u.gaps??0;y(c,"success",`Found ${g} competitor gap${g===1?"":"s"} across ${u.competitors?.length??0} competitor${u.competitors?.length===1?"":"s"} (added as "suggested").`,m.green(`${g} competitor gap${g===1?"":"s"} found.`)),bs(u.topGaps??[]),l.message(`Review them in ${m.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}if(r==="discover"){let g=u.discovered??0;y(c,"success",`Discovered ${g} new keyword${g===1?"":"s"} to target (added as "suggested").`,m.green(`${g} new keyword${g===1?"":"s"} discovered.`)),Gn(u.opportunities??[]),l.message(`Review them in ${m.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}let p=u.enriched??0;y(c,"success",`Enriched ${p} keyword${p===1?"":"s"}.`,m.green(`Enriched ${p} keyword${p===1?"":"s"}.`)),Gn(u.opportunities??[]),u.paid||l.message(`${m.dim("Free plan:")} enriched up to ${m.bold(String(u.cap??25))} keywords. ${m.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${m.cyan(k.PRICING)}`)}import S from"picocolors";import{existsSync as Ss,readFileSync as vs}from"fs";import{join as xs}from"path";var zn=["openai","fal","replicate"],Q={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function _s(e){let t={};if(!Ss(e))return t;let n=vs(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 Hn(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 W){let r=xs(e,o),i=_s(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 Ee(e){let t=[].concat(...zn.map(a=>Q[a])),n=Hn(e,t),o=[];for(let a of zn)Q[a].some(c=>n.found[c])&&o.push(a);if(o.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let r=o[0],i=Q[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 Yn(e,t){let n=Hn(e,Q[t]);for(let o of Q[t])if(n.found[o])return{key:n.found[o].value,envName:o};return null}function Jn(){return Q}function ft(e={}){let t=process.cwd(),n=$(t),o=Ee(t);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
|
|
346
|
+
`);return}if(l.message(Es(o)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}ne(t,{image_provider:o.provider}),l.info(`Saved to ${S.cyan(".seoagent/project.md")} ${S.dim(`(image_provider: ${o.provider})`)}`)}function Es(e){let n=i=>S.dim(i.padEnd(12)),o=[];if(e.provider==="none"){o.push({content:`${S.dim("\u25CB")} ${S.bold(S.yellow("No image provider detected"))}`}),o.push({sep:!0}),o.push({content:S.dim("Set ONE of these to enable image generation:")});let i=Jn();for(let s of Object.keys(i))o.push({content:`${n(s+":")}${S.cyan(i[s].join(" or "))}`});o.push({sep:!0}),o.push({content:S.dim("Add to your shell, .env.local, or .env, then re-run:")}),o.push({content:` ${S.cyan(f("env-check"))}`})}else{o.push({content:`${S.green("\u2713")} ${S.dim("Image provider:")} ${S.bold(S.green(e.provider))}`}),o.push({sep:!0}),e.matched_key&&o.push({content:`${n("Key:")}${S.bold(e.matched_key)}`}),e.source&&o.push({content:`${n("Source:")}${S.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&o.push({content:`${n("Available:")}${S.dim(i.join(", "))}`})}let r=`${S.bold(S.cyan("SEOAgent"))} ${S.dim("\xB7")} ${S.dim("env-check")}`;return P(o,{width:64,title:r})}import{existsSync as gt,mkdirSync as Xn,writeFileSync as Qn}from"fs";import{dirname as Ae,isAbsolute as Rs,join as Ce,resolve as Ts}from"path";import{tmpdir as Os}from"os";import{spinner as Ls}from"@clack/prompts";import x from"picocolors";import{Buffer as qn}from"buffer";async function mt(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 qn.from(n)}async function Cs(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,response_format:"b64_json"})});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:qn.from(r.b64_json,"base64"),contentType:"image/png"};if(r.url)return{bytes:await mt(r.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function As(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 mt(r.url),contentType:r.content_type??"image/png"}}async function Ps(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 Is(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 Ps(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 mt(r),contentType:"image/png",providerImageId:o.id}}async function Vn(e,t){switch(e){case"openai":return Cs(t);case"fal":return As(t);case"replicate":return Is(t);default:throw new Error(`Unknown image provider: ${e}`)}}function js(e){return e==="openai"||e==="fal"||e==="replicate"}async function ht(e={}){let t=process.cwd();if(!e.prompt){l.warn(`Missing --prompt. Example: ${f('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){l.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=$(t),o=null;if(e.provider){if(!js(e.provider)){l.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=Ee(t).provider;if(!o||o==="none"){l.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${f("env-check")}\`.`),process.exitCode=1;return}let r=Yn(t,o);if(!r){l.warn(`Provider "${o}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=Rs(e.out)?e.out:Ts(t,e.out),a=!e.silent&&!!process.stdout.isTTY?Ls():null;a?.start(`Generating image with ${x.bold(o)} ${x.dim(`(${r.envName})`)}\u2026`);try{let c=await Vn(o,{prompt:e.prompt,apiKey:r.key,size:e.size});gt(Ae(i))||Xn(Ae(i),{recursive:!0}),Qn(i,c.bytes),e.silent||y(a,"success",`Wrote ${i} (${c.bytes.length} bytes, ${c.contentType}).`,x.green(`Wrote ${i} ${x.dim(`(${c.bytes.length} bytes, ${c.contentType})`)}`))}catch(c){a?.stop(x.red("Image generation failed."));let d=Fs(t,{provider:o,envName:r.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(Ns({provider:o,envName:r.envName,prompt:e.prompt,size:e.size,message:c.message})),d&&l.message(`${x.dim("Full error log:")} ${x.cyan(d)}`),process.exitCode=1}}function Ns(e){let n=u=>x.dim(u.padEnd(10)),r=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${x.red("\u2717")} ${x.bold(x.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${x.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${x.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,c=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:x.red(c)});let d=`${x.bold(x.cyan("SEOAgent"))} ${x.dim("\xB7")} ${x.dim("generate-image")}`;return P(i,{width:70,title:d})}function Fs(e,t){let o=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,r=Ce(e,b),i=Ce(r,".errors"),s=gt(r)?Ce(i,o):Ce(Os(),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 gt(Ae(s))||Xn(Ae(s),{recursive:!0}),Qn(s,a.join(`
|
|
347
|
+
`)),s}catch{return null}}import I from"picocolors";async function yt(e={}){let t=v();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
|
|
347
348
|
`):l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||k.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){l.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})}
|
|
348
349
|
`);return}l.warn(`Logged in, but the server at this API base does not support \`/api/cli/whoami\` yet. Update with \`${f("update-cli")}\` (or re-deploy your server).`),l.message(`API base: ${n}`);return}let i=null;try{i=await 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}`})}
|
|
349
350
|
`):l.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)}
|
|
350
|
-
`);return}l.message(
|
|
351
|
+
`);return}l.message(Us(i)),i.paid===!1&&l.message(`${I.dim("Upgrade for autopilot:")} ${I.cyan(k.PRICING)}`)}function Us(e){let n=i=>I.dim(i.padEnd(10)),o=[];if(e.email&&(o.push({content:`${I.green("\u2713")} ${I.dim("Logged in as")} ${I.bold(e.email)}`}),o.push({sep:!0})),e.domain&&o.push({content:`${n("Website:")}${I.cyan(e.domain)}`}),e.plan){let i=e.paid?I.bold(I.green(e.plan)):I.bold(e.plan);o.push({content:`${n("Plan:")}${i}`})}e.api_base&&o.push({content:`${n("API:")}${I.dim(e.api_base)}`});let r=`${I.bold(I.cyan("SEOAgent"))} ${I.dim("\xB7")} ${I.dim("whoami")}`;return P(o,{width:55,title:r})}var _=new Ds;_.name("seoagent").description("AI SEO agent for Claude Code").version(H).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=>{Ye({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=>{Je({yes:e.yes,global:e.global})});_.command("status").description("Show current SEO project state").action(Xe);_.command("login").description("Connect this CLI to your seoagent.com account (browser flow)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{et({apiBase:e.apiBase})});_.command("logout").description("Remove stored credentials for seoagent.com").action(tt);_.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=>{le({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=>{st({force:e.force,silent:e.silent,print:e.print})});_.command("ack <action_id>").description("Close out a pending action from .seoagent/inbox/ (server marks completed)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{at(e,{failed:t.failed,reason:t.reason})});_.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)=>{lt(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("--api-base <url>","Override API base URL (for testing)").action(e=>{pt({peek:e.peek,discover:e.discover,competitors:e.competitors,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=>{dt({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=>{ft({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=>{ht({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=>{yt({json:e.json,apiBase:e.apiBase})});_.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(Qe);_.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=>{Ze({dryRun:e.dryRun})});_.parse();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seoagent-official/seoagent",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.40.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": {
|