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