@seoagent-official/seoagent 1.49.0 → 1.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -107,6 +107,8 @@ SEOAgent runs as a CLI on top of the [Claude Agent SDK](https://github.com/anthr
107
107
 
108
108
  **Image Generation (Bring Your Own Key)** — Detect `OPENAI_API_KEY`, `FAL_KEY`, or `REPLICATE_API_TOKEN` from your env. Generate hero + inline images with `npx @seoagent-official/seoagent generate-image`. You pay the LLM provider directly.
109
109
 
110
+ **Open Knowledge Format bundle (AEO/GEO)** — Generate a Google [Open Knowledge Format](https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf) bundle for your site — a curated, agent-readable knowledge layer so ChatGPT, Claude, Perplexity, and Google's AI understand and cite your business accurately. Claude maps your `.seoagent/` knowledge into OKF markdown; `npx @seoagent-official/seoagent okf scaffold` and `okf validate` handle the structure. Saved to `.seoagent/okf/`.
111
+
110
112
  **Compounding Roadmap** — Prioritized action plan that updates after every action. Saved to `.seoagent/roadmap.md`. Persistent changelog at `.seoagent/changelog.md`.
111
113
 
112
114
  ## Project Structure
@@ -126,6 +128,11 @@ SEOAgent runs as a CLI on top of the [Claude Agent SDK](https://github.com/anthr
126
128
  content/
127
129
  {article-slug}.md # Article with full SEO frontmatter + JSON-LD
128
130
  images/ # Generated hero + inline images
131
+ okf/ # Open Knowledge Format bundle for AI agents (AEO/GEO)
132
+ index.md # type: Organization — business overview
133
+ concepts/ # type: Concept|Topic — definitive explanations
134
+ faqs/ # type: FAQ — answer-engine Q&A
135
+ articles/ # type: Article — published pages (resource = live URL)
129
136
  pages.md # Sitemap inventory (URL list)
130
137
  competitors.md # Competitor profiles + gaps
131
138
  keywords.md # Master keyword inventory (assigned + backlog)
@@ -141,6 +148,7 @@ SEOAgent runs as a CLI on top of the [Claude Agent SDK](https://github.com/anthr
141
148
  long-tail-articles.md # Long-tail protocol
142
149
  programmatic.md # 12 programmatic SEO playbooks
143
150
  schema-markup.md # JSON-LD library by entity type
151
+ open-knowledge-format.md # OKF bundle protocol (AEO/GEO)
144
152
  keyword-research.md # WebSearch query patterns
145
153
  rewrite-protocol.md # Phase 4b refresh procedure
146
154
  audit-checks.md # Full audit check list with severity tiers
@@ -195,7 +203,7 @@ Three things to notice:
195
203
  2. **Priority badges** (`p:high · ⇧ +12% CTR · ⏱ 2 min`) tell you *which* actions to run first. The picker pre-selects high-priority entries by default — one Enter ships the highest-leverage work.
196
204
  3. **Declines self-ack.** When the agent decides an action is off-strategy, ambiguous, or a false positive, it emits `__DECLINED__: <reason>` and `seoagent ack --failed --reason "…"` fires automatically. You never type the reason by hand.
197
205
 
198
- ## CLI Commands (all 18)
206
+ ## CLI Commands (all 19)
199
207
 
200
208
  Grouped by what they're for. Run via `npx -y @seoagent-official/seoagent <cmd>` or, after `npm install -g @seoagent-official/seoagent`, just `seoagent <cmd>`.
201
209
 
@@ -235,6 +243,7 @@ Grouped by what they're for. Run via `npx -y @seoagent-official/seoagent <cmd>`
235
243
  | `keywords --peek "<kw>"` | Free single-keyword DataForSEO peek (no login, daily quota per install). |
236
244
  | `keywords` | Enrich your existing keyword inventory with real search volume + difficulty. `--discover` finds new targets; `--competitors` shows the gap (paid). |
237
245
  | `internal-links` | Generate internal-linking recommendations from your existing pages + topic clusters. |
246
+ | `okf [scaffold\|validate]` | Generate an [Open Knowledge Format](https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf) bundle for AI agents (AEO/GEO) → `.seoagent/okf/`. `scaffold` starts it; `validate` checks `type` fields, ISO-8601 timestamps + cross-links. The skill fills the content. |
238
247
  | `generate-image` | Generate hero / inline images via the detected provider (BYO API key). |
239
248
 
240
249
  **Account**
package/index.js CHANGED
@@ -1,34 +1,34 @@
1
1
  #!/usr/bin/env node
2
- import{Command as Vl}from"commander";import{dirname as yi,relative as Fn}from"path";import{intro as wi,outro as ki,text as Un,select as At,spinner as bi,isCancel as ue,cancel as de,confirm as $i}from"@clack/prompts";function ft(e=process.argv[1]){let t=process.env.SEOAGENT_INSTALL_FORM;return t==="global"?!0:t==="npx"||!e?!1:(e.split(/[/\\]/).pop()??"").replace(/\.(cmd|ps1|exe)$/i,"").toLowerCase()==="seoagent"}function p(e,t=ft()){return t?`seoagent ${e}`:`npx -y @seoagent-official/seoagent ${e}`}import{randomUUID as bo}from"crypto";import{existsSync as an,mkdirSync as ln,readFileSync as $o,writeFileSync as cn}from"fs";import{join as wt}from"path";var ie=[".env.local",".env.production",".env"],Zt=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];import{homedir as ao}from"os";import{join as We}from"path";var $=".seoagent",en=["audit","strategy/clusters","briefs","content","content/images","performance"],Q={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},Ge=".claude/settings.json",tn=".pull-receipt.json",nn=".ack-queue.json",rn=".sync.lock",on=`# SEOAgent local files
2
+ import{Command as hc}from"commander";import{dirname as Ri,relative as qn}from"path";import{intro as Pi,outro as Oi,text as zn,select as Nt,spinner as Ti,isCancel as pe,cancel as fe,confirm as Li}from"@clack/prompts";function xt(e=process.argv[1]){let t=process.env.SEOAGENT_INSTALL_FORM;return t==="global"?!0:t==="npx"||!e?!1:(e.split(/[/\\]/).pop()??"").replace(/\.(cmd|ps1|exe)$/i,"").toLowerCase()==="seoagent"}function p(e,t=xt()){return t?`seoagent ${e}`:`npx -y @seoagent-official/seoagent ${e}`}import{randomUUID as To}from"crypto";import{existsSync as hn,mkdirSync as yn,readFileSync as Lo,writeFileSync as wn}from"fs";import{join as Ct}from"path";var ae=[".env.local",".env.production",".env"],cn=["NEXT_PUBLIC_SITE_URL","SITE_URL","NEXT_PUBLIC_URL","NEXTAUTH_URL","VITE_SITE_URL"];import{homedir as $o}from"os";import{join as Ye}from"path";var $=".seoagent",un=["audit","strategy/clusters","briefs","content","content/images","performance"],ee={AGENTS:".agents/skills/seoagent",CLAUDE:".claude/skills/seoagent"},Je=".claude/settings.json",dn=".pull-receipt.json",pn=".ack-queue.json",fn=".sync.lock",mn=`# SEOAgent local files
3
3
  .legacy/
4
4
  content/images/*
5
5
  !content/images/.gitkeep
6
6
  .pull-receipt.json
7
7
  .ack-queue.json
8
8
  .sync.lock
9
- `,lo=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:We(ao(),".config"),D=We(lo,"seoagent"),q=We(D,"auth.json"),gt=We(D,"state");var ke="https://seoagent.com",se=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):ke,S={BASE:se,PRICING:`${se}/pricing`,LEAD_API:`${se}/api/cli/lead`,CLI_AUTH_PAGE:`${se}/cli/auth`,CLI_AUTH_POLL:`${se}/api/cli/auth/poll`,CLI_SYNC:`${se}/api/cli/sync`};import{readFileSync as co}from"fs";import{fileURLToPath as uo}from"url";import{dirname as po,join as mo}from"path";var sn="0.0.0";function fo(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return sn}function go(e=t=>co(t,"utf-8")){try{let t=po(uo(import.meta.url));return fo(e(mo(t,"package.json")))}catch{return sn}}var ae=go();import{existsSync as ho,readFileSync as yo}from"fs";var Ke="---";function wo(e){let t=e.trim();return t===""?"":t==="null"||t==="~"?null:t==="true"?!0:t==="false"?!1:t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):/^-?\d+$/.test(t)||/^-?\d+\.\d+$/.test(t)?Number(t):t}function ht(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==Ke)return{data:{},body:e};let n={},r=1;for(;r<t.length;r++){if(t[r].trim()===Ke){r++;break}let o=t[r],i=o.indexOf(":");if(i===-1)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1);s&&(n[s]=wo(a))}return{data:n,body:t.slice(r).join(`
10
- `)}}function He(e){if(!ho(e))return null;try{return ht(yo(e,"utf-8"))}catch{return null}}function ko(e){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return String(e);let t=String(e);return t===""||/[:#\[\]{}&*!|>'"%@`,]/.test(t)||/^\s|\s$/.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function yt(e,t=""){let n=[Ke];for(let[o,i]of Object.entries(e))i!==void 0&&n.push(`${o}: ${ko(i)}`);n.push(Ke);let r=t.length===0?"":t.startsWith(`
9
+ `,So=process.env.XDG_CONFIG_HOME&&process.env.XDG_CONFIG_HOME.trim().length>0?process.env.XDG_CONFIG_HOME:Ye($o(),".config"),M=Ye(So,"seoagent"),z=Ye(M,"auth.json"),vt=Ye(M,"state");var xe="https://seoagent.com",le=process.env.SEOAGENT_API_BASE&&process.env.SEOAGENT_API_BASE.trim().length>0?process.env.SEOAGENT_API_BASE.replace(/\/$/,""):xe,S={BASE:le,PRICING:`${le}/pricing`,LEAD_API:`${le}/api/cli/lead`,CLI_AUTH_PAGE:`${le}/cli/auth`,CLI_AUTH_POLL:`${le}/api/cli/auth/poll`,CLI_SYNC:`${le}/api/cli/sync`};import{readFileSync as xo}from"fs";import{fileURLToPath as vo}from"url";import{dirname as _o,join as Co}from"path";var gn="0.0.0";function Eo(e){try{let t=JSON.parse(e);if(typeof t.version=="string"&&/^\d+\.\d+\.\d+/.test(t.version))return t.version}catch{}return gn}function Ao(e=t=>xo(t,"utf-8")){try{let t=_o(vo(import.meta.url));return Eo(e(Co(t,"package.json")))}catch{return gn}}var ce=Ao();import{existsSync as Io,readFileSync as Ro}from"fs";var Ve="---";function Po(e){let t=e.trim();return t===""?"":t==="null"||t==="~"?null:t==="true"?!0:t==="false"?!1:t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):/^-?\d+$/.test(t)||/^-?\d+\.\d+$/.test(t)?Number(t):t}function ve(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!==Ve)return{data:{},body:e};let n={},r=1;for(;r<t.length;r++){if(t[r].trim()===Ve){r++;break}let o=t[r],i=o.indexOf(":");if(i===-1)continue;let s=o.slice(0,i).trim(),a=o.slice(i+1);s&&(n[s]=Po(a))}return{data:n,body:t.slice(r).join(`
10
+ `)}}function Xe(e){if(!Io(e))return null;try{return ve(Ro(e,"utf-8"))}catch{return null}}function Oo(e){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return String(e);let t=String(e);return t===""||/[:#\[\]{}&*!|>'"%@`,]/.test(t)||/^\s|\s$/.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function _t(e,t=""){let n=[Ve];for(let[o,i]of Object.entries(e))i!==void 0&&n.push(`${o}: ${Oo(i)}`);n.push(Ve);let r=t.length===0?"":t.startsWith(`
11
11
  `)?t:`
12
12
  ${t}`;return n.join(`
13
13
  `)+r+(r.endsWith(`
14
14
  `)?"":`
15
- `)}var So=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kt(){return bo()}var vo=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),xo="project.md";function be(e){return wt(e,$)}function qe(e){return wt(be(e),xo)}function un(e){return an(qe(e))}function C(e){let t=He(qe(e));if(!t)return null;let n=t.data;if(typeof n.domain!="string"||!n.domain)return null;let r=typeof n.image_provider=="string"?n.image_provider:void 0,o=typeof n.cms=="string"?n.cms:void 0,i=o&&vo.has(o)?o:void 0,s=typeof n.install_id=="string"?n.install_id:void 0;return{domain:n.domain,site_type:typeof n.site_type=="string"?n.site_type:"unknown",language:typeof n.language=="string"?n.language:"en",initialized_at:typeof n.initialized_at=="string"?n.initialized_at:"",seoagent_version:typeof n.seoagent_version=="string"?n.seoagent_version:"",install_id:s&&So.test(s)?s:void 0,image_provider:r==="openai"||r==="fal"||r==="replicate"||r==="none"?r:void 0,cms:i,blog_path:typeof n.blog_path=="string"&&n.blog_path?n.blog_path:void 0}}function dn(e){let t=C(e);if(!t)return null;if(t.install_id)return t.install_id;let n=kt();return $e(e,{install_id:n}),n}function _o(e){return["",`# SEOAgent Project \u2014 ${e.domain}`,"","This file holds project-level configuration for the SEOAgent skill.","The skill reads it on every session to know which domain it is working on.","",`Initialized ${e.initialized_at} with seoagent ${e.seoagent_version}.`,""].join(`
16
- `)}function Eo(e){let t={domain:e.domain,site_type:e.site_type,language:e.language,initialized_at:e.initialized_at,seoagent_version:e.seoagent_version};return e.install_id&&(t.install_id=e.install_id),e.image_provider&&(t.image_provider=e.image_provider),e.cms&&(t.cms=e.cms),e.blog_path&&(t.blog_path=e.blog_path),t}function pn(e,t){let n=be(e);ln(n,{recursive:!0});let r=yt(Eo(t),_o(t));cn(qe(e),r,"utf-8")}function $e(e,t){let n=qe(e);if(!an(n))return!1;let r=ht($o(n,"utf-8")),o={...r.data,...t};return cn(n,yt(o,r.body),"utf-8"),!0}function mn(e){let t=be(e);for(let n of en)ln(wt(t,n),{recursive:!0})}import{existsSync as ze,lstatSync as Co,mkdirSync as Se,readFileSync as fn,readdirSync as Ao,rmSync as Io,statSync as Po,symlinkSync as Ro,writeFileSync as gn}from"fs";import{dirname as Ye,join as M,relative as hn}from"path";import{fileURLToPath as To}from"url";var Oo=Ye(To(import.meta.url));function yn(){return M(Oo,"skills")}function Lo(){let e=M(yn(),"seoagent.md");if(ze(e))return fn(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function wn(e,t){let n=[];if(!ze(e))return n;for(let r of Ao(e,{withFileTypes:!0})){let o=M(e,r.name),i=M(t,r.name);r.isDirectory()?(Se(i,{recursive:!0}),n.push(...wn(o,i))):r.isFile()&&(Se(Ye(i),{recursive:!0}),gn(i,fn(o)),n.push(i))}return n}function kn(e,t){let n=ze(M(e,".agents")),r=M(e,n?Q.AGENTS:Q.CLAUDE),o=M(r,"SKILL.md");Se(r,{recursive:!0}),gn(o,t??Lo(),"utf-8");let i=M(yn(),"references"),s=M(r,"references"),a=[];try{ze(i)&&Po(i).isDirectory()&&(Se(s,{recursive:!0}),a=wn(i,s).map(u=>hn(r,u)))}catch{}let l=n?jo(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:l}}function jo(e,t){let n=M(e,Q.CLAUDE),r=null;try{r=Co(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{Io(n,{force:!0})}catch{return}}try{Se(Ye(n),{recursive:!0});let o=hn(Ye(n),t);return Ro(o,n,"dir"),n}catch{return}}import{existsSync as Je,mkdirSync as bt,readFileSync as No,writeFileSync as ve}from"fs";import{dirname as bn,join as le}from"path";var Fo="npx -y @seoagent-official/seoagent sync --silent";function $n(e){let t=le(e,$);bt(t,{recursive:!0});let n=le(t,".gitignore");ve(n,on,"utf-8");let r=le(t,"content","images",".gitkeep");return bt(bn(r),{recursive:!0}),Je(r)||ve(r,"","utf-8"),n}function $t(e){if(!Je(e))return{};try{let t=No(e,"utf-8");return JSON.parse(t)}catch{return{}}}function St(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function Sn(e){let t=le(e,Ge);bt(bn(t),{recursive:!0});let n=$t(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=r.find(i=>(i.matcher??"").includes("Write"));return o||(o={matcher:"Write|Edit",hooks:[]},r.push(o)),o.hooks.some(St)?(ve(t,JSON.stringify(n,null,2)+`
17
- `,"utf-8"),{file:t,added:!1}):(o.hooks.push({type:"command",command:Fo}),ve(t,JSON.stringify(n,null,2)+`
18
- `,"utf-8"),{file:t,added:!0})}function vn(e){let t=le(e,Ge);if(!Je(t))return!1;let n=$t(t).hooks?.PostToolUse;return Array.isArray(n)?n.some(r=>r.hooks?.some(St)):!1}function xn(e){let t=le(e,Ge);if(!Je(t))return{file:t,removed:!1};let n=$t(t),r=n.hooks?.PostToolUse;if(!Array.isArray(r))return{file:t,removed:!1};let o=!1;for(let i of r){let s=i.hooks.length;i.hooks=i.hooks.filter(a=>!St(a)),i.hooks.length!==s&&(o=!0)}return o?(n.hooks.PostToolUse=r.filter(i=>i.hooks.length>0),n.hooks.PostToolUse.length===0&&delete n.hooks.PostToolUse,n.hooks&&Object.keys(n.hooks).length===0&&delete n.hooks,ve(t,JSON.stringify(n,null,2)+`
19
- `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{readFileSync as Lc,writeFileSync as Uo,existsSync as jc}from"fs";import{join as Do}from"path";function _n(e){let t=[];t.push("# Business Context"),t.push("");let n=[["Name","name"],["Type","type"],["Audience","audience"],["Industry","industry"],["Location","location"],["Description","description"]];for(let[o,i]of n){let s=e.business[i];t.push(`- **${o}:** ${s||""}`)}let r=new Set(n.map(([,o])=>o));for(let[o,i]of Object.entries(e.business))if(!r.has(o)&&i){let s=o.charAt(0).toUpperCase()+o.slice(1);t.push(`- **${s}:** ${i}`)}if(t.push(""),t.push("# Writing Instructions"),t.push(""),e.writingInstructions.length>0)for(let o of e.writingInstructions)t.push(`- ${o}`);else t.push("- (Add your content writing guidelines here)");if(t.push(""),t.push("# Reference URLs"),t.push(""),e.referenceUrls.length>0)for(let o of e.referenceUrls)o.description?t.push(`- ${o.url} \u2014 ${o.description}`):t.push(`- ${o.url}`);else t.push("- (Add URLs the agent should reference for tone/style)");if(t.push(""),t.push("# Topics to Avoid"),t.push(""),e.topicsToAvoid.length>0)for(let o of e.topicsToAvoid)t.push(`- ${o}`);else t.push("- (Add topics the agent should never write about)");return t.push(""),t.push("# Content Tone"),t.push(""),t.push(e.contentTone||"professional"),t.push(""),t.push("# Additional Notes"),t.push(""),t.push(e.additionalNotes||"(Any other context you want the agent to know about your business, products, or audience.)"),t.push(""),t.join(`
20
- `)}var Mo="context.md";function Bo(e,t){let n=Do(e,".seoagent",Mo),r=_n(t);Uo(n,r,"utf-8")}function En(e,t){Bo(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as xe,readFileSync as Cn,readdirSync as Wo,statSync as An}from"fs";import{join as Z}from"path";var Go=[{cms:"strapi",deps:["strapi","@strapi/strapi","@strapi/"],envKeys:["STRAPI_URL","STRAPI_API_URL","NEXT_PUBLIC_STRAPI_URL","STRAPI_API_TOKEN"],fsMarkers:["strapi/","apps/strapi/","packages/strapi/","cms/"]},{cms:"wordpress",deps:["wpapi","wp-graphql","@wordpress/api-fetch","@wordpress/"],envKeys:["WORDPRESS_API_URL","WP_API_URL","NEXT_PUBLIC_WORDPRESS_URL"],fsMarkers:[]},{cms:"sanity",deps:["@sanity/client","next-sanity","sanity"],envKeys:["SANITY_PROJECT_ID","NEXT_PUBLIC_SANITY_PROJECT_ID","SANITY_API_TOKEN"],fsMarkers:["sanity/","studio/","sanity.config.ts","sanity.config.js"]},{cms:"contentful",deps:["contentful","@contentful/rich-text-react-renderer","@contentful/"],envKeys:["CONTENTFUL_SPACE_ID","CONTENTFUL_ACCESS_TOKEN","NEXT_PUBLIC_CONTENTFUL_SPACE_ID"],fsMarkers:[]},{cms:"ghost",deps:["@tryghost/content-api","@tryghost/"],envKeys:["GHOST_URL","GHOST_API_KEY","NEXT_PUBLIC_GHOST_URL"],fsMarkers:[]},{cms:"webflow",deps:["webflow-api"],envKeys:["WEBFLOW_API_TOKEN","WEBFLOW_SITE_ID"],fsMarkers:[]},{cms:"shopify",deps:["@shopify/hydrogen","@shopify/storefront-api-client","@shopify/shopify-api","@shopify/"],envKeys:["SHOPIFY_STOREFRONT_TOKEN","SHOPIFY_STORE_DOMAIN","SHOPIFY_ADMIN_API_TOKEN"],fsMarkers:["shopify.config.ts","shopify.config.js"]},{cms:"payload",deps:["payload","@payloadcms/next","@payloadcms/"],envKeys:["PAYLOAD_SECRET","PAYLOAD_PUBLIC_SERVER_URL"],fsMarkers:["payload.config.ts","payload.config.js"]},{cms:"directus",deps:["@directus/sdk","directus"],envKeys:["DIRECTUS_URL","DIRECTUS_TOKEN"],fsMarkers:[]}];function Ko(e){let t=Z(e,"package.json");if(!xe(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Cn(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function Ho(e,t){for(let n of t)if(n.endsWith("/")){if(e.startsWith(n))return!0}else if(e===n)return!0;return!1}function qo(e){let t={};for(let n of ie){let r=Z(e,n);if(xe(r))try{let o=Cn(r,"utf-8");for(let i of o.split(/\r?\n/)){let s=i.trim();if(!s||s.startsWith("#"))continue;let a=s.indexOf("=");if(a===-1)continue;let l=s.slice(0,a).trim();l&&!(l in t)&&(t[l]=n)}}catch{}}return t}function zo(e,t){let n=Z(e,t.replace(/\/$/,""));if(!xe(n))return!1;if(t.endsWith("/"))try{return An(n).isDirectory()}catch{return!1}return!0}function Yo(e){let t=["content","_posts","posts",Z("src","content")];for(let n of t){let r=Z(e,n);if(xe(r))try{if(!An(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of Wo(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(Z(s,a.name));continue}if(a.isFile()&&/\.(md|mdx)$/i.test(a.name))return{type:"directory",detail:n,source:`${n}/${a.name}`}}}}catch{}}return null}function Jo(e){let t=[{marker:"app/blog/page.tsx",path:"/blog"},{marker:"app/blog/page.jsx",path:"/blog"},{marker:"app/blog/page.js",path:"/blog"},{marker:"src/app/blog/page.tsx",path:"/blog"},{marker:"src/app/blog/page.jsx",path:"/blog"},{marker:"pages/blog/index.tsx",path:"/blog"},{marker:"pages/blog/index.jsx",path:"/blog"},{marker:"pages/blog/index.js",path:"/blog"},{marker:"src/pages/blog/index.tsx",path:"/blog"},{marker:"app/(blog)/page.tsx",path:"/blog"},{marker:"app/articles/page.tsx",path:"/articles"},{marker:"pages/articles/index.tsx",path:"/articles"},{marker:"app/posts/page.tsx",path:"/posts"},{marker:"pages/posts/index.tsx",path:"/posts"},{marker:"app/learn/page.tsx",path:"/learn"},{marker:"app/resources/page.tsx",path:"/resources"}];for(let n of t)if(xe(Z(e,n.marker)))return n.path;return null}function In(e){let t=[],{deps:n}=Ko(e),r=qo(e),o="none";for(let s of Go){let a=[];for(let l of Object.keys(n))if(Ho(l,s.deps)){a.push({type:"dep",detail:l,source:"package.json"});break}for(let l of s.envKeys)if(r[l]){a.push({type:"env",detail:l,source:r[l]});break}for(let l of s.fsMarkers)if(zo(e,l)){let u=l.endsWith("/")?"directory":"file";a.push({type:u,detail:l,source:l});break}if(a.length>0){o=s.cms,t.push(...a);break}}if(o==="none"){let s=Yo(e);s&&(o="mdx-local",t.push(s))}let i=Jo(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as ee,readFileSync as vt}from"fs";import{join as te}from"path";function Pn(e){try{return new URL(e).hostname}catch{return e}}function Rn(e){let t=e.toLowerCase();return!!(t==="github.com"||t.endsWith(".github.com")||t==="gitlab.com"||t.endsWith(".gitlab.com")||t==="bitbucket.org"||t.endsWith(".bitbucket.org")||t==="dev.azure.com"||t==="visualstudio.com"||t.endsWith(".visualstudio.com")||t==="npmjs.com"||t.endsWith(".npmjs.com"))}function Vo(e){for(let t of ie){let n=te(e,t);if(!ee(n))continue;let r=vt(n,"utf-8");for(let o of Zt){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Pn(s);if(Rn(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function Xo(e){let t=te(e,"package.json");if(!ee(t))return null;try{let n=JSON.parse(vt(t,"utf-8"));if(!n.homepage)return null;let r=Pn(n.homepage);return Rn(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function Tn(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ee(te(e,"pnpm-workspace.yaml"))&&n.push({field:"context",detail:"Monorepo workspace detected",source:"pnpm-workspace.yaml \u2014 using this directory for project signals"});let r=null;t?.("Scanning .env files for public / site URLs\u2026");let o=Vo(e);if(o)r=o.value,n.push({field:"domain",detail:o.value,source:o.source});else{t?.("Reading package.json homepage (skipping GitHub/GitLab repo URLs)\u2026");let a=Xo(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=te(e,"package.json"),s=null;if(ee(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(vt(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(m=>l.includes(m));if(u("@shopify/hydrogen","@shopify/polaris")||ee(te(e,"shopify.config.js"))||ee(te(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ee(te(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),m=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),g=u("next");d&&(g||m)?(s="saas",n.push({field:"site_type",detail:"saas",source:g?"payment SDK + Next.js in package.json":"payment SDK + auth library in package.json"})):!d&&u("astro","gatsby","contentlayer","next-mdx-remote","mdx-bundler","vitepress","vuepress","@docusaurus/core","docusaurus","nextra")&&(s="content",n.push({field:"site_type",detail:"content",source:u("vitepress","vuepress","@docusaurus/core","docusaurus","nextra")?"documentation / site generator in package.json (VitePress, Docusaurus, Nextra, etc.)":"content-oriented dependencies in package.json (no payment SDKs detected)"}))}}catch{}return{domain:r,siteType:s,evidence:n}}import{existsSync as Qo,readFileSync as Zo,readdirSync as ei,statSync as ti}from"fs";import{join as ne,sep as ni}from"path";var On=["tsx","jsx","js","mdx","md"],ri=["astro","md","mdx"],oi=5e3;function Ve(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let l=ii(i);if(l===null){r++;return}let u=n.get(l);if(u){u.in_sitemap=u.in_sitemap||a,u.source.includes(s)||(u.source+=`, ${s}`);return}n.set(l,{route:l,url:fi(t,l),in_sitemap:a,source:s})};for(let i of["app",ne("src","app")]){let s=ne(e,i);if(xt(s))for(let a of _t(s)){let l=Et(s,a),u=l[l.length-1];ui(u)&&(l.some(d=>d.startsWith("@"))||o(si(l.slice(0,-1)),"app router"))}}for(let i of["pages",ne("src","pages")]){let s=ne(e,i);if(xt(s))for(let a of _t(s)){let l=Et(s,a);if(l[0]==="api")continue;let u=l[l.length-1],d=Ct(u),m=On.includes(d),g=ri.includes(d);if(!m&&!g)continue;let y=Xe(u);di(y)||o(ai(l),g?"astro":"pages router")}}for(let i of[".","public"]){let s=ne(e,i);if(xt(s))for(let a of _t(s,i==="."?1:1/0)){let l=Et(s,a),u=l[l.length-1];Ct(u)==="html"&&(l.some(d=>d==="node_modules"||d.startsWith("."))||o(li(l),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=ne(e,...i.split("/"));if(Qo(s)){for(let a of pi(s)){let l=ci(a);l!==null&&o(l,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}function ii(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function si(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function ai(e){let t=[...e],n=Xe(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function li(e){let t=[...e],n=Xe(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function ci(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function ui(e){return Xe(e)==="page"&&On.includes(Ct(e))}function di(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function pi(e){try{let t=Zo(e,"utf-8"),n=[],r=/<loc>\s*([^<\s]+)\s*<\/loc>/gi,o;for(;(o=r.exec(t))!==null;)n.push(o[1].trim());return n}catch{return[]}}var mi=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function xt(e){try{return ti(e).isDirectory()}catch{return!1}}function*_t(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=ei(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=oi)return;if(a.name.startsWith("."))continue;let l=ne(o,a.name);if(a.isDirectory()){if(mi.has(a.name))continue;yield*r(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*r(e,1)}function Et(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(ni).filter(Boolean)}function Ct(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function Xe(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function fi(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as gi,writeFileSync as hi}from"fs";import{join as Ln}from"path";function Nn(e,t){if(t.length===0)return;let n=Ln(e,$);gi(n,{recursive:!0});let r=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
15
+ `)}var jo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Et(){return To()}var No=new Set(["strapi","wordpress","sanity","contentful","ghost","webflow","shopify","payload","directus","mdx-local","none"]),Fo="project.md";function _e(e){return Ct(e,$)}function Qe(e){return Ct(_e(e),Fo)}function kn(e){return hn(Qe(e))}function E(e){let t=Xe(Qe(e));if(!t)return null;let n=t.data;if(typeof n.domain!="string"||!n.domain)return null;let r=typeof n.image_provider=="string"?n.image_provider:void 0,o=typeof n.cms=="string"?n.cms:void 0,i=o&&No.has(o)?o:void 0,s=typeof n.install_id=="string"?n.install_id:void 0;return{domain:n.domain,site_type:typeof n.site_type=="string"?n.site_type:"unknown",language:typeof n.language=="string"?n.language:"en",initialized_at:typeof n.initialized_at=="string"?n.initialized_at:"",seoagent_version:typeof n.seoagent_version=="string"?n.seoagent_version:"",install_id:s&&jo.test(s)?s:void 0,image_provider:r==="openai"||r==="fal"||r==="replicate"||r==="none"?r:void 0,cms:i,blog_path:typeof n.blog_path=="string"&&n.blog_path?n.blog_path:void 0}}function bn(e){let t=E(e);if(!t)return null;if(t.install_id)return t.install_id;let n=Et();return Ce(e,{install_id:n}),n}function Do(e){return["",`# SEOAgent Project \u2014 ${e.domain}`,"","This file holds project-level configuration for the SEOAgent skill.","The skill reads it on every session to know which domain it is working on.","",`Initialized ${e.initialized_at} with seoagent ${e.seoagent_version}.`,""].join(`
16
+ `)}function Uo(e){let t={domain:e.domain,site_type:e.site_type,language:e.language,initialized_at:e.initialized_at,seoagent_version:e.seoagent_version};return e.install_id&&(t.install_id=e.install_id),e.image_provider&&(t.image_provider=e.image_provider),e.cms&&(t.cms=e.cms),e.blog_path&&(t.blog_path=e.blog_path),t}function $n(e,t){let n=_e(e);yn(n,{recursive:!0});let r=_t(Uo(t),Do(t));wn(Qe(e),r,"utf-8")}function Ce(e,t){let n=Qe(e);if(!hn(n))return!1;let r=ve(Lo(n,"utf-8")),o={...r.data,...t};return wn(n,_t(o,r.body),"utf-8"),!0}function Sn(e){let t=_e(e);for(let n of un)yn(Ct(t,n),{recursive:!0})}import{existsSync as Ze,lstatSync as Bo,mkdirSync as Ee,readFileSync as xn,readdirSync as Mo,rmSync as Ko,statSync as Wo,symlinkSync as Go,writeFileSync as vn}from"fs";import{dirname as et,join as K,relative as _n}from"path";import{fileURLToPath as Ho}from"url";var qo=et(Ho(import.meta.url));function Cn(){return K(qo,"skills")}function zo(){let e=K(Cn(),"seoagent.md");if(Ze(e))return xn(e,"utf-8");throw new Error(`Could not find skill file at: ${e}`)}function En(e,t){let n=[];if(!Ze(e))return n;for(let r of Mo(e,{withFileTypes:!0})){let o=K(e,r.name),i=K(t,r.name);r.isDirectory()?(Ee(i,{recursive:!0}),n.push(...En(o,i))):r.isFile()&&(Ee(et(i),{recursive:!0}),vn(i,xn(o)),n.push(i))}return n}function An(e,t){let n=Ze(K(e,".agents")),r=K(e,n?ee.AGENTS:ee.CLAUDE),o=K(r,"SKILL.md");Ee(r,{recursive:!0}),vn(o,t??zo(),"utf-8");let i=K(Cn(),"references"),s=K(r,"references"),a=[];try{Ze(i)&&Wo(i).isDirectory()&&(Ee(s,{recursive:!0}),a=En(i,s).map(u=>_n(r,u)))}catch{}let l=n?Yo(e,r):void 0;return{skillFile:o,referenceFiles:a,claudeSymlink:l}}function Yo(e,t){let n=K(e,ee.CLAUDE),r=null;try{r=Bo(n)}catch{}if(r){if(!r.isSymbolicLink())return;try{Ko(n,{force:!0})}catch{return}}try{Ee(et(n),{recursive:!0});let o=_n(et(n),t);return Go(o,n,"dir"),n}catch{return}}import{existsSync as tt,mkdirSync as At,readFileSync as Jo,writeFileSync as Ae}from"fs";import{dirname as In,join as ue}from"path";var Vo="npx -y @seoagent-official/seoagent sync --silent";function Rn(e){let t=ue(e,$);At(t,{recursive:!0});let n=ue(t,".gitignore");Ae(n,mn,"utf-8");let r=ue(t,"content","images",".gitkeep");return At(In(r),{recursive:!0}),tt(r)||Ae(r,"","utf-8"),n}function It(e){if(!tt(e))return{};try{let t=Jo(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Rt(e){return e.command.includes("@seoagent-official/seoagent")&&e.command.includes("sync")}function Pn(e){let t=ue(e,Je);At(In(t),{recursive:!0});let n=It(t);n.hooks=n.hooks??{};let r=n.hooks.PostToolUse=n.hooks.PostToolUse??[],o=r.find(i=>(i.matcher??"").includes("Write"));return o||(o={matcher:"Write|Edit",hooks:[]},r.push(o)),o.hooks.some(Rt)?(Ae(t,JSON.stringify(n,null,2)+`
17
+ `,"utf-8"),{file:t,added:!1}):(o.hooks.push({type:"command",command:Vo}),Ae(t,JSON.stringify(n,null,2)+`
18
+ `,"utf-8"),{file:t,added:!0})}function On(e){let t=ue(e,Je);if(!tt(t))return!1;let n=It(t).hooks?.PostToolUse;return Array.isArray(n)?n.some(r=>r.hooks?.some(Rt)):!1}function Tn(e){let t=ue(e,Je);if(!tt(t))return{file:t,removed:!1};let n=It(t),r=n.hooks?.PostToolUse;if(!Array.isArray(r))return{file:t,removed:!1};let o=!1;for(let i of r){let s=i.hooks.length;i.hooks=i.hooks.filter(a=>!Rt(a)),i.hooks.length!==s&&(o=!0)}return o?(n.hooks.PostToolUse=r.filter(i=>i.hooks.length>0),n.hooks.PostToolUse.length===0&&delete n.hooks.PostToolUse,n.hooks&&Object.keys(n.hooks).length===0&&delete n.hooks,Ae(t,JSON.stringify(n,null,2)+`
19
+ `,"utf-8"),{file:t,removed:!0}):{file:t,removed:!1}}import{readFileSync as eu,writeFileSync as Xo,existsSync as tu}from"fs";import{join as Qo}from"path";function Ln(e){let t=[];t.push("# Business Context"),t.push("");let n=[["Name","name"],["Type","type"],["Audience","audience"],["Industry","industry"],["Location","location"],["Description","description"]];for(let[o,i]of n){let s=e.business[i];t.push(`- **${o}:** ${s||""}`)}let r=new Set(n.map(([,o])=>o));for(let[o,i]of Object.entries(e.business))if(!r.has(o)&&i){let s=o.charAt(0).toUpperCase()+o.slice(1);t.push(`- **${s}:** ${i}`)}if(t.push(""),t.push("# Writing Instructions"),t.push(""),e.writingInstructions.length>0)for(let o of e.writingInstructions)t.push(`- ${o}`);else t.push("- (Add your content writing guidelines here)");if(t.push(""),t.push("# Reference URLs"),t.push(""),e.referenceUrls.length>0)for(let o of e.referenceUrls)o.description?t.push(`- ${o.url} \u2014 ${o.description}`):t.push(`- ${o.url}`);else t.push("- (Add URLs the agent should reference for tone/style)");if(t.push(""),t.push("# Topics to Avoid"),t.push(""),e.topicsToAvoid.length>0)for(let o of e.topicsToAvoid)t.push(`- ${o}`);else t.push("- (Add topics the agent should never write about)");return t.push(""),t.push("# Content Tone"),t.push(""),t.push(e.contentTone||"professional"),t.push(""),t.push("# Additional Notes"),t.push(""),t.push(e.additionalNotes||"(Any other context you want the agent to know about your business, products, or audience.)"),t.push(""),t.join(`
20
+ `)}var Zo="context.md";function ei(e,t){let n=Qo(e,".seoagent",Zo),r=Ln(t);Xo(n,r,"utf-8")}function jn(e,t){ei(e,{business:{type:t||""},writingInstructions:[],referenceUrls:[],topicsToAvoid:[],contentTone:null,additionalNotes:null})}import{existsSync as Ie,readFileSync as Nn,readdirSync as ti,statSync as Fn}from"fs";import{join as te}from"path";var ni=[{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 ri(e){let t=te(e,"package.json");if(!Ie(t))return{deps:{},source:"package.json"};try{let n=JSON.parse(Nn(t,"utf-8"));return{deps:{...n.dependencies,...n.devDependencies,...n.peerDependencies},source:"package.json"}}catch{return{deps:{},source:"package.json"}}}function oi(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 ii(e){let t={};for(let n of ae){let r=te(e,n);if(Ie(r))try{let o=Nn(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 si(e,t){let n=te(e,t.replace(/\/$/,""));if(!Ie(n))return!1;if(t.endsWith("/"))try{return Fn(n).isDirectory()}catch{return!1}return!0}function ai(e){let t=["content","_posts","posts",te("src","content")];for(let n of t){let r=te(e,n);if(Ie(r))try{if(!Fn(r).isDirectory())continue;let o=[r],i=0;for(;o.length>0&&i<50;){let s=o.pop();for(let a of ti(s,{withFileTypes:!0}))if(i++,!a.name.startsWith(".")){if(a.isDirectory()&&o.length<5){o.push(te(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 li(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(Ie(te(e,n.marker)))return n.path;return null}function Dn(e){let t=[],{deps:n}=ri(e),r=ii(e),o="none";for(let s of ni){let a=[];for(let l of Object.keys(n))if(oi(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(si(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=ai(e);s&&(o="mdx-local",t.push(s))}let i=li(e);return{cms:o,blog_path:i,evidence:t}}import{existsSync as ne,readFileSync as Pt}from"fs";import{join as re}from"path";function Un(e){try{return new URL(e).hostname}catch{return e}}function Bn(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 ci(e){for(let t of ae){let n=re(e,t);if(!ne(n))continue;let r=Pt(n,"utf-8");for(let o of cn){let i=r.match(new RegExp(`^${o}=(.+)$`,"m"));if(i){let s=i[1].trim().replace(/^["']|["']$/g,""),a=Un(s);if(Bn(a))continue;return{value:a,source:`${t} (${o})`}}}}return null}function ui(e){let t=re(e,"package.json");if(!ne(t))return null;try{let n=JSON.parse(Pt(t,"utf-8"));if(!n.homepage)return null;let r=Un(n.homepage);return Bn(r)?null:{value:r,source:"package.json (homepage)"}}catch{return null}}function Mn(e,t){let n=[];t?.("Checking for monorepo / workspace layout\u2026"),ne(re(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=ci(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=ui(e);a&&(r=a.value,n.push({field:"domain",detail:a.value,source:a.source}))}let i=re(e,"package.json"),s=null;if(ne(i))try{t?.("Reading dependencies to infer site type\u2026");let a=JSON.parse(Pt(i,"utf-8")),l=Object.keys({...a.dependencies,...a.devDependencies}),u=(...d)=>d.some(f=>l.includes(f));if(u("@shopify/hydrogen","@shopify/polaris")||ne(re(e,"shopify.config.js"))||ne(re(e,"shopify.config.ts"))){s="product";let d=u("@shopify/hydrogen","@shopify/polaris")?"Shopify-related dependencies in package.json":ne(re(e,"shopify.config.ts"))?"shopify.config.ts":"shopify.config.js";n.push({field:"site_type",detail:"product",source:d})}else{let d=u("stripe","@stripe/stripe-js","@stripe/react-stripe-js","paddle","@paddle/paddle-js"),f=u("next-auth","@auth/core","lucia","clerk","@clerk/nextjs","@clerk/clerk-react"),m=u("next");d&&(m||f)?(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 di,readFileSync as pi,readdirSync as fi,statSync as mi}from"fs";import{join as oe,sep as gi}from"path";var Kn=["tsx","jsx","js","mdx","md"],hi=["astro","md","mdx"],yi=5e3;function nt(e,t){let n=new Map,r=0,o=(i,s,a=!1)=>{let l=wi(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:Ei(t,l),in_sitemap:a,source:s})};for(let i of["app",oe("src","app")]){let s=oe(e,i);if(Ot(s))for(let a of Tt(s)){let l=Lt(s,a),u=l[l.length-1];xi(u)&&(l.some(d=>d.startsWith("@"))||o(ki(l.slice(0,-1)),"app router"))}}for(let i of["pages",oe("src","pages")]){let s=oe(e,i);if(Ot(s))for(let a of Tt(s)){let l=Lt(s,a);if(l[0]==="api")continue;let u=l[l.length-1],d=jt(u),f=Kn.includes(d),m=hi.includes(d);if(!f&&!m)continue;let y=rt(u);vi(y)||o(bi(l),m?"astro":"pages router")}}for(let i of[".","public"]){let s=oe(e,i);if(Ot(s))for(let a of Tt(s,i==="."?1:1/0)){let l=Lt(s,a),u=l[l.length-1];jt(u)==="html"&&(l.some(d=>d==="node_modules"||d.startsWith("."))||o($i(l),"static html"))}}for(let i of["public/sitemap.xml","sitemap.xml"]){let s=oe(e,...i.split("/"));if(di(s)){for(let a of _i(s)){let l=Si(a);l!==null&&o(l,"sitemap.xml",!0)}break}}return{pages:[...n.values()].sort((i,s)=>i.route.localeCompare(s.route)),dynamicCount:r}}function wi(e){let t=e.trim();return t===""||t==="/"||(t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/+$/,""),t==="")?"/":/\[.*\]/.test(t)?null:t}function ki(e){return"/"+e.filter(n=>!(n.startsWith("(")&&n.endsWith(")"))).join("/")}function bi(e){let t=[...e],n=rt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function $i(e){let t=[...e],n=rt(t[t.length-1]);return n==="index"?t.pop():t[t.length-1]=n,"/"+t.join("/")}function Si(e){try{return new URL(e).pathname||"/"}catch{return e.startsWith("/")?e:null}}function xi(e){return rt(e)==="page"&&Kn.includes(jt(e))}function vi(e){return["_app","_document","_error","404","500","middleware"].includes(e)}function _i(e){try{let t=pi(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 Ci=new Set(["node_modules",".git",".next","dist","build",".vercel","out"]);function Ot(e){try{return mi(e).isDirectory()}catch{return!1}}function*Tt(e,t=1/0){let n=0;function*r(o,i){if(i>t)return;let s;try{s=fi(o,{withFileTypes:!0})}catch{return}for(let a of s){if(n>=yi)return;if(a.name.startsWith("."))continue;let l=oe(o,a.name);if(a.isDirectory()){if(Ci.has(a.name))continue;yield*r(l,i+1)}else a.isFile()&&(n++,yield l)}}yield*r(e,1)}function Lt(e,t){return t.slice(e.length).replace(/^[/\\]+/,"").split(gi).filter(Boolean)}function jt(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()}function rt(e){let t=e.lastIndexOf(".");return t===-1?e:e.slice(0,t)}function Ei(e,t){return e?`https://${e.replace(/^https?:\/\//,"").replace(/\/$/,"")}${t==="/"?"/":t}`:t}import{mkdirSync as Ai,writeFileSync as Ii}from"fs";import{join as Wn}from"path";function Hn(e,t){if(t.length===0)return;let n=Wn(e,$);Ai(n,{recursive:!0});let r=["---","generated: false",`discovered_at: ${new Date().toISOString()}`,`row_count: ${t.length}`,"---"].join(`
21
21
  `),o=["# Pages","","Inventory of pages discovered in your codebase at setup. Status,","rendered, and in-nav are filled in by the Phase 1 audit. Add or remove","rows freely \u2014 this file syncs to the cloud when you log in."].join(`
22
- `),i="| URL | In sitemap | In nav | Status | Rendered | Notes |",s="|---|---|---|---|---|---|",a=t.map(u=>`| ${jn(u.url)} | ${u.in_sitemap?"yes":"no"} | \u2014 | \u2014 | \u2014 | ${jn(u.source)} |`),l=[r,"",o,"",i,s,...a,""].join(`
23
- `);hi(Ln(n,"pages.md"),l,"utf-8")}function jn(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as ce}from"@clack/prompts";var c={info:e=>ce.info(e),warn:e=>ce.warn(e),error:e=>ce.error(e),success:e=>ce.success(e),step:e=>ce.step(e),message:e=>ce.message(e)};function k(e,t,n,r=n){e?e.stop(r):c[t](n)}var Dn=[{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"}],Bn="unknown",Si=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function vi(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 Qe(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return Si.has(t)?t:null}async function _e(e={}){let t=process.cwd();if(un(t)){c.warn("SEOAgent project already exists in this directory."),c.info(`Run \`${p("status")}\` to see your project state.`),c.info(`To start fresh, run \`${p("uninstall")}\` then init again.`);return}let n=!!e.yes||!process.stdin.isTTY;n||wi("SEOAgent \u2014 AI SEO Agent");let r=Tn(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 ${vi(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=Qe(e.siteType)||Qe(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&Qe(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()&&Qe(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=Bn),s||(s="unknown"),await Mn(t,i,s);return}if(o(),!i){let a=await Un({message:"Website domain",placeholder:"example.com",validate:l=>l.trim()?void 0:"Domain is required"});ue(a)&&(de("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await At({message:"What kind of site is this?",options:[...Dn]});ue(a)&&(de("Cancelled"),process.exit(0)),s=a}for(;;){let a=await $i({message:`Create .seoagent for ${i} (${s})?`});if(ue(a)&&(de("Cancelled"),process.exit(0)),a)break;let l=await At({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((ue(l)||l==="abort")&&(de("Cancelled"),process.exit(0)),l==="domain"){let u=await Un({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});ue(u)&&(de("Cancelled"),process.exit(0)),i=String(u)}else{let u=await At({message:"What kind of site is this?",options:[...Dn]});ue(u)&&(de("Cancelled"),process.exit(0)),s=u}}await Mn(t,i,s)}async function Mn(e,t,n){let r=bi();r.start("Setting up your SEO project");let o=In(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:ae,install_id:kt(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{}};mn(e),pn(e,i),En(e,n),$n(e);let s=kn(e),a=Fn(e,s.skillFile),l=yi(a),u=`${l}/references/audit-checks.md`,d=s.claudeSymlink?Fn(e,s.claudeSymlink):void 0;Sn(e);let m=t!==Bn,g={pages:[],dynamicCount:0};try{g=Ve(e,m?t:null),Nn(e,g.pages)}catch{}if(r.stop(m?`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(F=>`${F.detail} (${F.source})`).slice(0,2).join(", ");c.info(`CMS detected: ${o.cms} \u2014 ${I}`)}o.blog_path&&c.info(`Blog route: ${o.blog_path}`),g.pages.length>0&&c.info(`Found ${g.pages.length} page${g.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`+(g.dynamicCount>0?` (plus ${g.dynamicCount} dynamic route template${g.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""));let y=m?i.domain:"your site",R=m?[" 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."];ki([m?`\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):","",...R,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${y}`," (homepage + sitemap + robots.txt; the checks live in",` ${u} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${p("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${a} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${l} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${p("login")}`,""].join(`
24
- `))}import{existsSync as Kn}from"fs";import{intro as _i,outro as Ei,confirm as Ci,isCancel as Ai,cancel as Ii}from"@clack/prompts";import{existsSync as Ze,rmSync as xi}from"fs";import{join as et}from"path";function Wn(e,t={}){let n=[],r=et(e,$);Ze(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=et(e,Q.CLAUDE);Ze(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=et(e,Q.AGENTS);return Ze(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),vn(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:et(e,".claude","settings.json"),kind:"hook"}),t.global&&Ze(D)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:D,kind:"global"}),n}function Gn(e,t){for(let n of t)n.kind==="hook"?xn(e):xi(n.path,{recursive:!0,force:!0})}async function Ee(e={}){let t=process.cwd(),n=Wn(t,{global:e.global});if(n.length===0){c.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&Kn(D)&&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(`
25
- `);if(!r){_i("SEOAgent \u2014 uninstall"),c.message(`This will remove:
26
- ${o}`);let s=await Ci({message:"Remove these and start fresh?"});if(Ai(s)||!s){Ii("Cancelled \u2014 nothing was removed.");return}}Gn(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
22
+ `),i="| URL | In sitemap | In nav | Status | Rendered | Notes |",s="|---|---|---|---|---|---|",a=t.map(u=>`| ${Gn(u.url)} | ${u.in_sitemap?"yes":"no"} | \u2014 | \u2014 | \u2014 | ${Gn(u.source)} |`),l=[r,"",o,"",i,s,...a,""].join(`
23
+ `);Ii(Wn(n,"pages.md"),l,"utf-8")}function Gn(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}import{log as de}from"@clack/prompts";var c={info:e=>de.info(e),warn:e=>de.warn(e),error:e=>de.error(e),success:e=>de.success(e),step:e=>de.step(e),message:e=>de.message(e)};function k(e,t,n,r=n){e?e.stop(r):c[t](n)}var Yn=[{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"}],Vn="unknown",ji=new Set(["saas","service","product","content","marketplace","tool","app","nonprofit","community","unknown"]);function Ni(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 ot(e){if(!e?.trim())return null;let t=e.trim().toLowerCase();return ji.has(t)?t:null}async function Re(e={}){let t=process.cwd();if(kn(t)){c.warn("SEOAgent project already exists in this directory."),c.info(`Run \`${p("status")}\` to see your project state.`),c.info(`To start fresh, run \`${p("uninstall")}\` then init again.`);return}let n=!!e.yes||!process.stdin.isTTY;n||Pi("SEOAgent \u2014 AI SEO Agent");let r=Mn(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 ${Ni(a)}`)}},i=e.domain?.trim()||process.env.SEOAGENT_DOMAIN?.trim()||r.domain||null,s=ot(e.siteType)||ot(process.env.SEOAGENT_SITE_TYPE)||r.siteType||null;if(n){e.siteType?.trim()&&ot(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()&&ot(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=Vn),s||(s="unknown"),await Jn(t,i,s);return}if(o(),!i){let a=await zn({message:"Website domain",placeholder:"example.com",validate:l=>l.trim()?void 0:"Domain is required"});pe(a)&&(fe("Cancelled"),process.exit(0)),i=String(a)}if(!s){let a=await Nt({message:"What kind of site is this?",options:[...Yn]});pe(a)&&(fe("Cancelled"),process.exit(0)),s=a}for(;;){let a=await Li({message:`Create .seoagent for ${i} (${s})?`});if(pe(a)&&(fe("Cancelled"),process.exit(0)),a)break;let l=await Nt({message:"What should we change?",options:[{value:"domain",label:"Domain"},{value:"site_type",label:"Site type"},{value:"abort",label:"Cancel setup"}]});if((pe(l)||l==="abort")&&(fe("Cancelled"),process.exit(0)),l==="domain"){let u=await zn({message:"Website domain",placeholder:"example.com",validate:d=>d.trim()?void 0:"Domain is required"});pe(u)&&(fe("Cancelled"),process.exit(0)),i=String(u)}else{let u=await Nt({message:"What kind of site is this?",options:[...Yn]});pe(u)&&(fe("Cancelled"),process.exit(0)),s=u}}await Jn(t,i,s)}async function Jn(e,t,n){let r=Ti();r.start("Setting up your SEO project");let o=Dn(e),i={domain:t,site_type:n,language:"en",initialized_at:new Date().toISOString(),seoagent_version:ce,install_id:Et(),...o.cms!=="none"?{cms:o.cms}:{},...o.blog_path?{blog_path:o.blog_path}:{}};Sn(e),$n(e,i),jn(e,n),Rn(e);let s=An(e),a=qn(e,s.skillFile),l=Ri(a),u=`${l}/references/audit-checks.md`,d=s.claudeSymlink?qn(e,s.claudeSymlink):void 0;Pn(e);let f=t!==Vn,m={pages:[],dynamicCount:0};try{m=nt(e,f?t:null),Hn(e,m.pages)}catch{}if(r.stop(f?`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(U=>`${U.detail} (${U.source})`).slice(0,2).join(", ");c.info(`CMS detected: ${o.cms} \u2014 ${I}`)}o.blog_path&&c.info(`Blog route: ${o.blog_path}`),m.pages.length>0&&c.info(`Found ${m.pages.length} page${m.pages.length===1?"":"s"} in your codebase \u2192 .seoagent/pages.md`+(m.dynamicCount>0?` (plus ${m.dynamicCount} dynamic route template${m.dynamicCount===1?"":"s"} \u2014 the audit will discover their instances)`:""));let y=f?i.domain:"your site",P=f?[" 1. If .seoagent/project.md still says site_type: unknown, you can",` WebFetch ${i.domain} and update project.md with the right type`," before you suggest the audit."]:[" 1. Heads up: .seoagent/project.md has `domain: unknown` \u2014 the site URL"," wasn't detectable from this repo. Please ask your human for their"," domain (or read it from a deploy config / live site) and update"," project.md (`domain:` and `site_type:`) first. Everything else"," depends on it."];Oi([f?`\u2713 SEOAgent installed for ${i.domain}.`:"\u2713 SEOAgent installed (site URL not detected \u2014 please ask the user for it).","","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," AGENT INSTRUCTIONS \u2014 a friendly note for Claude Code, Codex, Cursor","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Hi there, coding agent! \u{1F44B} SEOAgent is all set up. The natural next step"," is a quick SEO audit \u2014 but your human is the boss here, so please surface"," what's possible and let THEM decide. Nothing in this message is a command;"," it's just a friendly map. Your real instructions live in the skill:","",` ${a} \u2190 read this; it is your source of truth`,""," If your human approves, here is what you can do (otherwise just let them"," know it's ready and wait for the go-ahead):","",...P,"",` 2. The headline next step: offer to run a Phase 1 SEO audit on ${y}`," (homepage + sitemap + robots.txt; the checks live in",` ${u} \u2014 read that first).`," If they say yes, report findings as:"," \u{1F6A8} Biggest Issue \u2192 \u26A0\uFE0F Also Worth Fixing \u2192 \u2705 What's Working",' \u2192 "What do you want to do?" with numbered options.',""," 3. When it feels right, let them know about the free cloud dashboard and"," offer to start it (their call) \u2014 and that keyword strategy (Phase 2 in"," the skill) is there whenever they want it:",` ${p("login")}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"," HUMAN USERS (if you ran this in your terminal, no AI agent)","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",""," Open Claude Code in this directory and say:",""," audit my site","",` The skill at ${a} is picked up automatically.`,...d?[` Symlinked at ${d} \u2192 ${l} so Claude Code finds it too.`]:[],""," Want the cloud dashboard now? Free account, ~30 seconds:","",` ${p("login")}`,""].join(`
24
+ `))}import{existsSync as Zn}from"fs";import{intro as Di,outro as Ui,confirm as Bi,isCancel as Mi,cancel as Ki}from"@clack/prompts";import{existsSync as it,rmSync as Fi}from"fs";import{join as st}from"path";function Xn(e,t={}){let n=[],r=st(e,$);it(r)&&n.push({label:".seoagent/ \u2014 project state + all generated work",path:r,kind:"dir"});let o=st(e,ee.CLAUDE);it(o)&&n.push({label:".claude/skills/seoagent/ \u2014 installed skill bundle",path:o,kind:"dir"});let i=st(e,ee.AGENTS);return it(i)&&n.push({label:".agents/skills/seoagent/ \u2014 installed skill bundle",path:i,kind:"dir"}),On(e)&&n.push({label:".claude/settings.json \u2014 sync hook entry (other settings preserved)",path:st(e,".claude","settings.json"),kind:"hook"}),t.global&&it(M)&&n.push({label:"~/.config/seoagent/ \u2014 login credentials + sync state (all projects)",path:M,kind:"global"}),n}function Qn(e,t){for(let n of t)n.kind==="hook"?Tn(e):Fi(n.path,{recursive:!0,force:!0})}async function Pe(e={}){let t=process.cwd(),n=Xn(t,{global:e.global});if(n.length===0){c.info("No SEOAgent install found in this directory \u2014 nothing to remove."),!e.global&&Zn(M)&&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(`
25
+ `);if(!r){Di("SEOAgent \u2014 uninstall"),c.message(`This will remove:
26
+ ${o}`);let s=await Bi({message:"Remove these and start fresh?"});if(Mi(s)||!s){Ki("Cancelled \u2014 nothing was removed.");return}}Qn(t,n);let i=n.map(s=>` \u2713 ${s.label}`).join(`
27
27
  `);r?c.success(`Removed:
28
- ${i}`):Ei(`Removed:
29
- ${i}`),!e.global&&Kn(D)&&c.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),c.info(`Re-install any time with \`${p("init")}\`.`)}import b from"picocolors";import{existsSync as qn,mkdirSync as Hn,readFileSync as Pi,writeFileSync as Ri,chmodSync as Ti,unlinkSync as Oi}from"fs";import{dirname as Li}from"path";function A(){if(!qn(q))return null;try{let e=JSON.parse(Pi(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||ke}}catch{return null}}function zn(e){Hn(D,{recursive:!0}),Hn(Li(q),{recursive:!0}),Ri(q,JSON.stringify(e,null,2)+`
30
- `,"utf-8");try{Ti(q,384)}catch{}}function Yn(){if(!qn(q))return!1;try{return Oi(q),!0}catch{return!1}}import{existsSync as Ce,readdirSync as It,statSync as ji,readFileSync as Jn}from"fs";import{join as pe}from"path";function Ni(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function Fi(e){let t=pe(e,"audit","latest.md");if(!Ce(t))return null;let n=He(t);if(!n)return null;let r=Jn(t,"utf-8"),o=Ni(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function Ui(e){try{let n=Jn(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 Di(e){let t=pe(e,"strategy","clusters");if(!Ce(t))return null;let n=It(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=Ui(pe(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function Mi(e){let t=pe(e,"briefs");if(!Ce(t))return null;let n=It(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function Bi(e){let t=pe(e,"content");if(!Ce(t))return null;let n=It(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function Wi(e){let t=pe(e,"roadmap.md");return Ce(t)?{exists:!0,updatedAt:ji(t).mtime.toISOString()}:null}function Vn(e){let t=C(e);if(!t)return null;let n=be(e);return{domain:t.domain,audit:Fi(n),strategy:Di(n),briefs:Mi(n),content:Bi(n),roadmap:Wi(n)}}import z from"picocolors";var Gi=/\x1b\[[0-9;]*m/g;function Xn(e){return e.replace(Gi,"").length}function L(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=Ki(n,t.title),s=z.dim(`\u251C${o}\u2524`),a=z.dim(`\u2514${o}\u2518`),l=[i];for(let u of e){if("sep"in u){l.push(s);continue}l.push(Hi(u.content,r))}return l.push(a),l.join(`
31
- `)}function Ki(e,t){if(!t)return z.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=Xn(t),r=e-5-n;return r<1?z.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${z.dim("\u250C\u2500 ")}${t}${z.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function Hi(e,t){let n=Xn(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${z.dim("\u2502")} ${r} ${z.dim("\u2502")}`}function Pt(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n} minutes ago`;let r=Math.floor(n/60);return r<24?`${r} hours ago`:`${Math.floor(r/24)} days ago`}function Ae(){let e=Vn(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${p("init")}\` to get started.`);return}c.message(qi(e))}function qi(e){if(!e)return"";let t=11,n=s=>b.dim(s.padEnd(t)),r=[];A()?(r.push({content:`${b.green("\u2713")} ${b.dim("Logged in")}`}),r.push({content:b.dim(` Run \`${p("whoami")}\` for email / plan.`)})):(r.push({content:`${b.dim("\u25CB Not logged in")}`}),r.push({content:b.dim(` Run \`${p("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${b.green(`last run ${Pt(e.audit.date??"")}`)} ${b.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${b.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${b.bold(b.cyan(String(e.strategy.clusterCount??0)))} ${b.dim("clusters")} \xB7 ${b.bold(b.cyan(String(e.strategy.articleCount??0)))} ${b.dim("ideas")}`:`${n("Strategy:")}${b.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${b.bold(b.cyan(String(e.briefs.count??0)))} ${b.dim("ready")}`:`${n("Briefs:")}${b.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${b.green("\u2713")} ${b.bold(b.cyan(String(e.content.count??0)))} ${b.dim("articles written")}`:`${n("Content:")}${b.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${b.green("updated")} ${b.dim(Pt(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${b.dim("not yet created")}`});let i=`${b.bold(b.cyan("SEOAgent"))} ${b.dim("\xB7")} ${b.bold(e.domain)}`;return L(r,{width:78,title:i})}import{exec as zi,spawn as Yi}from"child_process";import{confirm as Ji,isCancel as Vi}from"@clack/prompts";import O from"picocolors";var Xi="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Ie="@seoagent-official/seoagent",Pe=["free","starter","pro","scale","enterprise"],tt={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function Qi(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return Pe.includes(t)?t:null}function Zi(e){let t=Pe.indexOf(e);return t===-1||t===Pe.length-1?null:Pe[t+1]}async function es(e,t=fetch){if(!e)return null;try{let n=(e.api_base||S.BASE).replace(/\/$/,""),r=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!r.ok)return null;let o=await r.json();return typeof o.plan!="string"||!o.plan?null:{plan:o.plan,email:typeof o.email=="string"&&o.email?o.email:void 0,domain:typeof o.domain=="string"&&o.domain?o.domain:void 0}}catch{return null}}function ts(e){let t=[],r=s=>O.dim(s.padEnd(10)),o=!1;e.email&&(t.push({content:`${r("Email:")}${O.bold(e.email)}`}),o=!0),e.domain&&(t.push({content:`${r("Website:")}${O.cyan(e.domain)}`}),o=!0),o&&t.push({sep:!0});for(let s of Pe){let a=tt[s];s===e.current?t.push({content:`${O.bold(O.green("\u25CF"))} ${O.bold(O.green(a.padEnd(11)))} ${O.dim("\u2190 you are here")}`}):s===e.next?t.push({content:`${O.yellow("\u25C6")} ${O.bold(O.yellow(a.padEnd(11)))} ${O.yellow("next tier")}`}):t.push({content:O.dim(` ${a}`)})}let i=`${O.bold(O.cyan("SEOAgent Cloud"))} ${O.dim("\xB7")} ${O.dim("your plan")}`;return L(t,{width:55,title:i})}async function Re(){let e=A(),t=!!process.stdin.isTTY;if(e&&t){let n=await es(e);if(n){let r=Qi(n.plan),o=r?Zi(r):null;if(r&&c.message(ts({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){c.success(`You're on ${tt[r]} (highest tier).`);return}if(r&&o){let i=await Ji({message:`Upgrade from ${tt[r]} to ${tt[o]}?`});if(Vi(i)||!i){c.info("No changes.");return}}}}ns()}function ns(){let e=rs();c.info("Opening SEOAgent Cloud pricing..."),c.message(`URL: ${e}`);let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "${e}"`:`xdg-open "${e}"`;zi(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function rs(){let e=process.cwd(),t=C(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${S.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Te(e={}){let t=ae,n=await is();if(!n){c.warn("Couldn't reach the npm registry to check for a newer version."),c.message(`You're on ${t}. To force-update: npm install -g ${Ie}@latest`);return}if(os(t,n)>=0){c.success(`You're on the latest CLI (${t}).`);return}if(!ft()){c.info(`A newer CLI is available: ${t} \u2192 ${n}.`),c.message("You're running via npx \u2014 it already fetches the latest on every run."),c.message(`For a bare \`seoagent <cmd>\` form, install globally once: npm install -g ${Ie}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${Ie}@latest`);return}c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),await ss()?c.success(`Updated to ${n}.`):c.error(`Update failed. Try manually: npm install -g ${Ie}@latest (you may need sudo on Linux/macOS).`)}function os(e,t){let n=i=>i.replace(/[-+].*$/,"").split(".").map(s=>Number.parseInt(s,10)||0).slice(0,3),r=n(e),o=n(t);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s}return 0}async function is(e=fetch){try{let t=await e(Xi,{headers:{Accept:"application/json"}});if(!t.ok)return null;let n=await t.json();return typeof n.version=="string"?n.version:null}catch{return null}}function ss(){return new Promise(e=>{let t=Yi("npm",["install","-g",`${Ie}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as as}from"child_process";import{randomBytes as ls}from"crypto";import{isCancel as cs,spinner as us,text as ds}from"@clack/prompts";import Y from"picocolors";function Qn(e,t){if(e>=500)return{status:"error",terminal:!1,message:`HTTP ${e} (server error)`};if(e>=400)return{status:"error",terminal:!0,message:`HTTP ${e} (client error)`};if(!t||typeof t!="object")return{status:"error",terminal:!0,message:`Malformed response: expected an object, got ${typeof t}`};let n=t;if(n.status==="ready"){if(typeof n.user_token=="string"&&typeof n.website_token=="string"){let r=typeof n.email=="string"&&n.email?n.email:void 0,o=typeof n.domain=="string"&&n.domain?n.domain:void 0;return{status:"ready",user_token:n.user_token,website_token:n.website_token,...r?{email:r}:{},...o?{domain:o}:{}}}return{status:"error",terminal:!0,message:"Malformed response: status=ready without user_token+website_token"}}return n.status==="pending"?{status:"pending"}:n.status==="expired"?{status:"expired"}:{status:"error",terminal:!0,message:`Malformed response: unknown status=${JSON.stringify(n.status)}`}}var ps=1500,ms=300*1e3;function fs(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;as(t,()=>{})}function gs(){return ls(16).toString("hex")}function hs(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function Zn(e){let t=e.trim().replace(/^https?:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"");return!t||!/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(t)?null:t.toLowerCase()}async function ys(e,t){try{let n=`${e}/api/cli/auth/poll?session=${encodeURIComponent(t)}`,r=await fetch(n,{headers:{Accept:"application/json"}}),o=null;try{o=await r.json()}catch{}return Qn(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function ws(e){return new Promise(t=>setTimeout(t,e))}async function Oe(e={}){let t=process.cwd(),n=C(t),r=(e.apiBase||S.BASE||ke).replace(/\/$/,"");if(A()){c.info(`Already logged in. To switch accounts, run \`${p("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let m=await ds({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(y){if(!String(y??"").trim())return"A site URL is required.";if(!Zn(String(y)))return"Please enter a valid domain like `example.com`."}});if(cs(m)){c.warn("Login cancelled.");return}let g=Zn(String(m));if(g){o=g;try{$e(t,{domain:g}),c.success(`Saved domain: ${g} \u2192 .seoagent/project.md`)}catch{}}}let i=gs(),s=hs(r,i,o);c.message("Opening seoagent.com to connect this CLI to your account..."),c.info(`If the browser does not open, visit: ${s}`),fs(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?us():null;l?.start(Y.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+ms,d=!0;for(;Date.now()<u;){d||await ws(ps),d=!1;let m=await ys(r,i);if(m.status==="ready"){zn({user_token:m.user_token,website_token:m.website_token,api_base:r});let g=m.email&&m.domain?`Logged in as ${m.email} (${m.domain}). Future SEO work in this repo will sync to your dashboard.`:m.email?`Logged in as ${m.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",y=m.email&&m.domain?`Logged in as ${Y.bold(m.email)} (${Y.cyan(m.domain)}).`:m.email?`Logged in as ${Y.bold(m.email)}.`:"Logged in.";k(l,"success",g,Y.green(y)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(m.status==="expired"){k(l,"warn",`Session expired. Run \`${p("login")}\` again.`,Y.red("Session expired.")),l&&c.warn(`Run \`${p("login")}\` again.`);return}if(m.status==="error"){if(m.terminal){k(l,"warn",`Login failed: ${m.message}. Run \`${p("login")}\` again.`,Y.red(`Login failed: ${m.message}.`)),l&&c.warn(`Run \`${p("login")}\` again.`);return}continue}}k(l,"warn",`Login timed out. Run \`${p("login")}\` again to retry.`,Y.yellow("Login timed out.")),l&&c.warn(`Run \`${p("login")}\` again to retry.`)}function Le(){Yn()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as _a}from"@clack/prompts";import he from"picocolors";import{existsSync as Ft,mkdirSync as la,readFileSync as vr,readdirSync as ca,statSync as ua,writeFileSync as da}from"fs";import{join as Ut,relative as pa,sep as ma}from"path";var ks=new Set([502,503,504]);async function K(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.fetchImpl??fetch,s=n.sleep??bs,a=n.transientStatuses??ks,l=null;for(let u=0;u<r;u++)try{let d=await i(e,t);if(a.has(d.status)&&u<r-1){await s(er(o,u));continue}return d}catch(d){if(l=d,u<r-1){await s(er(o,u));continue}}throw l instanceof Error?l:new Error(String(l))}function er(e,t){return e*Math.pow(3,t)}function bs(e){return new Promise(t=>setTimeout(t,e))}import{existsSync as Tt,mkdirSync as $s,readdirSync as tr,readFileSync as Ss,unlinkSync as vs,writeFileSync as Rt}from"fs";import{join as fe}from"path";import E from"picocolors";function H(e){return fe(e,$,"inbox")}function nr(e){return`${e.action_type}-${e.id}.md`}function xs(e,t){let n=0;if(!Tt(e))return 0;for(let r of tr(e)){if(!r.endsWith(".md")||r==="README.md")continue;let o=r.match(/^(?:.+)-(\d+)\.md$/);if(!o)continue;let i=Number.parseInt(o[1],10);if(!Number.isNaN(i)&&!t.has(i))try{vs(fe(e,r)),n++}catch{}}return n}function _s(e){let t=e.payload||{},n=t.articleId??"unknown",r=t.slug??null,o=t.originalTitle??null,i=t.originalUrl??null,s=t.cmsType??null;return`---
28
+ ${i}`):Ui(`Removed:
29
+ ${i}`),!e.global&&Zn(M)&&c.info("Your seoagent.com login (~/.config/seoagent/) was kept \u2014 it is shared across projects. Run `uninstall --global` to wipe it too."),c.info(`Re-install any time with \`${p("init")}\`.`)}import b from"picocolors";import{existsSync as tr,mkdirSync as er,readFileSync as Wi,writeFileSync as Gi,chmodSync as Hi,unlinkSync as qi}from"fs";import{dirname as zi}from"path";function A(){if(!tr(z))return null;try{let e=JSON.parse(Wi(z,"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||xe}}catch{return null}}function nr(e){er(M,{recursive:!0}),er(zi(z),{recursive:!0}),Gi(z,JSON.stringify(e,null,2)+`
30
+ `,"utf-8");try{Hi(z,384)}catch{}}function rr(){if(!tr(z))return!1;try{return qi(z),!0}catch{return!1}}import{existsSync as Oe,readdirSync as Ft,statSync as Yi,readFileSync as or}from"fs";import{join as me}from"path";function Ji(e){let t=(e.match(/^\s*-\s+\[\s\]/gm)??[]).length,n=(e.match(/^\s*-\s+\[x\]/gim)??[]).length;return{open:t,done:n}}function Vi(e){let t=me(e,"audit","latest.md");if(!Oe(t))return null;let n=Xe(t);if(!n)return null;let r=or(t,"utf-8"),o=Ji(r);return{exists:!0,date:typeof n.data.audited_at=="string"?n.data.audited_at:void 0,issueCount:o.open}}function Xi(e){try{let n=or(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 Qi(e){let t=me(e,"strategy","clusters");if(!Oe(t))return null;let n=Ft(t).filter(o=>o.endsWith(".md"));if(n.length===0)return null;let r=0;for(let o of n)r+=Xi(me(t,o));return{exists:!0,clusterCount:n.length,articleCount:r}}function Zi(e){let t=me(e,"briefs");if(!Oe(t))return null;let n=Ft(t).filter(r=>r.endsWith(".md"));return n.length>0?{exists:!0,count:n.length}:null}function es(e){let t=me(e,"content");if(!Oe(t))return null;let n=Ft(t).filter(r=>r.endsWith(".md"));return n.length===0?null:{exists:!0,count:n.length}}function ts(e){let t=me(e,"roadmap.md");return Oe(t)?{exists:!0,updatedAt:Yi(t).mtime.toISOString()}:null}function ir(e){let t=E(e);if(!t)return null;let n=_e(e);return{domain:t.domain,audit:Vi(n),strategy:Qi(n),briefs:Zi(n),content:es(n),roadmap:ts(n)}}import Y from"picocolors";var ns=/\x1b\[[0-9;]*m/g;function sr(e){return e.replace(ns,"").length}function T(e,t={}){let n=t.width??51,r=n-4,o="\u2500".repeat(n-2),i=rs(n,t.title),s=Y.dim(`\u251C${o}\u2524`),a=Y.dim(`\u2514${o}\u2518`),l=[i];for(let u of e){if("sep"in u){l.push(s);continue}l.push(os(u.content,r))}return l.push(a),l.join(`
31
+ `)}function rs(e,t){if(!t)return Y.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`);let n=sr(t),r=e-5-n;return r<1?Y.dim(`\u250C${"\u2500".repeat(e-2)}\u2510`):`${Y.dim("\u250C\u2500 ")}${t}${Y.dim(` ${"\u2500".repeat(r)}\u2510`)}`}function os(e,t){let n=sr(e),r;return n<=t?r=e+" ".repeat(t-n):r=e,`${Y.dim("\u2502")} ${r} ${Y.dim("\u2502")}`}function Dt(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 Te(){let e=ir(process.cwd());if(!e){c.warn("No SEOAgent project found in this directory."),c.info(`Run \`${p("init")}\` to get started.`);return}c.message(is(e))}function is(e){if(!e)return"";let t=11,n=s=>b.dim(s.padEnd(t)),r=[];A()?(r.push({content:`${b.green("\u2713")} ${b.dim("Logged in")}`}),r.push({content:b.dim(` Run \`${p("whoami")}\` for email / plan.`)})):(r.push({content:`${b.dim("\u25CB Not logged in")}`}),r.push({content:b.dim(` Run \`${p("login")}\` to connect.`)})),r.push({sep:!0}),r.push({content:e.audit?.exists?`${n("Audit:")}${b.green(`last run ${Dt(e.audit.date??"")}`)} ${b.dim(`(${e.audit.issueCount??0} issues)`)}`:`${n("Audit:")}${b.dim("not yet run")}`}),r.push({content:e.strategy?.exists?`${n("Strategy:")}${b.bold(b.cyan(String(e.strategy.clusterCount??0)))} ${b.dim("clusters")} \xB7 ${b.bold(b.cyan(String(e.strategy.articleCount??0)))} ${b.dim("ideas")}`:`${n("Strategy:")}${b.dim("not yet created")}`}),r.push({content:e.briefs?.exists?`${n("Briefs:")}${b.bold(b.cyan(String(e.briefs.count??0)))} ${b.dim("ready")}`:`${n("Briefs:")}${b.dim("none created")}`}),r.push({content:e.content?.exists?`${n("Content:")}${b.green("\u2713")} ${b.bold(b.cyan(String(e.content.count??0)))} ${b.dim("articles written")}`:`${n("Content:")}${b.dim("no articles yet")}`}),r.push({content:e.roadmap?.exists?`${n("Roadmap:")}${b.green("updated")} ${b.dim(Dt(e.roadmap.updatedAt??""))}`:`${n("Roadmap:")}${b.dim("not yet created")}`});let i=`${b.bold(b.cyan("SEOAgent"))} ${b.dim("\xB7")} ${b.bold(e.domain)}`;return T(r,{width:78,title:i})}import{exec as ss,spawn as as}from"child_process";import{confirm as ls,isCancel as cs}from"@clack/prompts";import L from"picocolors";var us="https://registry.npmjs.org/@seoagent-official/seoagent/latest",Le="@seoagent-official/seoagent",je=["free","starter","pro","scale","enterprise"],at={free:"Free",starter:"Starter",pro:"Pro",scale:"Scale",enterprise:"Enterprise"};function ds(e){let t=e.trim().toLowerCase().split(/\s+/)[0];return je.includes(t)?t:null}function ps(e){let t=je.indexOf(e);return t===-1||t===je.length-1?null:je[t+1]}async function fs(e,t=fetch){if(!e)return null;try{let n=(e.api_base||S.BASE).replace(/\/$/,""),r=await t(`${n}/api/cli/whoami`,{headers:{Authorization:`Bearer ${e.user_token}:${e.website_token}`,Accept:"application/json"}});if(!r.ok)return null;let o=await r.json();return typeof o.plan!="string"||!o.plan?null:{plan:o.plan,email:typeof o.email=="string"&&o.email?o.email:void 0,domain:typeof o.domain=="string"&&o.domain?o.domain:void 0}}catch{return null}}function ms(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 je){let a=at[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 T(t,{width:55,title:i})}async function Ne(){let e=A(),t=!!process.stdin.isTTY;if(e&&t){let n=await fs(e);if(n){let r=ds(n.plan),o=r?ps(r):null;if(r&&c.message(ms({email:n.email,domain:n.domain,current:r,next:o})),r&&!o){c.success(`You're on ${at[r]} (highest tier).`);return}if(r&&o){let i=await ls({message:`Upgrade from ${at[r]} to ${at[o]}?`});if(cs(i)||!i){c.info("No changes.");return}}}}gs()}function gs(){let e=hs();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}"`;ss(t,n=>{n&&c.warn("Could not open browser. Visit the URL above to upgrade.")})}function hs(){let e=process.cwd(),t=E(e),n=t?.domain&&t.domain!=="unknown"?t.domain:"";return`${S.PRICING}?ref=cli${n?`&domain=${encodeURIComponent(n)}`:""}`}async function Fe(e={}){let t=ce,n=await ws();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 ${Le}@latest`);return}if(ys(t,n)>=0){c.success(`You're on the latest CLI (${t}).`);return}if(!xt()){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 ${Le}@latest`);return}if(e.dryRun){c.info(`(dry-run) would run: npm install -g ${Le}@latest`);return}c.info(`Updating CLI: ${t} \u2192 ${n}\u2026`),await ks()?c.success(`Updated to ${n}.`):c.error(`Update failed. Try manually: npm install -g ${Le}@latest (you may need sudo on Linux/macOS).`)}function ys(e,t){let n=i=>i.replace(/[-+].*$/,"").split(".").map(s=>Number.parseInt(s,10)||0).slice(0,3),r=n(e),o=n(t);for(let i=0;i<3;i++){let s=(r[i]??0)-(o[i]??0);if(s!==0)return s}return 0}async function ws(e=fetch){try{let t=await e(us,{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 ks(){return new Promise(e=>{let t=as("npm",["install","-g",`${Le}@latest`],{stdio:"inherit"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}import{exec as bs}from"child_process";import{randomBytes as $s}from"crypto";import{isCancel as Ss,spinner as xs,text as vs}from"@clack/prompts";import J from"picocolors";function ar(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 _s=1500,Cs=300*1e3;function Es(e){let t=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;bs(t,()=>{})}function As(){return $s(16).toString("hex")}function Is(e,t,n){let r=new URLSearchParams({session:t});return n&&n!=="unknown"&&r.set("domain",n),`${e}/cli/auth?${r.toString()}`}function lr(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 Rs(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 ar(r.status,o)}catch(n){return{status:"error",terminal:!1,message:n.message||"network error"}}}function Ps(e){return new Promise(t=>setTimeout(t,e))}async function De(e={}){let t=process.cwd(),n=E(t),r=(e.apiBase||S.BASE||xe).replace(/\/$/,"");if(A()){c.info(`Already logged in. To switch accounts, run \`${p("logout")}\` first.`);return}let o=n?.domain??null;if(o==="unknown"&&process.stdin.isTTY){let f=await vs({message:".seoagent/project.md has `domain: unknown`. What is your site's URL?",placeholder:"example.com",validate(y){if(!String(y??"").trim())return"A site URL is required.";if(!lr(String(y)))return"Please enter a valid domain like `example.com`."}});if(Ss(f)){c.warn("Login cancelled.");return}let m=lr(String(f));if(m){o=m;try{Ce(t,{domain:m}),c.success(`Saved domain: ${m} \u2192 .seoagent/project.md`)}catch{}}}let i=As(),s=Is(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}`),Es(s),c.info('In your browser: sign in (if needed) and click "Connect this CLI" to finish.');let l=!!process.stdout.isTTY?xs():null;l?.start(J.dim("Waiting for browser confirmation\u2026"));let u=Date.now()+Cs,d=!0;for(;Date.now()<u;){d||await Ps(_s),d=!1;let f=await Rs(r,i);if(f.status==="ready"){nr({user_token:f.user_token,website_token:f.website_token,api_base:r});let m=f.email&&f.domain?`Logged in as ${f.email} (${f.domain}). Future SEO work in this repo will sync to your dashboard.`:f.email?`Logged in as ${f.email}. Future SEO work in this repo will sync to your dashboard.`:"Logged in. Future SEO work in this repo will sync to your dashboard.",y=f.email&&f.domain?`Logged in as ${J.bold(f.email)} (${J.cyan(f.domain)}).`:f.email?`Logged in as ${J.bold(f.email)}.`:"Logged in.";k(l,"success",m,J.green(y)),l&&c.info("Future SEO work in this repo will sync to your dashboard.");return}if(f.status==="expired"){k(l,"warn",`Session expired. Run \`${p("login")}\` again.`,J.red("Session expired.")),l&&c.warn(`Run \`${p("login")}\` again.`);return}if(f.status==="error"){if(f.terminal){k(l,"warn",`Login failed: ${f.message}. Run \`${p("login")}\` again.`,J.red(`Login failed: ${f.message}.`)),l&&c.warn(`Run \`${p("login")}\` again.`);return}continue}}k(l,"warn",`Login timed out. Run \`${p("login")}\` again to retry.`,J.yellow("Login timed out.")),l&&c.warn(`Run \`${p("login")}\` again to retry.`)}function Ue(){rr()?c.success("Logged out."):c.info("You were not logged in.")}import{spinner as Da}from"@clack/prompts";import we from"picocolors";import{existsSync as Ht,mkdirSync as $a,readFileSync as Or,readdirSync as Sa,statSync as xa,writeFileSync as va}from"fs";import{join as qt,relative as _a,sep as Ca}from"path";var Os=new Set([502,503,504]);async function H(e,t,n={}){let r=Math.max(1,n.attempts??3),o=Math.max(0,n.baseDelayMs??500),i=n.fetchImpl??fetch,s=n.sleep??Ts,a=n.transientStatuses??Os,l=null;for(let u=0;u<r;u++)try{let d=await i(e,t);if(a.has(d.status)&&u<r-1){await s(cr(o,u));continue}return d}catch(d){if(l=d,u<r-1){await s(cr(o,u));continue}}throw l instanceof Error?l:new Error(String(l))}function cr(e,t){return e*Math.pow(3,t)}function Ts(e){return new Promise(t=>setTimeout(t,e))}import{existsSync as Bt,mkdirSync as Ls,readdirSync as ur,readFileSync as js,unlinkSync as Ns,writeFileSync as Ut}from"fs";import{join as he}from"path";import C from"picocolors";function q(e){return he(e,$,"inbox")}function dr(e){return`${e.action_type}-${e.id}.md`}function Fs(e,t){let n=0;if(!Bt(e))return 0;for(let r of ur(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{Ns(he(e,r)),n++}catch{}}return n}function Ds(e){let t=e.payload||{},n=t.articleId??"unknown",r=t.slug??null,o=t.originalTitle??null,i=t.originalUrl??null,s=t.cmsType??null;return`---
32
32
  action_id: ${e.id}
33
33
  action_type: ${e.action_type}
34
34
  article_id: ${n}
@@ -71,8 +71,8 @@ positive, you disagree, etc.), close it out as failed with a reason:
71
71
  \`\`\`bash
72
72
  ${p(`ack ${e.id}`)} --failed --reason "kept; performs well off-search"
73
73
  \`\`\`
74
- `}function Es(e){switch(e){case"meta":return"Apply the **meta** fix \u2014 set the page's `<title>` / `<meta name=\"description\">` (or the framework's metadata API / frontmatter).";case"schema":return"Apply the **schema** fix \u2014 add or correct the JSON-LD structured data on the page.";case"canonical":return'Apply the **canonical** fix \u2014 set the correct `<link rel="canonical">` on the page.';case"internal_link":return"Apply the **internal_link** fix \u2014 add relevant internal links from related pages (look for high-authority pages on the same topic).";default:return["Apply the change for this issue:",' - **meta** \u2014 fix the `<title>` / `<meta name="description">` (or the framework\'s metadata API / frontmatter).'," - **schema** \u2014 add or correct JSON-LD structured data.",' - **canonical** \u2014 set the correct `<link rel="canonical">`.'," - **internal_link** \u2014 add relevant internal links (fix orphan/low-link pages)."," - **other** \u2014 follow the recommendation above."].join(`
75
- `)}}function Cs(e,t,n){if(n)return`Locate the page's source. It renders at \`${n}\` \u2014 find the matching route/template/markdown in this repo (look under \`app/\`, \`pages/\`, \`src/\`, \`content/\`).`;let r=(t||"").toLowerCase();return r.includes("robots")||r.includes("ai_bot")||r.includes("bot_policy")?"This is a site-wide policy issue. Edit `robots.txt` at the site root (or its generator \u2014 `app/robots.ts`, `public/robots.txt`, etc.) to add the appropriate `User-agent:` / `Allow:` / `Disallow:` rules.":r.includes("sitemap")?"This is a sitemap configuration issue. Edit your sitemap generator \u2014 `app/sitemap.ts`, `pages/sitemap.xml.ts`, `next-sitemap.config.js`, or the static `public/sitemap.xml`.":e==="canonical"?'This is a site-wide canonical pattern. Look in the layout/template that wraps your pages (e.g. `app/layout.tsx`, `_app.tsx`, theme `head` partial) \u2014 that\'s where the `<link rel="canonical">` is set for every page.':e==="schema"?"This is a site-wide schema gap. Apply JSON-LD to the layout/template (for Organization-level schema) or to specific page templates (for Article / Product / FAQPage etc.).":e==="meta"?"This is a site-wide metadata convention. Look at the page-template metadata \u2014 Next.js `generateMetadata()` / `metadata` export, Nuxt `useHead()`, Astro frontmatter, etc.":e==="internal_link"?"No specific page on file. Identify pages on the same topic/cluster from `.seoagent/strategy/clusters/` and add inbound links to the target page.":"This issue does not name a single page. Read the recommendation above, identify the relevant template/config in this repo, and apply the change there."}function As(e){let t=e.payload||{},n=t.page_url??null,r=t.issue??"other",o=t.check_id??"unknown",i=t.severity??"unknown",s=t.recommended_fix??null;return`---
74
+ `}function Us(e){switch(e){case"meta":return"Apply the **meta** fix \u2014 set the page's `<title>` / `<meta name=\"description\">` (or the framework's metadata API / frontmatter).";case"schema":return"Apply the **schema** fix \u2014 add or correct the JSON-LD structured data on the page.";case"canonical":return'Apply the **canonical** fix \u2014 set the correct `<link rel="canonical">` on the page.';case"internal_link":return"Apply the **internal_link** fix \u2014 add relevant internal links from related pages (look for high-authority pages on the same topic).";default:return["Apply the change for this issue:",' - **meta** \u2014 fix the `<title>` / `<meta name="description">` (or the framework\'s metadata API / frontmatter).'," - **schema** \u2014 add or correct JSON-LD structured data.",' - **canonical** \u2014 set the correct `<link rel="canonical">`.'," - **internal_link** \u2014 add relevant internal links (fix orphan/low-link pages)."," - **other** \u2014 follow the recommendation above."].join(`
75
+ `)}}function Bs(e,t,n){if(n)return`Locate the page's source. It renders at \`${n}\` \u2014 find the matching route/template/markdown in this repo (look under \`app/\`, \`pages/\`, \`src/\`, \`content/\`).`;let r=(t||"").toLowerCase();return r.includes("robots")||r.includes("ai_bot")||r.includes("bot_policy")?"This is a site-wide policy issue. Edit `robots.txt` at the site root (or its generator \u2014 `app/robots.ts`, `public/robots.txt`, etc.) to add the appropriate `User-agent:` / `Allow:` / `Disallow:` rules.":r.includes("sitemap")?"This is a sitemap configuration issue. Edit your sitemap generator \u2014 `app/sitemap.ts`, `pages/sitemap.xml.ts`, `next-sitemap.config.js`, or the static `public/sitemap.xml`.":e==="canonical"?'This is a site-wide canonical pattern. Look in the layout/template that wraps your pages (e.g. `app/layout.tsx`, `_app.tsx`, theme `head` partial) \u2014 that\'s where the `<link rel="canonical">` is set for every page.':e==="schema"?"This is a site-wide schema gap. Apply JSON-LD to the layout/template (for Organization-level schema) or to specific page templates (for Article / Product / FAQPage etc.).":e==="meta"?"This is a site-wide metadata convention. Look at the page-template metadata \u2014 Next.js `generateMetadata()` / `metadata` export, Nuxt `useHead()`, Astro frontmatter, etc.":e==="internal_link"?"No specific page on file. Identify pages on the same topic/cluster from `.seoagent/strategy/clusters/` and add inbound links to the target page.":"This issue does not name a single page. Read the recommendation above, identify the relevant template/config in this repo, and apply the change there."}function Ms(e){let t=e.payload||{},n=t.page_url??null,r=t.issue??"other",o=t.check_id??"unknown",i=t.severity??"unknown",s=t.recommended_fix??null;return`---
76
76
  action_id: ${e.id}
77
77
  action_type: ${e.action_type}
78
78
  issue: ${r}
@@ -95,8 +95,8 @@ ${s??e.description??"Apply the appropriate fix for this issue."}
95
95
 
96
96
  ## How to apply
97
97
 
98
- 1. ${Cs(r,o,n)}
99
- 2. ${Es(r)}
98
+ 1. ${Bs(r,o,n)}
99
+ 2. ${Us(r)}
100
100
  3. Show the user the diff before committing (confirm once per session, then proceed).
101
101
 
102
102
  ## How to close this out
@@ -113,7 +113,7 @@ next \`seoagent sync\`. If you disagree or it's a false positive, decline it:
113
113
  \`\`\`bash
114
114
  ${p(`ack ${e.id}`)} --failed --reason "not applicable; ..."
115
115
  \`\`\`
116
- `}function Is(e){let t=e.payload||{},n=t.brief_slug??null,r=t.primary_keyword??null,o=t.cluster??null,i=t.role??null,s=t.search_intent??null,a=t.priority??"medium";return`---
116
+ `}function Ks(e){let t=e.payload||{},n=t.brief_slug??null,r=t.primary_keyword??null,o=t.cluster??null,i=t.role??null,s=t.search_intent??null,a=t.priority??"medium";return`---
117
117
  action_id: ${e.id}
118
118
  action_type: ${e.action_type}
119
119
  brief_slug: ${n??""}
@@ -162,7 +162,7 @@ If you decide not to write it (off-strategy, duplicate, etc.), decline it:
162
162
  \`\`\`bash
163
163
  ${p(`ack ${e.id}`)} --failed --reason "skipped; ..."
164
164
  \`\`\`
165
- `}function Ps(e){let t=e.payload||{},n=t.page_url??null,r=t.reason??"stale_thin",o=t.metrics??null,i=o?Object.entries(o).map(([s,a])=>`- **${s}**: ${a??"(n/a)"}`).join(`
165
+ `}function Ws(e){let t=e.payload||{},n=t.page_url??null,r=t.reason??"stale_thin",o=t.metrics??null,i=o?Object.entries(o).map(([s,a])=>`- **${s}**: ${a??"(n/a)"}`).join(`
166
166
  `):"- (no metrics)";return`---
167
167
  action_id: ${e.id}
168
168
  action_type: ${e.action_type}
@@ -209,7 +209,7 @@ If you disagree (page is fine as-is, intentionally short, etc.), decline it:
209
209
  \`\`\`bash
210
210
  ${p(`ack ${e.id}`)} --failed --reason "kept as-is; ..."
211
211
  \`\`\`
212
- `}function Rs(e){let t=e.payload||{},n=t.sitemap_url??null,r=t.known_url_count??0,o=Array.isArray(t.urls)?t.urls:[],i=!!t.truncated,s=o.length>0?`\`\`\`
212
+ `}function Gs(e){let t=e.payload||{},n=t.sitemap_url??null,r=t.known_url_count??0,o=Array.isArray(t.urls)?t.urls:[],i=!!t.truncated,s=o.length>0?`\`\`\`
213
213
  ${o.join(`
214
214
  `)}
215
215
  \`\`\`${i?`
@@ -255,7 +255,7 @@ SEOAgent re-submits the sitemap to GSC on its schedule. If a sitemap already exi
255
255
  \`\`\`bash
256
256
  ${p(`ack ${e.id}`)} --failed --reason "sitemap already served at /sitemap.xml"
257
257
  \`\`\`
258
- `}function Ts(e){let t=e.payload||{},n=t.keyword??null,r=t.opportunity??"easy_win",o=t.volume??null,i=t.difficulty??null,s=t.intent??null,a=r==="competitor_gap"?"competitor gap (a rival ranks top-10 here, you don't)":"easy win (low difficulty, real volume)";return`---
258
+ `}function Hs(e){let t=e.payload||{},n=t.keyword??null,r=t.opportunity??"easy_win",o=t.volume??null,i=t.difficulty??null,s=t.intent??null,a=r==="competitor_gap"?"competitor gap (a rival ranks top-10 here, you don't)":"easy win (low difficulty, real volume)";return`---
259
259
  action_id: ${e.id}
260
260
  action_type: ${e.action_type}
261
261
  keyword: ${n??""}
@@ -313,10 +313,10 @@ decline it:
313
313
  \`\`\`bash
314
314
  ${p(`ack ${e.id}`)} --failed --reason "skipped; ..."
315
315
  \`\`\`
316
- `}function Os(e){switch(e.action_type){case"cli_prune_pending":return _s(e);case"cli_technical_fix":return As(e);case"cli_new_content":return Is(e);case"cli_content_update":return Ps(e);case"cli_sitemap_update":return Rs(e);case"cli_new_landing_page":return Ts(e);default:return null}}function Ls(e){if(e.length===0)return`# SEOAgent Inbox
316
+ `}function qs(e){switch(e.action_type){case"cli_prune_pending":return Ds(e);case"cli_technical_fix":return Ms(e);case"cli_new_content":return Ks(e);case"cli_content_update":return Ws(e);case"cli_sitemap_update":return Gs(e);case"cli_new_landing_page":return Hs(e);default:return null}}function zs(e){if(e.length===0)return`# SEOAgent Inbox
317
317
 
318
318
  No pending actions. Run \`seoagent sync\` later to check for new ones.
319
- `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${nr(n)}\``);return`# SEOAgent Inbox
319
+ `;let t=e.map(n=>`- **${n.action_type}** id \`${n.id}\` \u2014 ${n.title??"no title"} \u2192 see \`${dr(n)}\``);return`# SEOAgent Inbox
320
320
 
321
321
  You have **${e.length}** pending action${e.length===1?"":"s"} from your dashboard.
322
322
 
@@ -328,7 +328,7 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
328
328
 
329
329
  If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
330
330
  skill knows what to do.
331
- `}function re(e){let t=H(e);if(!Tt(t))return[];let n=[];for(let r of tr(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,m=null,g=null,y=null;try{let R=Ss(fe(t,r),"utf-8"),I=R.match(/^---\n([\s\S]*?)\n---/);if(I){let U=I[1];l=me(U,"severity"),u=me(U,"issue"),d=me(U,"page_url");let X=me(U,"priority");(X==="high"||X==="medium"||X==="low")&&(m=X),g=me(U,"impact_estimate"),y=me(U,"effort_estimate")}let x=R.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);x&&(a=x[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:l,issue:u,page_url:d,priority:m,impact_estimate:g,effort_estimate:y})}return n.sort((r,o)=>r.id-o.id)}function ge(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=js[e.severity??""]??E.dim,r=e.severity??"unknown",o=[E.dim("\u25B8"),E.bold(`id ${e.id}`),E.dim("\xB7"),E.cyan(t),n(r)];if(e.priority){let i=Ns[e.priority];o.push(E.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(E.dim("\xB7"),E.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(E.dim("\xB7"),E.dim(`\u23F1 ${e.effort_estimate}`)),o.push(E.dim("\u2014"),e.title),o.join(" ")}var js={critical:e=>E.red(E.bold(e)),high:e=>E.red(e),medium:e=>E.yellow(e),low:e=>E.dim(e)},Ns={high:e=>E.red(E.bold(e)),medium:e=>E.yellow(e),low:e=>E.dim(e)};function me(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 nt(e){let t=H(e);if(!Tt(t))return;let n=re(e),r=n.length===0?`# SEOAgent Inbox
331
+ `}function ie(e){let t=q(e);if(!Bt(t))return[];let n=[];for(let r of ur(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,f=null,m=null,y=null;try{let P=js(he(t,r),"utf-8"),I=P.match(/^---\n([\s\S]*?)\n---/);if(I){let B=I[1];l=ge(B,"severity"),u=ge(B,"issue"),d=ge(B,"page_url");let Z=ge(B,"priority");(Z==="high"||Z==="medium"||Z==="low")&&(f=Z),m=ge(B,"impact_estimate"),y=ge(B,"effort_estimate")}let v=P.replace(/^---\n[\s\S]*?\n---\n+/,"").match(/^#\s+(.+)$/m);v&&(a=v[1].trim())}catch{}n.push({id:s,action_type:i,title:a,filename:r,severity:l,issue:u,page_url:d,priority:f,impact_estimate:m,effort_estimate:y})}return n.sort((r,o)=>r.id-o.id)}function ye(e){let t=e.issue??e.action_type.replace(/^cli_/,"").replace(/_/g,"-"),n=Ys[e.severity??""]??C.dim,r=e.severity??"unknown",o=[C.dim("\u25B8"),C.bold(`id ${e.id}`),C.dim("\xB7"),C.cyan(t),n(r)];if(e.priority){let i=Js[e.priority];o.push(C.dim("\xB7"),i(`p:${e.priority}`))}return e.impact_estimate&&o.push(C.dim("\xB7"),C.green(`\u21E7 ${e.impact_estimate}`)),e.effort_estimate&&o.push(C.dim("\xB7"),C.dim(`\u23F1 ${e.effort_estimate}`)),o.push(C.dim("\u2014"),e.title),o.join(" ")}var Ys={critical:e=>C.red(C.bold(e)),high:e=>C.red(e),medium:e=>C.yellow(e),low:e=>C.dim(e)},Js={high:e=>C.red(C.bold(e)),medium:e=>C.yellow(e),low:e=>C.dim(e)};function ge(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 lt(e){let t=q(e);if(!Bt(t))return;let n=ie(e),r=n.length===0?`# SEOAgent Inbox
332
332
 
333
333
  No pending actions. Run \`seoagent sync\` later to check for new ones.
334
334
  `:`# SEOAgent Inbox
@@ -343,34 +343,34 @@ For each file, read it, take the action it describes, then run \`seoagent ack <a
343
343
 
344
344
  If you're using Claude Code, just open this directory and ask "process the inbox" \u2014 the
345
345
  skill knows what to do.
346
- `;Rt(fe(t,"README.md"),r,"utf-8")}function rr(e,t){let n=H(e);$s(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=xs(n,r),i=0;for(let s of t){let a=Os(s);a!==null&&(Rt(fe(n,nr(s)),a,"utf-8"),i++)}return Rt(fe(n,"README.md"),Ls(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as Ds}from"crypto";import{existsSync as sr,mkdirSync as Ms,readFileSync as Bs,statSync as ar,writeFileSync as ir,rmSync as Ws}from"fs";import{dirname as Gs,join as Ot,sep as Ks}from"path";function Fs(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Us=[{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 or(e,t){let n=Fs(e);for(let{cls:r,test:o}of Us)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function Hs(e){return"sha256:"+Ds("sha256").update(e).digest("hex")}function qs(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 zs(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:or(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 lr(e){let t=await ur({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 cr(e,t){return Ot(e,t.split("/").join(Ks))}function Ys(e,t,n){let r={};for(let o of t){let i=cr(e,o);if(!sr(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=ar(i),a=n[o],l=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:Hs(Bs(i,"utf-8")),locallyEdited:l}}return r}async function ur(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 dr(e){let t=Ot(e.projectDir,$),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!sr(t))return{...n,ok:!0};let r=await ur({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=Ys(t,i,e.stateFiles),a=qs(o,s,{force:e.force}),l={...n,cursor:o.now};for(let d of a){let m=cr(t,d.path);try{switch(d.kind){case"skip":l.skipped++;break;case"write":case"overwrite":{Ms(Gs(m),{recursive:!0}),ir(m,d.body??"","utf-8");let g=ar(m);e.stateFiles[d.path]={mtime:g.mtimeMs,size:g.size},d.kind==="write"?l.written++:l.overwritten++,d.note&&l.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":Ws(m,{force:!0}),delete e.stateFiles[d.path],l.deleted++;break;case"delete-skipped":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(g){l.ok=!1,l.error=`${d.path}: ${g.message}`}}(l.conflicts>0||!l.ok)&&(l.cursor=e.since);let u=zs(a,o,l.cursor,new Date().toISOString());if(u)try{ir(Ot(t,tn),JSON.stringify(u,null,2)+`
347
- `,"utf-8")}catch{}return l}import{existsSync as mr,mkdirSync as fr,readFileSync as Js,writeFileSync as Lt}from"fs";import{dirname as gr,join as Vs}from"path";var jt=1,pr=500;function Nt(e){return Vs(e,$,nn)}function rt(e){let t=Nt(e);if(!mr(t))return[];try{let n=Js(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==jt||!Array.isArray(o.entries)?[]:o.entries.filter(Xs)}catch{return[]}}function hr(e,t){let n=Nt(e),o=rt(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>pr?o.slice(-pr):o,s={version:jt,entries:i};try{fr(gr(n),{recursive:!0}),Lt(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function yr(e,t){if(t.length===0)return;let n=Nt(e),r=rt(e).filter(i=>!t.includes(i.action_id)),o={version:jt,entries:r};try{if(r.length===0&&mr(n)){Lt(n,JSON.stringify(o,null,2),"utf-8");return}fr(gr(n),{recursive:!0}),Lt(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function Xs(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 wr,readFileSync as Qs,unlinkSync as Zs,writeFileSync as ea,openSync as ta,closeSync as na,mkdirSync as ra}from"fs";import{dirname as oa,join as ia}from"path";var sa=6e4;function kr(e){return ia(e,$,rn)}function br(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??sa,i=kr(e);if(!wr(i))return ot(i,r,n());let s=Sr(i);return!s||n()-s.started_at>o||!aa(s.pid)?ot(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function $r(e,t={}){let n=t.pid??process.pid,r=kr(e);if(!wr(r))return;let o=Sr(r);if(!(o&&o.pid!==n))try{Zs(r)}catch{}}function ot(e,t,n){let r={pid:t,started_at:n};try{ra(oa(e),{recursive:!0});let o=ta(e,"w");try{ea(o,JSON.stringify(r))}finally{na(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Sr(e){try{let t=Qs(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 aa(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var fa=new Set([".md"]),ga=new Set(["inbox"]);function ha(e){let t=[];function n(r,o){if(Ft(r))for(let i of ca(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&ga.has(i.name))continue;let s=Ut(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);fa.has(l)&&t.push(s)}}}return n(e,""),t}function xr(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Ut(gt,`${t}.json`)}function ya(e){let t=xr(e);if(!Ft(t))return{files:{},last_synced_at:null};try{return JSON.parse(vr(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function wa(e,t){la(gt,{recursive:!0}),da(xr(e),JSON.stringify(t,null,2)+`
348
- `,"utf-8")}function ka(e,t){return pa(e,t).split(ma).join("/")}async function ba(e,t){try{let n=await K(`${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 $a(e,t,n){try{let r=await K(`${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 _r(e,t={}){let n=A();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=C(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=Ut(e,$);if(!Ft(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!br(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await Sa(e,t,n,r,o)}finally{$r(e)}}async function Sa(e,t,n,r,o){let i=ya(r.domain),s=ha(o),a=n.api_base||S.BASE,l=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,m=[],g=0,y=await va(e,a,l);if(!t.pullOnly)for(let T of s){let we=ka(o,T);if(t.pathFilter&&!we.endsWith(t.pathFilter))continue;let Be=ua(T),pt=i.files[we];if(!(!pt||pt.mtime!==Be.mtimeMs||pt.size!==Be.size)&&!t.force)continue;g++;let so=vr(T,"utf-8"),mt=await $a(a,{path:we,contents:so,domain:r.domain},l);mt.ok?(i.files[we]={mtime:Be.mtimeMs,size:Be.size},u++):(d++,m.push(`${we}: ${mt.status} ${mt.error??""}`.trim()))}let R=await ba(a,l),I=0,F=0;if(R.ok){let T=rr(e,R.actions);I=T.wrote,F=T.removed}else R.error&&m.push(`pull actions: ${R.error}`);let x,U=!1,X=i.last_synced_at;if(!t.pushOnly){let T=await dr({projectDir:e,apiBase:a,authHeader:l,since:i.last_synced_at,stateFiles:i.files,force:t.force});T.ok?X=T.cursor:(U=!0,T.error&&m.push(`pull: ${T.error}`)),x={written:T.written,overwritten:T.overwritten,skipped:T.skipped,conflicts:T.conflicts,deleted:T.deleted,warnings:T.warnings}}let io=!!x&&x.written+x.overwritten+x.deleted+x.conflicts>0;if(i.last_synced_at=X,wa(r.domain,i),g===0&&I===0&&F===0&&!io&&y.flushed===0&&y.dropped===0&&!U&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:m,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:x};let Qt=d===0&&!U;return{ok:Qt,reason:Qt?void 0:"error",synced:u,failed:d,errors:m,actionsPulled:I,actionsRemoved:F,acksFlushed:y.flushed,acksDropped:y.dropped,pull:x}}async function va(e,t,n){let r=rt(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let l=await xa(a,t,n);l==="flushed"?(o++,s.push(a.action_id)):l==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&yr(e,s),{flushed:o,dropped:i}}async function xa(e,t,n){try{let r=await K(`${t}/api/cli/actions/${e.action_id}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify({status:e.status,error_message:e.status==="failed"?e.reason:null,result:e.status==="failed"?{declined:!0,reason:e.reason}:{applied:!0}})});return r.ok?"flushed":r.status===409||r.status>=400&&r.status<500?"already-settled":"transient"}catch{return"transient"}}async function B(e={}){let t=!e.silent&&!!process.stdout.isTTY,n=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",r=t?_a():null;r?.start(`${n} ${he.dim(".seoagent/")} with your dashboard\u2026`);let o=await _r(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){o.ok||(process.exitCode=0);return}if(o.reason==="no-auth"){k(r,"info",`Not logged in. Run \`${p("login")}\` to enable cloud sync.`,he.dim("Not logged in \u2014 cloud sync skipped.")),r&&c.info(`Run \`${p("login")}\` to enable cloud sync.`);return}if(o.reason==="no-project"){k(r,"info",`No SEOAgent project here. Run \`${p("init")}\` first.`,he.dim("No SEOAgent project \u2014 sync skipped.")),r&&c.info(`Run \`${p("init")}\` first.`);return}if(o.reason==="no-changes"){k(r,"info","Already in sync.",he.green("Already in sync."));return}if(o.reason==="busy"){k(r,"info","Another sync is in progress \u2014 skipping this run.",he.dim("Another sync is in progress \u2014 skipping this run."));return}let i=Ea(o);k(r,"success",i??"Sync complete.",he.green(i??"Sync complete.")),o.synced>0&&c.success(`Synced ${o.synced} file${o.synced===1?"":"s"} to your dashboard.`);let s=o.pull;if(s){let a=s.written+s.overwritten;a>0&&c.success(`Pulled ${a} file${a===1?"":"s"} from the cloud`+(s.overwritten>0?` (${s.overwritten} updated)`:"")),s.deleted>0&&c.info(`Removed ${s.deleted} file${s.deleted===1?"":"s"} deleted in the cloud.`),s.conflicts>0&&c.warn(`${s.conflicts} conflict${s.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let l of s.warnings.slice(0,5))c.info(` \u2022 ${l}`)}if(o.acksFlushed&&o.acksFlushed>0&&c.success(`Flushed ${o.acksFlushed} offline ack${o.acksFlushed===1?"":"s"} from the queue.`),o.acksDropped&&o.acksDropped>0&&c.info(`Dropped ${o.acksDropped} stale ack${o.acksDropped===1?"":"s"} (already settled server-side).`),o.actionsPulled&&o.actionsPulled>0&&(c.success(`Pulled ${o.actionsPulled} pending action${o.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||c.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),o.actionsRemoved&&o.actionsRemoved>0&&c.info(`Cleaned up ${o.actionsRemoved} stale inbox file${o.actionsRemoved===1?"":"s"}.`),o.failed>0){c.warn(`${o.failed} file${o.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let a of o.errors.slice(0,3))c.info(` \u2022 ${a}`)}}function Ea(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 W(e){let t=C(e);return t||(c.error(`No SEOAgent project here. Run \`${p("init")}\` first.`),process.exitCode=1,null)}async function oe(e={}){if(e.print){let t=A();if(!t){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}if(!W(process.cwd()))return;let n=t.api_base||S.BASE,r=await lr({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(`
346
+ `;Ut(he(t,"README.md"),r,"utf-8")}function pr(e,t){let n=q(e);Ls(n,{recursive:!0});let r=new Set(t.map(s=>s.id)),o=Fs(n,r),i=0;for(let s of t){let a=qs(s);a!==null&&(Ut(he(n,dr(s)),a,"utf-8"),i++)}return Ut(he(n,"README.md"),zs(t),"utf-8"),{wrote:i,removed:o,inboxPath:n}}import{createHash as Qs}from"crypto";import{existsSync as gr,mkdirSync as Zs,readFileSync as ea,statSync as hr,writeFileSync as mr,rmSync as ta}from"fs";import{dirname as na,join as Mt,sep as ra}from"path";function Vs(e){return e.replace(/^\/+/,"").replace(/\\/g,"/")}var Xs=[{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 fr(e,t){let n=Vs(e);for(let{cls:r,test:o}of Xs)if(o(n))return t&&(r==="keywords"||r==="pages")?"generated-index":r;return"other"}function oa(e){return"sha256:"+Qs("sha256").update(e).digest("hex")}function ia(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 sa(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:fr(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 yr(e){let t=await kr({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 wr(e,t){return Mt(e,t.split("/").join(ra))}function aa(e,t,n){let r={};for(let o of t){let i=wr(e,o);if(!gr(i)){r[o]={exists:!1,locallyEdited:!1};continue}let s=hr(i),a=n[o],l=!a||a.mtime!==s.mtimeMs||a.size!==s.size;r[o]={exists:!0,contentHash:oa(ea(i,"utf-8")),locallyEdited:l}}return r}async function kr(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 br(e){let t=Mt(e.projectDir,$),n={ok:!0,written:0,overwritten:0,skipped:0,conflicts:0,deleted:0,warnings:[],cursor:e.since};if(!gr(t))return{...n,ok:!0};let r=await kr({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=aa(t,i,e.stateFiles),a=ia(o,s,{force:e.force}),l={...n,cursor:o.now};for(let d of a){let f=wr(t,d.path);try{switch(d.kind){case"skip":l.skipped++;break;case"write":case"overwrite":{Zs(na(f),{recursive:!0}),mr(f,d.body??"","utf-8");let m=hr(f);e.stateFiles[d.path]={mtime:m.mtimeMs,size:m.size},d.kind==="write"?l.written++:l.overwritten++,d.note&&l.warnings.push(`${d.path}: ${d.note}`);break}case"conflict":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"conflict"}`);break;case"delete":ta(f,{force:!0}),delete e.stateFiles[d.path],l.deleted++;break;case"delete-skipped":l.conflicts++,l.warnings.push(`${d.path}: ${d.note??"delete skipped"}`);break}}catch(m){l.ok=!1,l.error=`${d.path}: ${m.message}`}}(l.conflicts>0||!l.ok)&&(l.cursor=e.since);let u=sa(a,o,l.cursor,new Date().toISOString());if(u)try{mr(Mt(t,dn),JSON.stringify(u,null,2)+`
347
+ `,"utf-8")}catch{}return l}import{existsSync as Sr,mkdirSync as xr,readFileSync as la,writeFileSync as Kt}from"fs";import{dirname as vr,join as ca}from"path";var Wt=1,$r=500;function Gt(e){return ca(e,$,pn)}function ct(e){let t=Gt(e);if(!Sr(t))return[];try{let n=la(t,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object")return[];let o=r;return o.version!==Wt||!Array.isArray(o.entries)?[]:o.entries.filter(ua)}catch{return[]}}function _r(e,t){let n=Gt(e),o=ct(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>$r?o.slice(-$r):o,s={version:Wt,entries:i};try{xr(vr(n),{recursive:!0}),Kt(n,JSON.stringify(s,null,2),"utf-8")}catch{}}function Cr(e,t){if(t.length===0)return;let n=Gt(e),r=ct(e).filter(i=>!t.includes(i.action_id)),o={version:Wt,entries:r};try{if(r.length===0&&Sr(n)){Kt(n,JSON.stringify(o,null,2),"utf-8");return}xr(vr(n),{recursive:!0}),Kt(n,JSON.stringify(o,null,2),"utf-8")}catch{}}function ua(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 Er,readFileSync as da,unlinkSync as pa,writeFileSync as fa,openSync as ma,closeSync as ga,mkdirSync as ha}from"fs";import{dirname as ya,join as wa}from"path";var ka=6e4;function Ar(e){return wa(e,$,fn)}function Ir(e,t={}){let n=t.now??Date.now,r=t.pid??process.pid,o=t.staleMs??ka,i=Ar(e);if(!Er(i))return ut(i,r,n());let s=Pr(i);return!s||n()-s.started_at>o||!ba(s.pid)?ut(i,r,n()):{acquired:!1,reason:"held-by-live-process",held_by_pid:s.pid}}function Rr(e,t={}){let n=t.pid??process.pid,r=Ar(e);if(!Er(r))return;let o=Pr(r);if(!(o&&o.pid!==n))try{pa(r)}catch{}}function ut(e,t,n){let r={pid:t,started_at:n};try{ha(ya(e),{recursive:!0});let o=ma(e,"w");try{fa(o,JSON.stringify(r))}finally{ga(o)}return{acquired:!0}}catch{return{acquired:!1,reason:"held-but-pid-unknown"}}}function Pr(e){try{let t=da(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 ba(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var Ea=new Set([".md"]),Aa=new Set(["inbox"]);function Ia(e){let t=[];function n(r,o){if(Ht(r))for(let i of Sa(r,{withFileTypes:!0})){if(i.name.startsWith(".")||o===""&&Aa.has(i.name))continue;let s=qt(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);Ea.has(l)&&t.push(s)}}}return n(e,""),t}function Tr(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return qt(vt,`${t}.json`)}function Ra(e){let t=Tr(e);if(!Ht(t))return{files:{},last_synced_at:null};try{return JSON.parse(Or(t,"utf-8"))}catch{return{files:{},last_synced_at:null}}}function Pa(e,t){$a(vt,{recursive:!0}),va(Tr(e),JSON.stringify(t,null,2)+`
348
+ `,"utf-8")}function Oa(e,t){return _a(e,t).split(Ca).join("/")}async function Ta(e,t){try{let n=await H(`${e}/api/cli/actions/fetch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t},body:JSON.stringify({})});if(!n.ok){let o=await n.text().catch(()=>"");return{ok:!1,actions:[],error:`${n.status} ${o.slice(0,200)}`}}let r=await n.json().catch(()=>null);return!r||r.status!=="ok"||!Array.isArray(r.actions)?{ok:!1,actions:[],error:"Malformed response"}:{ok:!0,actions:r.actions}}catch(n){return{ok:!1,actions:[],error:n.message}}}async function La(e,t,n){try{let r=await H(`${e}/api/cli/sync`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify(t)});if(!r.ok){let o=await r.text().catch(()=>"");return{ok:!1,status:r.status,error:o.slice(0,200)}}return{ok:!0,status:r.status}}catch(r){return{ok:!1,status:0,error:r.message}}}async function Lr(e,t={}){let n=A();if(!n)return{ok:!0,reason:"no-auth",synced:0,failed:0,errors:[]};let r=E(e);if(!r)return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};let o=qt(e,$);if(!Ht(o))return{ok:!0,reason:"no-project",synced:0,failed:0,errors:[]};if(!Ir(e).acquired)return{ok:!0,reason:"busy",synced:0,failed:0,errors:[]};try{return await ja(e,t,n,r,o)}finally{Rr(e)}}async function ja(e,t,n,r,o){let i=Ra(r.domain),s=Ia(o),a=n.api_base||S.BASE,l=`Bearer ${n.user_token}:${n.website_token}`,u=0,d=0,f=[],m=0,y=await Na(e,a,l);if(!t.pullOnly)for(let O of s){let Se=Oa(o,O);if(t.pathFilter&&!Se.endsWith(t.pathFilter))continue;let ze=xa(O),$t=i.files[Se];if(!(!$t||$t.mtime!==ze.mtimeMs||$t.size!==ze.size)&&!t.force)continue;m++;let bo=Or(O,"utf-8"),St=await La(a,{path:Se,contents:bo,domain:r.domain},l);St.ok?(i.files[Se]={mtime:ze.mtimeMs,size:ze.size},u++):(d++,f.push(`${Se}: ${St.status} ${St.error??""}`.trim()))}let P=await Ta(a,l),I=0,U=0;if(P.ok){let O=pr(e,P.actions);I=O.wrote,U=O.removed}else P.error&&f.push(`pull actions: ${P.error}`);let v,B=!1,Z=i.last_synced_at;if(!t.pushOnly){let O=await br({projectDir:e,apiBase:a,authHeader:l,since:i.last_synced_at,stateFiles:i.files,force:t.force});O.ok?Z=O.cursor:(B=!0,O.error&&f.push(`pull: ${O.error}`)),v={written:O.written,overwritten:O.overwritten,skipped:O.skipped,conflicts:O.conflicts,deleted:O.deleted,warnings:O.warnings}}let ko=!!v&&v.written+v.overwritten+v.deleted+v.conflicts>0;if(i.last_synced_at=Z,Pa(r.domain,i),m===0&&I===0&&U===0&&!ko&&y.flushed===0&&y.dropped===0&&!B&&d===0)return{ok:!0,reason:"no-changes",synced:0,failed:0,errors:f,actionsPulled:0,actionsRemoved:0,acksFlushed:0,acksDropped:0,pull:v};let ln=d===0&&!B;return{ok:ln,reason:ln?void 0:"error",synced:u,failed:d,errors:f,actionsPulled:I,actionsRemoved:U,acksFlushed:y.flushed,acksDropped:y.dropped,pull:v}}async function Na(e,t,n){let r=ct(e);if(r.length===0)return{flushed:0,dropped:0};let o=0,i=0,s=[];for(let a of r){let l=await Fa(a,t,n);l==="flushed"?(o++,s.push(a.action_id)):l==="already-settled"&&(i++,s.push(a.action_id))}return s.length>0&&Cr(e,s),{flushed:o,dropped:i}}async function Fa(e,t,n){try{let r=await H(`${t}/api/cli/actions/${e.action_id}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n},body:JSON.stringify({status:e.status,error_message:e.status==="failed"?e.reason:null,result:e.status==="failed"?{declined:!0,reason:e.reason}:{applied:!0}})});return r.ok?"flushed":r.status===409||r.status>=400&&r.status<500?"already-settled":"transient"}catch{return"transient"}}async function W(e={}){let t=!e.silent&&!!process.stdout.isTTY,n=e.pullOnly?"Pulling":e.pushOnly?"Pushing":"Syncing",r=t?Da():null;r?.start(`${n} ${we.dim(".seoagent/")} with your dashboard\u2026`);let o=await Lr(process.cwd(),{pathFilter:e.path,force:e.force,pushOnly:e.pushOnly,pullOnly:e.pullOnly});if(e.silent){o.ok||(process.exitCode=0);return}if(o.reason==="no-auth"){k(r,"info",`Not logged in. Run \`${p("login")}\` to enable cloud sync.`,we.dim("Not logged in \u2014 cloud sync skipped.")),r&&c.info(`Run \`${p("login")}\` to enable cloud sync.`);return}if(o.reason==="no-project"){k(r,"info",`No SEOAgent project here. Run \`${p("init")}\` first.`,we.dim("No SEOAgent project \u2014 sync skipped.")),r&&c.info(`Run \`${p("init")}\` first.`);return}if(o.reason==="no-changes"){k(r,"info","Already in sync.",we.green("Already in sync."));return}if(o.reason==="busy"){k(r,"info","Another sync is in progress \u2014 skipping this run.",we.dim("Another sync is in progress \u2014 skipping this run."));return}let i=Ua(o);k(r,"success",i??"Sync complete.",we.green(i??"Sync complete.")),o.synced>0&&c.success(`Synced ${o.synced} file${o.synced===1?"":"s"} to your dashboard.`);let s=o.pull;if(s){let a=s.written+s.overwritten;a>0&&c.success(`Pulled ${a} file${a===1?"":"s"} from the cloud`+(s.overwritten>0?` (${s.overwritten} updated)`:"")),s.deleted>0&&c.info(`Removed ${s.deleted} file${s.deleted===1?"":"s"} deleted in the cloud.`),s.conflicts>0&&c.warn(`${s.conflicts} conflict${s.conflicts===1?"":"s"} \u2014 local changes kept. Re-run with --force to take the cloud version.`);for(let l of s.warnings.slice(0,5))c.info(` \u2022 ${l}`)}if(o.acksFlushed&&o.acksFlushed>0&&c.success(`Flushed ${o.acksFlushed} offline ack${o.acksFlushed===1?"":"s"} from the queue.`),o.acksDropped&&o.acksDropped>0&&c.info(`Dropped ${o.acksDropped} stale ack${o.acksDropped===1?"":"s"} (already settled server-side).`),o.actionsPulled&&o.actionsPulled>0&&(c.success(`Pulled ${o.actionsPulled} pending action${o.actionsPulled===1?"":"s"} \u2192 .seoagent/inbox/`),e.embedded||c.info(' Open Claude Code in this directory and ask it to "process the inbox", or read the files yourself.')),o.actionsRemoved&&o.actionsRemoved>0&&c.info(`Cleaned up ${o.actionsRemoved} stale inbox file${o.actionsRemoved===1?"":"s"}.`),o.failed>0){c.warn(`${o.failed} file${o.failed===1?"":"s"} failed to sync. Will retry next run.`);for(let a of o.errors.slice(0,3))c.info(` \u2022 ${a}`)}}function Ua(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 N(e){let t=E(e);return t||(c.error(`No SEOAgent project here. Run \`${p("init")}\` first.`),process.exitCode=1,null)}async function se(e={}){if(e.print){let t=A();if(!t){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}if(!N(process.cwd()))return;let n=t.api_base||S.BASE,r=await yr({apiBase:n,authHeader:`Bearer ${t.user_token}:${t.website_token}`,path:e.print});if(!r.ok){c.warn(r.error),process.exitCode=1;return}process.stdout.write(r.body),r.body.endsWith(`
349
349
  `)||process.stdout.write(`
350
- `);return}await B({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as Ca,readdirSync as Aa,unlinkSync as Ia}from"fs";import{join as Er}from"path";import{isCancel as Pa,select as Ra}from"@clack/prompts";async function J(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 Ta(),n===null)return;let r=n,o=A();if(!o){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}if(!W(process.cwd()))return;let i=o.api_base||S.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",l;try{l=await K(`${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{hr(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),Dt(r),nt(process.cwd()),t.silent||c.warn(`Network unavailable \u2014 ack queued locally. Run \`${p("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"){Dt(r),nt(process.cwd());let R=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||c.success(`Action ${r} was already ${R}.`);return}let m=typeof d?.code=="string"?d.code:null,g=typeof d?.error=="string"?d.error:u,y=m?`, code: ${m}`:"";c.error(`Server rejected ack (${l.status}${y}): ${g.slice(0,200)}`),process.exitCode=1;return}Dt(r),nt(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: ${Er($,"inbox")}`))}function Dt(e){let t=H(process.cwd());if(Ca(t)){for(let n of Aa(t))if(n.endsWith(`-${e}.md`))try{Ia(Er(t,n))}catch{}}}async function Ta(){let e=process.cwd(),t=re(e);if(t.length===0)return c.info("No pending actions in .seoagent/inbox/."),c.message(`Run \`${p("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 \`${p("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await Ra({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:ge(r)}))});return Pa(n)?(c.info("Cancelled \u2014 no action closed out."),null):n}import it from"picocolors";async function Mt(e={}){let t=process.cwd();if(!e.json&&!W(t))return;let n=re(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:H(t),actions:n})+`
351
- `);return}if(n.length===0){c.info(it.dim("No pending actions.")),c.message(`Run \`${p("sync")}\` to pull anything autopilot has queued, or \`${p("autopilot status")}\` to check whether autopilot is on.`);return}c.message(`${it.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),c.message("");for(let r of n)c.message(ge(r));c.message(""),c.message(`Apply one: ${it.bold(p("ack <id>"))} \xB7 Interactive picker: ${it.bold(p("ack"))} (no id)`)}import{readFileSync as Wa}from"fs";import{join as Ga,relative as Ka}from"path";import{confirm as Tr,isCancel as at,multiselect as Ha,note as jr,select as qa}from"@clack/prompts";import f from"picocolors";import{query as za}from"@anthropic-ai/claude-agent-sdk";import{existsSync as Oa,readdirSync as La}from"fs";import{homedir as ja}from"os";import{join as Na}from"path";import{execSync as Bt}from"child_process";function Wt(){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":Fa()?Ua()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function Fa(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return Bt(e,{stdio:"ignore"}),!0}catch{return!1}}function Ua(){let e=Na(ja(),".claude");if(!Oa(e))return!1;try{return La(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function Cr(){try{return Bt("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function Ar(){try{return Bt("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var st={"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 Pr}from"marked";import{markedTerminal as Da}from"marked-terminal";import Gt from"picocolors";var Ir=!1;function Ma(){Ir||(Pr.use(Da({reflowText:!1,width:100})),Ir=!0)}function Rr(e){if(!e)return e;Ma();try{let t=Pr.parse(e);return typeof t=="string"?Ba(t):e}catch{return e}}function Ba(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>Gt.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>Gt.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+Gt.italic(r))}async function Ht(e={}){let t=process.cwd();if(!W(t))return;if(!process.stdout.isTTY&&!e.yes){c.error(`\`${p("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 Za(e.yes)){process.exitCode=1;return}if(e.yes)await B({embedded:!0});else{let u=await qa({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(at(u)){c.info("Cancelled.");return}u==="sync"?await B({embedded:!0}):u==="pull"&&await oe({embedded:!0})}let r=re(t);if(r.length===0){c.info(f.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),c.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(y=>y.priority!==null),d=u?r.filter(y=>y.priority==="high").map(y=>y.id):r.map(y=>y.id),m=u&&d.length===0?" (no high-priority actions \u2014 toggle to select)":u?` (${d.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",g=await Ha({message:`Which actions to process? ${r.length} pending \u2014${m}`,options:r.map(y=>({value:y.id,label:ge(y)})),initialValues:d,required:!1});if(at(g)){c.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(g)||g.length===0){c.info("No actions selected. Nothing to do.");return}o=g}let i=0,s=0,a=0,l=Date.now();for(let u=0;u<o.length;u++){let d=o[u],m=r.find(x=>x.id===d);if(!m)continue;Ya({index:u+1,total:o.length,entry:m});let g=Ga(H(t),m.filename),y;try{y=Wa(g,"utf-8")}catch(x){c.error(` Could not read ${m.filename}: ${x.message}`),a++;continue}let R=Date.now(),I=await Qa({cwd:t,entry:m,actionContent:y,model:e.model}),F=Or(Date.now()-R);if(I.kind==="applied")try{await J(String(d),{silent:!0}),i++,c.message("");let x=I.summary?`
352
- `+f.dim(" "+I.summary):"";c.message(` ${f.green("\u2713")} id ${d} ${f.dim("\u2014 applied in "+F)}${x}`)}catch(x){c.warn(` Applied but ack failed: ${x.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(I.kind==="declined")try{await J(String(d),{silent:!0,failed:!0,reason:I.reason}),s++,c.message(""),c.message(` ${f.yellow("\u2298")} id ${d} ${f.dim("\u2014 declined: "+N(I.reason,100))}`)}catch(x){c.warn(` Could not ack decline: ${x.message}. Run \`seoagent ack ${d} --failed --reason "${I.reason.replace(/"/g,'\\"')}"\` to retry.`)}else a++,c.message(""),c.message(` ${f.red("\u2717")} id ${d} ${f.dim("\u2014 agent did not converge after "+F)}`)}Va({applied:i,declined:s,failed:a,total:o.length,elapsed:Or(Date.now()-l)})}function Ya(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=Ja[i]??f.dim,a=[f.bold(`[${t}/${n}]`),f.dim("\xB7"),f.bold(`id ${r.id}`),f.dim("\xB7"),f.cyan(o),s(i)].join(" ");jr(r.title,a)}var Ja={critical:e=>f.red(f.bold(e)),high:f.red,medium:f.yellow,low:f.dim};function Va(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?f.green(`\u2713 ${t}/${o} applied`):f.green(`\u2713 ${t}/${o} applied \xB7 ${n} declined`);else if(s===0)a=f.red(`\u2717 0/${o} applied`);else{let l=[`${t}/${o} applied`];n>0&&l.push(`${n} declined`),r>0&&l.push(`${r} failed`),a=f.yellow(`\u25D0 ${l.join(" \xB7 ")}`)}jr(`${a}
353
- ${f.dim("elapsed: "+i)}`,f.bold("Done"))}function Or(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 Xa(e){if(typeof e!="string"||!e)return null;let t=e.split(`
354
- `);for(let n=t.length-1;n>=0;n--){let r=t[n].match(/^__(APPLIED|DECLINED)__:\s*(.*)$/);if(!r)continue;let o=r[2].trim();return r[1]==="APPLIED"?{kind:"applied",summary:o}:{kind:"declined",reason:o}}return null}async function Qa(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=cl(n,r);try{let s=za({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)tl(d,a)}else if(l.type==="user"){let u=l.message.content;if(Array.isArray(u))for(let d of u)ol(d,a)}else if(l.type==="result"){if(process.stdout.write(`
355
- `),!(l.subtype==="success"&&!l.is_error))return{kind:"failed"};let d=Xa(l.result);return d?.kind==="declined"?{kind:"declined",reason:d.reason}:{kind:"applied",summary:d?.kind==="applied"?d.summary:void 0}}return{kind:"failed"}}catch(s){return process.stdout.write(`
356
- `),c.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function Za(e){let t=Wt();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return c.info(f.dim(st[t].summary)),!0;if(c.warn(st[t].summary),c.message(` ${st[t].next}`),e)return!1;if(t==="not-installed"){let n=await Tr({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(at(n)||!n)return c.info("Skipped install. Set up auth and re-run when ready."),!1;c.message(f.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=Cr();if(!r.ok)return c.error(`Install failed: ${r.error}`),c.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=Wt()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await Tr({message:"Run `claude login` now to sign in?",initialValue:!0});if(at(n)||!n)return c.info("Skipped login. Run `claude login` when ready and try again."),!1;c.message(f.dim("Launching `claude login`\u2026"));let r=Ar();if(!r.ok)return c.error(`Login failed: ${r.error}`),!1}return!0}function el(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function tl(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&el(e)){process.stdout.write(Rr(e.text));return}if(n==="tool_use"){let r=String(e.id??""),o=String(e.name??"unknown"),i=e.input;r&&t.toolUseById.set(r,{name:o,input:i});let s=rl[o]??f.cyan,a=ll(o,i);process.stdout.write(s(nl)+" "+f.bold(o)+f.dim("(")+a+f.dim(")")+`
357
- `);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(f.dim(f.italic(" "+N(r,200)))+`
358
- `)}}var nl="\u23FA",Lr="\u23BF",rl={Read:f.blue,Glob:f.cyan,Grep:f.cyan,Edit:f.yellow,Write:f.magenta,Bash:f.green,WebFetch:f.magenta,WebSearch:f.magenta};function ol(e,t){if(!e||typeof e!="object"||e.type!=="tool_result")return;let n=e.is_error===!0,r=String(e.tool_use_id??""),o=r?t.toolUseById.get(r):void 0,i=o?.name,s=e.content,a=il(s);if(n){process.stdout.write(f.red(` ${Lr} Error`)+`
359
- `),a&&process.stdout.write(al(N(a,500)," ",f.red)+`
360
- `);return}let l=sl(i,a,o?.input);l&&process.stdout.write(f.dim(` ${Lr} `)+l+`
361
- `)}function il(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:t&&typeof t=="object"&&typeof t.text=="string"?t.text:"").join(""):""}function sl(e,t,n){if(!e)return"";switch(e){case"Read":{let r=(t.match(/^\s*\d+→/gm)??[]).length,o=r>0?r:t.split(`
362
- `).filter(Boolean).length;return f.dim(`Read ${o} line${o===1?"":"s"}`)}case"Glob":{let r=t.split(`
363
- `).filter(o=>o.trim().length>0).length;return f.dim(`Found ${r} ${r===1?"entry":"entries"}`)}case"Grep":{let r=t.split(`
364
- `)[0]?.trim()??"";if(/^Found\s+\d+/.test(r))return f.dim(r);let o=t.split(`
365
- `).filter(i=>i.trim()).length;return f.dim(`${o} result${o===1?"":"s"}`)}case"Edit":case"Write":{let r=n?.file_path,o=e==="Edit"?"Updated":"Created";return f.dim(r?`${o} ${Kt(String(r))}`:o)}case"Bash":{let r=t.split(`
366
- `),o=r.slice(0,5).map(u=>N(u.trimEnd(),100)),i=r.length-5,s=o.join(`
350
+ `);return}await W({pullOnly:!0,force:e.force,silent:e.silent,embedded:e.embedded})}import{existsSync as Ba,readdirSync as Ma,unlinkSync as Ka}from"fs";import{join as jr}from"path";import{isCancel as Wa,select as Ga}from"@clack/prompts";async function V(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 Ha(),n===null)return;let r=n,o=A();if(!o){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}if(!N(process.cwd()))return;let i=o.api_base||S.BASE,s=`Bearer ${o.user_token}:${o.website_token}`,a=t.failed?"failed":"completed",l;try{l=await H(`${i}/api/cli/actions/${r}/ack`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:s},body:JSON.stringify({status:a,error_message:t.failed&&t.reason?t.reason:null,result:t.failed?{declined:!0,reason:t.reason??null}:{applied:!0}})})}catch{_r(process.cwd(),{action_id:r,status:a,reason:t.failed?t.reason??null:null}),zt(r),lt(process.cwd()),t.silent||c.warn(`Network unavailable \u2014 ack queued locally. Run \`${p("sync")}\` when you're back online; it'll flush automatically.`);return}if(!l.ok){let u=await l.text().catch(()=>""),d=null;try{d=JSON.parse(u)}catch{d=null}if(l.status===409&&d?.code==="already_acked"){zt(r),lt(process.cwd());let P=typeof d.error=="string"?d.error.match(/'([^']+)'/)?.[1]??"settled":"settled";t.silent||c.success(`Action ${r} was already ${P}.`);return}let f=typeof d?.code=="string"?d.code:null,m=typeof d?.error=="string"?d.error:u,y=f?`, code: ${f}`:"";c.error(`Server rejected ack (${l.status}${y}): ${m.slice(0,200)}`),process.exitCode=1;return}zt(r),lt(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: ${jr($,"inbox")}`))}function zt(e){let t=q(process.cwd());if(Ba(t)){for(let n of Ma(t))if(n.endsWith(`-${e}.md`))try{Ka(jr(t,n))}catch{}}}async function Ha(){let e=process.cwd(),t=ie(e);if(t.length===0)return c.info("No pending actions in .seoagent/inbox/."),c.message(`Run \`${p("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 \`${p("inbox")}\` to see what's pending.`),process.exitCode=1,null;let n=await Ga({message:`Which action do you want to close out? (${t.length} pending)`,options:t.map(r=>({value:r.id,label:ye(r)}))});return Wa(n)?(c.info("Cancelled \u2014 no action closed out."),null):n}import dt from"picocolors";async function Yt(e={}){let t=process.cwd();if(!e.json&&!N(t))return;let n=ie(t);if(e.json){process.stdout.write(JSON.stringify({count:n.length,inbox_path:q(t),actions:n})+`
351
+ `);return}if(n.length===0){c.info(dt.dim("No pending actions.")),c.message(`Run \`${p("sync")}\` to pull anything autopilot has queued, or \`${p("autopilot status")}\` to check whether autopilot is on.`);return}c.message(`${dt.bold("SEOAgent inbox")} \xB7 ${n.length} pending action${n.length===1?"":"s"}`),c.message("");for(let r of n)c.message(ye(r));c.message(""),c.message(`Apply one: ${dt.bold(p("ack <id>"))} \xB7 Interactive picker: ${dt.bold(p("ack"))} (no id)`)}import{readFileSync as tl}from"fs";import{join as nl,relative as rl}from"path";import{confirm as Mr,isCancel as ft,multiselect as ol,note as Gr,select as il}from"@clack/prompts";import g from"picocolors";import{query as sl}from"@anthropic-ai/claude-agent-sdk";import{existsSync as qa,readdirSync as za}from"fs";import{homedir as Ya}from"os";import{join as Ja}from"path";import{execSync as Jt}from"child_process";function Vt(){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":Va()?Xa()?"claude-session-likely":"claude-installed-no-session":"not-installed"}function Va(){let e=process.platform==="win32"?"where claude":"command -v claude";try{return Jt(e,{stdio:"ignore"}),!0}catch{return!1}}function Xa(){let e=Ja(Ya(),".claude");if(!qa(e))return!1;try{return za(e).filter(n=>!n.startsWith(".DS_Store")).length>0}catch{return!1}}function Nr(){try{return Jt("npm install -g @anthropic-ai/claude-code",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}function Fr(){try{return Jt("claude login",{stdio:"inherit"}),{ok:!0}}catch(e){return{ok:!1,error:e.message}}}var pt={"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 Ur}from"marked";import{markedTerminal as Qa}from"marked-terminal";import Xt from"picocolors";var Dr=!1;function Za(){Dr||(Ur.use(Qa({reflowText:!1,width:100})),Dr=!0)}function Br(e){if(!e)return e;Za();try{let t=Ur.parse(e);return typeof t=="string"?el(t):e}catch{return e}}function el(e){return e.replace(/`([^`\n]+)`/g,(t,n)=>Xt.yellow(n)).replace(/\*\*([^*\n]+)\*\*/g,(t,n)=>Xt.bold(n)).replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s.,;:!?)]|$)/gm,(t,n,r)=>n+Xt.italic(r))}async function Zt(e={}){let t=process.cwd();if(!N(t))return;if(!process.stdout.isTTY&&!e.yes){c.error(`\`${p("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 pl(e.yes)){process.exitCode=1;return}if(e.yes)await W({embedded:!0});else{let u=await il({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(ft(u)){c.info("Cancelled.");return}u==="sync"?await W({embedded:!0}):u==="pull"&&await se({embedded:!0})}let r=ie(t);if(r.length===0){c.info(g.dim("No pending actions to process. Inbox is empty."));return}let o;if(e.yes)o=r.map(u=>u.id),c.message(`Processing all ${r.length} pending action${r.length===1?"":"s"}\u2026`);else{let u=r.some(y=>y.priority!==null),d=u?r.filter(y=>y.priority==="high").map(y=>y.id):r.map(y=>y.id),f=u&&d.length===0?" (no high-priority actions \u2014 toggle to select)":u?` (${d.length} high-priority pre-selected \u2014 space to toggle)`:" (space to toggle)",m=await ol({message:`Which actions to process? ${r.length} pending \u2014${f}`,options:r.map(y=>({value:y.id,label:ye(y)})),initialValues:d,required:!1});if(ft(m)){c.info("Cancelled \u2014 no actions processed.");return}if(!Array.isArray(m)||m.length===0){c.info("No actions selected. Nothing to do.");return}o=m}let i=0,s=0,a=0,l=Date.now();for(let u=0;u<o.length;u++){let d=o[u],f=r.find(v=>v.id===d);if(!f)continue;al({index:u+1,total:o.length,entry:f});let m=nl(q(t),f.filename),y;try{y=tl(m,"utf-8")}catch(v){c.error(` Could not read ${f.filename}: ${v.message}`),a++;continue}let P=Date.now(),I=await dl({cwd:t,entry:f,actionContent:y,model:e.model}),U=Kr(Date.now()-P);if(I.kind==="applied")try{await V(String(d),{silent:!0}),i++,c.message("");let v=I.summary?`
352
+ `+g.dim(" "+I.summary):"";c.message(` ${g.green("\u2713")} id ${d} ${g.dim("\u2014 applied in "+U)}${v}`)}catch(v){c.warn(` Applied but ack failed: ${v.message}. Run \`seoagent ack ${d}\` to retry.`)}else if(I.kind==="declined")try{await V(String(d),{silent:!0,failed:!0,reason:I.reason}),s++,c.message(""),c.message(` ${g.yellow("\u2298")} id ${d} ${g.dim("\u2014 declined: "+F(I.reason,100))}`)}catch(v){c.warn(` Could not ack decline: ${v.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 "+U)}`)}cl({applied:i,declined:s,failed:a,total:o.length,elapsed:Kr(Date.now()-l)})}function al(e){let{index:t,total:n,entry:r}=e,o=r.issue??r.action_type.replace(/^cli_/,"").replace(/_/g,"-"),i=r.severity??"unknown",s=ll[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(" ");Gr(r.title,a)}var ll={critical:e=>g.red(g.bold(e)),high:g.red,medium:g.yellow,low:g.dim};function cl(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 ")}`)}Gr(`${a}
353
+ ${g.dim("elapsed: "+i)}`,g.bold("Done"))}function Kr(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 ul(e){if(typeof e!="string"||!e)return null;let t=e.split(`
354
+ `);for(let n=t.length-1;n>=0;n--){let r=t[n].match(/^__(APPLIED|DECLINED)__:\s*(.*)$/);if(!r)continue;let o=r[2].trim();return r[1]==="APPLIED"?{kind:"applied",summary:o}:{kind:"declined",reason:o}}return null}async function dl(e){let{cwd:t,entry:n,actionContent:r,model:o}=e,i=Sl(n,r);try{let s=sl({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)ml(d,a)}else if(l.type==="user"){let u=l.message.content;if(Array.isArray(u))for(let d of u)yl(d,a)}else if(l.type==="result"){if(process.stdout.write(`
355
+ `),!(l.subtype==="success"&&!l.is_error))return{kind:"failed"};let d=ul(l.result);return d?.kind==="declined"?{kind:"declined",reason:d.reason}:{kind:"applied",summary:d?.kind==="applied"?d.summary:void 0}}return{kind:"failed"}}catch(s){return process.stdout.write(`
356
+ `),c.error(` Agent error: ${s.message}`),{kind:"failed"}}}async function pl(e){let t=Vt();if(t==="env-key"||t==="enterprise"||t==="claude-session-likely")return c.info(g.dim(pt[t].summary)),!0;if(c.warn(pt[t].summary),c.message(` ${pt[t].next}`),e)return!1;if(t==="not-installed"){let n=await Mr({message:"Install Claude Code globally now? (runs `npm install -g @anthropic-ai/claude-code`)",initialValue:!0});if(ft(n)||!n)return c.info("Skipped install. Set up auth and re-run when ready."),!1;c.message(g.dim("Installing @anthropic-ai/claude-code globally\u2026"));let r=Nr();if(!r.ok)return c.error(`Install failed: ${r.error}`),c.message("Try running the install manually, or set `ANTHROPIC_API_KEY` and re-run."),!1;t=Vt()}if(t==="claude-installed-no-session"||t==="not-installed"){let n=await Mr({message:"Run `claude login` now to sign in?",initialValue:!0});if(ft(n)||!n)return c.info("Skipped login. Run `claude login` when ready and try again."),!1;c.message(g.dim("Launching `claude login`\u2026"));let r=Fr();if(!r.ok)return c.error(`Login failed: ${r.error}`),!1}return!0}function fl(e){return typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string"}function ml(e,t){if(!e||typeof e!="object")return;let n=e.type;if(n==="text"&&fl(e)){process.stdout.write(Br(e.text));return}if(n==="tool_use"){let r=String(e.id??""),o=String(e.name??"unknown"),i=e.input;r&&t.toolUseById.set(r,{name:o,input:i});let s=hl[o]??g.cyan,a=$l(o,i);process.stdout.write(s(gl)+" "+g.bold(o)+g.dim("(")+a+g.dim(")")+`
357
+ `);return}if(n==="thinking"){let r=e.thinking;typeof r=="string"&&r.trim()&&process.stdout.write(g.dim(g.italic(" "+F(r,200)))+`
358
+ `)}}var gl="\u23FA",Wr="\u23BF",hl={Read:g.blue,Glob:g.cyan,Grep:g.cyan,Edit:g.yellow,Write:g.magenta,Bash:g.green,WebFetch:g.magenta,WebSearch:g.magenta};function yl(e,t){if(!e||typeof e!="object"||e.type!=="tool_result")return;let n=e.is_error===!0,r=String(e.tool_use_id??""),o=r?t.toolUseById.get(r):void 0,i=o?.name,s=e.content,a=wl(s);if(n){process.stdout.write(g.red(` ${Wr} Error`)+`
359
+ `),a&&process.stdout.write(bl(F(a,500)," ",g.red)+`
360
+ `);return}let l=kl(i,a,o?.input);l&&process.stdout.write(g.dim(` ${Wr} `)+l+`
361
+ `)}function wl(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:t&&typeof t=="object"&&typeof t.text=="string"?t.text:"").join(""):""}function kl(e,t,n){if(!e)return"";switch(e){case"Read":{let r=(t.match(/^\s*\d+→/gm)??[]).length,o=r>0?r:t.split(`
362
+ `).filter(Boolean).length;return g.dim(`Read ${o} line${o===1?"":"s"}`)}case"Glob":{let r=t.split(`
363
+ `).filter(o=>o.trim().length>0).length;return g.dim(`Found ${r} ${r===1?"entry":"entries"}`)}case"Grep":{let r=t.split(`
364
+ `)[0]?.trim()??"";if(/^Found\s+\d+/.test(r))return g.dim(r);let o=t.split(`
365
+ `).filter(i=>i.trim()).length;return g.dim(`${o} result${o===1?"":"s"}`)}case"Edit":case"Write":{let r=n?.file_path,o=e==="Edit"?"Updated":"Created";return g.dim(r?`${o} ${Qt(String(r))}`:o)}case"Bash":{let r=t.split(`
366
+ `),o=r.slice(0,5).map(u=>F(u.trimEnd(),100)),i=r.length-5,s=o.join(`
367
367
  `)+(i>0?`
368
368
  \u2026 (+${i} more line${i===1?"":"s"})`:""),[a,...l]=s.split(`
369
- `);return l.length===0?f.dim(a):f.dim(a)+`
370
- `+f.dim(l.map(u=>" "+u).join(`
371
- `))}case"WebFetch":case"WebSearch":return f.dim(`Fetched ${N(t.replace(/\s+/g," "),80)}`);default:return""}}function al(e,t,n){return e.split(`
369
+ `);return l.length===0?g.dim(a):g.dim(a)+`
370
+ `+g.dim(l.map(u=>" "+u).join(`
371
+ `))}case"WebFetch":case"WebSearch":return g.dim(`Fetched ${F(t.replace(/\s+/g," "),80)}`);default:return""}}function bl(e,t,n){return e.split(`
372
372
  `).map(r=>n(t+r)).join(`
373
- `)}function ll(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return f.dim(N(Kt(String(n.file_path??"")),80));case"Bash":return f.dim(N(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${Kt(String(n.path))}`:"";return f.dim(N(r+o,80))}case"Glob":return f.dim(N(String(n.pattern??""),80));case"WebFetch":return f.dim(N(String(n.url??""),80));case"WebSearch":return f.dim(N(String(n.query??""),80));default:return""}}function Kt(e){if(!e)return e;let t=process.cwd(),n=Ka(t,e);return n.startsWith("..")?e:n||e}function N(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function cl(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
373
+ `)}function $l(e,t){if(!t||typeof t!="object")return"";let n=t;switch(e){case"Read":case"Write":case"Edit":return g.dim(F(Qt(String(n.file_path??"")),80));case"Bash":return g.dim(F(String(n.command??""),80));case"Grep":{let r=String(n.pattern??""),o=n.path?` in ${Qt(String(n.path))}`:"";return g.dim(F(r+o,80))}case"Glob":return g.dim(F(String(n.pattern??""),80));case"WebFetch":return g.dim(F(String(n.url??""),80));case"WebSearch":return g.dim(F(String(n.query??""),80));default:return""}}function Qt(e){if(!e)return e;let t=process.cwd(),n=rl(t,e);return n.startsWith("..")?e:n||e}function F(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Sl(e,t){return`You are SEOAgent processing one inbox action from \`.seoagent/inbox/\`.
374
374
 
375
375
  Your job: apply the change this action describes to the codebase at the current working directory. Read the "How to apply" section in the action file \u2014 it tells you what to do and where to look. Make the edit, then briefly state what you changed.
376
376
 
@@ -389,19 +389,57 @@ Action file (\`.seoagent/inbox/${e.filename}\`):
389
389
  \`\`\`
390
390
  ${t}
391
391
  \`\`\`
392
- `}import{spinner as ul}from"@clack/prompts";import w from"picocolors";var dl=new Set(["on","off","status"]);async function je(e,t={}){let n=(e||"").toLowerCase();if(!dl.has(n)){c.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=A();if(!r){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||S.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?ul():null,l=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(l);let u;try{u=await fetch(`${o}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(y){k(a,"error",`Network error: ${y.message}`,w.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){let R=C(process.cwd())?.domain??"",I=`${S.PRICING}?ref=cli${R?`&domain=${encodeURIComponent(R)}`:""}`;k(a,"warn","CLI autopilot is a paid feature.",w.yellow("Autopilot is a paid feature.")),c.message(pl(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:m,delivery_mode:g}=d.autopilot;if(n==="on"){a?.stop(w.green("Autopilot enabled.")),c.message(qt({enabled:!0,deliveryMode:g,action:n}));return}if(n==="off"){a?.stop(w.dim("Autopilot disabled.")),c.message(qt({enabled:!1,deliveryMode:g,action:n}));return}a?.stop(w.dim("Status:")),c.message(qt({enabled:m,deliveryMode:g,action:n}))}function qt(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(p("sync"))}`}),o.push({content:`${w.dim("Turn off any time:")} ${w.cyan(p("autopilot off"))}`})):(o.push({content:`${w.dim("Enable (paid):")} ${w.cyan(p("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 L(o,{width:78,title:i})}function pl(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 L(t,{width:78,title:n})}import{mkdirSync as xl,writeFileSync as _l}from"fs";import{join as zt}from"path";import{readdirSync as ml,readFileSync as fl,statSync as Nr}from"fs";import{join as gl}from"path";var hl=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),yl=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"]),wl=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),kl=5e3,bl=512*1024;function Br(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function Fr(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&&yl.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var Ur=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Dr=/\]\(\s*([^)\s]+)/g;function $l(e,t){if(!e)return[];let n=Br(t),r=[],o;for(Ur.lastIndex=0;(o=Ur.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=Fr(i,n);s&&r.push(s)}for(Dr.lastIndex=0;(o=Dr.exec(e))!==null;){let i=Fr(o[1],n);i&&r.push(i)}return r}function Sl(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 Wr(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(`
393
- `),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${Br(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(`
392
+ `}import{spinner as xl}from"@clack/prompts";import w from"picocolors";var vl=new Set(["on","off","status"]);async function Be(e,t={}){let n=(e||"").toLowerCase();if(!vl.has(n)){c.error(`Usage: seoagent autopilot <on|off|status> (got "${e}")`),process.exitCode=1;return}let r=A();if(!r){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let o=t.apiBase||r.api_base||S.BASE,i=`Bearer ${r.user_token}:${r.website_token}`,a=!!process.stdout.isTTY?xl():null,l=n==="on"?"Enabling autopilot\u2026":n==="off"?"Disabling autopilot\u2026":"Checking autopilot status\u2026";a?.start(l);let u;try{u=await fetch(`${o}/api/cli/autopilot/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:"{}"})}catch(y){k(a,"error",`Network error: ${y.message}`,w.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){let P=E(process.cwd())?.domain??"",I=`${S.PRICING}?ref=cli${P?`&domain=${encodeURIComponent(P)}`:""}`;k(a,"warn","CLI autopilot is a paid feature.",w.yellow("Autopilot is a paid feature.")),c.message(_l(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:f,delivery_mode:m}=d.autopilot;if(n==="on"){a?.stop(w.green("Autopilot enabled.")),c.message(en({enabled:!0,deliveryMode:m,action:n}));return}if(n==="off"){a?.stop(w.dim("Autopilot disabled.")),c.message(en({enabled:!1,deliveryMode:m,action:n}));return}a?.stop(w.dim("Status:")),c.message(en({enabled:f,deliveryMode:m,action:n}))}function en(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(p("sync"))}`}),o.push({content:`${w.dim("Turn off any time:")} ${w.cyan(p("autopilot off"))}`})):(o.push({content:`${w.dim("Enable (paid):")} ${w.cyan(p("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 T(o,{width:78,title:i})}function _l(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 T(t,{width:78,title:n})}import{mkdirSync as Fl,writeFileSync as Dl}from"fs";import{join as tn}from"path";import{readdirSync as Cl,readFileSync as El,statSync as Hr}from"fs";import{join as Al}from"path";var Il=new Set(["html","htm","md","mdx","markdown","mdoc","tsx","jsx","ts","js","astro","vue","svelte"]),Rl=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"]),Pl=new Set(["node_modules",".git",".next","dist","build",".vercel","out",".seoagent"]),Ol=5e3,Tl=512*1024;function Vr(e){return e?e.trim().toLowerCase().replace(/^sc-domain:/,"").replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,""):null}function qr(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&&Rl.has(r.slice(o+1).toLowerCase())?null:(n=n.replace(/\/+$/,""),n===""?"/":n)}var zr=/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*[`'"]([^`'"]*)[`'"]\s*\})/gi,Yr=/\]\(\s*([^)\s]+)/g;function Ll(e,t){if(!e)return[];let n=Vr(t),r=[],o;for(zr.lastIndex=0;(o=zr.exec(e))!==null;){let i=o[1]??o[2]??o[3]??"",s=qr(i,n);s&&r.push(s)}for(Yr.lastIndex=0;(o=Yr.exec(e))!==null;){let i=qr(o[1],n);i&&r.push(i)}return r}function jl(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 Xr(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(`
393
+ `),o=["# Internal Links","",`Internal link analysis of the pages discovered in this repo${t?` (${Vr(t)})`:""}. **Orphans** are pages no other page links to \u2014 they're hard for crawlers`,"and users to reach and tend to underperform. Add relevant internal links","pointing at them (from related, higher-authority pages).","",`Scanned ${e.filesScanned} file${e.filesScanned===1?"":"s"}, ${e.linkOccurrences} internal link${e.linkOccurrences===1?"":"s"}, ${e.pageCount} page${e.pageCount===1?"":"s"}.`,"","_Note: this scans the repo, so links inside CMS-hosted content aren't counted._"].join(`
394
394
  `),i=e.orphans.length===0?`## Orphan pages
395
395
 
396
- None \u2014 every page has at least one inbound internal link. \u{1F389}`:[`## Orphan pages (${e.orphans.length})`,"","No internal links point to these. Add links from related pages.","","| Page | Suggested link source (fill in) |","|---|---|",...e.orphans.map(a=>`| ${Mr(a.url)} | \u2014 |`)].join(`
397
- `),s=e.weak.length===0?"":["",`## Weakly linked (${e.weak.length})`,"","Exactly one inbound internal link \u2014 fragile. Consider adding more.","","| Page | Inbound |","|---|---|",...e.weak.map(a=>`| ${Mr(a.url)} | ${a.inbound} |`)].join(`
396
+ None \u2014 every page has at least one inbound internal link. \u{1F389}`:[`## Orphan pages (${e.orphans.length})`,"","No internal links point to these. Add links from related pages.","","| Page | Suggested link source (fill in) |","|---|---|",...e.orphans.map(a=>`| ${Jr(a.url)} | \u2014 |`)].join(`
397
+ `),s=e.weak.length===0?"":["",`## Weakly linked (${e.weak.length})`,"","Exactly one inbound internal link \u2014 fragile. Consider adding more.","","| Page | Inbound |","|---|---|",...e.weak.map(a=>`| ${Jr(a.url)} | ${a.inbound} |`)].join(`
398
398
  `);return[r,"",o,"",i,s,""].join(`
399
- `)}function Mr(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*vl(e){let t=0;function*n(r){let o;try{o=ml(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=kl)return;if(i.name.startsWith("."))continue;let s=gl(r,i.name);if(i.isDirectory()){if(wl.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(!hl.has(l))continue;t++,yield s}}}yield*n(e)}function Gr(e,t){let{pages:n}=Ve(e,t),r=[],o=0,i=!1;try{i=Nr(e).isDirectory()}catch{i=!1}if(i)for(let s of vl(e)){let a;try{if(Nr(s).size>bl)continue;a=fl(s,"utf-8")}catch{continue}o++;for(let l of $l(a,t))r.push(l)}return Sl(n,r,o)}function Ne(e={}){let t=process.cwd(),n=W(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Gr(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
400
- `);return}let i=zt(t,$);xl(i,{recursive:!0});let s=zt(i,"internal-links.md");if(_l(s,Wr(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 ${zt($,"internal-links.md")}`)}import{spinner as qr}from"@clack/prompts";import h from"picocolors";var zr={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function El(e){let t=process.cwd(),n=dn(t);if(!n){c.error(`No .seoagent/project.md found. Run \`${p("init")}\` first.`),process.exitCode=1;return}let r=C(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||S.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?qr():null;a?.start(`Looking up ${h.bold(`"${e.keyword}"`)} ${h.dim("via DataForSEO (free peek)\u2026")}`);let l;try{l=await K(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...o?{domain:o}:{}})})}catch(d){k(a,"error",`Network error: ${d.message}`,h.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await l.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:l.status,body:u??null})+`
401
- `);return}if(l.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";k(a,"warn",`Daily peek quota reached for ${d}.`,h.yellow(`Daily peek quota reached for ${d}.`)),c.message(Kr()),process.exitCode=1;return}if(!l.ok||!u){k(a,"error",`Peek failed (${l.status})${u?.error?`: ${u.error}`:""}`,h.red(`Peek failed (${l.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){k(a,"warn","Real keyword data is temporarily unavailable. Try again later.",h.yellow("Real keyword data is temporarily unavailable. Try again later.")),c.message(h.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){k(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){k(a,"warn",`No data returned for "${e.keyword}".`,h.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(h.green("Got it.")),c.message(Cl(u.opportunity)),u.remaining&&c.message(`${h.dim("Peeks remaining today:")} ${h.bold(String(u.remaining.install))} ${h.dim("\u2014 "+Kr())}`)}function Cl(e){let n=u=>h.dim(u.padEnd(14)),r=e.volume!=null?h.bold(String(e.volume)):h.dim("n/a"),o=e.difficulty!=null?`${h.bold(String(e.difficulty))} ${h.dim(Al(e.difficulty))}`:h.dim("n/a"),i=zr[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?h.bold(h.green(i)):e.opportunity==="striking_distance"?h.bold(h.cyan(i)):e.opportunity==="competitor_gap"?h.bold(h.yellow(i)):h.dim(i),a=[{content:`${h.green("\u25CF")} ${h.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${h.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],l=`${h.bold(h.cyan("Keyword peek"))}`;return L(a,{width:55,title:l})}function Al(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function Kr(e=A()){return e?`You're logged in \u2014 run \`${p("keywords")}\` for full enrichment (no quota), or \`${p("keywords --discover")}\` / \`${p("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${p("login")}`}function Hr(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 [${zr[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function Il(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 V(e={}){if(e.peek&&e.peek.trim().length>0){await El({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=A();if(!t){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let n=e.apiBase||t.api_base||S.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?qr():null;l?.start(s);let u;try{u=await K(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"})}catch(g){k(l,"error",`Network error: ${g.message}`,h.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){k(l,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",h.yellow("Paid feature \u2014 upgrade to continue.")),c.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${h.cyan(S.PRICING)}`:`Upgrade to find new keywords to target: ${h.cyan(S.PRICING)}`),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"){k(l,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,h.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}if(d.skipped==="no-keywords"||d.skipped==="no-seeds"){k(l,"warn","No keywords yet. Run the keyword strategy (Phase 2) first, then try again.",h.yellow("No keywords yet."));return}if(d.skipped==="no-competitors"){k(l,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",h.yellow("No competitors yet."));return}if(d.skipped==="no-creds"||d.skipped==="no-columns"||d.skipped==="no-table"){k(l,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(d.skipped){k(l,"warn",`Skipped: ${d.skipped}`,h.yellow(`Skipped: ${d.skipped}`));return}if(o==="competitors"){let g=d.gaps??0;k(l,"success",`Found ${g} competitor gap${g===1?"":"s"} across ${d.competitors?.length??0} competitor${d.competitors?.length===1?"":"s"} (added as "suggested").`,h.green(`${g} competitor gap${g===1?"":"s"} found.`)),Il(d.topGaps??[]),c.message(`Review them in ${h.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}if(o==="discover"){let g=d.discovered??0;k(l,"success",`Discovered ${g} new keyword${g===1?"":"s"} to target (added as "suggested").`,h.green(`${g} new keyword${g===1?"":"s"} discovered.`)),Hr(d.opportunities??[]),c.message(`Review them in ${h.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}let m=d.enriched??0;k(l,"success",`Enriched ${m} keyword${m===1?"":"s"}.`,h.green(`Enriched ${m} keyword${m===1?"":"s"}.`)),Hr(d.opportunities??[]),d.paid||c.message(`${h.dim("Free plan:")} enriched up to ${h.bold(String(d.cap??25))} keywords. ${h.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${h.cyan(S.PRICING)}`)}import _ from"picocolors";import{existsSync as Pl,readFileSync as Rl}from"fs";import{join as Tl}from"path";var Yr=["openai","fal","replicate"],ye={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Ol(e){let t={};if(!Pl(e))return t;let n=Rl(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 Jr(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 ie){let o=Tl(e,r),i=Ol(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 lt(e){let t=[].concat(...Yr.map(a=>ye[a])),n=Jr(e,t),r=[];for(let a of Yr)ye[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=ye[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 Vr(e,t){let n=Jr(e,ye[t]);for(let r of ye[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function Xr(){return ye}function Fe(e={}){let t=process.cwd(),n=C(t),r=lt(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
402
- `);return}if(c.message(Ll(r)),!n){c.warn(`No SEOAgent project here. Run \`${p("init")}\` first to persist the provider.`);return}$e(t,{image_provider:r.provider}),c.info(`Saved to ${_.cyan(".seoagent/project.md")} ${_.dim(`(image_provider: ${r.provider})`)}`)}function Ll(e){let n=i=>_.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${_.dim("\u25CB")} ${_.bold(_.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:_.dim("Set ONE of these to enable image generation:")});let i=Xr();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${_.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:_.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${_.cyan(p("env-check"))}`})}else{r.push({content:`${_.green("\u2713")} ${_.dim("Image provider:")} ${_.bold(_.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${_.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${_.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${_.dim(i.join(", "))}`})}let o=`${_.bold(_.cyan("SEOAgent"))} ${_.dim("\xB7")} ${_.dim("env-check")}`;return L(r,{width:64,title:o})}import{existsSync as Jt,mkdirSync as eo,writeFileSync as to}from"fs";import{dirname as ut,isAbsolute as Dl,join as ct,resolve as Ml}from"path";import{tmpdir as Bl}from"os";import{spinner as Wl}from"@clack/prompts";import P from"picocolors";import{Buffer as Qr}from"buffer";async function Yt(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 Qr.from(n)}async function jl(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:Qr.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await Yt(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function Nl(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 Yt(o.url),contentType:o.content_type??"image/png"}}async function Fl(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 Ul(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 Fl(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 Yt(o),contentType:"image/png",providerImageId:r.id}}async function Zr(e,t){switch(e){case"openai":return jl(t);case"fal":return Nl(t);case"replicate":return Ul(t);default:throw new Error(`Unknown image provider: ${e}`)}}function Gl(e){return e==="openai"||e==="fal"||e==="replicate"}async function Ue(e={}){let t=process.cwd();if(!e.prompt){c.warn(`Missing --prompt. Example: ${p('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){c.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=C(t),r=null;if(e.provider){if(!Gl(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=lt(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 \`${p("env-check")}\`.`),process.exitCode=1;return}let o=Vr(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=Dl(e.out)?e.out:Ml(t,e.out),a=!e.silent&&!!process.stdout.isTTY?Wl():null;a?.start(`Generating image with ${P.bold(r)} ${P.dim(`(${o.envName})`)}\u2026`);try{let l=await Zr(r,{prompt:e.prompt,apiKey:o.key,size:e.size});Jt(ut(i))||eo(ut(i),{recursive:!0}),to(i,l.bytes),e.silent||k(a,"success",`Wrote ${i} (${l.bytes.length} bytes, ${l.contentType}).`,P.green(`Wrote ${i} ${P.dim(`(${l.bytes.length} bytes, ${l.contentType})`)}`))}catch(l){a?.stop(P.red("Image generation failed."));let u=Hl(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:l});c.message(Kl({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:l.message})),u&&c.message(`${P.dim("Full error log:")} ${P.cyan(u)}`),process.exitCode=1}}function Kl(e){let n=d=>P.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${P.red("\u2717")} ${P.bold(P.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${P.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${P.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:P.red(l)});let u=`${P.bold(P.cyan("SEOAgent"))} ${P.dim("\xB7")} ${P.dim("generate-image")}`;return L(i,{width:70,title:u})}function Hl(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=ct(e,$),i=ct(o,".errors"),s=Jt(o)?ct(i,r):ct(Bl(),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 Jt(ut(s))||eo(ut(s),{recursive:!0}),to(s,a.join(`
403
- `)),s}catch{return null}}import j from"picocolors";async function De(e={}){let t=A();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
399
+ `)}function Jr(e){return e.replace(/\r?\n/g," ").replace(/\|/g,"/").trim()}function*Nl(e){let t=0;function*n(r){let o;try{o=Cl(r,{withFileTypes:!0})}catch{return}for(let i of o){if(t>=Ol)return;if(i.name.startsWith("."))continue;let s=Al(r,i.name);if(i.isDirectory()){if(Pl.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(!Il.has(l))continue;t++,yield s}}}yield*n(e)}function Qr(e,t){let{pages:n}=nt(e,t),r=[],o=0,i=!1;try{i=Hr(e).isDirectory()}catch{i=!1}if(i)for(let s of Nl(e)){let a;try{if(Hr(s).size>Tl)continue;a=El(s,"utf-8")}catch{continue}o++;for(let l of Ll(a,t))r.push(l)}return jl(n,r,o)}function Me(e={}){let t=process.cwd(),n=N(t);if(!n)return;let r=n.domain&&n.domain!=="unknown"?n.domain:null,o=Qr(t,r);if(e.json){process.stdout.write(JSON.stringify(o,null,2)+`
400
+ `);return}let i=tn(t,$);Fl(i,{recursive:!0});let s=tn(i,"internal-links.md");if(Dl(s,Xr(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 ${tn($,"internal-links.md")}`)}import G from"picocolors";import{existsSync as ke,mkdirSync as mt,readdirSync as Ul,readFileSync as Bl,statSync as zf,writeFileSync as Zr}from"fs";import{dirname as Ml,join as X,relative as Kl,resolve as Wl}from"path";var be="okf";function gt(e){return X(e,$,be)}var Gl=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;function nn(e){let t=[];for(let n of Ul(e,{withFileTypes:!0})){let r=X(e,n.name);n.isDirectory()?t.push(...nn(r)):n.isFile()&&n.name.toLowerCase().endsWith(".md")&&t.push(r)}return t}function Hl(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 eo(e){let t=[],n=[];if(!ke(e))return{ok:!1,fileCount:0,errors:[{file:be,message:"No OKF bundle found. Run `seoagent okf scaffold` first."}],warnings:[]};let r=nn(e);if(r.length===0)return{ok:!1,fileCount:0,errors:[{file:be,message:"OKF directory exists but contains no markdown files."}],warnings:[]};ke(X(e,"index.md"))||n.push({file:be,message:"No top-level index.md \u2014 agents use it for progressive disclosure."});for(let i of r){let s=Kl(e,i),a;try{a=ve(Bl(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!==""&&!Gl.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 f of Hl(a.body)){let m=f.split("#")[0];if(!m)continue;let y=Wl(Ml(i),m);ke(y)||t.push({file:s,message:`Broken link \u2192 "${f}" (target does not exist).`})}}return{ok:t.length===0,fileCount:r.length,errors:t,warnings:n}}function to(e){let t=gt(e);if(!ke(t))return{exists:!1,fileCount:0};try{return{exists:!0,fileCount:nn(t).length}}catch{return{exists:!0,fileCount:0}}}function no(e,t){let n=gt(e);mt(n,{recursive:!0}),mt(X(n,"concepts"),{recursive:!0}),mt(X(n,"faqs"),{recursive:!0}),mt(X(n,"articles"),{recursive:!0});let r=[],o=t&&t!=="unknown"?t:"your site",i=X(n,"index.md");ke(i)||(Zr(i,`---
401
+ type: Organization
402
+ title: ${o}
403
+ description: Knowledge bundle describing ${o} for AI agents and answer engines.
404
+ tags: [overview]
405
+ ---
406
+
407
+ # ${o}
408
+
409
+ > Open Knowledge Format bundle \u2014 a curated, agent-readable account of this
410
+ > business. Fill in the sections below and link out to concept files.
411
+
412
+ ## What this business does
413
+
414
+ _Describe the business in 2\u20134 sentences (pull from \`.seoagent/context.md\`)._
415
+
416
+ ## Key concepts
417
+
418
+ - _Link concept files here, e.g._ \`concepts/pricing.md\`
419
+
420
+ ## FAQs
421
+
422
+ - _Link FAQ files here, e.g._ \`faqs/what-is-x.md\`
423
+
424
+ ## Published articles
425
+
426
+ - _Link article files here, e.g._ \`articles/guide-to-x.md\`
427
+ `,"utf-8"),r.push("index.md"));let s=X(n,"log.md");return ke(s)||(Zr(s,`---
428
+ type: Log
429
+ title: Change log
430
+ description: Chronological history of changes to this OKF bundle.
431
+ ---
432
+
433
+ # Change log
434
+
435
+ - Bundle scaffolded.
436
+ `,"utf-8"),r.push("log.md")),{created:r,okfDir:n}}var rn=`${$}/${be}`;function Ke(e,t={}){let n=process.cwd(),r=N(n);if(!r)return;let o=(e||"status").toLowerCase(),i=r.domain&&r.domain!=="unknown"?r.domain:null;if(o==="scaffold"){let{created:a}=no(n,i);a.length===0?c.info(`OKF bundle already scaffolded at ${rn}/.`):(c.success(`Scaffolded ${rn}/ \u2014 created ${a.join(", ")}.`),c.info("Now fill the bundle from your .seoagent/ knowledge, then run `seoagent okf validate`."));return}if(o==="validate"){let a=eo(gt(n));if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
437
+ `);return}for(let l of a.errors)c.message(`${G.red("\u2717")} ${G.dim(l.file)} \u2014 ${l.message}`);for(let l of a.warnings)c.message(`${G.yellow("!")} ${G.dim(l.file)} \u2014 ${l.message}`);a.ok?c.success(`OKF bundle is valid \u2014 ${a.fileCount} file${a.fileCount===1?"":"s"}, ${a.warnings.length} warning${a.warnings.length===1?"":"s"}.`):(c.error(`OKF bundle has ${a.errors.length} error${a.errors.length===1?"":"s"} (see above).`),process.exitCode=1);return}let s=to(n);if(t.json){process.stdout.write(JSON.stringify(s,null,2)+`
438
+ `);return}c.message(T([{content:G.bold("Open Knowledge Format")},{sep:!0},{content:`Bundle: ${s.exists?G.green(rn+"/"):G.dim("not created")}`},{content:`Files: ${s.exists?String(s.fileCount):"\u2014"}`},{sep:!0},{content:s.exists?G.dim("Run `seoagent okf validate` to check it."):G.dim("Run `seoagent okf scaffold` to start one.")}],{title:G.cyan("OKF")}))}import{spinner as io}from"@clack/prompts";import h from"picocolors";var so={easy_win:"easy win",striking_distance:"striking distance",competitor_gap:"competitor gap",defend:"defend",low_priority:"low priority"};async function ql(e){let t=process.cwd(),n=bn(t);if(!n){c.error(`No .seoagent/project.md found. Run \`${p("init")}\` first.`),process.exitCode=1;return}let r=E(t),o=r?.domain&&r.domain!=="unknown"?r.domain:void 0,i=(e.apiBase||S.BASE).replace(/\/$/,""),a=!!process.stdout.isTTY&&!e.json?io():null;a?.start(`Looking up ${h.bold(`"${e.keyword}"`)} ${h.dim("via DataForSEO (free peek)\u2026")}`);let l;try{l=await H(`${i}/api/cli/keywords/peek`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({install_id:n,keyword:e.keyword,...o?{domain:o}:{}})})}catch(d){k(a,"error",`Network error: ${d.message}`,h.red("Network error.")),process.exitCode=1;return}let u=null;try{u=await l.json()}catch{u=null}if(e.json){process.stdout.write(JSON.stringify({status:u?.status??"error",http_status:l.status,body:u??null})+`
439
+ `);return}if(l.status===429||u?.skipped?.startsWith("rate-limited")){let d=u?.skipped==="rate-limited:ip"?"this network":"this install";k(a,"warn",`Daily peek quota reached for ${d}.`,h.yellow(`Daily peek quota reached for ${d}.`)),c.message(ro()),process.exitCode=1;return}if(!l.ok||!u){k(a,"error",`Peek failed (${l.status})${u?.error?`: ${u.error}`:""}`,h.red(`Peek failed (${l.status}).`)),process.exitCode=1;return}if(u.skipped==="provider-quota"){k(a,"warn","Real keyword data is temporarily unavailable. Try again later.",h.yellow("Real keyword data is temporarily unavailable. Try again later.")),c.message(h.dim("No action needed on your side \u2014 the maintainer has been notified."));return}if(u.skipped==="no-creds"||u.skipped==="no-table"){k(a,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(!u.opportunity){k(a,"warn",`No data returned for "${e.keyword}".`,h.yellow(`No data returned for "${e.keyword}".`));return}a?.stop(h.green("Got it.")),c.message(zl(u.opportunity)),u.remaining&&c.message(`${h.dim("Peeks remaining today:")} ${h.bold(String(u.remaining.install))} ${h.dim("\u2014 "+ro())}`)}function zl(e){let n=u=>h.dim(u.padEnd(14)),r=e.volume!=null?h.bold(String(e.volume)):h.dim("n/a"),o=e.difficulty!=null?`${h.bold(String(e.difficulty))} ${h.dim(Yl(e.difficulty))}`:h.dim("n/a"),i=so[e.opportunity]??e.opportunity,s=e.opportunity==="easy_win"?h.bold(h.green(i)):e.opportunity==="striking_distance"?h.bold(h.cyan(i)):e.opportunity==="competitor_gap"?h.bold(h.yellow(i)):h.dim(i),a=[{content:`${h.green("\u25CF")} ${h.bold(e.keyword)}`},{sep:!0},{content:`${n("Volume:")}${r} ${h.dim("/mo")}`},{content:`${n("Difficulty:")}${o}`},{content:`${n("Opportunity:")}${s}`}],l=`${h.bold(h.cyan("Keyword peek"))}`;return T(a,{width:55,title:l})}function Yl(e){return e<=20?"easy":e<=40?"moderate":e<=60?"hard":"very hard"}function ro(e=A()){return e?`You're logged in \u2014 run \`${p("keywords")}\` for full enrichment (no quota), or \`${p("keywords --discover")}\` / \`${p("keywords --competitors")}\` (paid).`:`Log in for the full top-25 enrichment, no quota: ${p("login")}`}function oo(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 [${so[n.opportunity]??n.opportunity}] ${n.keyword} \u2014 ${r}, ${o}${i}`)}}}function Jl(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 Q(e={}){if(e.peek&&e.peek.trim().length>0){await ql({keyword:e.peek.trim(),apiBase:e.apiBase,json:e.json});return}let t=A();if(!t){c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let n=e.apiBase||t.api_base||S.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?io():null;l?.start(s);let u;try{u=await H(`${n}${i}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:r},body:"{}"})}catch(m){k(l,"error",`Network error: ${m.message}`,h.red("Network error.")),process.exitCode=1;return}let d=null;try{d=await u.json()}catch{d=null}if(u.status===402||d?.code==="upgrade_required"){k(l,"warn",o==="competitors"?"Competitor gap analysis is a paid feature.":"Keyword discovery is a paid feature.",h.yellow("Paid feature \u2014 upgrade to continue.")),c.message(o==="competitors"?`Upgrade to see which keywords competitors rank for that you don't: ${h.cyan(S.PRICING)}`:`Upgrade to find new keywords to target: ${h.cyan(S.PRICING)}`),process.exitCode=1;return}if(!u.ok||d?.status!=="ok"){k(l,"error",`Server rejected request (${u.status})${d?.error?`: ${d.error}`:""}`,h.red(`Server rejected request (${u.status}).`)),process.exitCode=1;return}if(d.skipped==="no-keywords"||d.skipped==="no-seeds"){k(l,"warn","No keywords yet. Run the keyword strategy (Phase 2) first, then try again.",h.yellow("No keywords yet."));return}if(d.skipped==="no-competitors"){k(l,"warn","No competitors found yet. Add competitors or run strategy discovery first, then try again.",h.yellow("No competitors yet."));return}if(d.skipped==="no-creds"||d.skipped==="no-columns"||d.skipped==="no-table"){k(l,"warn","Real keyword data isn\u2019t enabled on the server yet \u2014 try again later.",h.yellow("Real keyword data is not enabled on the server yet."));return}if(d.skipped){k(l,"warn",`Skipped: ${d.skipped}`,h.yellow(`Skipped: ${d.skipped}`));return}if(o==="competitors"){let m=d.gaps??0;k(l,"success",`Found ${m} competitor gap${m===1?"":"s"} across ${d.competitors?.length??0} competitor${d.competitors?.length===1?"":"s"} (added as "suggested").`,h.green(`${m} competitor gap${m===1?"":"s"} found.`)),Jl(d.topGaps??[]),c.message(`Review them in ${h.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}if(o==="discover"){let m=d.discovered??0;k(l,"success",`Discovered ${m} new keyword${m===1?"":"s"} to target (added as "suggested").`,h.green(`${m} new keyword${m===1?"":"s"} discovered.`)),oo(d.opportunities??[]),c.message(`Review them in ${h.cyan(".seoagent/keywords.md")} and promote the ones you want into a cluster.`);return}let f=d.enriched??0;k(l,"success",`Enriched ${f} keyword${f===1?"":"s"}.`,h.green(`Enriched ${f} keyword${f===1?"":"s"}.`)),oo(d.opportunities??[]),d.paid||c.message(`${h.dim("Free plan:")} enriched up to ${h.bold(String(d.cap??25))} keywords. ${h.dim("Upgrade for full enrichment + discovery + competitor gap:")} ${h.cyan(S.PRICING)}`)}import _ from"picocolors";import{existsSync as Vl,readFileSync as Xl}from"fs";import{join as Ql}from"path";var ao=["openai","fal","replicate"],$e={openai:["OPENAI_API_KEY"],fal:["FAL_KEY","FAL_API_KEY"],replicate:["REPLICATE_API_TOKEN","REPLICATE_API_KEY"]};function Zl(e){let t={};if(!Vl(e))return t;let n=Xl(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 lo(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 ae){let o=Ql(e,r),i=Zl(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 ht(e){let t=[].concat(...ao.map(a=>$e[a])),n=lo(e,t),r=[];for(let a of ao)$e[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=$e[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 co(e,t){let n=lo(e,$e[t]);for(let r of $e[t])if(n.found[r])return{key:n.found[r].value,envName:r};return null}function uo(){return $e}function We(e={}){let t=process.cwd(),n=E(t),r=ht(t);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
440
+ `);return}if(c.message(ec(r)),!n){c.warn(`No SEOAgent project here. Run \`${p("init")}\` first to persist the provider.`);return}Ce(t,{image_provider:r.provider}),c.info(`Saved to ${_.cyan(".seoagent/project.md")} ${_.dim(`(image_provider: ${r.provider})`)}`)}function ec(e){let n=i=>_.dim(i.padEnd(12)),r=[];if(e.provider==="none"){r.push({content:`${_.dim("\u25CB")} ${_.bold(_.yellow("No image provider detected"))}`}),r.push({sep:!0}),r.push({content:_.dim("Set ONE of these to enable image generation:")});let i=uo();for(let s of Object.keys(i))r.push({content:`${n(s+":")}${_.cyan(i[s].join(" or "))}`});r.push({sep:!0}),r.push({content:_.dim("Add to your shell, .env.local, or .env, then re-run:")}),r.push({content:` ${_.cyan(p("env-check"))}`})}else{r.push({content:`${_.green("\u2713")} ${_.dim("Image provider:")} ${_.bold(_.green(e.provider))}`}),r.push({sep:!0}),e.matched_key&&r.push({content:`${n("Key:")}${_.bold(e.matched_key)}`}),e.source&&r.push({content:`${n("Source:")}${_.cyan(e.source)}`});let i=e.available_providers.filter(s=>s!==e.provider);i.length>0&&r.push({content:`${n("Available:")}${_.dim(i.join(", "))}`})}let o=`${_.bold(_.cyan("SEOAgent"))} ${_.dim("\xB7")} ${_.dim("env-check")}`;return T(r,{width:64,title:o})}import{existsSync as sn,mkdirSync as mo,writeFileSync as go}from"fs";import{dirname as wt,isAbsolute as ic,join as yt,resolve as sc}from"path";import{tmpdir as ac}from"os";import{spinner as lc}from"@clack/prompts";import R from"picocolors";import{Buffer as po}from"buffer";async function on(e){let t=await fetch(e);if(!t.ok)throw new Error(`Image download failed: ${t.status} ${t.statusText}`);let n=await t.arrayBuffer();return po.from(n)}async function tc(e){let t=e.size??"1024x1024",n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:"gpt-image-1",prompt:e.prompt,size:t,n:1})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`OpenAI image API ${n.status}: ${i.slice(0,300)}`)}let o=(await n.json()).data?.[0];if(!o)throw new Error("OpenAI image API returned no data");if(o.b64_json)return{bytes:po.from(o.b64_json,"base64"),contentType:"image/png"};if(o.url)return{bytes:await on(o.url),contentType:"image/png"};throw new Error("OpenAI image API returned neither b64_json nor url")}async function nc(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 on(o.url),contentType:o.content_type??"image/png"}}async function rc(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 oc(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 rc(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 on(o),contentType:"image/png",providerImageId:r.id}}async function fo(e,t){switch(e){case"openai":return tc(t);case"fal":return nc(t);case"replicate":return oc(t);default:throw new Error(`Unknown image provider: ${e}`)}}function cc(e){return e==="openai"||e==="fal"||e==="replicate"}async function Ge(e={}){let t=process.cwd();if(!e.prompt){c.warn(`Missing --prompt. Example: ${p('generate-image --prompt "..." --out content/images/hero.png')}`),process.exitCode=1;return}if(!e.out){c.warn("Missing --out. Example: --out .seoagent/content/images/hero.png"),process.exitCode=1;return}let n=E(t),r=null;if(e.provider){if(!cc(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=ht(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 \`${p("env-check")}\`.`),process.exitCode=1;return}let o=co(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=ic(e.out)?e.out:sc(t,e.out),a=!e.silent&&!!process.stdout.isTTY?lc():null;a?.start(`Generating image with ${R.bold(r)} ${R.dim(`(${o.envName})`)}\u2026`);try{let l=await fo(r,{prompt:e.prompt,apiKey:o.key,size:e.size});sn(wt(i))||mo(wt(i),{recursive:!0}),go(i,l.bytes),e.silent||k(a,"success",`Wrote ${i} (${l.bytes.length} bytes, ${l.contentType}).`,R.green(`Wrote ${i} ${R.dim(`(${l.bytes.length} bytes, ${l.contentType})`)}`))}catch(l){a?.stop(R.red("Image generation failed."));let u=dc(t,{provider:r,envName:o.envName,prompt:e.prompt,size:e.size,outPath:i,error:l});c.message(uc({provider:r,envName:o.envName,prompt:e.prompt,size:e.size,message:l.message})),u&&c.message(`${R.dim("Full error log:")} ${R.cyan(u)}`),process.exitCode=1}}function uc(e){let n=d=>R.dim(d.padEnd(10)),o=e.prompt.length>54?`${e.prompt.slice(0,53)}\u2026`:e.prompt,i=[{content:`${R.red("\u2717")} ${R.bold(R.red("Image generation failed"))}`},{sep:!0},{content:`${n("Provider:")}${R.bold(e.provider)}`},{content:`${n("Key:")}${e.envName}`},{content:`${n("Prompt:")}${R.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:R.red(l)});let u=`${R.bold(R.cyan("SEOAgent"))} ${R.dim("\xB7")} ${R.dim("generate-image")}`;return T(i,{width:70,title:u})}function dc(e,t){let r=`seoagent-generate-image-${new Date().toISOString().replace(/[:.]/g,"-")}.log`,o=yt(e,$),i=yt(o,".errors"),s=sn(o)?yt(i,r):yt(ac(),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 sn(wt(s))||mo(wt(s),{recursive:!0}),go(s,a.join(`
441
+ `)),s}catch{return null}}import j from"picocolors";async function He(e={}){let t=A();if(!t){e.json?process.stdout.write(`${JSON.stringify({logged_in:!1})}
404
442
  `):c.error(`Not logged in. Run \`${p("login")}\` first.`),process.exitCode=1;return}let n=(e.apiBase||t.api_base||S.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})}
405
443
  `);return}c.warn(`Logged in, but the server at this API base does not support \`/api/cli/whoami\` yet. Update with \`${p("update-cli")}\` (or re-deploy your server).`),c.message(`API base: ${n}`);return}let i=null;try{i=await o.json()}catch{i=null}if(!o.ok||!i||i.status!=="ok"){e.json?process.stdout.write(`${JSON.stringify({logged_in:!0,error:i?.error??`HTTP ${o.status}`})}
406
444
  `):c.error(`Could not fetch your account (HTTP ${o.status})${i?.error?`: ${i.error}`:""}`),process.exitCode=1;return}if(e.json){process.stdout.write(`${JSON.stringify({logged_in:!0,...i},null,2)}
407
- `);return}c.message(ql(i)),i.paid===!1&&c.message(`${j.dim("Upgrade for autopilot:")} ${j.cyan(S.PRICING)}`)}function ql(e){let n=i=>j.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${j.green("\u2713")} ${j.dim("Logged in as")} ${j.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${j.cyan(e.domain)}`}),e.plan){let i=e.paid?j.bold(j.green(e.plan)):j.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${j.dim(e.api_base)}`});let o=`${j.bold(j.cyan("SEOAgent"))} ${j.dim("\xB7")} ${j.dim("whoami")}`;return L(r,{width:55,title:o})}import{select as Vt,text as Me,confirm as oo,isCancel as G,intro as zl,outro as Yl}from"@clack/prompts";import dt from"picocolors";function Jl(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>Ae()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await B()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await _e()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await Oe()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await De()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await Vt({message:"Which mode?",options:[{value:"peek",label:"peek",hint:"Free, one keyword, no login required"},{value:"enrich",label:"enrich (default)",hint:"Enrich your full strategy (requires login)"},{value:"discover",label:"discover",hint:"Find new keywords to target (paid)"},{value:"competitors",label:"competitors",hint:"Find competitor keyword gaps (paid)"}]});if(!G(e))if(e==="peek"){let t=await Me({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(G(t))return;await V({peek:String(t)})}else e==="discover"?await V({discover:!0}):e==="competitors"?await V({competitors:!0}):await V()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>Ne({})},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await Me({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(G(e))return;let t=await Me({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});G(t)||await Ue({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>Fe({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await Vt({message:"Autopilot action:",options:[{value:"status",label:"status",hint:"Show current state"},{value:"on",label:"on",hint:"Turn autopilot ON (paid)"},{value:"off",label:"off",hint:"Turn autopilot OFF"}]});G(e)||await je(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await oe()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await Me({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(G(e))return;let t=await oo({message:"Mark as failed instead of completed?",initialValue:!1});if(G(t))return;let n;if(t===!0){let r=await Me({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(G(r))return;String(r).trim()&&(n=String(r))}await J(String(e),{failed:t===!0,reason:n})}},{command:"upgrade",label:"Upgrade your SEOAgent plan",hint:"Open the pricing page; contextual prompt if logged in.",run:async()=>await Re()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest",run:async()=>await Te({})},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>Le()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await Ee({})}]}var no="__exit__";async function ro(e=Jl()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:no,label:"Exit",hint:"Close the menu"});let n=await Vt({message:"What would you like to do?",options:t});if(G(n)||n===no)return!0;let r=e.find(o=>o.command===n);if(!r)return c.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){c.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function Xt(){if(!process.stdin.isTTY){c.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}zl(`${dt.bold(dt.cyan("SEOAgent"))} ${dt.dim("\xB7 menu")}`);let e=await ro();for(;!e;){let t=await oo({message:"Do another?",initialValue:!0});if(G(t)||t===!1){e=!0;break}e=await ro()}Yl(dt.dim("See you next time."))}var v=new Vl;v.name("seoagent").description("AI SEO agent for Claude Code").version(ae).showSuggestionAfterError(!0).showHelpAfterError(!0);v.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").action(e=>{_e({yes:e.yes,domain:e.domain,siteType:e.siteType})});v.command("uninstall").description("Remove SEOAgent from this project \u2014 deletes .seoagent/, the skill bundle, and the sync hook").option("-y, --yes","Skip the confirmation prompt (also implied in a non-TTY shell)").option("--global","Also wipe ~/.config/seoagent (login + sync state, all projects)").action(e=>{Ee({yes:e.yes,global:e.global})});v.command("status").description("Show current SEO project state").action(Ae);v.command("login").description("Connect this CLI to your seoagent.com account (browser flow)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{Oe({apiBase:e.apiBase})});v.command("logout").description("Remove stored credentials for seoagent.com").action(Le);v.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force","Re-send every artifact on push; take cloud on every pull conflict").option("--path <relpath>","Push only files matching this path suffix").option("--push-only","Skip the cloud \u2192 local pull pass").option("--pull-only","Skip the local \u2192 cloud push pass (same as `seoagent pull`)").action(e=>{B({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});v.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force","Take the cloud version on every conflict (discards local edits)").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{oe({force:e.force,silent:e.silent,print:e.print})});v.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{J(e,{failed:t.failed,reason:t.reason})});v.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{Mt({json:e.json})});v.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{Ht({yes:e.yes,model:e.model})});v.command("autopilot <action>").description("Turn CLI autopilot on|off or show status (paid; queues fixes for your agent)").option("--api-base <url>","Override API base URL (for testing)").action((e,t)=>{je(e,{apiBase:t.apiBase})});v.command("keywords").description("Enrich keywords with real volume + difficulty + opportunity labels (requires login)").option("--peek <keyword>","Free one-keyword DataForSEO lookup (no login required; daily quota)").option("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{V({peek:e.peek,discover:e.discover,competitors:e.competitors,json:e.json,apiBase:e.apiBase})});v.command("internal-links").description("Analyze the repo for orphan pages (no inbound internal links) \u2192 .seoagent/internal-links.md").option("--json","Print the analysis as JSON instead of writing the report").action(e=>{Ne({json:e.json})});v.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{Fe({json:e.json})});v.command("generate-image").description("Generate an image via the detected (or explicit) provider").requiredOption("--prompt <text>","Image prompt").requiredOption("--out <path>","Output file path (relative to cwd or absolute)").option("--provider <name>","Force provider: openai | fal | replicate").option("--size <wxh>","Pixel size hint, e.g. 1024x1024").option("--silent","Suppress progress output").action(e=>{Ue({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});v.command("whoami").description("Show the logged-in account: email, bound website, plan, and API base").option("--json","Output as JSON (handy for scripting / `jq`)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{De({json:e.json,apiBase:e.apiBase})});v.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(Re);v.command("update-cli").description("Update the SEOAgent CLI to the latest published npm version").option("--dry-run","Show what would happen without running the install").action(e=>{Te({dryRun:e.dryRun})});v.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{Xt()});process.argv.length===2&&(v.outputHelp(),process.exit(0));v.parse();
445
+ `);return}c.message(pc(i)),i.paid===!1&&c.message(`${j.dim("Upgrade for autopilot:")} ${j.cyan(S.PRICING)}`)}function pc(e){let n=i=>j.dim(i.padEnd(10)),r=[];if(e.email&&(r.push({content:`${j.green("\u2713")} ${j.dim("Logged in as")} ${j.bold(e.email)}`}),r.push({sep:!0})),e.domain&&r.push({content:`${n("Website:")}${j.cyan(e.domain)}`}),e.plan){let i=e.paid?j.bold(j.green(e.plan)):j.bold(e.plan);r.push({content:`${n("Plan:")}${i}`})}e.api_base&&r.push({content:`${n("API:")}${j.dim(e.api_base)}`});let o=`${j.bold(j.cyan("SEOAgent"))} ${j.dim("\xB7")} ${j.dim("whoami")}`;return T(r,{width:55,title:o})}import{select as bt,text as qe,confirm as wo,isCancel as D,intro as fc,outro as mc}from"@clack/prompts";import kt from"picocolors";function gc(){return[{command:"status",label:"Show project status",hint:"Audit, strategy, briefs, content, roadmap \u2014 everything at a glance.",run:async()=>Te()},{command:"sync",label:"Sync with the cloud dashboard",hint:"Push local .seoagent/ changes + pull dashboard edits.",run:async()=>await W()},{command:"init",label:"Initialize a SEOAgent project",hint:"Scaffold .seoagent/ + the skill file in this directory.",run:async()=>{await Re()}},{command:"login",label:"Connect this CLI to seoagent.com",hint:"Opens the browser to bind your account.",run:async()=>await De()},{command:"whoami",label:"Show logged-in account",hint:"Email, bound website, plan, API base.",run:async()=>await He()},{command:"keywords",label:"Keyword research",hint:"Peek (free, one keyword) \xB7 enrich \xB7 discover \xB7 competitor gaps.",run:async()=>{let e=await bt({message:"Which mode?",options:[{value:"peek",label:"peek",hint:"Free, one keyword, no login required"},{value:"enrich",label:"enrich (default)",hint:"Enrich your full strategy (requires login)"},{value:"discover",label:"discover",hint:"Find new keywords to target (paid)"},{value:"competitors",label:"competitors",hint:"Find competitor keyword gaps (paid)"}]});if(!D(e))if(e==="peek"){let t=await qe({message:"Keyword to peek:",placeholder:"saas seo",validate:n=>String(n??"").trim()?void 0:"A keyword is required."});if(D(t))return;await Q({peek:String(t)})}else e==="discover"?await Q({discover:!0}):e==="competitors"?await Q({competitors:!0}):await Q()}},{command:"internal-links",label:"Analyze internal links",hint:"Find orphan pages \u2192 .seoagent/internal-links.md",run:async()=>Me({})},{command:"okf",label:"Open Knowledge Format bundle",hint:"Make your site AI-readable (AEO/GEO) \u2192 .seoagent/okf/",run:async()=>{let e=await bt({message:"Which OKF action?",options:[{value:"status",label:"status",hint:"Is a bundle present?"},{value:"scaffold",label:"scaffold",hint:"Create the starter bundle"},{value:"validate",label:"validate",hint:"Check type fields, timestamps, links"}]});D(e)||Ke(e==="status"?void 0:String(e))}},{command:"generate-image",label:"Generate an image",hint:"Uses the detected (or explicit) provider.",run:async()=>{let e=await qe({message:"Image prompt:",placeholder:"a minimalist cyan box logo",validate:n=>String(n??"").trim()?void 0:"A prompt is required."});if(D(e))return;let t=await qe({message:"Output file path:",placeholder:".seoagent/content/images/hero.png",validate:n=>String(n??"").trim()?void 0:"An output path is required."});D(t)||await Ge({prompt:String(e),out:String(t)})}},{command:"env-check",label:"Check image-generation provider",hint:"Detect openai / fal / replicate from your env.",run:async()=>We({})},{command:"autopilot",label:"Toggle CLI autopilot",hint:"on / off / status \u2014 paid feature for queueing SEO fixes.",run:async()=>{let e=await bt({message:"Autopilot action:",options:[{value:"status",label:"status",hint:"Show current state"},{value:"on",label:"on",hint:"Turn autopilot ON (paid)"},{value:"off",label:"off",hint:"Turn autopilot OFF"}]});D(e)||await Be(String(e))}},{command:"pull",label:"Pull dashboard changes only",hint:"Cloud \u2192 local. Same as the second half of `sync`.",run:async()=>await se()},{command:"ack",label:"Close out a pending inbox action",hint:"Mark a .seoagent/inbox/ action completed or failed.",run:async()=>{let e=await qe({message:"Action ID to close out:",placeholder:"action-abc123",validate:r=>String(r??"").trim()?void 0:"Action ID is required."});if(D(e))return;let t=await wo({message:"Mark as failed instead of completed?",initialValue:!1});if(D(t))return;let n;if(t===!0){let r=await qe({message:"Reason for failure (optional):",placeholder:"couldn't apply because\u2026"});if(D(r))return;String(r).trim()&&(n=String(r))}await V(String(e),{failed:t===!0,reason:n})}},{command:"upgrade",label:"Upgrade your SEOAgent plan",hint:"Open the pricing page; contextual prompt if logged in.",run:async()=>await Ne()},{command:"update-cli",label:"Update the CLI to the latest version",hint:"npm install -g @seoagent-official/seoagent@latest",run:async()=>await Fe({})},{command:"logout",label:"Log out",hint:"Clear stored credentials for seoagent.com.",run:async()=>Ue()},{command:"uninstall",label:"Uninstall SEOAgent from this project",hint:"Remove .seoagent/, the skill bundle, and the sync hook.",run:async()=>await Pe({})}]}var ho="__exit__";async function yo(e=gc()){let t=e.map(o=>({value:o.command,label:o.label,hint:o.hint}));t.push({value:ho,label:"Exit",hint:"Close the menu"});let n=await bt({message:"What would you like to do?",options:t});if(D(n)||n===ho)return!0;let r=e.find(o=>o.command===n);if(!r)return c.warn(`Unknown menu pick "${String(n)}" \u2014 returning to menu.`),!1;try{await r.run()}catch(o){c.error(`\`${r.command}\` failed: ${o.message??String(o)}`)}return!1}async function an(){if(!process.stdin.isTTY){c.info("The menu needs an interactive terminal. Use the regular commands directly, e.g. `seoagent --help`.");return}fc(`${kt.bold(kt.cyan("SEOAgent"))} ${kt.dim("\xB7 menu")}`);let e=await yo();for(;!e;){let t=await wo({message:"Do another?",initialValue:!0});if(D(t)||t===!1){e=!0;break}e=await yo()}mc(kt.dim("See you next time."))}var x=new hc;x.name("seoagent").description("AI SEO agent for Claude Code").version(ce).showSuggestionAfterError(!0).showHelpAfterError(!0);x.command("init").description("Initialize SEOAgent project \u2014 creates .seoagent/ and installs the skill file").option("-y, --yes","Non-interactive: use inferred/env/flag values only (requires domain if not inferable)").option("--domain <domain>","Website domain (non-interactive or override)").option("--site-type <type>","Site type: saas, service, product, content, etc.").action(e=>{Re({yes:e.yes,domain:e.domain,siteType:e.siteType})});x.command("uninstall").description("Remove SEOAgent from this project \u2014 deletes .seoagent/, the skill bundle, and the sync hook").option("-y, --yes","Skip the confirmation prompt (also implied in a non-TTY shell)").option("--global","Also wipe ~/.config/seoagent (login + sync state, all projects)").action(e=>{Pe({yes:e.yes,global:e.global})});x.command("status").description("Show current SEO project state").action(Te);x.command("login").description("Connect this CLI to your seoagent.com account (browser flow)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{De({apiBase:e.apiBase})});x.command("logout").description("Remove stored credentials for seoagent.com").action(Ue);x.command("sync").description("Sync .seoagent/ with your dashboard \u2014 push local changes then pull cloud changes (no-op when not logged in)").option("--silent","Suppress output (used by the Claude Code hook)").option("--force","Re-send every artifact on push; take cloud on every pull conflict").option("--path <relpath>","Push only files matching this path suffix").option("--push-only","Skip the cloud \u2192 local pull pass").option("--pull-only","Skip the local \u2192 cloud push pass (same as `seoagent pull`)").action(e=>{W({silent:e.silent,force:e.force,path:e.path,pushOnly:e.pushOnly,pullOnly:e.pullOnly})});x.command("pull").description("Pull cloud changes into .seoagent/ (dashboard / autopilot / chat edits)").option("--silent","Suppress output").option("--force","Take the cloud version on every conflict (discards local edits)").option("--print <path>","Read-only: print the current cloud body of one artifact to stdout (writes nothing). For conflict diffs.").action(e=>{se({force:e.force,silent:e.silent,print:e.print})});x.command("ack [action_id]").description("Close out a pending action from .seoagent/inbox/ (omit id for an interactive picker)").option("--failed","Mark as failed instead of completed").option("--reason <text>","Reason for failure (used with --failed)").action((e,t)=>{V(e,{failed:t.failed,reason:t.reason})});x.command("inbox").description("List pending actions queued by autopilot in .seoagent/inbox/").option("--json","Output as JSON (handy for scripting / `jq`)").action(e=>{Yt({json:e.json})});x.command("process").description("Sync the inbox, pick which actions to apply, and run them via the Claude Agent SDK (uses your `claude login` session or ANTHROPIC_API_KEY)").option("--yes, -y","Skip the sync + selection prompts; process every pending action (for CI)").option("--model <name>","Override the model the Agent SDK uses (e.g. claude-sonnet-4-5-20250929)").action(e=>{Zt({yes:e.yes,model:e.model})});x.command("autopilot <action>").description("Turn CLI autopilot on|off or show status (paid; queues fixes for your agent)").option("--api-base <url>","Override API base URL (for testing)").action((e,t)=>{Be(e,{apiBase:t.apiBase})});x.command("keywords").description("Enrich keywords with real volume + difficulty + opportunity labels (requires login)").option("--peek <keyword>","Free one-keyword DataForSEO lookup (no login required; daily quota)").option("--discover","Find NEW keywords to target from your existing strategy (paid)").option("--competitors","Find keywords competitors rank for that you don\u2019t (paid)").option("--json","Output as JSON (handy for scripting / `jq` \u2014 currently --peek only)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{Q({peek:e.peek,discover:e.discover,competitors:e.competitors,json:e.json,apiBase:e.apiBase})});x.command("internal-links").description("Analyze the repo for orphan pages (no inbound internal links) \u2192 .seoagent/internal-links.md").option("--json","Print the analysis as JSON instead of writing the report").action(e=>{Me({json:e.json})});x.command("okf [action]").description("Manage the Open Knowledge Format bundle for AI agents \u2014 [validate|scaffold] \u2192 .seoagent/okf/").option("--json","Output result as JSON").action((e,t)=>{Ke(e,{json:t.json})});x.command("env-check").description("Detect which image generation provider is available (OPENAI / FAL / REPLICATE)").option("--json","Output detection result as JSON").action(e=>{We({json:e.json})});x.command("generate-image").description("Generate an image via the detected (or explicit) provider").requiredOption("--prompt <text>","Image prompt").requiredOption("--out <path>","Output file path (relative to cwd or absolute)").option("--provider <name>","Force provider: openai | fal | replicate").option("--size <wxh>","Pixel size hint, e.g. 1024x1024").option("--silent","Suppress progress output").action(e=>{Ge({prompt:e.prompt,out:e.out,provider:e.provider,size:e.size,silent:e.silent})});x.command("whoami").description("Show the logged-in account: email, bound website, plan, and API base").option("--json","Output as JSON (handy for scripting / `jq`)").option("--api-base <url>","Override API base URL (for testing)").action(e=>{He({json:e.json,apiBase:e.apiBase})});x.command("upgrade").description("Open the SEOAgent Cloud pricing page in your browser (plan upgrade)").action(Ne);x.command("update-cli").description("Update the SEOAgent CLI to the latest published npm version").option("--dry-run","Show what would happen without running the install").action(e=>{Fe({dryRun:e.dryRun})});x.command("menu").description("Interactive menu \u2014 pick a command from a list (no flags required)").action(()=>{an()});process.argv.length===2&&(x.outputHelp(),process.exit(0));x.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seoagent-official/seoagent",
3
- "version": "1.49.0",
3
+ "version": "1.50.0",
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": {
@@ -0,0 +1,74 @@
1
+ # Open Knowledge Format (OKF) Bundle
2
+
3
+ OKF is an open standard Google published in 2026 (spec + reference code at `github.com/GoogleCloudPlatform/knowledge-catalog/okf`) for packaging an organization's knowledge as a directory of **markdown files with YAML frontmatter**, designed for AI agents and answer engines to read directly. It is vendor-neutral, human-readable, and version-controlled like code — think of it as a wiki written for machines.
4
+
5
+ **Why it matters for SEO:** a growing share of search happens inside AI assistants (ChatGPT, Claude, Perplexity) and Google's AI Overviews. Being understood and cited there is **Answer Engine Optimization (AEO / GEO)**. An OKF bundle gives those models a curated, trustworthy account of the business instead of leaving them to guess from scraped pages. SEOAgent is uniquely positioned to produce it because the knowledge already lives in `.seoagent/` (business context, strategy, published content).
6
+
7
+ This file is the protocol for generating and maintaining a site's OKF bundle. The deterministic parts (scaffold + validate) are CLI commands; **you** write the bundle content by mapping `.seoagent/` artifacts into OKF files.
8
+
9
+ ## Where the bundle lives
10
+
11
+ `.seoagent/okf/` — it syncs to the cloud like the rest of `.seoagent/`. The user publishes it themselves at `/.well-known/okf/` or `/okf/` on their site (or links it from `llms.txt`).
12
+
13
+ ## Frontmatter rules
14
+
15
+ Every `.md` file MUST have YAML frontmatter with:
16
+
17
+ - **`type`** (required) — the only mandatory field. Use one of: `Organization`, `Concept`, `Topic`, `FAQ`, `Article`, `Service`, `Metric`, `Log`.
18
+
19
+ Recommended optional fields:
20
+
21
+ - `title` — human-readable name
22
+ - `description` — one or two sentences, ≤ 200 characters
23
+ - `resource` — canonical URL of the real asset (e.g. the live article/page)
24
+ - `tags` — list, e.g. `[pricing, plans]`
25
+ - `timestamp` — ISO-8601, e.g. `2026-05-28T14:30:00Z`
26
+
27
+ Cross-link concepts with **relative markdown links only** (`[Pricing](concepts/pricing.md)`) — every link must resolve to a file in the bundle. Reserved files: `index.md` (entry point / progressive disclosure) and `log.md` (chronological change history).
28
+
29
+ ## Bundle layout — map `.seoagent/` → OKF
30
+
31
+ ```
32
+ .seoagent/okf/
33
+ ├── index.md # type: Organization — business overview, links to everything
34
+ ├── log.md # type: Log — chronological change history
35
+ ├── concepts/ # type: Concept | Topic | Service
36
+ │ ├── pricing.md
37
+ │ └── <keyword-cluster-or-entity>.md
38
+ ├── faqs/ # type: FAQ — one answer-engine Q&A per file
39
+ │ └── what-is-x.md
40
+ └── articles/ # type: Article — published pages, resource = live URL
41
+ └── guide-to-x.md
42
+ ```
43
+
44
+ | OKF file | `type` | Source in `.seoagent/` |
45
+ |---|---|---|
46
+ | `index.md` | `Organization` | `project.md` (domain) + `context.md` (business description) |
47
+ | `concepts/*.md` | `Concept` / `Topic` / `Service` | `strategy/clusters/*` keyword clusters; core services/entities from `context.md` |
48
+ | `faqs/*.md` | `FAQ` | Questions answered in briefs/content; "People Also Ask" items |
49
+ | `articles/*.md` | `Article` | Each `content/*` article — set `resource:` to its live URL, summarize the key facts |
50
+ | `log.md` | `Log` | Append a dated line whenever you regenerate the bundle (mirror `changelog.md`) |
51
+
52
+ ## Generation protocol
53
+
54
+ 1. Run `seoagent okf scaffold` to create the directory skeleton (`index.md` + `log.md`) — it never overwrites existing files.
55
+ 2. Fill `index.md` from `.seoagent/context.md` and `project.md`: what the business does, who it serves, then a linked list of the concept / FAQ / article files.
56
+ 3. For each keyword cluster in `.seoagent/strategy/clusters/`, write a `concepts/<slug>.md` (`type: Concept` or `Topic`) capturing the definitive, factual explanation — not marketing fluff. Stats, definitions, and comparisons are what AI cites.
57
+ 4. For each clear question the business answers, write a `faqs/<slug>.md` (`type: FAQ`): the question as the title, a tight factual answer in the body.
58
+ 5. For each published article in `.seoagent/content/`, write `articles/<slug>.md` (`type: Article`) with `resource:` set to the live URL and a 2–4 sentence factual summary; cross-link related concepts.
59
+ 6. Add a dated entry to `log.md`.
60
+ 7. Run `seoagent okf validate` and fix every error (missing `type`, bad `timestamp`, broken link) before finishing.
61
+ 8. Sync runs automatically (or `seoagent sync`) so the bundle reaches the cloud dashboard.
62
+
63
+ ## Quality bar
64
+
65
+ - Write for a model, not a brochure: lead with facts, numbers, and definitions. Avoid superlatives and CTAs.
66
+ - One concept per file; keep files focused and cross-linked.
67
+ - Keep `resource:` URLs canonical and live — they are how an agent verifies and cites you.
68
+ - Regenerate when content changes so the bundle never drifts from reality.
69
+
70
+ ## CLI commands
71
+
72
+ - `seoagent okf` — status (is a bundle present? how many files?)
73
+ - `seoagent okf scaffold` — create the starter `index.md` + `log.md`
74
+ - `seoagent okf validate` — assert every file has `type`, timestamps are ISO-8601, and all relative links resolve
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: seoagent
3
- description: "Persistent AI SEO agent. ALWAYS use when the user mentions: SEO, ranking, rank, keywords, meta tags, search traffic, organic traffic, content strategy, audit, Google, Bing, Search Console, GSC, schema markup, JSON-LD, sitemap, robots.txt, internal linking, AI search, AEO, GEO, alt text, page speed, Core Web Vitals, slug, URL structure, canonical, breadcrumbs, hub and spoke, pillar content, topic cluster, programmatic SEO, landing page SEO, blog SEO, why am I not ranking. Also use SILENTLY when the user asks to write, edit, or improve a blog post, landing page, marketing copy, or any file under content/, posts/, blog/, pages/ — these are SEO-adjacent and should persist to .seoagent/ even without an explicit invocation. Replaces separate seo-audit, content-strategy, programmatic-seo, ai-seo, site-architecture, and schema-markup skills with one unified, persistent workflow."
3
+ description: "Persistent AI SEO agent. ALWAYS use when the user mentions: SEO, ranking, rank, keywords, meta tags, search traffic, organic traffic, content strategy, audit, Google, Bing, Search Console, GSC, schema markup, JSON-LD, sitemap, robots.txt, internal linking, AI search, AEO, GEO, OKF, Open Knowledge Format, AI knowledge bundle, llms.txt, alt text, page speed, Core Web Vitals, slug, URL structure, canonical, breadcrumbs, hub and spoke, pillar content, topic cluster, programmatic SEO, landing page SEO, blog SEO, why am I not ranking. Also use SILENTLY when the user asks to write, edit, or improve a blog post, landing page, marketing copy, or any file under content/, posts/, blog/, pages/ — these are SEO-adjacent and should persist to .seoagent/ even without an explicit invocation. Replaces separate seo-audit, content-strategy, programmatic-seo, ai-seo, site-architecture, and schema-markup skills with one unified, persistent workflow."
4
4
  allowed-tools: Read, Write, Edit, Bash, WebFetch, WebSearch
5
5
  ---
6
6
 
@@ -33,6 +33,7 @@ This SKILL.md is the orchestration layer. Detailed protocols live in `references
33
33
  | Programmatic SEO at scale | `references/programmatic.md` |
34
34
  | Adding schema markup / JSON-LD | `references/schema-markup.md` |
35
35
  | Refreshing or rewriting an existing page | `references/rewrite-protocol.md` |
36
+ | Generating/publishing an OKF bundle for AI agents (AEO/GEO) | `references/open-knowledge-format.md` |
36
37
 
37
38
  Loading the right reference makes outputs dramatically better. Don't skip it.
38
39
 
@@ -697,6 +698,21 @@ If the article already exists, **read `references/rewrite-protocol.md`** instead
697
698
 
698
699
  ---
699
700
 
701
+ ## Phase 6: Publish an OKF Knowledge Bundle (AEO/GEO)
702
+
703
+ When the user asks to "publish an OKF bundle", "make my site AI-readable", "get cited by ChatGPT / Claude / Perplexity", "Open Knowledge Format", or "AEO / GEO", produce an OKF bundle that AI agents can read to understand and cite the business.
704
+
705
+ **Read `references/open-knowledge-format.md` first** — it has the full frontmatter rules, the `.seoagent/` → OKF mapping table, and the quality bar. Then:
706
+
707
+ 1. `npx @seoagent-official/seoagent okf scaffold` — create the `.seoagent/okf/` skeleton.
708
+ 2. Fill the bundle by mapping `.seoagent/` artifacts → OKF files (`index.md` from `context.md`/`project.md`; `concepts/*` from strategy clusters; `faqs/*`; `articles/*` from `content/` with `resource:` set to the live URL).
709
+ 3. `npx @seoagent-official/seoagent okf validate` — fix every error (missing `type`, bad `timestamp`, broken link).
710
+ 4. Tell the user to publish the bundle at `/.well-known/okf/` or `/okf/` on their site (or link it from `llms.txt`). Sync pushes it to the cloud automatically.
711
+
712
+ This is the AEO/GEO complement to schema markup: schema describes a single page in HTML; the OKF bundle describes the whole business for agents to load wholesale.
713
+
714
+ ---
715
+
700
716
  ## File Schemas Reference
701
717
 
702
718
  ### `.seoagent/project.md`