@seoagent-official/seoagent 1.64.0 → 1.66.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 +4 -0
- package/index.js +91 -76
- package/package.json +5 -3
- package/skills/references/audit-checks.md +5 -0
- package/skills/references/keyword-research.md +17 -5
- package/skills/references/landing-pages.md +2 -0
- package/skills/references/listicle-articles.md +138 -0
- package/skills/references/rewrite-protocol.md +1 -0
- package/skills/references/screenshots.md +83 -0
- package/skills/seoagent.md +34 -12
package/index.js
CHANGED
|
@@ -1,47 +1,47 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as
|
|
2
|
+
import{Command as wp}from"commander";import{dirname as wo,relative as Nt}from"path";import{intro as Fa,outro as Da,text as go,select as bn,spinner as Ua,isCancel as Te,cancel as je,confirm as Ma}from"@clack/prompts";var _e=[".env.local",".env.production",".env"],ur=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];var te="@seoagent-official/seoagent",bt=`${te}@latest`;import{homedir as rs}from"os";import{join as Ce}from"path";var w=".seoagent",dr=["audit","strategy/clusters","briefs","content","content/images","performance"],ge={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},$t=".claude/settings.json",St=".pull-receipt.json",pr=".ack-queue.json",fr=".sync.lock",mr=`# 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
|
-
`),i=
|
|
9
|
+
`,os=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:Ce(rs(),".config"),M=Ce(os,"seoagent"),ie=Ce(M,"auth.json"),rn=Ce(M,"state"),vt=Ce(M,"update-check.json"),xt=Ce(M,"projects.json");var qe="https://seoagent.com",Ee=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):qe,A={BASE:Ee,PRICING:`${Ee}/pricing`,LEAD_API:`${Ee}/api/cli/lead`,CLI_AUTH_PAGE:`${Ee}/cli/auth`,CLI_AUTH_POLL:`${Ee}/api/cli/auth/poll`,CLI_SYNC:`${Ee}/api/cli/sync`};import{readFileSync as is}from"fs";import{fileURLToPath as ss}from"url";import{dirname as as,join as cs}from"path";var gr="0.0.0";function ls(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return gr}function us(e=t=>is(t,"utf-8")){try{let t=as(ss(import.meta.url));return ls(e(cs(t,"package.json")))}catch{return gr}}var E=us();function on(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=on()){return t?`seoagent ${e}`:`npx -y ${bt} ${e}`}import{randomUUID as hs}from"crypto";import{existsSync as wr,mkdirSync as kr,readFileSync as ys,writeFileSync as br}from"fs";import{join as an}from"path";import{existsSync as ds,readFileSync as ps}from"fs";var _t="---";function fs(e){let t=e.trim();return 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 ms(e){let t=[];for(let n of e){let r=n.trim();if(r===""||r.startsWith("#"))continue;let o=n.indexOf(":");if(o===-1)continue;let i=n.slice(0,o).trim();if(!i)continue;let s=n.slice(o+1),a=n.length-n.replace(/^\s+/,"").length;t.push({indent:a,key:i,valueRaw:s,value:s.trim()})}return t}function hr(e,t,n){let r={},o=t;for(;o<e.length;){let i=e[o];if(i.indent<n)break;if(i.indent>n){o++;continue}if(i.value===""){let s=e[o+1];if(s&&s.indent>n){let[a,c]=hr(e,o+1,s.indent);r[i.key]=a,o=c}else r[i.key]="",o++}else r[i.key]=fs(i.valueRaw),o++}return[r,o]}function se(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==_t)return{data:{},body:e};let n=-1;for(let c=1;c<t.length;c++)if(t[c].trim()===_t){n=c;break}let r=n===-1?t.slice(1):t.slice(1,n),o=n===-1?"":t.slice(n+1).join(`
|
|
10
|
+
`),i=ms(r),s=i.length>0?i[0].indent:0,[a]=hr(i,0,s);return{data:a,body:o}}function Ct(e){if(!ds(e))return null;try{return se(ps(e,"utf-8"))}catch{return null}}function gs(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 yr(e,t,n){let r=" ".repeat(t);for(let[o,i]of Object.entries(e))i!==void 0&&(i!==null&&typeof i=="object"?(n.push(`${r}${o}:`),yr(i,t+1,n)):n.push(`${r}${o}: ${gs(i)}`))}function sn(e,t=""){let n=[_t];yr(e,0,n),n.push(_t);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
|
|
15
|
+
`)}var ws=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function cn(){return hs()}var ks=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),bs="project.md";function He(e){return an(e,w)}function Et(e){return an(He(e),bs)}function $r(e){return wr(Et(e))}function _(e){let t=Ct(Et(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&&ks.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:"",skill_version:typeof n.skill_version=="string"&&n.skill_version?n.skill_version:void 0,install_id:s&&ws.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 Sr(e){let t=_(e);if(!t)return null;if(t.install_id)return t.install_id;let n=cn();return z(e,{install_id:n}),n}function $s(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 Ss(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.skill_version&&(t.skill_version=e.skill_version),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 vr(e,t){let n=He(e);kr(n,{recursive:!0});let r=sn(Ss(t),$s(t));br(Et(e),r,"utf-8")}function z(e,t){let n=Et(e);if(!wr(n))return!1;let r=se(ys(n,"utf-8")),o={...r.data,...t};return br(n,sn(o,r.body),"utf-8"),!0}function xr(e){let t=He(e);for(let n of dr)kr(an(t,n),{recursive:!0})}import{existsSync as At,lstatSync as vs,mkdirSync as Ye,readFileSync as _r,readdirSync as xs,rmSync as _s,statSync as Cs,symlinkSync as Es,writeFileSync as Cr}from"fs";import{dirname as Rt,join as J,relative as Er}from"path";import{fileURLToPath as As}from"url";var Rs=Rt(As(import.meta.url));function Ar(){return J(Rs,"skills")}function Is(){let e=J(Ar(),"seoagent.md");if(At(e))return _r(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function Rr(e,t){let n=[];if(!At(e))return n;for(let r of xs(e,{withFileTypes:!0})){let o=J(e,r.name),i=J(t,r.name);r.isDirectory()?(Ye(i,{recursive:!0}),n.push(...Rr(o,i))):r.isFile()&&(Ye(Rt(i),{recursive:!0}),Cr(i,_r(o)),n.push(i))}return n}function Ae(e,t){let n=At(J(e,".agents")),r=J(e,n?ge.AGENTS:ge.CLAUDE),o=J(r,"SKILL.md");Ye(r,{recursive:!0}),Cr(o,t??Is(),"utf-8");let i=J(Ar(),"references"),s=J(r,"references"),a=[];try{At(i)&&Cs(i).isDirectory()&&(Ye(s,{recursive:!0}),a=Rr(i,s).map(u=>Er(r,u)))}catch{}let c=n?Ps(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:c}}function Ps(e,t){let n=J(e,ge.CLAUDE),r=null;try{r=vs(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{_s(n,{force:!0})}catch{return}}try{Ye(Rt(n),{recursive:!0});let o=Er(Rt(n),t);return Es(o,n,"dir"),n}catch{return}}import{existsSync as Pt,mkdirSync as ln,readFileSync as Os,writeFileSync as It}from"fs";import{dirname as Pr,join as Re}from"path";var Ts=`npx -y ${bt} sync --silent`;function Or(e){let t=Re(e,w);ln(t,{recursive:!0});let n=Re(t,".gitignore");It(n,mr,"utf-8");let r=Re(t,"content","images",".gitkeep");return ln(Pr(r),{recursive:!0}),Pt(r)||It(r,"","utf-8"),n}var Tr=["PostToolUse","SessionStart"];function un(e){if(!Pt(e))return{};try{let t=Os(e,"utf-8");return JSON.parse(t)}catch{return{}}}function dn(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function Ir(e,t,n){let r=e.find(t);return r||(r=n(),e.push(r)),r.hooks.some(dn)?!1:(r.hooks.push({type:"command",command:Ts}),!0)}function he(e){let t=Re(e,$t);ln(Pr(t),{recursive:!0});let n=un(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=Ir(r,a=>(a.matcher??"").includes("Write"),()=>({matcher:"Write|Edit",hooks:[]})),i=n.hooks.SessionStart=n.hooks.SessionStart??[],s=Ir(i,a=>(a.matcher??"")==="",()=>({hooks:[]}));return It(t,JSON.stringify(n,null,2)+`
|
|
17
17
|
`,"utf-8"),{file:t,added:o||s}}function jr(e){let t=Re(e,$t);if(!Pt(t))return!1;let n=un(t).hooks;return n?Tr.some(r=>{let o=n[r];return Array.isArray(o)&&o.some(i=>i.hooks?.some(dn))}):!1}function Lr(e){let t=Re(e,$t);if(!Pt(t))return{file:t,removed:!1};let n=un(t),r=n.hooks;if(!r)return{file:t,removed:!1};let o=!1;for(let i of Tr){let s=r[i];if(!Array.isArray(s))continue;for(let c of s){let u=c.hooks.length;c.hooks=c.hooks.filter(d=>!dn(d)),c.hooks.length!==u&&(o=!0)}let a=s.filter(c=>c.hooks.length>0);a.length===0?delete r[i]:r[i]=a}return o?(Object.keys(r).length===0&&delete n.hooks,It(t,JSON.stringify(n,null,2)+`
|
|
18
|
-
`,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as Nr,mkdirSync as
|
|
19
|
-
`,"utf-8")}catch{}}function ye(e){try{if(!Fr(e))return;let t=Dr();if(t.includes(e))return;t.push(e),Ur(t)}catch{}}function Mr(){let e=Dr(),t=e.filter(Fr);return t.length!==e.length&&Ur(t),t}import{readFileSync as
|
|
20
|
-
`)}function
|
|
18
|
+
`,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{existsSync as Nr,mkdirSync as js,readFileSync as Ls,writeFileSync as Ns}from"fs";import{join as Fs}from"path";function Fr(e){return Nr(Fs(e,w,"project.md"))}function Dr(){try{if(!Nr(xt))return[];let e=JSON.parse(Ls(xt,"utf-8"));return Array.isArray(e.projects)?e.projects.filter(t=>typeof t=="string"&&t.length>0):[]}catch{return[]}}function Ur(e){try{js(M,{recursive:!0}),Ns(xt,JSON.stringify({projects:e},null,2)+`
|
|
19
|
+
`,"utf-8")}catch{}}function ye(e){try{if(!Fr(e))return;let t=Dr();if(t.includes(e))return;t.push(e),Ur(t)}catch{}}function Mr(){let e=Dr(),t=e.filter(Fr);return t.length!==e.length&&Ur(t),t}import{readFileSync as Bs,writeFileSync as Ws,existsSync as Gs}from"fs";import{join as Kr}from"path";function Wr(e){let t={business:{},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null},n=Ds(e);for(let[r,o]of n){let i=r.toLowerCase().trim();i==="business context"?t.business=Us(o):i==="writing instructions"?t.writingInstructions=Br(o):i==="reference urls"?t.referenceUrls=Ms(o):i==="topics to avoid"?t.topicsToAvoid=Br(o):i==="content tone"?t.contentTone=o.trim()||null:i==="additional notes"&&(t.additionalNotes=o.trim()||null)}return t}function Gr(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 Ds(e){let t=e.split(`
|
|
21
21
|
`),n=[],r="",o=[];for(let i of t){let s=i.match(/^#\s+(.+)$/);s?(r&&n.push([r,o.join(`
|
|
22
22
|
`)]),r=s[1],o=[]):o.push(i)}return r&&n.push([r,o.join(`
|
|
23
|
-
`)]),n}function
|
|
23
|
+
`)]),n}function Us(e){let t={},n=e.split(`
|
|
24
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 Br(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
|
|
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 qr="context.md";function Hr(e){let t=Kr(e,".seoagent",qr);if(!Ws(t))return null;let n=Ms(t,"utf-8");return Wr(n)}function Gs(e,t){let n=Kr(e,".seoagent",qr),r=Gr(t);Bs(n,r,"utf-8")}function Yr(e,t){Gs(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as ze,readFileSync as zr,readdirSync as Ks,statSync as Vr}from"fs";import{join as we}from"path";var qs=[{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 Hs(e){let t=we(e,"package.json");if(!ze(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(zr(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Ys(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 zs(e){let t={};for(let n of _e){let r=we(e,n);if(ze(r))try{let o=zr(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 c=s.slice(0,a).trim();c&&!(c in t)&&(t[c]=n)}}catch{}}return t}function Vs(e,t){let n=we(e,t.replace(/\/$/,""));if(!ze(n))return!1;if(t.endsWith("/"))try{return Vr(n).isDirectory()}catch{return!1}return!0}function Js(e){let t=["content","_posts","posts",we("src","content")];for(let n of t){let r=we(e,n);if(ze(r))try{if(!Vr(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of Ks(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(we(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 Xs(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(ze(we(e,n.marker)))return n.path;return null}function Jr(e){let t=[],{deps:n}=Hs(e),r=zs(e),o="none";for(let s of qs){let a=[];for(let c of Object.keys(n))if(Ys(c,s.deps)){a.push({type:"dep",detail:c,source:"package.json"});break}for(let c of s.envKeys)if(r[c]){a.push({type:"env",detail:c,source:r[c]});break}for(let c of s.fsMarkers)if(Vs(e,c)){let u=c.endsWith("/")?"directory":"file";a.push({type:u,detail:c,source:c});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=Js(e);s&&(o="mdx-local",t.push(s))}let i=Xs(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as Qs,readFileSync as Zs}from"fs";import{join as ea}from"path";var Xr=["openai","fal","replicate"],Ie={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function ta(e){let t={};if(!Qs(e))return t;let n=Zs(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 Qr(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 _e){let o=ea(e,r),i=ta(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 ae(e){let t=[].concat(...Xr.map(a=>Ie[a])),n=Qr(e,t),r=[];for(let a of Xr)Ie[a].some(c=>n.found[c])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=Ie[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 Zr(e,t){let n=Qr(e,Ie[t]);for(let r of Ie[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function eo(){return Ie}import{existsSync as ke,readFileSync as pn}from"fs";import{join as be}from"path";function to(e){try{return new URL(e).hostname}catch{return e}}function no(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 na(e){for(let t of _e){let n=be(e,t);if(!ke(n))continue;let r=pn(n,"utf-8");for(let o of ur){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=to(s);if(no(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function ra(e){let t=be(e,"package.json");if(!ke(t))return null;try{let n=JSON.parse(pn(t,"utf-8"));if(!n.homepage)return null;let r=to(n.homepage);return no(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function ro(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ke(be(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=na(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=ra(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=be(e,"package.json"),s=null;if(ke(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(pn(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>c.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||ke(be(e,"shopify.config.js"))||ke(be(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ke(be(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"),g=u("next");d&&(g||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:g?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!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 da,readFileSync as yn,readdirSync as so,statSync as pa}from"fs";import{join as H,sep as fa}from"path";var oa=new Set([502,503,504]),ia=1e4;async function B(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??ia,s=n.fetchImpl??fetch,a=n.sleep??sa,c=n.transientStatuses??oa,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:g}=aa(t,i);try{let m=await s(e,p);if(c.has(m.status)&&d<r-1){await a(oo(o,d));continue}return m}catch(m){if(u=m,d<r-1){await a(oo(o,d));continue}}finally{g()}}throw u instanceof Error?u:new Error(String(u))}function oo(e,t){return e*Math.pow(3,t)}function sa(e){return new Promise(t=>setTimeout(t,e))}function aa(e,t){if(t<=0)return{init:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Request timed out after ${t}ms`)),t),o=e?.signal??void 0,i;o&&(o.aborted?n.abort(o.reason):(i=()=>n.abort(o.reason),o.addEventListener("abort",i,{once:!0})));let s=()=>{clearTimeout(r),o&&i&&o.removeEventListener("abort",i)};return{init:{...e,signal:n.signal},cleanup:s}}var ca=[/^\/admin(\/|$)/i,/^\/account(s)?(\/|$)/i,/^\/dashboard(\/|$)/i,/^\/settings(\/|$)/i,/^\/login(\/|$)/i,/^\/logout(\/|$)/i,/^\/sign[-_]?in(\/|$)/i,/^\/sign[-_]?up(\/|$)/i,/^\/register(\/|$)/i,/^\/reset[-_]?password(\/|$)/i,/^\/verify(\/|$)/i,/^\/api(\/|$)/i,/^\/_next(\/|$)/i,/^\/checkout(\/|$)/i,/^\/cart(\/|$)/i];function fn(e){let t=[],n=/<loc>\s*([^<\s][^<]*?)\s*<\/loc>/gi,r;for(;(r=n.exec(e))!==null;){let o=r[1].replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,'"').trim();o&&t.push(o)}return t}function $e(e){let t=e;try{t=new URL(e).pathname}catch{let n=t.indexOf("#");n!==-1&&(t=t.slice(0,n));let r=t.indexOf("?");r!==-1&&(t=t.slice(0,r))}return t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t||"/"}function Ot(e){return ca.some(t=>t.test(e))}function la(e){return e.filter(t=>Ot($e(t)))}function ua(e,t){let n=new Set(e.map($e)),r=[],o=new Set;for(let i of t){let s=$e(i);Ot(s)||n.has(s)||o.has(s)||(o.add(s),r.push(s))}return r}function mn(e){return`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`}async function io(e){let t=e.sitemapUrl||mn(e.domain),n=[],r={ok:!1,sitemapUrl:t,fetched:!1,status:null,urls:[],privateUrls:[],missing:[],hasLastmod:!1,issues:n},o="";try{let i=await B(t,{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:2,timeoutMs:1e4,fetchImpl:e.fetchImpl});if(r.status=i.status,r.fetched=!0,!i.ok)return n.push({level:"error",message:`Sitemap returned HTTP ${i.status} \u2014 Google can't fetch it. Make sure ${t} serves 200.`}),r;o=await i.text()}catch(i){return n.push({level:"error",message:`Could not reach ${t} (${i instanceof Error?i.message:String(i)}). If the site isn't deployed yet, that's expected.`}),r}return/<urlset|<sitemapindex/i.test(o)?(r.urls=fn(o),r.hasLastmod=/<lastmod>/i.test(o),r.urls.length===0?(n.push({level:"error",message:"Sitemap is valid XML but contains zero <loc> URLs."}),r):(/<sitemapindex/i.test(o)&&n.push({level:"info",message:`Sitemap index with ${r.urls.length} child sitemap(s). Child URLs are not expanded by this check.`}),r.privateUrls=la(r.urls),r.privateUrls.length>0&&n.push({level:"warning",message:`${r.privateUrls.length} private/noindex URL(s) leaked into the sitemap (e.g. ${r.privateUrls.slice(0,3).map($e).join(", ")}). Remove auth/admin/api routes from the generator.`}),r.hasLastmod||n.push({level:"info",message:"No <lastmod> dates \u2014 adding them helps crawlers prioritize changed pages."}),e.knownUrls&&e.knownUrls.length>0&&(r.missing=ua(r.urls,e.knownUrls),r.missing.length>0&&n.push({level:"warning",message:`${r.missing.length} public page(s) in the repo are missing from the sitemap (e.g. ${r.missing.slice(0,3).join(", ")}). Add them to the generator so Google can find them.`})),r.ok=!n.some(i=>i.level==="error"),r)):(n.push({level:"error",message:`Response is not a valid XML sitemap (no <urlset>/<sitemapindex>). Got ${o.length} bytes.`}),r)}var ao=["tsx","jsx","js","mdx","md"],ma=["astro","md","mdx"],ga=5e3;function ce(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=ba(i);if(c===null){r++;return}let u=n.get(c);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(c,{route:c,url:Aa(t,c),in_sitemap:a,source:s})};for(let i of ya(e))ha(i,o);return{pages:[...n.values()].filter(i=>!Ot(i.route)).sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}async function co(e,t,n){let r=[];try{let s=await B(mn(t),{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:1,timeoutMs:5e3,fetchImpl:n});if(!s.ok)return{checked:!1,liveCount:0,flipped:0};r=fn(await s.text())}catch{return{checked:!1,liveCount:0,flipped:0}}if(r.length===0)return{checked:!1,liveCount:0,flipped:0};let o=new Set(r.map($e)),i=0;for(let s of e)!s.in_sitemap&&o.has($e(s.url||s.route))&&(s.in_sitemap=!0,i++,s.source.includes("live-sitemap")||(s.source+=", live-sitemap"));return{checked:!0,liveCount:r.length,flipped:i}}function ha(e,t){for(let n of["app",H("src","app")]){let r=H(e,n);if(Ve(r))for(let o of gn(r)){let i=hn(r,o),s=i[i.length-1];_a(s)&&(i.some(a=>a.startsWith("@"))||t($a(i.slice(0,-1)),"app router"))}}for(let n of["pages",H("src","pages")]){let r=H(e,n);if(Ve(r))for(let o of gn(r)){let i=hn(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=wn(s),c=ao.includes(a),u=ma.includes(a);if(!c&&!u)continue;let d=Tt(s);Ca(d)||t(Sa(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=H(e,n);if(Ve(r))for(let o of gn(r,n==="."?1:1/0)){let i=hn(r,o),s=i[i.length-1];wn(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(va(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=H(e,...n.split("/"));if(da(r)){for(let o of Ea(r)){let i=xa(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function ya(e){let t=[e],n=new Set([e]);for(let r of wa(e))for(let o of ka(e,r))n.has(o)||(n.add(o),t.push(o));return t}function wa(e){let t=[];try{let n=yn(H(e,"pnpm-workspace.yaml"),"utf-8"),r=!1;for(let o of n.split(/\r?\n/)){let i=o.replace(/#.*$/,"");if(/^\s*packages\s*:/.test(i)){r=!0;continue}if(r){let s=i.match(/^\s*-\s*['"]?([^'"\s]+)['"]?\s*$/);s?t.push(s[1]):/^\S/.test(i)&&(r=!1)}}}catch{}try{let r=JSON.parse(yn(H(e,"package.json"),"utf-8")).workspaces,o=Array.isArray(r)?r:Array.isArray(r?.packages)?r.packages:[];for(let i of o??[])typeof i=="string"&&t.push(i)}catch{}return t}function ka(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=H(e,...n.split("/").filter(Boolean));return Ve(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=H(e,...o.split("/").filter(Boolean));if(!Ve(i))return[];let s=[];try{for(let a of so(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!lo.has(a.name)&&(s.push(H(i,a.name)),s.length>=200))break}catch{}return s}function ba(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function $a(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function Sa(e){let t=[...e],n=Tt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function va(e){let t=[...e],n=Tt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function xa(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function _a(e){return Tt(e)==="page"&&ao.includes(wn(e))}function Ca(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Ea(e){try{let t=yn(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 lo=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Ve(e){try{return pa(e).isDirectory()}catch{return!1}}function*gn(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=so(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=ga)return;if(a.name.startsWith("."))continue;let c=H(o,a.name);if(a.isDirectory()){if(lo.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function hn(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(fa).filter(Boolean)}function wn(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Tt(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Aa(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as Ra,mkdirSync as Ia,readFileSync as Pa,writeFileSync as Oa}from"fs";import{join as uo}from"path";function po(e,t){let n=!1,r=t.status!==null?String(t.status):"\u2014";e.status!==r&&(e.status=r,n=!0),e.rendered!==t.rendered&&(e.rendered=t.rendered,n=!0);let o=t.rendered==="error"?"\u2014":String(t.wordCount);return e.word_count!==o&&(e.word_count=o,n=!0),n}function jt(e,t,n){let r=uo(e,w,"pages.md"),o=Ra(r),i=o?ja(r):new Map;if(t.length===0&&!o)return{wrote:!1,added:0,total:0,merged:!1};let s=new Map(i),a=0,c=!1;for(let d of t){let p=mo(d.url),g=n?.get(d.url),m=s.get(p);if(m)d.in_sitemap&&m.in_sitemap!=="yes"&&(m.in_sitemap="yes",c=!0),g&&po(m,g)&&(c=!0);else{let $={url:p,in_sitemap:d.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",word_count:"\u2014",notes:mo(d.source)};g&&po($,g),s.set(p,$),a++,c=!0}}if(o&&!c)return{wrote:!1,added:0,total:s.size,merged:!0};let u=[...s.values()];return Ia(uo(e,w),{recursive:!0}),Oa(r,Ta(u),"utf-8"),{wrote:!0,added:a,total:u.length,merged:o}}function Ta(e){let t=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
|
|
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 Ms(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 qr="context.md";function Hr(e){let t=Kr(e,".seoagent",qr);if(!Gs(t))return null;let n=Bs(t,"utf-8");return Wr(n)}function Ks(e,t){let n=Kr(e,".seoagent",qr),r=Gr(t);Ws(n,r,"utf-8")}function Yr(e,t){Ks(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as ze,readFileSync as zr,readdirSync as qs,statSync as Vr}from"fs";import{join as we}from"path";var Hs=[{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 Ys(e){let t=we(e,"package.json");if(!ze(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(zr(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function zs(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 Vs(e){let t={};for(let n of _e){let r=we(e,n);if(ze(r))try{let o=zr(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 c=s.slice(0,a).trim();c&&!(c in t)&&(t[c]=n)}}catch{}}return t}function Js(e,t){let n=we(e,t.replace(/\/$/,""));if(!ze(n))return!1;if(t.endsWith("/"))try{return Vr(n).isDirectory()}catch{return!1}return!0}function Xs(e){let t=["content","_posts","posts",we("src","content")];for(let n of t){let r=we(e,n);if(ze(r))try{if(!Vr(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of qs(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(we(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 Qs(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(ze(we(e,n.marker)))return n.path;return null}function Jr(e){let t=[],{deps:n}=Ys(e),r=Vs(e),o="none";for(let s of Hs){let a=[];for(let c of Object.keys(n))if(zs(c,s.deps)){a.push({type:"dep",detail:c,source:"package.json"});break}for(let c of s.envKeys)if(r[c]){a.push({type:"env",detail:c,source:r[c]});break}for(let c of s.fsMarkers)if(Js(e,c)){let u=c.endsWith("/")?"directory":"file";a.push({type:u,detail:c,source:c});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=Xs(e);s&&(o="mdx-local",t.push(s))}let i=Qs(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as Zs,readFileSync as ea}from"fs";import{join as ta}from"path";var Xr=["openai","fal","replicate"],Ie={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function na(e){let t={};if(!Zs(e))return t;let n=ea(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 Qr(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 _e){let o=ta(e,r),i=na(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 ae(e){let t=[].concat(...Xr.map(a=>Ie[a])),n=Qr(e,t),r=[];for(let a of Xr)Ie[a].some(c=>n.found[c])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=Ie[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 Zr(e,t){let n=Qr(e,Ie[t]);for(let r of Ie[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function eo(){return Ie}import{existsSync as ke,readFileSync as pn}from"fs";import{join as be}from"path";function to(e){try{return new URL(e).hostname}catch{return e}}function no(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 ra(e){for(let t of _e){let n=be(e,t);if(!ke(n))continue;let r=pn(n,"utf-8");for(let o of ur){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=to(s);if(no(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function oa(e){let t=be(e,"package.json");if(!ke(t))return null;try{let n=JSON.parse(pn(t,"utf-8"));if(!n.homepage)return null;let r=to(n.homepage);return no(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function ro(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ke(be(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=ra(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=oa(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=be(e,"package.json"),s=null;if(ke(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(pn(i,"utf-8")),c=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>c.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||ke(be(e,"shopify.config.js"))||ke(be(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ke(be(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"),g=u("next");d&&(g||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:g?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!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 pa,readFileSync as yn,readdirSync as so,statSync as fa}from"fs";import{join as H,sep as ma}from"path";var ia=new Set([502,503,504]),sa=1e4;async function B(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.timeoutMs??sa,s=n.fetchImpl??fetch,a=n.sleep??aa,c=n.transientStatuses??ia,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:g}=ca(t,i);try{let m=await s(e,p);if(c.has(m.status)&&d<r-1){await a(oo(o,d));continue}return m}catch(m){if(u=m,d<r-1){await a(oo(o,d));continue}}finally{g()}}throw u instanceof Error?u:new Error(String(u))}function oo(e,t){return e*Math.pow(3,t)}function aa(e){return new Promise(t=>setTimeout(t,e))}function ca(e,t){if(t<=0)return{init:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>n.abort(new Error(`Request timed out after ${t}ms`)),t),o=e?.signal??void 0,i;o&&(o.aborted?n.abort(o.reason):(i=()=>n.abort(o.reason),o.addEventListener("abort",i,{once:!0})));let s=()=>{clearTimeout(r),o&&i&&o.removeEventListener("abort",i)};return{init:{...e,signal:n.signal},cleanup:s}}var la=[/^\/admin(\/|$)/i,/^\/account(s)?(\/|$)/i,/^\/dashboard(\/|$)/i,/^\/settings(\/|$)/i,/^\/login(\/|$)/i,/^\/logout(\/|$)/i,/^\/sign[-_]?in(\/|$)/i,/^\/sign[-_]?up(\/|$)/i,/^\/register(\/|$)/i,/^\/reset[-_]?password(\/|$)/i,/^\/verify(\/|$)/i,/^\/api(\/|$)/i,/^\/_next(\/|$)/i,/^\/checkout(\/|$)/i,/^\/cart(\/|$)/i];function fn(e){let t=[],n=/<loc>\s*([^<\s][^<]*?)\s*<\/loc>/gi,r;for(;(r=n.exec(e))!==null;){let o=r[1].replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,'"').trim();o&&t.push(o)}return t}function $e(e){let t=e;try{t=new URL(e).pathname}catch{let n=t.indexOf("#");n!==-1&&(t=t.slice(0,n));let r=t.indexOf("?");r!==-1&&(t=t.slice(0,r))}return t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t||"/"}function Ot(e){return la.some(t=>t.test(e))}function ua(e){return e.filter(t=>Ot($e(t)))}function da(e,t){let n=new Set(e.map($e)),r=[],o=new Set;for(let i of t){let s=$e(i);Ot(s)||n.has(s)||o.has(s)||(o.add(s),r.push(s))}return r}function mn(e){return`https://${e.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/sitemap.xml`}async function io(e){let t=e.sitemapUrl||mn(e.domain),n=[],r={ok:!1,sitemapUrl:t,fetched:!1,status:null,urls:[],privateUrls:[],missing:[],hasLastmod:!1,issues:n},o="";try{let i=await B(t,{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:2,timeoutMs:1e4,fetchImpl:e.fetchImpl});if(r.status=i.status,r.fetched=!0,!i.ok)return n.push({level:"error",message:`Sitemap returned HTTP ${i.status} \u2014 Google can't fetch it. Make sure ${t} serves 200.`}),r;o=await i.text()}catch(i){return n.push({level:"error",message:`Could not reach ${t} (${i instanceof Error?i.message:String(i)}). If the site isn't deployed yet, that's expected.`}),r}return/<urlset|<sitemapindex/i.test(o)?(r.urls=fn(o),r.hasLastmod=/<lastmod>/i.test(o),r.urls.length===0?(n.push({level:"error",message:"Sitemap is valid XML but contains zero <loc> URLs."}),r):(/<sitemapindex/i.test(o)&&n.push({level:"info",message:`Sitemap index with ${r.urls.length} child sitemap(s). Child URLs are not expanded by this check.`}),r.privateUrls=ua(r.urls),r.privateUrls.length>0&&n.push({level:"warning",message:`${r.privateUrls.length} private/noindex URL(s) leaked into the sitemap (e.g. ${r.privateUrls.slice(0,3).map($e).join(", ")}). Remove auth/admin/api routes from the generator.`}),r.hasLastmod||n.push({level:"info",message:"No <lastmod> dates \u2014 adding them helps crawlers prioritize changed pages."}),e.knownUrls&&e.knownUrls.length>0&&(r.missing=da(r.urls,e.knownUrls),r.missing.length>0&&n.push({level:"warning",message:`${r.missing.length} public page(s) in the repo are missing from the sitemap (e.g. ${r.missing.slice(0,3).join(", ")}). Add them to the generator so Google can find them.`})),r.ok=!n.some(i=>i.level==="error"),r)):(n.push({level:"error",message:`Response is not a valid XML sitemap (no <urlset>/<sitemapindex>). Got ${o.length} bytes.`}),r)}var ao=["tsx","jsx","js","mdx","md"],ga=["astro","md","mdx"],ha=5e3;function ce(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let c=$a(i);if(c===null){r++;return}let u=n.get(c);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(c,{route:c,url:Ra(t,c),in_sitemap:a,source:s})};for(let i of wa(e))ya(i,o);return{pages:[...n.values()].filter(i=>!Ot(i.route)).sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}async function co(e,t,n){let r=[];try{let s=await B(mn(t),{headers:{"user-agent":"SEOAgent-CLI/sitemap-check"}},{attempts:1,timeoutMs:5e3,fetchImpl:n});if(!s.ok)return{checked:!1,liveCount:0,flipped:0};r=fn(await s.text())}catch{return{checked:!1,liveCount:0,flipped:0}}if(r.length===0)return{checked:!1,liveCount:0,flipped:0};let o=new Set(r.map($e)),i=0;for(let s of e)!s.in_sitemap&&o.has($e(s.url||s.route))&&(s.in_sitemap=!0,i++,s.source.includes("live-sitemap")||(s.source+=", live-sitemap"));return{checked:!0,liveCount:r.length,flipped:i}}function ya(e,t){for(let n of["app",H("src","app")]){let r=H(e,n);if(Ve(r))for(let o of gn(r)){let i=hn(r,o),s=i[i.length-1];Ca(s)&&(i.some(a=>a.startsWith("@"))||t(Sa(i.slice(0,-1)),"app router"))}}for(let n of["pages",H("src","pages")]){let r=H(e,n);if(Ve(r))for(let o of gn(r)){let i=hn(r,o);if(i[0]==="api")continue;let s=i[i.length-1],a=wn(s),c=ao.includes(a),u=ga.includes(a);if(!c&&!u)continue;let d=Tt(s);Ea(d)||t(va(i),u?"astro":"pages router")}}for(let n of[".","public"]){let r=H(e,n);if(Ve(r))for(let o of gn(r,n==="."?1:1/0)){let i=hn(r,o),s=i[i.length-1];wn(s)==="html"&&(i.some(a=>a==="node_modules"||a.startsWith("."))||t(xa(i),"static html"))}}for(let n of["public/sitemap.xml","sitemap.xml"]){let r=H(e,...n.split("/"));if(pa(r)){for(let o of Aa(r)){let i=_a(o);i!==null&&t(i,"sitemap.xml",!0)}break}}}function wa(e){let t=[e],n=new Set([e]);for(let r of ka(e))for(let o of ba(e,r))n.has(o)||(n.add(o),t.push(o));return t}function ka(e){let t=[];try{let n=yn(H(e,"pnpm-workspace.yaml"),"utf-8"),r=!1;for(let o of n.split(/\r?\n/)){let i=o.replace(/#.*$/,"");if(/^\s*packages\s*:/.test(i)){r=!0;continue}if(r){let s=i.match(/^\s*-\s*['"]?([^'"\s]+)['"]?\s*$/);s?t.push(s[1]):/^\S/.test(i)&&(r=!1)}}}catch{}try{let r=JSON.parse(yn(H(e,"package.json"),"utf-8")).workspaces,o=Array.isArray(r)?r:Array.isArray(r?.packages)?r.packages:[];for(let i of o??[])typeof i=="string"&&t.push(i)}catch{}return t}function ba(e,t){if(!t||t.startsWith("!"))return[];let n=t.replace(/\/\*\*?$/,"/*"),r=n.indexOf("*");if(r===-1){let a=H(e,...n.split("/").filter(Boolean));return Ve(a)?[a]:[]}let o=n.slice(0,r).replace(/\/$/,""),i=H(e,...o.split("/").filter(Boolean));if(!Ve(i))return[];let s=[];try{for(let a of so(i,{withFileTypes:!0}))if(a.isDirectory()&&!a.name.startsWith(".")&&!lo.has(a.name)&&(s.push(H(i,a.name)),s.length>=200))break}catch{}return s}function $a(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function Sa(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function va(e){let t=[...e],n=Tt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function xa(e){let t=[...e],n=Tt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function _a(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function Ca(e){return Tt(e)==="page"&&ao.includes(wn(e))}function Ea(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function Aa(e){try{let t=yn(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 lo=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Ve(e){try{return fa(e).isDirectory()}catch{return!1}}function*gn(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=so(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=ha)return;if(a.name.startsWith("."))continue;let c=H(o,a.name);if(a.isDirectory()){if(lo.has(a.name))continue;yield*r(c,i+1)}else a.isFile()&&(n++,yield c)}}yield*r(e,1)}function hn(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(ma).filter(Boolean)}function wn(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Tt(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Ra(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{existsSync as Ia,mkdirSync as Pa,readFileSync as Oa,writeFileSync as Ta}from"fs";import{join as uo}from"path";function po(e,t){let n=!1,r=t.status!==null?String(t.status):"\u2014";e.status!==r&&(e.status=r,n=!0),e.rendered!==t.rendered&&(e.rendered=t.rendered,n=!0);let o=t.rendered==="error"?"\u2014":String(t.wordCount);return e.word_count!==o&&(e.word_count=o,n=!0),n}function jt(e,t,n){let r=uo(e,w,"pages.md"),o=Ia(r),i=o?La(r):new Map;if(t.length===0&&!o)return{wrote:!1,added:0,total:0,merged:!1};let s=new Map(i),a=0,c=!1;for(let d of t){let p=mo(d.url),g=n?.get(d.url),m=s.get(p);if(m)d.in_sitemap&&m.in_sitemap!=="yes"&&(m.in_sitemap="yes",c=!0),g&&po(m,g)&&(c=!0);else{let $={url:p,in_sitemap:d.in_sitemap?"yes":"no",in_nav:"\u2014",status:"\u2014",rendered:"\u2014",word_count:"\u2014",notes:mo(d.source)};g&&po($,g),s.set(p,$),a++,c=!0}}if(o&&!c)return{wrote:!1,added:0,total:s.size,merged:!0};let u=[...s.values()];return Pa(uo(e,w),{recursive:!0}),Ta(r,ja(u),"utf-8"),{wrote:!0,added:a,total:u.length,merged:o}}function ja(e){let t=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${e.length}`,"---"].join(`
|
|
27
27
|
`),n=["# Pages","","Inventory of pages discovered in your codebase. Re-running `seoagent init`","or `seoagent refresh` re-scans and merges in newly-added pages without","touching rows you or the audit have edited. `In sitemap` is refreshed from","the live sitemap; `Status` / `Rendered` / `Word count` are filled by","`seoagent refresh --crawl` (a live fetch of each page). This file syncs to","the cloud on login."].join(`
|
|
28
28
|
`),r="| URL | In sitemap | In nav | Status | Rendered | Word count | Notes |",o="|---|---|---|---|---|---|---|",i=e.map(s=>`| ${s.url} | ${s.in_sitemap} | ${s.in_nav} | ${s.status} | ${s.rendered} | ${s.word_count} | ${s.notes} |`);return[t,"",n,"",r,o,...i,""].join(`
|
|
29
|
-
`)}function ja(e){let t=new Map,n;try{n=Pa(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!kn(r[o])||!La(r[o+1]))continue;let i=fo(r[o]).map(a=>a.toLowerCase()),s={url:i.findIndex(a=>a.includes("url")),in_sitemap:i.findIndex(a=>a.includes("sitemap")),in_nav:i.findIndex(a=>a.includes("nav")),status:i.findIndex(a=>a.includes("status")||a.includes("http")),rendered:i.findIndex(a=>a.includes("render")),word_count:i.findIndex(a=>a.includes("word")),notes:i.findIndex(a=>a.includes("note"))};if(s.url===-1)return t;for(let a=o+2;a<r.length&&kn(r[a]);a++){let c=fo(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:Pe(c,s.in_sitemap),in_nav:Pe(c,s.in_nav),status:Pe(c,s.status),rendered:Pe(c,s.rendered),word_count:Pe(c,s.word_count),notes:Pe(c,s.notes)})}break}return t}function Pe(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function kn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function La(e){let t=e.trim();return kn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function fo(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function mo(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as Oe}from"@clack/prompts";var l={info:e=>Oe.info(e),warn:e=>Oe.warn(e),error:e=>Oe.error(e),success:e=>Oe.success(e),step:e=>Oe.step(e),message:e=>Oe.message(e)};function k(e,t,n,r=n){e?e.stop(r):l[t](n)}var ho=[{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"}],ko="unknown",Ma=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Ba(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 Ma.has(t)?t:null}async function Je(e={}){let t=process.cwd();if($r(t)){let a=_(t),c=Ae(t);he(t),z(t,{skill_version:E}),ye(t);let u=wo(Nt(t,c.skillFile)),d=c.claudeSymlink?` (symlinked at ${Nt(t,c.claudeSymlink)})`:"",p=a?.skill_version&&a.skill_version!==E?`${a.skill_version} \u2192 ${E}`:E;l.success(`Refreshed the SEOAgent skill (${p}).`),l.info("Your `.seoagent/` knowledge was left untouched."),l.info(`Skill at ${u}${d}.`),l.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`);return}let n=!!e.yes||!process.stdin.isTTY;n||Na("SEOAgent \u2014 AI SEO Agent");let r=ro(t,a=>l.step(a)),o=()=>{if(r.evidence.length!==0){l.info("Inferred from your project:");for(let a of r.evidence)l.info(` \u2022 ${Ba(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()&&Lt(e.siteType)===null&&(l.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&Lt(process.env.SEOAGENT_SITE_TYPE)===null&&(l.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),o(),i||(l.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=ko),s||(s="unknown"),await yo(t,i,s);return}if(o(),!i){let a=await go({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});Te(a)&&(je("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await bn({message:"What kind of site is this?",options:[...ho]});Te(a)&&(je("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Ua({message:`Create .seoagent for ${i} (${s})?`});if(Te(a)&&(je("Cancelled"),process.exit(0)),a)break;let c=await bn({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((Te(c)||c==="abort")&&(je("Cancelled"),process.exit(0)),c==="domain"){let u=await go({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});Te(u)&&(je("Cancelled"),process.exit(0)),i=String(u)}else{let u=await bn({message:"What kind of site is this?",options:[...ho]});Te(u)&&(je("Cancelled"),process.exit(0)),s=u}}await yo(t,i,s)}async function yo(e,t,n){let r=Da();r.start("Setting up your SEO project");let o=Jr(e),i=ae(e),s={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:E,skill_version:E,install_id:cn(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{},...i.provider!=="none"?{image_provider:i.provider}:{}};xr(e),vr(e,s),ye(e),Yr(e,n),Or(e);let a=Ae(e),c=Nt(e,a.skillFile),u=wo(c),d=`${u}/references/audit-checks.md`,p=a.claudeSymlink?Nt(e,a.claudeSymlink):void 0;he(e);let g=t!==ko,m={pages:[],dynamicCount:0},$={wrote:!1,added:0,total:0,merged:!1};try{m=ce(e,g?t:null),$=jt(e,m.pages)}catch{}if(r.stop(g?`Created .seoagent/ project for ${s.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let x=o.evidence.map(F=>`${F.detail} (${F.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${x}`)}if(o.blog_path&&l.info(`Blog route: ${o.blog_path}`),i.provider!=="none"&&l.info(`Image generation: ${i.provider} (detected ${i.matched_key}) \u2014 articles can get AI hero images.`),m.pages.length>0){let x=$.merged?$.added>0?`Re-scanned your codebase: +${$.added} new page${$.added===1?"":"s"} merged into .seoagent/pages.md (${$.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${$.total} pages)`:`Found ${m.pages.length} page${m.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;l.info(x+(m.dynamicCount>0?` (plus ${m.dynamicCount} dynamic route template${m.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let S=g?s.domain:"your site",T=g?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${s.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."];Fa([g?`\u2713 SEOAgent installed for ${s.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:","",` ${c} \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):","",...T,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${S}`," (homepage + sitemap + robots.txt; the checks live in",` ${d} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${f("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${c} is picked up automatically.`,...p?[` Symlinked at ${p} \u2192 ${u} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
|
|
30
|
-
`))}import{existsSync as So}from"fs";import{intro as
|
|
31
|
-
`);if(!r){
|
|
32
|
-
${o}`);let s=await
|
|
29
|
+
`)}function La(e){let t=new Map,n;try{n=Oa(e,"utf-8")}catch{return t}let r=n.split(/\r?\n/);for(let o=0;o<r.length-1;o++){if(!kn(r[o])||!Na(r[o+1]))continue;let i=fo(r[o]).map(a=>a.toLowerCase()),s={url:i.findIndex(a=>a.includes("url")),in_sitemap:i.findIndex(a=>a.includes("sitemap")),in_nav:i.findIndex(a=>a.includes("nav")),status:i.findIndex(a=>a.includes("status")||a.includes("http")),rendered:i.findIndex(a=>a.includes("render")),word_count:i.findIndex(a=>a.includes("word")),notes:i.findIndex(a=>a.includes("note"))};if(s.url===-1)return t;for(let a=o+2;a<r.length&&kn(r[a]);a++){let c=fo(r[a]),u=(c[s.url]??"").trim();!u||u==="\u2014"||u==="-"||t.set(u,{url:u,in_sitemap:Pe(c,s.in_sitemap),in_nav:Pe(c,s.in_nav),status:Pe(c,s.status),rendered:Pe(c,s.rendered),word_count:Pe(c,s.word_count),notes:Pe(c,s.notes)})}break}return t}function Pe(e,t){let n=t>=0?(e[t]??"").trim():"";return n===""?"\u2014":n}function kn(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.length>1}function Na(e){let t=e.trim();return kn(t)&&/^\|(?:\s*:?-+:?\s*\|)+$/.test(t)}function fo(e){return e.trim().slice(1,-1).split("|").map(t=>t.trim())}function mo(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as Oe}from"@clack/prompts";var l={info:e=>Oe.info(e),warn:e=>Oe.warn(e),error:e=>Oe.error(e),success:e=>Oe.success(e),step:e=>Oe.step(e),message:e=>Oe.message(e)};function k(e,t,n,r=n){e?e.stop(r):l[t](n)}var ho=[{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"}],ko="unknown",Ba=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Wa(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 Ba.has(t)?t:null}async function Je(e={}){let t=process.cwd();if($r(t)){let a=_(t),c=Ae(t);he(t),z(t,{skill_version:E}),ye(t);let u=wo(Nt(t,c.skillFile)),d=c.claudeSymlink?` (symlinked at ${Nt(t,c.claudeSymlink)})`:"",p=a?.skill_version&&a.skill_version!==E?`${a.skill_version} \u2192 ${E}`:E;l.success(`Refreshed the SEOAgent skill (${p}).`),l.info("Your `.seoagent/` knowledge was left untouched."),l.info(`Skill at ${u}${d}.`),l.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`);return}let n=!!e.yes||!process.stdin.isTTY;n||Fa("SEOAgent \u2014 AI SEO Agent");let r=ro(t,a=>l.step(a)),o=()=>{if(r.evidence.length!==0){l.info("Inferred from your project:");for(let a of r.evidence)l.info(` \u2022 ${Wa(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()&&Lt(e.siteType)===null&&(l.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&Lt(process.env.SEOAGENT_SITE_TYPE)===null&&(l.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),o(),i||(l.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=ko),s||(s="unknown"),await yo(t,i,s);return}if(o(),!i){let a=await go({message:"Website domain",placeholder:"example.com",validate:c=>c.trim()?void 0:"Domain is required"});Te(a)&&(je("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await bn({message:"What kind of site is this?",options:[...ho]});Te(a)&&(je("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Ma({message:`Create .seoagent for ${i} (${s})?`});if(Te(a)&&(je("Cancelled"),process.exit(0)),a)break;let c=await bn({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((Te(c)||c==="abort")&&(je("Cancelled"),process.exit(0)),c==="domain"){let u=await go({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});Te(u)&&(je("Cancelled"),process.exit(0)),i=String(u)}else{let u=await bn({message:"What kind of site is this?",options:[...ho]});Te(u)&&(je("Cancelled"),process.exit(0)),s=u}}await yo(t,i,s)}async function yo(e,t,n){let r=Ua();r.start("Setting up your SEO project");let o=Jr(e),i=ae(e),s={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:E,skill_version:E,install_id:cn(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{},...i.provider!=="none"?{image_provider:i.provider}:{}};xr(e),vr(e,s),ye(e),Yr(e,n),Or(e);let a=Ae(e),c=Nt(e,a.skillFile),u=wo(c),d=`${u}/references/audit-checks.md`,p=a.claudeSymlink?Nt(e,a.claudeSymlink):void 0;he(e);let g=t!==ko,m={pages:[],dynamicCount:0},$={wrote:!1,added:0,total:0,merged:!1};try{m=ce(e,g?t:null),$=jt(e,m.pages)}catch{}if(r.stop(g?`Created .seoagent/ project for ${s.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let x=o.evidence.map(F=>`${F.detail} (${F.source})`).slice(0,2).join(", ");l.info(`CMS detected: ${o.cms} \u2014 ${x}`)}if(o.blog_path&&l.info(`Blog route: ${o.blog_path}`),i.provider!=="none"&&l.info(`Image generation: ${i.provider} (detected ${i.matched_key}) \u2014 articles can get AI hero images.`),m.pages.length>0){let x=$.merged?$.added>0?`Re-scanned your codebase: +${$.added} new page${$.added===1?"":"s"} merged into .seoagent/pages.md (${$.total} total)`:`Re-scanned your codebase: .seoagent/pages.md already current (${$.total} pages)`:`Found ${m.pages.length} page${m.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`;l.info(x+(m.dynamicCount>0?` (plus ${m.dynamicCount} dynamic route template${m.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""))}let S=g?s.domain:"your site",T=g?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${s.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."];Da([g?`\u2713 SEOAgent installed for ${s.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:","",` ${c} \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):","",...T,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${S}`," (homepage + sitemap + robots.txt; the checks live in",` ${d} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${f("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${c} is picked up automatically.`,...p?[` Symlinked at ${p} \u2192 ${u} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
|
|
30
|
+
`))}import{existsSync as So}from"fs";import{intro as Ka,outro as qa,confirm as Ha,isCancel as Ya,cancel as za}from"@clack/prompts";import{existsSync as Ft,rmSync as Ga}from"fs";import{join as Dt}from"path";function bo(e,t={}){let n=[],r=Dt(e,w);Ft(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=Dt(e,ge.CLAUDE);Ft(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=Dt(e,ge.AGENTS);return Ft(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),jr(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:Dt(e,".claude","settings.json"),kind:"hook"}),t.global&&Ft(M)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:M,kind:"global"}),n}function $o(e,t){for(let n of t)n.kind==="hook"?Lr(e):Ga(n.path,{recursive:!0,force:!0})}async function Xe(e={}){let t=process.cwd(),n=bo(t,{global:e.global});if(n.length===0){l.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&So(M)&&l.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){Ka("SEOAgent \u2014 uninstall"),l.message(`This will remove:
|
|
32
|
+
${o}`);let s=await Ha({message:"Remove these and start fresh?"});if(Ya(s)||!s){za("Cancelled \u2014 nothing was removed.");return}}$o(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
|
|
33
33
|
`);r?l.success(`Removed:
|
|
34
|
-
${i}`):
|
|
35
|
-
${i}`),!e.global&&So(M)&&l.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),l.info(`Re-install any time with \`${f("init")}\`.`)}import v from"picocolors";import{existsSync as xo,mkdirSync as vo,readFileSync as
|
|
36
|
-
`,"utf-8");try{
|
|
37
|
-
`)}function cc(e,t){if(!t)return le.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Ro(t),r=e-5-n;return r<1?le.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${le.dim("\u250C\u2500 ")}${t}${le.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function lc(e,t){let n=Ro(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${le.dim("\u2502")} ${r} ${le.dim("\u2502")}`}function Sn(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 Ze(){let e=Ao(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(uc(e))}function uc(e){if(!e)return"";let t=11,n=s=>v.dim(s.padEnd(t)),r=[];j()?(r.push({content:`${v.green("\u2713")} ${v.dim("Logged in")}`}),r.push({content:v.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${v.dim("\u25CB Not logged in")}`}),r.push({content:v.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${v.green(`last run ${Sn(e.audit.date??"")}`)} ${v.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${v.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${v.bold(v.cyan(String(e.strategy.clusterCount??0)))} ${v.dim("clusters")} \xB7 ${v.bold(v.cyan(String(e.strategy.articleCount??0)))} ${v.dim("ideas")}`:`${n("Strategy:")}${v.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${v.bold(v.cyan(String(e.briefs.count??0)))} ${v.dim("ready")}`:`${n("Briefs:")}${v.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${v.green("\u2713")} ${v.bold(v.cyan(String(e.content.count??0)))} ${v.dim("articles written")}`:`${n("Content:")}${v.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${v.green("updated")} ${v.dim(Sn(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${v.dim("not yet created")}`});let i=`${v.bold(v.cyan("SEOAgent"))} ${v.dim("\xB7")} ${v.bold(e.domain)}`;return I(r,{width:78,title:i})}import{exec as dc,spawn as Io}from"child_process";import{confirm as pc,isCancel as fc}from"@clack/prompts";import D from"picocolors";function Ne(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}var mc=`https://registry.npmjs.org/${te}/latest`,et=["free","starter","pro","scale","enterprise"],Ut={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function gc(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return et.includes(t)?t:null}function hc(e){let t=et.indexOf(e);return t===-1||t===et.length-1?null:et[t+1]}async function yc(e,t=fetch){if(!e)return null;try{let n=(e.api_base||A.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 wc(e){let t=[],r=s=>D.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${D.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${D.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of et){let a=Ut[s];s===e.current?t.push({content:`${D.bold(D.green("\u25CF"))} ${D.bold(D.green(a.padEnd(11)))} ${D.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${D.yellow("\u25C6")} ${D.bold(D.yellow(a.padEnd(11)))} ${D.yellow("next tier")}`}):t.push({content:D.dim(` ${a}`)})}let i=`${D.bold(D.cyan("SEOAgent Cloud"))} ${D.dim("\xB7")} ${D.dim("your plan")}`;return I(t,{width:55,title:i})}async function tt(){let e=j(),t=!!process.stdin.isTTY;if(e&&t){let n=await yc(e);if(n){let r=gc(n.plan),o=r?hc(r):null;if(r&&l.message(wc({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${Ut[r]} (highest tier).`);return}if(r&&o){let i=await pc({message:`Upgrade from ${Ut[r]} to ${Ut[o]}?`});if(fc(i)||!i){l.info("No changes.");return}}}}kc()}function kc(){let e=bc();l.info("Opening SEOAgent Cloud pricing..."),l.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;dc(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function bc(){let e=process.cwd(),t=_(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${A.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function nt(e={}){let t=E,n=await Sc();if(!n){l.warn("Couldn't reach the npm registry to check for a newer version."),l.message(`You're on ${t}. To force-update: npm install -g ${te}@latest`);return}if(Ne(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!on()){l.info(`A newer CLI is available: ${t} \u2192 ${n}.`),l.message("You're running via npx, which caches the package \u2014 an unpinned spec won't auto-upgrade."),l.message(`Run the latest now by pinning the tag: npx -y ${te}@latest <cmd>`),l.message(`Still on ${t} after that? Clear the npx cache: rm -rf ~/.npm/_npx`),l.message(`Or install globally once so \`seoagent <cmd>\` + \`update-cli\` work in place: npm install -g ${te}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${te}@latest`);return}if(l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await vc()){l.error(`Update failed. Try manually: npm install -g ${te}@latest (you may need sudo on Linux/macOS).`);return}if(l.success(`Updated to ${n}.`),e.projects===!1){l.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}l.info("Refreshing your other projects to the new version\u2026"),await $c()||l.info("Could not run the project sweep automatically \u2014 run `seoagent refresh --all` to update all projects now (otherwise each updates itself the next time you open it in Claude Code).")}function $c(){return new Promise(e=>{try{let t=Io("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function Sc(e=fetch){try{let t=await e(mc,{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 vc(){return new Promise(e=>{let t=Io("npm",["install","-g",`${te}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as xc}from"child_process";import{randomBytes as _c}from"crypto";import{isCancel as Cc,spinner as Ec,text as Ac}from"@clack/prompts";import ue from"picocolors";function Po(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 Rc=1500,Ic=300*1e3;function Pc(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;xc(t,()=>{})}function Oc(){return _c(16).toString("hex")}function Tc(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function Oo(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 jc(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 Po(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Lc(e){return new Promise(t=>setTimeout(t,e))}async function rt(e={}){let t=process.cwd(),n=_(t),r=(e.apiBase||A.BASE||qe).replace(/\/$/,"");if(j()){l.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 Ac({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(m){if(!String(m??"").trim())return"A site URL is required.";if(!Oo(String(m)))return"Please enter a valid domain like `example.com`."}});if(Cc(p)){l.warn("Login cancelled.");return}let g=Oo(String(p));if(g){o=g;try{z(t,{domain:g}),l.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=Oc(),s=Tc(r,i,o);l.message("Opening seoagent.com to connect this CLI to your account..."),l.info(`If the browser does not open, visit: ${s}`),Pc(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?Ec():null;c?.start(ue.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+Ic,d=!0;for(;Date.now()<u;){d||await Lc(Rc),d=!1;let p=await jc(r,i);if(p.status==="ready"){_o({user_token:p.user_token,website_token:p.website_token,api_base:r});let g=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",m=p.email&&p.domain?`Logged in as ${ue.bold(p.email)} (${ue.cyan(p.domain)}).`:p.email?`Logged in as ${ue.bold(p.email)}.`:"Logged in.";k(c,"success",g,ue.green(m)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){k(c,"warn",`Session expired. Run \`${f("login")}\` again.`,ue.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){k(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,ue.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}k(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,ue.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function ot(){Co()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as su}from"@clack/prompts";import de from"picocolors";import{existsSync as jn,mkdirSync as Al,readFileSync as ii,readdirSync as Rl,writeFileSync as Il}from"fs";import{createHash as Pl}from"crypto";import{join as Ln,relative as Ol,sep as Tl}from"path";import{existsSync as Nc,mkdirSync as Fc,readdirSync as To,readFileSync as jo,writeFileSync as Dc}from"fs";import{dirname as Uc,join as Fe,relative as Mc}from"path";var Se=e=>typeof e=="string"&&e?e:void 0;function vn(e,t){let n=Fe(e,t),r;try{r=To(n)}catch{return[]}let o=[];for(let i of r){if(!i.endsWith(".md")&&!i.endsWith(".mdx")||i.startsWith("_")||i.startsWith("."))continue;let s=Fe(n,i),a;try{a=se(jo(s,"utf-8")).data}catch{continue}let c=Se(a.slug)??i.replace(/\.mdx?$/,"");o.push({slug:c,title:Se(a.title)??c,draft:a.draft===!0,page_type:Se(a.page_type)??Se(a.type),path:Mc(e,s)})}return o}function xn(e){let t;try{t=To(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".md"))continue;let o=Fe(e,r),i;try{i=se(jo(o,"utf-8")).data}catch{continue}n.push({slug:Se(i.slug)??r.replace(/\.md$/,""),source:Se(i.source)??"external",repo_path:Se(i.repo_path)??null,file:o})}return n}function _n(e,t,n){let r=new Set(t.map(s=>s.slug)),o=e.filter(s=>!s.draft&&!r.has(s.slug)),i=t.filter(s=>s.source==="repo"&&s.repo_path!==null&&!n(s.repo_path));return{toTrack:o,stale:i,alreadyTracked:t.length-i.length}}function Cn(e){return t=>Nc(Fe(e,t))}function En(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Lo(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function it(e,t){if(t.url&&t.url.trim())return t.url.trim().replace(/\/+$/,"");if(!t.domain||t.domain==="unknown")return null;let n=t.domain.replace(/^https?:\/\//,"").replace(/\/$/,""),r=(t.blogPath||"").replace(/\/+$/,"");return`https://${n}${r}/${e}`}function st(e){let t=["---",`slug: ${e.slug}`,`title: ${JSON.stringify(e.title)}`];e.page_type&&t.push(`page_type: ${e.page_type}`),e.canonical&&t.push(`canonical: ${e.canonical}`),t.push(`status: ${e.status}`),t.push(`source: ${e.source}`),e.repo_path&&t.push(`repo_path: ${e.repo_path}`),e.primary_keyword&&t.push(`primary_keyword: ${JSON.stringify(e.primary_keyword)}`),t.push(`tracked_at: ${e.tracked_at}`),t.push("---");let n=e.repo_path?`rendered from \`${e.repo_path}\` (the source of truth for its body)`:"rendered from its source (repo or CMS)",r=e.canonical?`
|
|
34
|
+
${i}`):qa(`Removed:
|
|
35
|
+
${i}`),!e.global&&So(M)&&l.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),l.info(`Re-install any time with \`${f("init")}\`.`)}import v from"picocolors";import{existsSync as xo,mkdirSync as vo,readFileSync as Va,writeFileSync as Ja,chmodSync as Xa,unlinkSync as Qa}from"fs";import{dirname as Za}from"path";function j(){if(!xo(ie))return null;try{let e=JSON.parse(Va(ie,"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||qe}}catch{return null}}function _o(e){vo(M,{recursive:!0}),vo(Za(ie),{recursive:!0}),Ja(ie,JSON.stringify(e,null,2)+`
|
|
36
|
+
`,"utf-8");try{Xa(ie,384)}catch{}}function Co(){if(!xo(ie))return!1;try{return Qa(ie),!0}catch{return!1}}import{existsSync as Qe,readdirSync as $n,statSync as ec,readFileSync as Eo}from"fs";import{join as Le}from"path";function tc(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function nc(e){let t=Le(e,"audit","latest.md");if(!Qe(t))return null;let n=Ct(t);if(!n)return null;let r=Eo(t,"utf-8"),o=tc(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function rc(e){try{let n=Eo(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 oc(e){let t=Le(e,"strategy","clusters");if(!Qe(t))return null;let n=$n(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=rc(Le(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function ic(e){let t=Le(e,"briefs");if(!Qe(t))return null;let n=$n(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function sc(e){let t=Le(e,"content");if(!Qe(t))return null;let n=$n(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function ac(e){let t=Le(e,"roadmap.md");return Qe(t)?{exists:!0,updatedAt:ec(t).mtime.toISOString()}:null}function Ao(e){let t=_(e);if(!t)return null;let n=He(e);return{domain:t.domain,audit:nc(n),strategy:oc(n),briefs:ic(n),content:sc(n),roadmap:ac(n)}}import le from"picocolors";var cc=/\x1b\[[0-9;]*m/g;function Ro(e){return e.replace(cc,"").length}function I(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=lc(n,t.title),s=le.dim(`\u251C${o}\u2524`),a=le.dim(`\u2514${o}\u2518`),c=[i];for(let u of e){if("sep"in u){c.push(s);continue}c.push(uc(u.content,r))}return c.push(a),c.join(`
|
|
37
|
+
`)}function lc(e,t){if(!t)return le.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Ro(t),r=e-5-n;return r<1?le.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${le.dim("\u250C\u2500 ")}${t}${le.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function uc(e,t){let n=Ro(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${le.dim("\u2502")} ${r} ${le.dim("\u2502")}`}function Sn(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 Ze(){let e=Ao(process.cwd());if(!e){l.warn("No SEOAgent project found in this directory."),l.info(`Run \`${f("init")}\` to get started.`);return}l.message(dc(e))}function dc(e){if(!e)return"";let t=11,n=s=>v.dim(s.padEnd(t)),r=[];j()?(r.push({content:`${v.green("\u2713")} ${v.dim("Logged in")}`}),r.push({content:v.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${v.dim("\u25CB Not logged in")}`}),r.push({content:v.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${v.green(`last run ${Sn(e.audit.date??"")}`)} ${v.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${v.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${v.bold(v.cyan(String(e.strategy.clusterCount??0)))} ${v.dim("clusters")} \xB7 ${v.bold(v.cyan(String(e.strategy.articleCount??0)))} ${v.dim("ideas")}`:`${n("Strategy:")}${v.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${v.bold(v.cyan(String(e.briefs.count??0)))} ${v.dim("ready")}`:`${n("Briefs:")}${v.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${v.green("\u2713")} ${v.bold(v.cyan(String(e.content.count??0)))} ${v.dim("articles written")}`:`${n("Content:")}${v.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${v.green("updated")} ${v.dim(Sn(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${v.dim("not yet created")}`});let i=`${v.bold(v.cyan("SEOAgent"))} ${v.dim("\xB7")} ${v.bold(e.domain)}`;return I(r,{width:78,title:i})}import{exec as pc,spawn as Io}from"child_process";import{confirm as fc,isCancel as mc}from"@clack/prompts";import D from"picocolors";function Ne(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}var gc=`https://registry.npmjs.org/${te}/latest`,et=["free","starter","pro","scale","enterprise"],Ut={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function hc(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return et.includes(t)?t:null}function yc(e){let t=et.indexOf(e);return t===-1||t===et.length-1?null:et[t+1]}async function wc(e,t=fetch){if(!e)return null;try{let n=(e.api_base||A.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 kc(e){let t=[],r=s=>D.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${D.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${D.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of et){let a=Ut[s];s===e.current?t.push({content:`${D.bold(D.green("\u25CF"))} ${D.bold(D.green(a.padEnd(11)))} ${D.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${D.yellow("\u25C6")} ${D.bold(D.yellow(a.padEnd(11)))} ${D.yellow("next tier")}`}):t.push({content:D.dim(` ${a}`)})}let i=`${D.bold(D.cyan("SEOAgent Cloud"))} ${D.dim("\xB7")} ${D.dim("your plan")}`;return I(t,{width:55,title:i})}async function tt(){let e=j(),t=!!process.stdin.isTTY;if(e&&t){let n=await wc(e);if(n){let r=hc(n.plan),o=r?yc(r):null;if(r&&l.message(kc({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){l.success(`You're on ${Ut[r]} (highest tier).`);return}if(r&&o){let i=await fc({message:`Upgrade from ${Ut[r]} to ${Ut[o]}?`});if(mc(i)||!i){l.info("No changes.");return}}}}bc()}function bc(){let e=$c();l.info("Opening SEOAgent Cloud pricing..."),l.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;pc(t,n=>{n&&l.warn("Could not open browser. Visit the URL above to upgrade.")})}function $c(){let e=process.cwd(),t=_(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${A.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function nt(e={}){let t=E,n=await vc();if(!n){l.warn("Couldn't reach the npm registry to check for a newer version."),l.message(`You're on ${t}. To force-update: npm install -g ${te}@latest`);return}if(Ne(t,n)>=0){l.success(`You're on the latest CLI (${t}).`);return}if(!on()){l.info(`A newer CLI is available: ${t} \u2192 ${n}.`),l.message("You're running via npx, which caches the package \u2014 an unpinned spec won't auto-upgrade."),l.message(`Run the latest now by pinning the tag: npx -y ${te}@latest <cmd>`),l.message(`Still on ${t} after that? Clear the npx cache: rm -rf ~/.npm/_npx`),l.message(`Or install globally once so \`seoagent <cmd>\` + \`update-cli\` work in place: npm install -g ${te}@latest`);return}if(e.dryRun){l.info(`(dry-run) would run: npm install -g ${te}@latest`);return}if(l.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await xc()){l.error(`Update failed. Try manually: npm install -g ${te}@latest (you may need sudo on Linux/macOS).`);return}if(l.success(`Updated to ${n}.`),e.projects===!1){l.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}l.info("Refreshing your other projects to the new version\u2026"),await Sc()||l.info("Could not run the project sweep automatically \u2014 run `seoagent refresh --all` to update all projects now (otherwise each updates itself the next time you open it in Claude Code).")}function Sc(){return new Promise(e=>{try{let t=Io("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function vc(e=fetch){try{let t=await e(gc,{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 xc(){return new Promise(e=>{let t=Io("npm",["install","-g",`${te}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as _c}from"child_process";import{randomBytes as Cc}from"crypto";import{isCancel as Ec,spinner as Ac,text as Rc}from"@clack/prompts";import ue from"picocolors";function Po(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 Ic=1500,Pc=300*1e3;function Oc(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;_c(t,()=>{})}function Tc(){return Cc(16).toString("hex")}function jc(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function Oo(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 Lc(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 Po(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Nc(e){return new Promise(t=>setTimeout(t,e))}async function rt(e={}){let t=process.cwd(),n=_(t),r=(e.apiBase||A.BASE||qe).replace(/\/$/,"");if(j()){l.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 Rc({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(m){if(!String(m??"").trim())return"A site URL is required.";if(!Oo(String(m)))return"Please enter a valid domain like `example.com`."}});if(Ec(p)){l.warn("Login cancelled.");return}let g=Oo(String(p));if(g){o=g;try{z(t,{domain:g}),l.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=Tc(),s=jc(r,i,o);l.message("Opening seoagent.com to connect this CLI to your account..."),l.info(`If the browser does not open, visit: ${s}`),Oc(s),l.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let c=!!process.stdout.isTTY?Ac():null;c?.start(ue.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+Pc,d=!0;for(;Date.now()<u;){d||await Nc(Ic),d=!1;let p=await Lc(r,i);if(p.status==="ready"){_o({user_token:p.user_token,website_token:p.website_token,api_base:r});let g=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",m=p.email&&p.domain?`Logged in as ${ue.bold(p.email)} (${ue.cyan(p.domain)}).`:p.email?`Logged in as ${ue.bold(p.email)}.`:"Logged in.";k(c,"success",g,ue.green(m)),c&&l.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){k(c,"warn",`Session expired. Run \`${f("login")}\` again.`,ue.red("Session expired.")),c&&l.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){k(c,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,ue.red(`Login failed: ${p.message}.`)),c&&l.warn(`Run \`${f("login")}\` again.`);return}continue}}k(c,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,ue.yellow("Login timed out.")),c&&l.warn(`Run \`${f("login")}\` again to retry.`)}function ot(){Co()?l.success("Logged out."):l.info("You were not logged in.")}import{spinner as au}from"@clack/prompts";import de from"picocolors";import{existsSync as jn,mkdirSync as Rl,readFileSync as si,readdirSync as Il,writeFileSync as Pl}from"fs";import{createHash as Ol}from"crypto";import{join as Ln,relative as Tl,sep as jl}from"path";import{existsSync as Fc,mkdirSync as Dc,readdirSync as To,readFileSync as jo,writeFileSync as Uc}from"fs";import{dirname as Mc,join as Fe,relative as Bc}from"path";var Se=e=>typeof e=="string"&&e?e:void 0;function vn(e,t){let n=Fe(e,t),r;try{r=To(n)}catch{return[]}let o=[];for(let i of r){if(!i.endsWith(".md")&&!i.endsWith(".mdx")||i.startsWith("_")||i.startsWith("."))continue;let s=Fe(n,i),a;try{a=se(jo(s,"utf-8")).data}catch{continue}let c=Se(a.slug)??i.replace(/\.mdx?$/,"");o.push({slug:c,title:Se(a.title)??c,draft:a.draft===!0,page_type:Se(a.page_type)??Se(a.type),path:Bc(e,s)})}return o}function xn(e){let t;try{t=To(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".md"))continue;let o=Fe(e,r),i;try{i=se(jo(o,"utf-8")).data}catch{continue}n.push({slug:Se(i.slug)??r.replace(/\.md$/,""),source:Se(i.source)??"external",repo_path:Se(i.repo_path)??null,file:o})}return n}function _n(e,t,n){let r=new Set(t.map(s=>s.slug)),o=e.filter(s=>!s.draft&&!r.has(s.slug)),i=t.filter(s=>s.source==="repo"&&s.repo_path!==null&&!n(s.repo_path));return{toTrack:o,stale:i,alreadyTracked:t.length-i.length}}function Cn(e){return t=>Fc(Fe(e,t))}function En(e){return e.trim().replace(/^.*\/([^/]+)$/,"$1").replace(/\.[a-z0-9]+$/i,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Lo(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function it(e,t){if(t.url&&t.url.trim())return t.url.trim().replace(/\/+$/,"");if(!t.domain||t.domain==="unknown")return null;let n=t.domain.replace(/^https?:\/\//,"").replace(/\/$/,""),r=(t.blogPath||"").replace(/\/+$/,"");return`https://${n}${r}/${e}`}function st(e){let t=["---",`slug: ${e.slug}`,`title: ${JSON.stringify(e.title)}`];e.page_type&&t.push(`page_type: ${e.page_type}`),e.canonical&&t.push(`canonical: ${e.canonical}`),t.push(`status: ${e.status}`),t.push(`source: ${e.source}`),e.repo_path&&t.push(`repo_path: ${e.repo_path}`),e.primary_keyword&&t.push(`primary_keyword: ${JSON.stringify(e.primary_keyword)}`),t.push(`tracked_at: ${e.tracked_at}`),t.push("---");let n=e.repo_path?`rendered from \`${e.repo_path}\` (the source of truth for its body)`:"rendered from its source (repo or CMS)",r=e.canonical?`
|
|
38
38
|
|
|
39
39
|
Live: ${e.canonical}`:"",o=[`# ${e.title}`,"",`Tracked record \u2014 this article is **${e.status}** and ${n}.`,"This is a pointer so the cloud dashboard can track it without duplicating","the body. Edit the source file to change the article."+r,""].join(`
|
|
40
40
|
`);return`${t.join(`
|
|
41
41
|
`)}
|
|
42
42
|
|
|
43
43
|
${o}
|
|
44
|
-
`}function No(e,t){let n=Fe(e,w,"content"),r=xn(n),o=new Set;for(let c of r)c.source==="repo"&&c.repo_path&&o.add(
|
|
44
|
+
`}function No(e,t){let n=Fe(e,w,"content"),r=xn(n),o=new Set;for(let c of r)c.source==="repo"&&c.repo_path&&o.add(Mc(c.repo_path));if(o.size===0)return{tracked:[]};let i=[...o].flatMap(c=>vn(e,c)),s=_n(i,r,Cn(e));if(s.toTrack.length===0)return{tracked:[]};Dc(n,{recursive:!0});let a=[];for(let c of s.toTrack){let u=st({slug:c.slug,title:c.title,canonical:it(c.slug,{domain:t.domain,blogPath:t.blog_path}),status:"published",page_type:c.page_type,source:"repo",repo_path:c.path,tracked_at:new Date().toISOString()});Uc(Fe(n,`${c.slug}.md`),u,"utf-8"),a.push(c.slug)}return{tracked:a}}import{existsSync as Rn,mkdirSync as Wc,readdirSync as Fo,readFileSync as Gc,unlinkSync as Kc,writeFileSync as An}from"fs";import{join as Ue}from"path";import O from"picocolors";function ne(e){return Ue(e,w,"inbox")}function Do(e){return`${e.action_type}-${e.id}.md`}function qc(e,t){let n=0;if(!Rn(e))return 0;for(let r of Fo(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{Kc(Ue(e,r)),n++}catch{}}return n}function Hc(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`---
|
|
45
45
|
action_id: ${e.id}
|
|
46
46
|
action_type: ${e.action_type}
|
|
47
47
|
article_id: ${n}
|
|
@@ -84,8 +84,8 @@ positive, you disagree, etc.), close it out as failed with a reason:
|
|
|
84
84
|
\`\`\`bash
|
|
85
85
|
${f(`ack ${e.id}`)} --failed --reason "kept; performs well off-search"
|
|
86
86
|
\`\`\`
|
|
87
|
-
`}function
|
|
88
|
-
`)}}function
|
|
87
|
+
`}function Yc(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(`
|
|
88
|
+
`)}}function zc(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 Vc(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`---
|
|
89
89
|
action_id: ${e.id}
|
|
90
90
|
action_type: ${e.action_type}
|
|
91
91
|
issue: ${r}
|
|
@@ -108,8 +108,8 @@ ${s??e.description??"Apply the appropriate fix for this issue."}
|
|
|
108
108
|
|
|
109
109
|
## How to apply
|
|
110
110
|
|
|
111
|
-
1. ${
|
|
112
|
-
2. ${
|
|
111
|
+
1. ${zc(r,o,n)}
|
|
112
|
+
2. ${Yc(r)}
|
|
113
113
|
3. Show the user the diff before committing (confirm once per session, then proceed).
|
|
114
114
|
|
|
115
115
|
## How to close this out
|
|
@@ -126,13 +126,26 @@ next \`seoagent sync\`. If you disagree or it's a false positive, decline it:
|
|
|
126
126
|
\`\`\`bash
|
|
127
127
|
${f(`ack ${e.id}`)} --failed --reason "not applicable; ..."
|
|
128
128
|
\`\`\`
|
|
129
|
-
`}function
|
|
129
|
+
`}function Uo(e){return e.capture_screenshots!==!0?"":`
|
|
130
|
+
## Screenshots to capture
|
|
131
|
+
|
|
132
|
+
This is a **SaaS / product site**, so this page should include **real product
|
|
133
|
+
screenshots** \u2014 the highest-converting visual on a SaaS landing page or how-to.
|
|
134
|
+
Follow \`references/screenshots.md\`: scan the hero + feature/how-to sections for
|
|
135
|
+
spots where a UI shot would help and is missing, then capture those screens
|
|
136
|
+
**from the product's own code in this repo** (your screenshot tool + the
|
|
137
|
+
project's dev server \u2014 no Playwright/Puppeteer dependency, no paid API), save
|
|
138
|
+
them under \`public/screenshots/\`, and reference them with descriptive alt text.
|
|
139
|
+
If you can't capture (no dev server / no screenshot tool / no real UI), leave a
|
|
140
|
+
\`<!-- SCREENSHOT-TODO -->\` marker + an AI image prompt so publishing still works.
|
|
141
|
+
`}function Jc(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",c=t.capture_screenshots===!0;return`---
|
|
130
142
|
action_id: ${e.id}
|
|
131
143
|
action_type: ${e.action_type}
|
|
132
144
|
brief_slug: ${n??""}
|
|
133
145
|
primary_keyword: ${r??""}
|
|
134
146
|
cluster: ${o??""}
|
|
135
147
|
priority: ${a}
|
|
148
|
+
capture_screenshots: ${c}
|
|
136
149
|
created_at: ${e.created_at}
|
|
137
150
|
---
|
|
138
151
|
|
|
@@ -150,7 +163,7 @@ is auto-generated.
|
|
|
150
163
|
- **Role**: ${i??"(none)"}
|
|
151
164
|
- **Search intent**: ${s??"(none)"}
|
|
152
165
|
- **Priority**: ${a}
|
|
153
|
-
|
|
166
|
+
${Uo(t)}
|
|
154
167
|
## How to write it
|
|
155
168
|
|
|
156
169
|
1. Read the full brief \u2014 it's synced under \`.seoagent/\` (look for a briefs file
|
|
@@ -175,7 +188,7 @@ If you decide not to write it (off-strategy, duplicate, etc.), decline it:
|
|
|
175
188
|
\`\`\`bash
|
|
176
189
|
${f(`ack ${e.id}`)} --failed --reason "skipped; ..."
|
|
177
190
|
\`\`\`
|
|
178
|
-
`}function
|
|
191
|
+
`}function Xc(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(`
|
|
179
192
|
`):"- (no metrics)";return`---
|
|
180
193
|
action_id: ${e.id}
|
|
181
194
|
action_type: ${e.action_type}
|
|
@@ -222,7 +235,7 @@ If you disagree (page is fine as-is, intentionally short, etc.), decline it:
|
|
|
222
235
|
\`\`\`bash
|
|
223
236
|
${f(`ack ${e.id}`)} --failed --reason "kept as-is; ..."
|
|
224
237
|
\`\`\`
|
|
225
|
-
`}function
|
|
238
|
+
`}function Qc(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?`\`\`\`
|
|
226
239
|
${o.join(`
|
|
227
240
|
`)}
|
|
228
241
|
\`\`\`${i?`
|
|
@@ -268,7 +281,7 @@ SEOAgent re-submits the sitemap to GSC on its schedule. If a sitemap already exi
|
|
|
268
281
|
\`\`\`bash
|
|
269
282
|
${f(`ack ${e.id}`)} --failed --reason "sitemap already served at /sitemap.xml"
|
|
270
283
|
\`\`\`
|
|
271
|
-
`}function
|
|
284
|
+
`}function Zc(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=t.capture_screenshots===!0,c=r==="competitor_gap"?"competitor gap (a rival ranks top-10 here, you don't)":"easy win (low difficulty, real volume)";return`---
|
|
272
285
|
action_id: ${e.id}
|
|
273
286
|
action_type: ${e.action_type}
|
|
274
287
|
keyword: ${n??""}
|
|
@@ -276,13 +289,14 @@ opportunity: ${r}
|
|
|
276
289
|
volume: ${o??""}
|
|
277
290
|
difficulty: ${i??""}
|
|
278
291
|
intent: ${s??""}
|
|
292
|
+
capture_screenshots: ${a}
|
|
279
293
|
created_at: ${e.created_at}
|
|
280
294
|
---
|
|
281
295
|
|
|
282
296
|
# New landing page \u2014 \`${n??"(unknown)"}\`
|
|
283
297
|
|
|
284
298
|
SEOAgent's keyword engine flagged \`${n??"(unknown)"}\` as an
|
|
285
|
-
**${
|
|
299
|
+
**${c}**. There's no page covering this keyword yet \u2014 write a
|
|
286
300
|
dedicated landing page so the site can rank for it. The cloud has queued this
|
|
287
301
|
for **you** (or Claude Code reading this file) \u2014 nothing is auto-generated.
|
|
288
302
|
|
|
@@ -295,7 +309,7 @@ for **you** (or Claude Code reading this file) \u2014 nothing is auto-generated.
|
|
|
295
309
|
- **Search intent**: ${s??"(unknown)"}
|
|
296
310
|
|
|
297
311
|
${e.description??""}
|
|
298
|
-
|
|
312
|
+
${Uo(t)}
|
|
299
313
|
## How to write it
|
|
300
314
|
|
|
301
315
|
1. Decide what *kind* of page this should be \u2014 a guide, comparison, listicle,
|
|
@@ -326,7 +340,7 @@ decline it:
|
|
|
326
340
|
\`\`\`bash
|
|
327
341
|
${f(`ack ${e.id}`)} --failed --reason "skipped; ..."
|
|
328
342
|
\`\`\`
|
|
329
|
-
`}function
|
|
343
|
+
`}function el(e){switch(e.action_type){case"cli_prune_pending":return Hc(e);case"cli_technical_fix":return Vc(e);case"cli_new_content":return Jc(e);case"cli_content_update":return Xc(e);case"cli_sitemap_update":return Qc(e);case"cli_new_landing_page":return Zc(e);default:return null}}function tl(e){if(e.length===0)return`# SEOAgent Inbox
|
|
330
344
|
|
|
331
345
|
No pending actions. Run \`seoagent sync\` later to check for new ones.
|
|
332
346
|
`;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${Do(n)}\``);return`# SEOAgent Inbox
|
|
@@ -341,7 +355,7 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
|
|
|
341
355
|
|
|
342
356
|
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
343
357
|
skill knows what to do.
|
|
344
|
-
`}function ve(e){let t=ne(e);if(!Rn(t))return[];let n=[];for(let r of Fo(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",c=null,u=null,d=null,p=null,g=null,m=null;try{let $=
|
|
358
|
+
`}function ve(e){let t=ne(e);if(!Rn(t))return[];let n=[];for(let r of Fo(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",c=null,u=null,d=null,p=null,g=null,m=null;try{let $=Gc(Ue(t,r),"utf-8"),S=$.match(/^---\n([\s\S]*?)\n---/);if(S){let F=S[1];c=De(F,"severity"),u=De(F,"issue"),d=De(F,"page_url");let ee=De(F,"priority");(ee==="high"||ee==="medium"||ee==="low")&&(p=ee),g=De(F,"impact_estimate"),m=De(F,"effort_estimate")}let x=$.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);x&&(a=x[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:c,issue:u,page_url:d,priority:p,impact_estimate:g,effort_estimate:m})}return n.sort((r,o)=>r.id-o.id)}function Me(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=nl[e.severity??""]??O.dim,r=e.severity??"unknown",o=[O.dim("\u25B8"),O.bold(`id ${e.id}`),O.dim("\xB7"),O.cyan(t),n(r)];if(e.priority){let i=rl[e.priority];o.push(O.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(O.dim("\xB7"),O.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(O.dim("\xB7"),O.dim(`\u23F1 ${e.effort_estimate}`)),o.push(O.dim("\u2014"),e.title),o.join(" ")}var nl={critical:e=>O.red(O.bold(e)),high:e=>O.red(e),medium:e=>O.yellow(e),low:e=>O.dim(e)},rl={high:e=>O.red(O.bold(e)),medium:e=>O.yellow(e),low:e=>O.dim(e)};function De(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 Mt(e){let t=ne(e);if(!Rn(t))return;let n=ve(e),r=n.length===0?`# SEOAgent Inbox
|
|
345
359
|
|
|
346
360
|
No pending actions. Run \`seoagent sync\` later to check for new ones.
|
|
347
361
|
`:`# SEOAgent Inbox
|
|
@@ -356,23 +370,23 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
|
|
|
356
370
|
|
|
357
371
|
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
358
372
|
skill knows what to do.
|
|
359
|
-
`;An(Ue(t,"README.md"),r,"utf-8")}function
|
|
360
|
-
`,"utf-8")}catch{}return c}import{existsSync as
|
|
361
|
-
`,"utf-8")}function
|
|
362
|
-
`,"utf-8")}catch{}}async function
|
|
373
|
+
`;An(Ue(t,"README.md"),r,"utf-8")}function Mo(e,t){let n=ne(e);Wc(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=qc(n,r),i=0;for(let s of t){let a=el(s);a!==null&&(An(Ue(n,Do(s)),a,"utf-8"),i++)}return An(Ue(n,"README.md"),tl(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as sl}from"crypto";import{existsSync as Go,mkdirSync as al,readFileSync as cl,statSync as Ko,writeFileSync as Wo,rmSync as ll}from"fs";import{dirname as ul,join as In,sep as dl}from"path";function ol(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var il=[{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 Bo(e,t){let n=ol(e);for(let{cls:r,test:o}of il)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function pl(e){return"sha256:"+sl("sha256").update(e).digest("hex")}function fl(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 ml(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:Bo(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 qo(e){let t=await Yo({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 Ho(e,t){return In(e,t.split("/").join(dl))}function gl(e,t,n){let r={};for(let o of t){let i=Ho(e,o);if(!Go(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=Ko(i),a=n[o],c=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:pl(cl(i,"utf-8")),locallyEdited:c}}return r}async function Yo(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 zo(e){let t=In(e.projectDir,w),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!Go(t))return{...n,ok:!0};let r=await Yo({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=gl(t,i,e.stateFiles),a=fl(o,s,{force:e.force}),c={...n,cursor:o.now};for(let d of a){let p=Ho(t,d.path);try{switch(d.kind){case"skip":c.skipped++;break;case"write":case"overwrite":{al(ul(p),{recursive:!0}),Wo(p,d.body??"","utf-8");let g=Ko(p);e.stateFiles[d.path]={mtime:g.mtimeMs,size:g.size},d.kind==="write"?c.written++:c.overwritten++,d.note&&c.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":ll(p,{force:!0}),delete e.stateFiles[d.path],c.deleted++;break;case"delete-skipped":c.conflicts++,c.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(g){c.ok=!1,c.error=`${d.path}: ${g.message}`}}(c.conflicts>0||!c.ok)&&(c.cursor=e.since);let u=ml(a,o,c.cursor,new Date().toISOString());if(u)try{Wo(In(t,St),JSON.stringify(u,null,2)+`
|
|
374
|
+
`,"utf-8")}catch{}return c}import{existsSync as Jo,mkdirSync as Xo,readFileSync as hl,writeFileSync as Pn}from"fs";import{dirname as Qo,join as yl}from"path";var On=1,Vo=500;function Tn(e){return yl(e,w,pr)}function Bt(e){let t=Tn(e);if(!Jo(t))return[];try{let n=hl(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==On||!Array.isArray(o.entries)?[]:o.entries.filter(wl)}catch{return[]}}function Zo(e,t){let n=Tn(e),o=Bt(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>Vo?o.slice(-Vo):o,s={version:On,entries:i};try{Xo(Qo(n),{recursive:!0}),Pn(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function ei(e,t){if(t.length===0)return;let n=Tn(e),r=Bt(e).filter(i=>!t.includes(i.action_id)),o={version:On,entries:r};try{if(r.length===0&&Jo(n)){Pn(n,JSON.stringify(o,null,2),"utf-8");return}Xo(Qo(n),{recursive:!0}),Pn(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function wl(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 ti,readFileSync as kl,unlinkSync as bl,writeFileSync as $l,openSync as Sl,closeSync as vl,mkdirSync as xl}from"fs";import{dirname as _l,join as Cl}from"path";var El=6e4;function ni(e){return Cl(e,w,fr)}function ri(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??El,i=ni(e);if(!ti(i))return Wt(i,r,n());let s=ii(i);return!s||n()-s.started_at>o||!Al(s.pid)?Wt(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function oi(e,t={}){let n=t.pid??process.pid,r=ni(e);if(!ti(r))return;let o=ii(r);if(!(o&&o.pid!==n))try{bl(r)}catch{}}function Wt(e,t,n){let r={pid:t,started_at:n};try{xl(_l(e),{recursive:!0});let o=Sl(e,"w");try{$l(o,JSON.stringify(r))}finally{vl(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function ii(e){try{let t=kl(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 Al(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var Ll=new Set([".md"]),Nl=new Set(["inbox"]);function Fl(e){let t=[];function n(r,o){if(jn(r))for(let i of Il(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Nl.has(i.name))continue;let s=Ln(r,i.name);if(i.isDirectory())n(s,o?`${o}/${i.name}`:i.name);else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a);Ll.has(c)&&t.push(s)}}}return n(e,""),t}function ai(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Ln(rn,`${t}.json`)}function Dl(e){return Ol("sha256").update(e,"utf-8").digest("hex")}function Ul(e){let t=ai(e);if(!jn(t))return{files:{},last_synced_at:null};try{return JSON.parse(si(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Ml(e,t){Rl(rn,{recursive:!0}),Pl(ai(e),JSON.stringify(t,null,2)+`
|
|
375
|
+
`,"utf-8")}function Bl(e,t){return Tl(e,t).split(jl).join("/")}async function Wl(e,t){try{let n=await B(`${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 Gl(e,t,n){try{let r=await B(`${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 ci(e,t={}){let n=j();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=_(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=Ln(e,w);if(!jn(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!ri(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await Kl(e,t,n,r,o)}finally{oi(e)}}async function Kl(e,t,n,r,o){let i=Ul(r.domain);try{No(e,r)}catch{}let s=Fl(o),a=n.api_base||A.BASE,c=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,p=[],g=0,m=await ql(e,a,c);if(!t.pullOnly)for(let U of s){let Ke=Bl(o,U);if(t.pathFilter&&!Ke.endsWith(t.pathFilter))continue;let ar=si(U,"utf-8"),cr=Dl(ar),lr=i.files[Ke];if(!(!lr||lr.hash!==cr)&&!t.force)continue;g++;let nn=await Gl(a,{path:Ke,contents:ar,domain:r.domain},c);nn.ok?(i.files[Ke]={hash:cr},u++):(d++,p.push(`${Ke}: ${nn.status} ${nn.error??""}`.trim()))}let $=await Wl(a,c),S=0,T=0;if($.ok){let U=Mo(e,$.actions);S=U.wrote,T=U.removed}else $.error&&p.push(`pull actions: ${$.error}`);let x,F=!1,ee=i.last_synced_at;if(!t.pushOnly){let U=await zo({projectDir:e,apiBase:a,authHeader:c,since:i.last_synced_at,stateFiles:i.files,force:t.force});U.ok?ee=U.cursor:(F=!0,U.error&&p.push(`pull: ${U.error}`)),x={written:U.written,overwritten:U.overwritten,skipped:U.skipped,conflicts:U.conflicts,deleted:U.deleted,warnings:U.warnings}}let q=!!x&&x.written+x.overwritten+x.deleted+x.conflicts>0;if(i.last_synced_at=ee,Ml(r.domain,i),g===0&&S===0&&T===0&&!q&&m.flushed===0&&m.dropped===0&&!F&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:p,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:x};let kt=d===0&&!F;return{ok:kt,reason:kt?void 0:"error",synced:u,failed:d,errors:p,actionsPulled:S,actionsRemoved:T,acksFlushed:m.flushed,acksDropped:m.dropped,pull:x}}async function ql(e,t,n){let r=Bt(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let c=await Hl(a,t,n);c==="flushed"?(o++,s.push(a.action_id)):c==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&ei(e,s),{flushed:o,dropped:i}}async function Hl(e,t,n){try{let r=await B(`${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"}}function li(e){let t;try{t=_(e)}catch{return{refreshed:!1,reason:"error"}}if(!t)return{refreshed:!1,reason:"no-project"};let n=t.skill_version||t.seoagent_version||"0.0.0";if(Ne(E,n)<=0){if(!t.skill_version)try{z(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return Ae(e),z(e,{skill_version:E}),{refreshed:!0,from:n,to:E,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function Nn(e){let t;try{t=_(e)}catch{return{refreshed:!1,from:null,to:E,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:E,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return Ae(e),z(e,{skill_version:E}),{refreshed:!0,from:n,to:E,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:E,reason:"error"}}}import{existsSync as Yl,mkdirSync as zl,readFileSync as Vl,writeFileSync as Jl}from"fs";var Xl="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Ql=1440*60*1e3,Zl=720*60*1e3,eu=2e3;function tu(e,t,n=Ql){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function nu(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??Zl;if(!n||Ne(n,t)<=0)return null;if(r.notifiedVersion===n&&r.notifiedAt){let s=Date.parse(r.notifiedAt);if(!Number.isNaN(s)&&o.getTime()-s<i)return null}return`\u2191 SEOAgent ${n} is available (you have ${t}). Ask me to run \`seoagent update-cli\`, or run it yourself, to upgrade the CLI + all your projects.`}async function ru(e){let t=e.readCache();if(tu(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=nu({current:e.current,latest:t.latest,cache:t,now:e.now,notifyIntervalMs:e.notifyIntervalMs});return n&&t.latest&&e.writeCache({...t,notifiedVersion:t.latest,notifiedAt:e.now.toISOString()}),n}function ou(){try{return Yl(vt)?JSON.parse(Vl(vt,"utf-8")):{}}catch{return{}}}function iu(e){try{zl(M,{recursive:!0}),Jl(vt,JSON.stringify(e,null,2)+`
|
|
376
|
+
`,"utf-8")}catch{}}async function su(){try{let e=await fetch(Xl,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(eu)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function ui(e){try{return await ru({current:e,now:new Date,fetchLatest:su,readCache:ou,writeCache:iu})}catch{return null}}async function K(e={}){let t=li(process.cwd());if(t.refreshed){try{he(process.cwd())}catch{}e.silent||l.info(de.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}ye(process.cwd());let n=await ui(E);n&&l.message(de.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?au():null;i?.start(`${o} ${de.dim(".seoagent/")} with your dashboard\u2026`);let s=await ci(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){s.ok||(process.exitCode=0);return}if(s.reason==="no-auth"){k(i,"info",`Not logged in. Run \`${f("login")}\` to enable cloud sync.`,de.dim("Not logged in \u2014 cloud sync skipped.")),i&&l.info(`Run \`${f("login")}\` to enable cloud sync.`);return}if(s.reason==="no-project"){k(i,"info",`No SEOAgent project here. Run \`${f("init")}\` first.`,de.dim("No SEOAgent project \u2014 sync skipped.")),i&&l.info(`Run \`${f("init")}\` first.`);return}if(s.reason==="no-changes"){k(i,"info","Already in sync.",de.green("Already in sync."));return}if(s.reason==="busy"){k(i,"info","Another sync is in progress \u2014 skipping this run.",de.dim("Another sync is in progress \u2014 skipping this run."));return}let a=cu(s);k(i,"success",a??"Sync complete.",de.green(a??"Sync complete.")),s.synced>0&&l.success(`Synced ${s.synced} file${s.synced===1?"":"s"} to your dashboard.`);let c=s.pull;if(c){let u=c.written+c.overwritten;u>0&&l.success(`Pulled ${u} file${u===1?"":"s"} from the cloud`+(c.overwritten>0?` (${c.overwritten} updated)`:"")),c.deleted>0&&l.info(`Removed ${c.deleted} file${c.deleted===1?"":"s"} deleted in the cloud.`),c.conflicts>0&&l.warn(`${c.conflicts} conflict${c.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let d of c.warnings.slice(0,5))l.info(` \u2022 ${d}`)}if(s.acksFlushed&&s.acksFlushed>0&&l.success(`Flushed ${s.acksFlushed} offline ack${s.acksFlushed===1?"":"s"} from the queue.`),s.acksDropped&&s.acksDropped>0&&l.info(`Dropped ${s.acksDropped} stale ack${s.acksDropped===1?"":"s"} (already settled server-side).`),s.actionsPulled&&s.actionsPulled>0&&(l.success(`Pulled ${s.actionsPulled} pending action${s.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||l.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),s.actionsRemoved&&s.actionsRemoved>0&&l.info(`Cleaned up ${s.actionsRemoved} stale inbox file${s.actionsRemoved===1?"":"s"}.`),s.failed>0){l.warn(`${s.failed} file${s.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let u of s.errors.slice(0,3))l.info(` \u2022 ${u}`)}}function cu(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 L(e){let t=_(e);return t||(l.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function xe(e={}){if(e.print){let t=j();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!L(process.cwd()))return;let n=t.api_base||A.BASE,r=await qo({apiBase:n,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!r.ok){l.warn(r.error),process.exitCode=1;return}process.stdout.write(r.body),r.body.endsWith(`
|
|
363
377
|
`)||process.stdout.write(`
|
|
364
|
-
`);return}await K({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as
|
|
365
|
-
`);return}if(n.length===0){l.info(Gt.dim("No pending actions.")),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued, or \`${f("autopilot status")}\` to check whether autopilot is on.`);return}l.message(`${Gt.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(Me(r));l.message(""),l.message(`Apply one: ${Gt.bold(f("ack <id>"))} \xB7 Interactive picker: ${Gt.bold(f("ack"))} (no id)`)}import{readFileSync as
|
|
366
|
-
`+h.dim(" "+S.summary):"";l.message(` ${h.green("\u2713")} id ${d} ${h.dim("\u2014 applied in "+T)}${x}`)}catch(x){l.warn(` Applied but ack failed: ${x.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(S.kind==="declined")try{await pe(String(d),{silent:!0,failed:!0,reason:S.reason}),s++,l.message(""),l.message(` ${h.yellow("\u2298")} id ${d} ${h.dim("\u2014 declined: "+V(S.reason,100))}`)}catch(x){l.warn(` Could not ack decline: ${x.message}. Run \`seoagent ack ${d} --failed --reason "${S.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${h.red("\u2717")} id ${d} ${h.dim("\u2014 agent did not converge after "+T)}`)}
|
|
367
|
-
${h.dim("elapsed: "+i)}`,h.bold("Done"))}function
|
|
368
|
-
`);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
|
|
369
|
-
`),!(c.subtype==="success"&&!c.is_error))return{kind:"failed"};let d=
|
|
370
|
-
`),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function
|
|
378
|
+
`);return}await K({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as lu,readdirSync as uu,unlinkSync as du}from"fs";import{join as di}from"path";import{isCancel as pu,select as fu}from"@clack/prompts";async function pe(e,t={}){let n=null;if(e){let u=Number.parseInt(e,10);if(Number.isNaN(u)||u<=0){l.error(`Invalid action id: "${e}"`),process.exitCode=1;return}n=u}else if(n=await mu(),n===null)return;let r=n,o=j();if(!o){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!L(process.cwd()))return;let i=o.api_base||A.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",c;try{c=await B(`${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{Zo(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),Fn(r),Mt(process.cwd()),t.silent||l.warn(`Network unavailable \u2014 ack queued locally. Run \`${f("sync")}\` when you're back online; it'll flush automatically.`);return}if(!c.ok){let u=await c.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(c.status===409&&d?.code==="already_acked"){Fn(r),Mt(process.cwd());let $=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||l.success(`Action ${r} was already ${$}.`);return}let p=typeof d?.code=="string"?d.code:null,g=typeof d?.error=="string"?d.error:u,m=p?`, code: ${p}`:"";l.error(`Server rejected ack (${c.status}${m}): ${g.slice(0,200)}`),process.exitCode=1;return}Fn(r),Mt(process.cwd()),!t.silent&&(t.failed?l.success(`Action ${r} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):l.success(`Action ${r} marked completed.`),l.info(` inbox location: ${di(w,"inbox")}`))}function Fn(e){let t=ne(process.cwd());if(lu(t)){for(let n of uu(t))if(n.endsWith(`-${e}.md`))try{du(di(t,n))}catch{}}}async function mu(){let e=process.cwd(),t=ve(e);if(t.length===0)return l.info("No pending actions in .seoagent/inbox/."),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued.`),null;if(!process.stdout.isTTY)return l.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 fu({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Me(r)}))});return pu(n)?(l.info("Cancelled \u2014 no action closed out."),null):n}import Gt from"picocolors";async function Dn(e={}){let t=process.cwd();if(!e.json&&!L(t))return;let n=ve(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:ne(t),actions:n})+`
|
|
379
|
+
`);return}if(n.length===0){l.info(Gt.dim("No pending actions.")),l.message(`Run \`${f("sync")}\` to pull anything autopilot has queued, or \`${f("autopilot status")}\` to check whether autopilot is on.`);return}l.message(`${Gt.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),l.message("");for(let r of n)l.message(Me(r));l.message(""),l.message(`Apply one: ${Gt.bold(f("ack <id>"))} \xB7 Interactive picker: ${Gt.bold(f("ack"))} (no id)`)}import{readFileSync as xu}from"fs";import{join as _u,relative as Cu}from"path";import{confirm as hi,isCancel as qt,multiselect as Eu,note as ki,select as Au}from"@clack/prompts";import h from"picocolors";import{query as Ru}from"@anthropic-ai/claude-agent-sdk";import{existsSync as gu,readdirSync as hu}from"fs";import{homedir as yu}from"os";import{join as wu}from"path";import{execSync as Un}from"child_process";function at(){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":ku()?bu()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function ku(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return Un(e,{stdio:"ignore"}),!0}catch{return!1}}function bu(){let e=wu(yu(),".claude");if(!gu(e))return!1;try{return hu(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function pi(){try{return Un("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function fi(){try{return Un("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var re={"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 gi}from"marked";import{markedTerminal as $u}from"marked-terminal";import Mn from"picocolors";var mi=!1;function Su(){mi||(gi.use($u({reflowText:!1,width:100})),mi=!0)}function Kt(e){if(!e)return e;Su();try{let t=gi.parse(e);return typeof t=="string"?vu(t):e}catch{return e}}function vu(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>Mn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>Mn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+Mn.italic(r))}async function Wn(e={}){let t=process.cwd();if(!L(t))return;if(!process.stdout.isTTY&&!e.yes){l.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 Lu(e.yes)){process.exitCode=1;return}if(e.yes)await K({embedded:!0});else{let u=await Au({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(qt(u)){l.info("Cancelled.");return}u==="sync"?await K({embedded:!0}):u==="pull"&&await xe({embedded:!0})}let r=ve(t);if(r.length===0){l.info(h.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),l.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(m=>m.priority!==null),d=u?r.filter(m=>m.priority==="high").map(m=>m.id):r.map(m=>m.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)",g=await Eu({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(m=>({value:m.id,label:Me(m)})),initialValues:d,required:!1});if(qt(g)){l.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(g)||g.length===0){l.info("No actions selected. Nothing to do.");return}o=g}let i=0,s=0,a=0,c=Date.now();for(let u=0;u<o.length;u++){let d=o[u],p=r.find(x=>x.id===d);if(!p)continue;Iu({index:u+1,total:o.length,entry:p});let g=_u(ne(t),p.filename),m;try{m=xu(g,"utf-8")}catch(x){l.error(` Could not read ${p.filename}: ${x.message}`),a++;continue}let $=Date.now(),S=await ju({cwd:t,entry:p,actionContent:m,model:e.model}),T=yi(Date.now()-$);if(S.kind==="applied")try{await pe(String(d),{silent:!0}),i++,l.message("");let x=S.summary?`
|
|
380
|
+
`+h.dim(" "+S.summary):"";l.message(` ${h.green("\u2713")} id ${d} ${h.dim("\u2014 applied in "+T)}${x}`)}catch(x){l.warn(` Applied but ack failed: ${x.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(S.kind==="declined")try{await pe(String(d),{silent:!0,failed:!0,reason:S.reason}),s++,l.message(""),l.message(` ${h.yellow("\u2298")} id ${d} ${h.dim("\u2014 declined: "+V(S.reason,100))}`)}catch(x){l.warn(` Could not ack decline: ${x.message}. Run \`seoagent ack ${d} --failed --reason "${S.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,l.message(""),l.message(` ${h.red("\u2717")} id ${d} ${h.dim("\u2014 agent did not converge after "+T)}`)}Ou({applied:i,declined:s,failed:a,total:o.length,elapsed:yi(Date.now()-c)})}function Iu(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=Pu[i]??h.dim,a=[h.bold(`[${t}/${n}]`),h.dim("\xB7"),h.bold(`id ${r.id}`),h.dim("\xB7"),h.cyan(o),s(i)].join(" ");ki(r.title,a)}var Pu={critical:e=>h.red(h.bold(e)),high:h.red,medium:h.yellow,low:h.dim};function Ou(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?h.green(`\u2713 ${t}/${o} applied`):h.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=h.red(`\u2717 0/${o} applied`);else{let c=[`${t}/${o} applied`];n>0&&c.push(`${n} declined`),r>0&&c.push(`${r} failed`),a=h.yellow(`\u25D0 ${c.join(" \xB7 ")}`)}ki(`${a}
|
|
381
|
+
${h.dim("elapsed: "+i)}`,h.bold("Done"))}function yi(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 Tu(e){if(typeof e!="string"||!e)return null;let t=e.split(`
|
|
382
|
+
`);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 ju(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=qu(n,r);try{let s=Ru({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...o?{model:o}:{}}}),a={toolUseById:new Map};for await(let c of s)if(c.type==="assistant"){let u=c.message.content;if(Array.isArray(u))for(let d of u)Fu(d,a)}else if(c.type==="user"){let u=c.message.content;if(Array.isArray(u))for(let d of u)Mu(d,a)}else if(c.type==="result"){if(process.stdout.write(`
|
|
383
|
+
`),!(c.subtype==="success"&&!c.is_error))return{kind:"failed"};let d=Tu(c.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(`
|
|
384
|
+
`),l.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function Lu(e){let t=at();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return l.info(h.dim(re[t].summary)),!0;if(l.warn(re[t].summary),l.message(` ${re[t].next}`),e)return!1;if(t==="not-installed"){let n=await hi({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(qt(n)||!n)return l.info("Skipped install. Set up auth and re-run when ready."),!1;l.message(h.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=pi();if(!r.ok)return l.error(`Install failed: ${r.error}`),l.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=at()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await hi({message:"Run `claude login` now to sign in?",initialValue:!0});if(qt(n)||!n)return l.info("Skipped login. Run `claude login` when ready and try again."),!1;l.message(h.dim("Launching `claude login`\u2026"));let r=fi();if(!r.ok)return l.error(`Login failed: ${r.error}`),!1}return!0}function Nu(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function Fu(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&Nu(e)){process.stdout.write(Kt(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=Uu[o]??h.cyan,a=Ku(o,i);process.stdout.write(s(Du)+" "+h.bold(o)+h.dim("(")+a+h.dim(")")+`
|
|
371
385
|
`);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(h.dim(h.italic(" "+V(r,200)))+`
|
|
372
|
-
`)}}var
|
|
373
|
-
`),a&&process.stdout.write(
|
|
374
|
-
`);return}let c=
|
|
375
|
-
`)}function
|
|
386
|
+
`)}}var Du="\u23FA",wi="\u23BF",Uu={Read:h.blue,Glob:h.cyan,Grep:h.cyan,Edit:h.yellow,Write:h.magenta,Bash:h.green,WebFetch:h.magenta,WebSearch:h.magenta};function Mu(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=Bu(s);if(n){process.stdout.write(h.red(` ${wi} Error`)+`
|
|
387
|
+
`),a&&process.stdout.write(Gu(V(a,500)," ",h.red)+`
|
|
388
|
+
`);return}let c=Wu(i,a,o?.input);c&&process.stdout.write(h.dim(` ${wi} `)+c+`
|
|
389
|
+
`)}function Bu(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 Wu(e,t,n){if(!e)return"";switch(e){case"Read":{let r=(t.match(/^\s*\d+→/gm)??[]).length,o=r>0?r:t.split(`
|
|
376
390
|
`).filter(Boolean).length;return h.dim(`Read ${o} line${o===1?"":"s"}`)}case"Glob":{let r=t.split(`
|
|
377
391
|
`).filter(o=>o.trim().length>0).length;return h.dim(`Found ${r} ${r===1?"entry":"entries"}`)}case"Grep":{let r=t.split(`
|
|
378
392
|
`)[0]?.trim()??"";if(/^Found\s+\d+/.test(r))return h.dim(r);let o=t.split(`
|
|
@@ -382,15 +396,16 @@ ${h.dim("elapsed: "+i)}`,h.bold("Done"))}function hi(e){if(e<1e3)return`${e}ms`;
|
|
|
382
396
|
\u2026 (+${i} more line${i===1?"":"s"})`:""),[a,...c]=s.split(`
|
|
383
397
|
`);return c.length===0?h.dim(a):h.dim(a)+`
|
|
384
398
|
`+h.dim(c.map(u=>" "+u).join(`
|
|
385
|
-
`))}case"WebFetch":case"WebSearch":return h.dim(`Fetched ${V(t.replace(/\s+/g," "),80)}`);default:return""}}function
|
|
399
|
+
`))}case"WebFetch":case"WebSearch":return h.dim(`Fetched ${V(t.replace(/\s+/g," "),80)}`);default:return""}}function Gu(e,t,n){return e.split(`
|
|
386
400
|
`).map(r=>n(t+r)).join(`
|
|
387
|
-
`)}function
|
|
401
|
+
`)}function Ku(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return h.dim(V(Bn(String(n.file_path??"")),80));case"Bash":return h.dim(V(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${Bn(String(n.path))}`:"";return h.dim(V(r+o,80))}case"Glob":return h.dim(V(String(n.pattern??""),80));case"WebFetch":return h.dim(V(String(n.url??""),80));case"WebSearch":return h.dim(V(String(n.query??""),80));default:return""}}function Bn(e){if(!e)return e;let t=process.cwd(),n=Cu(t,e);return n.startsWith("..")?e:n||e}function V(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function qu(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
|
|
388
402
|
|
|
389
403
|
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.
|
|
390
404
|
|
|
391
405
|
Constraints:
|
|
392
406
|
- Do NOT run \`seoagent ack\` yourself. The CLI will do that automatically after you complete the action.
|
|
393
407
|
- Do NOT install dependencies or run \`git commit\` unless the action explicitly tells you to.
|
|
408
|
+
- If the action has a "Screenshots to capture" section, Read \`.claude/skills/seoagent/references/screenshots.md\` and follow it \u2014 capture real product screenshots from this repo's UI (no Playwright/Puppeteer install, no paid API). If you can't capture, fall back to a \`<!-- SCREENSHOT-TODO -->\` marker + an AI image prompt as that protocol describes; never block the action on a screenshot.
|
|
394
409
|
- If you cannot apply the action (false positive, target file not found, action is ambiguous), say so explicitly and stop \u2014 don't guess.
|
|
395
410
|
|
|
396
411
|
Verdict marker (REQUIRED):
|
|
@@ -403,19 +418,19 @@ Action file (\`.seoagent/inbox/${e.filename}\`):
|
|
|
403
418
|
\`\`\`
|
|
404
419
|
${t}
|
|
405
420
|
\`\`\`
|
|
406
|
-
`}import{spinner as
|
|
407
|
-
`),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${
|
|
421
|
+
`}import{spinner as Hu}from"@clack/prompts";import b from"picocolors";var Yu=new Set(["on","off","status"]);async function ct(e,t={}){let n=(e||"").toLowerCase();if(!Yu.has(n)){l.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=j();if(!r){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||A.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?Hu():null,c=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(c);let u;try{u=await fetch(`${o}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(m){k(a,"error",`Network error: ${m.message}`,b.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 $=_(process.cwd())?.domain??"",S=`${A.PRICING}?ref=cli${$?`&domain=${encodeURIComponent($)}`:""}`;k(a,"warn","CLI autopilot is a paid feature.",b.yellow("Autopilot is a paid feature.")),l.message(zu(S)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){k(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,b.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:g}=d.autopilot;if(n==="on"){a?.stop(b.green("Autopilot enabled.")),l.message(Gn({enabled:!0,deliveryMode:g,action:n}));return}if(n==="off"){a?.stop(b.dim("Autopilot disabled.")),l.message(Gn({enabled:!1,deliveryMode:g,action:n}));return}a?.stop(b.dim("Status:")),l.message(Gn({enabled:p,deliveryMode:g,action:n}))}function Gn(e){let n=s=>b.dim(s.padEnd(11)),r=e.enabled?`${b.bold(b.green("\u25CF ON"))} ${b.dim("(queueing fixes for your coding agent)")}`:`${b.dim("\u25CB OFF")} ${b.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${b.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${b.dim("Apply queued fixes:")} ${b.cyan(f("sync"))}`}),o.push({content:`${b.dim("Turn off any time:")} ${b.cyan(f("autopilot off"))}`})):(o.push({content:`${b.dim("Enable (paid):")} ${b.cyan(f("autopilot on"))}`}),o.push({content:b.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${b.bold(b.cyan("SEOAgent"))} ${b.dim("\xB7")} ${b.dim("autopilot")}`;return I(o,{width:78,title:i})}function zu(e){let t=[{content:b.bold(b.yellow("Autopilot is a paid feature."))},{sep:!0},{content:b.dim("SEOAgent continuously audits your site and queues fixes for")},{content:b.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:b.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${b.dim("Upgrade:")} ${b.cyan(e)}`}],n=`${b.bold(b.cyan("SEOAgent"))} ${b.dim("\xB7")} ${b.dim("autopilot")}`;return I(t,{width:78,title:n})}import{mkdirSync as sd,writeFileSync as ad}from"fs";import{join as Kn}from"path";import{readdirSync as Vu,readFileSync as Ju,statSync as bi}from"fs";import{join as Xu}from"path";var Qu=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Zu=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"]),ed=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),td=5e3,nd=512*1024;function _i(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function $i(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&&Zu.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var Si=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,vi=/\]\(\s*([^)\s]+)/g;function rd(e,t){if(!e)return[];let n=_i(t),r=[],o;for(Si.lastIndex=0;(o=Si.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=$i(i,n);s&&r.push(s)}for(vi.lastIndex=0;(o=vi.exec(e))!==null;){let i=$i(o[1],n);i&&r.push(i)}return r}function od(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 Ci(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(`
|
|
422
|
+
`),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${_i(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(`
|
|
408
423
|
`),i=e.orphans.length===0?`## Orphan pages
|
|
409
424
|
|
|
410
|
-
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=>`| ${
|
|
411
|
-
`),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=>`| ${
|
|
425
|
+
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=>`| ${xi(a.url)} | \u2014 |`)].join(`
|
|
426
|
+
`),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=>`| ${xi(a.url)} | ${a.inbound} |`)].join(`
|
|
412
427
|
`);return[r,"",o,"",i,s,""].join(`
|
|
413
|
-
`)}function
|
|
414
|
-
`);return}let i=Kn(t,w);
|
|
428
|
+
`)}function xi(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*id(e){let t=0;function*n(r){let o;try{o=Vu(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=td)return;if(i.name.startsWith("."))continue;let s=Xu(r,i.name);if(i.isDirectory()){if(ed.has(i.name))continue;yield*n(s)}else if(i.isFile()){let a=i.name.lastIndexOf("."),c=a===-1?"":i.name.slice(a+1).toLowerCase();if(!Qu.has(c))continue;t++,yield s}}}yield*n(e)}function Ei(e,t){let{pages:n}=ce(e,t),r=[],o=0,i=!1;try{i=bi(e).isDirectory()}catch{i=!1}if(i)for(let s of id(e)){let a;try{if(bi(s).size>nd)continue;a=Ju(s,"utf-8")}catch{continue}o++;for(let c of rd(a,t))r.push(c)}return od(n,r,o)}function lt(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Ei(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
|
|
429
|
+
`);return}let i=Kn(t,w);sd(i,{recursive:!0});let s=Kn(i,"internal-links.md");if(ad(s,Ci(o,r),"utf-8"),l.success(`Analyzed ${o.pageCount} page${o.pageCount===1?"":"s"} across ${o.filesScanned} file${o.filesScanned===1?"":"s"}.`),o.orphans.length===0)l.info("No orphan pages \u2014 every page has an inbound internal link.");else{l.warn(`${o.orphans.length} orphan page${o.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of o.orphans.slice(0,10))l.message(` \u2022 ${a.url}`);o.orphans.length>10&&l.message(` \u2026and ${o.orphans.length-10} more`)}l.info(`Report written to ${Kn(w,"internal-links.md")}`)}import{existsSync as cd,mkdirSync as ld,rmSync as ud,writeFileSync as Ai}from"fs";import{dirname as dd,join as Ht}from"path";import X from"picocolors";async function qn(e,t={}){if(e!=="track"&&e!=="reconcile"){l.message(`Usage:
|
|
415
430
|
${f("content track")} --slug <slug> --url <live-url> [--file <repo-path>] [--title "..."] [--type <page_type>] [--status published|draft]
|
|
416
|
-
${f("content reconcile")} [--dir <content-dir>] [--prune] # backfill pointers for published articles missing one`),e&&(l.error(`Unknown content action: ${e}. Actions: \`track\`, \`reconcile\`.`),process.exitCode=1);return}let n=process.cwd(),r=_(n);if(!r){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}if(e==="reconcile"){await
|
|
417
|
-
`);return}l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=ae(t),o=
|
|
418
|
-
`);return}let i=o.filter(s=>s.level==="action");if(i.length===0){l.success("SEOAgent health: everything looks good.");return}l.message(Hn.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)l.message(` ${Hn.yellow("\u25CF")} ${s.message}`),s.fix&&l.message(` ${Hn.dim("\u2192 "+s.fix)}`)}import Q from"picocolors";import{existsSync as Be,mkdirSync as Yt,readdirSync as
|
|
431
|
+
${f("content reconcile")} [--dir <content-dir>] [--prune] # backfill pointers for published articles missing one`),e&&(l.error(`Unknown content action: ${e}. Actions: \`track\`, \`reconcile\`.`),process.exitCode=1);return}let n=process.cwd(),r=_(n);if(!r){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}if(e==="reconcile"){await pd(n,r,t);return}let o=t.slug??(t.file?t.file:""),i=En(o);if(!i){l.error("A slug is required: --slug <slug> (or --file <repo-path> to derive it)."),process.exitCode=1;return}let s=it(i,{url:t.url,domain:r.domain,blogPath:r.blog_path});s||l.warn("No live URL \u2014 pass --url, or set domain + blog_path in project.md. Tracking without a canonical URL.");let a=t.title?.trim()||Lo(i),c=r.cms&&r.cms!=="mdx-local"?"cms":t.file?"repo":"external",u=st({slug:i,title:a,canonical:s,status:t.status?.trim()||"published",page_type:t.type?.trim()||void 0,primary_keyword:t.primaryKeyword?.trim()||void 0,source:c,repo_path:t.file?.trim()||void 0,tracked_at:new Date().toISOString()}),d=Ht(n,w,"content");ld(d,{recursive:!0});let p=Ht(d,`${i}.md`),g=cd(p);Ai(p,u,"utf-8"),l.success(`${g?"Updated":"Tracked"} ${X.bold(i)}${s?` \u2192 ${X.cyan(s)}`:""} in .seoagent/content/.`);try{await K({silent:!0,pushOnly:!0})}catch{}l.message(X.dim("It will appear on your dashboard after sync (run `seoagent login` if you haven\u2019t)."))}async function pd(e,t,n){let r=Ht(e,w,"content"),o=xn(r),i=new Set;for(let c of(n.dir??"").split(",").map(u=>u.trim()).filter(Boolean))i.add(c);for(let c of o)c.source==="repo"&&c.repo_path&&i.add(dd(c.repo_path));if(i.size===0){l.error("No content directory to scan. Pass `--dir <path>` (e.g. --dir apps/web/content/blog) \u2014 or track one article first so reconcile can infer the rest."),process.exitCode=1;return}let s=[...i].flatMap(c=>vn(e,c)),a=_n(s,o,Cn(e));if(a.toTrack.length===0&&a.stale.length===0){l.success(`Content tracking is in sync \u2014 ${a.alreadyTracked} pointer${a.alreadyTracked===1?"":"s"} cover every published article in ${[...i].join(", ")}.`);return}for(let c of a.toTrack){let u=it(c.slug,{domain:t.domain,blogPath:t.blog_path}),d=st({slug:c.slug,title:c.title,canonical:u,status:"published",page_type:c.page_type,source:"repo",repo_path:c.path,tracked_at:new Date().toISOString()});Ai(Ht(r,`${c.slug}.md`),d,"utf-8"),l.message(`${X.green("+")} tracked ${X.bold(c.slug)}${u?X.dim(` \u2192 ${u}`):""}`)}for(let c of a.stale)n.prune?(ud(c.file,{force:!0}),l.message(`${X.red("-")} pruned stale pointer ${X.bold(c.slug)} (source ${c.repo_path} is gone)`)):l.message(`${X.yellow("!")} stale pointer ${X.bold(c.slug)} \u2192 ${c.repo_path} no longer exists (re-run with --prune to delete)`);l.success(`Reconciled content: +${a.toTrack.length} tracked, ${a.stale.length} stale${n.prune?" (pruned)":""}.`);try{await K({silent:!0,pushOnly:!0})}catch{}}import{existsSync as fd,readFileSync as md}from"fs";import{join as gd}from"path";import Hn from"picocolors";function hd(e){let t=[];return e.pullReceiptCount!=null&&t.push({level:"action",code:"pull_receipt",message:`${e.pullReceiptCount} cloud change${e.pullReceiptCount===1?"":"s"} pulled but not triaged yet.`,fix:"Triage them (skill \xA7 Pull Receipt Triage), then delete .seoagent/.pull-receipt.json."}),(e.domain==="unknown"||!e.domain)&&t.push({level:"action",code:"domain_unknown",message:"Site URL is unknown \u2014 nothing works without a real domain.",fix:"Ask the user for their site URL, then set `domain:` in .seoagent/project.md."}),(e.siteType==="unknown"||!e.siteType)&&t.push({level:"action",code:"site_type_unknown",message:"Site type is unknown \u2014 strategy/briefs make worse calls without it.",fix:"WebFetch the homepage, infer the type, set `site_type:` in project.md."}),!(e.imageProvider&&e.imageProvider!=="none")&&e.detectedImageProvider!=="none"&&t.push({level:"action",code:"image_provider_unset",message:`Image generation is available (${e.detectedImageKey} found) but not enabled.`,fix:`Run \`${f("env-check")}\` to record image_provider, then articles can get AI hero images.`}),t.length===0&&t.push({level:"ok",code:"healthy",message:"Everything looks healthy."}),t}function yd(e){let t=gd(e,w,St);if(!fd(t))return null;try{let n=JSON.parse(md(t,"utf-8"));return Array.isArray(n.changes)?n.changes.length:0}catch{return 0}}function Yn(e={}){let t=process.cwd(),n=_(t);if(!n){if(e.json){process.stdout.write(JSON.stringify({status:"no-project",findings:[]})+`
|
|
432
|
+
`);return}l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=ae(t),o=hd({domain:n.domain,siteType:n.site_type,imageProvider:n.image_provider,detectedImageProvider:r.provider,detectedImageKey:r.matched_key,pullReceiptCount:yd(t)});if(e.json){process.stdout.write(JSON.stringify({status:"ok",findings:o})+`
|
|
433
|
+
`);return}let i=o.filter(s=>s.level==="action");if(i.length===0){l.success("SEOAgent health: everything looks good.");return}l.message(Hn.bold(`SEOAgent health \u2014 ${i.length} thing${i.length===1?"":"s"} to handle:`));for(let s of i)l.message(` ${Hn.yellow("\u25CF")} ${s.message}`),s.fix&&l.message(` ${Hn.dim("\u2192 "+s.fix)}`)}import Q from"picocolors";import{existsSync as Be,mkdirSync as Yt,readdirSync as wd,readFileSync as kd,statSync as Xy,writeFileSync as Ri}from"fs";import{dirname as bd,join as fe,relative as $d,resolve as Sd}from"path";var We="okf";function zt(e){return fe(e,w,We)}var vd=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function zn(e){let t=[];for(let n of wd(e,{withFileTypes:!0})){let r=fe(e,n.name);n.isDirectory()?t.push(...zn(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function xd(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 Ii(e){let t=[],n=[];if(!Be(e))return{ok:!1,fileCount:0,errors:[{file:We,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=zn(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:We,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Be(fe(e,"index.md"))||n.push({file:We,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=$d(e,i),a;try{a=se(kd(i,"utf-8"))}catch{t.push({file:s,message:"Could not read or parse file."});continue}let c=a.data.type;(c==null||String(c).trim()==="")&&t.push({file:s,message:"Missing required frontmatter field `type`."});let u=a.data.timestamp;u!=null&&u!==""&&!vd.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 xd(a.body)){let g=p.split("#")[0];if(!g)continue;let m=Sd(bd(i),g);Be(m)||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 Vt(e){let t=zt(e);if(!Be(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:zn(t).length}}catch{return{exists:!0,fileCount:0}}}function Pi(e,t){let n=zt(e);Yt(n,{recursive:!0}),Yt(fe(n,"concepts"),{recursive:!0}),Yt(fe(n,"faqs"),{recursive:!0}),Yt(fe(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=fe(n,"index.md");Be(i)||(Ri(i,`---
|
|
419
434
|
type: Organization
|
|
420
435
|
title: ${o}
|
|
421
436
|
description: Knowledge bundle describing ${o} for AI agents and answer engines.
|
|
@@ -442,7 +457,7 @@ _Describe the business in 2\u20134 sentences (pull from \`.seoagent/context.md\`
|
|
|
442
457
|
## Published articles
|
|
443
458
|
|
|
444
459
|
- _Link article files here, e.g._ \`articles/guide-to-x.md\`
|
|
445
|
-
`,"utf-8"),r.push("index.md"));let s=fe(n,"log.md");return Be(s)||(
|
|
460
|
+
`,"utf-8"),r.push("index.md"));let s=fe(n,"log.md");return Be(s)||(Ri(s,`---
|
|
446
461
|
type: Log
|
|
447
462
|
title: Change log
|
|
448
463
|
description: Chronological history of changes to this OKF bundle.
|
|
@@ -451,10 +466,10 @@ description: Chronological history of changes to this OKF bundle.
|
|
|
451
466
|
# Change log
|
|
452
467
|
|
|
453
468
|
- Bundle scaffolded.
|
|
454
|
-
`,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var Vn=`${w}/${We}`;function ut(e,t={}){let n=process.cwd(),r=L(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=
|
|
469
|
+
`,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var Vn=`${w}/${We}`;function ut(e,t={}){let n=process.cwd(),r=L(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=Pi(n,i);a.length===0?l.info(`OKF bundle already scaffolded at ${Vn}/.`):(l.success(`Scaffolded ${Vn}/ \u2014 created ${a.join(", ")}.`),l.info("Now fill the bundle from your .seoagent/ knowledge, then run `seoagent okf validate`."));return}if(o==="validate"){let a=Ii(zt(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
|
|
455
470
|
`);return}for(let c of a.errors)l.message(`${Q.red("\u2717")} ${Q.dim(c.file)} \u2014 ${c.message}`);for(let c of a.warnings)l.message(`${Q.yellow("!")} ${Q.dim(c.file)} \u2014 ${c.message}`);a.ok?l.success(`OKF bundle is valid \u2014 ${a.fileCount} file${a.fileCount===1?"":"s"}, ${a.warnings.length} warning${a.warnings.length===1?"":"s"}.`):(l.error(`OKF bundle has ${a.errors.length} error${a.errors.length===1?"":"s"} (see above).`),process.exitCode=1);return}let s=Vt(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
|
|
456
471
|
`);return}l.message(I([{content:Q.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?Q.green(Vn+"/"):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 W from"picocolors";async function Jn(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null;if(!r&&!e.url){l.error("No domain set in .seoagent/project.md \u2014 set `domain:` (or pass `--url <sitemap-url>`) so I know which sitemap to check."),process.exitCode=1;return}let o=r?ce(t,r).pages.map(s=>s.url||s.route):[],i=await io({domain:r||"",sitemapUrl:e.url,knownUrls:o});if(e.json){process.stdout.write(JSON.stringify(i,null,2)+`
|
|
457
|
-
`),i.ok||(process.exitCode=1);return}
|
|
472
|
+
`),i.ok||(process.exitCode=1);return}_d(i),i.ok||(process.exitCode=1)}function _d(e){let t=e.fetched?e.status===200?W.green(`200 \xB7 ${e.urls.length} URL${e.urls.length===1?"":"s"}`):W.red(String(e.status)):W.red("unreachable");l.message(I([{content:W.bold("Sitemap check")},{sep:!0},{content:`URL: ${W.dim(e.sitemapUrl)}`},{content:`Status: ${t}`},...e.fetched&&e.status===200?[{content:`Private leaked: ${e.privateUrls.length===0?W.green("none"):W.yellow(String(e.privateUrls.length))}`},{content:`Missing public: ${e.missing.length===0?W.green("none"):W.yellow(String(e.missing.length))}`},{content:`<lastmod>: ${e.hasLastmod?W.green("present"):W.dim("absent")}`}]:[]],{title:e.ok?W.cyan("Sitemap"):W.red("Sitemap")}));for(let n of e.issues){let r=n.level==="error"?W.red("\u2717"):n.level==="warning"?W.yellow("!"):W.dim("\xB7");l.message(`${r} ${n.message}`)}e.ok?l.success("Sitemap looks healthy."):l.error("Sitemap has errors (see above).")}import{mkdirSync as Wi,writeFileSync as Gi,readFileSync as Ld,readdirSync as Nd,existsSync as Fd}from"fs";import{join as Ki}from"path";import R from"picocolors";import{query as Dd}from"@anthropic-ai/claude-agent-sdk";import{join as Xn}from"path";var Qn="citations",Zn="scorecard.md",Cd="history",Ed=6,Ad=1,Rd=12,Id=5,Jt="Claude (web-grounded)";function Xt(e){return Xn(e,w,Qn)}function Ti(e){return Xn(Xt(e),Zn)}function ji(e){return Xn(Xt(e),Cd)}function Li(e){return`${e.replace(/[:.]/g,"-")}.json`}function Ni(e){return typeof e!="number"||!Number.isFinite(e)?Ed:Math.max(Ad,Math.min(Rd,Math.floor(e)))}function Qt(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e){let o=typeof r=="string"?r.trim():"";if(!o)continue;let i=o.toLowerCase();if(!t.has(i)&&(t.add(i),n.push(o),n.length>=Id))break}return n}function dt(e){let t=e.results.length;return{cited:e.results.filter(r=>r.surfaced).length,total:t}}function er(e){let t=e.results.length,n={brand:e.brand,isYou:!0,surfaced:e.results.filter(o=>o.surfaced).length,total:t},r=e.competitors.map(o=>({brand:o,isYou:!1,surfaced:e.results.filter(i=>i.competitorsSurfaced.some(s=>s.toLowerCase()===o.toLowerCase())).length,total:t}));return r.sort((o,i)=>i.surfaced-o.surfaced||o.brand.localeCompare(i.brand)),[n,...r]}function Fi(e,t){let{cited:n,total:r}=dt(e);return{generated_at:t.generatedAt,domain:e.domain,brand:e.brand,cited:n,total:r,competitors:e.competitors,results:e.results}}function Di(e,t){if(!t)return null;let{cited:n}=dt(e),r=new Map(t.results.map(s=>[s.query.toLowerCase(),s.surfaced])),o=[],i=[];for(let s of e.results){let a=r.get(s.query.toLowerCase());a!==void 0&&(s.surfaced&&!a&&o.push(s.query),!s.surfaced&&a&&i.push(s.query))}return{scoreDelta:n-t.cited,prevCited:t.cited,prevTotal:t.total,prevDate:t.generated_at.slice(0,10),newlyCited:o,newlyDropped:i}}function Ui(e,t){let n=Qt(e.competitors),r=[`- 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"}`,n.length?`- Competitors to track: ${n.join(", ")}`:null].filter(Boolean).join(`
|
|
458
473
|
`),o=n.length?`
|
|
459
474
|
4. For EACH question, also record which of these competitor brands appear in the cited sources: ${n.join(", ")}. Use these EXACT names in \`competitorsSurfaced\` (only the ones that actually appear; empty array if none). This powers a share-of-voice comparison.`:"",i=n.length?`,
|
|
460
475
|
"competitorsSurfaced": [${JSON.stringify(n[0])}]`:`,
|
|
@@ -496,10 +511,10 @@ End your reply with EXACTLY ONE fenced \`\`\`json block (and nothing after it) m
|
|
|
496
511
|
}
|
|
497
512
|
\`\`\`
|
|
498
513
|
|
|
499
|
-
\`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown. \`competitors\` must echo the tracked list exactly (${n.length?n.join(", "):"empty when none were given"}).`}function
|
|
514
|
+
\`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown. \`competitors\` must echo the tracked list exactly (${n.length?n.join(", "):"empty when none were given"}).`}function Mi(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=Pd(n[o]);if(i)return i}return null}function Pd(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,i=Qt(Array.isArray(n.competitors)?n.competitors.map(c=>String(c)):[]),s=new Set(i.map(c=>c.toLowerCase()));if(!Array.isArray(n.results))return null;let a=[];for(let c of n.results){if(!c||typeof c!="object")continue;let u=c,d=typeof u.query=="string"?u.query.trim():"";if(!d)continue;let p=u.surfaced===!0,g=typeof u.rank=="number"&&Number.isFinite(u.rank)?Math.round(u.rank):null,m=typeof u.evidence=="string"?u.evidence.trim():"",$=typeof u.source=="string"&&u.source.trim()?u.source.trim():null,S=Array.isArray(u.competitorsSurfaced)?Od(u.competitorsSurfaced.map(T=>typeof T=="string"?T.trim():"").filter(T=>T&&s.has(T.toLowerCase()))):[];a.push({query:d,surfaced:p,rank:p?g:null,evidence:m,source:$,competitorsSurfaced:S})}return a.length===0?null:{brand:o,domain:r,competitors:i,results:a}}function Od(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}function Bi(e,t){let{cited:n,total:r}=dt(e),o=t.generatedAt.slice(0,10),i=e.results.some(p=>p.source),s=e.results.map((p,g)=>{let m=p.surfaced?"\u2705":"\u2014",$=p.surfaced&&p.rank?`#${p.rank}`:"\u2014",S=Z(p.evidence||(p.surfaced?"surfaced":"not found")),T=p.source?Z(Oi(p.source)):"\u2014";return i?`| ${g+1} | ${Z(p.query)} | ${m} | ${$} | ${T} | ${S} |`:`| ${g+1} | ${Z(p.query)} | ${m} | ${$} | ${S} |`}).join(`
|
|
500
515
|
`),a=i?`| # | Query | Cited? | ~Rank | Source cited | Evidence |
|
|
501
516
|
|---|-------|--------|-------|--------------|----------|`:`| # | Query | Cited? | ~Rank | Evidence |
|
|
502
|
-
|---|-------|--------|-------|----------|`,c=e.results.filter(p=>!p.surfaced),u=c.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":c.map(p=>{let g=p.source?` _(currently cited: ${Z(
|
|
517
|
+
|---|-------|--------|-------|----------|`,c=e.results.filter(p=>!p.surfaced),u=c.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":c.map(p=>{let g=p.source?` _(currently cited: ${Z(Oi(p.source))})_`:"";return`- **${Z(p.query)}** \u2014 ${p.evidence||"not surfaced"}${g}`}).join(`
|
|
503
518
|
`),d=c.length?"- 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`---
|
|
504
519
|
type: Report
|
|
505
520
|
title: AI Citation Scorecard \u2014 ${e.domain}
|
|
@@ -515,10 +530,10 @@ engine: claude-web-grounded
|
|
|
515
530
|
> tells you whether it's working.
|
|
516
531
|
|
|
517
532
|
**Cited: ${n} / ${r} queries** \xB7 engine: ${Jt} \xB7 ${o}
|
|
518
|
-
${
|
|
533
|
+
${Td(t.trend,n,r)}
|
|
519
534
|
${a}
|
|
520
535
|
${s}
|
|
521
|
-
${
|
|
536
|
+
${jd(e)}
|
|
522
537
|
## Where you're not surfacing (opportunities)
|
|
523
538
|
|
|
524
539
|
${u}
|
|
@@ -542,13 +557,13 @@ This is **not a per-engine guarantee**: ChatGPT, Perplexity, and Gemini each
|
|
|
542
557
|
rank and cite differently, and tracking them individually is a planned
|
|
543
558
|
follow-up. Treat the score as directional \u2014 watch the trend rather than fixating
|
|
544
559
|
on a single number.
|
|
545
|
-
`}function
|
|
560
|
+
`}function Td(e,t,n){if(!e)return`
|
|
546
561
|
_First run \u2014 re-run on a cadence to start tracking the trend._
|
|
547
562
|
`;let r=e.scoreDelta>0?`\u25B2 up ${e.scoreDelta}`:e.scoreDelta<0?`\u25BC down ${Math.abs(e.scoreDelta)}`:"\u25AA no change",o=`
|
|
548
563
|
**Trend:** ${t}/${n} this run \u2014 ${r} from ${e.prevCited}/${e.prevTotal} on ${e.prevDate}.`;return e.newlyCited.length&&(o+=`
|
|
549
564
|
- \u2705 Newly cited: ${e.newlyCited.map(i=>`_${Z(i)}_`).join("; ")}`),e.newlyDropped.length&&(o+=`
|
|
550
565
|
- \u26A0\uFE0F Dropped: ${e.newlyDropped.map(i=>`_${Z(i)}_`).join("; ")}`),o+`
|
|
551
|
-
`}function
|
|
566
|
+
`}function jd(e){if(!e.competitors.length)return"";let t=er(e).map(n=>{let r=n.isYou?`**${Z(n.brand)} (you)**`:Z(n.brand),o=n.total>0?`${Math.round(n.surfaced/n.total*100)}%`:"\u2014";return`| ${r} | ${n.surfaced} / ${n.total} | ${o} |`}).join(`
|
|
552
567
|
`);return`
|
|
553
568
|
## Share of voice
|
|
554
569
|
|
|
@@ -557,17 +572,17 @@ How often each brand surfaces across the same ${e.results.length} queries.
|
|
|
557
572
|
| Brand | Surfaced | Rate |
|
|
558
573
|
|-------|----------|------|
|
|
559
574
|
${t}
|
|
560
|
-
`}function
|
|
561
|
-
`));let u=
|
|
575
|
+
`}function Oi(e){let t=e.replace(/^https?:\/\//i,"").replace(/\/$/,"");return t.length<=48?t:t.slice(0,47)+"\u2026"}function Z(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function pt(e={}){let t=process.cwd(),n=L(t);if(!n)return;let r=at();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){l.warn(re[r].summary),re[r].next&&l.message(` ${re[r].next}`),process.exitCode=1;return}l.info(R.dim(re[r].summary));let o=Hr(t),i=Vt(t),s=Qt(e.competitors&&e.competitors.length?e.competitors:Wd(o?.business.competitors)),a={domain:n.domain,name:o?.business.name,type:o?.business.type||n.site_type,description:o?.business.description,hasOkfBundle:i.exists&&i.fileCount>0,competitors:s},c=Ni(e.queries);l.message(`${R.cyan("\u25C7")} Auditing AI citations for ${R.bold(a.domain)} \u2014 ${c} web-grounded quer${c===1?"y":"ies"} via ${Jt}.`),l.message(R.dim(` This runs live web searches and can take a minute\u2026
|
|
576
|
+
`));let u=Ui(a,c),d=await Ud({cwd:t,prompt:u,model:e.model});if(d===null){process.exitCode=1;return}let p=Mi(d);if(!p){l.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 g=new Date().toISOString(),m=ji(t),$=Gd(m),S=Di(p,$),T=Bi(p,{generatedAt:g,trend:S});Wi(Xt(t),{recursive:!0}),Gi(Ti(t),T,"utf-8"),Wi(m,{recursive:!0}),Gi(Ki(m,Li(g)),JSON.stringify(Fi(p,{generatedAt:g}),null,2)+`
|
|
562
577
|
`,"utf-8");let{cited:x,total:F}=dt(p),ee=x===0?R.red:x<F?R.yellow:R.green,q=[{content:R.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${R.cyan(p.domain)}`},{content:`Cited: ${ee(`${x} / ${F}`)} ${R.dim("queries")}`}];if(S){let oe=S.scoreDelta>0?R.green(`\u25B2 +${S.scoreDelta}`):S.scoreDelta<0?R.red(`\u25BC ${S.scoreDelta}`):R.dim("\u25AA 0");q.push({content:`Trend: ${oe} ${R.dim(`vs ${S.prevCited}/${S.prevTotal} on ${S.prevDate}`)}`})}else q.push({content:R.dim("Trend: first run \u2014 re-run to start tracking")});if(q.push({content:`Engine: ${R.dim(Jt)}`}),p.competitors.length){q.push({sep:!0}),q.push({content:R.dim("Share of voice:")});for(let oe of er(p)){let kt=oe.isYou?R.bold(`${oe.brand} (you)`):oe.brand;q.push({content:` ${kt}: ${oe.surfaced}/${oe.total}`})}}q.push({sep:!0}),q.push({content:R.dim(`Saved \u2192 .seoagent/${Qn}/${Zn}`)}),q.push({content:x<F?R.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):R.dim("Surfacing across the board. Re-run periodically to catch drift.")}),l.message(I(q,{title:R.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(p,null,2)+`
|
|
563
|
-
`)}async function
|
|
578
|
+
`)}async function Ud(e){let{cwd:t,prompt:n,model:r}=e;try{let o=Dd({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 c of a)Md(c)}else if(s.type==="result"){if(process.stdout.write(`
|
|
564
579
|
`),!(s.subtype==="success"&&!s.is_error))return l.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(`
|
|
565
|
-
`),l.error(` Agent error: ${o.message}`),null}}function
|
|
566
|
-
`))}}function
|
|
567
|
-
`);return}if(c.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}.`,y.yellow(`Daily peek quota reached for ${d}.`)),l.message(
|
|
568
|
-
`);return}if(l.message(
|
|
580
|
+
`),l.error(` Agent error: ${o.message}`),null}}function Md(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(Kt(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(R.dim(` ${R.magenta("\u{1F50E}")} ${n}${o?` ${Bd(o,70)}`:""}
|
|
581
|
+
`))}}function Bd(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Wd(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function Gd(e){try{if(!Fd(e))return null;let t=Nd(e).filter(o=>o.endsWith(".json")).sort();if(t.length===0)return null;let n=t[t.length-1],r=JSON.parse(Ld(Ki(e,n),"utf-8"));return r&&typeof r=="object"&&Array.isArray(r.results)&&typeof r.generated_at=="string"?r:null}catch{return null}}import Ge from"picocolors";var Kd=30,qd=/<(script|style|noscript|template|svg|nav|header|footer)\b[^>]*>[\s\S]*?<\/\1>/gi;function Hd(e){let t=e,n=/<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(t);n&&(t=n[1]),t=t.replace(qd," ").replace(/<!--[\s\S]*?-->/g," ").replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&[a-z]+;/gi," ").replace(/\s+/g," ").trim();let r=t===""?0:t.split(" ").filter(Boolean).length;return{wordCount:r,rendered:r<Kd?"empty":"yes"}}async function Yd(e,t){try{let n=await B(e,{headers:{"user-agent":"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) SEOAgent-CLI"},redirect:"follow"},{attempts:2,timeoutMs:1e4,fetchImpl:t});if(!n.ok)return{status:n.status,rendered:"error",wordCount:0};let r=await n.text(),{wordCount:o,rendered:i}=Hd(r);return{status:n.status,rendered:i,wordCount:o}}catch{return{status:null,rendered:"error",wordCount:0}}}async function qi(e,t={}){let n=Math.max(1,t.concurrency??5),r=new Map,o=[...e],i=0;async function s(){for(;;){let a=o.shift();if(a===void 0)return;r.set(a,await Yd(a,t.fetchImpl)),i+=1,t.onProgress?.(i,e.length)}}return await Promise.all(Array.from({length:Math.min(n,e.length)},()=>s())),r}var tr=300;async function ft(e={}){if(e.all){await zd();return}let t=process.cwd();if(!L(t))return;ye(t);let n=Nn(t);Yi(t);let r=await Hi(t,{enrichSitemap:!0,crawl:e.crawl});if(n.reason==="refreshed"?(l.success(n.from&&n.from!==n.to?`Refreshed the SEOAgent skill ${n.from} \u2192 ${n.to}.`:`Refreshed the SEOAgent skill (now ${n.to}).`),l.info("Your `.seoagent/` knowledge was left untouched.")):(l.error(`Could not refresh the skill (${n.reason}).`),process.exitCode=1),r.added>0?l.success(`Re-scanned the codebase: +${r.added} new page${r.added===1?"":"s"} merged into .seoagent/pages.md (${r.total} total).`):r.total>0&&l.info(`Page inventory already current (${r.total} pages).`),r.crawl){let{crawled:o,empty:i,errors:s}=r.crawl;l.success(`Crawled ${o} page${o===1?"":"s"} \u2192 filled Status / Rendered / Word count`+(i>0?`, ${i} render empty`:"")+(s>0?`, ${s} unreachable`:"")+".")}}async function Hi(e,t={}){try{let n=_(e),r=n?.domain&&n.domain!=="unknown"?n.domain:null,{pages:o}=ce(e,r);t.enrichSitemap&&r&&await co(o,r);let i,s;if(t.crawl&&r){let c=o.map(d=>d.url).filter(d=>/^https?:\/\//.test(d)),u=c.slice(0,tr);if(c.length>tr&&l.info(`Crawling the first ${tr} of ${c.length} pages (cap).`),u.length>0){l.info(`Crawling ${u.length} page${u.length===1?"":"s"}\u2026`),s=await qi(u);let d=0,p=0;for(let g of s.values())g.rendered==="empty"?d++:g.rendered==="error"&&p++;i={crawled:s.size,empty:d,errors:p}}}let a=jt(e,o,s);return{added:a.added,total:a.total,crawl:i}}catch{return{added:0,total:0}}}async function zd(){let e=Mr();if(e.length===0){l.info("No SEOAgent projects are registered on this machine yet. They register themselves on `init` / `sync`.");return}l.message(`Refreshing ${e.length} project${e.length===1?"":"s"} to SEOAgent ${Ge.bold(E)}\u2026`);let t=0,n=0;for(let r of e){let o=Nn(r);Yi(r);let i=await Hi(r),s=i.added>0?Ge.cyan(` +${i.added} page${i.added===1?"":"s"}`):"";if(o.reason==="refreshed"){t++;let a=o.from&&o.from!==o.to?Ge.dim(` (${o.from} \u2192 ${o.to})`):"";l.message(` ${Ge.green("\u2713")} ${r}${a}${s}`)}else n++,l.message(` ${Ge.yellow("!")} ${r} ${Ge.dim("\u2014 "+o.reason)}${s}`)}l.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${E}.`),n>0&&l.info(`${n} could not be refreshed (see above).`)}function Yi(e){try{he(e)}catch{}}import{spinner as rr,confirm as Vd,isCancel as Jd}from"@clack/prompts";import y from"picocolors";var Vi={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function Xd(e){let t=process.cwd(),n=Sr(t);if(!n){l.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=_(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||A.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?rr():null;a?.start(`Looking up ${y.bold(`"${e.keyword}"`)} ${y.dim("via DataForSEO (free peek)\u2026")}`);let c;try{c=await B(`${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}`,y.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await c.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:c.status,body:u??null})+`
|
|
582
|
+
`);return}if(c.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}.`,y.yellow(`Daily peek quota reached for ${d}.`)),l.message(zi()),process.exitCode=1;return}if(!c.ok||!u){k(a,"error",`Peek failed (${c.status})${u?.error?`: ${u.error}`:""}`,y.red(`Peek failed (${c.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){k(a,"warn","Real keyword data is temporarily unavailable. Try again later.",y.yellow("Real keyword data is temporarily unavailable. Try again later.")),l.message(y.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.",y.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){k(a,"warn",`No data returned for "${e.keyword}".`,y.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(y.green("Got it.")),l.message(Qd(u.opportunity)),u.remaining&&l.message(`${y.dim("Peeks remaining today:")} ${y.bold(String(u.remaining.install))} ${y.dim("\u2014 "+zi())}`)}function Qd(e){let n=u=>y.dim(u.padEnd(14)),r=e.volume!=null?y.bold(String(e.volume)):y.dim("n/a"),o=e.difficulty!=null?`${y.bold(String(e.difficulty))} ${y.dim(Zd(e.difficulty))}`:y.dim("n/a"),i=Vi[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?y.bold(y.green(i)):e.opportunity==="striking_distance"?y.bold(y.cyan(i)):e.opportunity==="competitor_gap"?y.bold(y.yellow(i)):y.dim(i),a=[{content:`${y.green("\u25CF")} ${y.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${y.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],c=`${y.bold(y.cyan("Keyword peek"))}`;return I(a,{width:55,title:c})}function Zd(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function zi(e=j()){return e?`You're logged in \u2014 run \`${f("keywords")}\` for full enrichment (no quota). Pro unlocks the full inventory beyond the ~25 cap plus \`${f("keywords --discover")}\` (new targets) + \`${f("keywords --competitors")}\` (competitor gaps): ${f("upgrade")}.`:`Log in for the full top-25 enrichment, no quota: ${f("login")}`}function nr(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){l.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";l.message(` \u2022 [${Vi[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function ep(e){if(e.length!==0){l.message("Top competitor gaps:");for(let t of e){let n=t.volume!=null?`vol ${t.volume}`:"vol n/a",r=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",o=t.their_position!=null?`#${t.their_position}`:"top 10";l.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${o}, ${n}, ${r}`)}}}async function tp(e){let t=e.all?"all":"suggested";if(t==="all"&&process.stdin.isTTY){let a=await Vd({message:"Delete ALL keywords for this site from the cloud? This cannot be undone."});if(Jd(a)||!a){l.info("No changes.");return}}let n=e.apiBase||e.auth.api_base||A.BASE,r=process.stdout.isTTY?rr():null;r?.start(t==="all"?"Purging all keywords\u2026":"Purging suggested keywords\u2026");let o;try{o=await B(`${n}/api/cli/keywords/purge`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.auth.user_token}:${e.auth.website_token}`},body:JSON.stringify({scope:t})})}catch(a){k(r,"error",`Network error: ${a.message}`,y.red("Network error.")),process.exitCode=1;return}let i=null;try{i=await o.json()}catch{i=null}if(i?.skipped==="no-table"||i?.skipped==="no-columns"){k(r,"warn","Keyword storage isn\u2019t enabled on the server yet.",y.yellow("Nothing to purge yet."));return}if(!o.ok||i?.status!=="ok"){k(r,"error",`Purge failed (${o.status})${i?.error?`: ${i.error}`:""}`,y.red(`Purge failed (${o.status}).`)),process.exitCode=1;return}let s=i.purged??0;k(r,"success",`Purged ${s} ${t==="all"?"":"suggested "}keyword${s===1?"":"s"}.`,y.green(`Purged ${s} keyword${s===1?"":"s"}.`)),l.message(y.dim(t==="all"?"Cleared the cloud inventory. Re-run `seoagent keywords --seed` / strategy to rebuild it.":"Cleared discovery noise. Your clustered keywords were kept."))}async function me(e={}){if(e.peek&&e.peek.trim().length>0){await Xd({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=j();if(!t){l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(e.purge){await tp({all:e.all,apiBase:e.apiBase,auth:t});return}let n=e.apiBase||t.api_base||A.BASE,r=`Bearer ${t.user_token}:${t.website_token}`,o=e.competitors?"competitors":e.discover?"discover":e.seed?"seed":"enrich",i=o==="competitors"?"/api/cli/keywords/competitors":o==="discover"?"/api/cli/keywords/discover":o==="seed"?"/api/cli/keywords/seed":"/api/cli/keywords/enrich",s=o==="competitors"?"Finding keywords your competitors rank for\u2026":o==="discover"?"Discovering new keywords to target\u2026":o==="seed"?"Seeding keywords from your Search Console data\u2026":"Enriching keywords with real volume + difficulty\u2026",c=!!process.stdout.isTTY?rr():null;c?.start(s);let u=o==="competitors"||o==="discover"||o==="seed",d;try{d=await B(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"},u?{timeoutMs:6e4,attempts:1}:{})}catch(m){k(c,"error",`Network error: ${m.message}`,y.red("Network error.")),process.exitCode=1;return}let p=null;try{p=await d.json()}catch{p=null}if(d.status===402||p?.code==="upgrade_required"){k(c,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",y.yellow("Paid feature \u2014 upgrade to continue.")),l.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${y.cyan(A.PRICING)}`:`Upgrade to find new keywords to target: ${y.cyan(A.PRICING)}`),process.exitCode=1;return}if(!d.ok||p?.status!=="ok"){k(c,"error",`Server rejected request (${d.status})${p?.error?`: ${p.error}`:""}`,y.red(`Server rejected request (${d.status}).`)),process.exitCode=1;return}if(p.skipped==="no-gsc-data"){k(c,"warn","No Search Console data to seed from yet. Connect Google Search Console (run `seoagent login` and link GSC) \u2014 or wait for impressions to accrue on a new site.",y.yellow("No Search Console data yet."));return}if(p.skipped==="no-keywords"||p.skipped==="no-seeds"){k(c,"warn","No keywords yet. Seed from Search Console with `seoagent keywords --seed`, or run the keyword strategy (Phase 2) first, then try again.",y.yellow("No keywords yet."));return}if(p.skipped==="no-competitors"){k(c,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",y.yellow("No competitors yet."));return}if(p.skipped==="no-creds"||p.skipped==="no-columns"||p.skipped==="no-table"){k(c,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",y.yellow("Real keyword data is not enabled on the server yet."));return}if(p.skipped){k(c,"warn",`Skipped: ${p.skipped}`,y.yellow(`Skipped: ${p.skipped}`));return}if(o==="competitors"){let m=p.gaps??0;k(c,"success",`Found ${m} competitor gap${m===1?"":"s"} across ${p.competitors?.length??0} competitor${p.competitors?.length===1?"":"s"} (added as "suggested").`,y.green(`${m} competitor gap${m===1?"":"s"} found.`)),ep(p.topGaps??[]),l.message(`Review them in ${y.cyan(".seoagent/keywords.md")} (a read-only projection \u2014 don't hand-edit it). Keep the on-topic ones for your clusters; clear off-topic noise with \`${f("keywords --purge")}\`.`);return}if(o==="discover"){let m=p.discovered??0;k(c,"success",`Discovered ${m} new keyword${m===1?"":"s"} to target (added as "suggested").`,y.green(`${m} new keyword${m===1?"":"s"} discovered.`)),nr(p.opportunities??[]),l.message(`Review them in ${y.cyan(".seoagent/keywords.md")} (a read-only projection \u2014 don't hand-edit it). Relevance-check before adopting; clear off-topic noise with \`${f("keywords --purge")}\`.`);return}if(o==="seed"){let m=p.seeded??0;k(c,"success",`Seeded ${m} keyword${m===1?"":"s"} from Search Console (real impressed queries, added as "suggested").`,y.green(`${m} keyword${m===1?"":"s"} seeded from Search Console.`)),nr(p.opportunities??[]),l.message(`These are queries your site already gets impressions for \u2014 striking-distance wins first. Review in ${y.cyan(".seoagent/keywords.md")} and build clusters from them.`);return}let g=p.enriched??0;k(c,"success",`Enriched ${g} keyword${g===1?"":"s"}.`,y.green(`Enriched ${g} keyword${g===1?"":"s"}.`)),nr(p.opportunities??[]),p.paid||l.message(`${y.dim("Free plan:")} enriched up to ${y.bold(String(p.cap??25))} keywords. ${y.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${y.cyan(A.PRICING)}`)}import P from"picocolors";function mt(e={}){let t=process.cwd(),n=_(t),r=ae(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
|
|
583
|
+
`);return}if(l.message(np(r)),!n){l.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}z(t,{image_provider:r.provider}),l.info(`Saved to ${P.cyan(".seoagent/project.md")} ${P.dim(`(image_provider: ${r.provider})`)}`)}function np(e){let n=i=>P.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${P.dim("\u25CB")} ${P.bold(P.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:P.dim("Set ONE of these to enable image generation:")});let i=eo();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${P.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:P.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${P.cyan(f("env-check"))}`})}else{r.push({content:`${P.green("\u2713")} ${P.dim("Image provider:")} ${P.bold(P.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${P.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${P.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${P.dim(i.join(", "))}`})}let o=`${P.bold(P.cyan("SEOAgent"))} ${P.dim("\xB7")} ${P.dim("env-check")}`;return I(r,{width:64,title:o})}import{existsSync as ir,mkdirSync as Qi,writeFileSync as Zi}from"fs";import{dirname as en,isAbsolute as ap,join as Zt,resolve as cp}from"path";import{tmpdir as lp}from"os";import{spinner as up}from"@clack/prompts";import N from"picocolors";import{Buffer as Ji}from"buffer";async function or(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 Ji.from(n)}async function rp(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:Ji.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await or(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function op(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 or(o.url),contentType:o.content_type??"image/png"}}async function ip(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 sp(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 ip(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 or(o),contentType:"image/png",providerImageId:r.id}}async function Xi(e,t){switch(e){case"openai":return rp(t);case"fal":return op(t);case"replicate":return sp(t);default:throw new Error(`Unknown image provider: ${e}`)}}function dp(e){return e==="openai"||e==="fal"||e==="replicate"}async function gt(e={}){let t=process.cwd();if(!e.prompt){l.warn(`Missing --prompt. Example: ${f('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){l.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=_(t),r=null;if(e.provider){if(!dp(e.provider)){l.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=ae(t).provider;if(!r||r==="none"){l.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${f("env-check")}\`.`),process.exitCode=1;return}let o=Zr(t,r);if(!o){l.warn(`Provider "${r}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=ap(e.out)?e.out:cp(t,e.out),a=!e.silent&&!!process.stdout.isTTY?up():null;a?.start(`Generating image with ${N.bold(r)} ${N.dim(`(${o.envName})`)}\u2026`);try{let c=await Xi(r,{prompt:e.prompt,apiKey:o.key,size:e.size});ir(en(i))||Qi(en(i),{recursive:!0}),Zi(i,c.bytes),e.silent||k(a,"success",`Wrote ${i} (${c.bytes.length} bytes, ${c.contentType}).`,N.green(`Wrote ${i} ${N.dim(`(${c.bytes.length} bytes, ${c.contentType})`)}`))}catch(c){a?.stop(N.red("Image generation failed."));let u=fp(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:c});l.message(pp({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:c.message})),u&&l.message(`${N.dim("Full error log:")} ${N.cyan(u)}`),process.exitCode=1}}function pp(e){let n=d=>N.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${N.red("\u2717")} ${N.bold(N.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${N.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${N.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,c=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:N.red(c)});let u=`${N.bold(N.cyan("SEOAgent"))} ${N.dim("\xB7")} ${N.dim("generate-image")}`;return I(i,{width:70,title:u})}function fp(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=Zt(e,w),i=Zt(o,".errors"),s=ir(o)?Zt(i,r):Zt(lp(),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 ir(en(s))||Qi(en(s),{recursive:!0}),Zi(s,a.join(`
|
|
569
584
|
`)),s}catch{return null}}import G from"picocolors";async function ht(e={}){let t=j();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
|
|
570
585
|
`):l.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||A.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){l.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})}
|
|
571
586
|
`);return}l.warn(`Logged in, but the server at this API base does not support \`/api/cli/whoami\` yet. Update with \`${f("update-cli")}\` (or re-deploy your server).`),l.message(`API base: ${n}`);return}let i=null;try{i=await 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}`})}
|
|
572
587
|
`):l.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)}
|
|
573
|
-
`);return}l.message(fp(i)),i.paid===!1&&l.message(`${G.dim("Upgrade for autopilot:")} ${G.cyan(A.PRICING)}`)}function fp(e){let n=i=>G.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${G.green("\u2713")} ${G.dim("Logged in as")} ${G.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${G.cyan(e.domain)}`}),e.plan){let i=e.paid?G.bold(G.green(e.plan)):G.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${G.dim(e.api_base)}`});let o=`${G.bold(G.cyan("SEOAgent"))} ${G.dim("\xB7")} ${G.dim("whoami")}`;return I(r,{width:55,title:o})}import{select as wt,text as yt,confirm as ts,isCancel as Y,intro as mp,outro as gp}from"@clack/prompts";import tn from"picocolors";function hp(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>Ze()},{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 Je()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await rt()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await ht()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await wt({message:"Which mode?",options:[{value:"peek",label:"peek",hint:"Free, one keyword, no login required"},{value:"enrich",label:"enrich (default)",hint:"Enrich your full strategy (requires login)"},{value:"discover",label:"discover",hint:"Find new keywords to target (paid)"},{value:"competitors",label:"competitors",hint:"Find competitor keyword gaps (paid)"}]});if(!Y(e))if(e==="peek"){let t=await yt({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(Y(t))return;await me({peek:String(t)})}else e==="discover"?await me({discover:!0}):e==="competitors"?await me({competitors:!0}):await me()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>lt({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await wt({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"}]});Y(e)||ut(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 pt()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await yt({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(Y(e))return;let t=await yt({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});Y(t)||await gt({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>mt({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await wt({message:"Autopilot action:",options:[{value:"status",label:"status",hint:"Show current state"},{value:"on",label:"on",hint:"Turn autopilot ON (paid)"},{value:"off",label:"off",hint:"Turn autopilot OFF"}]});Y(e)||await ct(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await xe()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await yt({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(Y(e))return;let t=await ts({message:"Mark as failed instead of completed?",initialValue:!1});if(Y(t))return;let n;if(t===!0){let r=await yt({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(Y(r))return;String(r).trim()&&(n=String(r))}await pe(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 tt()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest + refresh your projects",run:async()=>await nt({})},{command:"refresh",label:"Refresh the skill to your CLI version",hint:"This project \u2014 or every project on the machine via `refresh --all`.",run:async()=>{let e=await wt({message:"Refresh which?",options:[{value:"this",label:"This project",hint:"Just the current directory"},{value:"all",label:"All projects",hint:"Every SEOAgent project on this machine"}]});Y(e)||ft({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>ot()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await Xe({})}]}var Zi="__exit__";async function es(e=hp()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:Zi,label:"Exit",hint:"Close the menu"});let n=await wt({message:"What would you like to do?",options:t});if(Y(n)||n===Zi)return!0;let r=e.find(o=>o.command===n);if(!r)return l.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){l.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function sr(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}mp(`${tn.bold(tn.cyan("SEOAgent"))} ${tn.dim("\xB7 menu")}`);let e=await es();for(;!e;){let t=await ts({message:"Do another?",initialValue:!0});if(Y(t)||t===!1){e=!0;break}e=await es()}gp(tn.dim("See you next time."))}var C=new yp;C.name("seoagent").description("AI SEO agent for Claude Code").version(E).showSuggestionAfterError(!0).showHelpAfterError(!0);C.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=>{Je({yes:e.yes,domain:e.domain,siteType:e.siteType})});C.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=>{Xe({yes:e.yes,global:e.global})});C.command("status").description("Show current SEO project state").action(Ze);C.command("doctor").description("Session-start health check \u2014 surfaces untriaged pull receipts, unknown domain/site_type, and an image key that needs enabling").option("--json","Output findings as JSON (for scripting / the agent)").action(e=>{Yn({json:e.json})});C.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=>{rt({apiBase:e.apiBase})});C.command("logout").description("Remove stored credentials for seoagent.com").action(ot);C.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})});C.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force","Take the cloud version on every conflict (discards local edits)").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{xe({force:e.force,silent:e.silent,print:e.print})});C.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)=>{pe(e,{failed:t.failed,reason:t.reason})});C.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{Dn({json:e.json})});C.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=>{Wn({yes:e.yes,model:e.model})});C.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)=>{ct(e,{apiBase:t.apiBase})});C.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("--seed","Add the queries your site already ranks for (Google Search Console) to the inventory \u2014 additive, keeps existing keywords (requires login + GSC)").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("--purge","Delete suggested keywords (discover/competitors noise) from the cloud inventory").option("--all","With --purge: clear EVERY keyword for this site, not just suggested").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=>{me({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});C.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=>{lt({json:e.json})});C.command("content [action]").description("Track published articles so the dashboard sees them \u2014 `content track` (one) or `content reconcile` (backfill all)").option("--slug <slug>","Article slug (or derive from --file)").option("--url <url>","Live/canonical URL (else built from project domain + blog_path + slug)").option("--file <path>","Repo/CMS source file that renders this article (the body source of truth)").option("--title <title>","Article title (else derived from the slug)").option("--type <page_type>","page_type: landing | pillar | sub_pillar | long_tail | programmatic | blog").option("--status <status>","published (default) | draft").option("--primary-keyword <kw>","Primary keyword for the article").option("--dir <dirs>","reconcile: content dir(s) to scan, comma-separated (else inferred from tracked articles)").option("--prune","reconcile: delete stale pointers whose source file is gone").action((e,t)=>{qn(e,{slug:t.slug,url:t.url,file:t.file,title:t.title,type:t.type,status:t.status,primaryKeyword:t.primaryKeyword,dir:t.dir,prune:t.prune})});C.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)=>{ut(e,{json:t.json})});C.command("sitemap").description("Validate the site\u2019s live sitemap \u2014 reachability, private-route leakage, freshness, and which public repo pages are missing").option("--url <url>","Override the sitemap URL (default https://{domain}/sitemap.xml)").option("--json","Output result as JSON").action(e=>{Jn({url:e.url,json:e.json})});C.command("citations").description("Track whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK, with history, share-of-voice + source-attribution \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--competitors <list>","Comma-separated competitor brands to track for share-of-voice").option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{pt({queries:e.queries,competitors:typeof e.competitors=="string"?e.competitors.split(",").map(t=>t.trim()).filter(Boolean):void 0,model:e.model,json:e.json})});C.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{mt({json:e.json})});C.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=>{gt({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});C.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=>{ht({json:e.json,apiBase:e.apiBase})});C.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(tt);C.command("update-cli").description("Update the SEOAgent CLI to the latest npm version, then refresh every project on this machine").option("--dry-run","Show what would happen without running the install").option("--no-projects","Skip refreshing your other projects after the update").action(e=>{nt({dryRun:e.dryRun,projects:e.projects})});C.command("refresh").description("Refresh the installed skill + re-scan the codebase for new pages. `--all` sweeps every project on this machine.").option("--all","Refresh every registered project, not just this one").option("--crawl","Also fetch each page to fill Status / Rendered / Word count in pages.md (slower)").action(e=>{ft({all:e.all,crawl:e.crawl})});C.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{sr()});process.argv.length===2&&(C.outputHelp(),process.exit(0));C.parse();
|
|
588
|
+
`);return}l.message(mp(i)),i.paid===!1&&l.message(`${G.dim("Upgrade for autopilot:")} ${G.cyan(A.PRICING)}`)}function mp(e){let n=i=>G.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${G.green("\u2713")} ${G.dim("Logged in as")} ${G.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${G.cyan(e.domain)}`}),e.plan){let i=e.paid?G.bold(G.green(e.plan)):G.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${G.dim(e.api_base)}`});let o=`${G.bold(G.cyan("SEOAgent"))} ${G.dim("\xB7")} ${G.dim("whoami")}`;return I(r,{width:55,title:o})}import{select as wt,text as yt,confirm as ns,isCancel as Y,intro as gp,outro as hp}from"@clack/prompts";import tn from"picocolors";function yp(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>Ze()},{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 Je()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await rt()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await ht()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await wt({message:"Which mode?",options:[{value:"peek",label:"peek",hint:"Free, one keyword, no login required"},{value:"enrich",label:"enrich (default)",hint:"Enrich your full strategy (requires login)"},{value:"discover",label:"discover",hint:"Find new keywords to target (paid)"},{value:"competitors",label:"competitors",hint:"Find competitor keyword gaps (paid)"}]});if(!Y(e))if(e==="peek"){let t=await yt({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(Y(t))return;await me({peek:String(t)})}else e==="discover"?await me({discover:!0}):e==="competitors"?await me({competitors:!0}):await me()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>lt({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await wt({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"}]});Y(e)||ut(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 pt()},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await yt({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(Y(e))return;let t=await yt({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});Y(t)||await gt({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>mt({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await wt({message:"Autopilot action:",options:[{value:"status",label:"status",hint:"Show current state"},{value:"on",label:"on",hint:"Turn autopilot ON (paid)"},{value:"off",label:"off",hint:"Turn autopilot OFF"}]});Y(e)||await ct(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await xe()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await yt({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(Y(e))return;let t=await ns({message:"Mark as failed instead of completed?",initialValue:!1});if(Y(t))return;let n;if(t===!0){let r=await yt({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(Y(r))return;String(r).trim()&&(n=String(r))}await pe(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 tt()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest + refresh your projects",run:async()=>await nt({})},{command:"refresh",label:"Refresh the skill to your CLI version",hint:"This project \u2014 or every project on the machine via `refresh --all`.",run:async()=>{let e=await wt({message:"Refresh which?",options:[{value:"this",label:"This project",hint:"Just the current directory"},{value:"all",label:"All projects",hint:"Every SEOAgent project on this machine"}]});Y(e)||ft({all:e==="all"})}},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>ot()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await Xe({})}]}var es="__exit__";async function ts(e=yp()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:es,label:"Exit",hint:"Close the menu"});let n=await wt({message:"What would you like to do?",options:t});if(Y(n)||n===es)return!0;let r=e.find(o=>o.command===n);if(!r)return l.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){l.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function sr(){if(!process.stdin.isTTY){l.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}gp(`${tn.bold(tn.cyan("SEOAgent"))} ${tn.dim("\xB7 menu")}`);let e=await ts();for(;!e;){let t=await ns({message:"Do another?",initialValue:!0});if(Y(t)||t===!1){e=!0;break}e=await ts()}hp(tn.dim("See you next time."))}var C=new wp;C.name("seoagent").description("AI SEO agent for Claude Code").version(E).showSuggestionAfterError(!0).showHelpAfterError(!0);C.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=>{Je({yes:e.yes,domain:e.domain,siteType:e.siteType})});C.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=>{Xe({yes:e.yes,global:e.global})});C.command("status").description("Show current SEO project state").action(Ze);C.command("doctor").description("Session-start health check \u2014 surfaces untriaged pull receipts, unknown domain/site_type, and an image key that needs enabling").option("--json","Output findings as JSON (for scripting / the agent)").action(e=>{Yn({json:e.json})});C.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=>{rt({apiBase:e.apiBase})});C.command("logout").description("Remove stored credentials for seoagent.com").action(ot);C.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})});C.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force","Take the cloud version on every conflict (discards local edits)").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{xe({force:e.force,silent:e.silent,print:e.print})});C.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)=>{pe(e,{failed:t.failed,reason:t.reason})});C.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{Dn({json:e.json})});C.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=>{Wn({yes:e.yes,model:e.model})});C.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)=>{ct(e,{apiBase:t.apiBase})});C.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("--seed","Add the queries your site already ranks for (Google Search Console) to the inventory \u2014 additive, keeps existing keywords (requires login + GSC)").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("--purge","Delete suggested keywords (discover/competitors noise) from the cloud inventory").option("--all","With --purge: clear EVERY keyword for this site, not just suggested").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=>{me({peek:e.peek,seed:e.seed,discover:e.discover,competitors:e.competitors,purge:e.purge,all:e.all,json:e.json,apiBase:e.apiBase})});C.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=>{lt({json:e.json})});C.command("content [action]").description("Track published articles so the dashboard sees them \u2014 `content track` (one) or `content reconcile` (backfill all)").option("--slug <slug>","Article slug (or derive from --file)").option("--url <url>","Live/canonical URL (else built from project domain + blog_path + slug)").option("--file <path>","Repo/CMS source file that renders this article (the body source of truth)").option("--title <title>","Article title (else derived from the slug)").option("--type <page_type>","page_type: landing | pillar | sub_pillar | long_tail | programmatic | blog").option("--status <status>","published (default) | draft").option("--primary-keyword <kw>","Primary keyword for the article").option("--dir <dirs>","reconcile: content dir(s) to scan, comma-separated (else inferred from tracked articles)").option("--prune","reconcile: delete stale pointers whose source file is gone").action((e,t)=>{qn(e,{slug:t.slug,url:t.url,file:t.file,title:t.title,type:t.type,status:t.status,primaryKeyword:t.primaryKeyword,dir:t.dir,prune:t.prune})});C.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)=>{ut(e,{json:t.json})});C.command("sitemap").description("Validate the site\u2019s live sitemap \u2014 reachability, private-route leakage, freshness, and which public repo pages are missing").option("--url <url>","Override the sitemap URL (default https://{domain}/sitemap.xml)").option("--json","Output result as JSON").action(e=>{Jn({url:e.url,json:e.json})});C.command("citations").description("Track whether answer engines cite you (AEO/GEO) \u2014 web-grounded via the Claude Agent SDK, with history, share-of-voice + source-attribution \u2192 .seoagent/citations/scorecard.md").option("--queries <n>","How many answer-engine queries to test (1\u201312, default 6)",e=>parseInt(e,10)).option("--competitors <list>","Comma-separated competitor brands to track for share-of-voice").option("--model <name>","Override the model the Agent SDK uses").option("--json","Also print the parsed report as JSON").action(e=>{pt({queries:e.queries,competitors:typeof e.competitors=="string"?e.competitors.split(",").map(t=>t.trim()).filter(Boolean):void 0,model:e.model,json:e.json})});C.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{mt({json:e.json})});C.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=>{gt({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});C.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=>{ht({json:e.json,apiBase:e.apiBase})});C.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(tt);C.command("update-cli").description("Update the SEOAgent CLI to the latest npm version, then refresh every project on this machine").option("--dry-run","Show what would happen without running the install").option("--no-projects","Skip refreshing your other projects after the update").action(e=>{nt({dryRun:e.dryRun,projects:e.projects})});C.command("refresh").description("Refresh the installed skill + re-scan the codebase for new pages. `--all` sweeps every project on this machine.").option("--all","Refresh every registered project, not just this one").option("--crawl","Also fetch each page to fill Status / Rendered / Word count in pages.md (slower)").action(e=>{ft({all:e.all,crawl:e.crawl})});C.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{sr()});process.argv.length===2&&(C.outputHelp(),process.exit(0));C.parse();
|