@seoagent-official/seoagent 1.51.1 → 1.51.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +13 -13
- package/package.json +1 -1
- package/skills/references/keyword-research.md +10 -0
- package/skills/seoagent.md +2 -0
package/index.js
CHANGED
|
@@ -23,10 +23,10 @@ ${t}`;return n.join(`
|
|
|
23
23
|
`)]),n}function Mi(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 ir(e){let t=[],n=e.split(`
|
|
25
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 Bi(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 cr="context.md";function ur(e){let t=lr(e,".seoagent",cr);if(!Wi(t))return null;let n=Gi(t,"utf-8");return sr(n)}function qi(e,t){let n=lr(e,".seoagent",cr),r=ar(t);Ki(n,r,"utf-8")}function dr(e,t){qi(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as Le,readFileSync as pr,readdirSync as Hi,statSync as fr}from"fs";import{join as le}from"path";var Yi=[{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 zi(e){let t=le(e,"package.json");if(!Le(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(pr(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Vi(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 Ji(e){let t={};for(let n of me){let r=le(e,n);if(Le(r))try{let o=pr(r,"utf-8");for(let i of o.split(/\r?\n/)){let s=i.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a===-1)continue;let l=s.slice(0,a).trim();l&&!(l in t)&&(t[l]=n)}}catch{}}return t}function Qi(e,t){let n=le(e,t.replace(/\/$/,""));if(!Le(n))return!1;if(t.endsWith("/"))try{return fr(n).isDirectory()}catch{return!1}return!0}function Xi(e){let t=["content","_posts","posts",le("src","content")];for(let n of t){let r=le(e,n);if(Le(r))try{if(!fr(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of Hi(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(le(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 Zi(e){let t=[{marker:"app/blog/page.tsx",path:"/blog"},{marker:"app/blog/page.jsx",path:"/blog"},{marker:"app/blog/page.js",path:"/blog"},{marker:"src/app/blog/page.tsx",path:"/blog"},{marker:"src/app/blog/page.jsx",path:"/blog"},{marker:"pages/blog/index.tsx",path:"/blog"},{marker:"pages/blog/index.jsx",path:"/blog"},{marker:"pages/blog/index.js",path:"/blog"},{marker:"src/pages/blog/index.tsx",path:"/blog"},{marker:"app/(blog)/page.tsx",path:"/blog"},{marker:"app/articles/page.tsx",path:"/articles"},{marker:"pages/articles/index.tsx",path:"/articles"},{marker:"app/posts/page.tsx",path:"/posts"},{marker:"pages/posts/index.tsx",path:"/posts"},{marker:"app/learn/page.tsx",path:"/learn"},{marker:"app/resources/page.tsx",path:"/resources"}];for(let n of t)if(Le(le(e,n.marker)))return n.path;return null}function mr(e){let t=[],{deps:n}=zi(e),r=Ji(e),o="none";for(let s of Yi){let a=[];for(let l of Object.keys(n))if(Vi(l,s.deps)){a.push({type:"dep",detail:l,source:"package.json"});break}for(let l of s.envKeys)if(r[l]){a.push({type:"env",detail:l,source:r[l]});break}for(let l of s.fsMarkers)if(Qi(e,l)){let u=l.endsWith("/")?"directory":"file";a.push({type:u,detail:l,source:l});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=Xi(e);s&&(o="mdx-local",t.push(s))}let i=Zi(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as ce,readFileSync as Ht}from"fs";import{join as ue}from"path";function gr(e){try{return new URL(e).hostname}catch{return e}}function hr(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 es(e){for(let t of me){let n=ue(e,t);if(!ce(n))continue;let r=Ht(n,"utf-8");for(let o of In){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=gr(s);if(hr(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function ts(e){let t=ue(e,"package.json");if(!ce(t))return null;try{let n=JSON.parse(Ht(t,"utf-8"));if(!n.homepage)return null;let r=gr(n.homepage);return hr(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function yr(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ce(ue(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=es(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=ts(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=ue(e,"package.json"),s=null;if(ce(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Ht(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>l.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||ce(ue(e,"shopify.config.js"))||ce(ue(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ce(ue(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),m=u("next");d&&(m||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:m?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:r,siteType:s,evidence:n}}import{existsSync as ns,readFileSync as rs,readdirSync as os,statSync as is}from"fs";import{join as de,sep as ss}from"path";var wr=["tsx","jsx","js","mdx","md"],as=["astro","md","mdx"],ls=5e3;function gt(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let l=cs(i);if(l===null){r++;return}let u=n.get(l);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(l,{route:l,url:ws(t,l),in_sitemap:a,source:s})};for(let i of["app",de("src","app")]){let s=de(e,i);if(Yt(s))for(let a of zt(s)){let l=Vt(s,a),u=l[l.length-1];ms(u)&&(l.some(d=>d.startsWith("@"))||o(us(l.slice(0,-1)),"app router"))}}for(let i of["pages",de("src","pages")]){let s=de(e,i);if(Yt(s))for(let a of zt(s)){let l=Vt(s,a);if(l[0]==="api")continue;let u=l[l.length-1],d=Jt(u),p=wr.includes(d),m=as.includes(d);if(!p&&!m)continue;let h=ht(u);gs(h)||o(ds(l),m?"astro":"pages router")}}for(let i of[".","public"]){let s=de(e,i);if(Yt(s))for(let a of zt(s,i==="."?1:1/0)){let l=Vt(s,a),u=l[l.length-1];Jt(u)==="html"&&(l.some(d=>d==="node_modules"||d.startsWith("."))||o(ps(l),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=de(e,...i.split("/"));if(ns(s)){for(let a of hs(s)){let l=fs(a);l!==null&&o(l,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}function cs(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function us(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function ds(e){let t=[...e],n=ht(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function ps(e){let t=[...e],n=ht(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function fs(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function ms(e){return ht(e)==="page"&&wr.includes(Jt(e))}function gs(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function hs(e){try{let t=rs(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 ys=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Yt(e){try{return is(e).isDirectory()}catch{return!1}}function*zt(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=os(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=ls)return;if(a.name.startsWith("."))continue;let l=de(o,a.name);if(a.isDirectory()){if(ys.has(a.name))continue;yield*r(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*r(e,1)}function Vt(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(ss).filter(Boolean)}function Jt(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function ht(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function ws(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as ks,writeFileSync as bs}from"fs";import{join as kr}from"path";function $r(e,t){if(t.length===0)return;let n=kr(e,b);ks(n,{recursive:!0});let r=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
|
|
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 cr="context.md";function ur(e){let t=lr(e,".seoagent",cr);if(!Wi(t))return null;let n=Gi(t,"utf-8");return sr(n)}function qi(e,t){let n=lr(e,".seoagent",cr),r=ar(t);Ki(n,r,"utf-8")}function dr(e,t){qi(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as Le,readFileSync as pr,readdirSync as Hi,statSync as fr}from"fs";import{join as le}from"path";var Yi=[{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 zi(e){let t=le(e,"package.json");if(!Le(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(pr(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Vi(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 Ji(e){let t={};for(let n of me){let r=le(e,n);if(Le(r))try{let o=pr(r,"utf-8");for(let i of o.split(/\r?\n/)){let s=i.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a===-1)continue;let l=s.slice(0,a).trim();l&&!(l in t)&&(t[l]=n)}}catch{}}return t}function Qi(e,t){let n=le(e,t.replace(/\/$/,""));if(!Le(n))return!1;if(t.endsWith("/"))try{return fr(n).isDirectory()}catch{return!1}return!0}function Xi(e){let t=["content","_posts","posts",le("src","content")];for(let n of t){let r=le(e,n);if(Le(r))try{if(!fr(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of Hi(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(le(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 Zi(e){let t=[{marker:"app/blog/page.tsx",path:"/blog"},{marker:"app/blog/page.jsx",path:"/blog"},{marker:"app/blog/page.js",path:"/blog"},{marker:"src/app/blog/page.tsx",path:"/blog"},{marker:"src/app/blog/page.jsx",path:"/blog"},{marker:"pages/blog/index.tsx",path:"/blog"},{marker:"pages/blog/index.jsx",path:"/blog"},{marker:"pages/blog/index.js",path:"/blog"},{marker:"src/pages/blog/index.tsx",path:"/blog"},{marker:"app/(blog)/page.tsx",path:"/blog"},{marker:"app/articles/page.tsx",path:"/articles"},{marker:"pages/articles/index.tsx",path:"/articles"},{marker:"app/posts/page.tsx",path:"/posts"},{marker:"pages/posts/index.tsx",path:"/posts"},{marker:"app/learn/page.tsx",path:"/learn"},{marker:"app/resources/page.tsx",path:"/resources"}];for(let n of t)if(Le(le(e,n.marker)))return n.path;return null}function mr(e){let t=[],{deps:n}=zi(e),r=Ji(e),o="none";for(let s of Yi){let a=[];for(let l of Object.keys(n))if(Vi(l,s.deps)){a.push({type:"dep",detail:l,source:"package.json"});break}for(let l of s.envKeys)if(r[l]){a.push({type:"env",detail:l,source:r[l]});break}for(let l of s.fsMarkers)if(Qi(e,l)){let u=l.endsWith("/")?"directory":"file";a.push({type:u,detail:l,source:l});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=Xi(e);s&&(o="mdx-local",t.push(s))}let i=Zi(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as ce,readFileSync as Ht}from"fs";import{join as ue}from"path";function gr(e){try{return new URL(e).hostname}catch{return e}}function hr(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 es(e){for(let t of me){let n=ue(e,t);if(!ce(n))continue;let r=Ht(n,"utf-8");for(let o of In){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=gr(s);if(hr(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function ts(e){let t=ue(e,"package.json");if(!ce(t))return null;try{let n=JSON.parse(Ht(t,"utf-8"));if(!n.homepage)return null;let r=gr(n.homepage);return hr(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function yr(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ce(ue(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=es(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=ts(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=ue(e,"package.json"),s=null;if(ce(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Ht(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(p=>l.includes(p));if(u("@shopify/hydrogen","@shopify/polaris")||ce(ue(e,"shopify.config.js"))||ce(ue(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ce(ue(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),p=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),h=u("next");d&&(h||p)?(s="saas",n.push({field:"site_type",detail:"saas",source:h?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:r,siteType:s,evidence:n}}import{existsSync as ns,readFileSync as rs,readdirSync as os,statSync as is}from"fs";import{join as de,sep as ss}from"path";var wr=["tsx","jsx","js","mdx","md"],as=["astro","md","mdx"],ls=5e3;function gt(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let l=cs(i);if(l===null){r++;return}let u=n.get(l);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(l,{route:l,url:ws(t,l),in_sitemap:a,source:s})};for(let i of["app",de("src","app")]){let s=de(e,i);if(Yt(s))for(let a of zt(s)){let l=Vt(s,a),u=l[l.length-1];ms(u)&&(l.some(d=>d.startsWith("@"))||o(us(l.slice(0,-1)),"app router"))}}for(let i of["pages",de("src","pages")]){let s=de(e,i);if(Yt(s))for(let a of zt(s)){let l=Vt(s,a);if(l[0]==="api")continue;let u=l[l.length-1],d=Jt(u),p=wr.includes(d),h=as.includes(d);if(!p&&!h)continue;let m=ht(u);gs(m)||o(ds(l),h?"astro":"pages router")}}for(let i of[".","public"]){let s=de(e,i);if(Yt(s))for(let a of zt(s,i==="."?1:1/0)){let l=Vt(s,a),u=l[l.length-1];Jt(u)==="html"&&(l.some(d=>d==="node_modules"||d.startsWith("."))||o(ps(l),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=de(e,...i.split("/"));if(ns(s)){for(let a of hs(s)){let l=fs(a);l!==null&&o(l,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}function cs(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function us(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function ds(e){let t=[...e],n=ht(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function ps(e){let t=[...e],n=ht(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function fs(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function ms(e){return ht(e)==="page"&&wr.includes(Jt(e))}function gs(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function hs(e){try{let t=rs(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 ys=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Yt(e){try{return is(e).isDirectory()}catch{return!1}}function*zt(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=os(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=ls)return;if(a.name.startsWith("."))continue;let l=de(o,a.name);if(a.isDirectory()){if(ys.has(a.name))continue;yield*r(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*r(e,1)}function Vt(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(ss).filter(Boolean)}function Jt(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function ht(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function ws(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as ks,writeFileSync as bs}from"fs";import{join as kr}from"path";function $r(e,t){if(t.length===0)return;let n=kr(e,b);ks(n,{recursive:!0});let r=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
|
|
27
27
|
`),o=["# Pages","","Inventory of pages discovered in your codebase at setup. Status,","rendered, and in-nav are filled in by the Phase 1 audit. Add or remove","rows freely \u2014 this file syncs to the cloud when you log in."].join(`
|
|
28
28
|
`),i="| URL | In sitemap | In nav | Status | Rendered | Notes |",s="|---|---|---|---|---|---|",a=t.map(u=>`| ${br(u.url)} | ${u.in_sitemap?"yes":"no"} | \u2014 | \u2014 | \u2014 | ${br(u.source)} |`),l=[r,"",o,"",i,s,...a,""].join(`
|
|
29
|
-
`);bs(kr(n,"pages.md"),l,"utf-8")}function br(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as ke}from"@clack/prompts";var c={info:e=>ke.info(e),warn:e=>ke.warn(e),error:e=>ke.error(e),success:e=>ke.success(e),step:e=>ke.step(e),message:e=>ke.message(e)};function k(e,t,n,r=n){e?e.stop(r):c[t](n)}var vr=[{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"}],Cr="unknown",_s=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Cs(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 yt(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return _s.has(t)?t:null}async function Ne(e={}){let t=process.cwd();if(Un(t)){let a=x(t),l=ye(t);se(t),B(t,{skill_version:S}),ae(t);let u=_r(wt(t,l.skillFile)),d=l.claudeSymlink?` (symlinked at ${wt(t,l.claudeSymlink)})`:"",p=a?.skill_version&&a.skill_version!==S?`${a.skill_version} \u2192 ${S}`:S;c.success(`Refreshed the SEOAgent skill (${p}).`),c.info("Your `.seoagent/` knowledge was left untouched."),c.info(`Skill at ${u}${d}.`),c.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`);return}let n=!!e.yes||!process.stdin.isTTY;n||$s("SEOAgent \u2014 AI SEO Agent");let r=yr(t,a=>c.step(a)),o=()=>{if(r.evidence.length!==0){c.info("Inferred from your project:");for(let a of r.evidence)c.info(` \u2022 ${Cs(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=yt(e.siteType)||yt(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&yt(e.siteType)===null&&(c.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&yt(process.env.SEOAGENT_SITE_TYPE)===null&&(c.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),o(),i||(c.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=Cr),s||(s="unknown"),await xr(t,i,s);return}if(o(),!i){let a=await Sr({message:"Website domain",placeholder:"example.com",validate:l=>l.trim()?void 0:"Domain is required"});be(a)&&($e("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await Qt({message:"What kind of site is this?",options:[...vr]});be(a)&&($e("Cancelled"),process.exit(0)),s=a}for(;;){let a=await xs({message:`Create .seoagent for ${i} (${s})?`});if(be(a)&&($e("Cancelled"),process.exit(0)),a)break;let l=await Qt({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((be(l)||l==="abort")&&($e("Cancelled"),process.exit(0)),l==="domain"){let u=await Sr({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});be(u)&&($e("Cancelled"),process.exit(0)),i=String(u)}else{let u=await Qt({message:"What kind of site is this?",options:[...vr]});be(u)&&($e("Cancelled"),process.exit(0)),s=u}}await xr(t,i,s)}async function xr(e,t,n){let r=vs();r.start("Setting up your SEO project");let o=mr(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:S,skill_version:S,install_id:Gt(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{}};Gn(e),Bn(e,i),ae(e),dr(e,n),Jn(e);let s=ye(e),a=wt(e,s.skillFile),l=_r(a),u=`${l}/references/audit-checks.md`,d=s.claudeSymlink?wt(e,s.claudeSymlink):void 0;se(e);let p=t!==Cr,
|
|
29
|
+
`);bs(kr(n,"pages.md"),l,"utf-8")}function br(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as ke}from"@clack/prompts";var c={info:e=>ke.info(e),warn:e=>ke.warn(e),error:e=>ke.error(e),success:e=>ke.success(e),step:e=>ke.step(e),message:e=>ke.message(e)};function k(e,t,n,r=n){e?e.stop(r):c[t](n)}var vr=[{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"}],Cr="unknown",_s=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Cs(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 yt(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return _s.has(t)?t:null}async function Ne(e={}){let t=process.cwd();if(Un(t)){let a=x(t),l=ye(t);se(t),B(t,{skill_version:S}),ae(t);let u=_r(wt(t,l.skillFile)),d=l.claudeSymlink?` (symlinked at ${wt(t,l.claudeSymlink)})`:"",p=a?.skill_version&&a.skill_version!==S?`${a.skill_version} \u2192 ${S}`:S;c.success(`Refreshed the SEOAgent skill (${p}).`),c.info("Your `.seoagent/` knowledge was left untouched."),c.info(`Skill at ${u}${d}.`),c.info(`Run \`${f("status")}\` to see your project, or \`${f("uninstall")}\` to start fresh.`);return}let n=!!e.yes||!process.stdin.isTTY;n||$s("SEOAgent \u2014 AI SEO Agent");let r=yr(t,a=>c.step(a)),o=()=>{if(r.evidence.length!==0){c.info("Inferred from your project:");for(let a of r.evidence)c.info(` \u2022 ${Cs(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=yt(e.siteType)||yt(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&yt(e.siteType)===null&&(c.warn("Invalid --site-type. Use: saas, service, product, content, marketplace, tool, nonprofit, unknown, app, community."),process.exit(1)),process.env.SEOAGENT_SITE_TYPE?.trim()&&yt(process.env.SEOAGENT_SITE_TYPE)===null&&(c.warn("Invalid SEOAGENT_SITE_TYPE environment value."),process.exit(1)),o(),i||(c.info("Couldn't detect your site URL from this repo \u2014 scaffolding anyway; you'll be prompted to supply it."),i=Cr),s||(s="unknown"),await xr(t,i,s);return}if(o(),!i){let a=await Sr({message:"Website domain",placeholder:"example.com",validate:l=>l.trim()?void 0:"Domain is required"});be(a)&&($e("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await Qt({message:"What kind of site is this?",options:[...vr]});be(a)&&($e("Cancelled"),process.exit(0)),s=a}for(;;){let a=await xs({message:`Create .seoagent for ${i} (${s})?`});if(be(a)&&($e("Cancelled"),process.exit(0)),a)break;let l=await Qt({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((be(l)||l==="abort")&&($e("Cancelled"),process.exit(0)),l==="domain"){let u=await Sr({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});be(u)&&($e("Cancelled"),process.exit(0)),i=String(u)}else{let u=await Qt({message:"What kind of site is this?",options:[...vr]});be(u)&&($e("Cancelled"),process.exit(0)),s=u}}await xr(t,i,s)}async function xr(e,t,n){let r=vs();r.start("Setting up your SEO project");let o=mr(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:S,skill_version:S,install_id:Gt(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{}};Gn(e),Bn(e,i),ae(e),dr(e,n),Jn(e);let s=ye(e),a=wt(e,s.skillFile),l=_r(a),u=`${l}/references/audit-checks.md`,d=s.claudeSymlink?wt(e,s.claudeSymlink):void 0;se(e);let p=t!==Cr,h={pages:[],dynamicCount:0};try{h=gt(e,p?t:null),$r(e,h.pages)}catch{}if(r.stop(p?`Created .seoagent/ project for ${i.domain}`:"Created .seoagent/ project (site URL not detected yet \u2014 see step 2)"),o.cms!=="none"){let I=o.evidence.map(K=>`${K.detail} (${K.source})`).slice(0,2).join(", ");c.info(`CMS detected: ${o.cms} \u2014 ${I}`)}o.blog_path&&c.info(`Blog route: ${o.blog_path}`),h.pages.length>0&&c.info(`Found ${h.pages.length} page${h.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`+(h.dynamicCount>0?` (plus ${h.dynamicCount} dynamic route template${h.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""));let m=p?i.domain:"your site",C=p?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${i.domain} and update project.md with the right type`," before you suggest the audit."]:[" 1. Heads up: .seoagent/project.md has `domain: unknown` \u2014 the site URL"," wasn't detectable from this repo. Please ask your human for their"," domain (or read it from a deploy config / live site) and update"," project.md (`domain:` and `site_type:`) first. Everything else"," depends on it."];Ss([p?`\u2713 SEOAgent installed for ${i.domain}.`:"\u2713 SEOAgent installed (site URL not detected \u2014 please ask the user for it).","","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," AGENT INSTRUCTIONS \u2014 a friendly note for Claude Code, Codex, Cursor","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Hi there, coding agent! \u{1F44B} SEOAgent is all set up. The natural next step"," is a quick SEO audit \u2014 but your human is the boss here, so please surface"," what's possible and let THEM decide. Nothing in this message is a command;"," it's just a friendly map. Your real instructions live in the skill:","",` ${a} \u2190 read this; it is your source of truth`,""," If your human approves, here is what you can do (otherwise just let them"," know it's ready and wait for the go-ahead):","",...C,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${m}`," (homepage + sitemap + robots.txt; the checks live in",` ${u} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${f("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${a} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${l} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${f("login")}`,""].join(`
|
|
30
30
|
`))}import{existsSync as Ir}from"fs";import{intro as As,outro as Is,confirm as Rs,isCancel as Ps,cancel as Os}from"@clack/prompts";import{existsSync as kt,rmSync as Es}from"fs";import{join as bt}from"path";function Er(e,t={}){let n=[],r=bt(e,b);kt(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=bt(e,ie.CLAUDE);kt(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=bt(e,ie.AGENTS);return kt(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),Xn(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:bt(e,".claude","settings.json"),kind:"hook"}),t.global&&kt(F)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:F,kind:"global"}),n}function Ar(e,t){for(let n of t)n.kind==="hook"?Zn(e):Es(n.path,{recursive:!0,force:!0})}async function Fe(e={}){let t=process.cwd(),n=Er(t,{global:e.global});if(n.length===0){c.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&Ir(F)&&c.info("Your seoagent.com login is still stored at ~/.config/seoagent/. Re-run with --global to wipe it too.");return}let r=!!e.yes||!process.stdin.isTTY,o=n.map(s=>` \u2022 ${s.label}`).join(`
|
|
31
31
|
`);if(!r){As("SEOAgent \u2014 uninstall"),c.message(`This will remove:
|
|
32
32
|
${o}`);let s=await Rs({message:"Remove these and start fresh?"});if(Ps(s)||!s){Os("Cancelled \u2014 nothing was removed.");return}}Ar(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
|
|
@@ -34,7 +34,7 @@ ${o}`);let s=await Rs({message:"Remove these and start fresh?"});if(Ps(s)||!s){O
|
|
|
34
34
|
${i}`):Is(`Removed:
|
|
35
35
|
${i}`),!e.global&&Ir(F)&&c.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),c.info(`Re-install any time with \`${f("init")}\`.`)}import $ from"picocolors";import{existsSync as Pr,mkdirSync as Rr,readFileSync as Ts,writeFileSync as js,chmodSync as Ls,unlinkSync as Ns}from"fs";import{dirname as Fs}from"path";function P(){if(!Pr(Q))return null;try{let e=JSON.parse(Ts(Q,"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||Pe}}catch{return null}}function Or(e){Rr(F,{recursive:!0}),Rr(Fs(Q),{recursive:!0}),js(Q,JSON.stringify(e,null,2)+`
|
|
36
36
|
`,"utf-8");try{Ls(Q,384)}catch{}}function Tr(){if(!Pr(Q))return!1;try{return Ns(Q),!0}catch{return!1}}import{existsSync as De,readdirSync as Xt,statSync as Ds,readFileSync as jr}from"fs";import{join as Se}from"path";function Us(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function Ms(e){let t=Se(e,"audit","latest.md");if(!De(t))return null;let n=ct(t);if(!n)return null;let r=jr(t,"utf-8"),o=Us(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function Bs(e){try{let n=jr(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 Gs(e){let t=Se(e,"strategy","clusters");if(!De(t))return null;let n=Xt(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=Bs(Se(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function Ks(e){let t=Se(e,"briefs");if(!De(t))return null;let n=Xt(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Ws(e){let t=Se(e,"content");if(!De(t))return null;let n=Xt(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function qs(e){let t=Se(e,"roadmap.md");return De(t)?{exists:!0,updatedAt:Ds(t).mtime.toISOString()}:null}function Lr(e){let t=x(e);if(!t)return null;let n=Te(e);return{domain:t.domain,audit:Ms(n),strategy:Gs(n),briefs:Ks(n),content:Ws(n),roadmap:qs(n)}}import X from"picocolors";var Hs=/\x1b\[[0-9;]*m/g;function Nr(e){return e.replace(Hs,"").length}function O(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=Ys(n,t.title),s=X.dim(`\u251C${o}\u2524`),a=X.dim(`\u2514${o}\u2518`),l=[i];for(let u of e){if("sep"in u){l.push(s);continue}l.push(zs(u.content,r))}return l.push(a),l.join(`
|
|
37
|
-
`)}function Ys(e,t){if(!t)return X.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Nr(t),r=e-5-n;return r<1?X.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${X.dim("\u250C\u2500 ")}${t}${X.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function zs(e,t){let n=Nr(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${X.dim("\u2502")} ${r} ${X.dim("\u2502")}`}function Zt(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 Ue(){let e=Lr(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${f("init")}\` to get started.`);return}c.message(Vs(e))}function Vs(e){if(!e)return"";let t=11,n=s=>$.dim(s.padEnd(t)),r=[];P()?(r.push({content:`${$.green("\u2713")} ${$.dim("Logged in")}`}),r.push({content:$.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${$.dim("\u25CB Not logged in")}`}),r.push({content:$.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${$.green(`last run ${Zt(e.audit.date??"")}`)} ${$.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${$.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${$.bold($.cyan(String(e.strategy.clusterCount??0)))} ${$.dim("clusters")} \xB7 ${$.bold($.cyan(String(e.strategy.articleCount??0)))} ${$.dim("ideas")}`:`${n("Strategy:")}${$.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${$.bold($.cyan(String(e.briefs.count??0)))} ${$.dim("ready")}`:`${n("Briefs:")}${$.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${$.green("\u2713")} ${$.bold($.cyan(String(e.content.count??0)))} ${$.dim("articles written")}`:`${n("Content:")}${$.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${$.green("updated")} ${$.dim(Zt(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${$.dim("not yet created")}`});let i=`${$.bold($.cyan("SEOAgent"))} ${$.dim("\xB7")} ${$.bold(e.domain)}`;return O(r,{width:78,title:i})}import{exec as Js,spawn as Fr}from"child_process";import{confirm as Qs,isCancel as Xs}from"@clack/prompts";import L from"picocolors";function ve(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 Zs="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Me="@seoagent-official/seoagent",Be=["free","starter","pro","scale","enterprise"],$t={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function ea(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return Be.includes(t)?t:null}function ta(e){let t=Be.indexOf(e);return t===-1||t===Be.length-1?null:Be[t+1]}async function na(e,t=fetch){if(!e)return null;try{let n=(e.api_base||_.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 ra(e){let t=[],r=s=>L.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${L.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${L.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of Be){let a=$t[s];s===e.current?t.push({content:`${L.bold(L.green("\u25CF"))} ${L.bold(L.green(a.padEnd(11)))} ${L.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${L.yellow("\u25C6")} ${L.bold(L.yellow(a.padEnd(11)))} ${L.yellow("next tier")}`}):t.push({content:L.dim(` ${a}`)})}let i=`${L.bold(L.cyan("SEOAgent Cloud"))} ${L.dim("\xB7")} ${L.dim("your plan")}`;return O(t,{width:55,title:i})}async function Ge(){let e=P(),t=!!process.stdin.isTTY;if(e&&t){let n=await na(e);if(n){let r=ea(n.plan),o=r?ta(r):null;if(r&&c.message(ra({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){c.success(`You're on ${$t[r]} (highest tier).`);return}if(r&&o){let i=await Qs({message:`Upgrade from ${$t[r]} to ${$t[o]}?`});if(Xs(i)||!i){c.info("No changes.");return}}}}oa()}function oa(){let e=ia();c.info("Opening SEOAgent Cloud pricing..."),c.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;Js(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function ia(){let e=process.cwd(),t=x(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${_.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ke(e={}){let t=S,n=await aa();if(!n){c.warn("Couldn't reach the npm registry to check for a newer version."),c.message(`You're on ${t}. To force-update: npm install -g ${Me}@latest`);return}if(ve(t,n)>=0){c.success(`You're on the latest CLI (${t}).`);return}if(!Dt()){c.info(`A newer CLI is available: ${t} \u2192 ${n}.`),c.message("You're running via npx \u2014 it already fetches the latest on every run."),c.message(`For a bare \`seoagent <cmd>\` form, install globally once: npm install -g ${Me}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${Me}@latest`);return}if(c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await la()){c.error(`Update failed. Try manually: npm install -g ${Me}@latest (you may need sudo on Linux/macOS).`);return}if(c.success(`Updated to ${n}.`),e.projects===!1){c.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}c.info("Refreshing your other projects to the new version\u2026"),await sa()||c.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 sa(){return new Promise(e=>{try{let t=Fr("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function aa(e=fetch){try{let t=await e(Zs,{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 la(){return new Promise(e=>{let t=Fr("npm",["install","-g",`${Me}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as ca}from"child_process";import{randomBytes as ua}from"crypto";import{isCancel as da,spinner as pa,text as fa}from"@clack/prompts";import Z from"picocolors";function Dr(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 ma=1500,ga=300*1e3;function ha(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;ca(t,()=>{})}function ya(){return ua(16).toString("hex")}function wa(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function Ur(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 ka(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 Dr(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function ba(e){return new Promise(t=>setTimeout(t,e))}async function We(e={}){let t=process.cwd(),n=x(t),r=(e.apiBase||_.BASE||Pe).replace(/\/$/,"");if(P()){c.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let p=await fa({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(h){if(!String(h??"").trim())return"A site URL is required.";if(!Ur(String(h)))return"Please enter a valid domain like `example.com`."}});if(da(p)){c.warn("Login cancelled.");return}let m=Ur(String(p));if(m){o=m;try{B(t,{domain:m}),c.success(`Saved domain: ${m} \u2192 .seoagent/project.md`)}catch{}}}let i=ya(),s=wa(r,i,o);c.message("Opening seoagent.com to connect this CLI to your account..."),c.info(`If the browser does not open, visit: ${s}`),ha(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?pa():null;l?.start(Z.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+ga,d=!0;for(;Date.now()<u;){d||await ba(ma),d=!1;let p=await ka(r,i);if(p.status==="ready"){Or({user_token:p.user_token,website_token:p.website_token,api_base:r});let m=p.email&&p.domain?`Logged in as ${p.email} (${p.domain}). Future SEO work in this repo will sync to your dashboard.`:p.email?`Logged in as ${p.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",h=p.email&&p.domain?`Logged in as ${Z.bold(p.email)} (${Z.cyan(p.domain)}).`:p.email?`Logged in as ${Z.bold(p.email)}.`:"Logged in.";k(l,"success",m,Z.green(h)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){k(l,"warn",`Session expired. Run \`${f("login")}\` again.`,Z.red("Session expired.")),l&&c.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){k(l,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,Z.red(`Login failed: ${p.message}.`)),l&&c.warn(`Run \`${f("login")}\` again.`);return}continue}}k(l,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,Z.yellow("Login timed out.")),l&&c.warn(`Run \`${f("login")}\` again to retry.`)}function qe(){Tr()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as Kl}from"@clack/prompts";import ee from"picocolors";import{existsSync as an,mkdirSync as pl,readFileSync as co,readdirSync as fl,statSync as ml,writeFileSync as gl}from"fs";import{join as ln,relative as hl,sep as yl}from"path";var $a=new Set([502,503,504]),Sa=1e4;async function z(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??va,l=n.transientStatuses??$a,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:m}=xa(t,i);try{let h=await s(e,p);if(l.has(h.status)&&d<r-1){await a(Mr(o,d));continue}return h}catch(h){if(u=h,d<r-1){await a(Mr(o,d));continue}}finally{m()}}throw u instanceof Error?u:new Error(String(u))}function Mr(e,t){return e*Math.pow(3,t)}function va(e){return new Promise(t=>setTimeout(t,e))}function xa(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}}import{existsSync as tn,mkdirSync as _a,readdirSync as Br,readFileSync as Ca,unlinkSync as Ea,writeFileSync as en}from"fs";import{join as _e}from"path";import R from"picocolors";function V(e){return _e(e,b,"inbox")}function Gr(e){return`${e.action_type}-${e.id}.md`}function Aa(e,t){let n=0;if(!tn(e))return 0;for(let r of Br(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{Ea(_e(e,r)),n++}catch{}}return n}function Ia(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`---
|
|
37
|
+
`)}function Ys(e,t){if(!t)return X.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Nr(t),r=e-5-n;return r<1?X.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${X.dim("\u250C\u2500 ")}${t}${X.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function zs(e,t){let n=Nr(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${X.dim("\u2502")} ${r} ${X.dim("\u2502")}`}function Zt(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 Ue(){let e=Lr(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${f("init")}\` to get started.`);return}c.message(Vs(e))}function Vs(e){if(!e)return"";let t=11,n=s=>$.dim(s.padEnd(t)),r=[];P()?(r.push({content:`${$.green("\u2713")} ${$.dim("Logged in")}`}),r.push({content:$.dim(` Run \`${f("whoami")}\` for email / plan.`)})):(r.push({content:`${$.dim("\u25CB Not logged in")}`}),r.push({content:$.dim(` Run \`${f("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${$.green(`last run ${Zt(e.audit.date??"")}`)} ${$.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${$.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${$.bold($.cyan(String(e.strategy.clusterCount??0)))} ${$.dim("clusters")} \xB7 ${$.bold($.cyan(String(e.strategy.articleCount??0)))} ${$.dim("ideas")}`:`${n("Strategy:")}${$.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${$.bold($.cyan(String(e.briefs.count??0)))} ${$.dim("ready")}`:`${n("Briefs:")}${$.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${$.green("\u2713")} ${$.bold($.cyan(String(e.content.count??0)))} ${$.dim("articles written")}`:`${n("Content:")}${$.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${$.green("updated")} ${$.dim(Zt(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${$.dim("not yet created")}`});let i=`${$.bold($.cyan("SEOAgent"))} ${$.dim("\xB7")} ${$.bold(e.domain)}`;return O(r,{width:78,title:i})}import{exec as Js,spawn as Fr}from"child_process";import{confirm as Qs,isCancel as Xs}from"@clack/prompts";import L from"picocolors";function ve(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 Zs="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Me="@seoagent-official/seoagent",Be=["free","starter","pro","scale","enterprise"],$t={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function ea(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return Be.includes(t)?t:null}function ta(e){let t=Be.indexOf(e);return t===-1||t===Be.length-1?null:Be[t+1]}async function na(e,t=fetch){if(!e)return null;try{let n=(e.api_base||_.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 ra(e){let t=[],r=s=>L.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${L.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${L.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of Be){let a=$t[s];s===e.current?t.push({content:`${L.bold(L.green("\u25CF"))} ${L.bold(L.green(a.padEnd(11)))} ${L.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${L.yellow("\u25C6")} ${L.bold(L.yellow(a.padEnd(11)))} ${L.yellow("next tier")}`}):t.push({content:L.dim(` ${a}`)})}let i=`${L.bold(L.cyan("SEOAgent Cloud"))} ${L.dim("\xB7")} ${L.dim("your plan")}`;return O(t,{width:55,title:i})}async function Ge(){let e=P(),t=!!process.stdin.isTTY;if(e&&t){let n=await na(e);if(n){let r=ea(n.plan),o=r?ta(r):null;if(r&&c.message(ra({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){c.success(`You're on ${$t[r]} (highest tier).`);return}if(r&&o){let i=await Qs({message:`Upgrade from ${$t[r]} to ${$t[o]}?`});if(Xs(i)||!i){c.info("No changes.");return}}}}oa()}function oa(){let e=ia();c.info("Opening SEOAgent Cloud pricing..."),c.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;Js(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function ia(){let e=process.cwd(),t=x(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${_.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Ke(e={}){let t=S,n=await aa();if(!n){c.warn("Couldn't reach the npm registry to check for a newer version."),c.message(`You're on ${t}. To force-update: npm install -g ${Me}@latest`);return}if(ve(t,n)>=0){c.success(`You're on the latest CLI (${t}).`);return}if(!Dt()){c.info(`A newer CLI is available: ${t} \u2192 ${n}.`),c.message("You're running via npx \u2014 it already fetches the latest on every run."),c.message(`For a bare \`seoagent <cmd>\` form, install globally once: npm install -g ${Me}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${Me}@latest`);return}if(c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),!await la()){c.error(`Update failed. Try manually: npm install -g ${Me}@latest (you may need sudo on Linux/macOS).`);return}if(c.success(`Updated to ${n}.`),e.projects===!1){c.info("Skipped project refresh (--no-projects). Each project updates itself on its next sync.");return}c.info("Refreshing your other projects to the new version\u2026"),await sa()||c.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 sa(){return new Promise(e=>{try{let t=Fr("seoagent",["refresh","--all"],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))}catch{e(!1)}})}async function aa(e=fetch){try{let t=await e(Zs,{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 la(){return new Promise(e=>{let t=Fr("npm",["install","-g",`${Me}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as ca}from"child_process";import{randomBytes as ua}from"crypto";import{isCancel as da,spinner as pa,text as fa}from"@clack/prompts";import Z from"picocolors";function Dr(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 ma=1500,ga=300*1e3;function ha(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;ca(t,()=>{})}function ya(){return ua(16).toString("hex")}function wa(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function Ur(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 ka(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 Dr(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function ba(e){return new Promise(t=>setTimeout(t,e))}async function We(e={}){let t=process.cwd(),n=x(t),r=(e.apiBase||_.BASE||Pe).replace(/\/$/,"");if(P()){c.info(`Already logged in. To switch accounts, run \`${f("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let p=await fa({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(!Ur(String(m)))return"Please enter a valid domain like `example.com`."}});if(da(p)){c.warn("Login cancelled.");return}let h=Ur(String(p));if(h){o=h;try{B(t,{domain:h}),c.success(`Saved domain: ${h} \u2192 .seoagent/project.md`)}catch{}}}let i=ya(),s=wa(r,i,o);c.message("Opening seoagent.com to connect this CLI to your account..."),c.info(`If the browser does not open, visit: ${s}`),ha(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?pa():null;l?.start(Z.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+ga,d=!0;for(;Date.now()<u;){d||await ba(ma),d=!1;let p=await ka(r,i);if(p.status==="ready"){Or({user_token:p.user_token,website_token:p.website_token,api_base:r});let h=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 ${Z.bold(p.email)} (${Z.cyan(p.domain)}).`:p.email?`Logged in as ${Z.bold(p.email)}.`:"Logged in.";k(l,"success",h,Z.green(m)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(p.status==="expired"){k(l,"warn",`Session expired. Run \`${f("login")}\` again.`,Z.red("Session expired.")),l&&c.warn(`Run \`${f("login")}\` again.`);return}if(p.status==="error"){if(p.terminal){k(l,"warn",`Login failed: ${p.message}. Run \`${f("login")}\` again.`,Z.red(`Login failed: ${p.message}.`)),l&&c.warn(`Run \`${f("login")}\` again.`);return}continue}}k(l,"warn",`Login timed out. Run \`${f("login")}\` again to retry.`,Z.yellow("Login timed out.")),l&&c.warn(`Run \`${f("login")}\` again to retry.`)}function qe(){Tr()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as Kl}from"@clack/prompts";import ee from"picocolors";import{existsSync as an,mkdirSync as pl,readFileSync as co,readdirSync as fl,statSync as ml,writeFileSync as gl}from"fs";import{join as ln,relative as hl,sep as yl}from"path";var $a=new Set([502,503,504]),Sa=1e4;async function z(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??va,l=n.transientStatuses??$a,u=null;for(let d=0;d<r;d++){let{init:p,cleanup:h}=xa(t,i);try{let m=await s(e,p);if(l.has(m.status)&&d<r-1){await a(Mr(o,d));continue}return m}catch(m){if(u=m,d<r-1){await a(Mr(o,d));continue}}finally{h()}}throw u instanceof Error?u:new Error(String(u))}function Mr(e,t){return e*Math.pow(3,t)}function va(e){return new Promise(t=>setTimeout(t,e))}function xa(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}}import{existsSync as tn,mkdirSync as _a,readdirSync as Br,readFileSync as Ca,unlinkSync as Ea,writeFileSync as en}from"fs";import{join as _e}from"path";import R from"picocolors";function V(e){return _e(e,b,"inbox")}function Gr(e){return`${e.action_type}-${e.id}.md`}function Aa(e,t){let n=0;if(!tn(e))return 0;for(let r of Br(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{Ea(_e(e,r)),n++}catch{}}return n}function Ia(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`---
|
|
38
38
|
action_id: ${e.id}
|
|
39
39
|
action_type: ${e.action_type}
|
|
40
40
|
article_id: ${n}
|
|
@@ -334,7 +334,7 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
|
|
|
334
334
|
|
|
335
335
|
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
336
336
|
skill knows what to do.
|
|
337
|
-
`}function pe(e){let t=V(e);if(!tn(t))return[];let n=[];for(let r of Br(t)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(.+)-(\d+)\.md$/);if(!o)continue;let i=o[1],s=Number.parseInt(o[2],10);if(!Number.isFinite(s))continue;let a="no title",l=null,u=null,d=null,p=null,
|
|
337
|
+
`}function pe(e){let t=V(e);if(!tn(t))return[];let n=[];for(let r of Br(t)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(.+)-(\d+)\.md$/);if(!o)continue;let i=o[1],s=Number.parseInt(o[2],10);if(!Number.isFinite(s))continue;let a="no title",l=null,u=null,d=null,p=null,h=null,m=null;try{let C=Ca(_e(t,r),"utf-8"),I=C.match(/^---\n([\s\S]*?)\n---/);if(I){let W=I[1];l=xe(W,"severity"),u=xe(W,"issue"),d=xe(W,"page_url");let oe=xe(W,"priority");(oe==="high"||oe==="medium"||oe==="low")&&(p=oe),h=xe(W,"impact_estimate"),m=xe(W,"effort_estimate")}let E=C.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);E&&(a=E[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:l,issue:u,page_url:d,priority:p,impact_estimate:h,effort_estimate:m})}return n.sort((r,o)=>r.id-o.id)}function Ce(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Ua[e.severity??""]??R.dim,r=e.severity??"unknown",o=[R.dim("\u25B8"),R.bold(`id ${e.id}`),R.dim("\xB7"),R.cyan(t),n(r)];if(e.priority){let i=Ma[e.priority];o.push(R.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(R.dim("\xB7"),R.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(R.dim("\xB7"),R.dim(`\u23F1 ${e.effort_estimate}`)),o.push(R.dim("\u2014"),e.title),o.join(" ")}var Ua={critical:e=>R.red(R.bold(e)),high:e=>R.red(e),medium:e=>R.yellow(e),low:e=>R.dim(e)},Ma={high:e=>R.red(R.bold(e)),medium:e=>R.yellow(e),low:e=>R.dim(e)};function xe(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 St(e){let t=V(e);if(!tn(t))return;let n=pe(e),r=n.length===0?`# SEOAgent Inbox
|
|
338
338
|
|
|
339
339
|
No pending actions. Run \`seoagent sync\` later to check for new ones.
|
|
340
340
|
`:`# SEOAgent Inbox
|
|
@@ -349,13 +349,13 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
|
|
|
349
349
|
|
|
350
350
|
If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
|
|
351
351
|
skill knows what to do.
|
|
352
|
-
`;en(_e(t,"README.md"),r,"utf-8")}function Kr(e,t){let n=V(e);_a(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=Aa(n,r),i=0;for(let s of t){let a=Fa(s);a!==null&&(en(_e(n,Gr(s)),a,"utf-8"),i++)}return en(_e(n,"README.md"),Da(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as Ka}from"crypto";import{existsSync as Hr,mkdirSync as Wa,readFileSync as qa,statSync as Yr,writeFileSync as qr,rmSync as Ha}from"fs";import{dirname as Ya,join as nn,sep as za}from"path";function Ba(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Ga=[{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 Wr(e,t){let n=Ba(e);for(let{cls:r,test:o}of Ga)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function Va(e){return"sha256:"+Ka("sha256").update(e).digest("hex")}function Ja(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 Qa(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:Wr(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 zr(e){let t=await Jr({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 Vr(e,t){return nn(e,t.split("/").join(za))}function Xa(e,t,n){let r={};for(let o of t){let i=Vr(e,o);if(!Hr(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=Yr(i),a=n[o],l=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:Va(qa(i,"utf-8")),locallyEdited:l}}return r}async function Jr(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 Qr(e){let t=nn(e.projectDir,b),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!Hr(t))return{...n,ok:!0};let r=await Jr({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=Xa(t,i,e.stateFiles),a=Ja(o,s,{force:e.force}),l={...n,cursor:o.now};for(let d of a){let p=Vr(t,d.path);try{switch(d.kind){case"skip":l.skipped++;break;case"write":case"overwrite":{Wa(Ya(p),{recursive:!0}),qr(p,d.body??"","utf-8");let
|
|
352
|
+
`;en(_e(t,"README.md"),r,"utf-8")}function Kr(e,t){let n=V(e);_a(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=Aa(n,r),i=0;for(let s of t){let a=Fa(s);a!==null&&(en(_e(n,Gr(s)),a,"utf-8"),i++)}return en(_e(n,"README.md"),Da(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as Ka}from"crypto";import{existsSync as Hr,mkdirSync as Wa,readFileSync as qa,statSync as Yr,writeFileSync as qr,rmSync as Ha}from"fs";import{dirname as Ya,join as nn,sep as za}from"path";function Ba(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Ga=[{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 Wr(e,t){let n=Ba(e);for(let{cls:r,test:o}of Ga)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function Va(e){return"sha256:"+Ka("sha256").update(e).digest("hex")}function Ja(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 Qa(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:Wr(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 zr(e){let t=await Jr({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 Vr(e,t){return nn(e,t.split("/").join(za))}function Xa(e,t,n){let r={};for(let o of t){let i=Vr(e,o);if(!Hr(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=Yr(i),a=n[o],l=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:Va(qa(i,"utf-8")),locallyEdited:l}}return r}async function Jr(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 Qr(e){let t=nn(e.projectDir,b),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!Hr(t))return{...n,ok:!0};let r=await Jr({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=Xa(t,i,e.stateFiles),a=Ja(o,s,{force:e.force}),l={...n,cursor:o.now};for(let d of a){let p=Vr(t,d.path);try{switch(d.kind){case"skip":l.skipped++;break;case"write":case"overwrite":{Wa(Ya(p),{recursive:!0}),qr(p,d.body??"","utf-8");let h=Yr(p);e.stateFiles[d.path]={mtime:h.mtimeMs,size:h.size},d.kind==="write"?l.written++:l.overwritten++,d.note&&l.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":Ha(p,{force:!0}),delete e.stateFiles[d.path],l.deleted++;break;case"delete-skipped":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(h){l.ok=!1,l.error=`${d.path}: ${h.message}`}}(l.conflicts>0||!l.ok)&&(l.cursor=e.since);let u=Qa(a,o,l.cursor,new Date().toISOString());if(u)try{qr(nn(t,Pn),JSON.stringify(u,null,2)+`
|
|
353
353
|
`,"utf-8")}catch{}return l}import{existsSync as Zr,mkdirSync as eo,readFileSync as Za,writeFileSync as rn}from"fs";import{dirname as to,join as el}from"path";var on=1,Xr=500;function sn(e){return el(e,b,On)}function vt(e){let t=sn(e);if(!Zr(t))return[];try{let n=Za(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(tl)}catch{return[]}}function no(e,t){let n=sn(e),o=vt(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>Xr?o.slice(-Xr):o,s={version:on,entries:i};try{eo(to(n),{recursive:!0}),rn(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function ro(e,t){if(t.length===0)return;let n=sn(e),r=vt(e).filter(i=>!t.includes(i.action_id)),o={version:on,entries:r};try{if(r.length===0&&Zr(n)){rn(n,JSON.stringify(o,null,2),"utf-8");return}eo(to(n),{recursive:!0}),rn(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function tl(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 oo,readFileSync as nl,unlinkSync as rl,writeFileSync as ol,openSync as il,closeSync as sl,mkdirSync as al}from"fs";import{dirname as ll,join as cl}from"path";var ul=6e4;function io(e){return cl(e,b,Tn)}function so(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??ul,i=io(e);if(!oo(i))return xt(i,r,n());let s=lo(i);return!s||n()-s.started_at>o||!dl(s.pid)?xt(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function ao(e,t={}){let n=t.pid??process.pid,r=io(e);if(!oo(r))return;let o=lo(r);if(!(o&&o.pid!==n))try{rl(r)}catch{}}function xt(e,t,n){let r={pid:t,started_at:n};try{al(ll(e),{recursive:!0});let o=il(e,"w");try{ol(o,JSON.stringify(r))}finally{sl(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function lo(e){try{let t=nl(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 dl(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var wl=new Set([".md"]),kl=new Set(["inbox"]);function bl(e){let t=[];function n(r,o){if(an(r))for(let i of fl(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&kl.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("."),l=a===-1?"":i.name.slice(a);wl.has(l)&&t.push(s)}}}return n(e,""),t}function uo(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return ln(Ut,`${t}.json`)}function $l(e){let t=uo(e);if(!an(t))return{files:{},last_synced_at:null};try{return JSON.parse(co(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Sl(e,t){pl(Ut,{recursive:!0}),gl(uo(e),JSON.stringify(t,null,2)+`
|
|
354
|
-
`,"utf-8")}function vl(e,t){return hl(e,t).split(yl).join("/")}async function xl(e,t){try{let n=await z(`${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 _l(e,t,n){try{let r=await z(`${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 po(e,t={}){let n=P();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=x(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=ln(e,b);if(!an(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!so(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await Cl(e,t,n,r,o)}finally{ao(e)}}async function Cl(e,t,n,r,o){let i=$l(r.domain),s=bl(o),a=n.api_base||_.BASE,l=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,p=[],
|
|
354
|
+
`,"utf-8")}function vl(e,t){return hl(e,t).split(yl).join("/")}async function xl(e,t){try{let n=await z(`${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 _l(e,t,n){try{let r=await z(`${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 po(e,t={}){let n=P();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=x(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=ln(e,b);if(!an(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!so(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await Cl(e,t,n,r,o)}finally{ao(e)}}async function Cl(e,t,n,r,o){let i=$l(r.domain),s=bl(o),a=n.api_base||_.BASE,l=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,p=[],h=0,m=await El(e,a,l);if(!t.pullOnly)for(let j of s){let Re=vl(o,j);if(t.pathFilter&&!Re.endsWith(t.pathFilter))continue;let ot=ml(j),Nt=i.files[Re];if(!(!Nt||Nt.mtime!==ot.mtimeMs||Nt.size!==ot.size)&&!t.force)continue;h++;let oi=co(j,"utf-8"),Ft=await _l(a,{path:Re,contents:oi,domain:r.domain},l);Ft.ok?(i.files[Re]={mtime:ot.mtimeMs,size:ot.size},u++):(d++,p.push(`${Re}: ${Ft.status} ${Ft.error??""}`.trim()))}let C=await xl(a,l),I=0,K=0;if(C.ok){let j=Kr(e,C.actions);I=j.wrote,K=j.removed}else C.error&&p.push(`pull actions: ${C.error}`);let E,W=!1,oe=i.last_synced_at;if(!t.pushOnly){let j=await Qr({projectDir:e,apiBase:a,authHeader:l,since:i.last_synced_at,stateFiles:i.files,force:t.force});j.ok?oe=j.cursor:(W=!0,j.error&&p.push(`pull: ${j.error}`)),E={written:j.written,overwritten:j.overwritten,skipped:j.skipped,conflicts:j.conflicts,deleted:j.deleted,warnings:j.warnings}}let ri=!!E&&E.written+E.overwritten+E.deleted+E.conflicts>0;if(i.last_synced_at=oe,Sl(r.domain,i),h===0&&I===0&&K===0&&!ri&&m.flushed===0&&m.dropped===0&&!W&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:p,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:E};let An=d===0&&!W;return{ok:An,reason:An?void 0:"error",synced:u,failed:d,errors:p,actionsPulled:I,actionsRemoved:K,acksFlushed:m.flushed,acksDropped:m.dropped,pull:E}}async function El(e,t,n){let r=vt(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let l=await Al(a,t,n);l==="flushed"?(o++,s.push(a.action_id)):l==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&ro(e,s),{flushed:o,dropped:i}}async function Al(e,t,n){try{let r=await z(`${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 fo(e){let t;try{t=x(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(ve(S,n)<=0){if(!t.skill_version)try{B(e,{skill_version:n})}catch{}return{refreshed:!1,reason:"up-to-date"}}try{return ye(e),B(e,{skill_version:S}),{refreshed:!0,from:n,to:S,reason:"refreshed"}}catch{return{refreshed:!1,reason:"error"}}}function cn(e){let t;try{t=x(e)}catch{return{refreshed:!1,from:null,to:S,reason:"error"}}if(!t)return{refreshed:!1,from:null,to:S,reason:"no-project"};let n=t.skill_version||t.seoagent_version||null;try{return ye(e),B(e,{skill_version:S}),{refreshed:!0,from:n,to:S,reason:"refreshed"}}catch{return{refreshed:!1,from:n,to:S,reason:"error"}}}import{existsSync as Il,mkdirSync as Rl,readFileSync as Pl,writeFileSync as Ol}from"fs";var Tl="https://registry.npmjs.org/@seoagent-official/seoagent/latest",jl=1440*60*1e3,Ll=720*60*1e3,Nl=2e3;function Fl(e,t,n=jl){if(!e.checkedAt)return!0;let r=Date.parse(e.checkedAt);return Number.isNaN(r)?!0:t.getTime()-r>=n}function Dl(e){let{current:t,latest:n,cache:r,now:o}=e,i=e.notifyIntervalMs??Ll;if(!n||ve(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 Ul(e){let t=e.readCache();if(Fl(t,e.now,e.checkIntervalMs)){let r=await e.fetchLatest();t={...t,checkedAt:e.now.toISOString(),...r?{latest:r}:{}},e.writeCache(t)}let n=Dl({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 Ml(){try{return Il(st)?JSON.parse(Pl(st,"utf-8")):{}}catch{return{}}}function Bl(e){try{Rl(F,{recursive:!0}),Ol(st,JSON.stringify(e,null,2)+`
|
|
355
355
|
`,"utf-8")}catch{}}async function Gl(){try{let e=await fetch(Tl,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(Nl)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}catch{return null}}async function mo(e){try{return await Ul({current:e,now:new Date,fetchLatest:Gl,readCache:Ml,writeCache:Bl})}catch{return null}}async function H(e={}){let t=fo(process.cwd());if(t.refreshed){try{se(process.cwd())}catch{}e.silent||c.info(ee.dim(`\u21BB Updated SEOAgent skill ${t.from} \u2192 ${t.to}.`))}ae(process.cwd());let n=await mo(S);n&&c.message(ee.yellow(n));let r=!e.silent&&!!process.stdout.isTTY,o=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",i=r?Kl():null;i?.start(`${o} ${ee.dim(".seoagent/")} with your dashboard\u2026`);let s=await po(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.`,ee.dim("Not logged in \u2014 cloud sync skipped.")),i&&c.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.`,ee.dim("No SEOAgent project \u2014 sync skipped.")),i&&c.info(`Run \`${f("init")}\` first.`);return}if(s.reason==="no-changes"){k(i,"info","Already in sync.",ee.green("Already in sync."));return}if(s.reason==="busy"){k(i,"info","Another sync is in progress \u2014 skipping this run.",ee.dim("Another sync is in progress \u2014 skipping this run."));return}let a=Wl(s);k(i,"success",a??"Sync complete.",ee.green(a??"Sync complete.")),s.synced>0&&c.success(`Synced ${s.synced} file${s.synced===1?"":"s"} to your dashboard.`);let l=s.pull;if(l){let u=l.written+l.overwritten;u>0&&c.success(`Pulled ${u} file${u===1?"":"s"} from the cloud`+(l.overwritten>0?` (${l.overwritten} updated)`:"")),l.deleted>0&&c.info(`Removed ${l.deleted} file${l.deleted===1?"":"s"} deleted in the cloud.`),l.conflicts>0&&c.warn(`${l.conflicts} conflict${l.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let d of l.warnings.slice(0,5))c.info(` \u2022 ${d}`)}if(s.acksFlushed&&s.acksFlushed>0&&c.success(`Flushed ${s.acksFlushed} offline ack${s.acksFlushed===1?"":"s"} from the queue.`),s.acksDropped&&s.acksDropped>0&&c.info(`Dropped ${s.acksDropped} stale ack${s.acksDropped===1?"":"s"} (already settled server-side).`),s.actionsPulled&&s.actionsPulled>0&&(c.success(`Pulled ${s.actionsPulled} pending action${s.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||c.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),s.actionsRemoved&&s.actionsRemoved>0&&c.info(`Cleaned up ${s.actionsRemoved} stale inbox file${s.actionsRemoved===1?"":"s"}.`),s.failed>0){c.warn(`${s.failed} file${s.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let u of s.errors.slice(0,3))c.info(` \u2022 ${u}`)}}function Wl(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 D(e){let t=x(e);return t||(c.error(`No SEOAgent project here. Run \`${f("init")}\` first.`),process.exitCode=1,null)}async function fe(e={}){if(e.print){let t=P();if(!t){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let n=t.api_base||_.BASE,r=await zr({apiBase:n,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!r.ok){c.warn(r.error),process.exitCode=1;return}process.stdout.write(r.body),r.body.endsWith(`
|
|
356
356
|
`)||process.stdout.write(`
|
|
357
|
-
`);return}await H({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as ql,readdirSync as Hl,unlinkSync as Yl}from"fs";import{join as go}from"path";import{isCancel as zl,select as Vl}from"@clack/prompts";async function te(e,t={}){let n=null;if(e){let u=Number.parseInt(e,10);if(Number.isNaN(u)||u<=0){c.error(`Invalid action id: "${e}"`),process.exitCode=1;return}n=u}else if(n=await Jl(),n===null)return;let r=n,o=P();if(!o){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let i=o.api_base||_.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",l;try{l=await z(`${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{no(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),un(r),St(process.cwd()),t.silent||c.warn(`Network unavailable \u2014 ack queued locally. Run \`${f("sync")}\` when you're back online; it'll flush automatically.`);return}if(!l.ok){let u=await l.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(l.status===409&&d?.code==="already_acked"){un(r),St(process.cwd());let C=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||c.success(`Action ${r} was already ${C}.`);return}let p=typeof d?.code=="string"?d.code:null,
|
|
358
|
-
`);return}if(n.length===0){c.info(_t.dim("No pending actions.")),c.message(`Run \`${f("sync")}\` to pull anything autopilot has queued, or \`${f("autopilot status")}\` to check whether autopilot is on.`);return}c.message(`${_t.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),c.message("");for(let r of n)c.message(Ce(r));c.message(""),c.message(`Apply one: ${_t.bold(f("ack <id>"))} \xB7 Interactive picker: ${_t.bold(f("ack"))} (no id)`)}import{readFileSync as sc}from"fs";import{join as ac,relative as lc}from"path";import{confirm as bo,isCancel as Et,multiselect as cc,note as vo,select as uc}from"@clack/prompts";import g from"picocolors";import{query as dc}from"@anthropic-ai/claude-agent-sdk";import{existsSync as Ql,readdirSync as Xl}from"fs";import{homedir as Zl}from"os";import{join as ec}from"path";import{execSync as pn}from"child_process";function He(){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":tc()?nc()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function tc(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return pn(e,{stdio:"ignore"}),!0}catch{return!1}}function nc(){let e=ec(Zl(),".claude");if(!Ql(e))return!1;try{return Xl(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function ho(){try{return pn("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function yo(){try{return pn("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var J={"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 ko}from"marked";import{markedTerminal as rc}from"marked-terminal";import fn from"picocolors";var wo=!1;function oc(){wo||(ko.use(rc({reflowText:!1,width:100})),wo=!0)}function Ct(e){if(!e)return e;oc();try{let t=ko.parse(e);return typeof t=="string"?ic(t):e}catch{return e}}function ic(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>fn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>fn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+fn.italic(r))}async function gn(e={}){let t=process.cwd();if(!D(t))return;if(!process.stdout.isTTY&&!e.yes){c.error(`\`${f("process")}\` needs an interactive TTY for the sync + selection prompts. Use \`--yes\` to skip prompts and process everything (for CI/CD).`),process.exitCode=1;return}if(!await yc(e.yes)){process.exitCode=1;return}if(e.yes)await H({embedded:!0});else{let u=await uc({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(Et(u)){c.info("Cancelled.");return}u==="sync"?await H({embedded:!0}):u==="pull"&&await fe({embedded:!0})}let r=pe(t);if(r.length===0){c.info(g.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),c.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(
|
|
357
|
+
`);return}await H({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as ql,readdirSync as Hl,unlinkSync as Yl}from"fs";import{join as go}from"path";import{isCancel as zl,select as Vl}from"@clack/prompts";async function te(e,t={}){let n=null;if(e){let u=Number.parseInt(e,10);if(Number.isNaN(u)||u<=0){c.error(`Invalid action id: "${e}"`),process.exitCode=1;return}n=u}else if(n=await Jl(),n===null)return;let r=n,o=P();if(!o){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}if(!D(process.cwd()))return;let i=o.api_base||_.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",l;try{l=await z(`${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{no(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),un(r),St(process.cwd()),t.silent||c.warn(`Network unavailable \u2014 ack queued locally. Run \`${f("sync")}\` when you're back online; it'll flush automatically.`);return}if(!l.ok){let u=await l.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(l.status===409&&d?.code==="already_acked"){un(r),St(process.cwd());let C=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||c.success(`Action ${r} was already ${C}.`);return}let p=typeof d?.code=="string"?d.code:null,h=typeof d?.error=="string"?d.error:u,m=p?`, code: ${p}`:"";c.error(`Server rejected ack (${l.status}${m}): ${h.slice(0,200)}`),process.exitCode=1;return}un(r),St(process.cwd()),!t.silent&&(t.failed?c.success(`Action ${r} marked failed${t.reason?` (reason: ${t.reason})`:""}.`):c.success(`Action ${r} marked completed.`),c.info(` inbox location: ${go(b,"inbox")}`))}function un(e){let t=V(process.cwd());if(ql(t)){for(let n of Hl(t))if(n.endsWith(`-${e}.md`))try{Yl(go(t,n))}catch{}}}async function Jl(){let e=process.cwd(),t=pe(e);if(t.length===0)return c.info("No pending actions in .seoagent/inbox/."),c.message(`Run \`${f("sync")}\` to pull anything autopilot has queued.`),null;if(!process.stdout.isTTY)return c.error(`Cannot show interactive picker in non-TTY mode. Pass an action id explicitly, or run \`${f("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await Vl({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:Ce(r)}))});return zl(n)?(c.info("Cancelled \u2014 no action closed out."),null):n}import _t from"picocolors";async function dn(e={}){let t=process.cwd();if(!e.json&&!D(t))return;let n=pe(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:V(t),actions:n})+`
|
|
358
|
+
`);return}if(n.length===0){c.info(_t.dim("No pending actions.")),c.message(`Run \`${f("sync")}\` to pull anything autopilot has queued, or \`${f("autopilot status")}\` to check whether autopilot is on.`);return}c.message(`${_t.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),c.message("");for(let r of n)c.message(Ce(r));c.message(""),c.message(`Apply one: ${_t.bold(f("ack <id>"))} \xB7 Interactive picker: ${_t.bold(f("ack"))} (no id)`)}import{readFileSync as sc}from"fs";import{join as ac,relative as lc}from"path";import{confirm as bo,isCancel as Et,multiselect as cc,note as vo,select as uc}from"@clack/prompts";import g from"picocolors";import{query as dc}from"@anthropic-ai/claude-agent-sdk";import{existsSync as Ql,readdirSync as Xl}from"fs";import{homedir as Zl}from"os";import{join as ec}from"path";import{execSync as pn}from"child_process";function He(){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":tc()?nc()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function tc(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return pn(e,{stdio:"ignore"}),!0}catch{return!1}}function nc(){let e=ec(Zl(),".claude");if(!Ql(e))return!1;try{return Xl(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function ho(){try{return pn("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function yo(){try{return pn("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var J={"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 ko}from"marked";import{markedTerminal as rc}from"marked-terminal";import fn from"picocolors";var wo=!1;function oc(){wo||(ko.use(rc({reflowText:!1,width:100})),wo=!0)}function Ct(e){if(!e)return e;oc();try{let t=ko.parse(e);return typeof t=="string"?ic(t):e}catch{return e}}function ic(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>fn.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>fn.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+fn.italic(r))}async function gn(e={}){let t=process.cwd();if(!D(t))return;if(!process.stdout.isTTY&&!e.yes){c.error(`\`${f("process")}\` needs an interactive TTY for the sync + selection prompts. Use \`--yes\` to skip prompts and process everything (for CI/CD).`),process.exitCode=1;return}if(!await yc(e.yes)){process.exitCode=1;return}if(e.yes)await H({embedded:!0});else{let u=await uc({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(Et(u)){c.info("Cancelled.");return}u==="sync"?await H({embedded:!0}):u==="pull"&&await fe({embedded:!0})}let r=pe(t);if(r.length===0){c.info(g.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),c.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(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)",h=await cc({message:`Which actions to process? ${r.length} pending \u2014${p}`,options:r.map(m=>({value:m.id,label:Ce(m)})),initialValues:d,required:!1});if(Et(h)){c.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(h)||h.length===0){c.info("No actions selected. Nothing to do.");return}o=h}let i=0,s=0,a=0,l=Date.now();for(let u=0;u<o.length;u++){let d=o[u],p=r.find(E=>E.id===d);if(!p)continue;pc({index:u+1,total:o.length,entry:p});let h=ac(V(t),p.filename),m;try{m=sc(h,"utf-8")}catch(E){c.error(` Could not read ${p.filename}: ${E.message}`),a++;continue}let C=Date.now(),I=await hc({cwd:t,entry:p,actionContent:m,model:e.model}),K=$o(Date.now()-C);if(I.kind==="applied")try{await te(String(d),{silent:!0}),i++,c.message("");let E=I.summary?`
|
|
359
359
|
`+g.dim(" "+I.summary):"";c.message(` ${g.green("\u2713")} id ${d} ${g.dim("\u2014 applied in "+K)}${E}`)}catch(E){c.warn(` Applied but ack failed: ${E.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(I.kind==="declined")try{await te(String(d),{silent:!0,failed:!0,reason:I.reason}),s++,c.message(""),c.message(` ${g.yellow("\u2298")} id ${d} ${g.dim("\u2014 declined: "+G(I.reason,100))}`)}catch(E){c.warn(` Could not ack decline: ${E.message}. Run \`seoagent ack ${d} --failed --reason "${I.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,c.message(""),c.message(` ${g.red("\u2717")} id ${d} ${g.dim("\u2014 agent did not converge after "+K)}`)}mc({applied:i,declined:s,failed:a,total:o.length,elapsed:$o(Date.now()-l)})}function pc(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=fc[i]??g.dim,a=[g.bold(`[${t}/${n}]`),g.dim("\xB7"),g.bold(`id ${r.id}`),g.dim("\xB7"),g.cyan(o),s(i)].join(" ");vo(r.title,a)}var fc={critical:e=>g.red(g.bold(e)),high:g.red,medium:g.yellow,low:g.dim};function mc(e){let{applied:t,declined:n,failed:r,total:o,elapsed:i}=e,s=t+n,a;if(s===o&&r===0)a=n===0?g.green(`\u2713 ${t}/${o} applied`):g.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=g.red(`\u2717 0/${o} applied`);else{let l=[`${t}/${o} applied`];n>0&&l.push(`${n} declined`),r>0&&l.push(`${r} failed`),a=g.yellow(`\u25D0 ${l.join(" \xB7 ")}`)}vo(`${a}
|
|
360
360
|
${g.dim("elapsed: "+i)}`,g.bold("Done"))}function $o(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 gc(e){if(typeof e!="string"||!e)return null;let t=e.split(`
|
|
361
361
|
`);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 hc(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=Ec(n,r);try{let s=dc({prompt:i,options:{cwd:t,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],permissionMode:"acceptEdits",...o?{model:o}:{}}}),a={toolUseById:new Map};for await(let l of s)if(l.type==="assistant"){let u=l.message.content;if(Array.isArray(u))for(let d of u)kc(d,a)}else if(l.type==="user"){let u=l.message.content;if(Array.isArray(u))for(let d of u)Sc(d,a)}else if(l.type==="result"){if(process.stdout.write(`
|
|
@@ -396,7 +396,7 @@ Action file (\`.seoagent/inbox/${e.filename}\`):
|
|
|
396
396
|
\`\`\`
|
|
397
397
|
${t}
|
|
398
398
|
\`\`\`
|
|
399
|
-
`}import{spinner as Ac}from"@clack/prompts";import w from"picocolors";var Ic=new Set(["on","off","status"]);async function Ye(e,t={}){let n=(e||"").toLowerCase();if(!Ic.has(n)){c.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=P();if(!r){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||_.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?Ac():null,l=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(l);let u;try{u=await fetch(`${o}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(
|
|
399
|
+
`}import{spinner as Ac}from"@clack/prompts";import w from"picocolors";var Ic=new Set(["on","off","status"]);async function Ye(e,t={}){let n=(e||"").toLowerCase();if(!Ic.has(n)){c.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=P();if(!r){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||_.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?Ac():null,l=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(l);let u;try{u=await fetch(`${o}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(m){k(a,"error",`Network error: ${m.message}`,w.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){let C=x(process.cwd())?.domain??"",I=`${_.PRICING}?ref=cli${C?`&domain=${encodeURIComponent(C)}`:""}`;k(a,"warn","CLI autopilot is a paid feature.",w.yellow("Autopilot is a paid feature.")),c.message(Rc(I)),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"||!d.autopilot){k(a,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,w.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}let{enabled:p,delivery_mode:h}=d.autopilot;if(n==="on"){a?.stop(w.green("Autopilot enabled.")),c.message(hn({enabled:!0,deliveryMode:h,action:n}));return}if(n==="off"){a?.stop(w.dim("Autopilot disabled.")),c.message(hn({enabled:!1,deliveryMode:h,action:n}));return}a?.stop(w.dim("Status:")),c.message(hn({enabled:p,deliveryMode:h,action:n}))}function hn(e){let n=s=>w.dim(s.padEnd(11)),r=e.enabled?`${w.bold(w.green("\u25CF ON"))} ${w.dim("(queueing fixes for your coding agent)")}`:`${w.dim("\u25CB OFF")} ${w.dim("(no new suggestions will be queued)")}`,o=[{content:`${n("Status:")}${r}`}];e.enabled&&e.deliveryMode&&o.push({content:`${n("Mode:")}${w.dim(e.deliveryMode)}`}),o.push({sep:!0}),e.enabled?(o.push({content:`${w.dim("Apply queued fixes:")} ${w.cyan(f("sync"))}`}),o.push({content:`${w.dim("Turn off any time:")} ${w.cyan(f("autopilot off"))}`})):(o.push({content:`${w.dim("Enable (paid):")} ${w.cyan(f("autopilot on"))}`}),o.push({content:w.dim("Queues SEO fixes for your coding agent to apply on each sync.")}));let i=`${w.bold(w.cyan("SEOAgent"))} ${w.dim("\xB7")} ${w.dim("autopilot")}`;return O(o,{width:78,title:i})}function Rc(e){let t=[{content:w.bold(w.yellow("Autopilot is a paid feature."))},{sep:!0},{content:w.dim("SEOAgent continuously audits your site and queues fixes for")},{content:w.dim("your coding agent to apply on each `sync` \u2014 you stay in the")},{content:w.dim("loop; nothing is auto-applied.")},{sep:!0},{content:`${w.dim("Upgrade:")} ${w.cyan(e)}`}],n=`${w.bold(w.cyan("SEOAgent"))} ${w.dim("\xB7")} ${w.dim("autopilot")}`;return O(t,{width:78,title:n})}import{mkdirSync as Gc,writeFileSync as Kc}from"fs";import{join as yn}from"path";import{readdirSync as Pc,readFileSync as Oc,statSync as xo}from"fs";import{join as Tc}from"path";var jc=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Lc=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"]),Nc=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Fc=5e3,Dc=512*1024;function Io(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function _o(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&&Lc.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var Co=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Eo=/\]\(\s*([^)\s]+)/g;function Uc(e,t){if(!e)return[];let n=Io(t),r=[],o;for(Co.lastIndex=0;(o=Co.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=_o(i,n);s&&r.push(s)}for(Eo.lastIndex=0;(o=Eo.exec(e))!==null;){let i=_o(o[1],n);i&&r.push(i)}return r}function Mc(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 Ro(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(`
|
|
400
400
|
`),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${Io(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(`
|
|
401
401
|
`),i=e.orphans.length===0?`## Orphan pages
|
|
402
402
|
|
|
@@ -404,7 +404,7 @@ None \u2014 every page has at least one inbound internal link. \u{1F389}`:[`## O
|
|
|
404
404
|
`),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=>`| ${Ao(a.url)} | ${a.inbound} |`)].join(`
|
|
405
405
|
`);return[r,"",o,"",i,s,""].join(`
|
|
406
406
|
`)}function Ao(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*Bc(e){let t=0;function*n(r){let o;try{o=Pc(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=Fc)return;if(i.name.startsWith("."))continue;let s=Tc(r,i.name);if(i.isDirectory()){if(Nc.has(i.name))continue;yield*n(s)}else if(i.isFile()){let a=i.name.lastIndexOf("."),l=a===-1?"":i.name.slice(a+1).toLowerCase();if(!jc.has(l))continue;t++,yield s}}}yield*n(e)}function Po(e,t){let{pages:n}=gt(e,t),r=[],o=0,i=!1;try{i=xo(e).isDirectory()}catch{i=!1}if(i)for(let s of Bc(e)){let a;try{if(xo(s).size>Dc)continue;a=Oc(s,"utf-8")}catch{continue}o++;for(let l of Uc(a,t))r.push(l)}return Mc(n,r,o)}function ze(e={}){let t=process.cwd(),n=D(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Po(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
|
|
407
|
-
`);return}let i=yn(t,b);Gc(i,{recursive:!0});let s=yn(i,"internal-links.md");if(Kc(s,Ro(o,r),"utf-8"),c.success(`Analyzed ${o.pageCount} page${o.pageCount===1?"":"s"} across ${o.filesScanned} file${o.filesScanned===1?"":"s"}.`),o.orphans.length===0)c.info("No orphan pages \u2014 every page has an inbound internal link.");else{c.warn(`${o.orphans.length} orphan page${o.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of o.orphans.slice(0,10))c.message(` \u2022 ${a.url}`);o.orphans.length>10&&c.message(` \u2026and ${o.orphans.length-10} more`)}c.info(`Report written to ${yn(b,"internal-links.md")}`)}import Y from"picocolors";import{existsSync as Ee,mkdirSync as At,readdirSync as Wc,readFileSync as qc,statSync as Eg,writeFileSync as Oo}from"fs";import{dirname as Hc,join as ne,relative as Yc,resolve as zc}from"path";var Ae="okf";function It(e){return ne(e,b,Ae)}var Vc=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function wn(e){let t=[];for(let n of Wc(e,{withFileTypes:!0})){let r=ne(e,n.name);n.isDirectory()?t.push(...wn(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function Jc(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 To(e){let t=[],n=[];if(!Ee(e))return{ok:!1,fileCount:0,errors:[{file:Ae,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=wn(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Ae,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Ee(ne(e,"index.md"))||n.push({file:Ae,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=Yc(e,i),a;try{a=Oe(qc(i,"utf-8"))}catch{t.push({file:s,message:"Could not read or parse file."});continue}let l=a.data.type;(l==null||String(l).trim()==="")&&t.push({file:s,message:"Missing required frontmatter field `type`."});let u=a.data.timestamp;u!=null&&u!==""&&!Vc.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 Jc(a.body)){let
|
|
407
|
+
`);return}let i=yn(t,b);Gc(i,{recursive:!0});let s=yn(i,"internal-links.md");if(Kc(s,Ro(o,r),"utf-8"),c.success(`Analyzed ${o.pageCount} page${o.pageCount===1?"":"s"} across ${o.filesScanned} file${o.filesScanned===1?"":"s"}.`),o.orphans.length===0)c.info("No orphan pages \u2014 every page has an inbound internal link.");else{c.warn(`${o.orphans.length} orphan page${o.orphans.length===1?"":"s"} (no inbound internal links):`);for(let a of o.orphans.slice(0,10))c.message(` \u2022 ${a.url}`);o.orphans.length>10&&c.message(` \u2026and ${o.orphans.length-10} more`)}c.info(`Report written to ${yn(b,"internal-links.md")}`)}import Y from"picocolors";import{existsSync as Ee,mkdirSync as At,readdirSync as Wc,readFileSync as qc,statSync as Eg,writeFileSync as Oo}from"fs";import{dirname as Hc,join as ne,relative as Yc,resolve as zc}from"path";var Ae="okf";function It(e){return ne(e,b,Ae)}var Vc=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function wn(e){let t=[];for(let n of Wc(e,{withFileTypes:!0})){let r=ne(e,n.name);n.isDirectory()?t.push(...wn(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function Jc(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 To(e){let t=[],n=[];if(!Ee(e))return{ok:!1,fileCount:0,errors:[{file:Ae,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=wn(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:Ae,message:"OKF directory exists but contains no markdown files."}],warnings:[]};Ee(ne(e,"index.md"))||n.push({file:Ae,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=Yc(e,i),a;try{a=Oe(qc(i,"utf-8"))}catch{t.push({file:s,message:"Could not read or parse file."});continue}let l=a.data.type;(l==null||String(l).trim()==="")&&t.push({file:s,message:"Missing required frontmatter field `type`."});let u=a.data.timestamp;u!=null&&u!==""&&!Vc.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 Jc(a.body)){let h=p.split("#")[0];if(!h)continue;let m=zc(Hc(i),h);Ee(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 Rt(e){let t=It(e);if(!Ee(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:wn(t).length}}catch{return{exists:!0,fileCount:0}}}function jo(e,t){let n=It(e);At(n,{recursive:!0}),At(ne(n,"concepts"),{recursive:!0}),At(ne(n,"faqs"),{recursive:!0}),At(ne(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=ne(n,"index.md");Ee(i)||(Oo(i,`---
|
|
408
408
|
type: Organization
|
|
409
409
|
title: ${o}
|
|
410
410
|
description: Knowledge bundle describing ${o} for AI agents and answer engines.
|
|
@@ -477,7 +477,7 @@ End your reply with EXACTLY ONE fenced \`\`\`json block (and nothing after it) m
|
|
|
477
477
|
}
|
|
478
478
|
\`\`\`
|
|
479
479
|
|
|
480
|
-
\`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown.`}function Uo(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=eu(n[o]);if(i)return i}return null}function eu(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=typeof n.domain=="string"?n.domain.trim():"";if(!r)return null;let o=typeof n.brand=="string"&&n.brand.trim()?n.brand.trim():r;if(!Array.isArray(n.results))return null;let i=[];for(let s of n.results){if(!s||typeof s!="object")continue;let a=s,l=typeof a.query=="string"?a.query.trim():"";if(!l)continue;let u=a.surfaced===!0,d=typeof a.rank=="number"&&Number.isFinite(a.rank)?Math.round(a.rank):null,p=typeof a.evidence=="string"?a.evidence.trim():"";i.push({query:l,surfaced:u,rank:u?d:null,evidence:p})}return i.length===0?null:{brand:o,domain:r,results:i}}function Mo(e,t){let{cited:n,total:r}=xn(e),o=t.generatedAt.slice(0,10),i=e.results.map((u,d)=>{let p=u.surfaced?"\u2705":"\u2014",
|
|
480
|
+
\`results\` must have exactly ${t} entries. \`rank\` is a number when surfaced, or null when not surfaced or unknown.`}function Uo(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=eu(n[o]);if(i)return i}return null}function eu(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=typeof n.domain=="string"?n.domain.trim():"";if(!r)return null;let o=typeof n.brand=="string"&&n.brand.trim()?n.brand.trim():r;if(!Array.isArray(n.results))return null;let i=[];for(let s of n.results){if(!s||typeof s!="object")continue;let a=s,l=typeof a.query=="string"?a.query.trim():"";if(!l)continue;let u=a.surfaced===!0,d=typeof a.rank=="number"&&Number.isFinite(a.rank)?Math.round(a.rank):null,p=typeof a.evidence=="string"?a.evidence.trim():"";i.push({query:l,surfaced:u,rank:u?d:null,evidence:p})}return i.length===0?null:{brand:o,domain:r,results:i}}function Mo(e,t){let{cited:n,total:r}=xn(e),o=t.generatedAt.slice(0,10),i=e.results.map((u,d)=>{let p=u.surfaced?"\u2705":"\u2014",h=u.surfaced&&u.rank?`#${u.rank}`:"\u2014",m=bn(u.evidence||(u.surfaced?"surfaced":"not found"));return`| ${d+1} | ${bn(u.query)} | ${p} | ${h} | ${m} |`}).join(`
|
|
481
481
|
`),s=e.results.filter(u=>!u.surfaced),a=s.length===0?"_None \u2014 the business surfaced for every query tested. Re-run periodically to catch drift._":s.map(u=>`- **${bn(u.query)}** \u2014 ${u.evidence||"not surfaced"}`).join(`
|
|
482
482
|
`),l=e.results.some(u=>!u.surfaced)?"- Enrich the Open Knowledge Format bundle so answer engines understand the business: run `seoagent okf scaffold` then fill it (the skill maps your `.seoagent/` knowledge into it), and publish it at `/.well-known/okf/`.\n- Cover the missed questions directly in your content (a page or FAQ that answers each one), then re-run `seoagent citations`.":"- Keep the OKF bundle current as the business evolves, and re-run to catch regressions.";return`---
|
|
483
483
|
type: Report
|
|
@@ -521,12 +521,12 @@ rank and cite differently, and tracking them individually is a planned
|
|
|
521
521
|
follow-up. Treat the score as directional \u2014 re-run over time to watch the
|
|
522
522
|
trend rather than fixating on a single number.
|
|
523
523
|
`}function bn(e){return e.replace(/\|/g,"\\|").replace(/\n+/g," ").trim()}async function Je(e={}){let t=process.cwd(),n=D(t);if(!n)return;let r=He();if(r!=="env-key"&&r!=="enterprise"&&r!=="claude-session-likely"){c.warn(J[r].summary),J[r].next&&c.message(` ${J[r].next}`),process.exitCode=1;return}c.info(N.dim(J[r].summary));let o=ur(t),i=Rt(t),s={domain:n.domain,name:o?.business.name,type:o?.business.type||n.site_type,description:o?.business.description,hasOkfBundle:i.exists&&i.fileCount>0},a=Fo(e.queries);c.message(`${N.cyan("\u25C7")} Auditing AI citations for ${N.bold(s.domain)} \u2014 ${a} web-grounded quer${a===1?"y":"ies"} via ${Pt}.`),c.message(N.dim(` This runs live web searches and can take a minute\u2026
|
|
524
|
-
`));let l=Do(s,a),u=await ou({cwd:t,prompt:l,model:e.model});if(u===null){process.exitCode=1;return}let d=Uo(u);if(!d){c.error(`Couldn't read a citation report from the agent's reply. Re-run \`${f("citations")}\`, optionally with fewer queries (\`--queries 4\`).`),process.exitCode=1;return}let p=new Date().toISOString(),
|
|
524
|
+
`));let l=Do(s,a),u=await ou({cwd:t,prompt:l,model:e.model});if(u===null){process.exitCode=1;return}let d=Uo(u);if(!d){c.error(`Couldn't read a citation report from the agent's reply. Re-run \`${f("citations")}\`, optionally with fewer queries (\`--queries 4\`).`),process.exitCode=1;return}let p=new Date().toISOString(),h=Mo(d,{generatedAt:p});tu(vn(t),{recursive:!0}),nu(No(t),h,"utf-8");let{cited:m,total:C}=xn(d),I=m===0?N.red:m<C?N.yellow:N.green;c.message(O([{content:N.bold("AI Citation Scorecard")},{sep:!0},{content:`Domain: ${N.cyan(d.domain)}`},{content:`Cited: ${I(`${m} / ${C}`)} ${N.dim("queries")}`},{content:`Engine: ${N.dim(Pt)}`},{sep:!0},{content:N.dim(`Saved \u2192 .seoagent/${$n}/${Sn}`)},{content:m<C?N.dim("Not surfacing everywhere \u2014 see the scorecard, then `seoagent okf`."):N.dim("Surfacing across the board. Re-run periodically to catch drift.")}],{title:N.magenta("citations")})),e.json&&process.stdout.write(JSON.stringify(d,null,2)+`
|
|
525
525
|
`)}async function ou(e){let{cwd:t,prompt:n,model:r}=e;try{let o=ru({prompt:n,options:{cwd:t,allowedTools:["WebSearch","WebFetch","Read","Grep","Glob"],permissionMode:"acceptEdits",...r?{model:r}:{}}}),i="";for await(let s of o)if(s.type==="assistant"){let a=s.message.content;if(Array.isArray(a))for(let l of a)iu(l)}else if(s.type==="result"){if(process.stdout.write(`
|
|
526
526
|
`),!(s.subtype==="success"&&!s.is_error))return c.error(" Agent did not complete the citation audit (rate limit, auth, or network)."),null;i=String(s.result??"")}return i}catch(o){return process.stdout.write(`
|
|
527
527
|
`),c.error(` Agent error: ${o.message}`),null}}function iu(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(Ct(n));return}if(t==="tool_use"){let n=String(e.name??"tool"),r=e.input,o=n==="WebSearch"?String(r?.query??""):n==="WebFetch"?String(r?.url??""):"";process.stdout.write(N.dim(` ${N.magenta("\u{1F50E}")} ${n}${o?` ${su(o,70)}`:""}
|
|
528
528
|
`))}}function su(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}import Qe from"picocolors";function Xe(e={}){if(e.all){au();return}let t=process.cwd();if(!D(t))return;ae(t);let n=cn(t);Bo(t),n.reason==="refreshed"?(c.success(n.from&&n.from!==n.to?`Refreshed the SEOAgent skill ${n.from} \u2192 ${n.to}.`:`Refreshed the SEOAgent skill (now ${n.to}).`),c.info("Your `.seoagent/` knowledge was left untouched.")):(c.error(`Could not refresh the skill (${n.reason}).`),process.exitCode=1)}function au(){let e=or();if(e.length===0){c.info("No SEOAgent projects are registered on this machine yet. They register themselves on `init` / `sync`.");return}c.message(`Refreshing ${e.length} project${e.length===1?"":"s"} to SEOAgent ${Qe.bold(S)}\u2026`);let t=0,n=0;for(let r of e){let o=cn(r);if(Bo(r),o.reason==="refreshed"){t++;let i=o.from&&o.from!==o.to?Qe.dim(` (${o.from} \u2192 ${o.to})`):"";c.message(` ${Qe.green("\u2713")} ${r}${i}`)}else n++,c.message(` ${Qe.yellow("!")} ${r} ${Qe.dim("\u2014 "+o.reason)}`)}c.success(`Refreshed ${t}/${e.length} project${e.length===1?"":"s"} to ${S}.`),n>0&&c.info(`${n} could not be refreshed (see above).`)}function Bo(e){try{se(e)}catch{}}import{spinner as Wo}from"@clack/prompts";import y from"picocolors";var qo={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function lu(e){let t=process.cwd(),n=Mn(t);if(!n){c.error(`No .seoagent/project.md found. Run \`${f("init")}\` first.`),process.exitCode=1;return}let r=x(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||_.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?Wo():null;a?.start(`Looking up ${y.bold(`"${e.keyword}"`)} ${y.dim("via DataForSEO (free peek)\u2026")}`);let l;try{l=await z(`${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 l.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:l.status,body:u??null})+`
|
|
529
|
-
`);return}if(l.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";k(a,"warn",`Daily peek quota reached for ${d}.`,y.yellow(`Daily peek quota reached for ${d}.`)),c.message(Go()),process.exitCode=1;return}if(!l.ok||!u){k(a,"error",`Peek failed (${l.status})${u?.error?`: ${u.error}`:""}`,y.red(`Peek failed (${l.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){k(a,"warn","Real keyword data is temporarily unavailable. Try again later.",y.yellow("Real keyword data is temporarily unavailable. Try again later.")),c.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.")),c.message(cu(u.opportunity)),u.remaining&&c.message(`${y.dim("Peeks remaining today:")} ${y.bold(String(u.remaining.install))} ${y.dim("\u2014 "+Go())}`)}function cu(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(uu(e.difficulty))}`:y.dim("n/a"),i=qo[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}`}],l=`${y.bold(y.cyan("Keyword peek"))}`;return O(a,{width:55,title:l})}function uu(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Go(e=P()){return e?`You're logged in \u2014 run \`${f("keywords")}\` for full enrichment (no quota), or \`${f("keywords --discover")}\` / \`${f("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${f("login")}`}function Ko(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){c.message("Top opportunities:");for(let n of t){let r=n.volume!=null?`vol ${n.volume}`:"vol n/a",o=n.difficulty!=null?`KD ${n.difficulty}`:"KD n/a",i=n.our_position!=null?`, you're #${n.our_position}`:", not ranking";c.message(` \u2022 [${qo[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function du(e){if(e.length!==0){c.message("Top competitor gaps:");for(let t of e){let n=t.volume!=null?`vol ${t.volume}`:"vol n/a",r=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",o=t.their_position!=null?`#${t.their_position}`:"top 10";c.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${o}, ${n}, ${r}`)}}}async function re(e={}){if(e.peek&&e.peek.trim().length>0){await lu({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=P();if(!t){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=e.apiBase||t.api_base||_.BASE,r=`Bearer ${t.user_token}:${t.website_token}`,o=e.competitors?"competitors":e.discover?"discover":"enrich",i=o==="competitors"?"/api/cli/keywords/competitors":o==="discover"?"/api/cli/keywords/discover":"/api/cli/keywords/enrich",s=o==="competitors"?"Finding keywords your competitors rank for\u2026":o==="discover"?"Discovering new keywords to target\u2026":"Enriching keywords with real volume + difficulty\u2026",l=!!process.stdout.isTTY?Wo():null;l?.start(s);let u;try{
|
|
529
|
+
`);return}if(l.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";k(a,"warn",`Daily peek quota reached for ${d}.`,y.yellow(`Daily peek quota reached for ${d}.`)),c.message(Go()),process.exitCode=1;return}if(!l.ok||!u){k(a,"error",`Peek failed (${l.status})${u?.error?`: ${u.error}`:""}`,y.red(`Peek failed (${l.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){k(a,"warn","Real keyword data is temporarily unavailable. Try again later.",y.yellow("Real keyword data is temporarily unavailable. Try again later.")),c.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.")),c.message(cu(u.opportunity)),u.remaining&&c.message(`${y.dim("Peeks remaining today:")} ${y.bold(String(u.remaining.install))} ${y.dim("\u2014 "+Go())}`)}function cu(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(uu(e.difficulty))}`:y.dim("n/a"),i=qo[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}`}],l=`${y.bold(y.cyan("Keyword peek"))}`;return O(a,{width:55,title:l})}function uu(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Go(e=P()){return e?`You're logged in \u2014 run \`${f("keywords")}\` for full enrichment (no quota), or \`${f("keywords --discover")}\` / \`${f("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${f("login")}`}function Ko(e){let t=e.filter(n=>n.opportunity!=="low_priority");if(t.length!==0){c.message("Top opportunities:");for(let n of t){let r=n.volume!=null?`vol ${n.volume}`:"vol n/a",o=n.difficulty!=null?`KD ${n.difficulty}`:"KD n/a",i=n.our_position!=null?`, you're #${n.our_position}`:", not ranking";c.message(` \u2022 [${qo[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function du(e){if(e.length!==0){c.message("Top competitor gaps:");for(let t of e){let n=t.volume!=null?`vol ${t.volume}`:"vol n/a",r=t.difficulty!=null?`KD ${t.difficulty}`:"KD n/a",o=t.their_position!=null?`#${t.their_position}`:"top 10";c.message(` \u2022 ${t.keyword} \u2014 ${t.competitor_domain} ranks ${o}, ${n}, ${r}`)}}}async function re(e={}){if(e.peek&&e.peek.trim().length>0){await lu({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=P();if(!t){c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=e.apiBase||t.api_base||_.BASE,r=`Bearer ${t.user_token}:${t.website_token}`,o=e.competitors?"competitors":e.discover?"discover":"enrich",i=o==="competitors"?"/api/cli/keywords/competitors":o==="discover"?"/api/cli/keywords/discover":"/api/cli/keywords/enrich",s=o==="competitors"?"Finding keywords your competitors rank for\u2026":o==="discover"?"Discovering new keywords to target\u2026":"Enriching keywords with real volume + difficulty\u2026",l=!!process.stdout.isTTY?Wo():null;l?.start(s);let u=o==="competitors"||o==="discover",d;try{d=await z(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"},u?{timeoutMs:6e4,attempts:1}:{})}catch(m){k(l,"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(l,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",y.yellow("Paid feature \u2014 upgrade to continue.")),c.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${y.cyan(_.PRICING)}`:`Upgrade to find new keywords to target: ${y.cyan(_.PRICING)}`),process.exitCode=1;return}if(!d.ok||p?.status!=="ok"){k(l,"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-keywords"||p.skipped==="no-seeds"){k(l,"warn","No keywords yet. Run the keyword strategy (Phase 2) first, then try again.",y.yellow("No keywords yet."));return}if(p.skipped==="no-competitors"){k(l,"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(l,"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(l,"warn",`Skipped: ${p.skipped}`,y.yellow(`Skipped: ${p.skipped}`));return}if(o==="competitors"){let m=p.gaps??0;k(l,"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.`)),du(p.topGaps??[]),c.message(`Review them in ${y.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}if(o==="discover"){let m=p.discovered??0;k(l,"success",`Discovered ${m} new keyword${m===1?"":"s"} to target (added as "suggested").`,y.green(`${m} new keyword${m===1?"":"s"} discovered.`)),Ko(p.opportunities??[]),c.message(`Review them in ${y.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}let h=p.enriched??0;k(l,"success",`Enriched ${h} keyword${h===1?"":"s"}.`,y.green(`Enriched ${h} keyword${h===1?"":"s"}.`)),Ko(p.opportunities??[]),p.paid||c.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(_.PRICING)}`)}import A from"picocolors";import{existsSync as pu,readFileSync as fu}from"fs";import{join as mu}from"path";var Ho=["openai","fal","replicate"],Ie={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function gu(e){let t={};if(!pu(e))return t;let n=fu(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 Yo(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 me){let o=mu(e,r),i=gu(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 Ot(e){let t=[].concat(...Ho.map(a=>Ie[a])),n=Yo(e,t),r=[];for(let a of Ho)Ie[a].some(l=>n.found[l])&&r.push(a);if(r.length===0)return{provider:"none",matched_key:null,source:null,available_providers:[]};let o=r[0],i=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 zo(e,t){let n=Yo(e,Ie[t]);for(let r of Ie[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Vo(){return Ie}function Ze(e={}){let t=process.cwd(),n=x(t),r=Ot(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
|
|
530
530
|
`);return}if(c.message(hu(r)),!n){c.warn(`No SEOAgent project here. Run \`${f("init")}\` first to persist the provider.`);return}B(t,{image_provider:r.provider}),c.info(`Saved to ${A.cyan(".seoagent/project.md")} ${A.dim(`(image_provider: ${r.provider})`)}`)}function hu(e){let n=i=>A.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${A.dim("\u25CB")} ${A.bold(A.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:A.dim("Set ONE of these to enable image generation:")});let i=Vo();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${A.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:A.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${A.cyan(f("env-check"))}`})}else{r.push({content:`${A.green("\u2713")} ${A.dim("Image provider:")} ${A.bold(A.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${A.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${A.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${A.dim(i.join(", "))}`})}let o=`${A.bold(A.cyan("SEOAgent"))} ${A.dim("\xB7")} ${A.dim("env-check")}`;return O(r,{width:64,title:o})}import{existsSync as Cn,mkdirSync as Xo,writeFileSync as Zo}from"fs";import{dirname as jt,isAbsolute as $u,join as Tt,resolve as Su}from"path";import{tmpdir as vu}from"os";import{spinner as xu}from"@clack/prompts";import T from"picocolors";import{Buffer as Jo}from"buffer";async function _n(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 Jo.from(n)}async function yu(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:Jo.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await _n(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function wu(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 _n(o.url),contentType:o.content_type??"image/png"}}async function ku(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 bu(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 ku(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 _n(o),contentType:"image/png",providerImageId:r.id}}async function Qo(e,t){switch(e){case"openai":return yu(t);case"fal":return wu(t);case"replicate":return bu(t);default:throw new Error(`Unknown image provider: ${e}`)}}function _u(e){return e==="openai"||e==="fal"||e==="replicate"}async function et(e={}){let t=process.cwd();if(!e.prompt){c.warn(`Missing --prompt. Example: ${f('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){c.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=x(t),r=null;if(e.provider){if(!_u(e.provider)){c.warn(`Invalid --provider "${e.provider}". Use one of: openai, fal, replicate.`),process.exitCode=1;return}r=e.provider}else n?.image_provider&&n.image_provider!=="none"?r=n.image_provider:r=Ot(t).provider;if(!r||r==="none"){c.warn(`No image generation provider available. Set OPENAI_API_KEY, FAL_KEY, or REPLICATE_API_TOKEN, then run \`${f("env-check")}\`.`),process.exitCode=1;return}let o=zo(t,r);if(!o){c.warn(`Provider "${r}" selected but no API key found. Set the env var, then re-run.`),process.exitCode=1;return}let i=$u(e.out)?e.out:Su(t,e.out),a=!e.silent&&!!process.stdout.isTTY?xu():null;a?.start(`Generating image with ${T.bold(r)} ${T.dim(`(${o.envName})`)}\u2026`);try{let l=await Qo(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Cn(jt(i))||Xo(jt(i),{recursive:!0}),Zo(i,l.bytes),e.silent||k(a,"success",`Wrote ${i} (${l.bytes.length} bytes, ${l.contentType}).`,T.green(`Wrote ${i} ${T.dim(`(${l.bytes.length} bytes, ${l.contentType})`)}`))}catch(l){a?.stop(T.red("Image generation failed."));let u=Eu(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:l});c.message(Cu({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:l.message})),u&&c.message(`${T.dim("Full error log:")} ${T.cyan(u)}`),process.exitCode=1}}function Cu(e){let n=d=>T.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${T.red("\u2717")} ${T.bold(T.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${T.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${T.dim(`"${o}"`)}`}];e.size&&i.push({content:`${n("Size:")}${e.size}`}),i.push({sep:!0});let s=e.message.replace(/\s+/g," ").trim(),a=64,l=s.length>a?`${s.slice(0,a-1)}\u2026`:s;i.push({content:T.red(l)});let u=`${T.bold(T.cyan("SEOAgent"))} ${T.dim("\xB7")} ${T.dim("generate-image")}`;return O(i,{width:70,title:u})}function Eu(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=Tt(e,b),i=Tt(o,".errors"),s=Cn(o)?Tt(i,r):Tt(vu(),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 Cn(jt(s))||Xo(jt(s),{recursive:!0}),Zo(s,a.join(`
|
|
531
531
|
`)),s}catch{return null}}import U from"picocolors";async function tt(e={}){let t=P();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
|
|
532
532
|
`):c.error(`Not logged in. Run \`${f("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||_.BASE).replace(/\/$/,""),r=`Bearer ${t.user_token}:${t.website_token}`,o;try{o=await fetch(`${n}/api/cli/whoami`,{method:"GET",headers:{Authorization:r,Accept:"application/json"}})}catch(s){c.error(`Network error: ${s.message}`),process.exitCode=1;return}if(o.status===404){if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,server_supports_whoami:!1,api_base:n})}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seoagent-official/seoagent",
|
|
3
|
-
"version": "1.51.
|
|
3
|
+
"version": "1.51.2",
|
|
4
4
|
"description": "The persistent AI SEO agent for Claude Code. Audits, keyword strategy, briefs, articles, and the autopilot loop (cloud detects → CLI executes → ack closes) — other SEO tools write the prompt, SEOAgent runs it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -6,6 +6,16 @@ The **local skill alone** (no cloud account) uses `WebSearch` only — no real v
|
|
|
6
6
|
|
|
7
7
|
A **free SEOAgent Cloud account** enriches the top ~25 keywords with **real volume + difficulty + opportunity classification** (DataForSEO Labs) — after `seoagent login`, run `seoagent keywords` and the enriched numbers project into `.seoagent/keywords.md`. **Paid upgrade** lifts the cap and unlocks `keywords --discover` (new targets from `keyword_ideas`) and `keywords --competitors` (gap keywords from rivals' `ranked_keywords`).
|
|
8
8
|
|
|
9
|
+
### Use the Pro discovery commands correctly (avoid garbage)
|
|
10
|
+
|
|
11
|
+
`--discover` and `--competitors` are **expansion** tools — they only work well once the site has a real topic signal. On a brand-new or thin site they degrade into generic high-volume noise (e.g. "1/8 as a decimal") because DataForSEO has nothing relevant to anchor to. Follow this order:
|
|
12
|
+
|
|
13
|
+
1. **Do WebSearch research FIRST** (the steps below). It's the primary discovery method and is the most reliable source for a new site — do not lead with `--discover`/`--competitors`.
|
|
14
|
+
2. **Seed the inventory + name real competitors before running them.** Write your researched keywords to `.seoagent/keywords.md` and your competitors to `.seoagent/competitors.md` — **with real domains in the headings** (e.g. `## Competitor 1: Surfer SEO — surferseo.com`), because that's what gets parsed into the cloud's competitor table. Then `seoagent sync` so the cloud has them. `--competitors` uses your named competitors; without them it tries to auto-detect and returns junk for a thin domain.
|
|
15
|
+
3. **Then** run `seoagent keywords` (enrich) → `--discover` → `--competitors`.
|
|
16
|
+
4. **Always relevance-check what they return.** Treat every `status='suggested'` keyword as a *candidate*, not a fact — drop anything off-topic for the business before adding it to the strategy, no matter how high the volume or low the difficulty. The server now filters obvious noise, but you are the final gate.
|
|
17
|
+
5. **For a single keyword's real numbers without the bulk commands, use `--peek`** — it's reliable and quota-limited; ideal for validating finalists.
|
|
18
|
+
|
|
9
19
|
## Goals of Free-Tier Research
|
|
10
20
|
|
|
11
21
|
1. **Discover the keyword space** — what terms is the audience actually searching?
|
package/skills/seoagent.md
CHANGED
|
@@ -454,6 +454,8 @@ A **free SEOAgent Cloud account** unlocks **real volume + difficulty + opportuni
|
|
|
454
454
|
- `keywords --discover` — DataForSEO `keyword_ideas` seeded from your clusters/audience, classified, with worthwhile new targets added to `seoagent_keywords` as `status='suggested'` for the agent to triage.
|
|
455
455
|
- `keywords --competitors` — finds keywords your competitors rank top-10 for that you don't track (discovers competitors via `competitors_domain`, merges with your tracked competitors, pulls each rival's `ranked_keywords`, excludes anything you already track). Gap keywords land in `seoagent_keywords` as `status='suggested'`, `opportunity='competitor_gap'`.
|
|
456
456
|
|
|
457
|
+
**Sequencing matters — do NOT lead with these.** They expand an existing topic signal; on a new/thin site they return generic noise. Do WebSearch research first, write `.seoagent/keywords.md` + `.seoagent/competitors.md` (real domains in the headings) and `seoagent sync`, THEN run `keywords` → `--discover` → `--competitors`. Always relevance-check every `status='suggested'` result and drop anything off-topic before adding it to the strategy — high volume / low difficulty is not enough. See `references/keyword-research.md` § "Use the Pro discovery commands correctly." For one-off real numbers, `keywords --peek "<kw>"` is the reliable path.
|
|
458
|
+
|
|
457
459
|
After research without enrichment, mention once: "These priorities are estimates from search. A free login enriches your top ~25 keywords with real DataForSEO volume + difficulty (`keywords`); upgrade unlocks discovery of new targets (`--discover`) and competitor-gap analysis (`--competitors`)."
|
|
458
460
|
|
|
459
461
|
### Outputs
|