@seoagent-official/seoagent 1.49.0 → 1.51.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/README.md +45 -12
- package/index.js +204 -77
- package/package.json +1 -1
- package/skills/references/keyword-research.md +3 -3
- package/skills/references/landing-pages.md +1 -1
- package/skills/references/long-tail-articles.md +1 -1
- package/skills/references/open-knowledge-format.md +74 -0
- package/skills/references/pillar-articles.md +1 -1
- package/skills/references/rewrite-protocol.md +1 -1
- package/skills/references/sub-pillar-articles.md +1 -1
- package/skills/seoagent.md +85 -50
package/index.js
CHANGED
|
@@ -1,34 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as
|
|
2
|
+
import{Command as zc}from"commander";import{dirname as Xi,relative as ar}from"path";import{intro as Zi,outro as es,text as lr,select as Gt,spinner as ts,isCancel as me,cancel as ge,confirm as ns}from"@clack/prompts";function It(e=process.argv[1]){let t=process.env.SEOAGENT_INSTALL_FORM;return t==="global"?!0:t==="npx"||!e?!1:(e.split(/[/\\]/).pop()??"").replace(/\.(cmd|ps1|exe)$/i,"").toLowerCase()==="seoagent"}function f(e,t=It()){return t?`seoagent ${e}`:`npx -y @seoagent-official/seoagent ${e}`}import{randomUUID as Xo}from"crypto";import{existsSync as Cn,mkdirSync as En,readFileSync as Zo,writeFileSync as An}from"fs";import{join as Ot}from"path";var ce=[".env.local",".env.production",".env"],kn=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];import{homedir as Mo}from"os";import{join as Xe}from"path";var $=".seoagent",bn=["audit","strategy/clusters","briefs","content","content/images","performance"],ne={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},Ze=".claude/settings.json",$n=".pull-receipt.json",Sn=".ack-queue.json",xn=".sync.lock",vn=`# SEOAgent local files
|
|
3
3
|
.legacy/
|
|
4
4
|
content/images/*
|
|
5
5
|
!content/images/.gitkeep
|
|
6
6
|
.pull-receipt.json
|
|
7
7
|
.ack-queue.json
|
|
8
8
|
.sync.lock
|
|
9
|
-
`,
|
|
10
|
-
`)}}function
|
|
9
|
+
`,Bo=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:Xe(Mo(),".config"),G=Xe(Bo,"seoagent"),J=Xe(G,"auth.json"),Rt=Xe(G,"state");var _e="https://seoagent.com",ue=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):_e,x={BASE:ue,PRICING:`${ue}/pricing`,LEAD_API:`${ue}/api/cli/lead`,CLI_AUTH_PAGE:`${ue}/cli/auth`,CLI_AUTH_POLL:`${ue}/api/cli/auth/poll`,CLI_SYNC:`${ue}/api/cli/sync`};import{readFileSync as Go}from"fs";import{fileURLToPath as Wo}from"url";import{dirname as Ko,join as qo}from"path";var _n="0.0.0";function Ho(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return _n}function Yo(e=t=>Go(t,"utf-8")){try{let t=Ko(Wo(import.meta.url));return Ho(e(qo(t,"package.json")))}catch{return _n}}var de=Yo();import{existsSync as zo,readFileSync as Jo}from"fs";var et="---";function Vo(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 Ce(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==et)return{data:{},body:e};let n={},r=1;for(;r<t.length;r++){if(t[r].trim()===et){r++;break}let o=t[r],i=o.indexOf(":");if(i===-1)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1);s&&(n[s]=Vo(a))}return{data:n,body:t.slice(r).join(`
|
|
10
|
+
`)}}function tt(e){if(!zo(e))return null;try{return Ce(Jo(e,"utf-8"))}catch{return null}}function Qo(e){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return String(e);let t=String(e);return t===""||/[:#\[\]{}&*!|>'"%@`,]/.test(t)||/^\s|\s$/.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function Pt(e,t=""){let n=[et];for(let[o,i]of Object.entries(e))i!==void 0&&n.push(`${o}: ${Qo(i)}`);n.push(et);let r=t.length===0?"":t.startsWith(`
|
|
11
11
|
`)?t:`
|
|
12
12
|
${t}`;return n.join(`
|
|
13
13
|
`)+r+(r.endsWith(`
|
|
14
14
|
`)?"":`
|
|
15
|
-
`)}var
|
|
16
|
-
`)}function
|
|
17
|
-
`,"utf-8"),{file:t,added:!1}):(o.hooks.push({type:"command",command:
|
|
18
|
-
`,"utf-8"),{file:t,added:!0})}function
|
|
19
|
-
`,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{readFileSync as
|
|
20
|
-
`)}var Mo="context.md";function Bo(e,t){let n=Do(e,".seoagent",Mo),r=_n(t);Uo(n,r,"utf-8")}function En(e,t){Bo(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as xe,readFileSync as Cn,readdirSync as Wo,statSync as An}from"fs";import{join as Z}from"path";var Go=[{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 Ko(e){let t=Z(e,"package.json");if(!xe(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Cn(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Ho(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 qo(e){let t={};for(let n of ie){let r=Z(e,n);if(xe(r))try{let o=Cn(r,"utf-8");for(let i of o.split(/\r?\n/)){let s=i.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a===-1)continue;let l=s.slice(0,a).trim();l&&!(l in t)&&(t[l]=n)}}catch{}}return t}function zo(e,t){let n=Z(e,t.replace(/\/$/,""));if(!xe(n))return!1;if(t.endsWith("/"))try{return An(n).isDirectory()}catch{return!1}return!0}function Yo(e){let t=["content","_posts","posts",Z("src","content")];for(let n of t){let r=Z(e,n);if(xe(r))try{if(!An(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of Wo(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(Z(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 Jo(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(xe(Z(e,n.marker)))return n.path;return null}function In(e){let t=[],{deps:n}=Ko(e),r=qo(e),o="none";for(let s of Go){let a=[];for(let l of Object.keys(n))if(Ho(l,s.deps)){a.push({type:"dep",detail:l,source:"package.json"});break}for(let l of s.envKeys)if(r[l]){a.push({type:"env",detail:l,source:r[l]});break}for(let l of s.fsMarkers)if(zo(e,l)){let u=l.endsWith("/")?"directory":"file";a.push({type:u,detail:l,source:l});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=Yo(e);s&&(o="mdx-local",t.push(s))}let i=Jo(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as ee,readFileSync as vt}from"fs";import{join as te}from"path";function Pn(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 Vo(e){for(let t of ie){let n=te(e,t);if(!ee(n))continue;let r=vt(n,"utf-8");for(let o of Zt){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Pn(s);if(Rn(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function Xo(e){let t=te(e,"package.json");if(!ee(t))return null;try{let n=JSON.parse(vt(t,"utf-8"));if(!n.homepage)return null;let r=Pn(n.homepage);return Rn(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function Tn(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ee(te(e,"pnpm-workspace.yaml"))&&n.push({field:"context",detail:"Monorepo workspace detected",source:"pnpm-workspace.yaml \u2014 using this directory for project signals"});let r=null;t?.("Scanning .env files for public / site URLs\u2026");let o=Vo(e);if(o)r=o.value,n.push({field:"domain",detail:o.value,source:o.source});else{t?.("Reading package.json homepage (skipping GitHub/GitLab repo URLs)\u2026");let a=Xo(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=te(e,"package.json"),s=null;if(ee(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(vt(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(m=>l.includes(m));if(u("@shopify/hydrogen","@shopify/polaris")||ee(te(e,"shopify.config.js"))||ee(te(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ee(te(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),m=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),g=u("next");d&&(g||m)?(s="saas",n.push({field:"site_type",detail:"saas",source:g?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:r,siteType:s,evidence:n}}import{existsSync as Qo,readFileSync as Zo,readdirSync as ei,statSync as ti}from"fs";import{join as ne,sep as ni}from"path";var On=["tsx","jsx","js","mdx","md"],ri=["astro","md","mdx"],oi=5e3;function Ve(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let l=ii(i);if(l===null){r++;return}let u=n.get(l);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(l,{route:l,url:fi(t,l),in_sitemap:a,source:s})};for(let i of["app",ne("src","app")]){let s=ne(e,i);if(xt(s))for(let a of _t(s)){let l=Et(s,a),u=l[l.length-1];ui(u)&&(l.some(d=>d.startsWith("@"))||o(si(l.slice(0,-1)),"app router"))}}for(let i of["pages",ne("src","pages")]){let s=ne(e,i);if(xt(s))for(let a of _t(s)){let l=Et(s,a);if(l[0]==="api")continue;let u=l[l.length-1],d=Ct(u),m=On.includes(d),g=ri.includes(d);if(!m&&!g)continue;let y=Xe(u);di(y)||o(ai(l),g?"astro":"pages router")}}for(let i of[".","public"]){let s=ne(e,i);if(xt(s))for(let a of _t(s,i==="."?1:1/0)){let l=Et(s,a),u=l[l.length-1];Ct(u)==="html"&&(l.some(d=>d==="node_modules"||d.startsWith("."))||o(li(l),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=ne(e,...i.split("/"));if(Qo(s)){for(let a of pi(s)){let l=ci(a);l!==null&&o(l,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}function ii(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function si(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function ai(e){let t=[...e],n=Xe(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function li(e){let t=[...e],n=Xe(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function ci(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function ui(e){return Xe(e)==="page"&&On.includes(Ct(e))}function di(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function pi(e){try{let t=Zo(e,"utf-8"),n=[],r=/<loc>\s*([^<\s]+)\s*<\/loc>/gi,o;for(;(o=r.exec(t))!==null;)n.push(o[1].trim());return n}catch{return[]}}var mi=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function xt(e){try{return ti(e).isDirectory()}catch{return!1}}function*_t(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=ei(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=oi)return;if(a.name.startsWith("."))continue;let l=ne(o,a.name);if(a.isDirectory()){if(mi.has(a.name))continue;yield*r(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*r(e,1)}function Et(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(ni).filter(Boolean)}function Ct(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Xe(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function fi(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as gi,writeFileSync as hi}from"fs";import{join as Ln}from"path";function Nn(e,t){if(t.length===0)return;let n=Ln(e,$);gi(n,{recursive:!0});let r=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
|
|
15
|
+
`)}var ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Tt(){return Xo()}var ti=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),ni="project.md";function Ee(e){return Ot(e,$)}function nt(e){return Ot(Ee(e),ni)}function In(e){return Cn(nt(e))}function I(e){let t=tt(nt(e));if(!t)return null;let n=t.data;if(typeof n.domain!="string"||!n.domain)return null;let r=typeof n.image_provider=="string"?n.image_provider:void 0,o=typeof n.cms=="string"?n.cms:void 0,i=o&&ti.has(o)?o:void 0,s=typeof n.install_id=="string"?n.install_id:void 0;return{domain:n.domain,site_type:typeof n.site_type=="string"?n.site_type:"unknown",language:typeof n.language=="string"?n.language:"en",initialized_at:typeof n.initialized_at=="string"?n.initialized_at:"",seoagent_version:typeof n.seoagent_version=="string"?n.seoagent_version:"",install_id:s&&ei.test(s)?s:void 0,image_provider:r==="openai"||r==="fal"||r==="replicate"||r==="none"?r:void 0,cms:i,blog_path:typeof n.blog_path=="string"&&n.blog_path?n.blog_path:void 0}}function Rn(e){let t=I(e);if(!t)return null;if(t.install_id)return t.install_id;let n=Tt();return Ae(e,{install_id:n}),n}function ri(e){return["",`# SEOAgent Project \u2014 ${e.domain}`,"","This file holds project-level configuration for the SEOAgent skill.","The skill reads it on every session to know which domain it is working on.","",`Initialized ${e.initialized_at} with seoagent ${e.seoagent_version}.`,""].join(`
|
|
16
|
+
`)}function oi(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 Pn(e,t){let n=Ee(e);En(n,{recursive:!0});let r=Pt(oi(t),ri(t));An(nt(e),r,"utf-8")}function Ae(e,t){let n=nt(e);if(!Cn(n))return!1;let r=Ce(Zo(n,"utf-8")),o={...r.data,...t};return An(n,Pt(o,r.body),"utf-8"),!0}function On(e){let t=Ee(e);for(let n of bn)En(Ot(t,n),{recursive:!0})}import{existsSync as rt,lstatSync as ii,mkdirSync as Ie,readFileSync as Tn,readdirSync as si,rmSync as ai,statSync as li,symlinkSync as ci,writeFileSync as Ln}from"fs";import{dirname as ot,join as W,relative as Nn}from"path";import{fileURLToPath as ui}from"url";var di=ot(ui(import.meta.url));function jn(){return W(di,"skills")}function pi(){let e=W(jn(),"seoagent.md");if(rt(e))return Tn(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function Fn(e,t){let n=[];if(!rt(e))return n;for(let r of si(e,{withFileTypes:!0})){let o=W(e,r.name),i=W(t,r.name);r.isDirectory()?(Ie(i,{recursive:!0}),n.push(...Fn(o,i))):r.isFile()&&(Ie(ot(i),{recursive:!0}),Ln(i,Tn(o)),n.push(i))}return n}function Dn(e,t){let n=rt(W(e,".agents")),r=W(e,n?ne.AGENTS:ne.CLAUDE),o=W(r,"SKILL.md");Ie(r,{recursive:!0}),Ln(o,t??pi(),"utf-8");let i=W(jn(),"references"),s=W(r,"references"),a=[];try{rt(i)&&li(i).isDirectory()&&(Ie(s,{recursive:!0}),a=Fn(i,s).map(u=>Nn(r,u)))}catch{}let l=n?fi(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:l}}function fi(e,t){let n=W(e,ne.CLAUDE),r=null;try{r=ii(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{ai(n,{force:!0})}catch{return}}try{Ie(ot(n),{recursive:!0});let o=Nn(ot(n),t);return ci(o,n,"dir"),n}catch{return}}import{existsSync as it,mkdirSync as Lt,readFileSync as mi,writeFileSync as Re}from"fs";import{dirname as Un,join as pe}from"path";var gi="npx -y @seoagent-official/seoagent sync --silent";function Mn(e){let t=pe(e,$);Lt(t,{recursive:!0});let n=pe(t,".gitignore");Re(n,vn,"utf-8");let r=pe(t,"content","images",".gitkeep");return Lt(Un(r),{recursive:!0}),it(r)||Re(r,"","utf-8"),n}function Nt(e){if(!it(e))return{};try{let t=mi(e,"utf-8");return JSON.parse(t)}catch{return{}}}function jt(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function Bn(e){let t=pe(e,Ze);Lt(Un(t),{recursive:!0});let n=Nt(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=r.find(i=>(i.matcher??"").includes("Write"));return o||(o={matcher:"Write|Edit",hooks:[]},r.push(o)),o.hooks.some(jt)?(Re(t,JSON.stringify(n,null,2)+`
|
|
17
|
+
`,"utf-8"),{file:t,added:!1}):(o.hooks.push({type:"command",command:gi}),Re(t,JSON.stringify(n,null,2)+`
|
|
18
|
+
`,"utf-8"),{file:t,added:!0})}function Gn(e){let t=pe(e,Ze);if(!it(t))return!1;let n=Nt(t).hooks?.PostToolUse;return Array.isArray(n)?n.some(r=>r.hooks?.some(jt)):!1}function Wn(e){let t=pe(e,Ze);if(!it(t))return{file:t,removed:!1};let n=Nt(t),r=n.hooks?.PostToolUse;if(!Array.isArray(r))return{file:t,removed:!1};let o=!1;for(let i of r){let s=i.hooks.length;i.hooks=i.hooks.filter(a=>!jt(a)),i.hooks.length!==s&&(o=!0)}return o?(n.hooks.PostToolUse=r.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,Re(t,JSON.stringify(n,null,2)+`
|
|
19
|
+
`,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{readFileSync as ki,writeFileSync as bi,existsSync as $i}from"fs";import{join as Yn}from"path";function qn(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=hi(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=yi(o):i==="writing instructions"?t.writingInstructions=Kn(o):i==="reference urls"?t.referenceUrls=wi(o):i==="topics to avoid"?t.topicsToAvoid=Kn(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function Hn(e){let t=[];t.push("# Business Context"),t.push("");let n=[["Name","name"],["Type","type"],["Audience","audience"],["Industry","industry"],["Location","location"],["Description","description"]];for(let[o,i]of n){let s=e.business[i];t.push(`- **${o}:** ${s||""}`)}let r=new Set(n.map(([,o])=>o));for(let[o,i]of Object.entries(e.business))if(!r.has(o)&&i){let s=o.charAt(0).toUpperCase()+o.slice(1);t.push(`- **${s}:** ${i}`)}if(t.push(""),t.push("# Writing Instructions"),t.push(""),e.writingInstructions.length>0)for(let o of e.writingInstructions)t.push(`- ${o}`);else t.push("- (Add your content writing guidelines here)");if(t.push(""),t.push("# Reference URLs"),t.push(""),e.referenceUrls.length>0)for(let o of e.referenceUrls)o.description?t.push(`- ${o.url} \u2014 ${o.description}`):t.push(`- ${o.url}`);else t.push("- (Add URLs the agent should reference for tone/style)");if(t.push(""),t.push("# Topics to Avoid"),t.push(""),e.topicsToAvoid.length>0)for(let o of e.topicsToAvoid)t.push(`- ${o}`);else t.push("- (Add topics the agent should never write about)");return t.push(""),t.push("# Content Tone"),t.push(""),t.push(e.contentTone||"professional"),t.push(""),t.push("# Additional Notes"),t.push(""),t.push(e.additionalNotes||"(Any other context you want the agent to know about your business, products, or audience.)"),t.push(""),t.join(`
|
|
20
|
+
`)}function hi(e){let t=e.split(`
|
|
21
|
+
`),n=[],r="",o=[];for(let i of t){let s=i.match(/^#\s+(.+)$/);s?(r&&n.push([r,o.join(`
|
|
22
|
+
`)]),r=s[1],o=[]):o.push(i)}return r&&n.push([r,o.join(`
|
|
23
|
+
`)]),n}function yi(e){let t={},n=e.split(`
|
|
24
|
+
`);for(let r of n){let o=r.match(/^[-*]\s+\*\*(.+?):\*\*\s*(.*)$/);if(o){let i=o[1].toLowerCase().trim(),s=o[2].trim();s&&(t[i]=s)}}return t}function Kn(e){let t=[],n=e.split(`
|
|
25
|
+
`);for(let r of n){let o=r.match(/^[-*]\s+(.+)$/);if(o){let i=o[1].trim();(!i.startsWith("(")||!i.endsWith(")"))&&t.push(i)}}return t}function wi(e){let t=[],n=e.split(`
|
|
26
|
+
`);for(let r of n){let o=r.match(/^[-*]\s+(https?:\/\/\S+)(?:\s+[—–-]\s+(.+))?$/);o&&t.push({url:o[1].trim(),description:o[2]?.trim()||""})}return t}var zn="context.md";function Jn(e){let t=Yn(e,".seoagent",zn);if(!$i(t))return null;let n=ki(t,"utf-8");return qn(n)}function Si(e,t){let n=Yn(e,".seoagent",zn),r=Hn(t);bi(n,r,"utf-8")}function Vn(e,t){Si(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as Pe,readFileSync as Qn,readdirSync as xi,statSync as Xn}from"fs";import{join as re}from"path";var vi=[{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 _i(e){let t=re(e,"package.json");if(!Pe(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Qn(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Ci(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 Ei(e){let t={};for(let n of ce){let r=re(e,n);if(Pe(r))try{let o=Qn(r,"utf-8");for(let i of o.split(/\r?\n/)){let s=i.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a===-1)continue;let l=s.slice(0,a).trim();l&&!(l in t)&&(t[l]=n)}}catch{}}return t}function Ai(e,t){let n=re(e,t.replace(/\/$/,""));if(!Pe(n))return!1;if(t.endsWith("/"))try{return Xn(n).isDirectory()}catch{return!1}return!0}function Ii(e){let t=["content","_posts","posts",re("src","content")];for(let n of t){let r=re(e,n);if(Pe(r))try{if(!Xn(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of xi(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(re(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 Ri(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(Pe(re(e,n.marker)))return n.path;return null}function Zn(e){let t=[],{deps:n}=_i(e),r=Ei(e),o="none";for(let s of vi){let a=[];for(let l of Object.keys(n))if(Ci(l,s.deps)){a.push({type:"dep",detail:l,source:"package.json"});break}for(let l of s.envKeys)if(r[l]){a.push({type:"env",detail:l,source:r[l]});break}for(let l of s.fsMarkers)if(Ai(e,l)){let u=l.endsWith("/")?"directory":"file";a.push({type:u,detail:l,source:l});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=Ii(e);s&&(o="mdx-local",t.push(s))}let i=Ri(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as oe,readFileSync as Ft}from"fs";import{join as ie}from"path";function er(e){try{return new URL(e).hostname}catch{return e}}function tr(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 Pi(e){for(let t of ce){let n=ie(e,t);if(!oe(n))continue;let r=Ft(n,"utf-8");for(let o of kn){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=er(s);if(tr(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function Oi(e){let t=ie(e,"package.json");if(!oe(t))return null;try{let n=JSON.parse(Ft(t,"utf-8"));if(!n.homepage)return null;let r=er(n.homepage);return tr(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function nr(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),oe(ie(e,"pnpm-workspace.yaml"))&&n.push({field:"context",detail:"Monorepo workspace detected",source:"pnpm-workspace.yaml \u2014 using this directory for project signals"});let r=null;t?.("Scanning .env files for public / site URLs\u2026");let o=Pi(e);if(o)r=o.value,n.push({field:"domain",detail:o.value,source:o.source});else{t?.("Reading package.json homepage (skipping GitHub/GitLab repo URLs)\u2026");let a=Oi(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=ie(e,"package.json"),s=null;if(oe(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Ft(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>l.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||oe(ie(e,"shopify.config.js"))||oe(ie(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":oe(ie(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),m=u("next");d&&(m||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:m?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:r,siteType:s,evidence:n}}import{existsSync as Ti,readFileSync as Li,readdirSync as Ni,statSync as ji}from"fs";import{join as se,sep as Fi}from"path";var rr=["tsx","jsx","js","mdx","md"],Di=["astro","md","mdx"],Ui=5e3;function st(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let l=Mi(i);if(l===null){r++;return}let u=n.get(l);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(l,{route:l,url:Ji(t,l),in_sitemap:a,source:s})};for(let i of["app",se("src","app")]){let s=se(e,i);if(Dt(s))for(let a of Ut(s)){let l=Mt(s,a),u=l[l.length-1];qi(u)&&(l.some(d=>d.startsWith("@"))||o(Bi(l.slice(0,-1)),"app router"))}}for(let i of["pages",se("src","pages")]){let s=se(e,i);if(Dt(s))for(let a of Ut(s)){let l=Mt(s,a);if(l[0]==="api")continue;let u=l[l.length-1],d=Bt(u),p=rr.includes(d),m=Di.includes(d);if(!p&&!m)continue;let y=at(u);Hi(y)||o(Gi(l),m?"astro":"pages router")}}for(let i of[".","public"]){let s=se(e,i);if(Dt(s))for(let a of Ut(s,i==="."?1:1/0)){let l=Mt(s,a),u=l[l.length-1];Bt(u)==="html"&&(l.some(d=>d==="node_modules"||d.startsWith("."))||o(Wi(l),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=se(e,...i.split("/"));if(Ti(s)){for(let a of Yi(s)){let l=Ki(a);l!==null&&o(l,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}function Mi(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function Bi(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function Gi(e){let t=[...e],n=at(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Wi(e){let t=[...e],n=at(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Ki(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function qi(e){return at(e)==="page"&&rr.includes(Bt(e))}function Hi(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Yi(e){try{let t=Li(e,"utf-8"),n=[],r=/<loc>\s*([^<\s]+)\s*<\/loc>/gi,o;for(;(o=r.exec(t))!==null;)n.push(o[1].trim());return n}catch{return[]}}var zi=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Dt(e){try{return ji(e).isDirectory()}catch{return!1}}function*Ut(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=Ni(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=Ui)return;if(a.name.startsWith("."))continue;let l=se(o,a.name);if(a.isDirectory()){if(zi.has(a.name))continue;yield*r(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*r(e,1)}function Mt(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(Fi).filter(Boolean)}function Bt(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function at(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Ji(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as Vi,writeFileSync as Qi}from"fs";import{join as or}from"path";function sr(e,t){if(t.length===0)return;let n=or(e,$);Vi(n,{recursive:!0});let r=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
|
|
21
27
|
`),o=["# 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(`
|
|
22
|
-
`),i="| URL | In sitemap | In nav | Status | Rendered | Notes |",s="|---|---|---|---|---|---|",a=t.map(u=>`| ${
|
|
23
|
-
`);
|
|
24
|
-
`))}import{existsSync as
|
|
25
|
-
`);if(!r){
|
|
26
|
-
${o}`);let s=await
|
|
28
|
+
`),i="| URL | In sitemap | In nav | Status | Rendered | Notes |",s="|---|---|---|---|---|---|",a=t.map(u=>`| ${ir(u.url)} | ${u.in_sitemap?"yes":"no"} | \u2014 | \u2014 | \u2014 | ${ir(u.source)} |`),l=[r,"",o,"",i,s,...a,""].join(`
|
|
29
|
+
`);Qi(or(n,"pages.md"),l,"utf-8")}function ir(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as fe}from"@clack/prompts";var c={info:e=>fe.info(e),warn:e=>fe.warn(e),error:e=>fe.error(e),success:e=>fe.success(e),step:e=>fe.step(e),message:e=>fe.message(e)};function k(e,t,n,r=n){e?e.stop(r):c[t](n)}var cr=[{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"}],dr="unknown",rs=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function os(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 lt(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return rs.has(t)?t:null}async function Oe(e={}){let t=process.cwd();if(In(t)){c.warn("SEOAgent project already exists in this directory."),c.info(`Run \`${f("status")}\` to see your project state.`),c.info(`To start fresh, run \`${f("uninstall")}\` then init again.`);return}let n=!!e.yes||!process.stdin.isTTY;n||Zi("SEOAgent \u2014 AI SEO Agent");let r=nr(t,a=>c.step(a)),o=()=>{if(r.evidence.length!==0){c.info("Inferred from your project:");for(let a of r.evidence)c.info(` \u2022 ${os(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=lt(e.siteType)||lt(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&<(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()&<(process.env.SEOAGENT_SITE_TYPE)===null&&(c.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),o(),i||(c.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=dr),s||(s="unknown"),await ur(t,i,s);return}if(o(),!i){let a=await lr({message:"Website domain",placeholder:"example.com",validate:l=>l.trim()?void 0:"Domain is required"});me(a)&&(ge("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await Gt({message:"What kind of site is this?",options:[...cr]});me(a)&&(ge("Cancelled"),process.exit(0)),s=a}for(;;){let a=await ns({message:`Create .seoagent for ${i} (${s})?`});if(me(a)&&(ge("Cancelled"),process.exit(0)),a)break;let l=await Gt({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((me(l)||l==="abort")&&(ge("Cancelled"),process.exit(0)),l==="domain"){let u=await lr({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});me(u)&&(ge("Cancelled"),process.exit(0)),i=String(u)}else{let u=await Gt({message:"What kind of site is this?",options:[...cr]});me(u)&&(ge("Cancelled"),process.exit(0)),s=u}}await ur(t,i,s)}async function ur(e,t,n){let r=ts();r.start("Setting up your SEO project");let o=Zn(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:de,install_id:Tt(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{}};On(e),Pn(e,i),Vn(e,n),Mn(e);let s=Dn(e),a=ar(e,s.skillFile),l=Xi(a),u=`${l}/references/audit-checks.md`,d=s.claudeSymlink?ar(e,s.claudeSymlink):void 0;Bn(e);let p=t!==dr,m={pages:[],dynamicCount:0};try{m=st(e,p?t:null),sr(e,m.pages)}catch{}if(r.stop(p?`Created .seoagent/ project for ${i.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let E=o.evidence.map(M=>`${M.detail} (${M.source})`).slice(0,2).join(", ");c.info(`CMS detected: ${o.cms} \u2014 ${E}`)}o.blog_path&&c.info(`Blog route: ${o.blog_path}`),m.pages.length>0&&c.info(`Found ${m.pages.length} page${m.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`+(m.dynamicCount>0?` (plus ${m.dynamicCount} dynamic route template${m.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""));let y=p?i.domain:"your site",v=p?[" 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."];es([p?`\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):","",...v,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${y}`," (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:",` ${f("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${a} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${l} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
|
|
30
|
+
`))}import{existsSync as mr}from"fs";import{intro as ss,outro as as,confirm as ls,isCancel as cs,cancel as us}from"@clack/prompts";import{existsSync as ct,rmSync as is}from"fs";import{join as ut}from"path";function pr(e,t={}){let n=[],r=ut(e,$);ct(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=ut(e,ne.CLAUDE);ct(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=ut(e,ne.AGENTS);return ct(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),Gn(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:ut(e,".claude","settings.json"),kind:"hook"}),t.global&&ct(G)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:G,kind:"global"}),n}function fr(e,t){for(let n of t)n.kind==="hook"?Wn(e):is(n.path,{recursive:!0,force:!0})}async function Te(e={}){let t=process.cwd(),n=pr(t,{global:e.global});if(n.length===0){c.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&mr(G)&&c.info("Your seoagent.com login is still stored at ~/.config/seoagent/. Re-run with --global to wipe it too.");return}let r=!!e.yes||!process.stdin.isTTY,o=n.map(s=>` \u2022 ${s.label}`).join(`
|
|
31
|
+
`);if(!r){ss("SEOAgent \u2014 uninstall"),c.message(`This will remove:
|
|
32
|
+
${o}`);let s=await ls({message:"Remove these and start fresh?"});if(cs(s)||!s){us("Cancelled \u2014 nothing was removed.");return}}fr(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
|
|
27
33
|
`);r?c.success(`Removed:
|
|
28
|
-
${i}`):
|
|
29
|
-
${i}`),!e.global&&
|
|
30
|
-
`,"utf-8");try{
|
|
31
|
-
`)}function Ki(e,t){if(!t)return z.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Xn(t),r=e-5-n;return r<1?z.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${z.dim("\u250C\u2500 ")}${t}${z.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function Hi(e,t){let n=Xn(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${z.dim("\u2502")} ${r} ${z.dim("\u2502")}`}function Pt(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n} minutes ago`;let r=Math.floor(n/60);return r<24?`${r} hours ago`:`${Math.floor(r/24)} days ago`}function Ae(){let e=Vn(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${p("init")}\` to get started.`);return}c.message(qi(e))}function qi(e){if(!e)return"";let t=11,n=s=>b.dim(s.padEnd(t)),r=[];A()?(r.push({content:`${b.green("\u2713")} ${b.dim("Logged in")}`}),r.push({content:b.dim(` Run \`${p("whoami")}\` for email / plan.`)})):(r.push({content:`${b.dim("\u25CB Not logged in")}`}),r.push({content:b.dim(` Run \`${p("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${b.green(`last run ${Pt(e.audit.date??"")}`)} ${b.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${b.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${b.bold(b.cyan(String(e.strategy.clusterCount??0)))} ${b.dim("clusters")} \xB7 ${b.bold(b.cyan(String(e.strategy.articleCount??0)))} ${b.dim("ideas")}`:`${n("Strategy:")}${b.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${b.bold(b.cyan(String(e.briefs.count??0)))} ${b.dim("ready")}`:`${n("Briefs:")}${b.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${b.green("\u2713")} ${b.bold(b.cyan(String(e.content.count??0)))} ${b.dim("articles written")}`:`${n("Content:")}${b.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${b.green("updated")} ${b.dim(Pt(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${b.dim("not yet created")}`});let i=`${b.bold(b.cyan("SEOAgent"))} ${b.dim("\xB7")} ${b.bold(e.domain)}`;return L(r,{width:78,title:i})}import{exec as zi,spawn as Yi}from"child_process";import{confirm as Ji,isCancel as Vi}from"@clack/prompts";import O from"picocolors";var Xi="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Ie="@seoagent-official/seoagent",Pe=["free","starter","pro","scale","enterprise"],tt={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function Qi(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return Pe.includes(t)?t:null}function Zi(e){let t=Pe.indexOf(e);return t===-1||t===Pe.length-1?null:Pe[t+1]}async function es(e,t=fetch){if(!e)return null;try{let n=(e.api_base||S.BASE).replace(/\/$/,""),r=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!r.ok)return null;let o=await r.json();return typeof o.plan!="string"||!o.plan?null:{plan:o.plan,email:typeof o.email=="string"&&o.email?o.email:void 0,domain:typeof o.domain=="string"&&o.domain?o.domain:void 0}}catch{return null}}function ts(e){let t=[],r=s=>O.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${O.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${O.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of Pe){let a=tt[s];s===e.current?t.push({content:`${O.bold(O.green("\u25CF"))} ${O.bold(O.green(a.padEnd(11)))} ${O.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${O.yellow("\u25C6")} ${O.bold(O.yellow(a.padEnd(11)))} ${O.yellow("next tier")}`}):t.push({content:O.dim(` ${a}`)})}let i=`${O.bold(O.cyan("SEOAgent Cloud"))} ${O.dim("\xB7")} ${O.dim("your plan")}`;return L(t,{width:55,title:i})}async function Re(){let e=A(),t=!!process.stdin.isTTY;if(e&&t){let n=await es(e);if(n){let r=Qi(n.plan),o=r?Zi(r):null;if(r&&c.message(ts({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){c.success(`You're on ${tt[r]} (highest tier).`);return}if(r&&o){let i=await Ji({message:`Upgrade from ${tt[r]} to ${tt[o]}?`});if(Vi(i)||!i){c.info("No changes.");return}}}}ns()}function ns(){let e=rs();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}"`;zi(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function rs(){let e=process.cwd(),t=C(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${S.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Te(e={}){let t=ae,n=await is();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 ${Ie}@latest`);return}if(os(t,n)>=0){c.success(`You're on the latest CLI (${t}).`);return}if(!ft()){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 ${Ie}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${Ie}@latest`);return}c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),await ss()?c.success(`Updated to ${n}.`):c.error(`Update failed. Try manually: npm install -g ${Ie}@latest (you may need sudo on Linux/macOS).`)}function os(e,t){let n=i=>i.replace(/[-+].*$/,"").split(".").map(s=>Number.parseInt(s,10)||0).slice(0,3),r=n(e),o=n(t);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s}return 0}async function is(e=fetch){try{let t=await e(Xi,{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 ss(){return new Promise(e=>{let t=Yi("npm",["install","-g",`${Ie}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as as}from"child_process";import{randomBytes as ls}from"crypto";import{isCancel as cs,spinner as us,text as ds}from"@clack/prompts";import Y from"picocolors";function Qn(e,t){if(e>=500)return{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e>=400)return{status:"error",terminal:!0,message:`HTTP ${e} (client error)`};if(!t||typeof t!="object")return{status:"error",terminal:!0,message:`Malformed response: expected an object, got ${typeof t}`};let n=t;if(n.status==="ready"){if(typeof n.user_token=="string"&&typeof n.website_token=="string"){let r=typeof n.email=="string"&&n.email?n.email:void 0,o=typeof n.domain=="string"&&n.domain?n.domain:void 0;return{status:"ready",user_token:n.user_token,website_token:n.website_token,...r?{email:r}:{},...o?{domain:o}:{}}}return{status:"error",terminal:!0,message:"Malformed response: status=ready without user_token+website_token"}}return n.status==="pending"?{status:"pending"}:n.status==="expired"?{status:"expired"}:{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}var ps=1500,ms=300*1e3;function fs(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;as(t,()=>{})}function gs(){return ls(16).toString("hex")}function hs(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function Zn(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 ys(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,r=await fetch(n,{headers:{Accept:"application/json"}}),o=null;try{o=await r.json()}catch{}return Qn(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function ws(e){return new Promise(t=>setTimeout(t,e))}async function Oe(e={}){let t=process.cwd(),n=C(t),r=(e.apiBase||S.BASE||ke).replace(/\/$/,"");if(A()){c.info(`Already logged in. To switch accounts, run \`${p("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let m=await ds({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(y){if(!String(y??"").trim())return"A site URL is required.";if(!Zn(String(y)))return"Please enter a valid domain like `example.com`."}});if(cs(m)){c.warn("Login cancelled.");return}let g=Zn(String(m));if(g){o=g;try{$e(t,{domain:g}),c.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=gs(),s=hs(r,i,o);c.message("Opening seoagent.com to connect this CLI to your account..."),c.info(`If the browser does not open, visit: ${s}`),fs(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?us():null;l?.start(Y.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+ms,d=!0;for(;Date.now()<u;){d||await ws(ps),d=!1;let m=await ys(r,i);if(m.status==="ready"){zn({user_token:m.user_token,website_token:m.website_token,api_base:r});let g=m.email&&m.domain?`Logged in as ${m.email} (${m.domain}). Future SEO work in this repo will sync to your dashboard.`:m.email?`Logged in as ${m.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",y=m.email&&m.domain?`Logged in as ${Y.bold(m.email)} (${Y.cyan(m.domain)}).`:m.email?`Logged in as ${Y.bold(m.email)}.`:"Logged in.";k(l,"success",g,Y.green(y)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(m.status==="expired"){k(l,"warn",`Session expired. Run \`${p("login")}\` again.`,Y.red("Session expired.")),l&&c.warn(`Run \`${p("login")}\` again.`);return}if(m.status==="error"){if(m.terminal){k(l,"warn",`Login failed: ${m.message}. Run \`${p("login")}\` again.`,Y.red(`Login failed: ${m.message}.`)),l&&c.warn(`Run \`${p("login")}\` again.`);return}continue}}k(l,"warn",`Login timed out. Run \`${p("login")}\` again to retry.`,Y.yellow("Login timed out.")),l&&c.warn(`Run \`${p("login")}\` again to retry.`)}function Le(){Yn()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as _a}from"@clack/prompts";import he from"picocolors";import{existsSync as Ft,mkdirSync as la,readFileSync as vr,readdirSync as ca,statSync as ua,writeFileSync as da}from"fs";import{join as Ut,relative as pa,sep as ma}from"path";var ks=new Set([502,503,504]);async function K(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.fetchImpl??fetch,s=n.sleep??bs,a=n.transientStatuses??ks,l=null;for(let u=0;u<r;u++)try{let d=await i(e,t);if(a.has(d.status)&&u<r-1){await s(er(o,u));continue}return d}catch(d){if(l=d,u<r-1){await s(er(o,u));continue}}throw l instanceof Error?l:new Error(String(l))}function er(e,t){return e*Math.pow(3,t)}function bs(e){return new Promise(t=>setTimeout(t,e))}import{existsSync as Tt,mkdirSync as $s,readdirSync as tr,readFileSync as Ss,unlinkSync as vs,writeFileSync as Rt}from"fs";import{join as fe}from"path";import E from"picocolors";function H(e){return fe(e,$,"inbox")}function nr(e){return`${e.action_type}-${e.id}.md`}function xs(e,t){let n=0;if(!Tt(e))return 0;for(let r of tr(e)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(?:.+)-(\d+)\.md$/);if(!o)continue;let i=Number.parseInt(o[1],10);if(!Number.isNaN(i)&&!t.has(i))try{vs(fe(e,r)),n++}catch{}}return n}function _s(e){let t=e.payload||{},n=t.articleId??"unknown",r=t.slug??null,o=t.originalTitle??null,i=t.originalUrl??null,s=t.cmsType??null;return`---
|
|
34
|
+
${i}`):as(`Removed:
|
|
35
|
+
${i}`),!e.global&&mr(G)&&c.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),c.info(`Re-install any time with \`${f("init")}\`.`)}import b from"picocolors";import{existsSync as hr,mkdirSync as gr,readFileSync as ds,writeFileSync as ps,chmodSync as fs,unlinkSync as ms}from"fs";import{dirname as gs}from"path";function R(){if(!hr(J))return null;try{let e=JSON.parse(ds(J,"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||_e}}catch{return null}}function yr(e){gr(G,{recursive:!0}),gr(gs(J),{recursive:!0}),ps(J,JSON.stringify(e,null,2)+`
|
|
36
|
+
`,"utf-8");try{fs(J,384)}catch{}}function wr(){if(!hr(J))return!1;try{return ms(J),!0}catch{return!1}}import{existsSync as Le,readdirSync as Wt,statSync as hs,readFileSync as kr}from"fs";import{join as he}from"path";function ys(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function ws(e){let t=he(e,"audit","latest.md");if(!Le(t))return null;let n=tt(t);if(!n)return null;let r=kr(t,"utf-8"),o=ys(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function ks(e){try{let n=kr(e,"utf-8").split(/\r?\n/),r=!1,o=0;for(let i of n){let s=i.trim();if(s.startsWith("|")&&s.endsWith("|")){if(/^\|\s*-+\s*(\|\s*-+\s*)+\|$/.test(s)){r=!0;continue}r&&o++}else if(r&&s==="")break}return o}catch{return 0}}function bs(e){let t=he(e,"strategy","clusters");if(!Le(t))return null;let n=Wt(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=ks(he(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function $s(e){let t=he(e,"briefs");if(!Le(t))return null;let n=Wt(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Ss(e){let t=he(e,"content");if(!Le(t))return null;let n=Wt(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function xs(e){let t=he(e,"roadmap.md");return Le(t)?{exists:!0,updatedAt:hs(t).mtime.toISOString()}:null}function br(e){let t=I(e);if(!t)return null;let n=Ee(e);return{domain:t.domain,audit:ws(n),strategy:bs(n),briefs:$s(n),content:Ss(n),roadmap:xs(n)}}import V from"picocolors";var vs=/\x1b\[[0-9;]*m/g;function $r(e){return e.replace(vs,"").length}function P(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=_s(n,t.title),s=V.dim(`\u251C${o}\u2524`),a=V.dim(`\u2514${o}\u2518`),l=[i];for(let u of e){if("sep"in u){l.push(s);continue}l.push(Cs(u.content,r))}return l.push(a),l.join(`
|
|
37
|
+
`)}function _s(e,t){if(!t)return V.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=$r(t),r=e-5-n;return r<1?V.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${V.dim("\u250C\u2500 ")}${t}${V.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function Cs(e,t){let n=$r(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${V.dim("\u2502")} ${r} ${V.dim("\u2502")}`}function Kt(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n} minutes ago`;let r=Math.floor(n/60);return r<24?`${r} hours ago`:`${Math.floor(r/24)} days ago`}function Ne(){let e=br(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${f("init")}\` to get started.`);return}c.message(Es(e))}function Es(e){if(!e)return"";let t=11,n=s=>b.dim(s.padEnd(t)),r=[];R()?(r.push({content:`${b.green("\u2713")} ${b.dim("Logged in")}`}),r.push({content:b.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${b.dim("\u25CB Not logged in")}`}),r.push({content:b.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${b.green(`last run ${Kt(e.audit.date??"")}`)} ${b.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${b.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${b.bold(b.cyan(String(e.strategy.clusterCount??0)))} ${b.dim("clusters")} \xB7 ${b.bold(b.cyan(String(e.strategy.articleCount??0)))} ${b.dim("ideas")}`:`${n("Strategy:")}${b.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${b.bold(b.cyan(String(e.briefs.count??0)))} ${b.dim("ready")}`:`${n("Briefs:")}${b.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${b.green("\u2713")} ${b.bold(b.cyan(String(e.content.count??0)))} ${b.dim("articles written")}`:`${n("Content:")}${b.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${b.green("updated")} ${b.dim(Kt(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${b.dim("not yet created")}`});let i=`${b.bold(b.cyan("SEOAgent"))} ${b.dim("\xB7")} ${b.bold(e.domain)}`;return P(r,{width:78,title:i})}import{exec as As,spawn as Is}from"child_process";import{confirm as Rs,isCancel as Ps}from"@clack/prompts";import L from"picocolors";var Os="https://registry.npmjs.org/@seoagent-official/seoagent/latest",je="@seoagent-official/seoagent",Fe=["free","starter","pro","scale","enterprise"],dt={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function Ts(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return Fe.includes(t)?t:null}function Ls(e){let t=Fe.indexOf(e);return t===-1||t===Fe.length-1?null:Fe[t+1]}async function Ns(e,t=fetch){if(!e)return null;try{let n=(e.api_base||x.BASE).replace(/\/$/,""),r=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!r.ok)return null;let o=await r.json();return typeof o.plan!="string"||!o.plan?null:{plan:o.plan,email:typeof o.email=="string"&&o.email?o.email:void 0,domain:typeof o.domain=="string"&&o.domain?o.domain:void 0}}catch{return null}}function js(e){let t=[],r=s=>L.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${L.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${L.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of Fe){let a=dt[s];s===e.current?t.push({content:`${L.bold(L.green("\u25CF"))} ${L.bold(L.green(a.padEnd(11)))} ${L.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${L.yellow("\u25C6")} ${L.bold(L.yellow(a.padEnd(11)))} ${L.yellow("next tier")}`}):t.push({content:L.dim(` ${a}`)})}let i=`${L.bold(L.cyan("SEOAgent Cloud"))} ${L.dim("\xB7")} ${L.dim("your plan")}`;return P(t,{width:55,title:i})}async function De(){let e=R(),t=!!process.stdin.isTTY;if(e&&t){let n=await Ns(e);if(n){let r=Ts(n.plan),o=r?Ls(r):null;if(r&&c.message(js({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){c.success(`You're on ${dt[r]} (highest tier).`);return}if(r&&o){let i=await Rs({message:`Upgrade from ${dt[r]} to ${dt[o]}?`});if(Ps(i)||!i){c.info("No changes.");return}}}}Fs()}function Fs(){let e=Ds();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}"`;As(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function Ds(){let e=process.cwd(),t=I(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${x.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ue(e={}){let t=de,n=await Ms();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 ${je}@latest`);return}if(Us(t,n)>=0){c.success(`You're on the latest CLI (${t}).`);return}if(!It()){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 ${je}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${je}@latest`);return}c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),await Bs()?c.success(`Updated to ${n}.`):c.error(`Update failed. Try manually: npm install -g ${je}@latest (you may need sudo on Linux/macOS).`)}function Us(e,t){let n=i=>i.replace(/[-+].*$/,"").split(".").map(s=>Number.parseInt(s,10)||0).slice(0,3),r=n(e),o=n(t);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s}return 0}async function Ms(e=fetch){try{let t=await e(Os,{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 Bs(){return new Promise(e=>{let t=Is("npm",["install","-g",`${je}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as Gs}from"child_process";import{randomBytes as Ws}from"crypto";import{isCancel as Ks,spinner as qs,text as Hs}from"@clack/prompts";import Q from"picocolors";function Sr(e,t){if(e>=500)return{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e>=400)return{status:"error",terminal:!0,message:`HTTP ${e} (client error)`};if(!t||typeof t!="object")return{status:"error",terminal:!0,message:`Malformed response: expected an object, got ${typeof t}`};let n=t;if(n.status==="ready"){if(typeof n.user_token=="string"&&typeof n.website_token=="string"){let r=typeof n.email=="string"&&n.email?n.email:void 0,o=typeof n.domain=="string"&&n.domain?n.domain:void 0;return{status:"ready",user_token:n.user_token,website_token:n.website_token,...r?{email:r}:{},...o?{domain:o}:{}}}return{status:"error",terminal:!0,message:"Malformed response: status=ready without user_token+website_token"}}return n.status==="pending"?{status:"pending"}:n.status==="expired"?{status:"expired"}:{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}var Ys=1500,zs=300*1e3;function Js(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;Gs(t,()=>{})}function Vs(){return Ws(16).toString("hex")}function Qs(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function xr(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 Xs(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,r=await fetch(n,{headers:{Accept:"application/json"}}),o=null;try{o=await r.json()}catch{}return Sr(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Zs(e){return new Promise(t=>setTimeout(t,e))}async function Me(e={}){let t=process.cwd(),n=I(t),r=(e.apiBase||x.BASE||_e).replace(/\/$/,"");if(R()){c.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let p=await Hs({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(y){if(!String(y??"").trim())return"A site URL is required.";if(!xr(String(y)))return"Please enter a valid domain like `example.com`."}});if(Ks(p)){c.warn("Login cancelled.");return}let m=xr(String(p));if(m){o=m;try{Ae(t,{domain:m}),c.success(`Saved domain: ${m} \u2192 .seoagent/project.md`)}catch{}}}let i=Vs(),s=Qs(r,i,o);c.message("Opening seoagent.com to connect this CLI to your account..."),c.info(`If the browser does not open, visit: ${s}`),Js(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?qs():null;l?.start(Q.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+zs,d=!0;for(;Date.now()<u;){d||await Zs(Ys),d=!1;let p=await Xs(r,i);if(p.status==="ready"){yr({user_token:p.user_token,website_token:p.website_token,api_base:r});let m=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.",y=p.email&&p.domain?`Logged in as ${Q.bold(p.email)} (${Q.cyan(p.domain)}).`:p.email?`Logged in as ${Q.bold(p.email)}.`:"Logged in.";k(l,"success",m,Q.green(y)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){k(l,"warn",`Session expired. Run \`${f("login")}\` again.`,Q.red("Session expired.")),l&&c.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){k(l,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,Q.red(`Login failed: ${p.message}.`)),l&&c.warn(`Run \`${f("login")}\` again.`);return}continue}}k(l,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,Q.yellow("Login timed out.")),l&&c.warn(`Run \`${f("login")}\` again to retry.`)}function Be(){wr()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as sl}from"@clack/prompts";import be from"picocolors";import{existsSync as Qt,mkdirSync as Wa,readFileSync as Yr,readdirSync as Ka,statSync as qa,writeFileSync as Ha}from"fs";import{join as Xt,relative as Ya,sep as za}from"path";var ea=new Set([502,503,504]);async function H(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.fetchImpl??fetch,s=n.sleep??ta,a=n.transientStatuses??ea,l=null;for(let u=0;u<r;u++)try{let d=await i(e,t);if(a.has(d.status)&&u<r-1){await s(vr(o,u));continue}return d}catch(d){if(l=d,u<r-1){await s(vr(o,u));continue}}throw l instanceof Error?l:new Error(String(l))}function vr(e,t){return e*Math.pow(3,t)}function ta(e){return new Promise(t=>setTimeout(t,e))}import{existsSync as Ht,mkdirSync as na,readdirSync as _r,readFileSync as ra,unlinkSync as oa,writeFileSync as qt}from"fs";import{join as we}from"path";import A from"picocolors";function Y(e){return we(e,$,"inbox")}function Cr(e){return`${e.action_type}-${e.id}.md`}function ia(e,t){let n=0;if(!Ht(e))return 0;for(let r of _r(e)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(?:.+)-(\d+)\.md$/);if(!o)continue;let i=Number.parseInt(o[1],10);if(!Number.isNaN(i)&&!t.has(i))try{oa(we(e,r)),n++}catch{}}return n}function sa(e){let t=e.payload||{},n=t.articleId??"unknown",r=t.slug??null,o=t.originalTitle??null,i=t.originalUrl??null,s=t.cmsType??null;return`---
|
|
32
38
|
action_id: ${e.id}
|
|
33
39
|
action_type: ${e.action_type}
|
|
34
40
|
article_id: ${n}
|
|
@@ -61,7 +67,7 @@ typically that's a markdown or MDX file matching the slug under \`content/\`,
|
|
|
61
67
|
After deleting (and committing if you want), run:
|
|
62
68
|
|
|
63
69
|
\`\`\`bash
|
|
64
|
-
${
|
|
70
|
+
${f(`ack ${e.id}`)}
|
|
65
71
|
\`\`\`
|
|
66
72
|
|
|
67
73
|
That marks the action \`completed\` server-side and removes this inbox file
|
|
@@ -69,10 +75,10 @@ on the next \`seoagent sync\`. If you decided NOT to remove the file (false
|
|
|
69
75
|
positive, you disagree, etc.), close it out as failed with a reason:
|
|
70
76
|
|
|
71
77
|
\`\`\`bash
|
|
72
|
-
${
|
|
78
|
+
${f(`ack ${e.id}`)} --failed --reason "kept; performs well off-search"
|
|
73
79
|
\`\`\`
|
|
74
|
-
`}function
|
|
75
|
-
`)}}function
|
|
80
|
+
`}function aa(e){switch(e){case"meta":return"Apply the **meta** fix \u2014 set the page's `<title>` / `<meta name=\"description\">` (or the framework's metadata API / frontmatter).";case"schema":return"Apply the **schema** fix \u2014 add or correct the JSON-LD structured data on the page.";case"canonical":return'Apply the **canonical** fix \u2014 set the correct `<link rel="canonical">` on the page.';case"internal_link":return"Apply the **internal_link** fix \u2014 add relevant internal links from related pages (look for high-authority pages on the same topic).";default:return["Apply the change for this issue:",' - **meta** \u2014 fix the `<title>` / `<meta name="description">` (or the framework\'s metadata API / frontmatter).'," - **schema** \u2014 add or correct JSON-LD structured data.",' - **canonical** \u2014 set the correct `<link rel="canonical">`.'," - **internal_link** \u2014 add relevant internal links (fix orphan/low-link pages)."," - **other** \u2014 follow the recommendation above."].join(`
|
|
81
|
+
`)}}function la(e,t,n){if(n)return`Locate the page's source. It renders at \`${n}\` \u2014 find the matching route/template/markdown in this repo (look under \`app/\`, \`pages/\`, \`src/\`, \`content/\`).`;let r=(t||"").toLowerCase();return r.includes("robots")||r.includes("ai_bot")||r.includes("bot_policy")?"This is a site-wide policy issue. Edit `robots.txt` at the site root (or its generator \u2014 `app/robots.ts`, `public/robots.txt`, etc.) to add the appropriate `User-agent:` / `Allow:` / `Disallow:` rules.":r.includes("sitemap")?"This is a sitemap configuration issue. Edit your sitemap generator \u2014 `app/sitemap.ts`, `pages/sitemap.xml.ts`, `next-sitemap.config.js`, or the static `public/sitemap.xml`.":e==="canonical"?'This is a site-wide canonical pattern. Look in the layout/template that wraps your pages (e.g. `app/layout.tsx`, `_app.tsx`, theme `head` partial) \u2014 that\'s where the `<link rel="canonical">` is set for every page.':e==="schema"?"This is a site-wide schema gap. Apply JSON-LD to the layout/template (for Organization-level schema) or to specific page templates (for Article / Product / FAQPage etc.).":e==="meta"?"This is a site-wide metadata convention. Look at the page-template metadata \u2014 Next.js `generateMetadata()` / `metadata` export, Nuxt `useHead()`, Astro frontmatter, etc.":e==="internal_link"?"No specific page on file. Identify pages on the same topic/cluster from `.seoagent/strategy/clusters/` and add inbound links to the target page.":"This issue does not name a single page. Read the recommendation above, identify the relevant template/config in this repo, and apply the change there."}function ca(e){let t=e.payload||{},n=t.page_url??null,r=t.issue??"other",o=t.check_id??"unknown",i=t.severity??"unknown",s=t.recommended_fix??null;return`---
|
|
76
82
|
action_id: ${e.id}
|
|
77
83
|
action_type: ${e.action_type}
|
|
78
84
|
issue: ${r}
|
|
@@ -95,8 +101,8 @@ ${s??e.description??"Apply the appropriate fix for this issue."}
|
|
|
95
101
|
|
|
96
102
|
## How to apply
|
|
97
103
|
|
|
98
|
-
1. ${
|
|
99
|
-
2. ${
|
|
104
|
+
1. ${la(r,o,n)}
|
|
105
|
+
2. ${aa(r)}
|
|
100
106
|
3. Show the user the diff before committing (confirm once per session, then proceed).
|
|
101
107
|
|
|
102
108
|
## How to close this out
|
|
@@ -104,16 +110,16 @@ ${s??e.description??"Apply the appropriate fix for this issue."}
|
|
|
104
110
|
After applying:
|
|
105
111
|
|
|
106
112
|
\`\`\`bash
|
|
107
|
-
${
|
|
113
|
+
${f(`ack ${e.id}`)}
|
|
108
114
|
\`\`\`
|
|
109
115
|
|
|
110
116
|
That marks the action \`completed\` server-side and removes this inbox file on the
|
|
111
117
|
next \`seoagent sync\`. If you disagree or it's a false positive, decline it:
|
|
112
118
|
|
|
113
119
|
\`\`\`bash
|
|
114
|
-
${
|
|
120
|
+
${f(`ack ${e.id}`)} --failed --reason "not applicable; ..."
|
|
115
121
|
\`\`\`
|
|
116
|
-
`}function
|
|
122
|
+
`}function ua(e){let t=e.payload||{},n=t.brief_slug??null,r=t.primary_keyword??null,o=t.cluster??null,i=t.role??null,s=t.search_intent??null,a=t.priority??"medium";return`---
|
|
117
123
|
action_id: ${e.id}
|
|
118
124
|
action_type: ${e.action_type}
|
|
119
125
|
brief_slug: ${n??""}
|
|
@@ -154,15 +160,15 @@ is auto-generated.
|
|
|
154
160
|
After writing (and publishing/committing):
|
|
155
161
|
|
|
156
162
|
\`\`\`bash
|
|
157
|
-
${
|
|
163
|
+
${f(`ack ${e.id}`)}
|
|
158
164
|
\`\`\`
|
|
159
165
|
|
|
160
166
|
If you decide not to write it (off-strategy, duplicate, etc.), decline it:
|
|
161
167
|
|
|
162
168
|
\`\`\`bash
|
|
163
|
-
${
|
|
169
|
+
${f(`ack ${e.id}`)} --failed --reason "skipped; ..."
|
|
164
170
|
\`\`\`
|
|
165
|
-
`}function
|
|
171
|
+
`}function da(e){let t=e.payload||{},n=t.page_url??null,r=t.reason??"stale_thin",o=t.metrics??null,i=o?Object.entries(o).map(([s,a])=>`- **${s}**: ${a??"(n/a)"}`).join(`
|
|
166
172
|
`):"- (no metrics)";return`---
|
|
167
173
|
action_id: ${e.id}
|
|
168
174
|
action_type: ${e.action_type}
|
|
@@ -201,15 +207,15 @@ ${i}
|
|
|
201
207
|
After revising:
|
|
202
208
|
|
|
203
209
|
\`\`\`bash
|
|
204
|
-
${
|
|
210
|
+
${f(`ack ${e.id}`)}
|
|
205
211
|
\`\`\`
|
|
206
212
|
|
|
207
213
|
If you disagree (page is fine as-is, intentionally short, etc.), decline it:
|
|
208
214
|
|
|
209
215
|
\`\`\`bash
|
|
210
|
-
${
|
|
216
|
+
${f(`ack ${e.id}`)} --failed --reason "kept as-is; ..."
|
|
211
217
|
\`\`\`
|
|
212
|
-
`}function
|
|
218
|
+
`}function pa(e){let t=e.payload||{},n=t.sitemap_url??null,r=t.known_url_count??0,o=Array.isArray(t.urls)?t.urls:[],i=!!t.truncated,s=o.length>0?`\`\`\`
|
|
213
219
|
${o.join(`
|
|
214
220
|
`)}
|
|
215
221
|
\`\`\`${i?`
|
|
@@ -247,15 +253,15 @@ ${s}
|
|
|
247
253
|
Once the sitemap is served at \`${n??"/sitemap.xml"}\` (deploy if needed \u2014 GSC fetches the live URL):
|
|
248
254
|
|
|
249
255
|
\`\`\`bash
|
|
250
|
-
${
|
|
256
|
+
${f(`ack ${e.id}`)}
|
|
251
257
|
\`\`\`
|
|
252
258
|
|
|
253
259
|
SEOAgent re-submits the sitemap to GSC on its schedule. If a sitemap already exists and is correct, decline:
|
|
254
260
|
|
|
255
261
|
\`\`\`bash
|
|
256
|
-
${
|
|
262
|
+
${f(`ack ${e.id}`)} --failed --reason "sitemap already served at /sitemap.xml"
|
|
257
263
|
\`\`\`
|
|
258
|
-
`}function
|
|
264
|
+
`}function fa(e){let t=e.payload||{},n=t.keyword??null,r=t.opportunity??"easy_win",o=t.volume??null,i=t.difficulty??null,s=t.intent??null,a=r==="competitor_gap"?"competitor gap (a rival ranks top-10 here, you don't)":"easy win (low difficulty, real volume)";return`---
|
|
259
265
|
action_id: ${e.id}
|
|
260
266
|
action_type: ${e.action_type}
|
|
261
267
|
keyword: ${n??""}
|
|
@@ -304,19 +310,19 @@ ${e.description??""}
|
|
|
304
310
|
After publishing (and committing):
|
|
305
311
|
|
|
306
312
|
\`\`\`bash
|
|
307
|
-
${
|
|
313
|
+
${f(`ack ${e.id}`)}
|
|
308
314
|
\`\`\`
|
|
309
315
|
|
|
310
316
|
If you decide *not* to write it (already covered elsewhere, off-strategy, etc.),
|
|
311
317
|
decline it:
|
|
312
318
|
|
|
313
319
|
\`\`\`bash
|
|
314
|
-
${
|
|
320
|
+
${f(`ack ${e.id}`)} --failed --reason "skipped; ..."
|
|
315
321
|
\`\`\`
|
|
316
|
-
`}function
|
|
322
|
+
`}function ma(e){switch(e.action_type){case"cli_prune_pending":return sa(e);case"cli_technical_fix":return ca(e);case"cli_new_content":return ua(e);case"cli_content_update":return da(e);case"cli_sitemap_update":return pa(e);case"cli_new_landing_page":return fa(e);default:return null}}function ga(e){if(e.length===0)return`# SEOAgent Inbox
|
|
317
323
|
|
|
318
324
|
No pending actions. Run \`seoagent sync\` later to check for new ones.
|
|
319
|
-
`;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${
|
|
325
|
+
`;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${Cr(n)}\``);return`# SEOAgent Inbox
|
|
320
326
|
|
|
321
327
|
You have **${e.length}** pending action${e.length===1?"":"s"} from your dashboard.
|
|
322
328
|
|
|
@@ -328,7 +334,7 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
|
|
|
328
334
|
|
|
329
335
|
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
330
336
|
skill knows what to do.
|
|
331
|
-
`}function
|
|
337
|
+
`}function ae(e){let t=Y(e);if(!Ht(t))return[];let n=[];for(let r of _r(t)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(.+)-(\d+)\.md$/);if(!o)continue;let i=o[1],s=Number.parseInt(o[2],10);if(!Number.isFinite(s))continue;let a="no title",l=null,u=null,d=null,p=null,m=null,y=null;try{let v=ra(we(t,r),"utf-8"),E=v.match(/^---\n([\s\S]*?)\n---/);if(E){let B=E[1];l=ye(B,"severity"),u=ye(B,"issue"),d=ye(B,"page_url");let te=ye(B,"priority");(te==="high"||te==="medium"||te==="low")&&(p=te),m=ye(B,"impact_estimate"),y=ye(B,"effort_estimate")}let _=v.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);_&&(a=_[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:l,issue:u,page_url:d,priority:p,impact_estimate:m,effort_estimate:y})}return n.sort((r,o)=>r.id-o.id)}function ke(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=ha[e.severity??""]??A.dim,r=e.severity??"unknown",o=[A.dim("\u25B8"),A.bold(`id ${e.id}`),A.dim("\xB7"),A.cyan(t),n(r)];if(e.priority){let i=ya[e.priority];o.push(A.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(A.dim("\xB7"),A.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(A.dim("\xB7"),A.dim(`\u23F1 ${e.effort_estimate}`)),o.push(A.dim("\u2014"),e.title),o.join(" ")}var ha={critical:e=>A.red(A.bold(e)),high:e=>A.red(e),medium:e=>A.yellow(e),low:e=>A.dim(e)},ya={high:e=>A.red(A.bold(e)),medium:e=>A.yellow(e),low:e=>A.dim(e)};function ye(e,t){let n=e.match(new RegExp(`^${t}:[ \\t]*([^\\n]*?)[ \\t]*$`,"m"));if(!n)return null;let r=n[1].replace(/^["']|["']$/g,"").trim();return!r||r==="null"||r==="~"?null:r}function pt(e){let t=Y(e);if(!Ht(t))return;let n=ae(e),r=n.length===0?`# SEOAgent Inbox
|
|
332
338
|
|
|
333
339
|
No pending actions. Run \`seoagent sync\` later to check for new ones.
|
|
334
340
|
`:`# SEOAgent Inbox
|
|
@@ -343,34 +349,34 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
|
|
|
343
349
|
|
|
344
350
|
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
345
351
|
skill knows what to do.
|
|
346
|
-
`;
|
|
347
|
-
`,"utf-8")}catch{}return l}import{existsSync as
|
|
348
|
-
`,"utf-8")}function
|
|
352
|
+
`;qt(we(t,"README.md"),r,"utf-8")}function Er(e,t){let n=Y(e);na(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=ia(n,r),i=0;for(let s of t){let a=ma(s);a!==null&&(qt(we(n,Cr(s)),a,"utf-8"),i++)}return qt(we(n,"README.md"),ga(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as ba}from"crypto";import{existsSync as Rr,mkdirSync as $a,readFileSync as Sa,statSync as Pr,writeFileSync as Ir,rmSync as xa}from"fs";import{dirname as va,join as Yt,sep as _a}from"path";function wa(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var ka=[{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 Ar(e,t){let n=wa(e);for(let{cls:r,test:o}of ka)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function Ca(e){return"sha256:"+ba("sha256").update(e).digest("hex")}function Ea(e,t,n={}){let r=[];for(let o of e.artifacts){let i=t[o.path]??{exists:!1,locallyEdited:!1};if(!i.exists){r.push({path:o.path,kind:"write",body:o.body_md});continue}if(i.contentHash===o.content_hash){r.push({path:o.path,kind:"skip"});continue}if(o.generated){r.push({path:o.path,kind:"overwrite",body:o.body_md,note:i.locallyEdited?"discarded local edits \u2014 this is a cloud-generated file (edit it in the dashboard)":void 0});continue}if(i.locallyEdited&&!n.force){r.push({path:o.path,kind:"conflict",note:"local newer than cloud, keeping local \u2014 use --force to take cloud"});continue}r.push({path:o.path,kind:"overwrite",body:o.body_md})}for(let o of e.deleted){let i=t[o];if(!(!i||!i.exists)){if(i.locallyEdited&&!n.force){r.push({path:o,kind:"delete-skipped",note:"server deleted this but it has local edits \u2014 keeping it (use --force to delete)"});continue}r.push({path:o,kind:"delete"})}}return r}function Aa(e,t,n,r){let o=new Map;for(let s of t.artifacts)o.set(s.path,s.generated);let i=[];for(let s of e)s.kind!=="skip"&&i.push({path:s.path,kind:s.kind,class:Ar(s.path,o.get(s.path)??!1),...s.note?{note:s.note}:{}});return i.length===0?null:{pulled_at:r,cursor:n,changes:i}}async function Or(e){let t=await Lr({apiBase:e.apiBase,authHeader:e.authHeader,since:null,fetchImpl:e.fetchImpl});if(!t.ok)return{ok:!1,error:t.error};let n=e.path.replace(/^\/+/,"").replace(/\\/g,"/"),r=t.manifest.artifacts.find(o=>o.path===n);return r?{ok:!0,body:r.body_md}:{ok:!1,error:`No cloud artifact found at "${n}"`}}function Tr(e,t){return Yt(e,t.split("/").join(_a))}function Ia(e,t,n){let r={};for(let o of t){let i=Tr(e,o);if(!Rr(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=Pr(i),a=n[o],l=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:Ca(Sa(i,"utf-8")),locallyEdited:l}}return r}async function Lr(e){let t=e.fetchImpl??fetch,n=`${e.apiBase}/api/cli/sync`+(e.since?`?since=${encodeURIComponent(e.since)}`:"");try{let r=await t(n,{method:"GET",headers:{Authorization:e.authHeader,Accept:"application/json"}});if(!r.ok){let i=await r.text().catch(()=>"");return{ok:!1,error:`${r.status} ${i.slice(0,200)}`.trim()}}let o=await r.json().catch(()=>null);return!o||!Array.isArray(o.artifacts)||typeof o.now!="string"?{ok:!1,error:"Malformed manifest response"}:(Array.isArray(o.deleted)||(o.deleted=[]),{ok:!0,manifest:o})}catch(r){return{ok:!1,error:r.message}}}async function Nr(e){let t=Yt(e.projectDir,$),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!Rr(t))return{...n,ok:!0};let r=await Lr({apiBase:e.apiBase,authHeader:e.authHeader,since:e.since,fetchImpl:e.fetchImpl});if(!r.ok)return{...n,ok:!1,error:r.error};let o=r.manifest,i=[...o.artifacts.map(d=>d.path),...o.deleted],s=Ia(t,i,e.stateFiles),a=Ea(o,s,{force:e.force}),l={...n,cursor:o.now};for(let d of a){let p=Tr(t,d.path);try{switch(d.kind){case"skip":l.skipped++;break;case"write":case"overwrite":{$a(va(p),{recursive:!0}),Ir(p,d.body??"","utf-8");let m=Pr(p);e.stateFiles[d.path]={mtime:m.mtimeMs,size:m.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":xa(p,{force:!0}),delete e.stateFiles[d.path],l.deleted++;break;case"delete-skipped":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(m){l.ok=!1,l.error=`${d.path}: ${m.message}`}}(l.conflicts>0||!l.ok)&&(l.cursor=e.since);let u=Aa(a,o,l.cursor,new Date().toISOString());if(u)try{Ir(Yt(t,$n),JSON.stringify(u,null,2)+`
|
|
353
|
+
`,"utf-8")}catch{}return l}import{existsSync as Fr,mkdirSync as Dr,readFileSync as Ra,writeFileSync as zt}from"fs";import{dirname as Ur,join as Pa}from"path";var Jt=1,jr=500;function Vt(e){return Pa(e,$,Sn)}function ft(e){let t=Vt(e);if(!Fr(t))return[];try{let n=Ra(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==Jt||!Array.isArray(o.entries)?[]:o.entries.filter(Oa)}catch{return[]}}function Mr(e,t){let n=Vt(e),o=ft(e).filter(a=>a.action_id!==t.action_id);o.push({action_id:t.action_id,status:t.status,reason:t.reason,queued_at:new Date().toISOString()});let i=o.length>jr?o.slice(-jr):o,s={version:Jt,entries:i};try{Dr(Ur(n),{recursive:!0}),zt(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function Br(e,t){if(t.length===0)return;let n=Vt(e),r=ft(e).filter(i=>!t.includes(i.action_id)),o={version:Jt,entries:r};try{if(r.length===0&&Fr(n)){zt(n,JSON.stringify(o,null,2),"utf-8");return}Dr(Ur(n),{recursive:!0}),zt(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function Oa(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.action_id=="number"&&(t.status==="completed"||t.status==="failed")&&(t.reason===null||typeof t.reason=="string")&&typeof t.queued_at=="string"}import{existsSync as Gr,readFileSync as Ta,unlinkSync as La,writeFileSync as Na,openSync as ja,closeSync as Fa,mkdirSync as Da}from"fs";import{dirname as Ua,join as Ma}from"path";var Ba=6e4;function Wr(e){return Ma(e,$,xn)}function Kr(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??Ba,i=Wr(e);if(!Gr(i))return mt(i,r,n());let s=Hr(i);return!s||n()-s.started_at>o||!Ga(s.pid)?mt(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function qr(e,t={}){let n=t.pid??process.pid,r=Wr(e);if(!Gr(r))return;let o=Hr(r);if(!(o&&o.pid!==n))try{La(r)}catch{}}function mt(e,t,n){let r={pid:t,started_at:n};try{Da(Ua(e),{recursive:!0});let o=ja(e,"w");try{Na(o,JSON.stringify(r))}finally{Fa(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Hr(e){try{let t=Ta(e,"utf-8"),n=JSON.parse(t);return n&&typeof n=="object"&&typeof n.pid=="number"&&typeof n.started_at=="number"?n:null}catch{return null}}function Ga(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var Ja=new Set([".md"]),Va=new Set(["inbox"]);function Qa(e){let t=[];function n(r,o){if(Qt(r))for(let i of Ka(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Va.has(i.name))continue;let s=Xt(r,i.name);if(i.isDirectory())n(s,o?`${o}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),l=a===-1?"":i.name.slice(a);Ja.has(l)&&t.push(s)}}}return n(e,""),t}function zr(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Xt(Rt,`${t}.json`)}function Xa(e){let t=zr(e);if(!Qt(t))return{files:{},last_synced_at:null};try{return JSON.parse(Yr(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Za(e,t){Wa(Rt,{recursive:!0}),Ha(zr(e),JSON.stringify(t,null,2)+`
|
|
354
|
+
`,"utf-8")}function el(e,t){return Ya(e,t).split(za).join("/")}async function tl(e,t){try{let n=await H(`${e}/api/cli/actions/fetch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t},body:JSON.stringify({})});if(!n.ok){let o=await n.text().catch(()=>"");return{ok:!1,actions:[],error:`${n.status} ${o.slice(0,200)}`}}let r=await n.json().catch(()=>null);return!r||r.status!=="ok"||!Array.isArray(r.actions)?{ok:!1,actions:[],error:"Malformed response"}:{ok:!0,actions:r.actions}}catch(n){return{ok:!1,actions:[],error:n.message}}}async function nl(e,t,n){try{let r=await H(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,status:r.status,error:o.slice(0,200)}}return{ok:!0,status:r.status}}catch(r){return{ok:!1,status:0,error:r.message}}}async function Jr(e,t={}){let n=R();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=I(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=Xt(e,$);if(!Qt(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!Kr(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await rl(e,t,n,r,o)}finally{qr(e)}}async function rl(e,t,n,r,o){let i=Xa(r.domain),s=Qa(o),a=n.api_base||x.BASE,l=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,p=[],m=0,y=await ol(e,a,l);if(!t.pullOnly)for(let T of s){let ve=el(o,T);if(t.pathFilter&&!ve.endsWith(t.pathFilter))continue;let Qe=qa(T),Et=i.files[ve];if(!(!Et||Et.mtime!==Qe.mtimeMs||Et.size!==Qe.size)&&!t.force)continue;m++;let Uo=Yr(T,"utf-8"),At=await nl(a,{path:ve,contents:Uo,domain:r.domain},l);At.ok?(i.files[ve]={mtime:Qe.mtimeMs,size:Qe.size},u++):(d++,p.push(`${ve}: ${At.status} ${At.error??""}`.trim()))}let v=await tl(a,l),E=0,M=0;if(v.ok){let T=Er(e,v.actions);E=T.wrote,M=T.removed}else v.error&&p.push(`pull actions: ${v.error}`);let _,B=!1,te=i.last_synced_at;if(!t.pushOnly){let T=await Nr({projectDir:e,apiBase:a,authHeader:l,since:i.last_synced_at,stateFiles:i.files,force:t.force});T.ok?te=T.cursor:(B=!0,T.error&&p.push(`pull: ${T.error}`)),_={written:T.written,overwritten:T.overwritten,skipped:T.skipped,conflicts:T.conflicts,deleted:T.deleted,warnings:T.warnings}}let Do=!!_&&_.written+_.overwritten+_.deleted+_.conflicts>0;if(i.last_synced_at=te,Za(r.domain,i),m===0&&E===0&&M===0&&!Do&&y.flushed===0&&y.dropped===0&&!B&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:p,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:_};let wn=d===0&&!B;return{ok:wn,reason:wn?void 0:"error",synced:u,failed:d,errors:p,actionsPulled:E,actionsRemoved:M,acksFlushed:y.flushed,acksDropped:y.dropped,pull:_}}async function ol(e,t,n){let r=ft(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let l=await il(a,t,n);l==="flushed"?(o++,s.push(a.action_id)):l==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&Br(e,s),{flushed:o,dropped:i}}async function il(e,t,n){try{let r=await H(`${t}/api/cli/actions/${e.action_id}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify({status:e.status,error_message:e.status==="failed"?e.reason:null,result:e.status==="failed"?{declined:!0,reason:e.reason}:{applied:!0}})});return r.ok?"flushed":r.status===409||r.status>=400&&r.status<500?"already-settled":"transient"}catch{return"transient"}}async function K(e={}){let t=!e.silent&&!!process.stdout.isTTY,n=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",r=t?sl():null;r?.start(`${n} ${be.dim(".seoagent/")} with your dashboard\u2026`);let o=await Jr(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){o.ok||(process.exitCode=0);return}if(o.reason==="no-auth"){k(r,"info",`Not logged in. Run \`${f("login")}\` to enable cloud sync.`,be.dim("Not logged in \u2014 cloud sync skipped.")),r&&c.info(`Run \`${f("login")}\` to enable cloud sync.`);return}if(o.reason==="no-project"){k(r,"info",`No SEOAgent project here. Run \`${f("init")}\` first.`,be.dim("No SEOAgent project \u2014 sync skipped.")),r&&c.info(`Run \`${f("init")}\` first.`);return}if(o.reason==="no-changes"){k(r,"info","Already in sync.",be.green("Already in sync."));return}if(o.reason==="busy"){k(r,"info","Another sync is in progress \u2014 skipping this run.",be.dim("Another sync is in progress \u2014 skipping this run."));return}let i=al(o);k(r,"success",i??"Sync complete.",be.green(i??"Sync complete.")),o.synced>0&&c.success(`Synced ${o.synced} file${o.synced===1?"":"s"} to your dashboard.`);let s=o.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(o.acksFlushed&&o.acksFlushed>0&&c.success(`Flushed ${o.acksFlushed} offline ack${o.acksFlushed===1?"":"s"} from the queue.`),o.acksDropped&&o.acksDropped>0&&c.info(`Dropped ${o.acksDropped} stale ack${o.acksDropped===1?"":"s"} (already settled server-side).`),o.actionsPulled&&o.actionsPulled>0&&(c.success(`Pulled ${o.actionsPulled} pending action${o.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||c.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),o.actionsRemoved&&o.actionsRemoved>0&&c.info(`Cleaned up ${o.actionsRemoved} stale inbox file${o.actionsRemoved===1?"":"s"}.`),o.failed>0){c.warn(`${o.failed} file${o.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let a of o.errors.slice(0,3))c.info(` \u2022 ${a}`)}}function al(e){let t=e.synced,n=e.pull?e.pull.written+e.pull.overwritten:0,r=e.actionsPulled??0,o=e.acksFlushed??0,i=e.pull?.conflicts??0,s=[];return o>0&&s.push(`${o} ack${o===1?"":"s"} flushed`),t>0&&s.push(`${t} pushed`),n>0&&s.push(`${n} pulled`),r>0&&s.push(`${r} action${r===1?"":"s"}`),i>0&&s.push(`${i} conflict${i===1?"":"s"}`),s.length===0&&e.failed===0?null:s.length>0?s.join(" \xB7 "):"Sync complete."}function F(e){let t=I(e);return t||(c.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function le(e={}){if(e.print){let t=R();if(!t){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!F(process.cwd()))return;let n=t.api_base||x.BASE,r=await Or({apiBase:n,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!r.ok){c.warn(r.error),process.exitCode=1;return}process.stdout.write(r.body),r.body.endsWith(`
|
|
349
355
|
`)||process.stdout.write(`
|
|
350
|
-
`);return}await
|
|
351
|
-
`);return}if(n.length===0){c.info(
|
|
352
|
-
`+
|
|
353
|
-
${
|
|
354
|
-
`);for(let n=t.length-1;n>=0;n--){let r=t[n].match(/^__(APPLIED|DECLINED)__:\s*(.*)$/);if(!r)continue;let o=r[2].trim();return r[1]==="APPLIED"?{kind:"applied",summary:o}:{kind:"declined",reason:o}}return null}async function
|
|
355
|
-
`),!(l.subtype==="success"&&!l.is_error))return{kind:"failed"};let d=
|
|
356
|
-
`),c.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function
|
|
357
|
-
`);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(
|
|
358
|
-
`)}}var
|
|
359
|
-
`),a&&process.stdout.write(
|
|
360
|
-
`);return}let l=
|
|
361
|
-
`)}function
|
|
362
|
-
`).filter(Boolean).length;return
|
|
363
|
-
`).filter(o=>o.trim().length>0).length;return
|
|
364
|
-
`)[0]?.trim()??"";if(/^Found\s+\d+/.test(r))return
|
|
365
|
-
`).filter(i=>i.trim()).length;return
|
|
366
|
-
`),o=r.slice(0,5).map(u=>
|
|
356
|
+
`);return}await K({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as ll,readdirSync as cl,unlinkSync as ul}from"fs";import{join as Vr}from"path";import{isCancel as dl,select as pl}from"@clack/prompts";async function X(e,t={}){let n=null;if(e){let u=Number.parseInt(e,10);if(Number.isNaN(u)||u<=0){c.error(`Invalid action id: "${e}"`),process.exitCode=1;return}n=u}else if(n=await fl(),n===null)return;let r=n,o=R();if(!o){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!F(process.cwd()))return;let i=o.api_base||x.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",l;try{l=await H(`${i}/api/cli/actions/${r}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:s},body:JSON.stringify({status:a,error_message:t.failed&&t.reason?t.reason:null,result:t.failed?{declined:!0,reason:t.reason??null}:{applied:!0}})})}catch{Mr(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),Zt(r),pt(process.cwd()),t.silent||c.warn(`Network unavailable \u2014 ack queued locally. Run \`${f("sync")}\` when you're back online; it'll flush automatically.`);return}if(!l.ok){let u=await l.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(l.status===409&&d?.code==="already_acked"){Zt(r),pt(process.cwd());let v=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||c.success(`Action ${r} was already ${v}.`);return}let p=typeof d?.code=="string"?d.code:null,m=typeof d?.error=="string"?d.error:u,y=p?`, code: ${p}`:"";c.error(`Server rejected ack (${l.status}${y}): ${m.slice(0,200)}`),process.exitCode=1;return}Zt(r),pt(process.cwd()),!t.silent&&(t.failed?c.success(`Action ${r} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):c.success(`Action ${r} marked completed.`),c.info(` inbox location: ${Vr($,"inbox")}`))}function Zt(e){let t=Y(process.cwd());if(ll(t)){for(let n of cl(t))if(n.endsWith(`-${e}.md`))try{ul(Vr(t,n))}catch{}}}async function fl(){let e=process.cwd(),t=ae(e);if(t.length===0)return c.info("No pending actions in .seoagent/inbox/."),c.message(`Run \`${f("sync")}\` to pull anything autopilot has queued.`),null;if(!process.stdout.isTTY)return c.error(`Cannot show interactive picker in non-TTY mode. Pass an action id explicitly, or run \`${f("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await pl({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:ke(r)}))});return dl(n)?(c.info("Cancelled \u2014 no action closed out."),null):n}import gt from"picocolors";async function en(e={}){let t=process.cwd();if(!e.json&&!F(t))return;let n=ae(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:Y(t),actions:n})+`
|
|
357
|
+
`);return}if(n.length===0){c.info(gt.dim("No pending actions.")),c.message(`Run \`${f("sync")}\` to pull anything autopilot has queued, or \`${f("autopilot status")}\` to check whether autopilot is on.`);return}c.message(`${gt.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),c.message("");for(let r of n)c.message(ke(r));c.message(""),c.message(`Apply one: ${gt.bold(f("ack <id>"))} \xB7 Interactive picker: ${gt.bold(f("ack"))} (no id)`)}import{readFileSync as xl}from"fs";import{join as vl,relative as _l}from"path";import{confirm as to,isCancel as yt,multiselect as Cl,note as oo,select as El}from"@clack/prompts";import g from"picocolors";import{query as Al}from"@anthropic-ai/claude-agent-sdk";import{existsSync as ml,readdirSync as gl}from"fs";import{homedir as hl}from"os";import{join as yl}from"path";import{execSync as tn}from"child_process";function Ge(){return process.env.ANTHROPIC_API_KEY?"env-key":process.env.CLAUDE_CODE_USE_BEDROCK==="1"||process.env.CLAUDE_CODE_USE_VERTEX==="1"||process.env.CLAUDE_CODE_USE_FOUNDRY==="1"||process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS==="1"?"enterprise":wl()?kl()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function wl(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return tn(e,{stdio:"ignore"}),!0}catch{return!1}}function kl(){let e=yl(hl(),".claude");if(!ml(e))return!1;try{return gl(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function Qr(){try{return tn("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function Xr(){try{return tn("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var z={"env-key":{summary:"Using ANTHROPIC_API_KEY env var.",next:""},enterprise:{summary:"Using enterprise provider (Bedrock / Vertex / Foundry).",next:""},"claude-session-likely":{summary:"Using your existing `claude login` session.",next:""},"claude-installed-no-session":{summary:"Claude Code is installed but you are not logged in.",next:"Run `claude login` to sign in with your Claude.ai / Pro / Max account, or set `ANTHROPIC_API_KEY` and re-run."},"not-installed":{summary:"Claude Code is not installed on this machine.",next:"Install it with `npm install -g @anthropic-ai/claude-code` then `claude login`, or set `ANTHROPIC_API_KEY` (get one at https://console.anthropic.com/) and re-run."}};import{marked as eo}from"marked";import{markedTerminal as bl}from"marked-terminal";import nn from"picocolors";var Zr=!1;function $l(){Zr||(eo.use(bl({reflowText:!1,width:100})),Zr=!0)}function ht(e){if(!e)return e;$l();try{let t=eo.parse(e);return typeof t=="string"?Sl(t):e}catch{return e}}function Sl(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>nn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>nn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+nn.italic(r))}async function on(e={}){let t=process.cwd();if(!F(t))return;if(!process.stdout.isTTY&&!e.yes){c.error(`\`${f("process")}\` needs an interactive TTY for the sync + selection prompts. Use \`--yes\` to skip prompts and process everything (for CI/CD).`),process.exitCode=1;return}if(!await Ll(e.yes)){process.exitCode=1;return}if(e.yes)await K({embedded:!0});else{let u=await El({message:"Sync the inbox before processing?",options:[{value:"sync",label:"Sync (recommended) \u2014 pull pending actions + push local changes"},{value:"pull",label:"Pull only \u2014 get new actions, skip pushing your local changes"},{value:"skip",label:"Skip \u2014 use the current local inbox state"}],initialValue:"sync"});if(yt(u)){c.info("Cancelled.");return}u==="sync"?await K({embedded:!0}):u==="pull"&&await le({embedded:!0})}let r=ae(t);if(r.length===0){c.info(g.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),c.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(y=>y.priority!==null),d=u?r.filter(y=>y.priority==="high").map(y=>y.id):r.map(y=>y.id),p=u&&d.length===0?" (no high-priority actions \u2014 toggle to select)":u?` (${d.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",m=await Cl({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(y=>({value:y.id,label:ke(y)})),initialValues:d,required:!1});if(yt(m)){c.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(m)||m.length===0){c.info("No actions selected. Nothing to do.");return}o=m}let i=0,s=0,a=0,l=Date.now();for(let u=0;u<o.length;u++){let d=o[u],p=r.find(_=>_.id===d);if(!p)continue;Il({index:u+1,total:o.length,entry:p});let m=vl(Y(t),p.filename),y;try{y=xl(m,"utf-8")}catch(_){c.error(` Could not read ${p.filename}: ${_.message}`),a++;continue}let v=Date.now(),E=await Tl({cwd:t,entry:p,actionContent:y,model:e.model}),M=no(Date.now()-v);if(E.kind==="applied")try{await X(String(d),{silent:!0}),i++,c.message("");let _=E.summary?`
|
|
358
|
+
`+g.dim(" "+E.summary):"";c.message(` ${g.green("\u2713")} id ${d} ${g.dim("\u2014 applied in "+M)}${_}`)}catch(_){c.warn(` Applied but ack failed: ${_.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(E.kind==="declined")try{await X(String(d),{silent:!0,failed:!0,reason:E.reason}),s++,c.message(""),c.message(` ${g.yellow("\u2298")} id ${d} ${g.dim("\u2014 declined: "+D(E.reason,100))}`)}catch(_){c.warn(` Could not ack decline: ${_.message}. Run \`seoagent ack ${d} --failed --reason "${E.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,c.message(""),c.message(` ${g.red("\u2717")} id ${d} ${g.dim("\u2014 agent did not converge after "+M)}`)}Pl({applied:i,declined:s,failed:a,total:o.length,elapsed:no(Date.now()-l)})}function Il(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=Rl[i]??g.dim,a=[g.bold(`[${t}/${n}]`),g.dim("\xB7"),g.bold(`id ${r.id}`),g.dim("\xB7"),g.cyan(o),s(i)].join(" ");oo(r.title,a)}var Rl={critical:e=>g.red(g.bold(e)),high:g.red,medium:g.yellow,low:g.dim};function Pl(e){let{applied:t,declined:n,failed:r,total:o,elapsed:i}=e,s=t+n,a;if(s===o&&r===0)a=n===0?g.green(`\u2713 ${t}/${o} applied`):g.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=g.red(`\u2717 0/${o} applied`);else{let l=[`${t}/${o} applied`];n>0&&l.push(`${n} declined`),r>0&&l.push(`${r} failed`),a=g.yellow(`\u25D0 ${l.join(" \xB7 ")}`)}oo(`${a}
|
|
359
|
+
${g.dim("elapsed: "+i)}`,g.bold("Done"))}function no(e){if(e<1e3)return`${e}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;if(n<60)return r>0?`${n}m ${r}s`:`${n}m`;let o=Math.floor(n/60),i=n%60;return i>0?`${o}h ${i}m`:`${o}h`}function Ol(e){if(typeof e!="string"||!e)return null;let t=e.split(`
|
|
360
|
+
`);for(let n=t.length-1;n>=0;n--){let r=t[n].match(/^__(APPLIED|DECLINED)__:\s*(.*)$/);if(!r)continue;let o=r[2].trim();return r[1]==="APPLIED"?{kind:"applied",summary:o}:{kind:"declined",reason:o}}return null}async function Tl(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=Kl(n,r);try{let s=Al({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...o?{model:o}:{}}}),a={toolUseById:new Map};for await(let l of s)if(l.type==="assistant"){let u=l.message.content;if(Array.isArray(u))for(let d of u)jl(d,a)}else if(l.type==="user"){let u=l.message.content;if(Array.isArray(u))for(let d of u)Ul(d,a)}else if(l.type==="result"){if(process.stdout.write(`
|
|
361
|
+
`),!(l.subtype==="success"&&!l.is_error))return{kind:"failed"};let d=Ol(l.result);return d?.kind==="declined"?{kind:"declined",reason:d.reason}:{kind:"applied",summary:d?.kind==="applied"?d.summary:void 0}}return{kind:"failed"}}catch(s){return process.stdout.write(`
|
|
362
|
+
`),c.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function Ll(e){let t=Ge();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return c.info(g.dim(z[t].summary)),!0;if(c.warn(z[t].summary),c.message(` ${z[t].next}`),e)return!1;if(t==="not-installed"){let n=await to({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(yt(n)||!n)return c.info("Skipped install. Set up auth and re-run when ready."),!1;c.message(g.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=Qr();if(!r.ok)return c.error(`Install failed: ${r.error}`),c.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=Ge()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await to({message:"Run `claude login` now to sign in?",initialValue:!0});if(yt(n)||!n)return c.info("Skipped login. Run `claude login` when ready and try again."),!1;c.message(g.dim("Launching `claude login`\u2026"));let r=Xr();if(!r.ok)return c.error(`Login failed: ${r.error}`),!1}return!0}function Nl(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function jl(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&Nl(e)){process.stdout.write(ht(e.text));return}if(n==="tool_use"){let r=String(e.id??""),o=String(e.name??"unknown"),i=e.input;r&&t.toolUseById.set(r,{name:o,input:i});let s=Dl[o]??g.cyan,a=Wl(o,i);process.stdout.write(s(Fl)+" "+g.bold(o)+g.dim("(")+a+g.dim(")")+`
|
|
363
|
+
`);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(g.dim(g.italic(" "+D(r,200)))+`
|
|
364
|
+
`)}}var Fl="\u23FA",ro="\u23BF",Dl={Read:g.blue,Glob:g.cyan,Grep:g.cyan,Edit:g.yellow,Write:g.magenta,Bash:g.green,WebFetch:g.magenta,WebSearch:g.magenta};function Ul(e,t){if(!e||typeof e!="object"||e.type!=="tool_result")return;let n=e.is_error===!0,r=String(e.tool_use_id??""),o=r?t.toolUseById.get(r):void 0,i=o?.name,s=e.content,a=Ml(s);if(n){process.stdout.write(g.red(` ${ro} Error`)+`
|
|
365
|
+
`),a&&process.stdout.write(Gl(D(a,500)," ",g.red)+`
|
|
366
|
+
`);return}let l=Bl(i,a,o?.input);l&&process.stdout.write(g.dim(` ${ro} `)+l+`
|
|
367
|
+
`)}function Ml(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:t&&typeof t=="object"&&typeof t.text=="string"?t.text:"").join(""):""}function Bl(e,t,n){if(!e)return"";switch(e){case"Read":{let r=(t.match(/^\s*\d+→/gm)??[]).length,o=r>0?r:t.split(`
|
|
368
|
+
`).filter(Boolean).length;return g.dim(`Read ${o} line${o===1?"":"s"}`)}case"Glob":{let r=t.split(`
|
|
369
|
+
`).filter(o=>o.trim().length>0).length;return g.dim(`Found ${r} ${r===1?"entry":"entries"}`)}case"Grep":{let r=t.split(`
|
|
370
|
+
`)[0]?.trim()??"";if(/^Found\s+\d+/.test(r))return g.dim(r);let o=t.split(`
|
|
371
|
+
`).filter(i=>i.trim()).length;return g.dim(`${o} result${o===1?"":"s"}`)}case"Edit":case"Write":{let r=n?.file_path,o=e==="Edit"?"Updated":"Created";return g.dim(r?`${o} ${rn(String(r))}`:o)}case"Bash":{let r=t.split(`
|
|
372
|
+
`),o=r.slice(0,5).map(u=>D(u.trimEnd(),100)),i=r.length-5,s=o.join(`
|
|
367
373
|
`)+(i>0?`
|
|
368
374
|
\u2026 (+${i} more line${i===1?"":"s"})`:""),[a,...l]=s.split(`
|
|
369
|
-
`);return l.length===0?
|
|
370
|
-
`+
|
|
371
|
-
`))}case"WebFetch":case"WebSearch":return
|
|
375
|
+
`);return l.length===0?g.dim(a):g.dim(a)+`
|
|
376
|
+
`+g.dim(l.map(u=>" "+u).join(`
|
|
377
|
+
`))}case"WebFetch":case"WebSearch":return g.dim(`Fetched ${D(t.replace(/\s+/g," "),80)}`);default:return""}}function Gl(e,t,n){return e.split(`
|
|
372
378
|
`).map(r=>n(t+r)).join(`
|
|
373
|
-
`)}function
|
|
379
|
+
`)}function Wl(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return g.dim(D(rn(String(n.file_path??"")),80));case"Bash":return g.dim(D(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${rn(String(n.path))}`:"";return g.dim(D(r+o,80))}case"Glob":return g.dim(D(String(n.pattern??""),80));case"WebFetch":return g.dim(D(String(n.url??""),80));case"WebSearch":return g.dim(D(String(n.query??""),80));default:return""}}function rn(e){if(!e)return e;let t=process.cwd(),n=_l(t,e);return n.startsWith("..")?e:n||e}function D(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Kl(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
|
|
374
380
|
|
|
375
381
|
Your job: apply the change this action describes to the codebase at the current working directory. Read the "How to apply" section in the action file \u2014 it tells you what to do and where to look. Make the edit, then briefly state what you changed.
|
|
376
382
|
|
|
@@ -389,19 +395,140 @@ Action file (\`.seoagent/inbox/${e.filename}\`):
|
|
|
389
395
|
\`\`\`
|
|
390
396
|
${t}
|
|
391
397
|
\`\`\`
|
|
392
|
-
`}import{spinner as
|
|
393
|
-
`),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${
|
|
398
|
+
`}import{spinner as ql}from"@clack/prompts";import w from"picocolors";var Hl=new Set(["on","off","status"]);async function We(e,t={}){let n=(e||"").toLowerCase();if(!Hl.has(n)){c.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=R();if(!r){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||x.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?ql():null,l=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(l);let u;try{u=await fetch(`${o}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(y){k(a,"error",`Network error: ${y.message}`,w.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){let v=I(process.cwd())?.domain??"",E=`${x.PRICING}?ref=cli${v?`&domain=${encodeURIComponent(v)}`:""}`;k(a,"warn","CLI autopilot is a paid feature.",w.yellow("Autopilot is a paid feature.")),c.message(Yl(E)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){k(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,w.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:m}=d.autopilot;if(n==="on"){a?.stop(w.green("Autopilot enabled.")),c.message(sn({enabled:!0,deliveryMode:m,action:n}));return}if(n==="off"){a?.stop(w.dim("Autopilot disabled.")),c.message(sn({enabled:!1,deliveryMode:m,action:n}));return}a?.stop(w.dim("Status:")),c.message(sn({enabled:p,deliveryMode:m,action:n}))}function sn(e){let n=s=>w.dim(s.padEnd(11)),r=e.enabled?`${w.bold(w.green("\u25CF ON"))} ${w.dim("(queueing fixes for your coding agent)")}`:`${w.dim("\u25CB OFF")} ${w.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${w.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${w.dim("Apply queued fixes:")} ${w.cyan(f("sync"))}`}),o.push({content:`${w.dim("Turn off any time:")} ${w.cyan(f("autopilot off"))}`})):(o.push({content:`${w.dim("Enable (paid):")} ${w.cyan(f("autopilot on"))}`}),o.push({content:w.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${w.bold(w.cyan("SEOAgent"))} ${w.dim("\xB7")} ${w.dim("autopilot")}`;return P(o,{width:78,title:i})}function Yl(e){let t=[{content:w.bold(w.yellow("Autopilot is a paid feature."))},{sep:!0},{content:w.dim("SEOAgent continuously audits your site and queues fixes for")},{content:w.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:w.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${w.dim("Upgrade:")} ${w.cyan(e)}`}],n=`${w.bold(w.cyan("SEOAgent"))} ${w.dim("\xB7")} ${w.dim("autopilot")}`;return P(t,{width:78,title:n})}import{mkdirSync as ic,writeFileSync as sc}from"fs";import{join as an}from"path";import{readdirSync as zl,readFileSync as Jl,statSync as io}from"fs";import{join as Vl}from"path";var Ql=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Xl=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"]),Zl=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),ec=5e3,tc=512*1024;function uo(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function so(e,t){let n=(e||"").trim();if(!n||(n=n.replace(/[?#].*$/,""),!n)||/^(mailto:|tel:|javascript:|data:)/i.test(n)||n.startsWith("//"))return null;if(/^https?:\/\//i.test(n))try{let i=new URL(n),s=i.hostname.toLowerCase().replace(/^www\./,"");if(!t||s!==t)return null;n=i.pathname||"/"}catch{return null}if(!n.startsWith("/")||n.startsWith("/api/")||n==="/api")return null;let r=n.split("/").pop()||"",o=r.lastIndexOf(".");return o>0&&Xl.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var ao=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,lo=/\]\(\s*([^)\s]+)/g;function nc(e,t){if(!e)return[];let n=uo(t),r=[],o;for(ao.lastIndex=0;(o=ao.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=so(i,n);s&&r.push(s)}for(lo.lastIndex=0;(o=lo.exec(e))!==null;){let i=so(o[1],n);i&&r.push(i)}return r}function rc(e,t,n=0){let r={};for(let s of e)r[s.route]=0;for(let s of t)s in r&&(r[s]+=1);let o=[],i=[];for(let s of e){if(s.route==="/")continue;let a=r[s.route]??0;a===0?o.push({route:s.route,url:s.url}):a===1&&i.push({route:s.route,url:s.url,inbound:a})}return o.sort((s,a)=>s.route.localeCompare(a.route)),i.sort((s,a)=>s.route.localeCompare(a.route)),{pageCount:e.length,linkOccurrences:t.length,orphans:o,weak:i,inboundByRoute:r,filesScanned:n}}function po(e,t){let n=JSON.stringify(e.orphans.slice(0,100).map(a=>a.url)),r=["---","generated: false",`analyzed_at: ${new Date().toISOString()}`,`page_count: ${e.pageCount}`,`orphan_count: ${e.orphans.length}`,`weak_count: ${e.weak.length}`,`orphans_json: ${n}`,"---"].join(`
|
|
399
|
+
`),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${uo(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(`
|
|
394
400
|
`),i=e.orphans.length===0?`## Orphan pages
|
|
395
401
|
|
|
396
|
-
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=>`| ${
|
|
397
|
-
`),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=>`| ${
|
|
402
|
+
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=>`| ${co(a.url)} | \u2014 |`)].join(`
|
|
403
|
+
`),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=>`| ${co(a.url)} | ${a.inbound} |`)].join(`
|
|
398
404
|
`);return[r,"",o,"",i,s,""].join(`
|
|
399
|
-
`)}function
|
|
400
|
-
`);return}let i=
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
405
|
+
`)}function co(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*oc(e){let t=0;function*n(r){let o;try{o=zl(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=ec)return;if(i.name.startsWith("."))continue;let s=Vl(r,i.name);if(i.isDirectory()){if(Zl.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(!Ql.has(l))continue;t++,yield s}}}yield*n(e)}function fo(e,t){let{pages:n}=st(e,t),r=[],o=0,i=!1;try{i=io(e).isDirectory()}catch{i=!1}if(i)for(let s of oc(e)){let a;try{if(io(s).size>tc)continue;a=Jl(s,"utf-8")}catch{continue}o++;for(let l of nc(a,t))r.push(l)}return rc(n,r,o)}function Ke(e={}){let t=process.cwd(),n=F(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=fo(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
|
|
406
|
+
`);return}let i=an(t,$);ic(i,{recursive:!0});let s=an(i,"internal-links.md");if(sc(s,po(o,r),"utf-8"),c.success(`Analyzed ${o.pageCount} page${o.pageCount===1?"":"s"} across ${o.filesScanned} file${o.filesScanned===1?"":"s"}.`),o.orphans.length===0)c.info("No orphan pages \u2014 every page has an inbound internal link.");else{c.warn(`${o.orphans.length} orphan page${o.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of o.orphans.slice(0,10))c.message(` \u2022 ${a.url}`);o.orphans.length>10&&c.message(` \u2026and ${o.orphans.length-10} more`)}c.info(`Report written to ${an($,"internal-links.md")}`)}import q from"picocolors";import{existsSync as $e,mkdirSync as wt,readdirSync as ac,readFileSync as lc,statSync as Sm,writeFileSync as mo}from"fs";import{dirname as cc,join as Z,relative as uc,resolve as dc}from"path";var Se="okf";function kt(e){return Z(e,$,Se)}var pc=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function ln(e){let t=[];for(let n of ac(e,{withFileTypes:!0})){let r=Z(e,n.name);n.isDirectory()?t.push(...ln(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function fc(e){let t=[],n=/\[[^\]]*\]\(([^)]+)\)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1].trim().split(/\s+/)[0];o&&(/^[a-z][a-z0-9+.-]*:/i.test(o)||o.startsWith("#")||t.push(o))}return t}function go(e){let t=[],n=[];if(!$e(e))return{ok:!1,fileCount:0,errors:[{file:Se,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=ln(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Se,message:"OKF directory exists but contains no markdown files."}],warnings:[]};$e(Z(e,"index.md"))||n.push({file:Se,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=uc(e,i),a;try{a=Ce(lc(i,"utf-8"))}catch{t.push({file:s,message:"Could not read or parse file."});continue}let l=a.data.type;(l==null||String(l).trim()==="")&&t.push({file:s,message:"Missing required frontmatter field `type`."});let u=a.data.timestamp;u!=null&&u!==""&&!pc.test(String(u))&&t.push({file:s,message:`\`timestamp\` is not ISO-8601: "${String(u)}"`});let d=a.data.description;typeof d=="string"&&d.length>200&&n.push({file:s,message:`\`description\` is ${d.length} chars (keep \u2264 200).`});for(let p of fc(a.body)){let m=p.split("#")[0];if(!m)continue;let y=dc(cc(i),m);$e(y)||t.push({file:s,message:`Broken link \u2192 "${p}" (target does not exist).`})}}return{ok:t.length===0,fileCount:r.length,errors:t,warnings:n}}function bt(e){let t=kt(e);if(!$e(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:ln(t).length}}catch{return{exists:!0,fileCount:0}}}function ho(e,t){let n=kt(e);wt(n,{recursive:!0}),wt(Z(n,"concepts"),{recursive:!0}),wt(Z(n,"faqs"),{recursive:!0}),wt(Z(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=Z(n,"index.md");$e(i)||(mo(i,`---
|
|
407
|
+
type: Organization
|
|
408
|
+
title: ${o}
|
|
409
|
+
description: Knowledge bundle describing ${o} for AI agents and answer engines.
|
|
410
|
+
tags: [overview]
|
|
411
|
+
---
|
|
412
|
+
|
|
413
|
+
# ${o}
|
|
414
|
+
|
|
415
|
+
> Open Knowledge Format bundle \u2014 a curated, agent-readable account of this
|
|
416
|
+
> business. Fill in the sections below and link out to concept files.
|
|
417
|
+
|
|
418
|
+
## What this business does
|
|
419
|
+
|
|
420
|
+
_Describe the business in 2\u20134 sentences (pull from \`.seoagent/context.md\`)._
|
|
421
|
+
|
|
422
|
+
## Key concepts
|
|
423
|
+
|
|
424
|
+
- _Link concept files here, e.g._ \`concepts/pricing.md\`
|
|
425
|
+
|
|
426
|
+
## FAQs
|
|
427
|
+
|
|
428
|
+
- _Link FAQ files here, e.g._ \`faqs/what-is-x.md\`
|
|
429
|
+
|
|
430
|
+
## Published articles
|
|
431
|
+
|
|
432
|
+
- _Link article files here, e.g._ \`articles/guide-to-x.md\`
|
|
433
|
+
`,"utf-8"),r.push("index.md"));let s=Z(n,"log.md");return $e(s)||(mo(s,`---
|
|
434
|
+
type: Log
|
|
435
|
+
title: Change log
|
|
436
|
+
description: Chronological history of changes to this OKF bundle.
|
|
437
|
+
---
|
|
438
|
+
|
|
439
|
+
# Change log
|
|
440
|
+
|
|
441
|
+
- Bundle scaffolded.
|
|
442
|
+
`,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var cn=`${$}/${Se}`;function qe(e,t={}){let n=process.cwd(),r=F(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=ho(n,i);a.length===0?c.info(`OKF bundle already scaffolded at ${cn}/.`):(c.success(`Scaffolded ${cn}/ \u2014 created ${a.join(", ")}.`),c.info("Now fill the bundle from your .seoagent/ knowledge, then run `seoagent okf validate`."));return}if(o==="validate"){let a=go(kt(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
|
|
443
|
+
`);return}for(let l of a.errors)c.message(`${q.red("\u2717")} ${q.dim(l.file)} \u2014 ${l.message}`);for(let l of a.warnings)c.message(`${q.yellow("!")} ${q.dim(l.file)} \u2014 ${l.message}`);a.ok?c.success(`OKF bundle is valid \u2014 ${a.fileCount} file${a.fileCount===1?"":"s"}, ${a.warnings.length} warning${a.warnings.length===1?"":"s"}.`):(c.error(`OKF bundle has ${a.errors.length} error${a.errors.length===1?"":"s"} (see above).`),process.exitCode=1);return}let s=bt(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
|
|
444
|
+
`);return}c.message(P([{content:q.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?q.green(cn+"/"):q.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?q.dim("Run `seoagent okf validate` to check it."):q.dim("Run `seoagent okf scaffold` to start one.")}],{title:q.cyan("OKF")}))}import{mkdirSync as wc,writeFileSync as kc}from"fs";import N from"picocolors";import{query as bc}from"@anthropic-ai/claude-agent-sdk";import{join as yo}from"path";var dn="citations",pn="scorecard.md",mc=6,gc=1,hc=12,$t="Claude (web-grounded)";function fn(e){return yo(e,$,dn)}function wo(e){return yo(fn(e),pn)}function ko(e){return typeof e!="number"||!Number.isFinite(e)?mc:Math.max(gc,Math.min(hc,Math.floor(e)))}function mn(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function bo(e,t){return`You are SEOAgent measuring this business's AI-citation visibility (AEO/GEO) \u2014 whether answer engines surface and cite it.
|
|
445
|
+
|
|
446
|
+
Business under audit:
|
|
447
|
+
${[`- Domain: ${e.domain}`,e.name?`- Business name: ${e.name}`:null,e.type?`- Business type: ${e.type}`:null,e.description?`- What it does: ${e.description}`:null,`- OKF knowledge bundle present in repo: ${e.hasOkfBundle?"yes":"no"}`].filter(Boolean).join(`
|
|
448
|
+
`)}
|
|
449
|
+
|
|
450
|
+
Your job has three steps:
|
|
451
|
+
|
|
452
|
+
1. Generate ${t} realistic questions a potential customer would ask an AI assistant (ChatGPT, Claude, Perplexity, Google AI Overviews) where THIS business should ideally be surfaced or cited. Make them DIVERSE and buyer-intent \u2014 mix:
|
|
453
|
+
- category / "best tool for X" questions,
|
|
454
|
+
- "alternatives to <a real competitor>" questions,
|
|
455
|
+
- problem-first questions ("how do I <the problem this business solves>").
|
|
456
|
+
Do NOT just ask "what is ${e.domain}" \u2014 that's not how discovery works.
|
|
457
|
+
|
|
458
|
+
2. For EACH question, use the WebSearch tool (and WebFetch if you need to read a result) to see what a web-grounded answer engine would actually cite right now. Decide whether "${e.name||e.domain}" / ${e.domain} appears among the sources an answer engine would draw from, and its approximate rank. You MAY Read the local \`.seoagent/okf/\` bundle and \`.seoagent/context.md\` to understand the brand accurately, but the verdict must come from the live web results \u2014 not from what you already know.
|
|
459
|
+
|
|
460
|
+
3. Be honest. Mark \`surfaced: false\` when the business does not appear \u2014 a low score is useful signal, a fabricated "cited" is worse than useless. Never invent a source.
|
|
461
|
+
|
|
462
|
+
End your reply with EXACTLY ONE fenced \`\`\`json block (and nothing after it) matching this schema:
|
|
463
|
+
|
|
464
|
+
\`\`\`json
|
|
465
|
+
{
|
|
466
|
+
"brand": "${e.name||e.domain}",
|
|
467
|
+
"domain": "${e.domain}",
|
|
468
|
+
"results": [
|
|
469
|
+
{
|
|
470
|
+
"query": "the question you tested",
|
|
471
|
+
"surfaced": true,
|
|
472
|
+
"rank": 2,
|
|
473
|
+
"evidence": "one line: which source surfaced it, or why it didn't"
|
|
474
|
+
}
|
|
475
|
+
]
|
|
476
|
+
}
|
|
477
|
+
\`\`\`
|
|
478
|
+
|
|
479
|
+
\`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown.`}function $o(e){if(typeof e!="string"||!e.trim())return null;let t=/```json\s*([\s\S]*?)```/gi,n=[],r;for(;(r=t.exec(e))!==null;)r[1].trim()&&n.push(r[1].trim());if(n.length===0)return null;for(let o=n.length-1;o>=0;o--){let i=yc(n[o]);if(i)return i}return null}function yc(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=typeof n.domain=="string"?n.domain.trim():"";if(!r)return null;let o=typeof n.brand=="string"&&n.brand.trim()?n.brand.trim():r;if(!Array.isArray(n.results))return null;let i=[];for(let s of n.results){if(!s||typeof s!="object")continue;let a=s,l=typeof a.query=="string"?a.query.trim():"";if(!l)continue;let u=a.surfaced===!0,d=typeof a.rank=="number"&&Number.isFinite(a.rank)?Math.round(a.rank):null,p=typeof a.evidence=="string"?a.evidence.trim():"";i.push({query:l,surfaced:u,rank:u?d:null,evidence:p})}return i.length===0?null:{brand:o,domain:r,results:i}}function So(e,t){let{cited:n,total:r}=mn(e),o=t.generatedAt.slice(0,10),i=e.results.map((u,d)=>{let p=u.surfaced?"\u2705":"\u2014",m=u.surfaced&&u.rank?`#${u.rank}`:"\u2014",y=un(u.evidence||(u.surfaced?"surfaced":"not found"));return`| ${d+1} | ${un(u.query)} | ${p} | ${m} | ${y} |`}).join(`
|
|
480
|
+
`),s=e.results.filter(u=>!u.surfaced),a=s.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":s.map(u=>`- **${un(u.query)}** \u2014 ${u.evidence||"not surfaced"}`).join(`
|
|
481
|
+
`),l=e.results.some(u=>!u.surfaced)?"- Enrich the Open Knowledge Format bundle so answer engines understand the business: run `seoagent okf scaffold` then fill it (the skill maps your `.seoagent/` knowledge into it), and publish it at `/.well-known/okf/`.\n- Cover the missed questions directly in your content (a page or FAQ that answers each one), then re-run `seoagent citations`.":"- Keep the OKF bundle current as the business evolves, and re-run to catch regressions.";return`---
|
|
482
|
+
type: Report
|
|
483
|
+
title: AI Citation Scorecard \u2014 ${e.domain}
|
|
484
|
+
generated_at: ${t.generatedAt}
|
|
485
|
+
engine: claude-web-grounded
|
|
486
|
+
---
|
|
487
|
+
|
|
488
|
+
# AI Citation Scorecard \u2014 ${e.domain}
|
|
489
|
+
|
|
490
|
+
> Whether a web-grounded answer engine surfaces **${e.brand}** for the kind
|
|
491
|
+
> of buyer-intent questions your customers ask AI assistants. This is the
|
|
492
|
+
> measurement half of the AEO/GEO loop \u2014 \`seoagent okf\` makes you citable, this
|
|
493
|
+
> tells you whether it's working.
|
|
494
|
+
|
|
495
|
+
**Cited: ${n} / ${r} queries** \xB7 engine: ${$t} \xB7 ${o}
|
|
496
|
+
|
|
497
|
+
| # | Query | Cited? | ~Rank | Evidence |
|
|
498
|
+
|---|-------|--------|-------|----------|
|
|
499
|
+
${i}
|
|
500
|
+
|
|
501
|
+
## Where you're not surfacing (opportunities)
|
|
502
|
+
|
|
503
|
+
${a}
|
|
504
|
+
|
|
505
|
+
### How to improve these
|
|
506
|
+
|
|
507
|
+
${l}
|
|
508
|
+
|
|
509
|
+
## Methodology \u2014 read before quoting the number
|
|
510
|
+
|
|
511
|
+
Measured on ${o} by querying **Claude with live web search**, which
|
|
512
|
+
approximates how a web-grounded answer engine (ChatGPT search, Perplexity,
|
|
513
|
+
Google AI Overviews) synthesizes an answer from current web results.
|
|
514
|
+
|
|
515
|
+
What this **is**: a real, repeatable signal of whether the open web currently
|
|
516
|
+
positions ${e.brand} as an answer for these questions.
|
|
517
|
+
|
|
518
|
+
This is **not a per-engine guarantee**: ChatGPT, Perplexity, and Gemini each
|
|
519
|
+
rank and cite differently, and tracking them individually is a planned
|
|
520
|
+
follow-up. Treat the score as directional \u2014 re-run over time to watch the
|
|
521
|
+
trend rather than fixating on a single number.
|
|
522
|
+
`}function un(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function He(e={}){let t=process.cwd(),n=F(t);if(!n)return;let r=Ge();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){c.warn(z[r].summary),z[r].next&&c.message(` ${z[r].next}`),process.exitCode=1;return}c.info(N.dim(z[r].summary));let o=Jn(t),i=bt(t),s={domain:n.domain,name:o?.business.name,type:o?.business.type||n.site_type,description:o?.business.description,hasOkfBundle:i.exists&&i.fileCount>0},a=ko(e.queries);c.message(`${N.cyan("\u25C7")} Auditing AI citations for ${N.bold(s.domain)} \u2014 ${a} web-grounded quer${a===1?"y":"ies"} via ${$t}.`),c.message(N.dim(` This runs live web searches and can take a minute\u2026
|
|
523
|
+
`));let l=bo(s,a),u=await $c({cwd:t,prompt:l,model:e.model});if(u===null){process.exitCode=1;return}let d=$o(u);if(!d){c.error(`Couldn't read a citation report from the agent's reply. Re-run \`${f("citations")}\`, optionally with fewer queries (\`--queries 4\`).`),process.exitCode=1;return}let p=new Date().toISOString(),m=So(d,{generatedAt:p});wc(fn(t),{recursive:!0}),kc(wo(t),m,"utf-8");let{cited:y,total:v}=mn(d),E=y===0?N.red:y<v?N.yellow:N.green;c.message(P([{content:N.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${N.cyan(d.domain)}`},{content:`Cited: ${E(`${y} / ${v}`)} ${N.dim("queries")}`},{content:`Engine: ${N.dim($t)}`},{sep:!0},{content:N.dim(`Saved \u2192 .seoagent/${dn}/${pn}`)},{content:y<v?N.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):N.dim("Surfacing across the board. Re-run periodically to catch drift.")}],{title:N.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(d,null,2)+`
|
|
524
|
+
`)}async function $c(e){let{cwd:t,prompt:n,model:r}=e;try{let o=bc({prompt:n,options:{cwd:t,allowedTools:["WebSearch","WebFetch","Read","Grep","Glob"],permissionMode:"acceptEdits",...r?{model:r}:{}}}),i="";for await(let s of o)if(s.type==="assistant"){let a=s.message.content;if(Array.isArray(a))for(let l of a)Sc(l)}else if(s.type==="result"){if(process.stdout.write(`
|
|
525
|
+
`),!(s.subtype==="success"&&!s.is_error))return c.error(" Agent did not complete the citation audit (rate limit, auth, or network)."),null;i=String(s.result??"")}return i}catch(o){return process.stdout.write(`
|
|
526
|
+
`),c.error(` Agent error: ${o.message}`),null}}function Sc(e){if(!e||typeof e!="object")return;let t=e.type;if(t==="text"){let n=e.text;typeof n=="string"&&n&&process.stdout.write(ht(n));return}if(t==="tool_use"){let n=String(e.name??"tool"),r=e.input,o=n==="WebSearch"?String(r?.query??""):n==="WebFetch"?String(r?.url??""):"";process.stdout.write(N.dim(` ${N.magenta("\u{1F50E}")} ${n}${o?` ${xc(o,70)}`:""}
|
|
527
|
+
`))}}function xc(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}import{spinner as _o}from"@clack/prompts";import h from"picocolors";var Co={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function vc(e){let t=process.cwd(),n=Rn(t);if(!n){c.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=I(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||x.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?_o():null;a?.start(`Looking up ${h.bold(`"${e.keyword}"`)} ${h.dim("via DataForSEO (free peek)\u2026")}`);let l;try{l=await H(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...o?{domain:o}:{}})})}catch(d){k(a,"error",`Network error: ${d.message}`,h.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await l.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:l.status,body:u??null})+`
|
|
528
|
+
`);return}if(l.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";k(a,"warn",`Daily peek quota reached for ${d}.`,h.yellow(`Daily peek quota reached for ${d}.`)),c.message(xo()),process.exitCode=1;return}if(!l.ok||!u){k(a,"error",`Peek failed (${l.status})${u?.error?`: ${u.error}`:""}`,h.red(`Peek failed (${l.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){k(a,"warn","Real keyword data is temporarily unavailable. Try again later.",h.yellow("Real keyword data is temporarily unavailable. Try again later.")),c.message(h.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){k(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){k(a,"warn",`No data returned for "${e.keyword}".`,h.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(h.green("Got it.")),c.message(_c(u.opportunity)),u.remaining&&c.message(`${h.dim("Peeks remaining today:")} ${h.bold(String(u.remaining.install))} ${h.dim("\u2014 "+xo())}`)}function _c(e){let n=u=>h.dim(u.padEnd(14)),r=e.volume!=null?h.bold(String(e.volume)):h.dim("n/a"),o=e.difficulty!=null?`${h.bold(String(e.difficulty))} ${h.dim(Cc(e.difficulty))}`:h.dim("n/a"),i=Co[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?h.bold(h.green(i)):e.opportunity==="striking_distance"?h.bold(h.cyan(i)):e.opportunity==="competitor_gap"?h.bold(h.yellow(i)):h.dim(i),a=[{content:`${h.green("\u25CF")} ${h.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${h.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],l=`${h.bold(h.cyan("Keyword peek"))}`;return P(a,{width:55,title:l})}function Cc(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function xo(e=R()){return e?`You're logged in \u2014 run \`${f("keywords")}\` for full enrichment (no quota), or \`${f("keywords --discover")}\` / \`${f("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${f("login")}`}function vo(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){c.message("Top opportunities:");for(let n of t){let r=n.volume!=null?`vol ${n.volume}`:"vol n/a",o=n.difficulty!=null?`KD ${n.difficulty}`:"KD n/a",i=n.our_position!=null?`, you're #${n.our_position}`:", not ranking";c.message(` \u2022 [${Co[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function Ec(e){if(e.length!==0){c.message("Top competitor gaps:");for(let t of e){let n=t.volume!=null?`vol ${t.volume}`:"vol n/a",r=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",o=t.their_position!=null?`#${t.their_position}`:"top 10";c.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${o}, ${n}, ${r}`)}}}async function ee(e={}){if(e.peek&&e.peek.trim().length>0){await vc({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=R();if(!t){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=e.apiBase||t.api_base||x.BASE,r=`Bearer ${t.user_token}:${t.website_token}`,o=e.competitors?"competitors":e.discover?"discover":"enrich",i=o==="competitors"?"/api/cli/keywords/competitors":o==="discover"?"/api/cli/keywords/discover":"/api/cli/keywords/enrich",s=o==="competitors"?"Finding keywords your competitors rank for\u2026":o==="discover"?"Discovering new keywords to target\u2026":"Enriching keywords with real volume + difficulty\u2026",l=!!process.stdout.isTTY?_o():null;l?.start(s);let u;try{u=await H(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"})}catch(m){k(l,"error",`Network error: ${m.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"){k(l,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",h.yellow("Paid feature \u2014 upgrade to continue.")),c.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${h.cyan(x.PRICING)}`:`Upgrade to find new keywords to target: ${h.cyan(x.PRICING)}`),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"){k(l,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,h.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}if(d.skipped==="no-keywords"||d.skipped==="no-seeds"){k(l,"warn","No keywords yet. Run the keyword strategy (Phase 2) first, then try again.",h.yellow("No keywords yet."));return}if(d.skipped==="no-competitors"){k(l,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",h.yellow("No competitors yet."));return}if(d.skipped==="no-creds"||d.skipped==="no-columns"||d.skipped==="no-table"){k(l,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(d.skipped){k(l,"warn",`Skipped: ${d.skipped}`,h.yellow(`Skipped: ${d.skipped}`));return}if(o==="competitors"){let m=d.gaps??0;k(l,"success",`Found ${m} competitor gap${m===1?"":"s"} across ${d.competitors?.length??0} competitor${d.competitors?.length===1?"":"s"} (added as "suggested").`,h.green(`${m} competitor gap${m===1?"":"s"} found.`)),Ec(d.topGaps??[]),c.message(`Review them in ${h.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}if(o==="discover"){let m=d.discovered??0;k(l,"success",`Discovered ${m} new keyword${m===1?"":"s"} to target (added as "suggested").`,h.green(`${m} new keyword${m===1?"":"s"} discovered.`)),vo(d.opportunities??[]),c.message(`Review them in ${h.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}let p=d.enriched??0;k(l,"success",`Enriched ${p} keyword${p===1?"":"s"}.`,h.green(`Enriched ${p} keyword${p===1?"":"s"}.`)),vo(d.opportunities??[]),d.paid||c.message(`${h.dim("Free plan:")} enriched up to ${h.bold(String(d.cap??25))} keywords. ${h.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${h.cyan(x.PRICING)}`)}import C from"picocolors";import{existsSync as Ac,readFileSync as Ic}from"fs";import{join as Rc}from"path";var Eo=["openai","fal","replicate"],xe={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Pc(e){let t={};if(!Ac(e))return t;let n=Ic(e,"utf-8");for(let r of n.split(/\r?\n/)){let o=r.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i===-1)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return t}function Ao(e,t){let n={};for(let r of t){let o=process.env[r];o&&o.trim().length>0&&(n[r]={value:o,source:"process"})}for(let r of ce){let o=Rc(e,r),i=Pc(o);for(let s of t){if(n[s])continue;let a=i[s];a&&a.length>0&&(n[s]={value:a,source:r})}}return{found:n}}function St(e){let t=[].concat(...Eo.map(a=>xe[a])),n=Ao(e,t),r=[];for(let a of Eo)xe[a].some(l=>n.found[l])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=xe[o].find(a=>n.found[a])??null,s=i?n.found[i].source:null;return{provider:o,matched_key:i,source:s,available_providers:r}}function Io(e,t){let n=Ao(e,xe[t]);for(let r of xe[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Ro(){return xe}function Ye(e={}){let t=process.cwd(),n=I(t),r=St(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
|
|
529
|
+
`);return}if(c.message(Oc(r)),!n){c.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}Ae(t,{image_provider:r.provider}),c.info(`Saved to ${C.cyan(".seoagent/project.md")} ${C.dim(`(image_provider: ${r.provider})`)}`)}function Oc(e){let n=i=>C.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${C.dim("\u25CB")} ${C.bold(C.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:C.dim("Set ONE of these to enable image generation:")});let i=Ro();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${C.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:C.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${C.cyan(f("env-check"))}`})}else{r.push({content:`${C.green("\u2713")} ${C.dim("Image provider:")} ${C.bold(C.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${C.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${C.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${C.dim(i.join(", "))}`})}let o=`${C.bold(C.cyan("SEOAgent"))} ${C.dim("\xB7")} ${C.dim("env-check")}`;return P(r,{width:64,title:o})}import{existsSync as hn,mkdirSync as To,writeFileSync as Lo}from"fs";import{dirname as vt,isAbsolute as Fc,join as xt,resolve as Dc}from"path";import{tmpdir as Uc}from"os";import{spinner as Mc}from"@clack/prompts";import O from"picocolors";import{Buffer as Po}from"buffer";async function gn(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 Po.from(n)}async function Tc(e){let t=e.size??"1024x1024",n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:"gpt-image-1",prompt:e.prompt,size:t,n:1})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`OpenAI image API ${n.status}: ${i.slice(0,300)}`)}let o=(await n.json()).data?.[0];if(!o)throw new Error("OpenAI image API returned no data");if(o.b64_json)return{bytes:Po.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await gn(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function Lc(e){let t=process.env.FAL_MODEL||"fal-ai/flux/schnell",n=await fetch(`https://fal.run/${t}`,{method:"POST",headers:{Authorization:`Key ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({prompt:e.prompt,image_size:"landscape_16_9",num_images:1})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`fal.ai API ${n.status}: ${s.slice(0,300)}`)}let o=(await n.json()).images?.[0];if(!o?.url)throw new Error("fal.ai API returned no image url");return{bytes:await gn(o.url),contentType:o.content_type??"image/png"}}async function Nc(e,t,n=9e4){let r=Date.now(),o=1e3;for(;Date.now()-r<n;){let i=await fetch(`https://api.replicate.com/v1/predictions/${e}`,{headers:{Authorization:`Token ${t}`}});if(!i.ok)throw new Error(`Replicate poll failed: ${i.status}`);let s=await i.json();if(s.status==="succeeded"||s.status==="failed"||s.status==="canceled")return s;await new Promise(a=>setTimeout(a,o)),o=Math.min(o*1.5,5e3)}throw new Error("Replicate prediction timed out")}async function jc(e){let t=process.env.REPLICATE_MODEL||"black-forest-labs/flux-schnell",n=await fetch(`https://api.replicate.com/v1/models/${t}/predictions`,{method:"POST",headers:{Authorization:`Token ${e.apiKey}`,"Content-Type":"application/json",Prefer:"wait"},body:JSON.stringify({input:{prompt:e.prompt,aspect_ratio:"16:9"}})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Replicate API ${n.status}: ${s.slice(0,300)}`)}let r=await n.json();if(r.status!=="succeeded"&&r.status!=="failed"&&(r=await Nc(r.id,e.apiKey)),r.status!=="succeeded")throw new Error(`Replicate prediction ${r.status}: ${r.error??""}`);let o=Array.isArray(r.output)?r.output[0]:r.output;if(!o)throw new Error("Replicate prediction returned no output");return{bytes:await gn(o),contentType:"image/png",providerImageId:r.id}}async function Oo(e,t){switch(e){case"openai":return Tc(t);case"fal":return Lc(t);case"replicate":return jc(t);default:throw new Error(`Unknown image provider: ${e}`)}}function Bc(e){return e==="openai"||e==="fal"||e==="replicate"}async function ze(e={}){let t=process.cwd();if(!e.prompt){c.warn(`Missing --prompt. Example: ${f('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){c.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=I(t),r=null;if(e.provider){if(!Bc(e.provider)){c.warn(`Invalid --provider "${e.provider}". Use one of: openai, fal, replicate.`),process.exitCode=1;return}r=e.provider}else n?.image_provider&&n.image_provider!=="none"?r=n.image_provider:r=St(t).provider;if(!r||r==="none"){c.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${f("env-check")}\`.`),process.exitCode=1;return}let o=Io(t,r);if(!o){c.warn(`Provider "${r}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=Fc(e.out)?e.out:Dc(t,e.out),a=!e.silent&&!!process.stdout.isTTY?Mc():null;a?.start(`Generating image with ${O.bold(r)} ${O.dim(`(${o.envName})`)}\u2026`);try{let l=await Oo(r,{prompt:e.prompt,apiKey:o.key,size:e.size});hn(vt(i))||To(vt(i),{recursive:!0}),Lo(i,l.bytes),e.silent||k(a,"success",`Wrote ${i} (${l.bytes.length} bytes, ${l.contentType}).`,O.green(`Wrote ${i} ${O.dim(`(${l.bytes.length} bytes, ${l.contentType})`)}`))}catch(l){a?.stop(O.red("Image generation failed."));let u=Wc(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:l});c.message(Gc({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:l.message})),u&&c.message(`${O.dim("Full error log:")} ${O.cyan(u)}`),process.exitCode=1}}function Gc(e){let n=d=>O.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${O.red("\u2717")} ${O.bold(O.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${O.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${O.dim(`"${o}"`)}`}];e.size&&i.push({content:`${n("Size:")}${e.size}`}),i.push({sep:!0});let s=e.message.replace(/\s+/g," ").trim(),a=64,l=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:O.red(l)});let u=`${O.bold(O.cyan("SEOAgent"))} ${O.dim("\xB7")} ${O.dim("generate-image")}`;return P(i,{width:70,title:u})}function Wc(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=xt(e,$),i=xt(o,".errors"),s=hn(o)?xt(i,r):xt(Uc(),r),a=["# SEOAgent generate-image error",`# ${new Date().toISOString()}`,"","## Request",`provider: ${t.provider}`,`env_var: ${t.envName}`,`prompt: ${JSON.stringify(t.prompt)}`,`size: ${t.size??"(default)"}`,`out_path: ${t.outPath}`,`cwd: ${e}`,"","## Error",`message: ${t.error.message}`,"","## Stack",t.error.stack??"(no stack)",""];t.error.cause&&a.push("## Cause",String(t.error.cause),"");try{return hn(vt(s))||To(vt(s),{recursive:!0}),Lo(s,a.join(`
|
|
530
|
+
`)),s}catch{return null}}import j from"picocolors";async function Je(e={}){let t=R();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
|
|
531
|
+
`):c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||x.BASE).replace(/\/$/,""),r=`Bearer ${t.user_token}:${t.website_token}`,o;try{o=await fetch(`${n}/api/cli/whoami`,{method:"GET",headers:{Authorization:r,Accept:"application/json"}})}catch(s){c.error(`Network error: ${s.message}`),process.exitCode=1;return}if(o.status===404){if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,server_supports_whoami:!1,api_base:n})}
|
|
532
|
+
`);return}c.warn(`Logged in, but the server at this API base does not support \`/api/cli/whoami\` yet. Update with \`${f("update-cli")}\` (or re-deploy your server).`),c.message(`API base: ${n}`);return}let i=null;try{i=await o.json()}catch{i=null}if(!o.ok||!i||i.status!=="ok"){e.json?process.stdout.write(`${JSON.stringify({logged_in:!0,error:i?.error??`HTTP ${o.status}`})}
|
|
406
533
|
`):c.error(`Could not fetch your account (HTTP ${o.status})${i?.error?`: ${i.error}`:""}`),process.exitCode=1;return}if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,...i},null,2)}
|
|
407
|
-
`);return}c.message(ql(i)),i.paid===!1&&c.message(`${j.dim("Upgrade for autopilot:")} ${j.cyan(S.PRICING)}`)}function ql(e){let n=i=>j.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${j.green("\u2713")} ${j.dim("Logged in as")} ${j.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${j.cyan(e.domain)}`}),e.plan){let i=e.paid?j.bold(j.green(e.plan)):j.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${j.dim(e.api_base)}`});let o=`${j.bold(j.cyan("SEOAgent"))} ${j.dim("\xB7")} ${j.dim("whoami")}`;return L(r,{width:55,title:o})}import{select as Vt,text as Me,confirm as oo,isCancel as G,intro as zl,outro as Yl}from"@clack/prompts";import dt from"picocolors";function Jl(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>Ae()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await B()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await _e()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await Oe()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await De()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await Vt({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(!G(e))if(e==="peek"){let t=await Me({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(G(t))return;await V({peek:String(t)})}else e==="discover"?await V({discover:!0}):e==="competitors"?await V({competitors:!0}):await V()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>Ne({})},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Me({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(G(e))return;let t=await Me({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});G(t)||await Ue({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Fe({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await Vt({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"}]});G(e)||await je(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await oe()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Me({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(G(e))return;let t=await oo({message:"Mark as failed instead of completed?",initialValue:!1});if(G(t))return;let n;if(t===!0){let r=await Me({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(G(r))return;String(r).trim()&&(n=String(r))}await J(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 Re()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest",run:async()=>await Te({})},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>Le()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await Ee({})}]}var no="__exit__";async function ro(e=Jl()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:no,label:"Exit",hint:"Close the menu"});let n=await Vt({message:"What would you like to do?",options:t});if(G(n)||n===no)return!0;let r=e.find(o=>o.command===n);if(!r)return c.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){c.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function Xt(){if(!process.stdin.isTTY){c.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}zl(`${dt.bold(dt.cyan("SEOAgent"))} ${dt.dim("\xB7 menu")}`);let e=await ro();for(;!e;){let t=await oo({message:"Do another?",initialValue:!0});if(G(t)||t===!1){e=!0;break}e=await ro()}Yl(dt.dim("See you next time."))}var v=new Vl;v.name("seoagent").description("AI SEO agent for Claude Code").version(ae).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=>{_e({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=>{Ee({yes:e.yes,global:e.global})});v.command("status").description("Show current SEO project state").action(Ae);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=>{Oe({apiBase:e.apiBase})});v.command("logout").description("Remove stored credentials for seoagent.com").action(Le);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=>{B({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=>{oe({force:e.force,silent:e.silent,print:e.print})});v.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{J(e,{failed:t.failed,reason:t.reason})});v.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{Mt({json:e.json})});v.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{Ht({yes:e.yes,model:e.model})});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)=>{je(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=>{V({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=>{Ne({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=>{Fe({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=>{Ue({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=>{De({json:e.json,apiBase:e.apiBase})});v.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(Re);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=>{Te({dryRun:e.dryRun})});v.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Xt()});process.argv.length===2&&(v.outputHelp(),process.exit(0));v.parse();
|
|
534
|
+
`);return}c.message(Kc(i)),i.paid===!1&&c.message(`${j.dim("Upgrade for autopilot:")} ${j.cyan(x.PRICING)}`)}function Kc(e){let n=i=>j.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${j.green("\u2713")} ${j.dim("Logged in as")} ${j.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${j.cyan(e.domain)}`}),e.plan){let i=e.paid?j.bold(j.green(e.plan)):j.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${j.dim(e.api_base)}`});let o=`${j.bold(j.cyan("SEOAgent"))} ${j.dim("\xB7")} ${j.dim("whoami")}`;return P(r,{width:55,title:o})}import{select as Ct,text as Ve,confirm as Fo,isCancel as U,intro as qc,outro as Hc}from"@clack/prompts";import _t from"picocolors";function Yc(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>Ne()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await K()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await Oe()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await Me()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await Je()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await Ct({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(!U(e))if(e==="peek"){let t=await Ve({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(U(t))return;await ee({peek:String(t)})}else e==="discover"?await ee({discover:!0}):e==="competitors"?await ee({competitors:!0}):await ee()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>Ke({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await Ct({message:"Which OKF action?",options:[{value:"status",label:"status",hint:"Is a bundle present?"},{value:"scaffold",label:"scaffold",hint:"Create the starter bundle"},{value:"validate",label:"validate",hint:"Check type fields, timestamps, links"}]});U(e)||qe(e==="status"?void 0:String(e))}},{command:"citations",label:"Measure AI citations (AEO/GEO)",hint:"Are answer engines citing you? Web-grounded \u2192 .seoagent/citations/scorecard.md",run:async()=>await He()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Ve({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(U(e))return;let t=await Ve({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});U(t)||await ze({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Ye({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await Ct({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"}]});U(e)||await We(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await le()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Ve({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(U(e))return;let t=await Fo({message:"Mark as failed instead of completed?",initialValue:!1});if(U(t))return;let n;if(t===!0){let r=await Ve({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(U(r))return;String(r).trim()&&(n=String(r))}await X(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 De()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest",run:async()=>await Ue({})},{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 Te({})}]}var No="__exit__";async function jo(e=Yc()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:No,label:"Exit",hint:"Close the menu"});let n=await Ct({message:"What would you like to do?",options:t});if(U(n)||n===No)return!0;let r=e.find(o=>o.command===n);if(!r)return c.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){c.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function yn(){if(!process.stdin.isTTY){c.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}qc(`${_t.bold(_t.cyan("SEOAgent"))} ${_t.dim("\xB7 menu")}`);let e=await jo();for(;!e;){let t=await Fo({message:"Do another?",initialValue:!0});if(U(t)||t===!1){e=!0;break}e=await jo()}Hc(_t.dim("See you next time."))}var S=new zc;S.name("seoagent").description("AI SEO agent for Claude Code").version(de).showSuggestionAfterError(!0).showHelpAfterError(!0);S.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=>{Oe({yes:e.yes,domain:e.domain,siteType:e.siteType})});S.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=>{Te({yes:e.yes,global:e.global})});S.command("status").description("Show current SEO project state").action(Ne);S.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=>{Me({apiBase:e.apiBase})});S.command("logout").description("Remove stored credentials for seoagent.com").action(Be);S.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=>{K({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});S.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=>{le({force:e.force,silent:e.silent,print:e.print})});S.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{X(e,{failed:t.failed,reason:t.reason})});S.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{en({json:e.json})});S.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{on({yes:e.yes,model:e.model})});S.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)=>{We(e,{apiBase:t.apiBase})});S.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=>{ee({peek:e.peek,discover:e.discover,competitors:e.competitors,json:e.json,apiBase:e.apiBase})});S.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=>{Ke({json:e.json})});S.command("okf [action]").description("Manage the Open Knowledge Format bundle for AI agents \u2014 [validate|scaffold] \u2192 .seoagent/okf/").option("--json","Output result as JSON").action((e,t)=>{qe(e,{json:t.json})});S.command("citations").description("Measure whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{He({queries:e.queries,model:e.model,json:e.json})});S.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{Ye({json:e.json})});S.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=>{ze({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});S.command("whoami").description("Show the logged-in account: email, bound website, plan, and API base").option("--json","Output as JSON (handy for scripting / `jq`)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{Je({json:e.json,apiBase:e.apiBase})});S.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(De);S.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=>{Ue({dryRun:e.dryRun})});S.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{yn()});process.argv.length===2&&(S.outputHelp(),process.exit(0));S.parse();
|