@seoagent-official/seoagent 1.42.3 → 1.43.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 +70 -58
- 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 la}from"commander";import{dirname as Cr,relative as dn}from"path";import{intro as Ar,outro as Ir,text as pn,select as ft,spinner as Pr,isCancel as Q,cancel as Z,confirm as Rr}from"@clack/prompts";function Ze(e=process.argv[1]){let t=process.env.SEOAGENT_INSTALL_FORM;return t==="global"?!0:t==="npx"||!e?!1:(e.split(/[/\\]/).pop()??"").replace(/\.(cmd|ps1|exe)$/i,"").toLowerCase()==="seoagent"}function p(e,t=Ze()){return t?`seoagent ${e}`:`npx -y @seoagent-official/seoagent ${e}`}import{randomUUID as Po}from"crypto";import{existsSync as Lt,mkdirSync as jt,readFileSync as Ro,writeFileSync as Nt}from"fs";import{join as ot}from"path";var Y=[".env.local",".env.production",".env"],It=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];import{homedir as wo}from"os";import{join as Re}from"path";var $=".seoagent",Pt=["audit","strategy/clusters","briefs","content","content/images","performance"],M={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},Te=".claude/settings.json",Rt=".pull-receipt.json",Tt=`# SEOAgent local files
|
|
3
3
|
.legacy/
|
|
4
4
|
content/images/*
|
|
5
5
|
!content/images/.gitkeep
|
|
6
6
|
.pull-receipt.json
|
|
7
|
-
`,
|
|
8
|
-
`)}}function
|
|
7
|
+
`,ko=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:Re(wo(),".config"),T=Re(ko,"seoagent"),N=Re(T,"auth.json"),et=Re(T,"state");var ie="https://seoagent.com",q=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):ie,k={BASE:q,PRICING:`${q}/pricing`,LEAD_API:`${q}/api/cli/lead`,CLI_AUTH_PAGE:`${q}/cli/auth`,CLI_AUTH_POLL:`${q}/api/cli/auth/poll`,CLI_SYNC:`${q}/api/cli/sync`};import{readFileSync as bo}from"fs";import{fileURLToPath as $o}from"url";import{dirname as So,join as vo}from"path";var Ot="0.0.0";function xo(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return Ot}function _o(e=t=>bo(t,"utf-8")){try{let t=So($o(import.meta.url));return xo(e(vo(t,"package.json")))}catch{return Ot}}var J=_o();import{existsSync as Eo,readFileSync as Co}from"fs";var Oe="---";function Ao(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 tt(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==Oe)return{data:{},body:e};let n={},o=1;for(;o<t.length;o++){if(t[o].trim()===Oe){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]=Ao(a))}return{data:n,body:t.slice(o).join(`
|
|
8
|
+
`)}}function Le(e){if(!Eo(e))return null;try{return tt(Co(e,"utf-8"))}catch{return null}}function Io(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 nt(e,t=""){let n=[Oe];for(let[r,i]of Object.entries(e))i!==void 0&&n.push(`${r}: ${Io(i)}`);n.push(Oe);let o=t.length===0?"":t.startsWith(`
|
|
9
9
|
`)?t:`
|
|
10
10
|
${t}`;return n.join(`
|
|
11
11
|
`)+o+(o.endsWith(`
|
|
12
12
|
`)?"":`
|
|
13
|
-
`)}var
|
|
14
|
-
`)}function
|
|
15
|
-
`,"utf-8"),{file:t,added:!1}):(r.hooks.push({type:"command",command:
|
|
16
|
-
`,"utf-8"),{file:t,added:!0})}function
|
|
17
|
-
`,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{readFileSync as
|
|
18
|
-
`)}var Ko="context.md";function zo(e,t){let n=Wo(e,".seoagent",Ko),o=Jt(t);Go(n,o,"utf-8")}function Vt(e,t){zo(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as le,readFileSync as Xt,readdirSync as Ho,statSync as Qt}from"fs";import{join as G}from"path";var Yo=[{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 qo(e){let t=G(e,"package.json");if(!le(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Xt(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Jo(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 Y){let o=G(e,n);if(le(o))try{let r=Xt(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 Xo(e,t){let n=G(e,t.replace(/\/$/,""));if(!le(n))return!1;if(t.endsWith("/"))try{return Qt(n).isDirectory()}catch{return!1}return!0}function Qo(e){let t=["content","_posts","posts",G("src","content")];for(let n of t){let o=G(e,n);if(le(o))try{if(!Qt(o).isDirectory())continue;let r=[o],i=0;for(;r.length>0&&i<50;){let s=r.pop();for(let a of Ho(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&r.length<5){r.push(G(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 Zo(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(le(G(e,n.marker)))return n.path;return null}function Zt(e){let t=[],{deps:n}=qo(e),o=Vo(e),r="none";for(let s of Yo){let a=[];for(let l of Object.keys(n))if(Jo(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(Xo(e,l)){let d=l.endsWith("/")?"directory":"file";a.push({type:d,detail:l,source:l});break}if(a.length>0){r=s.cms,t.push(...a);break}}if(r==="none"){let s=Qo(e);s&&(r="mdx-local",t.push(s))}let i=Zo(e);return{cms:r,blog_path:i,evidence:t}}import{existsSync as W,readFileSync as st}from"fs";import{join as K}from"path";function en(e){try{return new URL(e).hostname}catch{return e}}function tn(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 er(e){for(let t of Y){let n=K(e,t);if(!W(n))continue;let o=st(n,"utf-8");for(let r of Et){let i=o.match(new RegExp(`^${r}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=en(s);if(tn(a))continue;return{value:a,source:`${t} (${r})`}}}}return null}function tr(e){let t=K(e,"package.json");if(!W(t))return null;try{let n=JSON.parse(st(t,"utf-8"));if(!n.homepage)return null;let o=en(n.homepage);return tn(o)?null:{value:o,source:"package.json (homepage)"}}catch{return null}}function nn(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),W(K(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=er(e);if(r)o=r.value,n.push({field:"domain",detail:r.value,source:r.source});else{t?.("Reading package.json homepage (skipping GitHub/GitLab repo URLs)\u2026");let a=tr(e);a&&(o=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=K(e,"package.json"),s=null;if(W(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(st(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),d=(...u)=>u.some(p=>l.includes(p));if(d("@shopify/hydrogen","@shopify/polaris")||W(K(e,"shopify.config.js"))||W(K(e,"shopify.config.ts"))){s="product";let u=d("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":W(K(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:u})}else{let u=d("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=d("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),g=d("next");u&&(g||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:g?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!u&&d("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:d("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:o,siteType:s,evidence:n}}import{existsSync as nr,readFileSync as or,readdirSync as rr,statSync as ir}from"fs";import{join as z,sep as sr}from"path";var on=["tsx","jsx","js","mdx","md"],ar=["astro","md","mdx"],lr=5e3;function Fe(e,t){let n=new Map,o=0,r=(i,s,a=!1)=>{let l=cr(i);if(l===null){o++;return}let d=n.get(l);if(d){d.in_sitemap=d.in_sitemap||a,d.source.includes(s)||(d.source+=`, ${s}`);return}n.set(l,{route:l,url:wr(t,l),in_sitemap:a,source:s})};for(let i of["app",z("src","app")]){let s=z(e,i);if(at(s))for(let a of lt(s)){let l=ct(s,a),d=l[l.length-1];mr(d)&&(l.some(u=>u.startsWith("@"))||r(ur(l.slice(0,-1)),"app router"))}}for(let i of["pages",z("src","pages")]){let s=z(e,i);if(at(s))for(let a of lt(s)){let l=ct(s,a);if(l[0]==="api")continue;let d=l[l.length-1],u=ut(d),p=on.includes(u),g=ar.includes(u);if(!p&&!g)continue;let A=Ue(d);gr(A)||r(dr(l),g?"astro":"pages router")}}for(let i of[".","public"]){let s=z(e,i);if(at(s))for(let a of lt(s,i==="."?1:1/0)){let l=ct(s,a),d=l[l.length-1];ut(d)==="html"&&(l.some(u=>u==="node_modules"||u.startsWith("."))||r(pr(l),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=z(e,...i.split("/"));if(nr(s)){for(let a of hr(s)){let l=fr(a);l!==null&&r(l,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:o}}function cr(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function ur(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function dr(e){let t=[...e],n=Ue(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function pr(e){let t=[...e],n=Ue(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function fr(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function mr(e){return Ue(e)==="page"&&on.includes(ut(e))}function gr(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function hr(e){try{let t=or(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 yr=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function at(e){try{return ir(e).isDirectory()}catch{return!1}}function*lt(e,t=1/0){let n=0;function*o(r,i){if(i>t)return;let s;try{s=rr(r,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=lr)return;if(a.name.startsWith("."))continue;let l=z(r,a.name);if(a.isDirectory()){if(yr.has(a.name))continue;yield*o(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*o(e,1)}function ct(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(sr).filter(Boolean)}function ut(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Ue(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function wr(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as kr,writeFileSync as br}from"fs";import{join as rn}from"path";function an(e,t){if(t.length===0)return;let n=rn(e,$);kr(n,{recursive:!0});let o=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
|
|
13
|
+
`)}var To=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rt(){return Po()}var Oo=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),Lo="project.md";function se(e){return ot(e,$)}function je(e){return ot(se(e),Lo)}function Ft(e){return Lt(je(e))}function b(e){let t=Le(je(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&&To.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 Ut(e){let t=b(e);if(!t)return null;if(t.install_id)return t.install_id;let n=rt();return ae(e,{install_id:n}),n}function jo(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 No(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 Dt(e,t){let n=se(e);jt(n,{recursive:!0});let o=nt(No(t),jo(t));Nt(je(e),o,"utf-8")}function ae(e,t){let n=je(e);if(!Lt(n))return!1;let o=tt(Ro(n,"utf-8")),r={...o.data,...t};return Nt(n,nt(r,o.body),"utf-8"),!0}function Bt(e){let t=se(e);for(let n of Pt)jt(ot(t,n),{recursive:!0})}import{existsSync as Ne,lstatSync as Fo,mkdirSync as le,readFileSync as Mt,readdirSync as Uo,rmSync as Do,statSync as Bo,symlinkSync as Mo,writeFileSync as Gt}from"fs";import{dirname as Fe,join as O,relative as Wt}from"path";import{fileURLToPath as Go}from"url";var Wo=Fe(Go(import.meta.url));function Kt(){return O(Wo,"skills")}function Ko(){let e=O(Kt(),"seoagent.md");if(Ne(e))return Mt(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function zt(e,t){let n=[];if(!Ne(e))return n;for(let o of Uo(e,{withFileTypes:!0})){let r=O(e,o.name),i=O(t,o.name);o.isDirectory()?(le(i,{recursive:!0}),n.push(...zt(r,i))):o.isFile()&&(le(Fe(i),{recursive:!0}),Gt(i,Mt(r)),n.push(i))}return n}function Ht(e,t){let n=Ne(O(e,".agents")),o=O(e,n?M.AGENTS:M.CLAUDE),r=O(o,"SKILL.md");le(o,{recursive:!0}),Gt(r,t??Ko(),"utf-8");let i=O(Kt(),"references"),s=O(o,"references"),a=[];try{Ne(i)&&Bo(i).isDirectory()&&(le(s,{recursive:!0}),a=zt(i,s).map(u=>Wt(o,u)))}catch{}let l=n?zo(e,o):void 0;return{skillFile:r,referenceFiles:a,claudeSymlink:l}}function zo(e,t){let n=O(e,M.CLAUDE),o=null;try{o=Fo(n)}catch{}if(o){if(!o.isSymbolicLink())return;try{Do(n,{force:!0})}catch{return}}try{le(Fe(n),{recursive:!0});let r=Wt(Fe(n),t);return Mo(r,n,"dir"),n}catch{return}}import{existsSync as Ue,mkdirSync as it,readFileSync as Ho,writeFileSync as ce}from"fs";import{dirname as Yt,join as V}from"path";var Yo="npx -y @seoagent-official/seoagent sync --silent";function qt(e){let t=V(e,$);it(t,{recursive:!0});let n=V(t,".gitignore");ce(n,Tt,"utf-8");let o=V(t,"content","images",".gitkeep");return it(Yt(o),{recursive:!0}),Ue(o)||ce(o,"","utf-8"),n}function st(e){if(!Ue(e))return{};try{let t=Ho(e,"utf-8");return JSON.parse(t)}catch{return{}}}function at(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function Jt(e){let t=V(e,Te);it(Yt(t),{recursive:!0});let n=st(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(at)?(ce(t,JSON.stringify(n,null,2)+`
|
|
15
|
+
`,"utf-8"),{file:t,added:!1}):(r.hooks.push({type:"command",command:Yo}),ce(t,JSON.stringify(n,null,2)+`
|
|
16
|
+
`,"utf-8"),{file:t,added:!0})}function Vt(e){let t=V(e,Te);if(!Ue(t))return!1;let n=st(t).hooks?.PostToolUse;return Array.isArray(n)?n.some(o=>o.hooks?.some(at)):!1}function Xt(e){let t=V(e,Te);if(!Ue(t))return{file:t,removed:!1};let n=st(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=>!at(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,ce(t,JSON.stringify(n,null,2)+`
|
|
17
|
+
`,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{readFileSync as Ha,writeFileSync as qo,existsSync as Ya}from"fs";import{join as Jo}from"path";function Qt(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 Vo="context.md";function Xo(e,t){let n=Jo(e,".seoagent",Vo),o=Qt(t);qo(n,o,"utf-8")}function Zt(e,t){Xo(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as ue,readFileSync as en,readdirSync as Qo,statSync as tn}from"fs";import{join as G}from"path";var Zo=[{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 er(e){let t=G(e,"package.json");if(!ue(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(en(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function tr(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 nr(e){let t={};for(let n of Y){let o=G(e,n);if(ue(o))try{let r=en(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 or(e,t){let n=G(e,t.replace(/\/$/,""));if(!ue(n))return!1;if(t.endsWith("/"))try{return tn(n).isDirectory()}catch{return!1}return!0}function rr(e){let t=["content","_posts","posts",G("src","content")];for(let n of t){let o=G(e,n);if(ue(o))try{if(!tn(o).isDirectory())continue;let r=[o],i=0;for(;r.length>0&&i<50;){let s=r.pop();for(let a of Qo(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&r.length<5){r.push(G(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 ir(e){let t=[{marker:"app/blog/page.tsx",path:"/blog"},{marker:"app/blog/page.jsx",path:"/blog"},{marker:"app/blog/page.js",path:"/blog"},{marker:"src/app/blog/page.tsx",path:"/blog"},{marker:"src/app/blog/page.jsx",path:"/blog"},{marker:"pages/blog/index.tsx",path:"/blog"},{marker:"pages/blog/index.jsx",path:"/blog"},{marker:"pages/blog/index.js",path:"/blog"},{marker:"src/pages/blog/index.tsx",path:"/blog"},{marker:"app/(blog)/page.tsx",path:"/blog"},{marker:"app/articles/page.tsx",path:"/articles"},{marker:"pages/articles/index.tsx",path:"/articles"},{marker:"app/posts/page.tsx",path:"/posts"},{marker:"pages/posts/index.tsx",path:"/posts"},{marker:"app/learn/page.tsx",path:"/learn"},{marker:"app/resources/page.tsx",path:"/resources"}];for(let n of t)if(ue(G(e,n.marker)))return n.path;return null}function nn(e){let t=[],{deps:n}=er(e),o=nr(e),r="none";for(let s of Zo){let a=[];for(let l of Object.keys(n))if(tr(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(or(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=rr(e);s&&(r="mdx-local",t.push(s))}let i=ir(e);return{cms:r,blog_path:i,evidence:t}}import{existsSync as W,readFileSync as lt}from"fs";import{join as K}from"path";function on(e){try{return new URL(e).hostname}catch{return e}}function rn(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 sr(e){for(let t of Y){let n=K(e,t);if(!W(n))continue;let o=lt(n,"utf-8");for(let r of It){let i=o.match(new RegExp(`^${r}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=on(s);if(rn(a))continue;return{value:a,source:`${t} (${r})`}}}}return null}function ar(e){let t=K(e,"package.json");if(!W(t))return null;try{let n=JSON.parse(lt(t,"utf-8"));if(!n.homepage)return null;let o=on(n.homepage);return rn(o)?null:{value:o,source:"package.json (homepage)"}}catch{return null}}function sn(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),W(K(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=sr(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=ar(e);a&&(o=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=K(e,"package.json"),s=null;if(W(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(lt(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(f=>l.includes(f));if(u("@shopify/hydrogen","@shopify/polaris")||W(K(e,"shopify.config.js"))||W(K(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":W(K(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"),f=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),g=u("next");d&&(g||f)?(s="saas",n.push({field:"site_type",detail:"saas",source:g?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:o,siteType:s,evidence:n}}import{existsSync as lr,readFileSync as cr,readdirSync as ur,statSync as dr}from"fs";import{join as z,sep as pr}from"path";var an=["tsx","jsx","js","mdx","md"],fr=["astro","md","mdx"],mr=5e3;function De(e,t){let n=new Map,o=0,r=(i,s,a=!1)=>{let l=gr(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:xr(t,l),in_sitemap:a,source:s})};for(let i of["app",z("src","app")]){let s=z(e,i);if(ct(s))for(let a of ut(s)){let l=dt(s,a),u=l[l.length-1];br(u)&&(l.some(d=>d.startsWith("@"))||r(hr(l.slice(0,-1)),"app router"))}}for(let i of["pages",z("src","pages")]){let s=z(e,i);if(ct(s))for(let a of ut(s)){let l=dt(s,a);if(l[0]==="api")continue;let u=l[l.length-1],d=pt(u),f=an.includes(d),g=fr.includes(d);if(!f&&!g)continue;let A=Be(u);$r(A)||r(yr(l),g?"astro":"pages router")}}for(let i of[".","public"]){let s=z(e,i);if(ct(s))for(let a of ut(s,i==="."?1:1/0)){let l=dt(s,a),u=l[l.length-1];pt(u)==="html"&&(l.some(d=>d==="node_modules"||d.startsWith("."))||r(wr(l),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=z(e,...i.split("/"));if(lr(s)){for(let a of Sr(s)){let l=kr(a);l!==null&&r(l,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:o}}function gr(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function hr(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function yr(e){let t=[...e],n=Be(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function wr(e){let t=[...e],n=Be(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function kr(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function br(e){return Be(e)==="page"&&an.includes(pt(e))}function $r(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Sr(e){try{let t=cr(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 vr=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function ct(e){try{return dr(e).isDirectory()}catch{return!1}}function*ut(e,t=1/0){let n=0;function*o(r,i){if(i>t)return;let s;try{s=ur(r,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=mr)return;if(a.name.startsWith("."))continue;let l=z(r,a.name);if(a.isDirectory()){if(vr.has(a.name))continue;yield*o(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*o(e,1)}function dt(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(pr).filter(Boolean)}function pt(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Be(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function xr(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as _r,writeFileSync as Er}from"fs";import{join as ln}from"path";function un(e,t){if(t.length===0)return;let n=ln(e,$);_r(n,{recursive:!0});let o=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
|
|
19
19
|
`),r=["# Pages","","Inventory of pages discovered in your codebase at setup. Status,","rendered, and in-nav are filled in by the Phase 1 audit. Add or remove","rows freely \u2014 this file syncs to the cloud when you log in."].join(`
|
|
20
|
-
`),i="| URL | In sitemap | In nav | Status | Rendered | Notes |",s="|---|---|---|---|---|---|",a=t.map(
|
|
21
|
-
`);
|
|
22
|
-
`))}import{existsSync as
|
|
23
|
-
`);if(!o){
|
|
24
|
-
${r}`);let s=await
|
|
20
|
+
`),i="| URL | In sitemap | In nav | Status | Rendered | Notes |",s="|---|---|---|---|---|---|",a=t.map(u=>`| ${cn(u.url)} | ${u.in_sitemap?"yes":"no"} | \u2014 | \u2014 | \u2014 | ${cn(u.source)} |`),l=[o,"",r,"",i,s,...a,""].join(`
|
|
21
|
+
`);Er(ln(n,"pages.md"),l,"utf-8")}function cn(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as X}from"@clack/prompts";var c={info:e=>X.info(e),warn:e=>X.warn(e),error:e=>X.error(e),success:e=>X.success(e),step:e=>X.step(e),message:e=>X.message(e)};function y(e,t,n,o=n){e?e.stop(o):c[t](n)}var fn=[{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"}],gn="unknown",Tr=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 Tr.has(t)?t:null}async function de(e={}){let t=process.cwd();if(Ft(t)){c.warn("SEOAgent project already exists in this directory."),c.info(`Run \`${p("status")}\` to see your project state.`),c.info(`To start fresh, run \`${p("uninstall")}\` then init again.`);return}let n=!!e.yes||!process.stdin.isTTY;n||Ar("SEOAgent \u2014 AI SEO Agent");let o=sn(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=gn),s||(s="unknown"),await mn(t,i,s);return}if(r(),!i){let a=await pn({message:"Website domain",placeholder:"example.com",validate:l=>l.trim()?void 0:"Domain is required"});Q(a)&&(Z("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await ft({message:"What kind of site is this?",options:[...fn]});Q(a)&&(Z("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Rr({message:`Create .seoagent for ${i} (${s})?`});if(Q(a)&&(Z("Cancelled"),process.exit(0)),a)break;let l=await ft({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((Q(l)||l==="abort")&&(Z("Cancelled"),process.exit(0)),l==="domain"){let u=await pn({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});Q(u)&&(Z("Cancelled"),process.exit(0)),i=String(u)}else{let u=await ft({message:"What kind of site is this?",options:[...fn]});Q(u)&&(Z("Cancelled"),process.exit(0)),s=u}}await mn(t,i,s)}async function mn(e,t,n){let o=Pr();o.start("Setting up your SEO project");let r=nn(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:J,install_id:rt(),...r.cms!=="none"?{cms:r.cms}:{},...r.blog_path?{blog_path:r.blog_path}:{}};Bt(e),Dt(e,i),Zt(e,n),qt(e);let s=Ht(e),a=dn(e,s.skillFile),l=Cr(a),u=`${l}/references/audit-checks.md`,d=s.claudeSymlink?dn(e,s.claudeSymlink):void 0;Jt(e);let f=t!==gn,g={pages:[],dynamicCount:0};try{g=De(e,f?t:null),un(e,g.pages)}catch{}if(o.stop(f?`Created .seoagent/ project for ${i.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),r.cms!=="none"){let B=r.evidence.map(R=>`${R.detail} (${R.source})`).slice(0,2).join(", ");c.info(`CMS detected: ${r.cms} \u2014 ${B}`)}r.blog_path&&c.info(`Blog route: ${r.blog_path}`),g.pages.length>0&&c.info(`Found ${g.pages.length} page${g.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`+(g.dynamicCount>0?` (plus ${g.dynamicCount} dynamic route template${g.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""));let A=f?i.domain:"your site",j=f?[" 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."];Ir([f?`\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):","",...j,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${A}`," (homepage + sitemap + robots.txt; the checks live in",` ${u} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${p("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${a} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${l} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${p("login")}`,""].join(`
|
|
22
|
+
`))}import{existsSync as wn}from"fs";import{intro as jr,outro as Nr,confirm as Fr,isCancel as Ur,cancel as Dr}from"@clack/prompts";import{existsSync as Ge,rmSync as Lr}from"fs";import{join as We}from"path";function hn(e,t={}){let n=[],o=We(e,$);Ge(o)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:o,kind:"dir"});let r=We(e,M.CLAUDE);Ge(r)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:r,kind:"dir"});let i=We(e,M.AGENTS);return Ge(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),Vt(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:We(e,".claude","settings.json"),kind:"hook"}),t.global&&Ge(T)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:T,kind:"global"}),n}function yn(e,t){for(let n of t)n.kind==="hook"?Xt(e):Lr(n.path,{recursive:!0,force:!0})}async function pe(e={}){let t=process.cwd(),n=hn(t,{global:e.global});if(n.length===0){c.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&wn(T)&&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){jr("SEOAgent \u2014 uninstall"),c.message(`This will remove:
|
|
24
|
+
${r}`);let s=await Fr({message:"Remove these and start fresh?"});if(Ur(s)||!s){Dr("Cancelled \u2014 nothing was removed.");return}}yn(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
|
|
25
25
|
`);o?c.success(`Removed:
|
|
26
|
-
${i}`):
|
|
27
|
-
${i}`),!e.global&&
|
|
28
|
-
`,"utf-8");try{
|
|
29
|
-
`)}function qr(e,t){if(!t)return F.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Sn(t),o=e-5-n;return o<1?F.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${F.dim("\u250C\u2500 ")}${t}${F.dim(` ${"\u2500".repeat(o)}\u2510`)}`}function Jr(e,t){let n=Sn(e),o;return n<=t?o=e+" ".repeat(t-n):o=e,`${F.dim("\u2502")} ${o} ${F.dim("\u2502")}`}function ft(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 pe(){let e=$n(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${f("init")}\` to get started.`);return}c.message(Vr(e))}function Vr(e){if(!e)return"";let t=11,n=s=>w.dim(s.padEnd(t)),o=[];x()?(o.push({content:`${w.green("\u2713")} ${w.dim("Logged in")}`}),o.push({content:w.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(o.push({content:`${w.dim("\u25CB Not logged in")}`}),o.push({content:w.dim(` Run \`${f("login")}\` to connect.`)})),o.push({sep:!0}),o.push({content:e.audit?.exists?`${n("Audit:")}${w.green(`last run ${ft(e.audit.date??"")}`)} ${w.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${w.dim("not yet run")}`}),o.push({content:e.strategy?.exists?`${n("Strategy:")}${w.bold(w.cyan(String(e.strategy.clusterCount??0)))} ${w.dim("clusters")} \xB7 ${w.bold(w.cyan(String(e.strategy.articleCount??0)))} ${w.dim("ideas")}`:`${n("Strategy:")}${w.dim("not yet created")}`}),o.push({content:e.briefs?.exists?`${n("Briefs:")}${w.bold(w.cyan(String(e.briefs.count??0)))} ${w.dim("ready")}`:`${n("Briefs:")}${w.dim("none created")}`}),o.push({content:e.content?.exists?`${n("Content:")}${w.green("\u2713")} ${w.bold(w.cyan(String(e.content.count??0)))} ${w.dim("articles written")}`:`${n("Content:")}${w.dim("no articles yet")}`}),o.push({content:e.roadmap?.exists?`${n("Roadmap:")}${w.green("updated")} ${w.dim(ft(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${w.dim("not yet created")}`});let i=`${w.bold(w.cyan("SEOAgent"))} ${w.dim("\xB7")} ${w.bold(e.domain)}`;return I(o,{width:78,title:i})}import{exec as Xr,spawn as Qr}from"child_process";import{confirm as Zr,isCancel as ei}from"@clack/prompts";import C from"picocolors";var ti="https://registry.npmjs.org/@seoagent-official/seoagent/latest",fe="@seoagent-official/seoagent",me=["free","starter","pro","scale","enterprise"],Ge={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function ni(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return me.includes(t)?t:null}function oi(e){let t=me.indexOf(e);return t===-1||t===me.length-1?null:me[t+1]}async function ri(e,t=fetch){if(!e)return null;try{let n=(e.api_base||k.BASE).replace(/\/$/,""),o=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!o.ok)return null;let r=await o.json();return typeof r.plan!="string"||!r.plan?null:{plan:r.plan,email:typeof r.email=="string"&&r.email?r.email:void 0,domain:typeof r.domain=="string"&&r.domain?r.domain:void 0}}catch{return null}}function ii(e){let t=[],o=s=>C.dim(s.padEnd(10)),r=!1;e.email&&(t.push({content:`${o("Email:")}${C.bold(e.email)}`}),r=!0),e.domain&&(t.push({content:`${o("Website:")}${C.cyan(e.domain)}`}),r=!0),r&&t.push({sep:!0});for(let s of me){let a=Ge[s];s===e.current?t.push({content:`${C.bold(C.green("\u25CF"))} ${C.bold(C.green(a.padEnd(11)))} ${C.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${C.yellow("\u25C6")} ${C.bold(C.yellow(a.padEnd(11)))} ${C.yellow("next tier")}`}):t.push({content:C.dim(` ${a}`)})}let i=`${C.bold(C.cyan("SEOAgent Cloud"))} ${C.dim("\xB7")} ${C.dim("your plan")}`;return I(t,{width:55,title:i})}async function ge(){let e=x(),t=!!process.stdin.isTTY;if(e&&t){let n=await ri(e);if(n){let o=ni(n.plan),r=o?oi(o):null;if(o&&c.message(ii({email:n.email,domain:n.domain,current:o,next:r})),o&&!r){c.success(`You're on ${Ge[o]} (highest tier).`);return}if(o&&r){let i=await Zr({message:`Upgrade from ${Ge[o]} to ${Ge[r]}?`});if(ei(i)||!i){c.info("No changes.");return}}}}si()}function si(){let e=ai();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}"`;Xr(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function ai(){let e=process.cwd(),t=b(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${k.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function he(e={}){let t=J,n=await ci();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 ${fe}@latest`);return}if(li(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 ${fe}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${fe}@latest`);return}c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),await ui()?c.success(`Updated to ${n}.`):c.error(`Update failed. Try manually: npm install -g ${fe}@latest (you may need sudo on Linux/macOS).`)}function li(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 ci(e=fetch){try{let t=await e(ti,{headers:{Accept:"application/json"}});if(!t.ok)return null;let n=await t.json();return typeof n.version=="string"?n.version:null}catch{return null}}function ui(){return new Promise(e=>{let t=Qr("npm",["install","-g",`${fe}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as di}from"child_process";import{randomBytes as pi}from"crypto";import{isCancel as fi,spinner as mi,text as gi}from"@clack/prompts";import U from"picocolors";function vn(e,t){if(e>=500)return{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e>=400)return{status:"error",terminal:!0,message:`HTTP ${e} (client error)`};if(!t||typeof t!="object")return{status:"error",terminal:!0,message:`Malformed response: expected an object, got ${typeof t}`};let n=t;if(n.status==="ready"){if(typeof n.user_token=="string"&&typeof n.website_token=="string"){let o=typeof n.email=="string"&&n.email?n.email:void 0,r=typeof n.domain=="string"&&n.domain?n.domain:void 0;return{status:"ready",user_token:n.user_token,website_token:n.website_token,...o?{email:o}:{},...r?{domain:r}:{}}}return{status:"error",terminal:!0,message:"Malformed response: status=ready without user_token+website_token"}}return n.status==="pending"?{status:"pending"}:n.status==="expired"?{status:"expired"}:{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}var hi=1500,yi=300*1e3;function wi(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;di(t,()=>{})}function ki(){return pi(16).toString("hex")}function bi(e,t,n){let o=new URLSearchParams({session:t});return n&&n!=="unknown"&&o.set("domain",n),`${e}/cli/auth?${o.toString()}`}function xn(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 $i(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 vn(o.status,r)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Si(e){return new Promise(t=>setTimeout(t,e))}async function ye(e={}){let t=process.cwd(),n=b(t),o=(e.apiBase||k.BASE||oe).replace(/\/$/,"");if(x()){c.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let r=n?.domain??null;if(r==="unknown"&&process.stdin.isTTY){let p=await gi({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(A){if(!String(A??"").trim())return"A site URL is required.";if(!xn(String(A)))return"Please enter a valid domain like `example.com`."}});if(fi(p)){c.warn("Login cancelled.");return}let g=xn(String(p));if(g){r=g;try{ie(t,{domain:g}),c.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=ki(),s=bi(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}`),wi(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?mi():null;l?.start(U.dim("Waiting for browser confirmation\u2026"));let d=Date.now()+yi,u=!0;for(;Date.now()<d;){u||await Si(hi),u=!1;let p=await $i(o,i);if(p.status==="ready"){wn({user_token:p.user_token,website_token:p.website_token,api_base:o});let g=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",A=p.email&&p.domain?`Logged in as ${U.bold(p.email)} (${U.cyan(p.domain)}).`:p.email?`Logged in as ${U.bold(p.email)}.`:"Logged in.";y(l,"success",g,U.green(A)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){y(l,"warn",`Session expired. Run \`${f("login")}\` again.`,U.red("Session expired.")),l&&c.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){y(l,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,U.red(`Login failed: ${p.message}.`)),l&&c.warn(`Run \`${f("login")}\` again.`);return}continue}}y(l,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,U.yellow("Login timed out.")),l&&c.warn(`Run \`${f("login")}\` again to retry.`)}function we(){kn()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as ls}from"@clack/prompts";import ke from"picocolors";import{existsSync as ht,mkdirSync as qi,readFileSync as Nn,readdirSync as Ji,statSync as Vi,writeFileSync as Xi}from"fs";import{join as yt,relative as Qi,sep as Zi}from"path";import{existsSync as vi,mkdirSync as xi,readdirSync as _i,unlinkSync as Ei,writeFileSync as _n}from"fs";import{join as We}from"path";function mt(e){return We(e,$,"inbox")}function En(e){return`${e.action_type}-${e.id}.md`}function Ci(e,t){let n=0;if(!vi(e))return 0;for(let o of _i(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(We(e,o)),n++}catch{}}return n}function Ai(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}`):Nr(`Removed:
|
|
27
|
+
${i}`),!e.global&&wn(T)&&c.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),c.info(`Re-install any time with \`${p("init")}\`.`)}import w from"picocolors";import{existsSync as bn,mkdirSync as kn,readFileSync as Br,writeFileSync as Mr,chmodSync as Gr,unlinkSync as Wr}from"fs";import{dirname as Kr}from"path";function x(){if(!bn(N))return null;try{let e=JSON.parse(Br(N,"utf-8"));return!e.user_token||!e.website_token?null:{user_token:e.user_token,website_token:e.website_token,api_base:e.api_base||ie}}catch{return null}}function $n(e){kn(T,{recursive:!0}),kn(Kr(N),{recursive:!0}),Mr(N,JSON.stringify(e,null,2)+`
|
|
28
|
+
`,"utf-8");try{Gr(N,384)}catch{}}function Sn(){if(!bn(N))return!1;try{return Wr(N),!0}catch{return!1}}import{existsSync as fe,readdirSync as mt,statSync as zr,readFileSync as vn}from"fs";import{join as ee}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=ee(e,"audit","latest.md");if(!fe(t))return null;let n=Le(t);if(!n)return null;let o=vn(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 qr(e){try{let n=vn(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 Jr(e){let t=ee(e,"strategy","clusters");if(!fe(t))return null;let n=mt(t).filter(r=>r.endsWith(".md"));if(n.length===0)return null;let o=0;for(let r of n)o+=qr(ee(t,r));return{exists:!0,clusterCount:n.length,articleCount:o}}function Vr(e){let t=ee(e,"briefs");if(!fe(t))return null;let n=mt(t).filter(o=>o.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Xr(e){let t=ee(e,"content");if(!fe(t))return null;let n=mt(t).filter(o=>o.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function Qr(e){let t=ee(e,"roadmap.md");return fe(t)?{exists:!0,updatedAt:zr(t).mtime.toISOString()}:null}function xn(e){let t=b(e);if(!t)return null;let n=se(e);return{domain:t.domain,audit:Yr(n),strategy:Jr(n),briefs:Vr(n),content:Xr(n),roadmap:Qr(n)}}import F from"picocolors";var Zr=/\x1b\[[0-9;]*m/g;function _n(e){return e.replace(Zr,"").length}function I(e,t={}){let n=t.width??51,o=n-4,r="\u2500".repeat(n-2),i=ei(n,t.title),s=F.dim(`\u251C${r}\u2524`),a=F.dim(`\u2514${r}\u2518`),l=[i];for(let u of e){if("sep"in u){l.push(s);continue}l.push(ti(u.content,o))}return l.push(a),l.join(`
|
|
29
|
+
`)}function ei(e,t){if(!t)return F.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=_n(t),o=e-5-n;return o<1?F.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${F.dim("\u250C\u2500 ")}${t}${F.dim(` ${"\u2500".repeat(o)}\u2510`)}`}function ti(e,t){let n=_n(e),o;return n<=t?o=e+" ".repeat(t-n):o=e,`${F.dim("\u2502")} ${o} ${F.dim("\u2502")}`}function gt(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 me(){let e=xn(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${p("init")}\` to get started.`);return}c.message(ni(e))}function ni(e){if(!e)return"";let t=11,n=s=>w.dim(s.padEnd(t)),o=[];x()?(o.push({content:`${w.green("\u2713")} ${w.dim("Logged in")}`}),o.push({content:w.dim(` Run \`${p("whoami")}\` for email / plan.`)})):(o.push({content:`${w.dim("\u25CB Not logged in")}`}),o.push({content:w.dim(` Run \`${p("login")}\` to connect.`)})),o.push({sep:!0}),o.push({content:e.audit?.exists?`${n("Audit:")}${w.green(`last run ${gt(e.audit.date??"")}`)} ${w.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${w.dim("not yet run")}`}),o.push({content:e.strategy?.exists?`${n("Strategy:")}${w.bold(w.cyan(String(e.strategy.clusterCount??0)))} ${w.dim("clusters")} \xB7 ${w.bold(w.cyan(String(e.strategy.articleCount??0)))} ${w.dim("ideas")}`:`${n("Strategy:")}${w.dim("not yet created")}`}),o.push({content:e.briefs?.exists?`${n("Briefs:")}${w.bold(w.cyan(String(e.briefs.count??0)))} ${w.dim("ready")}`:`${n("Briefs:")}${w.dim("none created")}`}),o.push({content:e.content?.exists?`${n("Content:")}${w.green("\u2713")} ${w.bold(w.cyan(String(e.content.count??0)))} ${w.dim("articles written")}`:`${n("Content:")}${w.dim("no articles yet")}`}),o.push({content:e.roadmap?.exists?`${n("Roadmap:")}${w.green("updated")} ${w.dim(gt(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${w.dim("not yet created")}`});let i=`${w.bold(w.cyan("SEOAgent"))} ${w.dim("\xB7")} ${w.bold(e.domain)}`;return I(o,{width:78,title:i})}import{exec as oi,spawn as ri}from"child_process";import{confirm as ii,isCancel as si}from"@clack/prompts";import C from"picocolors";var ai="https://registry.npmjs.org/@seoagent-official/seoagent/latest",ge="@seoagent-official/seoagent",he=["free","starter","pro","scale","enterprise"],Ke={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function li(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return he.includes(t)?t:null}function ci(e){let t=he.indexOf(e);return t===-1||t===he.length-1?null:he[t+1]}async function ui(e,t=fetch){if(!e)return null;try{let n=(e.api_base||k.BASE).replace(/\/$/,""),o=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!o.ok)return null;let r=await o.json();return typeof r.plan!="string"||!r.plan?null:{plan:r.plan,email:typeof r.email=="string"&&r.email?r.email:void 0,domain:typeof r.domain=="string"&&r.domain?r.domain:void 0}}catch{return null}}function di(e){let t=[],o=s=>C.dim(s.padEnd(10)),r=!1;e.email&&(t.push({content:`${o("Email:")}${C.bold(e.email)}`}),r=!0),e.domain&&(t.push({content:`${o("Website:")}${C.cyan(e.domain)}`}),r=!0),r&&t.push({sep:!0});for(let s of he){let a=Ke[s];s===e.current?t.push({content:`${C.bold(C.green("\u25CF"))} ${C.bold(C.green(a.padEnd(11)))} ${C.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${C.yellow("\u25C6")} ${C.bold(C.yellow(a.padEnd(11)))} ${C.yellow("next tier")}`}):t.push({content:C.dim(` ${a}`)})}let i=`${C.bold(C.cyan("SEOAgent Cloud"))} ${C.dim("\xB7")} ${C.dim("your plan")}`;return I(t,{width:55,title:i})}async function ye(){let e=x(),t=!!process.stdin.isTTY;if(e&&t){let n=await ui(e);if(n){let o=li(n.plan),r=o?ci(o):null;if(o&&c.message(di({email:n.email,domain:n.domain,current:o,next:r})),o&&!r){c.success(`You're on ${Ke[o]} (highest tier).`);return}if(o&&r){let i=await ii({message:`Upgrade from ${Ke[o]} to ${Ke[r]}?`});if(si(i)||!i){c.info("No changes.");return}}}}pi()}function pi(){let e=fi();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}"`;oi(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function fi(){let e=process.cwd(),t=b(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${k.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function we(e={}){let t=J,n=await gi();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 ${ge}@latest`);return}if(mi(t,n)>=0){c.success(`You're on the latest CLI (${t}).`);return}if(!Ze()){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 ${ge}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${ge}@latest`);return}c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),await hi()?c.success(`Updated to ${n}.`):c.error(`Update failed. Try manually: npm install -g ${ge}@latest (you may need sudo on Linux/macOS).`)}function mi(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 gi(e=fetch){try{let t=await e(ai,{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 hi(){return new Promise(e=>{let t=ri("npm",["install","-g",`${ge}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as yi}from"child_process";import{randomBytes as wi}from"crypto";import{isCancel as ki,spinner as bi,text as $i}from"@clack/prompts";import U from"picocolors";function En(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 Si=1500,vi=300*1e3;function xi(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;yi(t,()=>{})}function _i(){return wi(16).toString("hex")}function Ei(e,t,n){let o=new URLSearchParams({session:t});return n&&n!=="unknown"&&o.set("domain",n),`${e}/cli/auth?${o.toString()}`}function Cn(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 Ci(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 En(o.status,r)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Ai(e){return new Promise(t=>setTimeout(t,e))}async function ke(e={}){let t=process.cwd(),n=b(t),o=(e.apiBase||k.BASE||ie).replace(/\/$/,"");if(x()){c.info(`Already logged in. To switch accounts, run \`${p("logout")}\` first.`);return}let r=n?.domain??null;if(r==="unknown"&&process.stdin.isTTY){let f=await $i({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(A){if(!String(A??"").trim())return"A site URL is required.";if(!Cn(String(A)))return"Please enter a valid domain like `example.com`."}});if(ki(f)){c.warn("Login cancelled.");return}let g=Cn(String(f));if(g){r=g;try{ae(t,{domain:g}),c.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=_i(),s=Ei(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}`),xi(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?bi():null;l?.start(U.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+vi,d=!0;for(;Date.now()<u;){d||await Ai(Si),d=!1;let f=await Ci(o,i);if(f.status==="ready"){$n({user_token:f.user_token,website_token:f.website_token,api_base:o});let g=f.email&&f.domain?`Logged in as ${f.email} (${f.domain}). Future SEO work in this repo will sync to your dashboard.`:f.email?`Logged in as ${f.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",A=f.email&&f.domain?`Logged in as ${U.bold(f.email)} (${U.cyan(f.domain)}).`:f.email?`Logged in as ${U.bold(f.email)}.`:"Logged in.";y(l,"success",g,U.green(A)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(f.status==="expired"){y(l,"warn",`Session expired. Run \`${p("login")}\` again.`,U.red("Session expired.")),l&&c.warn(`Run \`${p("login")}\` again.`);return}if(f.status==="error"){if(f.terminal){y(l,"warn",`Login failed: ${f.message}. Run \`${p("login")}\` again.`,U.red(`Login failed: ${f.message}.`)),l&&c.warn(`Run \`${p("login")}\` again.`);return}continue}}y(l,"warn",`Login timed out. Run \`${p("login")}\` again to retry.`,U.yellow("Login timed out.")),l&&c.warn(`Run \`${p("login")}\` again to retry.`)}function be(){Sn()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as ys}from"@clack/prompts";import $e from"picocolors";import{existsSync as kt,mkdirSync as os,readFileSync as Mn,readdirSync as rs,statSync as is,writeFileSync as ss}from"fs";import{join as bt,relative as as,sep as ls}from"path";var Ii=new Set([502,503,504]);async function te(e,t,n={}){let o=Math.max(1,n.attempts??3),r=Math.max(0,n.baseDelayMs??500),i=n.fetchImpl??fetch,s=n.sleep??Pi,a=n.transientStatuses??Ii,l=null;for(let u=0;u<o;u++)try{let d=await i(e,t);if(a.has(d.status)&&u<o-1){await s(An(r,u));continue}return d}catch(d){if(l=d,u<o-1){await s(An(r,u));continue}}throw l instanceof Error?l:new Error(String(l))}function An(e,t){return e*Math.pow(3,t)}function Pi(e){return new Promise(t=>setTimeout(t,e))}import{existsSync as In,mkdirSync as Ri,readdirSync as Pn,readFileSync as Ti,unlinkSync as Oi,writeFileSync as ht}from"fs";import{join as ne}from"path";function ze(e){return ne(e,$,"inbox")}function Rn(e){return`${e.action_type}-${e.id}.md`}function Li(e,t){let n=0;if(!In(e))return 0;for(let o of Pn(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{Oi(ne(e,o)),n++}catch{}}return n}function ji(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}
|
|
@@ -59,7 +59,7 @@ typically that's a markdown or MDX file matching the slug under \`content/\`,
|
|
|
59
59
|
After deleting (and committing if you want), run:
|
|
60
60
|
|
|
61
61
|
\`\`\`bash
|
|
62
|
-
|
|
62
|
+
${p(`ack ${e.id}`)}
|
|
63
63
|
\`\`\`
|
|
64
64
|
|
|
65
65
|
That marks the action \`completed\` server-side and removes this inbox file
|
|
@@ -67,9 +67,10 @@ on the next \`seoagent sync\`. If you decided NOT to remove the file (false
|
|
|
67
67
|
positive, you disagree, etc.), close it out as failed with a reason:
|
|
68
68
|
|
|
69
69
|
\`\`\`bash
|
|
70
|
-
|
|
70
|
+
${p(`ack ${e.id}`)} --failed --reason "kept; performs well off-search"
|
|
71
71
|
\`\`\`
|
|
72
|
-
`}function
|
|
72
|
+
`}function Ni(e){switch(e){case"meta":return"Apply the **meta** fix \u2014 set the page's `<title>` / `<meta name=\"description\">` (or the framework's metadata API / frontmatter).";case"schema":return"Apply the **schema** fix \u2014 add or correct the JSON-LD structured data on the page.";case"canonical":return'Apply the **canonical** fix \u2014 set the correct `<link rel="canonical">` on the page.';case"internal_link":return"Apply the **internal_link** fix \u2014 add relevant internal links from related pages (look for high-authority pages on the same topic).";default:return["Apply the change for this issue:",' - **meta** \u2014 fix the `<title>` / `<meta name="description">` (or the framework\'s metadata API / frontmatter).'," - **schema** \u2014 add or correct JSON-LD structured data.",' - **canonical** \u2014 set the correct `<link rel="canonical">`.'," - **internal_link** \u2014 add relevant internal links (fix orphan/low-link pages)."," - **other** \u2014 follow the recommendation above."].join(`
|
|
73
|
+
`)}}function Fi(e,t,n){if(n)return`Locate the page's source. It renders at \`${n}\` \u2014 find the matching route/template/markdown in this repo (look under \`app/\`, \`pages/\`, \`src/\`, \`content/\`).`;let o=(t||"").toLowerCase();return o.includes("robots")||o.includes("ai_bot")||o.includes("bot_policy")?"This is a site-wide policy issue. Edit `robots.txt` at the site root (or its generator \u2014 `app/robots.ts`, `public/robots.txt`, etc.) to add the appropriate `User-agent:` / `Allow:` / `Disallow:` rules.":o.includes("sitemap")?"This is a sitemap configuration issue. Edit your sitemap generator \u2014 `app/sitemap.ts`, `pages/sitemap.xml.ts`, `next-sitemap.config.js`, or the static `public/sitemap.xml`.":e==="canonical"?'This is a site-wide canonical pattern. Look in the layout/template that wraps your pages (e.g. `app/layout.tsx`, `_app.tsx`, theme `head` partial) \u2014 that\'s where the `<link rel="canonical">` is set for every page.':e==="schema"?"This is a site-wide schema gap. Apply JSON-LD to the layout/template (for Organization-level schema) or to specific page templates (for Article / Product / FAQPage etc.).":e==="meta"?"This is a site-wide metadata convention. Look at the page-template metadata \u2014 Next.js `generateMetadata()` / `metadata` export, Nuxt `useHead()`, Astro frontmatter, etc.":e==="internal_link"?"No specific page on file. Identify pages on the same topic/cluster from `.seoagent/strategy/clusters/` and add inbound links to the target page.":"This issue does not name a single page. Read the recommendation above, identify the relevant template/config in this repo, and apply the change there."}function Ui(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
74
|
action_id: ${e.id}
|
|
74
75
|
action_type: ${e.action_type}
|
|
75
76
|
issue: ${o}
|
|
@@ -92,13 +93,8 @@ ${s??e.description??"Apply the appropriate fix for this issue."}
|
|
|
92
93
|
|
|
93
94
|
## How to apply
|
|
94
95
|
|
|
95
|
-
1.
|
|
96
|
-
2.
|
|
97
|
-
- **meta** \u2014 fix the \`<title>\` / \`<meta name="description">\` (or the framework's metadata API / frontmatter).
|
|
98
|
-
- **schema** \u2014 add or correct JSON-LD structured data.
|
|
99
|
-
- **canonical** \u2014 set the correct \`<link rel="canonical">\`.
|
|
100
|
-
- **internal_link** \u2014 add relevant internal links (fix orphan/low-link pages).
|
|
101
|
-
- **other** \u2014 follow the recommendation above.
|
|
96
|
+
1. ${Fi(o,r,n)}
|
|
97
|
+
2. ${Ni(o)}
|
|
102
98
|
3. Show the user the diff before committing (confirm once per session, then proceed).
|
|
103
99
|
|
|
104
100
|
## How to close this out
|
|
@@ -106,16 +102,16 @@ ${s??e.description??"Apply the appropriate fix for this issue."}
|
|
|
106
102
|
After applying:
|
|
107
103
|
|
|
108
104
|
\`\`\`bash
|
|
109
|
-
|
|
105
|
+
${p(`ack ${e.id}`)}
|
|
110
106
|
\`\`\`
|
|
111
107
|
|
|
112
108
|
That marks the action \`completed\` server-side and removes this inbox file on the
|
|
113
109
|
next \`seoagent sync\`. If you disagree or it's a false positive, decline it:
|
|
114
110
|
|
|
115
111
|
\`\`\`bash
|
|
116
|
-
|
|
112
|
+
${p(`ack ${e.id}`)} --failed --reason "not applicable; ..."
|
|
117
113
|
\`\`\`
|
|
118
|
-
`}function
|
|
114
|
+
`}function Di(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
115
|
action_id: ${e.id}
|
|
120
116
|
action_type: ${e.action_type}
|
|
121
117
|
brief_slug: ${n??""}
|
|
@@ -156,15 +152,15 @@ is auto-generated.
|
|
|
156
152
|
After writing (and publishing/committing):
|
|
157
153
|
|
|
158
154
|
\`\`\`bash
|
|
159
|
-
|
|
155
|
+
${p(`ack ${e.id}`)}
|
|
160
156
|
\`\`\`
|
|
161
157
|
|
|
162
158
|
If you decide not to write it (off-strategy, duplicate, etc.), decline it:
|
|
163
159
|
|
|
164
160
|
\`\`\`bash
|
|
165
|
-
|
|
161
|
+
${p(`ack ${e.id}`)} --failed --reason "skipped; ..."
|
|
166
162
|
\`\`\`
|
|
167
|
-
`}function
|
|
163
|
+
`}function Bi(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
164
|
`):"- (no metrics)";return`---
|
|
169
165
|
action_id: ${e.id}
|
|
170
166
|
action_type: ${e.action_type}
|
|
@@ -203,15 +199,15 @@ ${i}
|
|
|
203
199
|
After revising:
|
|
204
200
|
|
|
205
201
|
\`\`\`bash
|
|
206
|
-
|
|
202
|
+
${p(`ack ${e.id}`)}
|
|
207
203
|
\`\`\`
|
|
208
204
|
|
|
209
205
|
If you disagree (page is fine as-is, intentionally short, etc.), decline it:
|
|
210
206
|
|
|
211
207
|
\`\`\`bash
|
|
212
|
-
|
|
208
|
+
${p(`ack ${e.id}`)} --failed --reason "kept as-is; ..."
|
|
213
209
|
\`\`\`
|
|
214
|
-
`}function
|
|
210
|
+
`}function Mi(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
211
|
${r.join(`
|
|
216
212
|
`)}
|
|
217
213
|
\`\`\`${i?`
|
|
@@ -249,15 +245,15 @@ ${s}
|
|
|
249
245
|
Once the sitemap is served at \`${n??"/sitemap.xml"}\` (deploy if needed \u2014 GSC fetches the live URL):
|
|
250
246
|
|
|
251
247
|
\`\`\`bash
|
|
252
|
-
|
|
248
|
+
${p(`ack ${e.id}`)}
|
|
253
249
|
\`\`\`
|
|
254
250
|
|
|
255
251
|
SEOAgent re-submits the sitemap to GSC on its schedule. If a sitemap already exists and is correct, decline:
|
|
256
252
|
|
|
257
253
|
\`\`\`bash
|
|
258
|
-
|
|
254
|
+
${p(`ack ${e.id}`)} --failed --reason "sitemap already served at /sitemap.xml"
|
|
259
255
|
\`\`\`
|
|
260
|
-
`}function
|
|
256
|
+
`}function Gi(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
257
|
action_id: ${e.id}
|
|
262
258
|
action_type: ${e.action_type}
|
|
263
259
|
keyword: ${n??""}
|
|
@@ -306,19 +302,19 @@ ${e.description??""}
|
|
|
306
302
|
After publishing (and committing):
|
|
307
303
|
|
|
308
304
|
\`\`\`bash
|
|
309
|
-
|
|
305
|
+
${p(`ack ${e.id}`)}
|
|
310
306
|
\`\`\`
|
|
311
307
|
|
|
312
308
|
If you decide *not* to write it (already covered elsewhere, off-strategy, etc.),
|
|
313
309
|
decline it:
|
|
314
310
|
|
|
315
311
|
\`\`\`bash
|
|
316
|
-
|
|
312
|
+
${p(`ack ${e.id}`)} --failed --reason "skipped; ..."
|
|
317
313
|
\`\`\`
|
|
318
|
-
`}function
|
|
314
|
+
`}function Wi(e){switch(e.action_type){case"cli_prune_pending":return ji(e);case"cli_technical_fix":return Ui(e);case"cli_new_content":return Di(e);case"cli_content_update":return Bi(e);case"cli_sitemap_update":return Mi(e);case"cli_new_landing_page":return Gi(e);default:return null}}function Ki(e){if(e.length===0)return`# SEOAgent Inbox
|
|
319
315
|
|
|
320
316
|
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 \`${
|
|
317
|
+
`;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${Rn(n)}\``);return`# SEOAgent Inbox
|
|
322
318
|
|
|
323
319
|
You have **${e.length}** pending action${e.length===1?"":"s"} from your dashboard.
|
|
324
320
|
|
|
@@ -330,22 +326,38 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
|
|
|
330
326
|
|
|
331
327
|
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
332
328
|
skill knows what to do.
|
|
333
|
-
`}function
|
|
334
|
-
|
|
335
|
-
|
|
329
|
+
`}function yt(e){let t=ze(e);if(!In(t))return;let n=[];for(let r of Pn(t)){if(!r.endsWith(".md")||r==="README.md")continue;let i=r.match(/^(.+)-(\d+)\.md$/);if(!i)continue;let s=i[1],a=Number.parseInt(i[2],10);if(!Number.isFinite(a))continue;let l="no title";try{let f=Ti(ne(t,r),"utf-8").replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);f&&(l=f[1].trim())}catch{}n.push({id:a,action_type:s,title:l,filename:r})}n.sort((r,i)=>r.id-i.id);let o=n.length===0?`# SEOAgent Inbox
|
|
330
|
+
|
|
331
|
+
No pending actions. Run \`seoagent sync\` later to check for new ones.
|
|
332
|
+
`:`# SEOAgent Inbox
|
|
333
|
+
|
|
334
|
+
You have **${n.length}** pending action${n.length===1?"":"s"} from your dashboard.
|
|
335
|
+
|
|
336
|
+
${n.map(r=>`- **${r.action_type}** id \`${r.id}\` \u2014 ${r.title} \u2192 see \`${r.filename}\``).join(`
|
|
337
|
+
`)}
|
|
338
|
+
|
|
339
|
+
For each file, read it, take the action it describes, then run \`seoagent ack <action_id>\`
|
|
340
|
+
(or \`seoagent ack <action_id> --failed --reason "..."\` if you decline).
|
|
341
|
+
|
|
342
|
+
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
343
|
+
skill knows what to do.
|
|
344
|
+
`;ht(ne(t,"README.md"),o,"utf-8")}function Tn(e,t){let n=ze(e);Ri(n,{recursive:!0});let o=new Set(t.map(s=>s.id)),r=Li(n,o),i=0;for(let s of t){let a=Wi(s);a!==null&&(ht(ne(n,Rn(s)),a,"utf-8"),i++)}return ht(ne(n,"README.md"),Ki(t),"utf-8"),{wrote:i,removed:r,inboxPath:n}}import{createHash as Yi}from"crypto";import{existsSync as jn,mkdirSync as qi,readFileSync as Ji,statSync as Nn,writeFileSync as Ln,rmSync as Vi}from"fs";import{dirname as Xi,join as wt,sep as Qi}from"path";function zi(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Hi=[{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 On(e,t){let n=zi(e);for(let{cls:o,test:r}of Hi)if(r(n))return t&&(o==="keywords"||o==="pages")?"generated-index":o;return"other"}function Zi(e){return"sha256:"+Yi("sha256").update(e).digest("hex")}function es(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 ts(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:On(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 Fn(e){let t=await Dn({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 Un(e,t){return wt(e,t.split("/").join(Qi))}function ns(e,t,n){let o={};for(let r of t){let i=Un(e,r);if(!jn(i)){o[r]={exists:!1,locallyEdited:!1};continue}let s=Nn(i),a=n[r],l=!a||a.mtime!==s.mtimeMs||a.size!==s.size;o[r]={exists:!0,contentHash:Zi(Ji(i,"utf-8")),locallyEdited:l}}return o}async function Dn(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 Bn(e){let t=wt(e.projectDir,$),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!jn(t))return{...n,ok:!0};let o=await Dn({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=ns(t,i,e.stateFiles),a=es(r,s,{force:e.force}),l={...n,cursor:r.now};for(let d of a){let f=Un(t,d.path);try{switch(d.kind){case"skip":l.skipped++;break;case"write":case"overwrite":{qi(Xi(f),{recursive:!0}),Ln(f,d.body??"","utf-8");let g=Nn(f);e.stateFiles[d.path]={mtime:g.mtimeMs,size:g.size},d.kind==="write"?l.written++:l.overwritten++,d.note&&l.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":Vi(f,{force:!0}),delete e.stateFiles[d.path],l.deleted++;break;case"delete-skipped":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(g){l.ok=!1,l.error=`${d.path}: ${g.message}`}}(l.conflicts>0||!l.ok)&&(l.cursor=e.since);let u=ts(a,r,l.cursor,new Date().toISOString());if(u)try{Ln(wt(t,Rt),JSON.stringify(u,null,2)+`
|
|
345
|
+
`,"utf-8")}catch{}return l}var cs=new Set([".md"]),us=new Set(["inbox"]);function ds(e){let t=[];function n(o,r){if(kt(o))for(let i of rs(o,{withFileTypes:!0})){if(i.name.startsWith(".")||r===""&&us.has(i.name))continue;let s=bt(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);cs.has(l)&&t.push(s)}}}return n(e,""),t}function Gn(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return bt(et,`${t}.json`)}function ps(e){let t=Gn(e);if(!kt(t))return{files:{},last_synced_at:null};try{return JSON.parse(Mn(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function fs(e,t){os(et,{recursive:!0}),ss(Gn(e),JSON.stringify(t,null,2)+`
|
|
346
|
+
`,"utf-8")}function ms(e,t){return as(e,t).split(ls).join("/")}async function gs(e,t){try{let n=await te(`${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 hs(e,t,n){try{let o=await te(`${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 Wn(e,t={}){let n=x();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let o=b(e);if(!o)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let r=bt(e,$);if(!kt(r))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let i=ps(o.domain),s=ds(r),a=n.api_base||k.BASE,l=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,f=[],g=0;if(!t.pullOnly)for(let E of s){let re=ms(r,E);if(t.pathFilter&&!re.endsWith(t.pathFilter))continue;let Pe=is(E),Xe=i.files[re];if(!(!Xe||Xe.mtime!==Pe.mtimeMs||Xe.size!==Pe.size)&&!t.force)continue;g++;let yo=Mn(E,"utf-8"),Qe=await hs(a,{path:re,contents:yo,domain:o.domain},l);Qe.ok?(i.files[re]={mtime:Pe.mtimeMs,size:Pe.size},u++):(d++,f.push(`${re}: ${Qe.status} ${Qe.error??""}`.trim()))}let A=await gs(a,l),j=0,B=0;if(A.ok){let E=Tn(e,A.actions);j=E.wrote,B=E.removed}else A.error&&f.push(`pull actions: ${A.error}`);let R,Ve=!1,Ct=i.last_synced_at;if(!t.pushOnly){let E=await Bn({projectDir:e,apiBase:a,authHeader:l,since:i.last_synced_at,stateFiles:i.files,force:t.force});E.ok?Ct=E.cursor:(Ve=!0,E.error&&f.push(`pull: ${E.error}`)),R={written:E.written,overwritten:E.overwritten,skipped:E.skipped,conflicts:E.conflicts,deleted:E.deleted,warnings:E.warnings}}let ho=!!R&&R.written+R.overwritten+R.deleted+R.conflicts>0;if(i.last_synced_at=Ct,fs(o.domain,i),g===0&&j===0&&B===0&&!ho&&!Ve&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:f,actionsPulled:0,actionsRemoved:0,pull:R};let At=d===0&&!Ve;return{ok:At,reason:At?void 0:"error",synced:u,failed:d,errors:f,actionsPulled:j,actionsRemoved:B,pull:R}}async function H(e={}){let t=!e.silent&&!!process.stdout.isTTY,n=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",o=t?ys():null;o?.start(`${n} ${$e.dim(".seoagent/")} with your dashboard\u2026`);let r=await Wn(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){r.ok||(process.exitCode=0);return}if(r.reason==="no-auth"){y(o,"info",`Not logged in. Run \`${p("login")}\` to enable cloud sync.`,$e.dim("Not logged in \u2014 cloud sync skipped.")),o&&c.info(`Run \`${p("login")}\` to enable cloud sync.`);return}if(r.reason==="no-project"){y(o,"info",`No SEOAgent project here. Run \`${p("init")}\` first.`,$e.dim("No SEOAgent project \u2014 sync skipped.")),o&&c.info(`Run \`${p("init")}\` first.`);return}if(r.reason==="no-changes"){y(o,"info","Already in sync.",$e.green("Already in sync."));return}let i=ws(r);y(o,"success",i??"Sync complete.",$e.green(i??"Sync complete.")),r.synced>0&&c.success(`Synced ${r.synced} file${r.synced===1?"":"s"} to your dashboard.`);let s=r.pull;if(s){let a=s.written+s.overwritten;a>0&&c.success(`Pulled ${a} file${a===1?"":"s"} from the cloud`+(s.overwritten>0?` (${s.overwritten} updated)`:"")),s.deleted>0&&c.info(`Removed ${s.deleted} file${s.deleted===1?"":"s"} deleted in the cloud.`),s.conflicts>0&&c.warn(`${s.conflicts} conflict${s.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let l of s.warnings.slice(0,5))c.info(` \u2022 ${l}`)}if(r.actionsPulled&&r.actionsPulled>0&&(c.success(`Pulled ${r.actionsPulled} pending action${r.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),c.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),r.actionsRemoved&&r.actionsRemoved>0&&c.info(`Cleaned up ${r.actionsRemoved} stale inbox file${r.actionsRemoved===1?"":"s"}.`),r.failed>0){c.warn(`${r.failed} file${r.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let a of r.errors.slice(0,3))c.info(` \u2022 ${a}`)}}function ws(e){let t=e.synced,n=e.pull?e.pull.written+e.pull.overwritten:0,o=e.actionsPulled??0,r=e.pull?.conflicts??0,i=[];return t>0&&i.push(`${t} pushed`),n>0&&i.push(`${n} pulled`),o>0&&i.push(`${o} action${o===1?"":"s"}`),r>0&&i.push(`${r} conflict${r===1?"":"s"}`),i.length===0&&e.failed===0?null:i.length>0?i.join(" \xB7 "):"Sync complete."}async function Se(e={}){if(e.print){let t=x();if(!t){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}if(!b(process.cwd())){c.error(`No SEOAgent project here. Run \`${p("init")}\` first.`),process.exitCode=1;return}let o=t.api_base||k.BASE,r=await Fn({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
347
|
`)||process.stdout.write(`
|
|
337
|
-
`);return}await H({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?` (${
|
|
348
|
+
`);return}await H({pullOnly:!0,force:e.force,silent:e.silent})}import{existsSync as ks,readdirSync as bs,unlinkSync as $s}from"fs";import{join as zn}from"path";async function ve(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=x();if(!o){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}if(!b(process.cwd())){c.error(`No SEOAgent project here. Run \`${p("init")}\` first.`),process.exitCode=1;return}let i=o.api_base||k.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",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(u){c.error(`Network error: ${u.message}`),process.exitCode=1;return}if(!l.ok){let u=await l.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(l.status===409&&d?.code==="already_acked"){Kn(n),yt(process.cwd());let f=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";c.success(`Action ${n} was already ${f}.`);return}c.error(`Server rejected ack (${l.status}): ${u.slice(0,200)}`),process.exitCode=1;return}Kn(n),yt(process.cwd()),t.failed?c.success(`Action ${n} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):c.success(`Action ${n} marked completed.`),c.info(` inbox location: ${zn($,"inbox")}`)}function Kn(e){let t=ze(process.cwd());if(ks(t)){for(let n of bs(t))if(n.endsWith(`-${e}.md`))try{$s(zn(t,n))}catch{}}}import{spinner as Ss}from"@clack/prompts";import h from"picocolors";var vs=new Set(["on","off","status"]);async function xe(e,t={}){let n=(e||"").toLowerCase();if(!vs.has(n)){c.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let o=x();if(!o){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let r=t.apiBase||o.api_base||k.BASE,i=`Bearer ${o.user_token}:${o.website_token}`,a=!!process.stdout.isTTY?Ss():null,l=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(l);let u;try{u=await fetch(`${r}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(A){y(a,"error",`Network error: ${A.message}`,h.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){let j=b(process.cwd())?.domain??"",B=`${k.PRICING}?ref=cli${j?`&domain=${encodeURIComponent(j)}`:""}`;y(a,"warn","CLI autopilot is a paid feature.",h.yellow("Autopilot is a paid feature.")),c.message(xs(B)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){y(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,h.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:f,delivery_mode:g}=d.autopilot;if(n==="on"){a?.stop(h.green("Autopilot enabled.")),c.message($t({enabled:!0,deliveryMode:g,action:n}));return}if(n==="off"){a?.stop(h.dim("Autopilot disabled.")),c.message($t({enabled:!1,deliveryMode:g,action:n}));return}a?.stop(h.dim("Status:")),c.message($t({enabled:f,deliveryMode:g,action:n}))}function $t(e){let n=s=>h.dim(s.padEnd(11)),o=e.enabled?`${h.bold(h.green("\u25CF ON"))} ${h.dim("(queueing fixes for your coding agent)")}`:`${h.dim("\u25CB OFF")} ${h.dim("(no new suggestions will be queued)")}`,r=[{content:`${n("Status:")}${o}`}];e.enabled&&e.deliveryMode&&r.push({content:`${n("Mode:")}${h.dim(e.deliveryMode)}`}),r.push({sep:!0}),e.enabled?(r.push({content:`${h.dim("Apply queued fixes:")} ${h.cyan(p("sync"))}`}),r.push({content:`${h.dim("Turn off any time:")} ${h.cyan(p("autopilot off"))}`})):(r.push({content:`${h.dim("Enable (paid):")} ${h.cyan(p("autopilot on"))}`}),r.push({content:h.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${h.bold(h.cyan("SEOAgent"))} ${h.dim("\xB7")} ${h.dim("autopilot")}`;return I(r,{width:78,title:i})}function xs(e){let t=[{content:h.bold(h.yellow("Autopilot is a paid feature."))},{sep:!0},{content:h.dim("SEOAgent continuously audits your site and queues fixes for")},{content:h.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:h.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${h.dim("Upgrade:")} ${h.cyan(e)}`}],n=`${h.bold(h.cyan("SEOAgent"))} ${h.dim("\xB7")} ${h.dim("autopilot")}`;return I(t,{width:78,title:n})}import{mkdirSync as Ns,writeFileSync as Fs}from"fs";import{join as St}from"path";import{readdirSync as _s,readFileSync as Es,statSync as Hn}from"fs";import{join as Cs}from"path";var As=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Is=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"]),Ps=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Rs=5e3,Ts=512*1024;function Xn(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function Yn(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&&Is.has(o.slice(r+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var qn=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Jn=/\]\(\s*([^)\s]+)/g;function Os(e,t){if(!e)return[];let n=Xn(t),o=[],r;for(qn.lastIndex=0;(r=qn.exec(e))!==null;){let i=r[1]??r[2]??r[3]??"",s=Yn(i,n);s&&o.push(s)}for(Jn.lastIndex=0;(r=Jn.exec(e))!==null;){let i=Yn(r[1],n);i&&o.push(i)}return o}function Ls(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 Qn(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(`
|
|
349
|
+
`),r=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${Xn(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
350
|
`),i=e.orphans.length===0?`## Orphan pages
|
|
340
351
|
|
|
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=>`| ${
|
|
352
|
+
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=>`| ${Vn(a.url)} | \u2014 |`)].join(`
|
|
353
|
+
`),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=>`| ${Vn(a.url)} | ${a.inbound} |`)].join(`
|
|
343
354
|
`);return[o,"",r,"",i,s,""].join(`
|
|
344
|
-
`)}function
|
|
345
|
-
`);return}let i=
|
|
346
|
-
`);return}if(
|
|
347
|
-
`)),s}
|
|
348
|
-
`)
|
|
349
|
-
`)
|
|
355
|
+
`)}function Vn(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*js(e){let t=0;function*n(o){let r;try{r=_s(o,{withFileTypes:!0})}catch{return}for(let i of r){if(t>=Rs)return;if(i.name.startsWith("."))continue;let s=Cs(o,i.name);if(i.isDirectory()){if(Ps.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(!As.has(l))continue;t++,yield s}}}yield*n(e)}function Zn(e,t){let{pages:n}=De(e,t),o=[],r=0,i=!1;try{i=Hn(e).isDirectory()}catch{i=!1}if(i)for(let s of js(e)){let a;try{if(Hn(s).size>Ts)continue;a=Es(s,"utf-8")}catch{continue}r++;for(let l of Os(a,t))o.push(l)}return Ls(n,o,r)}function _e(e={}){let t=process.cwd(),n=b(t);if(!n){c.error(`No SEOAgent project here. Run \`${p("init")}\` first.`),process.exitCode=1;return}let o=n.domain&&n.domain!=="unknown"?n.domain:null,r=Zn(t,o);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
|
|
356
|
+
`);return}let i=St(t,$);Ns(i,{recursive:!0});let s=St(i,"internal-links.md");if(Fs(s,Qn(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 ${St($,"internal-links.md")}`)}import{spinner as no}from"@clack/prompts";import m from"picocolors";var oo={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function Us(e){let t=process.cwd(),n=Ut(t);if(!n){c.error(`No .seoagent/project.md found. Run \`${p("init")}\` first.`),process.exitCode=1;return}let o=b(t),r=o?.domain&&o.domain!=="unknown"?o.domain:void 0,i=(e.apiBase||k.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?no():null;a?.start(`Looking up ${m.bold(`"${e.keyword}"`)} ${m.dim("via DataForSEO (free peek)\u2026")}`);let l;try{l=await te(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...r?{domain:r}:{}})})}catch(d){y(a,"error",`Network error: ${d.message}`,m.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await l.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:l.status,body:u??null})+`
|
|
357
|
+
`);return}if(l.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";y(a,"warn",`Daily peek quota reached for ${d}.`,m.yellow(`Daily peek quota reached for ${d}.`)),c.message(eo()),process.exitCode=1;return}if(!l.ok||!u){y(a,"error",`Peek failed (${l.status})${u?.error?`: ${u.error}`:""}`,m.red(`Peek failed (${l.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){y(a,"warn","Real keyword data is temporarily unavailable. Try again later.",m.yellow("Real keyword data is temporarily unavailable. Try again later.")),c.message(m.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){y(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",m.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){y(a,"warn",`No data returned for "${e.keyword}".`,m.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(m.green("Got it.")),c.message(Ds(u.opportunity)),u.remaining&&c.message(`${m.dim("Peeks remaining today:")} ${m.bold(String(u.remaining.install))} ${m.dim("\u2014 "+eo())}`)}function Ds(e){let n=u=>m.dim(u.padEnd(14)),o=e.volume!=null?m.bold(String(e.volume)):m.dim("n/a"),r=e.difficulty!=null?`${m.bold(String(e.difficulty))} ${m.dim(Bs(e.difficulty))}`:m.dim("n/a"),i=oo[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?m.bold(m.green(i)):e.opportunity==="striking_distance"?m.bold(m.cyan(i)):e.opportunity==="competitor_gap"?m.bold(m.yellow(i)):m.dim(i),a=[{content:`${m.green("\u25CF")} ${m.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${o} ${m.dim("/mo")}`},{content:`${n("Difficulty:")}${r}`},{content:`${n("Opportunity:")}${s}`}],l=`${m.bold(m.cyan("Keyword peek"))}`;return I(a,{width:55,title:l})}function Bs(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function eo(e=x()){return e?`You're logged in \u2014 run \`${p("keywords")}\` for full enrichment (no quota), or \`${p("keywords --discover")}\` / \`${p("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${p("login")}`}function to(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 [${oo[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${o}, ${r}${i}`)}}}function Ms(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 D(e={}){if(e.peek&&e.peek.trim().length>0){await Us({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=x();if(!t){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let n=e.apiBase||t.api_base||k.BASE,o=`Bearer ${t.user_token}:${t.website_token}`,r=e.competitors?"competitors":e.discover?"discover":"enrich",i=r==="competitors"?"/api/cli/keywords/competitors":r==="discover"?"/api/cli/keywords/discover":"/api/cli/keywords/enrich",s=r==="competitors"?"Finding keywords your competitors rank for\u2026":r==="discover"?"Discovering new keywords to target\u2026":"Enriching keywords with real volume + difficulty\u2026",l=!!process.stdout.isTTY?no():null;l?.start(s);let u;try{u=await te(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:o},body:"{}"})}catch(g){y(l,"error",`Network error: ${g.message}`,m.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){y(l,"warn",r==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",m.yellow("Paid feature \u2014 upgrade to continue.")),c.message(r==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${m.cyan(k.PRICING)}`:`Upgrade to find new keywords to target: ${m.cyan(k.PRICING)}`),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"){y(l,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,m.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}if(d.skipped==="no-keywords"||d.skipped==="no-seeds"){y(l,"warn","No keywords yet. Run the keyword strategy (Phase 2) first, then try again.",m.yellow("No keywords yet."));return}if(d.skipped==="no-competitors"){y(l,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",m.yellow("No competitors yet."));return}if(d.skipped==="no-creds"||d.skipped==="no-columns"||d.skipped==="no-table"){y(l,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",m.yellow("Real keyword data is not enabled on the server yet."));return}if(d.skipped){y(l,"warn",`Skipped: ${d.skipped}`,m.yellow(`Skipped: ${d.skipped}`));return}if(r==="competitors"){let g=d.gaps??0;y(l,"success",`Found ${g} competitor gap${g===1?"":"s"} across ${d.competitors?.length??0} competitor${d.competitors?.length===1?"":"s"} (added as "suggested").`,m.green(`${g} competitor gap${g===1?"":"s"} found.`)),Ms(d.topGaps??[]),c.message(`Review them in ${m.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}if(r==="discover"){let g=d.discovered??0;y(l,"success",`Discovered ${g} new keyword${g===1?"":"s"} to target (added as "suggested").`,m.green(`${g} new keyword${g===1?"":"s"} discovered.`)),to(d.opportunities??[]),c.message(`Review them in ${m.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}let f=d.enriched??0;y(l,"success",`Enriched ${f} keyword${f===1?"":"s"}.`,m.green(`Enriched ${f} keyword${f===1?"":"s"}.`)),to(d.opportunities??[]),d.paid||c.message(`${m.dim("Free plan:")} enriched up to ${m.bold(String(d.cap??25))} keywords. ${m.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${m.cyan(k.PRICING)}`)}import S from"picocolors";import{existsSync as Gs,readFileSync as Ws}from"fs";import{join as Ks}from"path";var ro=["openai","fal","replicate"],oe={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function zs(e){let t={};if(!Gs(e))return t;let n=Ws(e,"utf-8");for(let o of n.split(/\r?\n/)){let r=o.trim();if(!r||r.startsWith("#"))continue;let i=r.indexOf("=");if(i===-1)continue;let s=r.slice(0,i).trim(),a=r.slice(i+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return t}function io(e,t){let n={};for(let o of t){let r=process.env[o];r&&r.trim().length>0&&(n[o]={value:r,source:"process"})}for(let o of Y){let r=Ks(e,o),i=zs(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 He(e){let t=[].concat(...ro.map(a=>oe[a])),n=io(e,t),o=[];for(let a of ro)oe[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=oe[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 so(e,t){let n=io(e,oe[t]);for(let o of oe[t])if(n.found[o])return{key:n.found[o].value,envName:o};return null}function ao(){return oe}function Ee(e={}){let t=process.cwd(),n=b(t),o=He(t);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
|
|
358
|
+
`);return}if(c.message(Hs(o)),!n){c.warn(`No SEOAgent project here. Run \`${p("init")}\` first to persist the provider.`);return}ae(t,{image_provider:o.provider}),c.info(`Saved to ${S.cyan(".seoagent/project.md")} ${S.dim(`(image_provider: ${o.provider})`)}`)}function Hs(e){let n=i=>S.dim(i.padEnd(12)),o=[];if(e.provider==="none"){o.push({content:`${S.dim("\u25CB")} ${S.bold(S.yellow("No image provider detected"))}`}),o.push({sep:!0}),o.push({content:S.dim("Set ONE of these to enable image generation:")});let i=ao();for(let s of Object.keys(i))o.push({content:`${n(s+":")}${S.cyan(i[s].join(" or "))}`});o.push({sep:!0}),o.push({content:S.dim("Add to your shell, .env.local, or .env, then re-run:")}),o.push({content:` ${S.cyan(p("env-check"))}`})}else{o.push({content:`${S.green("\u2713")} ${S.dim("Image provider:")} ${S.bold(S.green(e.provider))}`}),o.push({sep:!0}),e.matched_key&&o.push({content:`${n("Key:")}${S.bold(e.matched_key)}`}),e.source&&o.push({content:`${n("Source:")}${S.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&o.push({content:`${n("Available:")}${S.dim(i.join(", "))}`})}let r=`${S.bold(S.cyan("SEOAgent"))} ${S.dim("\xB7")} ${S.dim("env-check")}`;return I(o,{width:64,title:r})}import{existsSync as xt,mkdirSync as uo,writeFileSync as po}from"fs";import{dirname as qe,isAbsolute as Xs,join as Ye,resolve as Qs}from"path";import{tmpdir as Zs}from"os";import{spinner as ea}from"@clack/prompts";import _ from"picocolors";import{Buffer as lo}from"buffer";async function vt(e){let t=await fetch(e);if(!t.ok)throw new Error(`Image download failed: ${t.status} ${t.statusText}`);let n=await t.arrayBuffer();return lo.from(n)}async function Ys(e){let t=e.size??"1024x1024",n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:"gpt-image-1",prompt:e.prompt,size:t,n:1})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`OpenAI image API ${n.status}: ${i.slice(0,300)}`)}let r=(await n.json()).data?.[0];if(!r)throw new Error("OpenAI image API returned no data");if(r.b64_json)return{bytes:lo.from(r.b64_json,"base64"),contentType:"image/png"};if(r.url)return{bytes:await vt(r.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function qs(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 vt(r.url),contentType:r.content_type??"image/png"}}async function Js(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 Vs(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 Js(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 vt(r),contentType:"image/png",providerImageId:o.id}}async function co(e,t){switch(e){case"openai":return Ys(t);case"fal":return qs(t);case"replicate":return Vs(t);default:throw new Error(`Unknown image provider: ${e}`)}}function ta(e){return e==="openai"||e==="fal"||e==="replicate"}async function Ce(e={}){let t=process.cwd();if(!e.prompt){c.warn(`Missing --prompt. Example: ${p('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){c.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=b(t),o=null;if(e.provider){if(!ta(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=He(t).provider;if(!o||o==="none"){c.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${p("env-check")}\`.`),process.exitCode=1;return}let r=so(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=Xs(e.out)?e.out:Qs(t,e.out),a=!e.silent&&!!process.stdout.isTTY?ea():null;a?.start(`Generating image with ${_.bold(o)} ${_.dim(`(${r.envName})`)}\u2026`);try{let l=await co(o,{prompt:e.prompt,apiKey:r.key,size:e.size});xt(qe(i))||uo(qe(i),{recursive:!0}),po(i,l.bytes),e.silent||y(a,"success",`Wrote ${i} (${l.bytes.length} bytes, ${l.contentType}).`,_.green(`Wrote ${i} ${_.dim(`(${l.bytes.length} bytes, ${l.contentType})`)}`))}catch(l){a?.stop(_.red("Image generation failed."));let u=oa(t,{provider:o,envName:r.envName,prompt:e.prompt,size:e.size,outPath:i,error:l});c.message(na({provider:o,envName:r.envName,prompt:e.prompt,size:e.size,message:l.message})),u&&c.message(`${_.dim("Full error log:")} ${_.cyan(u)}`),process.exitCode=1}}function na(e){let n=d=>_.dim(d.padEnd(10)),r=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${_.red("\u2717")} ${_.bold(_.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${_.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${_.dim(`"${r}"`)}`}];e.size&&i.push({content:`${n("Size:")}${e.size}`}),i.push({sep:!0});let s=e.message.replace(/\s+/g," ").trim(),a=64,l=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:_.red(l)});let u=`${_.bold(_.cyan("SEOAgent"))} ${_.dim("\xB7")} ${_.dim("generate-image")}`;return I(i,{width:70,title:u})}function oa(e,t){let o=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,r=Ye(e,$),i=Ye(r,".errors"),s=xt(r)?Ye(i,o):Ye(Zs(),o),a=["# SEOAgent generate-image error",`# ${new Date().toISOString()}`,"","## Request",`provider: ${t.provider}`,`env_var: ${t.envName}`,`prompt: ${JSON.stringify(t.prompt)}`,`size: ${t.size??"(default)"}`,`out_path: ${t.outPath}`,`cwd: ${e}`,"","## Error",`message: ${t.error.message}`,"","## Stack",t.error.stack??"(no stack)",""];t.error.cause&&a.push("## Cause",String(t.error.cause),"");try{return xt(qe(s))||uo(qe(s),{recursive:!0}),po(s,a.join(`
|
|
359
|
+
`)),s}catch{return null}}import P from"picocolors";async function Ae(e={}){let t=x();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
|
|
360
|
+
`):c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||k.BASE).replace(/\/$/,""),o=`Bearer ${t.user_token}:${t.website_token}`,r;try{r=await fetch(`${n}/api/cli/whoami`,{method:"GET",headers:{Authorization:o,Accept:"application/json"}})}catch(s){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})}
|
|
361
|
+
`);return}c.warn(`Logged in, but the server at this API base does not support \`/api/cli/whoami\` yet. Update with \`${p("update-cli")}\` (or re-deploy your server).`),c.message(`API base: ${n}`);return}let i=null;try{i=await r.json()}catch{i=null}if(!r.ok||!i||i.status!=="ok"){e.json?process.stdout.write(`${JSON.stringify({logged_in:!0,error:i?.error??`HTTP ${r.status}`})}
|
|
350
362
|
`):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)}
|
|
351
|
-
`);return}c.message(Js(i)),i.paid===!1&&c.message(`${P.dim("Upgrade for autopilot:")} ${P.cyan(k.PRICING)}`)}function Js(e){let n=i=>P.dim(i.padEnd(10)),o=[];if(e.email&&(o.push({content:`${P.green("\u2713")} ${P.dim("Logged in as")} ${P.bold(e.email)}`}),o.push({sep:!0})),e.domain&&o.push({content:`${n("Website:")}${P.cyan(e.domain)}`}),e.plan){let i=e.paid?P.bold(P.green(e.plan)):P.bold(e.plan);o.push({content:`${n("Plan:")}${i}`})}e.api_base&&o.push({content:`${n("API:")}${P.dim(e.api_base)}`});let r=`${P.bold(P.cyan("SEOAgent"))} ${P.dim("\xB7")} ${P.dim("whoami")}`;return I(o,{width:55,title:r})}import{select as St,text as Ce,confirm as lo,isCancel as L,intro as Vs,outro as Xs}from"@clack/prompts";import Ye from"picocolors";function Qs(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>pe()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await H()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await ce()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await ye()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await Ee()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await St({message:"Which mode?",options:[{value:"peek",label:"peek",hint:"Free, one keyword, no login required"},{value:"enrich",label:"enrich (default)",hint:"Enrich your full strategy (requires login)"},{value:"discover",label:"discover",hint:"Find new keywords to target (paid)"},{value:"competitors",label:"competitors",hint:"Find competitor keyword gaps (paid)"}]});if(!L(e))if(e==="peek"){let t=await Ce({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(L(t))return;await D({peek:String(t)})}else e==="discover"?await D({discover:!0}):e==="competitors"?await D({competitors:!0}):await D()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>ve({})},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Ce({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(L(e))return;let t=await Ce({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});L(t)||await _e({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>xe({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await St({message:"Autopilot action:",options:[{value:"status",label:"status",hint:"Show current state"},{value:"on",label:"on",hint:"Turn autopilot ON (paid)"},{value:"off",label:"off",hint:"Turn autopilot OFF"}]});L(e)||await Se(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await be()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Ce({message:"Action ID to close out:",placeholder:"action-abc123",validate:o=>String(o??"").trim()?void 0:"Action ID is required."});if(L(e))return;let t=await lo({message:"Mark as failed instead of completed?",initialValue:!1});if(L(t))return;let n;if(t===!0){let o=await Ce({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(L(o))return;String(o).trim()&&(n=String(o))}await $e(String(e),{failed:t===!0,reason:n})}},{command:"upgrade",label:"Upgrade your SEOAgent plan",hint:"Open the pricing page; contextual prompt if logged in.",run:async()=>await ge()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest",run:async()=>await he({})},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>we()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await ue({})}]}var so="__exit__";async function ao(e=Qs()){let t=e.map(r=>({value:r.command,label:r.label,hint:r.hint}));t.push({value:so,label:"Exit",hint:"Close the menu"});let n=await St({message:"What would you like to do?",options:t});if(L(n)||n===so)return!0;let o=e.find(r=>r.command===n);if(!o)return c.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await o.run()}catch(r){c.error(`\`${o.command}\` failed: ${r.message??String(r)}`)}return!1}async function vt(){if(!process.stdin.isTTY){c.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}Vs(`${Ye.bold(Ye.cyan("SEOAgent"))} ${Ye.dim("\xB7 menu")}`);let e=await ao();for(;!e;){let t=await lo({message:"Do another?",initialValue:!0});if(L(t)||t===!1){e=!0;break}e=await ao()}Xs(Ye.dim("See you next time."))}var v=new Zs;v.name("seoagent").description("AI SEO agent for Claude Code").version(J).showSuggestionAfterError(!0).showHelpAfterError(!0);v.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=>{ce({yes:e.yes,domain:e.domain,siteType:e.siteType})});v.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=>{ue({yes:e.yes,global:e.global})});v.command("status").description("Show current SEO project state").action(pe);v.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=>{ye({apiBase:e.apiBase})});v.command("logout").description("Remove stored credentials for seoagent.com").action(we);v.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force","Re-send every artifact on push; take cloud on every pull conflict").option("--path <relpath>","Push only files matching this path suffix").option("--push-only","Skip the cloud \u2192 local pull pass").option("--pull-only","Skip the local \u2192 cloud push pass (same as `seoagent pull`)").action(e=>{H({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});v.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=>{be({force:e.force,silent:e.silent,print:e.print})});v.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)=>{$e(e,{failed:t.failed,reason:t.reason})});v.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)=>{Se(e,{apiBase:t.apiBase})});v.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=>{D({peek:e.peek,discover:e.discover,competitors:e.competitors,apiBase:e.apiBase})});v.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=>{ve({json:e.json})});v.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{xe({json:e.json})});v.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=>{_e({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});v.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=>{Ee({json:e.json,apiBase:e.apiBase})});v.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(ge);v.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=>{he({dryRun:e.dryRun})});v.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{vt()});process.argv.length===2&&(v.outputHelp(),process.exit(0));v.parse();
|
|
363
|
+
`);return}c.message(ra(i)),i.paid===!1&&c.message(`${P.dim("Upgrade for autopilot:")} ${P.cyan(k.PRICING)}`)}function ra(e){let n=i=>P.dim(i.padEnd(10)),o=[];if(e.email&&(o.push({content:`${P.green("\u2713")} ${P.dim("Logged in as")} ${P.bold(e.email)}`}),o.push({sep:!0})),e.domain&&o.push({content:`${n("Website:")}${P.cyan(e.domain)}`}),e.plan){let i=e.paid?P.bold(P.green(e.plan)):P.bold(e.plan);o.push({content:`${n("Plan:")}${i}`})}e.api_base&&o.push({content:`${n("API:")}${P.dim(e.api_base)}`});let r=`${P.bold(P.cyan("SEOAgent"))} ${P.dim("\xB7")} ${P.dim("whoami")}`;return I(o,{width:55,title:r})}import{select as _t,text as Ie,confirm as go,isCancel as L,intro as ia,outro as sa}from"@clack/prompts";import Je from"picocolors";function aa(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>me()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await H()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await de()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await ke()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await Ae()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await _t({message:"Which mode?",options:[{value:"peek",label:"peek",hint:"Free, one keyword, no login required"},{value:"enrich",label:"enrich (default)",hint:"Enrich your full strategy (requires login)"},{value:"discover",label:"discover",hint:"Find new keywords to target (paid)"},{value:"competitors",label:"competitors",hint:"Find competitor keyword gaps (paid)"}]});if(!L(e))if(e==="peek"){let t=await Ie({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(L(t))return;await D({peek:String(t)})}else e==="discover"?await D({discover:!0}):e==="competitors"?await D({competitors:!0}):await D()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>_e({})},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Ie({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(L(e))return;let t=await Ie({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});L(t)||await Ce({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Ee({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await _t({message:"Autopilot action:",options:[{value:"status",label:"status",hint:"Show current state"},{value:"on",label:"on",hint:"Turn autopilot ON (paid)"},{value:"off",label:"off",hint:"Turn autopilot OFF"}]});L(e)||await xe(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await Se()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Ie({message:"Action ID to close out:",placeholder:"action-abc123",validate:o=>String(o??"").trim()?void 0:"Action ID is required."});if(L(e))return;let t=await go({message:"Mark as failed instead of completed?",initialValue:!1});if(L(t))return;let n;if(t===!0){let o=await Ie({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(L(o))return;String(o).trim()&&(n=String(o))}await ve(String(e),{failed:t===!0,reason:n})}},{command:"upgrade",label:"Upgrade your SEOAgent plan",hint:"Open the pricing page; contextual prompt if logged in.",run:async()=>await ye()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest",run:async()=>await we({})},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>be()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await pe({})}]}var fo="__exit__";async function mo(e=aa()){let t=e.map(r=>({value:r.command,label:r.label,hint:r.hint}));t.push({value:fo,label:"Exit",hint:"Close the menu"});let n=await _t({message:"What would you like to do?",options:t});if(L(n)||n===fo)return!0;let o=e.find(r=>r.command===n);if(!o)return c.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await o.run()}catch(r){c.error(`\`${o.command}\` failed: ${r.message??String(r)}`)}return!1}async function Et(){if(!process.stdin.isTTY){c.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}ia(`${Je.bold(Je.cyan("SEOAgent"))} ${Je.dim("\xB7 menu")}`);let e=await mo();for(;!e;){let t=await go({message:"Do another?",initialValue:!0});if(L(t)||t===!1){e=!0;break}e=await mo()}sa(Je.dim("See you next time."))}var v=new la;v.name("seoagent").description("AI SEO agent for Claude Code").version(J).showSuggestionAfterError(!0).showHelpAfterError(!0);v.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=>{de({yes:e.yes,domain:e.domain,siteType:e.siteType})});v.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=>{pe({yes:e.yes,global:e.global})});v.command("status").description("Show current SEO project state").action(me);v.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=>{ke({apiBase:e.apiBase})});v.command("logout").description("Remove stored credentials for seoagent.com").action(be);v.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force","Re-send every artifact on push; take cloud on every pull conflict").option("--path <relpath>","Push only files matching this path suffix").option("--push-only","Skip the cloud \u2192 local pull pass").option("--pull-only","Skip the local \u2192 cloud push pass (same as `seoagent pull`)").action(e=>{H({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});v.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=>{Se({force:e.force,silent:e.silent,print:e.print})});v.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)=>{ve(e,{failed:t.failed,reason:t.reason})});v.command("autopilot <action>").description("Turn CLI autopilot on|off or show status (paid; queues fixes for your agent)").option("--api-base <url>","Override API base URL (for testing)").action((e,t)=>{xe(e,{apiBase:t.apiBase})});v.command("keywords").description("Enrich keywords with real volume + difficulty + opportunity labels (requires login)").option("--peek <keyword>","Free one-keyword DataForSEO lookup (no login required; daily quota)").option("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{D({peek:e.peek,discover:e.discover,competitors:e.competitors,json:e.json,apiBase:e.apiBase})});v.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=>{_e({json:e.json})});v.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{Ee({json:e.json})});v.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=>{Ce({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});v.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=>{Ae({json:e.json,apiBase:e.apiBase})});v.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(ye);v.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})});v.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Et()});process.argv.length===2&&(v.outputHelp(),process.exit(0));v.parse();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seoagent-official/seoagent",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.43.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": {
|