seo 0.27.0 → 0.27.1
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/dist/cli.js +2 -2
- package/dist/{dist-r92pXU-n.js → dist-BqfqFOEM.js} +3 -3
- package/dist/{dist-r92pXU-n.js.map → dist-BqfqFOEM.js.map} +1 -1
- package/dist/{dist-caFW7mZ4.js → dist-CrF8rEUb.js} +1 -1
- package/dist/{esm-DxjXNzAF.js → esm-C1VCS-a2.js} +2 -2
- package/dist/{esm-DxjXNzAF.js.map → esm-C1VCS-a2.js.map} +1 -1
- package/dist/index.d.ts +111 -111
- package/dist/index.js +1 -1
- package/dist/mcp.js +3 -6
- package/dist/mcp.js.map +1 -1
- package/package.json +4 -4
|
@@ -3,7 +3,7 @@ import { createRequire as __seoCreateRequire } from 'node:module'; const require
|
|
|
3
3
|
import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,Ft as f,G as p,Gt as m,H as h,Ht as g,I as _,It as v,J as y,Jt as b,K as x,Kt as S,L as C,Lt as w,M as T,Mt as E,N as D,Nt as O,O as k,Ot as A,P as ee,Pt as j,Q as te,Qt as ne,R as M,Rt as re,S as ie,St as ae,T as oe,Tt as se,U as ce,Ut as le,V as ue,Vt as de,W as fe,Wt as pe,X as me,Xt as N,Y as he,Yt as ge,Z as _e,Zt as ve,_ as ye,_t as be,a as xe,an as Se,at as Ce,b as we,bt as Te,c as Ee,cn as De,ct as Oe,d as ke,dt as Ae,en as je,et as Me,f as Ne,ft as Pe,g as Fe,gt as Ie,h as Le,ht as Re,i as ze,in as Be,it as Ve,jt as He,kt as Ue,l as We,lt as Ge,m as Ke,mt as qe,n as Je,nn as Ye,nt as Xe,o as Ze,ot as Qe,p as $e,pt as et,q as tt,qt as nt,r as rt,rn as P,rt as it,sn as at,st as ot,t as st,tn as ct,tt as lt,u as ut,ut as dt,v as ft,vt as pt,w as mt,wt as ht,x as gt,xt as _t,y as vt,yt,z as bt}from"./progress-DS6XGY-8.js";import{createRequire as xt}from"node:module";import St,{createHash as Ct,randomUUID as wt,sign as Tt}from"node:crypto";import{ZodOptional as Et,z as F}from"zod";import{arch as Dt,homedir as Ot,hostname as kt,platform as At,tmpdir as jt,totalmem as Mt}from"node:os";import{dirname as Nt,extname as Pt,isAbsolute as Ft,join as I,relative as It,resolve as Lt}from"node:path";import Rt from"open";import{chmodSync as zt,createReadStream as Bt,existsSync as Vt,mkdirSync as Ht,readFileSync as Ut,readdirSync as Wt,realpathSync as Gt,renameSync as Kt,rmSync as qt,statSync as Jt,writeFileSync as Yt}from"node:fs";import Xt from"proper-lockfile";import Zt,{createServer as Qt}from"node:http";import{Headers as $t,fetch as en}from"undici";import tn from"libsql";import{ElementType as nn,Parser as rn,parseDocument as an}from"htmlparser2";import{Readability as on}from"@mozilla/readability";import sn from"defuddle";import{parseHTML as cn}from"linkedom";import ln,{AbortError as un}from"p-retry";import dn from"p-queue";import fn from"robots-parser";import{chromium as pn}from"playwright-core";import{gunzipSync as mn}from"node:zlib";import{setTimeout as hn}from"node:timers/promises";import{fileURLToPath as gn,pathToFileURL as _n}from"node:url";import{glob as vn,mkdtemp as yn,open as bn,readFile as xn,readdir as Sn,rm as Cn,stat as wn}from"node:fs/promises";import{TextDecoder as Tn,promisify as En}from"node:util";import{execFile as Dn}from"node:child_process";import"pino";import"pino-pretty";import{request as On}from"node:https";import*as kn from"zod/v3";import{ZodFirstPartyTypeKind as L}from"zod/v3";import*as An from"zod/v4-mini";import*as R from"zod/v4";import jn from"node:process";var Mn=Object.create,Nn=Object.defineProperty,Pn=Object.getOwnPropertyDescriptor,Fn=Object.getOwnPropertyNames,In=Object.getPrototypeOf,Ln=Object.prototype.hasOwnProperty,z=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),Rn=(e,t)=>{let n=Object.setPrototypeOf({},null);for(var r in e)Nn(n,r,{get:e[r],enumerable:!0});return t&1||Nn(n,Symbol.toStringTag,{value:`Module`}),t&2?n:Object.preventExtensions(n)},zn=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Fn(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ln.call(e,s)&&s!==n&&Nn(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Pn(t,s))||r.enumerable});return e},Bn=(e,t,n)=>(n=e==null?{}:Mn(In(e)),zn(t||!e||!e.__esModule||!Ln.call(e,`default`)?Nn(n,`default`,{value:e,enumerable:!0}):n,e)),Vn=/* @__PURE__ */ xt(import.meta.url);const Hn={google:{label:`Google Analytics`,landingMetricLabel:`sessions`},clicky:{label:`Clicky`,landingMetricLabel:`landing-page visits`}};function Un(e){return e in Hn?Hn[e]:{label:e,landingMetricLabel:`landing-page visits`}}function Wn(e){return e.provider===`extension`?e.providerId:e.provider}const Gn=[{id:`missing_title`,title:`Title missing`,category:`metadata`,defaultSeverity:`high`,whyItMatters:`The title is the main search-result headline and one of the clearest page-topic signals. Without it, search engines invent a label and users get a weaker reason to click.`,howToFix:`Add one descriptive title that names the page topic and matches the main query intent. Keep it useful for humans first.`,impactIfIgnored:`The page can look vague in search results, earn lower CTR, and send weaker relevance signals.`,howToVerify:"Re-run `seo audit-page --url <url>` and confirm the title is present in the page audit output.",agentHints:{evidenceFields:[`page.title`],suggestedCommands:[`seo audit-page --url <url> --json`]}},{id:`empty_title`,title:`Title empty`,category:`metadata`,defaultSeverity:`high`,whyItMatters:`The page has a <title> element with no text. Search engines treat it like a missing title and write their own headline for the result.`,howToFix:`Fill the title element with a descriptive title that names the page topic. An empty title usually means a template field or CMS value is blank.`,impactIfIgnored:`The page can look vague in search results, earn lower CTR, and send weaker relevance signals.`,howToVerify:`Re-run the crawl and confirm the title element has text.`,agentHints:{evidenceFields:[`page.title`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`title_too_wide`,title:`Title may truncate on some devices`,category:`metadata`,defaultSeverity:`low`,whyItMatters:`Google has no fixed title length limit, but title links are truncated to fit the available device width. Important wording placed late may not always display.`,howToFix:`Review the title rather than shortening it blindly. Put the clearest page-specific wording first and remove filler only when meaning is preserved.`,impactIfIgnored:`Some result layouts may truncate later words. This is a display estimate, not an indexing or ranking defect.`,howToVerify:`Re-run the audit and review estimatedPixels, referencePixels, confidence, and profile. Confirm the important wording appears early.`,agentHints:{evidenceFields:[`page.title`,`issue.evidence.estimatedPixels`,`issue.evidence.referencePixels`,`issue.evidence.confidence`,`issue.evidence.profile`],suggestedCommands:[`seo audit-page --url <url> --json`]}},{id:`title_duplicate`,title:`Duplicate title`,category:`metadata`,defaultSeverity:`medium`,whyItMatters:`When multiple pages share the same title, search engines and users get a weaker signal about which page is the right result.`,howToFix:`Rewrite each title so it reflects the specific page, including the unique entity, intent, location, product, or angle.`,impactIfIgnored:`Search engines may pick the wrong page to rank, and users may see repetitive snippets that do not explain the difference.`,howToVerify:`Re-run the crawl and confirm this title appears on only one indexable URL.`,agentHints:{evidenceFields:[`page.title`,`issue.evidence.duplicateCount`,`issue.evidence.sampleUrls`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`h1_missing`,title:`Missing H1`,category:`headings`,defaultSeverity:`low`,whyItMatters:`A descriptive main heading helps readers and assistive technology identify the page topic and navigate its content.`,howToFix:`Add one clear H1 near the top of the main content. Make it describe the specific page, not just a generic section label.`,impactIfIgnored:`The visible document outline may be less clear to readers and assistive technology.`,howToVerify:`Re-run the crawl and confirm an H1 describes the page’s main visible topic.`,agentHints:{evidenceFields:[`page.h1`,`page.h1Count`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`h1_multiple`,title:`Multiple H1 headings`,category:`headings`,defaultSeverity:`low`,whyItMatters:`Multiple H1 headings are valid HTML. Keeping one H1 is a common convention that keeps the visible document outline clear for readers and assistive technology. This is a convention heuristic, not a search-engine requirement.`,howToFix:`Review the headings before changing anything. If one heading describes the whole page, keep it as the H1 and move the others to H2 or below so the outline stays consistent.`,impactIfIgnored:`The visible document outline may be harder to scan, and templates can drift into inconsistent heading use.`,howToVerify:`Re-run the crawl and confirm h1Count matches the intended heading structure.`,agentHints:{evidenceFields:[`page.h1`,`page.h1Count`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`canonical_invalid`,title:`Canonical URL is invalid`,category:`canonical`,defaultSeverity:`high`,whyItMatters:`A malformed or non-HTTP canonical cannot identify a valid preferred page and may be ignored by search engines.`,howToFix:`Replace it with one absolute HTTP or HTTPS URL for the intended preferred page.`,impactIfIgnored:`Search engines receive unusable consolidation evidence and may choose a different canonical on their own.`,howToVerify:`Re-run the page audit and confirm the canonical resolves to the intended HTTP or HTTPS URL.`,agentHints:{evidenceFields:[`page.canonical`,`page.canonicalRaw`,`issue.evidence.canonicalRaw`],suggestedCommands:[`seo audit-page --url <url> --json`]}},{id:`canonical_conflict`,title:`Canonical declarations conflict`,category:`canonical`,defaultSeverity:`high`,whyItMatters:`Different canonical targets in HTML or HTTP headers give search engines contradictory consolidation signals.`,howToFix:`Choose one preferred absolute URL and make every canonical declaration agree, or remove the extra declaration source.`,impactIfIgnored:`Search engines may ignore the declarations or select a different canonical than the site intended.`,howToVerify:`Re-run the crawl and confirm canonicalStatus is single with one intended target.`,agentHints:{evidenceFields:[`page.canonicalCandidates`,`page.canonicalStatus`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`canonical_multiple`,title:`Canonical declared more than once`,category:`canonical`,defaultSeverity:`low`,whyItMatters:`Repeated canonical declarations are error-prone even when they currently point to the same URL.`,howToFix:`Keep one canonical method per response where practical. If HTML and HTTP headers are both required, keep their targets identical.`,impactIfIgnored:`A future template or header change can create a hidden canonical conflict.`,howToVerify:`Re-run the crawl and confirm canonicalStatus is single.`,agentHints:{evidenceFields:[`page.canonicalCandidates`,`page.canonicalStatus`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`canonical_outside_head`,title:`Canonical appears outside the HTML head`,category:`canonical`,defaultSeverity:`medium`,whyItMatters:`Google only accepts an HTML canonical link element in the document head.`,howToFix:`Move the canonical link element into a valid head section and keep one absolute preferred URL.`,impactIfIgnored:`The body declaration may be ignored, leaving the page without the intended canonical signal.`,howToVerify:`Re-run the crawl and confirm the canonical candidate source is html-head.`,agentHints:{evidenceFields:[`page.canonicalCandidates`,`page.canonicalStatus`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`canonical_streamed_in_body`,title:`Canonical streamed into the body`,category:`canonical`,defaultSeverity:`medium`,whyItMatters:`This Next.js App Router response put the canonical link in the body because Next.js streamed the page metadata after the head was sent. Next.js streams metadata to Googlebot and browsers, and sends it in the head only to bots on its HTML-limited list, such as Bingbot. Google documents that it only accepts a canonical link in the head. Next.js states that Googlebot reads streamed metadata correctly, but a browser render can leave the link in the body.`,howToFix:`If Google must see the canonical in the head, make Next.js send metadata before the body for Googlebot. Set htmlLimitedBots in the Next.js config to a pattern that matches Googlebot as well as the default bots, or to /.*/ to turn streaming metadata off for everyone. Waiting for metadata can slow the first byte.`,impactIfIgnored:`Google may ignore the canonical and choose its own, which matters most when the canonical points to another URL. Placement depends on the user agent and cache state, so repeated fetches of the same URL can disagree.`,howToVerify:`Fetch the URL with a Googlebot user agent and confirm the canonical is in the head, then re-run the crawl and confirm canonicalStatus is single.`,review:{question:`Should Google receive this canonical in the head, or is relying on Next.js streamed metadata acceptable for this site?`,changeOnlyIf:`Change the config when canonicals consolidate duplicate or parameter URLs, or when Search Console reports a Google-selected canonical that differs from the declared one.`,ifNotNeeded:`Record that Next.js streams metadata into the body for Googlebot, and keep checking Google-selected canonicals in Search Console.`,doNot:[`Do not treat the URL Inspection live test as proof of head placement. Its Google-InspectionTool user agent is on the Next.js HTML-limited list, so it receives metadata in the head.`,`Do not hand-write a second canonical into the layout; that creates duplicate declarations.`]},agentHints:{evidenceFields:[`page.canonicalCandidates`,`page.canonicalStatus`,`page.responseHeaders`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`canonical_mismatch`,title:`Canonical differs from final URL`,category:`canonical`,defaultSeverity:`medium`,whyItMatters:`A canonical pointing somewhere else tells search engines that another URL may be the preferred page. That is useful when intentional and risky when accidental.`,howToFix:`If this page should rank, make the canonical self-referencing. If another URL is preferred, make sure internal links and redirects also point there.`,impactIfIgnored:`Search engines may consolidate signals into the wrong URL or drop this URL from search results.`,howToVerify:`Re-run the page audit and confirm the canonical matches the fetched final URL, or inspect the preferred target instead.`,agentHints:{evidenceFields:[`page.canonical`,`page.finalUrl`],suggestedCommands:[`seo audit-page --url <url> --json`]}},{id:`canonical_non_absolute`,title:`Canonical uses a relative URL`,category:`canonical`,defaultSeverity:`low`,whyItMatters:`Search engines can usually resolve relative canonicals, but absolute canonical URLs are clearer and less fragile across mirrors, previews, and rendered variants.`,howToFix:`Use a full https URL in the canonical tag, including protocol, host, and path.`,impactIfIgnored:`Canonical signals are easier to misread when pages are copied, proxied, or rendered from alternate origins.`,howToVerify:`Re-run the crawl and confirm canonicalRaw starts with http:// or https://.`,agentHints:{evidenceFields:[`page.canonicalRaw`,`page.canonical`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`canonical_chain`,title:`Canonical chain`,category:`canonical`,defaultSeverity:`medium`,whyItMatters:`A canonical that points to another URL which then canonicalizes again creates an indirect consolidation path.`,howToFix:`Point the first page directly at the final preferred URL, or make the intermediate canonical target self-referencing.`,impactIfIgnored:`Search engines may ignore or reinterpret the canonical path, especially at scale.`,howToVerify:`Re-run the crawl and confirm the canonical target is self-referencing.`,agentHints:{evidenceFields:[`page.canonical`,`issue.evidence.nextCanonical`,`issue.evidence.chain`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`connection_error`,title:`Connection error`,category:`response`,defaultSeverity:`high`,whyItMatters:`A URL that cannot be fetched is invisible to users, search crawlers, and AI agents. It may be a DNS, TLS, timeout, firewall, or server availability problem.`,howToFix:`Check DNS, TLS certificates, firewall/CDN rules, server logs, and timeout behavior. Make the URL return a stable 2xx response or one direct redirect to the replacement.`,impactIfIgnored:`The page cannot be crawled, ranked, or cited while the connection failure remains.`,howToVerify:`Re-run the crawl and confirm the URL returns a normal HTTP status instead of status 0.`},{id:`crawler_access_blocked`,title:`Crawler access blocked`,category:`response`,defaultSeverity:`medium`,whyItMatters:`The audit could not observe the intended page because an authentication layer, rate limit, firewall, or challenge intercepted this crawler. This limits the audit evidence but does not prove that search engines or users are blocked.`,howToFix:`First confirm the block is unintended. If the audit should have access, use the provider evidence in the report to grant temporary, narrow access for the audit machine source IP, required hostname or paths, and the exact crawler User-Agent. Do not trust a User-Agent by itself.`,impactIfIgnored:`The affected URL remains unverified in this crawl, so content and indexability checks cannot support a pass or an all-clear.`,howToVerify:`Re-run the same health check and confirm access.blockedRequests is zero and the URL returns its intended status without challenge evidence.`,agentHints:{evidenceFields:[`request.accessBlock`,`report.access`,`issue.evidence.accessBlock`],suggestedCommands:[`seo crawl --sitemap-url <url> --health --json`]}},{id:`soft_authentication_gate`,title:`Page appears to be an authentication gate`,category:`response`,defaultSeverity:`medium`,whyItMatters:`The URL returned a successful HTML response, but the visible document looks like a login gate rather than the intended public page. Users and crawlers may receive a 200 response without the content they expected.`,howToFix:`Confirm whether authentication is intentional. Public URLs should return their public content without a login form. Protected URLs should use a clear 401 or 403 response where appropriate and should not appear in public sitemaps or internal crawl paths.`,impactIfIgnored:`A login page can be mistaken for the intended content, producing misleading crawl results and weak search or agent access.`,howToVerify:`Fetch the affected URL without a session and confirm it returns the intended public page, or a deliberate authentication status for protected content.`,agentHints:{evidenceFields:[`page.softAuthenticationGate`,`page.finalUrl`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`client_rendered_content`,title:`Important content requires JavaScript rendering`,category:`response`,defaultSeverity:`medium`,whyItMatters:`The raw HTML contained very little content and the useful document appeared only after JavaScript rendering. Some crawlers, agents, previews, and constrained clients do not run the page JavaScript.`,howToFix:`Render the important page content into the initial HTML, or publish a complete server-generated representation such as negotiated Markdown. Keep navigation, headings, canonicals, and indexability signals available without client execution.`,impactIfIgnored:`Clients that do not execute JavaScript may see an empty shell or miss important content and links.`,howToVerify:`Re-run the crawl and confirm the raw and rendered content observations contain the same important document content.`,agentHints:{evidenceFields:[`page.fetchDiagnostics.rendering.documentDifference`,`page.usedJs`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`near_empty_content`,title:`Near-empty main content`,category:`content`,defaultSeverity:`low`,whyItMatters:`The extracted main content contains fewer than ten words. This is a review heuristic, not a search-engine word-count requirement. The page may be intentional, incomplete, or dependent on client-side rendering.`,howToFix:`Confirm that the intended body content and internal links exist in the server-delivered HTML. If the useful page appears only after client JavaScript, render it on the server or pre-render it. Leave deliberately minimal pages alone when their purpose is clear.`,impactIfIgnored:`Crawlers and clients that do not execute JavaScript may receive an empty shell or too little context to understand and navigate the page.`,howToVerify:`Fetch the page without browser rendering and confirm the initial HTML contains the intended main content and crawlable links. Then re-run the crawl and review the extracted word count and content sample.`,agentHints:{evidenceFields:[`page.wordCount`,`page.contentSample`,`page.outgoingInternalCount`,`page.fetchDiagnostics.rendering`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`crawl_single_page_reach`,title:`Crawl could reach only the start page`,category:`links`,defaultSeverity:`high`,whyItMatters:`The start page had no crawlable internal links and no sitemap returned URLs, so the crawl checked one page. Every other finding in this report covers that page only. The page probably builds its links with JavaScript.`,howToFix:"Rerun with `--rendering on` so the crawler reads the links a browser sees, or pass the pages to check with `--mode list`. For crawlers that do not run JavaScript, put plain `<a href>` links in the initial HTML and publish a sitemap.",impactIfIgnored:`Crawlers and audits that do not run JavaScript can find only this page, so the rest of the site stays unchecked and harder to discover.`,howToVerify:`Rerun the crawl and confirm it retains more than one page and the start page reports internal links.`,agentHints:{evidenceFields:[`page.outgoingInternalCount`,`report.sitemapDiscovery.urlsReturned`,`page.fetchDiagnostics.rendering`],suggestedCommands:[`seo crawl <url> --rendering on --json`,`seo crawl --mode list --urls <url>,<url> --json`]}},{id:`soft_404`,title:`Unknown URLs return a successful response`,category:`response`,defaultSeverity:`high`,whyItMatters:`Known-nonexistent URLs returned a successful response or redirected to another successful page. Search engines and users cannot reliably distinguish missing content from a real page.`,howToFix:`Return 404 or 410 for missing URLs. If a replacement exists, redirect only the specific retired URL to its closest relevant replacement rather than sending every unknown path to a generic page.`,impactIfIgnored:`Missing URLs can remain in crawl queues, waste crawl attention, and create confusing search or monitoring evidence.`,howToVerify:`Request several made-up paths, including one at the site root and one nested path, and confirm each returns 404 or 410 without redirecting to a generic successful page.`,agentHints:{evidenceFields:[`report.siteChecks.soft404`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`host_variant_not_redirected`,title:`www and the bare domain both serve the site`,category:`canonical`,defaultSeverity:`medium`,whyItMatters:`The home page answered with a page on both www and the bare domain instead of one redirecting to the other. Every page can then be reached at two URLs, which splits links and leaves search engines to pick one.`,howToFix:`Pick one host and send the other to it with a permanent (301 or 308) redirect for every path, at the host, CDN or DNS provider. Keep canonicals and sitemap URLs on the chosen host.`,impactIfIgnored:`Links and signals can split across two copies of the site, and search results may show the host you did not choose.`,howToVerify:`Request the home page on the other host and confirm it returns a 301 or 308 to the same path on the chosen host.`,agentHints:{evidenceFields:[`report.siteChecks.hostVariant`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`client_error`,title:`Client error`,category:`response`,defaultSeverity:`high`,whyItMatters:`A 4xx URL is a dead end for users and search engines. Internal links to 4xx pages waste crawl attention and leak authority.`,howToFix:`Restore the page, update links to the correct URL, or add one direct 301 to the best replacement.`,impactIfIgnored:`Users hit broken pages and search engines may drop the URL or reduce trust in nearby internal links.`,howToVerify:`Re-run the crawl and confirm the URL returns a 2xx status or redirects once to a useful replacement.`},{id:`server_error`,title:`Server error`,category:`response`,defaultSeverity:`high`,whyItMatters:`A 5xx means the server failed to deliver the page. Persistent 5xx errors can slow crawling and remove pages from search.`,howToFix:`Check application logs, hosting health, upstream services, and cache/CDN rules. Return 200 when fixed, or 503 only for planned maintenance.`,impactIfIgnored:`Search engines may crawl less often and users cannot reach the affected pages.`,howToVerify:`Re-run the crawl and confirm the affected URL no longer returns a 5xx status.`},{id:`redirected_url`,title:`URL redirects`,category:`response`,defaultSeverity:`low`,whyItMatters:`This crawl reached the page through a redirect. A direct redirect can be intentional. It becomes worth fixing when internal links, canonicals, or sitemap entries still point to the old URL.`,howToFix:`Check why the old URL was requested. Update internal links, canonicals, and sitemap entries to the final URL when appropriate. Keep one direct 301 when the old URL must remain supported.`,impactIfIgnored:`An avoidable redirect adds a request and can turn into a chain later. An intentional direct redirect needs no change.`,howToVerify:`Re-run the crawl and confirm the requested URL is the same as the final URL, or that the redirect is intentional.`,agentHints:{evidenceFields:[`page.url`,`page.finalUrl`,`page.status`,`page.metaRefresh`],suggestedCommands:[`seo redirect-trace --url <url> --json`]}},{id:`redirect_chain`,title:`Redirect chain`,category:`response`,defaultSeverity:`medium`,whyItMatters:`Multiple redirect hops slow users and crawlers, and each hop is another place a migration can break.`,howToFix:`Point internal links, canonicals, and sitemap URLs directly at the final destination. Keep only one necessary 301 from old URLs.`,impactIfIgnored:`Pages load slower, crawl paths are less clear, and future redirects can turn into loops or dead ends.`,howToVerify:`Re-run the crawl and confirm fetchDiagnostics.redirectChain has zero or one hop.`},{id:`slow_response`,title:`Slow response in this crawl`,category:`response`,defaultSeverity:`low`,whyItMatters:`The crawler observed a slow HTML response. One request is a diagnostic sample, not a field performance verdict, but repeated slow responses are worth investigating.`,howToFix:`Repeat the check and use the performance report before changing anything. If the delay persists, check server timing, cache headers, database queries, CDN caching, and origin health.`,impactIfIgnored:`Persistent slow HTML can delay users and crawlers. A one-off slow sample may be network or origin variance.`,howToVerify:`Re-run the crawl and compare repeated response times. Use field data where available for a user-experience decision.`},{id:`large_html`,title:`Large HTML response`,category:`performance`,defaultSeverity:`low`,whyItMatters:`Googlebot reads only the first 2MB of uncompressed HTML for Google Search and indexes the page as if the file ended there. When the h1 or main element, or most of the visible text, sits past that cut, Google may index the page without its main content. Large HTML is also slow to download and parse.`,howToFix:`Move the main content earlier and trim what comes before it: large inline CSS, inline SVG, JSON data and duplicated markup. Load non-critical styles and scripts as separate files.`,impactIfIgnored:`Content past the 2MB cut is not indexed, and every page of the template carries the same weight on slow connections.`,howToVerify:`Re-run the crawl and confirm sizeBytes is under 2,097,152, or that mainContentStartBytes is well before it and few visible words sit after it. The word split is a heuristic from the raw HTML.`,agentHints:{evidenceFields:[`page.sizeBytes`,`issue.evidence.thresholdBytes`,`issue.evidence.mainContentStartBytes`,`issue.evidence.bytesAfterLimit`,`issue.evidence.visibleWordsAfterLimit`,`issue.evidence.indexingRisk`],suggestedCommands:[`seo crawl <url> --mode page --json`]}},{id:`no_compression`,title:`No text compression`,category:`performance`,defaultSeverity:`low`,whyItMatters:`HTML without gzip or brotli sends more bytes than necessary and slows every first page load.`,howToFix:`Enable gzip or brotli for HTML and other text responses at the server, CDN, or reverse proxy.`,impactIfIgnored:`Users download more data, pages load slower, and the origin may spend more bandwidth than needed.`,howToVerify:`Re-run the crawl and confirm compression is br or gzip for sizeable HTML responses.`,agentHints:{evidenceFields:[`page.compression`,`page.sizeBytes`,`issue.evidence.thresholdBytes`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`http_not_secure`,title:`Page is not served over HTTPS`,category:`security`,defaultSeverity:`medium`,whyItMatters:`HTTPS is a baseline trust signal. Browsers label HTTP pages as not secure, and users can be intercepted or downgraded.`,howToFix:`Install TLS, serve the page on HTTPS, and redirect the HTTP URL to the HTTPS version with a permanent redirect.`,impactIfIgnored:`Users see trust warnings, conversions suffer, and search quality signals are weaker.`,howToVerify:`Re-run the crawl and confirm finalUrl starts with https:// and isHttps is true.`},{id:`mixed_content`,title:`Mixed content`,category:`security`,defaultSeverity:`medium`,whyItMatters:`An HTTPS page that loads HTTP resources can trigger browser warnings or blocked images, scripts, fonts, or media.`,howToFix:`Change insecure resource URLs to HTTPS, update CDN origins, or remove resources that are no longer available securely.`,impactIfIgnored:`Parts of the page may break, users lose trust, and the security guarantee of HTTPS is weakened.`,howToVerify:`Re-run the crawl and confirm mixedContentCount is zero.`,agentHints:{evidenceFields:[`page.mixedContentSamples`,`issue.evidence.mixedContentSamples`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`hsts_missing`,title:`HSTS header missing`,category:`security`,defaultSeverity:`low`,whyItMatters:`HSTS tells browsers to keep using HTTPS, which reduces downgrade risk after the first secure visit.`,howToFix:`Send a Strict-Transport-Security header with a suitable max-age once the whole site is stable on HTTPS.`,impactIfIgnored:`Repeat visitors have a larger downgrade window if a network or link tries to send them to HTTP.`,howToVerify:`Re-run the crawl and confirm hasHsts is true for HTTPS pages.`},{id:`broken_internal_link`,title:`Broken internal link`,category:`links`,defaultSeverity:`high`,whyItMatters:`Internal links that land on broken URLs waste crawl paths, frustrate users, and leak authority inside the site.`,howToFix:`Update every internal link to the working destination, restore the missing page, or add one direct 301 to the best replacement.`,impactIfIgnored:`Users hit dead ends and search engines keep discovering broken URLs from your own pages.`,howToVerify:`Re-run the crawl and confirm the linked URL no longer returns a broken status.`},{id:`broken_external_link`,title:`Broken external link`,category:`links`,defaultSeverity:`medium`,whyItMatters:`External links are part of the page experience and source trail. Broken references make content feel stale and less trustworthy.`,howToFix:`Replace the link with a working source, update the URL, or remove the reference if it no longer supports the page.`,impactIfIgnored:`Readers and agents following citations hit dead ends, which weakens trust in the content.`,howToVerify:`Re-run the crawl with external checks enabled and confirm the URL no longer has a confirmed-broken externalLinkChecks result.`},{id:`orphan_page`,title:`No observed internal links`,category:`links`,defaultSeverity:`low`,whyItMatters:`This crawl did not find an internal link to the page. That is worth checking, but a partial crawl cannot prove that the page is a true sitewide orphan.`,howToFix:`Check the page in a complete crawl and in the sitemap. If it is meant to be discovered, add a relevant link from a hub, navigation path, related page, or template.`,impactIfIgnored:`A genuinely unlinked page can be hard for users and crawlers to find. A page omitted by the crawl needs no change yet.`,howToVerify:`Re-run a complete crawl from the same site entry point and confirm an observed internal link reaches the page.`},{id:`deep_page`,title:`Deep crawl path`,category:`links`,defaultSeverity:`low`,whyItMatters:`This crawl reached the page several links away from its start URL. A capped crawl or a non-homepage start URL does not prove the shortest sitewide path.`,howToFix:`Check whether the page is important and whether a shorter user path makes sense. Add a link from a closer hub, category page, related content block, or navigation path only when it helps users.`,impactIfIgnored:`A genuinely deep important page can be harder to reach. Treat this as a crawl-path review, not a sitewide architecture verdict.`,howToVerify:`Re-run a complete crawl from the same start URL and confirm crawlDepth changed after a justified link update.`},{id:`weak_internal_links_to_valuable_page`,title:`Review internal links to a valuable page`,category:`links`,defaultSeverity:`low`,whyItMatters:`The page has observed search or analytics value but few inlinks within this crawl. It is a review cue, not proof that the page lacks enough internal authority.`,howToFix:`Check the page's role and current navigation first. Add contextual links from relevant hubs, templates, or related pages only when they help users reach it.`,impactIfIgnored:`A valuable page may be harder to find if it is genuinely underlinked. Do not treat the observed count as a ranking forecast.`,howToVerify:`Re-run the same crawl after a justified link change and confirm the observed inlink count changed.`},{id:`missing_meta_description`,title:`Meta description missing`,category:`metadata`,defaultSeverity:`medium`,whyItMatters:`The meta description is often used as search-result copy. Without it, search engines choose their own snippet.`,howToFix:`Write a concise, unique description that explains the page value and matches the main search intent.`,impactIfIgnored:`Search snippets may be generic or less persuasive, especially on pages that already rank.`,howToVerify:`Re-run the crawl and confirm the page has a meta description.`},{id:`empty_meta_description`,title:`Meta description empty`,category:`metadata`,defaultSeverity:`medium`,whyItMatters:`The page has a meta description tag with no content, so search engines choose their own snippet. An empty tag usually means a template field or CMS value is blank.`,howToFix:`Fill the content attribute with a concise, unique description, or fix the template value that leaves it blank.`,impactIfIgnored:`Search snippets may be generic or less persuasive, especially on pages that already rank.`,howToVerify:`Re-run the crawl and confirm the meta description has content.`},{id:`meta_description_duplicate`,title:`Duplicate meta description`,category:`metadata`,defaultSeverity:`medium`,whyItMatters:`Repeated descriptions make different pages look interchangeable and can weaken snippet quality across a section.`,howToFix:`Write a distinct description for each page that explains what is unique about that URL.`,impactIfIgnored:`Search snippets stay generic, and search engines may rewrite them or struggle to distinguish similar pages.`,howToVerify:`Re-run the crawl and confirm this description appears on only one URL.`,agentHints:{evidenceFields:[`page.metaDescription`,`issue.evidence.duplicateCount`,`issue.evidence.sampleUrls`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`canonical_missing`,title:`No canonical declared`,category:`canonical`,defaultSeverity:`low`,whyItMatters:`The page did not declare a canonical. That is often fine for a unique URL. It matters when parameter, protocol, pagination, or duplicate-content variants need a preferred URL.`,howToFix:`First check whether equivalent URL variants exist. Add a self-referencing canonical only when the site uses canonical tags as part of a deliberate duplicate-URL strategy.`,impactIfIgnored:`A unique page may need no action. If duplicate variants exist, search engines can choose a different preferred URL.`,howToVerify:`Re-run the crawl and confirm the canonical field is present and points to the preferred URL.`},{id:`noindex`,title:`Noindex found`,category:`indexability`,defaultSeverity:`medium`,whyItMatters:`Noindex tells search engines not to show the page in search results. It is useful when intentional and risky when accidental.`,howToFix:`Remove the noindex directive if the page should rank. Leave it in place only for intentionally private or low-value pages.`,impactIfIgnored:`The page cannot earn organic search traffic while the noindex directive remains.`,howToVerify:`Re-run the crawl or URL Inspection and confirm no effective meta robots or X-Robots-Tag noindex remains, including the equivalent none directive.`},{id:`nofollow`,title:`Nofollow found`,category:`indexability`,defaultSeverity:`low`,whyItMatters:`Nofollow asks crawlers not to follow links from the page. On important pages, that can block discovery and weaken internal authority flow.`,howToFix:`Remove nofollow from meta robots or X-Robots-Tag unless the page is intentionally isolated from link discovery.`,impactIfIgnored:`Internal links on the page may pass weaker discovery and authority signals.`,howToVerify:`Re-run the crawl and confirm the effective meta robots and X-Robots-Tag rules no longer block following, including through the equivalent none directive.`,agentHints:{evidenceFields:[`page.metaRobots`,`page.xRobotsTag`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`x_robots_noindex`,title:`X-Robots-Tag noindex`,category:`indexability`,defaultSeverity:`medium`,whyItMatters:`An X-Robots-Tag noindex header can remove a page from search even when the HTML looks indexable.`,howToFix:`Remove the noindex directive from server, CDN, or framework response headers if the page should rank.`,impactIfIgnored:`The page remains excluded from search results while the header is present.`,howToVerify:`Re-run the crawl and confirm the effective X-Robots-Tag rules no longer block indexing, including through the equivalent none directive.`,agentHints:{evidenceFields:[`page.xRobotsTag`,`page.responseHeaders`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`robots_blocked`,title:`Blocked by robots.txt`,category:`indexability`,defaultSeverity:`medium`,whyItMatters:`Robots.txt blocking prevents crawlers from fetching the URL. If accidental, search engines and AI systems cannot evaluate the page content.`,howToFix:`Update robots.txt so important public pages are allowed, or leave the block in place only for intentionally private or low-value paths.`,impactIfIgnored:`The page may stay uncrawled, stale, or missing from search and AI retrieval systems.`,howToVerify:`Re-run the crawl and confirm robotsTxt.allowed is true for the URL.`,agentHints:{evidenceFields:[`page.robotsTxt`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`robots_txt_html`,title:`robots.txt returns an HTML page`,category:`indexability`,defaultSeverity:`medium`,whyItMatters:`Crawlers read /robots.txt as plain text rules. An HTML page there, often the home page served for every path, holds no rules and no Sitemap line, so crawlers treat the site as having no robots.txt.`,howToFix:`Serve a plain text /robots.txt with the rules the site needs and a Sitemap line. Check that the catch-all route does not answer before the static file.`,impactIfIgnored:`Rules meant to keep crawlers out of some paths do nothing, and crawlers must find the sitemap another way.`,howToVerify:`Request /robots.txt and confirm a 200 text/plain response with User-agent lines.`,agentHints:{evidenceFields:[`report.ai.robotsTxt`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`sitemap_url_off_host`,title:`Sitemap lists URLs on another host`,category:`indexability`,defaultSeverity:`high`,whyItMatters:`A sitemap may list only URLs on its own host, unless the other host's robots.txt or Search Console vouches for it. Localhost URLs, left by a build that used a development base URL, can never be fetched. Either way, those entries tell search engines nothing about the real pages.`,howToFix:`Build the sitemap with the production URL as the base, so every <loc> uses the same scheme and host as the live site.`,impactIfIgnored:`Search engines find pages only through links, and new or deep pages can take longer to be crawled.`,howToVerify:`Open the sitemap and confirm every <loc> starts with the live site URL, then re-run the crawl.`,agentHints:{evidenceFields:[`report.sitemapDiscovery.roots[].offHost`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`canonicalized_page`,title:`Canonicalized page`,category:`indexability`,defaultSeverity:`low`,whyItMatters:`A canonicalized page tells search engines another URL should receive the ranking signals. That is fine when intentional and risky when accidental.`,howToFix:`If this URL should rank, make the canonical self-referencing. If another URL is preferred, make internal links and sitemap entries point to that preferred URL.`,impactIfIgnored:`The page may be excluded from search in favor of the canonical target.`,howToVerify:`Re-run the crawl and confirm the canonical target matches the intended indexable URL.`,agentHints:{evidenceFields:[`page.canonical`,`page.finalUrl`,`page.indexability`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`duplicate_content`,title:`Duplicate content`,category:`content`,defaultSeverity:`medium`,whyItMatters:`Pages with the same main content force search engines to choose a winner and can split internal signals across duplicates.`,howToFix:`Consolidate duplicate pages with redirects or canonicals, or make each page meaningfully different for its own intent.`,impactIfIgnored:`The wrong URL may rank, similar pages may underperform, and AI systems may cite a less useful duplicate.`,howToVerify:`Re-run the crawl and confirm the duplicate mainContentHash appears on only one URL.`,agentHints:{evidenceFields:[`page.mainContentHash`,`issue.evidence.duplicateCount`,`issue.evidence.sampleUrls`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`query_coverage_missing`,title:`Review top-query text coverage`,category:`content`,defaultSeverity:`low`,whyItMatters:`The top reported query has terms that were not found in the title, description, H1, or retained content sample. Exact terms alone do not prove relevance, and the sample cannot assess every section or useful synonym.`,howToFix:`Read the page and the search results before changing copy. Add or clarify wording only when it makes the page answer the query better. Do not force exact terms into a page that already serves the intent.`,impactIfIgnored:`Use this as a review prompt. It does not predict rankings, clicks, or a need to rewrite the page.`,howToVerify:`Re-run the crawl with the same GSC property and review the query, sampled text, and any deliberate wording changes together.`,agentHints:{evidenceFields:[`page.topQuery`,`issue.evidence.missingTerms`,`issue.evidence.coverage`],suggestedCommands:[`seo crawl <url> --site <site> --json`]}},{id:`image_missing_alt`,title:`Images lack alt attributes`,category:`images`,defaultSeverity:`medium`,whyItMatters:`An image with no alt attribute gives screen readers no declared text alternative. A deliberately empty alt attribute is valid for decorative images and is not included here.`,howToFix:`Add concise alt text to meaningful images that currently have no alt attribute. Keep alt="" on decorative images.`,impactIfIgnored:`People using screen readers may miss the purpose of a meaningful image, and search engines have less image context.`,howToVerify:`Re-run the crawl and confirm imagesMissingAlt is zero. Decorative images can keep an empty alt attribute.`},{id:`image_oversized_candidate`,title:`Oversized image candidates`,category:`images`,defaultSeverity:`low`,whyItMatters:`Very large images can slow pages down, especially when the browser only needs a small rendered size.`,howToFix:`Resize the source image, add responsive srcset sizes, and serve modern compressed formats such as WebP or AVIF where supported.`,impactIfIgnored:`Users may download more image data than needed, which hurts load speed and wastes bandwidth.`,howToVerify:`Re-run the crawl and confirm oversizedImageCandidates is empty, then spot-check the page in a browser performance trace if the image is important.`,agentHints:{evidenceFields:[`page.oversizedImageCandidates`,`issue.evidence.thresholdPx`,`issue.evidence.candidates`],suggestedCommands:[`seo crawl <url> --max-pages 10 --json`]}},{id:`viewport_missing`,title:`Viewport missing`,category:`mobile`,defaultSeverity:`medium`,whyItMatters:`The viewport tag lets mobile browsers render responsive layouts correctly.`,howToFix:'Add `<meta name="viewport" content="width=device-width, initial-scale=1">` to the document head.',impactIfIgnored:`Mobile users may get a zoomed-out desktop page and mobile-first search quality can suffer.`,howToVerify:`Re-run the crawl and confirm hasViewport is true.`},{id:`lang_missing`,title:`Language missing`,category:`international`,defaultSeverity:`low`,whyItMatters:`The html lang attribute helps browsers, screen readers, search engines, and translators understand the page language.`,howToFix:'Set the language on the root html element, for example `<html lang="en">`.',impactIfIgnored:`Accessibility and language targeting signals are weaker.`,howToVerify:`Re-run the crawl and confirm the lang field is populated.`},{id:`hreflang_invalid`,title:`Malformed hreflang values`,category:`international`,defaultSeverity:`low`,whyItMatters:`These hreflang values do not match the basic language or language-region shape. This check does not validate every officially supported language or region code.`,howToFix:`Use a supported language or language-region code such as en, en-gb, fr-ca, or x-default. Check the current Google hreflang documentation before changing a locale set.`,impactIfIgnored:`Search engines may ignore malformed annotations and show a less relevant regional page.`,howToVerify:`Re-run the crawl and confirm no hreflang values are marked malformed. Validate the full locale set against Google documentation.`,agentHints:{evidenceFields:[`page.hreflang`,`issue.evidence.malformed`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`hreflang_duplicate`,title:`Repeated hreflang values`,category:`international`,defaultSeverity:`low`,whyItMatters:`Repeated hreflang declarations make a locale set harder to review. They only conflict when the same language code points to different URLs.`,howToFix:`Keep one hreflang declaration per language code. If repeated codes point to different URLs, decide which page is the intended locale target.`,impactIfIgnored:`Conflicting duplicate targets may be ignored. Identical repeats are usually cleanup work, not a search emergency.`,howToVerify:`Re-run the crawl and confirm each hreflang code appears only once per page.`,agentHints:{evidenceFields:[`page.hreflang`,`issue.evidence.duplicateCodes`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`hreflang_incomplete`,title:`Hreflang missing self reference`,category:`international`,defaultSeverity:`low`,whyItMatters:`A page that declares hreflang should include an alternate that points back to its own final URL. An x-default entry does not replace that self reference.`,howToFix:`Add one hreflang entry that points to this page's final URL. Keep x-default as an additional fallback only where it is useful.`,impactIfIgnored:`Search engines may treat the hreflang set as incomplete and show a less relevant language variant.`,howToVerify:`Re-run the crawl and confirm one hreflang href matches the fetched final URL.`,agentHints:{evidenceFields:[`page.lang`,`page.hreflang`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`hreflang_no_return_link`,title:`Hreflang alternate does not link back`,category:`international`,defaultSeverity:`medium`,whyItMatters:`Google uses an hreflang pair only when both pages name each other. This page names a crawled alternate whose own hreflang set does not point back to this page's URL, so Google ignores the pair.`,howToFix:`Give every page in the language set the same full hreflang list, each entry pointing at the exact final URL of that version. Generate the list from one source so the pages cannot drift apart.`,impactIfIgnored:`Search engines may show the wrong language or country version, or treat the versions as unrelated pages.`,howToVerify:`Re-run the crawl on both URLs and confirm the alternate's hreflang set includes this page's final URL.`,agentHints:{evidenceFields:[`page.hreflang`,`issue.evidence.missingReturnLinks`],suggestedCommands:[`seo crawl --mode list --urls <url>,<url> --json`]}},{id:`hreflang_x_default_missing`,title:`Hreflang set has no x-default`,category:`international`,defaultSeverity:`low`,whyItMatters:`An x-default entry tells search engines which version to show searchers whose language or country matches none of the listed versions. Google recommends it but does not require it.`,howToFix:`Add one x-default entry to every page in the set, pointing at the version for everyone else, such as a language picker or the main language page.`,impactIfIgnored:`Searchers outside the listed languages and countries may get whichever version search engines pick.`,howToVerify:`Re-run the crawl and confirm each page in the set has one x-default entry pointing at the same URL.`,review:{question:`Is there a version that should serve searchers outside the listed languages and countries?`,changeOnlyIf:`One version, or a language picker, is the right default for everyone else.`,ifNotNeeded:`Leave it. A set without x-default still works for the languages it lists.`},agentHints:{evidenceFields:[`page.hreflang`],suggestedCommands:[`seo crawl <url> --json`]}},{id:`structured_data_missing`,title:`No structured data detected`,category:`structured-data`,defaultSeverity:`low`,whyItMatters:`The crawler detected no JSON-LD, microdata, or RDFa on this page. Structured data is optional and page-type dependent, so this is an observation, not a defect.`,howToFix:`Add structured data only where a schema type genuinely describes the page, for example an article page describing its article. Validate the markup after adding it, and leave pages without a fitting schema type unmarked.`,impactIfIgnored:`Consumers that read structured data get no machine-readable description of this page. Many page types work fine without any markup.`,howToVerify:`Re-run the crawl and confirm structuredDataFormats lists the added format, then validate the page with a structured data tester.`,review:{question:`Does a specific structured data type accurately describe the visible content on this page?`,changeOnlyIf:`Add markup only when a specific schema type fits the page and every claimed property is supported by its visible content.`,ifNotNeeded:`Leave the page unmarked and record that no suitable schema type was confirmed.`,doNot:[`Do not add Organization or another generic schema type only to clear this finding.`,`Do not copy site-wide markup onto unrelated page types.`]},agentHints:{evidenceFields:[`page.structuredDataFormats`,`page.schemaTypes`,`issue.evidence.structuredDataFormats`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`jsonld_invalid`,title:`Invalid JSON-LD`,category:`structured-data`,defaultSeverity:`medium`,whyItMatters:`Broken JSON-LD can make structured data unreadable even when the right schema was intended.`,howToFix:`Fix the JSON syntax in each application/ld+json script. Validate quotes, commas, braces, and any server-rendered values inserted into the block.`,impactIfIgnored:`Consumers cannot reliably read the invalid block, and Google cannot use unreadable markup for supported Search features.`,howToVerify:`Re-run the crawl and confirm invalidJsonLdCount is zero, then validate the page with a structured data tester.`,agentHints:{evidenceFields:[`page.invalidJsonLdSamples`,`issue.evidence.invalidJsonLdSamples`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`rich_result_required_fields_missing`,title:`Required rich-result properties are missing`,category:`structured-data`,defaultSeverity:`medium`,whyItMatters:`Schema.org vocabulary and valid JSON syntax do not make markup eligible for a Google rich result when documented required properties are absent.`,howToFix:`Add the missing properties only when they accurately represent visible page content. Follow the linked Google feature documentation and validate the result.`,impactIfIgnored:`Google can understand some of the markup while still treating the item as ineligible for that enhanced Search feature.`,howToVerify:`Re-run the crawl, review googleRichResults, and confirm no supported item reports missing-required-properties. Then use Google’s Rich Results Test.`,agentHints:{evidenceFields:[`page.googleRichResults`,`issue.evidence.assessments`],suggestedCommands:[`seo crawl <url> --max-pages 1 --json`]}},{id:`og_title_missing`,title:`Open Graph title missing`,category:`social`,defaultSeverity:`low`,whyItMatters:`Open Graph tags control how pages appear in social feeds, chat previews, and many sharing surfaces.`,howToFix:`Add an og:title that matches the page title or a share-friendly version of it.`,impactIfIgnored:`Shared links can look generic, reducing clicks from social and messaging apps.`,howToVerify:`Re-run the crawl and confirm openGraphTitle is present.`},{id:`og_description_missing`,title:`og:description not set`,category:`social`,defaultSeverity:`low`,whyItMatters:`The og:description tag is often the short pitch shown when a page is shared in chat, Slack, social feeds, and link previews. Other og: tags can be present while this one is not set.`,howToFix:`Add an og:description that briefly explains why the page is worth opening.`,impactIfIgnored:`Shared links can appear vague or empty, which reduces clicks from discovery surfaces.`,howToVerify:`Re-run the crawl and confirm openGraphDescription is present.`},{id:`og_image_missing`,title:`Open Graph image missing`,category:`social`,defaultSeverity:`low`,whyItMatters:`An Open Graph image helps shared links stand out and makes previews feel trustworthy and complete.`,howToFix:`Add an og:image URL with a representative image that crawlers can fetch over HTTPS.`,impactIfIgnored:`Shared links may render without a visual preview, reducing click appeal.`,howToVerify:`Re-run the crawl and confirm openGraphImage is present.`},{id:`twitter_card_missing`,title:`No Twitter card declared`,category:`social`,defaultSeverity:`low`,whyItMatters:`A Twitter card tells X which preview format to use. X can sometimes fall back to Open Graph metadata, so this is a sharing observation, not a search issue.`,howToFix:`Add twitter:card and matching metadata only when you need a specific X preview. Keep Open Graph metadata accurate either way.`,impactIfIgnored:`X may use fallback metadata or a simple link preview. Organic rankings are not affected.`,howToVerify:`Re-run the crawl and confirm twitterCard is present if a specific X preview is required.`},{id:`ai_search_bot_blocked`,title:`robots.txt blocks AI search bots`,category:`agents`,defaultSeverity:`medium`,whyItMatters:`AI search bots fetch pages to answer a person's question and cite the source. A blocked bot cannot read the site, so its answers cannot quote or link to it. Training bots are a separate choice and are listed apart.`,howToFix:`Allow the AI search and user bots in robots.txt if the site should appear in AI answers. Block training bots separately if the person wants that.`,impactIfIgnored:`ChatGPT, Claude, Perplexity and similar tools can leave the site out of answers and citations.`,howToVerify:`Re-run the crawl and confirm the search bots in ai.robotsTxt.botAccess show allowed: true.`,review:{question:`Is the site meant to be left out of AI search answers?`,changeOnlyIf:`Change robots.txt when the person wants the site to appear in AI answers.`,ifNotNeeded:`Record that blocking AI search bots is a deliberate choice for this site.`},agentHints:{evidenceFields:[`report.ai.robotsTxt.botAccess`]}},{id:`llms_txt_missing`,title:`No llms.txt`,category:`agents`,defaultSeverity:`low`,whyItMatters:`llms.txt gives agents a short summary of the site and links to its main pages, ideally their Markdown copies. Search engines do not use it for ranking.`,howToFix:`Publish /llms.txt as plain text with a one-line summary and sections of links to the main pages.`,impactIfIgnored:`Agents must find the main pages by crawling, which costs them more requests and tokens.`,howToVerify:`Request /llms.txt and confirm a 200 plain text response.`,review:{question:`Should agents get a reading list for this site?`,changeOnlyIf:`Add it when agents are expected to read or use the site.`,ifNotNeeded:`Record that the site has no llms.txt by choice.`},agentHints:{evidenceFields:[`report.ai.llmsTxt`]}},{id:`llms_txt_broken_link`,title:`llms.txt links to a page that does not load`,category:`agents`,defaultSeverity:`low`,whyItMatters:`An agent that follows a link in llms.txt and gets an error loses its reading list entry.`,howToFix:`Update or remove each broken link in llms.txt, or restore the page it points to.`,impactIfIgnored:`Agents waste requests and can miss the page.`,howToVerify:`Re-run the crawl and confirm ai.llmsTxt.links.broken is empty.`,agentHints:{evidenceFields:[`report.ai.llmsTxt.links`]}},{id:`markdown_missing`,title:`No Markdown copy of the pages`,category:`agents`,defaultSeverity:`low`,whyItMatters:`A Markdown copy gives agents the page content without layout, scripts or navigation, at a fraction of the tokens. Neither a request with Accept: text/markdown nor a rel="alternate" link returned one. Search engines do not use it for ranking.`,howToFix:`Serve a Markdown copy of each page, linked from the page with <link rel="alternate" type="text/markdown">, and return it for Accept: text/markdown with Vary: Accept.`,impactIfIgnored:`Agents read the full HTML, which costs more tokens and can include layout text.`,howToVerify:`Request a page with Accept: text/markdown and confirm a text/markdown response.`,review:{question:`Should agents get a Markdown copy of the pages?`,changeOnlyIf:`Add it when agents are expected to read the site.`,ifNotNeeded:`Record that the site serves HTML only by choice.`},agentHints:{evidenceFields:[`report.ai.markdownNegotiation`,`report.ai.markdownCopies`]}},{id:`markdown_alternate_missing`,title:`Page has no link to its Markdown copy`,category:`agents`,defaultSeverity:`low`,whyItMatters:`Other pages on the site link to a Markdown copy, but this one does not, so agents cannot find a copy for it.`,howToFix:`Add <link rel="alternate" type="text/markdown" href="..."> to the page head, pointing at its Markdown copy.`,impactIfIgnored:`Agents read the full HTML for this page.`,howToVerify:`Re-run the crawl and confirm the page lists a Markdown alternate.`,agentHints:{evidenceFields:[`page.markdownAlternates`,`report.ai.markdownCopies`]}},{id:`markdown_alternate_on_private_page`,title:`Signed-in page links to a Markdown copy`,category:`agents`,defaultSeverity:`medium`,whyItMatters:`Signed-in pages should have no Markdown copy. This page needs a sign-in, yet it links to one. A copy can show agents content that a signed-out visitor cannot see, or fail and waste their requests.`,howToFix:`Remove the rel="alternate" Markdown link, the Link header and any Markdown copy for signed-in routes. Public pages keep theirs, including noindex pages such as privacy and terms.`,impactIfIgnored:`Agents can request a copy that fails, or read content that was meant to stay behind a sign-in.`,howToVerify:`Re-run the crawl and confirm the page no longer lists a Markdown alternate.`,agentHints:{evidenceFields:[`page.markdownAlternates`,`report.ai.markdownCopies.broken`]}},{id:`markdown_copy_broken`,title:`Markdown copy does not load`,category:`agents`,defaultSeverity:`medium`,whyItMatters:`The page links to a Markdown copy that returns an error or HTML, so an agent that follows the link gets nothing useful. If the page needs a sign-in, remove the link instead.`,howToFix:`Make the linked URL return the page as text/markdown, or fix the link.`,impactIfIgnored:`Agents get an error or the HTML page instead of the copy.`,howToVerify:`Request the Markdown URL and confirm a 200 text/markdown response.`,agentHints:{evidenceFields:[`report.ai.markdownCopies.broken`]}}],Kn={title_too_wide:`review`,h1_multiple:`review`,structured_data_missing:`review`,canonical_missing:`review`,canonical_multiple:`review`,canonical_streamed_in_body:`review`,canonical_mismatch:`review`,canonical_non_absolute:`review`,canonicalized_page:`review`,noindex:`review`,nofollow:`review`,x_robots_noindex:`review`,robots_blocked:`review`,crawler_access_blocked:`review`,soft_authentication_gate:`review`,client_rendered_content:`review`,near_empty_content:`review`,orphan_page:`review`,redirected_url:`review`,slow_response:`review`,image_oversized_candidate:`review`,hsts_missing:`review`,og_title_missing:`review`,og_description_missing:`review`,og_image_missing:`review`,twitter_card_missing:`review`,ai_search_bot_blocked:`review`,llms_txt_missing:`review`,markdown_missing:`review`,hreflang_x_default_missing:`review`},qn=new Map(Gn.map(e=>[e.id,{...e,recommendation:Kn[e.id]??`fix`}]));function Jn(){return[...qn.values()]}function Yn(e){return qn.get(e)}function Xn(e){return Yn(e)?.recommendation??`fix`}const Zn=/* @__PURE__ */ new Set([`actions`,`findings`,`fixes`,`issues`,`nextSteps`,`priorities`,`queue`,`recommendations`,`reviewObservations`,`topActions`,`topFixes`,`templateRecommendations`]),Qn=/* @__PURE__ */ new Set([`inventories`,`markdown`,`outputBudget`,`presentation`]);function $n(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}function er(e){let t=$n(e),n=$n(t?.counts);return t?.schemaVersion===1&&t.scope===`returned-report`&&typeof n?.total==`number`&&typeof n.returned==`number`&&Array.isArray(t.items)&&t.items.every(e=>{let t=$n(e);if(!tr(t?.id)||t?.status!==`open`||!tr(t.title)||!tr(t.sourcePath)||!Array.isArray(t.allowedOutcomes))return!1;if(t.type===`fix`)return!!tr($n(t.fix)?.instruction);if(t.type===`review`){let e=$n(t.review);return e?!!(tr(e.question)&&tr(e.changeOnlyIf)&&tr(e.ifConfirmed)&&tr(e.ifNotNeeded)&&Array.isArray(e.doNot)):!1}return!1})}function tr(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function nr(e){return Ct(`sha256`).update(e).digest(`hex`).slice(0,12)}function rr(e,t){let n=[...e],r=[...t];for(let e=0;e<Math.min(n.length,r.length);e+=1){let t=(n[e]?.codePointAt(0)??0)-(r[e]?.codePointAt(0)??0);if(t)return t}return n.length-r.length}function ir(e,t,n){for(let t of[`ruleId`,`checkId`,`findingId`,`actionId`,`id`]){let n=tr(e[t]);if(n)return n}return`action-${nr(`${t}|${n}`)}`}function ar(e,t){return e.endsWith(`.reviewObservations`)||t.kind===`review`||t.recommendation===`review`||t.requiresIntentReview===!0?`review`:`fix`}function or(e,t){let n=$n(e.verification),r=tr(n?.expected??e.howToVerify??t);if(!r)return;let i=tr(n?.command);return{...i?{command:i}:{},expected:r}}function sr(e){return Array.isArray(e)?e.flatMap(e=>tr(e)?[tr(e)]:[]):[]}function cr(e,t){let n=sr(e.sampleUrls),r=$n(e.affectedUrlsReport),i=$n(r?.params),a=r?.id===`affected-urls`?tr(i?.reportId):void 0,o=r?.id===`affected-urls`?tr(i?.ruleId):void 0;if(!n.length&&!a)return;let s=t??n.length;return{total:s,returned:n.length,complete:n.length>=s,items:n,...a&&o?{report:{id:`affected-urls`,params:{reportId:a,ruleId:o}}}:{}}}function lr(e,t,n){let r=$n(e.review),i=$n(e.evidence),a=tr(e.ruleId??i?.ruleId),o=(a?Yn(a):void 0)?.review;return{question:tr(r?.question)??o?.question??`Does the retained evidence and confirmed intent show that "${t}" needs a change?`,changeOnlyIf:tr(r?.changeOnlyIf)??o?.changeOnlyIf??`Make a change only when the retained evidence and required intent support it.`,ifConfirmed:tr(r?.ifConfirmed)??n,ifNotNeeded:tr(r?.ifNotNeeded)??o?.ifNotNeeded??`Record no change and cite the evidence or confirmed intent that makes a change unnecessary.`,doNot:sr(r?.doNot).length?sr(r?.doNot):[...o?.doNot??[]]}}function ur(e){let t={...$n(e.evidence)};for(let n of[`target`,`url`,`count`,`sampleUrls`,`whyThisRanks`,`score`,`scoreFactors`])e[n]!==void 0&&(t[n]=e[n]);return Object.keys(t).length?t:void 0}function dr(e,t,n,r){if(typeof e==`string`){let i=tr(e);if(!i)return;let a={id:`action-${nr(`${r.reportId??``}|${t}|${i}`)}`,status:`open`,title:i,sourcePath:`${t}[${n}]`,...r.verify?{verification:{expected:r.verify}}:{},rank:n};return t.endsWith(`.reviewObservations`)?{...a,type:`review`,review:lr({},i,i),allowedOutcomes:[`changed`,`no-change`,`deferred`]}:{...a,type:`fix`,fix:{instruction:i},allowedOutcomes:[`fixed`,`deferred`,`not-needed`]}}let i=$n(e);if(!i)return;let a=tr(i.action)??tr(i.howToFix)??(i.recommendation===`fix`||i.recommendation===`review`?void 0:tr(i.recommendation))??tr(i.nextStep),o=tr(i.title)??tr(i.headline)??tr(i.name)??a;if(!a||!o)return;let s=[`high`,`medium`,`low`].includes(String(i.confidence))?i.confidence:void 0,c=i.affectedCount??i.count,l=typeof c==`number`?c:void 0,u=or(i,r.verify),d=ur(i),f=ar(t,i),p=cr(i,l),m={id:ir(i,`${r.reportId??``}|${t}`,a),status:`open`,title:o,...s?{confidence:s}:{},...tr(i.severity)?{severity:tr(i.severity)}:{},...typeof l==`number`&&Number.isFinite(l)?{affectedCount:l}:{},...p?{affectedUrls:p}:{},sourcePath:`${t}[${n}]`,...d?{evidence:d}:{},...u?{verification:u}:{},rank:n};return f===`review`?{...m,type:f,review:lr(i,o,a),allowedOutcomes:[`changed`,`no-change`,`deferred`]}:{...m,type:f,fix:{instruction:a},allowedOutcomes:[`fixed`,`deferred`,`not-needed`]}}function fr(e,t){return{...t,...e,type:e.type===`review`||t.type===`review`?`review`:`fix`,affectedCount:e.affectedCount??t.affectedCount,evidence:e.evidence||t.evidence?{...t.evidence,...e.evidence}:void 0,verification:e.verification??t.verification,...e.type===`review`||t.type===`review`?{review:e.type===`review`?e.review:t.review,allowedOutcomes:[`changed`,`no-change`,`deferred`]}:{fix:e.type===`fix`?e.fix:t.fix,allowedOutcomes:[`fixed`,`deferred`,`not-needed`]}}}function pr(e,t,n){let r=$n(e);if(!r||!Array.isArray(r.rows))return;let i=typeof(r.totalPages??r.totalItems)==`number`?Number(r.totalPages??r.totalItems):r.rows.length,a=r.rows.map((e,r)=>{let i=$n(e)??{value:e},a=tr(i.id)??tr(i.url)??tr(i.path)??`${t}[${r}]`;return{...i,id:`inventory-item-${nr(`${n??``}|${t}|${a}`)}`,decisionStatus:`open`}}),o=a.length>0,s=typeof r.page==`number`?r.page:1,c=typeof r.pageCount==`number`?r.pageCount:void 0,l=typeof r.nextPage==`number`?r.nextPage:null;return{id:`inventory-${nr(`${n??``}|${t}`)}`,sourcePath:t,title:`Content migration inventory`,totalItems:i,returnedItems:a.length,complete:r.capped===!1&&a.length>=i,...r.criteria===void 0?{}:{criteria:r.criteria},...tr(r.note)?{note:tr(r.note)}:{},...c===void 0?{}:{pagination:{page:s,pageCount:c,nextPage:l}},completion:{state:o?`pending`:`not-required`,instruction:o?`Return one decision for every returned row, with evidence; the decision count must equal returnedItems. A recommendation can be explicit while implementation is deferred for owner approval. Do not use one blanket policy or redirect unrelated URLs to a generic hub.${c&&c>1?` Fetch and account for every inventory page before treating it as complete.`:``}`:`No returned inventory row needs a disposition.`},items:a}}function eee(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=[],a=0;function o(e,s=``,c=0){let l=$n(e);if(!(!l||c>6))for(let[e,u]of Object.entries(l).sort(([e],[t])=>rr(e,t))){if(!s&&e===`findings`&&er(u)||Qn.has(e))continue;let l=s?`${s}.${e}`:e;if(e===`pageInventory`){let e=pr(u,l,t.reportId);e&&i.push(e)}Zn.has(e)&&Array.isArray(u)&&(!t.preferRootActions||l===`actions`)&&(r.add(l),u.forEach((e,r)=>{let i=dr(e,l,r,t);if(!i)return;i.rank=a++;let o=n.get(i.id);n.set(i.id,o?fr(o,i):i)})),o(u,l,c+1)}}return o(e),{findings:[...n.values()].sort((e,t)=>e.rank-t.rank||rr(e.id,t.id)).map(({rank:e,...t})=>t),sourcePaths:[...r].sort(rr),inventories:i.sort((e,t)=>rr(e.sourcePath,t.sourcePath))}}function tee(e,t,n){return n===`partial`||t.some(e=>!e.complete)?{state:`partial`,detail:`At least one source inventory is capped or partial. Do not treat missing rows as zero.`}:n===`complete`?{state:`complete`,detail:`Every finding in the declared report scope is represented.`}:{state:`unknown`,detail:e.length?`The findings include every recognised item returned by this report; source acquisition completeness is not declared.`:`This report returned no recognised actionable collection.`}}function nee(e,t={}){let n=eee(e,t),r=n.findings.filter(e=>e.type===`fix`).length,i=n.findings.length>0;return{findings:{schemaVersion:1,scope:`returned-report`,coverage:tee(n.sourcePaths,n.inventories,t.coverage),counts:{total:n.findings.length,returned:n.findings.length,fixes:r,reviews:n.findings.length-r,open:n.findings.length},completion:{state:i?`pending`:`not-required`,instruction:i?`Before finishing, return one allowed outcome and reason for every open item; the outcome count must equal counts.returned. A review is a decision task, not an instruction to change the site. Do not silently drop findings.`:`No returned finding needs completion accounting.`},verification:{requiredAfterChanges:!0,instruction:`After edits, run each changed item's verification and rerun the originating report. A code change alone does not close a finding.`,...t.verify?{reportCheck:t.verify}:{}},sourcePaths:n.sourcePaths,items:n.findings},inventories:n.inventories}}function mr(e,t={}){if(er(e.findings))return e;let n=nee(e,t),r=e.findings,i=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`findings`&&e!==`inventories`));return{findings:n.findings,...r===void 0?{}:{reportFindings:r},...n.inventories.length?{inventories:n.inventories}:{},...i}}function hr(e,t={}){let n=mr(e,t),r=$n(e.output),i=Object.fromEntries(Object.entries({caveats:e.caveats??r?.caveats,warnings:e.warnings??r?.warnings,provenance:e.provenance??r?.provenance,selection:e.selection??r?.selection,totals:e.totals??r?.totals,skippedSections:e.skippedSections??r?.skippedSections,partialReasons:e.partialReasons??r?.partialReasons}).filter(([,e])=>e!==void 0));return{view:`actions`,report:Object.fromEntries(Object.entries({id:t.reportId,workflow:e.workflow,site:e.site,generatedAt:e.generatedAt,summary:e.summary,dataStatus:e.dataStatus??r?.dataStatus}).filter(([,e])=>e!==void 0)),findings:n.findings,...n.inventories?{inventories:n.inventories}:{},...Object.keys(i).length?{retainedEvidence:i}:{}}}const gr=F.object({property:F.string().trim().min(1),displayName:F.string().optional(),propertyType:F.string().optional(),parent:F.string().optional()}).strip(),_r=F.object({accountSummaries:F.array(F.object({account:F.string().trim().min(1),displayName:F.string().optional(),propertySummaries:F.array(gr).optional()}).strip()).max(200).optional(),nextPageToken:F.string().optional()}).strip();function vr(e){let t=_r.safeParse(e);if(!t.success)throw Error(`Google Analytics account summary response was invalid.`);return{accountSummaries:(t.data.accountSummaries??[]).map(e=>({...e,propertySummaries:e.propertySummaries??[]})),nextPageToken:t.data.nextPageToken||void 0}}async function yr(e){let t=[],n=/* @__PURE__ */ new Set,r;for(let i=0;i<20;i+=1){let i=vr(await e(r));if(t.push(...i.accountSummaries),!i.nextPageToken)return t;if(n.has(i.nextPageToken))throw Error(`Google Analytics account summary pagination repeated a page token.`);n.add(i.nextPageToken),r=i.nextPageToken}throw Error(`Google Analytics account summary discovery exceeded 20 pages.`)}var br=class extends P{status;constructor(e,t,n){super(e,t),this.status=n}};const xr=6e4;async function Sr(e,t,n,r){let i=new AbortController,a=()=>i.abort(n?.reason);n?.aborted?a():n?.addEventListener(`abort`,a,{once:!0});let o,s=new Promise((n,r)=>{o=setTimeout(()=>{let n=new P(`PROVIDER_UNAVAILABLE`,`${e} did not answer within ${t/1e3} seconds, so the request was stopped. Try again later.`);r(n),i.abort(n)},t)});try{return await Promise.race([r(i.signal),s])}finally{clearTimeout(o),n?.removeEventListener(`abort`,a)}}function Cr(e){return async(t,n)=>fetch(t,{...n,headers:{...n?.headers,authorization:`Bearer ${await e()}`,"content-type":`application/json`}})}async function wr(e,t,n,r){let i=(await e.text().catch(()=>``)).slice(0,300),a=e.status,o=n?`${t} for ${n}`:t;if(a===400){let e=i;try{e=JSON.parse(i).error?.message??i}catch{}return new br(`INVALID_INPUT`,`${t} rejected the request: ${e}`.trim(),a)}return a===401?new br(`AUTH_EXPIRED`,`Google rejected the sign-in. ${r.signIn}`,a):a===403?new br(`ACCESS_DENIED`,`Google denied access to ${o}. Check the Google account, its access to this property, and the granted scopes. ${i}`.trim(),a):a===404?new br(`PROPERTY_NOT_FOUND`,`Google could not find ${o}. Check the property and account access.`,a):a===429?new br(`RATE_LIMITED`,`Google quota reached for ${t}. Wait and try again. ${i}`.trim(),a):new br(`PROVIDER_UNAVAILABLE`,`${t} answered ${a}. ${i}`.trim(),a)}async function Tr(e,t,n){return Sr(n.subject?`${n.label} for ${n.subject}`:n.label,n.timeoutMs??3e4,void 0,async r=>{let i=await e(t,{method:n.body===void 0?`GET`:`POST`,body:n.body===void 0?void 0:JSON.stringify(n.body),signal:r});if(!i.ok)throw await wr(i,n.label,n.subject,n);return ct(i,n.label,{maxBytes:n.maxBytes})})}const Er=`https://www.googleapis.com/webmasters/v3`,Dr=25e3;async function Or(e,t,n,r){let i=[],{maxRows:a,...o}=n,s=a??n.rowLimit,c=`${Er}/sites/${encodeURIComponent(t)}/searchAnalytics/query`,l=0,u=0;for(;;){let n=typeof s==`number`?s-i.length:void 0;if(typeof n==`number`&&n<=0)break;let a=Math.min(o.rowLimit??Dr,n??Dr,Dr),d=await Tr(e,c,{...r,label:`Search Console`,subject:t,body:{...o,rowLimit:a,startRow:l,dataState:o.dataState??`final`,dimensions:o.dimensions??[`query`,`page`],type:o.type??`web`,aggregationType:o.aggregationType??`auto`}});u+=1;let f=d.rows??[];if(i.push(...f),f.length<a||typeof s==`number`&&i.length>=s)break;l+=a}return{rows:i,calls:u,rowsFetched:i.length}}async function kr(e,t){return(await Tr(e,`${Er}/sites`,{...t,label:`Search Console`})).siteEntry??[]}async function Ar(e,t,n,r){return Tr(e,`https://searchconsole.googleapis.com/v1/urlInspection/index:inspect`,{...r,label:`URL Inspection`,subject:n,timeoutMs:xr,body:{siteUrl:t,inspectionUrl:n,...r.languageCode?{languageCode:r.languageCode}:{}}})}async function jr(e,t){return yr(async n=>{let r=new URL(`https://analyticsadmin.googleapis.com/v1beta/accountSummaries`);return r.searchParams.set(`pageSize`,`200`),n&&r.searchParams.set(`pageToken`,n),Tr(e,r.toString(),{...t,label:`Google Analytics accounts`,maxBytes:10485760})})}async function Mr(e,t,n){return(await Tr(e,`https://analyticsadmin.googleapis.com/v1beta/properties/${t}/dataStreams?pageSize=200`,{...n,label:`Google Analytics data streams`,subject:`property ${t}`,maxBytes:1048576})).dataStreams??[]}async function Nr(e,t,n,r){if(!/^\d+$/.test(t))throw new P(`INVALID_INPUT`,`The Google Analytics property must be its numeric id.`);return Tr(e,`https://analyticsdata.googleapis.com/v1beta/properties/${t}:runReport`,{...r,label:`Google Analytics`,subject:`property ${t}`,body:n})}function Pr(e,t){return async(n,r={})=>{let i=new URL(`https://ssl.bing.com/webmaster/api.svc/json/${n}`);for(let[e,t]of Object.entries(r))i.searchParams.set(e,t);let a={accept:`application/json`};`apiKey`in e?i.searchParams.set(`apikey`,e.apiKey):a.authorization=`Bearer ${await e.accessToken()}`;let o;try{o=await fetch(i,{headers:a,signal:AbortSignal.timeout(3e4)})}catch(e){throw new P(`OPTIONAL_PROVIDER_UNAVAILABLE`,`Bing Webmaster did not respond: ${e instanceof Error?e.message:String(e)}`)}if(!o.ok){let e=(await o.text().catch(()=>``)).slice(0,200);throw o.status===401||/invalidapikey/i.test(e)?new P(`AUTH_REQUIRED`,`Bing Webmaster rejected the sign-in. ${t.signIn}`):o.status===403||/notauthorized/i.test(e)?new P(`ACCESS_DENIED`,`Bing Webmaster denied access to this site. It must be verified in the connected Bing account.`):/ThrottleIP/i.test(e)?new P(`RATE_LIMITED`,`Bing Webmaster is blocking requests from this network (ThrottleIP). Run the same report with the CLI on your own machine, where Bing answers.`):o.status===429||/throttle/i.test(e)?new P(`RATE_LIMITED`,`Bing Webmaster is limiting requests. Try again in a few minutes.`):new P(`OPTIONAL_PROVIDER_UNAVAILABLE`,`Bing Webmaster answered ${o.status}. ${e}`.trim())}return(await ct(o,`Bing Webmaster`,{maxBytes:8e6})).d}}function Fr(e){if(typeof e!=`string`)return null;let t=/^\/Date\((-?\d+)(?:[+-]\d{4})?\)\/$/.exec(e),n=t?new Date(Number(t[1])):new Date(e);return Number.isNaN(n.getTime())?null:n.toISOString().slice(0,10)}const Ir=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0?e:null;function Lr(e,t){if(!Array.isArray(e))throw new P(`OPTIONAL_PROVIDER_UNAVAILABLE`,`Bing Webmaster returned an invalid ${t}.`);return e.filter(e=>!!e&&typeof e==`object`)}async function Rr(e){return Lr(await e(`GetUserSites`),`site list`).filter(e=>typeof e.Url==`string`).map(e=>({url:e.Url,verified:e.IsVerified===!0})).sort((e,t)=>e.url.localeCompare(t.url,`en`))}async function zr(e,t){let n=[],r=0;for(let i of Lr(await e(`GetRankAndTrafficStats`,{siteUrl:t}),`traffic list`)){let e=Fr(i.Date),t=Ir(i.Clicks),a=Ir(i.Impressions);!e||t===null||a===null?r+=1:n.push({date:e,clicks:t,impressions:a})}return n.sort((e,t)=>e.date.localeCompare(t.date,`en`)),{rows:n,invalidRows:r}}async function Br(e,t,n){let r=[],i=0;for(let a of Lr(await e(t,n),`row list`)){let e=Fr(a.Date),t=typeof a.Query==`string`?a.Query.trim():``,n=Ir(a.Clicks),o=Ir(a.Impressions),s=Ir(a.AvgImpressionPosition);!e||!t||n===null||o===null?i+=1:r.push({date:e,key:t,clicks:n,impressions:o,position:s})}return r.sort((e,t)=>e.date.localeCompare(t.date,`en`)||e.key.localeCompare(t.key,`en`)),{rows:r,invalidRows:i}}const Vr=(e,t)=>Br(e,`GetQueryStats`,{siteUrl:t}),Hr=(e,t)=>Br(e,`GetPageStats`,{siteUrl:t});function Ur(e,t){let n=e=>{try{return new URL(e.includes(`://`)?e:`https://${e.replace(/^sc-domain:/,``)}`).hostname.replace(/^www\./,``)}catch{return null}},r=n(t);return r?e.filter(e=>n(e.url)===r).sort((e,t)=>Number(t.verified)-Number(e.verified)||Number(t.url.startsWith(`https://`))-Number(e.url.startsWith(`https://`))||e.url.localeCompare(t.url,`en`))[0]??null:null}async function Wr(e,t){return(await kr(e,{signIn:t})).filter(e=>e.permissionLevel!==`siteUnverifiedUser`).map(e=>({siteUrl:e.siteUrl,permissionLevel:e.permissionLevel??``})).sort((e,t)=>e.siteUrl.localeCompare(t.siteUrl))}const Gr=e=>{try{return new URL(e.includes(`://`)?e:`https://${e.replace(/^sc-domain:/,``)}`).hostname.replace(/^www\./,``)}catch{return e}};async function Kr(e){let t=e.accounts.length>1,[n,r]=await Promise.all([Promise.all(e.accounts.map(async t=>{let[n,r]=await Promise.all([Wr(t.google,e.signIn).catch(e=>e instanceof Error?e:Error(String(e))),jr(t.google,{signIn:e.signIn}).catch(()=>null)]);return{email:t.email,properties:n,analytics:r}})),e.bing?Rr(e.bing).catch(e=>e instanceof Error?e:Error(String(e))):Promise.resolve(null)]),i=Array.isArray(r)?r.filter(e=>e.verified):[],a=new Map(i.map(e=>[Gr(e.url),e])),o=n.flatMap(e=>e.properties instanceof Error?[]:e.properties.map(n=>({...n,...t?{account:e.email??``}:{},...Array.isArray(r)?{bing:a.get(Gr(n.siteUrl))?.url??``}:{}}))),s=new Set(o.map(e=>Gr(e.siteUrl))),c=i.filter(e=>!s.has(Gr(e.url))),l=n.filter(e=>e.properties instanceof Error),u=n.flatMap(e=>(e.analytics??[]).flatMap(n=>n.propertySummaries.map(r=>({property:r.property.replace(`properties/`,``),name:r.displayName??``,account:n.displayName??``,...t?{signIn:e.email??``}:{}})))),d=[[`dataforseo`,`x-dataforseo-login`],[`ahrefs`,`x-ahrefs-key`]].filter(([,t])=>e.keys.get(t??``)).map(([e])=>e),f=[`siteUrl`,`permissionLevel`,...t?[`account`]:[],...Array.isArray(r)?[`bing`]:[]];return{text:[t?`Google accounts: ${e.accounts.map(e=>e.email).join(`, `)}.`:null,`Search Console properties (${o.length}):`,o.length?se(o,f,null):`None. These Google sign-ins have no Search Console access, so the reports cannot run.`,...l.map(e=>`${e.email??`Google`}: could not list properties. ${e.properties.message}`),u.length?`Google Analytics properties (${u.length}):\n${se(u,[`property`,`name`,`account`,...t?[`signIn`]:[]],null)}`:`Google Analytics: no properties readable with these sign-ins.`,e.bing===void 0?null:r===null?`Bing Webmaster: not connected.`:r instanceof Error?`Bing Webmaster: could not list sites. ${r.message}`:c.length?`Bing Webmaster sites with no Search Console property here (${c.length}): ${c.map(e=>e.url).join(`, `)}.`:`Bing Webmaster: ${i.length} verified sites; the bing column shows each one.`,`Research keys: ${d.length?d.join(`, `):`none`}.`,e.clicky?.length?`Clicky sites (seo_data with source "clicky"): ${e.clicky.join(`, `)}.`:null,e.simpleAnalytics?`Simple Analytics: API key saved; seo_data with source "simple_analytics" and the site's domain.`:null,`Add a Google account${e.bing===void 0?``:`, Bing`} or a key: ${e.connect}`,`Next: seo_report with a site.`].filter(Boolean).join(`
|
|
4
4
|
|
|
5
5
|
`),data:{searchConsole:o,googleAnalytics:u,bing:Array.isArray(r)?i:null,research:d,clicky:e.clicky??[],simpleAnalytics:!!e.simpleAnalytics}}}const qr={siteOwner:0,siteFullUser:1,siteRestrictedUser:2};function Jr(e){if(e.length===0)return null;let t=e[0];if(e.length===1&&t)return t;let n,r=()=>(n??=Promise.all(e.map(async e=>({call:e,sites:await e(`GetUserSites`).then(e=>Array.isArray(e)?e:[]).catch(()=>[])}))),n);return async(e,n={})=>{let i=await r();return e===`GetUserSites`?i.flatMap(e=>e.sites):(i.find(e=>e.sites.some(e=>e.IsVerified===!0&&e.Url===n.siteUrl))?.call??t)(e,n)}}var Yr=class{hint;google;bing;sites=/* @__PURE__ */ new Map;owners;constructor(e,t){this.hint=t,this.google=e.google.map(e=>({email:e.email,google:Cr(e.token)})),this.bing=Jr(e.bing)}accounts(){return this.google.map(e=>({email:e.email,google:e.google}))}sitesOf(e){let t=this.sites.get(e);return t||(t=Wr(e.google,this.hint.signIn),this.sites.set(e,t)),t}ownerMap(){return this.owners??=(async()=>{let e=await Promise.all(this.google.map(async e=>({linked:e,sites:await this.sitesOf(e).catch(e=>{if(this.google.length===1)throw e;return[]})}))),t=/* @__PURE__ */ new Map;for(let{linked:n,sites:r}of e)for(let e of r){let r=qr[e.permissionLevel]??3,i=t.get(e.siteUrl);(!i||r<i.rank)&&t.set(e.siteUrl,{linked:n,rank:r})}return new Map([...t].map(([e,{linked:t}])=>[e,t]))})(),this.owners}async properties(){return[...(await this.ownerMap()).keys()].sort()}async resolve(e){if(this.google.length===0)throw new a(`NOT_CONNECTED`,`No Google account is connected. ${this.hint.signIn}`);let t=await this.properties(),n=E(t,e);if(n)return n;throw new a(`NO_ACCESS`,`None of the connected Google accounts (${this.google.map(e=>e.email).join(`, `)}) has a Search Console property for ${e}. ${v(t,`they`)} ${this.hint.addGoogle}`)}async owner(e){let t=(await this.ownerMap()).get(await this.resolve(e));if(!t)throw new a(`NO_ACCESS`,`No access to ${e}.`);return t}searchAnalytics(){return async(e,t)=>Or((await this.owner(e)).google,e,{...t,maxRows:t.maxRows??t.rowLimit??1e5},{signIn:this.hint.signIn})}async inspect(e,t){return Ar((await this.owner(e)).google,e,t,{signIn:this.hint.signIn,languageCode:`en-US`})}};let Xr;function Zr(e){return e.platform===`win32`?I(e.env.APPDATA??I(e.home,`AppData`,`Roaming`),`seo`,`Config`):I(e.env.XDG_CONFIG_HOME??I(e.home,`.config`),`seo`)}function Qr(e){return e.platform===`darwin`?I(e.home,`Library`,`Caches`,`seo`):e.platform===`win32`?I(e.env.LOCALAPPDATA??I(e.home,`AppData`,`Local`),`seo`,`Cache`):I(e.env.XDG_CACHE_HOME??I(e.home,`.cache`),`seo`)}function $r(e){return e.platform===`darwin`?I(e.home,`Library`,`Logs`,`seo`):e.platform===`win32`?I(e.env.LOCALAPPDATA??I(e.home,`AppData`,`Local`),`seo`,`Log`):I(e.env.XDG_STATE_HOME??I(e.home,`.local`,`state`),`seo`)}function ei(e){return{env:e.env??process.env,home:e.home??Ot(),platform:e.platform??process.platform}}function ti(e={}){let t=ei(e),n=t.env.SEO_CONFIG_DIR??Zr(t),r=t.env.SEO_CACHE_DIR??Qr(t);return{configDir:n,cacheDir:r,logDir:t.env.SEO_LOG_DIR??$r(t),providerPackagesDir:I(n,`providers`),installedProviderPackagesFile:I(n,`provider-packages.json`),configFile:I(n,`config.json`),tokensFile:I(n,`tokens.json`),oauthClientFile:I(n,`oauth-client.json`),providerSecretsFile:I(n,`provider-secrets.json`),telemetryStateFile:I(n,`telemetry.json`),cacheDbFile:I(r,`cache.db`)}}function ni(e){let t=ei(e);if(!(t.platform!==`darwin`||t.env.SEO_CONFIG_DIR||t.env.XDG_CONFIG_HOME))return I(t.home,`Library`,`Preferences`,`seo`)}function ri(e={}){let t=ni(e);if(!t)return;let n=ti(e);if(Vt(t)&&!Vt(n.configDir))try{Ht(Nt(n.configDir),{recursive:!0,mode:448}),Kt(t,n.configDir)}catch(e){let t=e.code;if(t!==`EEXIST`&&t!==`ENOENT`)throw e}}function ii(){return Xr||(Xr=ti(),Xr)}function ai(){let e=ii();return ri(),Ht(e.configDir,{recursive:!0,mode:448}),Ht(e.cacheDir,{recursive:!0,mode:448}),Ht(e.logDir,{recursive:!0,mode:448}),Ht(e.providerPackagesDir,{recursive:!0,mode:448}),e}function oi(e){try{return Jt(e).size}catch{return 0}}function si(e,t=448){Ht(Nt(e),{recursive:!0,mode:t})}function ci(e){try{return JSON.parse(Ut(e,`utf8`))}catch{return}}function li(e,t,n){si(e);let r=`${e}.${process.pid}.${Date.now()}.tmp`;Yt(r,JSON.stringify(t,null,2),{encoding:`utf8`,mode:n}),zt(r,n),Kt(r,e),zt(e,n)}function ui(e){try{return`0${(Jt(e).mode&511).toString(8)}`}catch{return`missing`}}function di(e){qt(e,{recursive:!0,force:!0})}const fi=[`auth`,`crawl_timeout`,`network`,`config`,`data`,`database`,`filesystem`,`internal`,`unknown`],pi=[`access_denied`,`auth_config_required`,`auth_expired`,`auth_required`,`crawl_timeout`,`database_constraint`,`database_corrupt`,`database_locked`,`database_read_only`,`database_unique_constraint`,`filesystem_full`,`filesystem_not_found`,`filesystem_permission`,`insufficient_data`,`internal_error`,`invalid_input`,`network_connection`,`network_dns`,`network_timeout`,`network_tls`,`optional_provider_unavailable`,`property_not_found`,`provider_unavailable`,`rate_limited`,`unknown`],mi=[`crawl_pages_run_id_url`],hi=/* @__PURE__ */ `analytics.auth.cache.change-log.client.content.content-groups.crawl-reports.diagnose.export.gsc-query.indexnow.init.llms.logs.mcp.monitoring.okf.perf.privacy.project.projects.providers.pseo.reports.reset.schedule.server-logs.setup.skill.sites.start.telemetry.tests.updates.url-inspect`.split(`.`),gi={ACCESS_DENIED:{errorCategory:`auth`,failureReason:`access_denied`},AUTH_CONFIG_REQUIRED:{errorCategory:`auth`,failureReason:`auth_config_required`},AUTH_EXPIRED:{errorCategory:`auth`,failureReason:`auth_expired`},AUTH_REQUIRED:{errorCategory:`auth`,failureReason:`auth_required`},INSUFFICIENT_DATA:{errorCategory:`data`,failureReason:`insufficient_data`},INTERNAL_ERROR:{errorCategory:`internal`,failureReason:`internal_error`},INVALID_INPUT:{errorCategory:`config`,failureReason:`invalid_input`},OPTIONAL_PROVIDER_UNAVAILABLE:{errorCategory:`network`,failureReason:`optional_provider_unavailable`},PROPERTY_NOT_FOUND:{errorCategory:`config`,failureReason:`property_not_found`},PROVIDER_UNAVAILABLE:{errorCategory:`network`,failureReason:`provider_unavailable`},RATE_LIMITED:{errorCategory:`network`,failureReason:`rate_limited`}},_i=/* @__PURE__ */ new Set([`EAI_AGAIN`,`ENODATA`,`ENOTFOUND`]),vi=/* @__PURE__ */ new Set([`ECONNREFUSED`,`ECONNRESET`,`ECONNABORTED`,`EPIPE`,`EHOSTUNREACH`,`ENETUNREACH`,`UND_ERR_SOCKET`,`UND_ERR_CONNECT`]),yi=/* @__PURE__ */ new Set([`ETIMEDOUT`,`UND_ERR_CONNECT_TIMEOUT`,`UND_ERR_BODY_TIMEOUT`,`UND_ERR_HEADERS_TIMEOUT`]);function bi(e,t){try{return e[t]}catch{return}}function xi(e){if(typeof e!=`string`&&typeof e!=`number`)return;let t=String(e);return t.length>2048?t.slice(0,2048):t}function Si(e){let t=[e],n=/* @__PURE__ */ new Set,r=[];for(;t.length>0&&r.length<4;){let e=t.shift();typeof e==`string`?r.push({message:xi(e)}):e&&typeof e==`object`&&!n.has(e)&&(n.add(e),r.push({code:xi(bi(e,`code`)),message:xi(bi(e,`message`)),name:xi(bi(e,`name`))}),t.push(bi(e,`cause`),bi(e,`error`)))}return r}function Ci(e,t){if(e.has(`SQLITE_CONSTRAINT_PRIMARYKEY`)||e.has(`SQLITE_CONSTRAINT_UNIQUE`)||/unique constraint failed/i.test(t)){let e=/unique constraint failed:\s*crawl_pages\.run_id\s*,\s*crawl_pages\.url/i.test(t)?`crawl_pages_run_id_url`:void 0;return{errorCategory:`database`,failureReason:`database_unique_constraint`,...e?{failureContext:e}:{}}}if([...e].some(e=>e.startsWith(`SQLITE_CONSTRAINT`))||/constraint failed/i.test(t))return{errorCategory:`database`,failureReason:`database_constraint`};if([...e].some(e=>e.startsWith(`SQLITE_BUSY`)||e.startsWith(`SQLITE_LOCKED`))||/database is locked/i.test(t))return{errorCategory:`database`,failureReason:`database_locked`};if([...e].some(e=>e.startsWith(`SQLITE_CORRUPT`))||e.has(`SQLITE_NOTADB`)||/database disk image is malformed|file is not a database/i.test(t))return{errorCategory:`database`,failureReason:`database_corrupt`};if([...e].some(e=>e.startsWith(`SQLITE_READONLY`))||/attempt to write a readonly database/i.test(t))return{errorCategory:`database`,failureReason:`database_read_only`}}function wi(e){if(e.has(`EACCES`)||e.has(`EPERM`)||e.has(`EROFS`))return{errorCategory:`filesystem`,failureReason:`filesystem_permission`};if(e.has(`ENOENT`))return{errorCategory:`filesystem`,failureReason:`filesystem_not_found`};if(e.has(`ENOSPC`)||e.has(`EDQUOT`)||e.has(`SQLITE_FULL`))return{errorCategory:`filesystem`,failureReason:`filesystem_full`};if([...e].some(e=>_i.has(e)))return{errorCategory:`network`,failureReason:`network_dns`};if([...e].some(e=>yi.has(e)))return{errorCategory:`network`,failureReason:`network_timeout`};if([...e].some(e=>vi.has(e)))return{errorCategory:`network`,failureReason:`network_connection`};if([...e].some(e=>/^(?:CERT_|DEPTH_ZERO_SELF_SIGNED_CERT$|ERR_SSL_|ERR_TLS_|SELF_SIGNED_CERT_IN_CHAIN$|UNABLE_TO_VERIFY_LEAF_SIGNATURE$)/.test(e)))return{errorCategory:`network`,failureReason:`network_tls`}}function Ti(e){let t=Si(e),n=new Set(t.map(e=>e.code?.toUpperCase()).filter(e=>!!e)),r=Ci(n,t.map(e=>e.message).filter(e=>!!e).join(`
|
|
6
|
-
`));if(r)return r;let i=wi(n);if(i)return i;if(t.some(e=>e.name===`AbortError`||e.name===`TimeoutError`))return{errorCategory:`crawl_timeout`,failureReason:`crawl_timeout`};let a=t.find(e=>e.name===`ProviderError`),o=at[a?.code],s=o&&gi[o];if(s)return s;for(let e of n){let t=gi[e];if(t)return t}return t.some(e=>e.name===`CLIError`)?{errorCategory:`config`,failureReason:`invalid_input`}:{errorCategory:`unknown`,failureReason:`unknown`}}function Ei(e){try{return Ti(e)}catch{return{errorCategory:`unknown`,failureReason:`unknown`}}}function Di(e){return typeof e==`string`&&hi.includes(e)}function Oi(e){let t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),n=t.getUTCDay()||7;t.setUTCDate(t.getUTCDate()+4-n);let r=new Date(Date.UTC(t.getUTCFullYear(),0,1)),i=Math.ceil(((t.getTime()-r.getTime())/864e5+1)/7);return`${t.getUTCFullYear()}-W${String(i).padStart(2,`0`)}`}function ki(e){let t=e?.toLowerCase()??``;return t?t.includes(`claude`)?`claude-code`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)||t.includes(`openai`)?`codex`:`unknown`:null}const Ai=`0.27.
|
|
6
|
+
`));if(r)return r;let i=wi(n);if(i)return i;if(t.some(e=>e.name===`AbortError`||e.name===`TimeoutError`))return{errorCategory:`crawl_timeout`,failureReason:`crawl_timeout`};let a=t.find(e=>e.name===`ProviderError`),o=at[a?.code],s=o&&gi[o];if(s)return s;for(let e of n){let t=gi[e];if(t)return t}return t.some(e=>e.name===`CLIError`)?{errorCategory:`config`,failureReason:`invalid_input`}:{errorCategory:`unknown`,failureReason:`unknown`}}function Ei(e){try{return Ti(e)}catch{return{errorCategory:`unknown`,failureReason:`unknown`}}}function Di(e){return typeof e==`string`&&hi.includes(e)}function Oi(e){let t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),n=t.getUTCDay()||7;t.setUTCDate(t.getUTCDate()+4-n);let r=new Date(Date.UTC(t.getUTCFullYear(),0,1)),i=Math.ceil(((t.getTime()-r.getTime())/864e5+1)/7);return`${t.getUTCFullYear()}-W${String(i).padStart(2,`0`)}`}function ki(e){let t=e?.toLowerCase()??``;return t?t.includes(`claude`)?`claude-code`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)||t.includes(`openai`)?`codex`:`unknown`:null}const Ai=`0.27.1`,ji=/* @__PURE__ */ `affected-urls.ai-referrals.audit-page.audit-urls.cannibalisation.compare-crawls.content-optimization.crawl-diff.site-crawl.ctr-underperformers.decaying-pages.setup-check.explain-crawl-issue.crawl-report.index-coverage.index-coverage-plan.index-monitor.index-watch.internal-links.keyword-metrics.link-evidence.link-recovery.crawl-history.crawler-rules.measure-change.page-opportunities.performance-audit.query-clusters.quick-wins.ranked-keywords.redirect-trace.second-page.segment-impact.serp-results.serp-competitors.striking-distance.top-fixes.traffic-anomaly.update-correlation.search-performance-overview.refresh-priorities.technical-watch.update-postmortem`.split(`.`),Mi=[{days:1,event:`active_d1`},{days:7,event:`active_d7`},{days:30,event:`active_d30`}],Ni=[`GITHUB_ACTIONS`,`GITLAB_CI`,`CIRCLECI`,`TRAVIS`,`BUILDKITE`,`JENKINS_URL`,`TEAMCITY_VERSION`,`TF_BUILD`,`BITBUCKET_BUILD_NUMBER`,`CODEBUILD_BUILD_ID`];function Pi(e){return e.env??process.env}function Fi(e){return e.now??/* @__PURE__ */ new Date}function Ii(e){return e.stateFile??ii().telemetryStateFile}function Li(e){return e===`1`||e?.toLowerCase()===`true`}function Ri(e=process.env){return e.NODE_ENV===`test`||!!e.NODE_TEST_CONTEXT||Li(e.CI)||Ni.some(t=>!!e[t])}function zi(e){if(Ri(e))return`ci`;if(Li(e.DO_NOT_TRACK))return`do_not_track`;if(Li(e.SEOSKILL_TELEMETRY_DISABLED)||Li(e.SEO_TELEMETRY_DISABLED))return`environment`}function Bi(e){return typeof e==`string`&&[`first_run`,`setup_complete`,`first_audit_complete`,`active_d1`,`active_d7`,`active_d30`].includes(e)}function Vi(e){return typeof e==`string`&&ji.includes(e)}function Hi(e){return typeof e==`string`&&/^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/.test(e)}function Ui(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.telemetryEnabled==`boolean`&&typeof t.firstRunAt==`string`&&Number.isFinite(Date.parse(t.firstRunAt))&&Hi(t.cohort)&&Array.isArray(t.sentMilestones)&&t.sentMilestones.every(Bi)}function Wi(e){if(!Vt(e))return{kind:`missing`};let t=ci(e);return Ui(t)?{kind:`valid`,state:t}:{kind:`invalid`}}function Gi(e,t){li(e,t,384)}function Ki(e,t=!0){let n=Fi(e);return{telemetryEnabled:t,firstRunAt:n.toISOString(),cohort:Oi(n),sentMilestones:[]}}function qi(e={}){let t=e.env??process.env;return ki(e.clientName)||(t.CLAUDECODE||t.CLAUDE_CODE?`claude-code`:t.CURSOR_AGENT||t.CURSOR_TRACE_ID||t.CURSOR_SESSION_ID?`cursor`:t.CODEX_HOME||t.CODEX_THREAD_ID||t.CODEX_SANDBOX?`codex`:`cli`)}function Ji(e=process.env){let t=(e.AI_AGENT||e.AGENT)?.trim().toLowerCase();if(t)return t.slice(0,40);let n=qi({env:e});return n===`cli`?e.GEMINI_CLI?`gemini`:e.OPENCODE||e.OPENCODE_CLIENT?`opencode`:e.ANTIGRAVITY_AGENT?`antigravity`:e.AUGMENT_AGENT?`augment`:e.COPILOT_MODEL||e.COPILOT_ALLOW_ALL?`github-copilot`:e.REPL_ID?`replit`:null:n}function Yi(e){return e.agent??qi({clientName:e.clientName,env:Pi(e)})}function Xi(e){return e.replace(/^v/,``).split(`.`)[0]||`unknown`}function Zi(e,t,n={},r={}){return{event:e,version:r.version??Ai,agent:Yi(r),os:r.processPlatform??At(),arch:r.processArch??Dt(),node:Xi(r.nodeVersion??process.version),cohort:t.cohort,schema:2,...n.errorCategory?{errorCategory:n.errorCategory}:{},...n.failureReason?{failureReason:n.failureReason}:{},...n.failureContext?{failureContext:n.failureContext}:{},...n.operation?{operation:n.operation}:{},...n.report?{report:n.report}:{}}}function Qi(e,t){let n=t.fetch??globalThis.fetch;try{n(t.endpoint??`https://seoskill.dev/api/t`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:AbortSignal.timeout(2e3)}).catch(()=>void 0)}catch{}}function $i(e){let t=Ii(e),n=zi(Pi(e)),r=Wi(t);return n?{enabled:!1,reason:n,stateFile:t,...r.kind===`valid`?{state:r.state}:{}}:r.kind===`invalid`?{enabled:!1,reason:`invalid_state`,stateFile:t}:r.kind===`valid`&&!r.state.telemetryEnabled?{enabled:!1,reason:`local_setting`,stateFile:t,state:r.state}:{enabled:!0,stateFile:t,...r.kind===`valid`?{state:r.state}:{}}}function ea(e={}){return $i(e)}function ta(e,t={}){let n=Ii(t),r=Wi(n),i=r.kind===`valid`?r.state:Ki(t,e);return i.telemetryEnabled=e,Gi(n,i),$i(t)}function na(e){let t=$i(e);return t.enabled?t.state:void 0}function ra(e={}){let t=$i(e);if(!t.enabled)return t;let n=t.stateFile,r=t.state??Ki(e),i=[];if(!r.sentMilestones.includes(`first_run`)){try{(e.notice??(e=>process.stderr.write(e)))(`SEO Skill collects anonymous usage data to improve the tool (event name,
|
|
7
7
|
fixed report or command name, fixed failure classification, version, agent,
|
|
8
8
|
OS, architecture, Node major, and install week; never URLs, report data, error
|
|
9
9
|
messages, command arguments, or identifiers of any kind).
|
|
@@ -474,7 +474,7 @@ if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discrimin
|
|
|
474
474
|
/* istanbul ignore if */
|
|
475
475
|
if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),R7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=L5(),n=R5(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),z7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R5();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),B7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=w7(),n=E7(),r=T7(),i=D7(),a=O7(),o=k7(),s=A7(),c=j7(),l=M7(),u=N7(),d=P7(),f=F7(),p=I7(),m=L7(),h=R7(),g=z7();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),V7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=L5();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),H7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[V7().default]})),U7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),W7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=u7(),n=C7(),r=B7(),i=H7(),a=U7();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),G7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),K7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=L5(),n=G7(),r=t7(),i=e7(),a=R5();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),q7=/* @__PURE__ */ z(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),J7=/* @__PURE__ */ z(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=s7(),r=W7(),i=K7(),a=q7(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=Q5();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=L5();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=$5();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=e7();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Y7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:E,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=(/* @__PURE__ */ new Date(`2020-01-01T`+e)).valueOf(),r=(/* @__PURE__ */ new Date(`2020-01-01T`+t)).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),X7=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=J7(),n=L5(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),Z7=/* @__PURE__ */ z(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Y7(),r=X7(),i=L5(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),Q7=/* @__PURE__ */ Bn(J7(),1),$7=/* @__PURE__ */ Bn(Z7(),1);function e9(){let e=new Q7.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$7.default)(e),e}var t9=class{constructor(e){this._ajv=e??e9()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},n9=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},K6,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},f8,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function r9(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function i9(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var a9=class extends M5{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=/* @__PURE__ */ new Map,this.LOG_LEVEL_SEVERITY=new Map(M6.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new t9,this.setRequestHandler(h3,e=>this._oninitialize(e)),this.setNotificationHandler(v3,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(P6,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=M6.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new n9(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=P5(this._capabilities,e)}setRequestHandler(e,t){let n=C4(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=k4(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=x4(A6,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new $(Q.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=x4(O3,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new $(Q.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=x4(O6,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new $(Q.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){i9(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&r9(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:j4.includes(t)?t:A4,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},n3)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},q6,t):this.request({method:`sampling/createMessage`,params:e},K6,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},f8,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},f8,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new $(Q.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof $?e:new $(Q.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},S8,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const o9=Symbol.for(`mcp.completable`);function s9(e){return!!e&&typeof e==`object`&&o9 in e}function c9(e){return e[o9]?.complete}var l9;(function(e){e.Completable=`McpCompletable`})(l9||={});const u9=/^[A-Za-z0-9._-]{1,128}$/;function d9(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!u9.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function f9(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function p9(e){let t=d9(e);return f9(e,t.warnings),t.isValid}var Hee=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}};function Uee(e,t){let n=0,r=[e];for(;r.length>0;){let e=r.pop();if(typeof e==`object`&&e){if(Array.isArray(e))for(let i of e){if(++n>t)return n;typeof i==`object`&&i&&r.push(i)}else for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++n>t)return n;let a=e[i];typeof a==`object`&&a&&r.push(a)}}}return n}function Wee(e){if(e!==void 0&&e!==1/0){if(typeof e!=`number`||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var Gee=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new a9(e,t),this._maxToolInputElements=Wee(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||={tasks:new Hee(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(v9(E6)),this.server.assertCanSetRequestHandler(v9(A6)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(E6,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=w4(t.inputSchema);return e?k5(e,{strictUnions:!0,pipeStrategy:`input`}):Kee})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=w4(t.outputSchema);e&&(n.outputSchema=k5(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(A6,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new $(Q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new $(Q.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new $(Q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof $&&e.code===Q.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(this._maxToolInputElements!==void 0&&Uee(t,this._maxToolInputElements)>this._maxToolInputElements)throw new $(Q.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let r=await S4(w4(e.inputSchema)??e.inputSchema,t??{});if(!r.success){let e=E4(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new $(Q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await S4(w4(e.outputSchema),t.structuredContent);if(!r.success){let e=E4(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new $(Q.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(v9(g8)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(g8,async e=>{switch(e.params.ref.type){case`ref/prompt`:return _8(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return v8(e),this.handleResourceCompletion(e,e.params.ref);default:throw new $(Q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new $(Q.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return b9;let r=C4(n.argsSchema)?.[e.params.argument.name];if(!s9(r))return b9;let i=c9(r);return i?y9(await i(e.params.argument.value,e.params.context)):b9}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return b9;throw new $(Q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?y9(await r(e.params.argument.value,e.params.context)):b9}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(v9(K3)),this.server.assertCanSetRequestHandler(v9(J3)),this.server.assertCanSetRequestHandler(v9(Q3)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(K3,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(J3,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Q3,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new $(Q.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new $(Q.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(v9(l6)),this.server.assertCanSetRequestHandler(v9(f6)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(l6,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?qee(t.argsSchema):void 0}))})),this.server.setRequestHandler(f6,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new $(Q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await S4(w4(n.argsSchema),e.params.arguments??{});if(!r.success){let t=E4(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:b4(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=b4(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>s9(e instanceof Et?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){p9(e);let l={title:t,description:n,inputSchema:_9(r),outputSchema:_9(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&p9(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=b4(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=b4(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(g9(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!g9(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const Kee={type:`object`,properties:{}};function m9(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function h9(e){return`_def`in e||`_zod`in e||m9(e)}function g9(e){return typeof e!=`object`||!e||h9(e)?!1:Object.keys(e).length===0||Object.values(e).some(m9)}function _9(e){if(e){if(g9(e))return b4(e);if(!h9(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function qee(e){let t=C4(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:D4(t),required:!O4(t)})):[]}function v9(e){let t=C4(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=k4(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function y9(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const b9={completion:{values:[],hasMore:!1}};var Jee=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
476
476
|
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),Yee(t)}clear(){this._buffer=void 0}};function Yee(e){return t3.parse(JSON.parse(e))}function Xee(e){return JSON.stringify(e)+`
|
|
477
|
-
`}var Zee=class{constructor(e=jn.stdin,t=jn.stdout,n){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}},this._onerror=e=>{this.onerror?.(e)},this._readBuffer=new Jee({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=Xee(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function x9(e){return Buffer.byteLength(JSON.stringify(e))}function S9(e){let t=x9(e);for(;e.outputBudget.returnedBytes!==t;)e.outputBudget.returnedBytes=t,t=x9(e);return t}function C9(e,t,n,r){if(typeof e==`string`)return e.length<=n.stringLimit?e:(r.push({path:t,kind:`string`,available:e.length,returned:n.stringLimit}),`${e.slice(0,Math.max(1,n.stringLimit-3)).trimEnd()}...`);if(Array.isArray(e))return e.length>n.arrayLimit&&r.push({path:t,kind:`array`,available:e.length,returned:n.arrayLimit}),e.slice(0,n.arrayLimit).map((e,i)=>C9(e,`${t}[${i}]`,n,r));if(!e||typeof e!=`object`)return e;let i={};for(let[a,o]of Object.entries(e)){let e=t?`${t}.${a}`:a;!t&&n.preserveAgentContract&&(a===`findings`||a===`inventories`)?i[a]=o:a===`markdown`?r.push({path:e,kind:`field`}):i[a]=C9(o,e,n,r)}return i}function w9(e,t={}){let n=t.maxBytes??98304,r=e,i=e.findings,a=i?.schemaVersion===1&&i.scope===`returned-report`&&Array.isArray(i.items),o=x9(r),s={...r,outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:!1,omissions:[],omissionsTruncated:!1,detail:`The complete structured report fits within the agent output budget.`}};if(S9(s)<=n)return s;let c=[{arrayLimit:10,stringLimit:4e3,preserveAgentContract:a},{arrayLimit:5,stringLimit:2e3,preserveAgentContract:a},{arrayLimit:3,stringLimit:1e3,preserveAgentContract:a},{arrayLimit:1,stringLimit:500,preserveAgentContract:a}];for(let e of c){let t=[],i={...C9(r,``,e,t),outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:t.length>0,arrayLimit:e.arrayLimit,stringLimit:e.stringLimit,omissions:t.slice(0,100),omissionsTruncated:t.length>100,detail:`Counts, provenance, caveats, and compact evidence are retained. Run the related focused report when more rows are needed.`}};if(S9(i)<=n)return i}let l={...hr(r),outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:!0,fallback:!0,omissionsTruncated:!1,omissions:[{path:`reportBody`,kind:`field`}],detail:`The detailed report exceeded the budget, so the complete findings and retained inventories are returned instead.`}};if(S9(l)<=n)return l;throw Error(`The complete findings and inventories exceed the ${n}-byte agent output budget. Run a focused report with a narrower bounded scope; actionable rows were not truncated.`)}function T9(e){let t=Se(e);return{content:[{type:`text`,text:`Error: ${t.error.message}`}],structuredContent:t,isError:!0}}function E9(e,t,n={}){return{content:[{type:`text`,text:n.markdown??e}],structuredContent:t}}function Qee(e){e.registerTool(`seo_list_providers`,{description:`List provider packages installed through the seo CLI. Package installation requires human approval in a terminal.`,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async()=>{try{let e=await q0();return E9(`${e.installed.length} provider packages are installed.`,e)}catch(e){return T9(e)}}),e.registerTool(`seo_describe_provider`,{description:`Describe one installed provider, its shared capabilities, and its agent action schemas`,inputSchema:{id:R.string().trim().min(1).max(64)},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async({id:e})=>{try{let t=await J0(e);return E9(`${t.id}: ${t.description}`,t)}catch(e){return T9(e)}}),e.registerTool(`seo_run_provider`,{description:`Run one action from an installed provider after reading its schema with seo_describe_provider`,inputSchema:{id:R.string().trim().min(1).max(64),action:R.string().trim().min(1).max(64),account:R.record(R.string(),R.string()).optional(),params:R.record(R.string(),R.unknown()).optional(),refresh:R.boolean().optional()},annotations:{readOnlyHint:!1,destructiveHint:!1}},async({id:e,action:t,account:n,params:r,refresh:i})=>{try{let a=await U0({providerId:e,actionId:t,account:n??W0(e),params:r??{},refresh:i});return E9(`Provider ${e} completed action ${t}.`,w9(a))}catch(e){return T9(e)}})}const D9=R.iso.date(`Use a YYYY-MM-DD date.`);function O9(e,t){return e===void 0?t:e}const $ee={site:{mcp:`site`,schema:R.string()},days:{mcp:`days`,schema:R.number().optional()},recentDays:{mcp:`recentDays`,schema:R.number().optional()},range:{mcp:`range`,schema:R.number().optional()},limit:{mcp:`limit`,schema:R.number().optional()},checkLimit:{mcp:`checkLimit`,schema:R.number().optional()},minImpressions:{mcp:`minImpressions`,schema:R.number().optional()},includeBrand:{mcp:`includeBrand`,schema:R.boolean().optional()},verifyContent:{mcp:`verifyContent`,schema:R.boolean().optional()},verifyLimit:{mcp:`verifyLimit`,schema:R.number().optional()},js:{mcp:`js`,schema:R.boolean().optional()},fetchConcurrency:{mcp:`fetchConcurrency`,schema:R.number().optional()},fetchIntervalCap:{mcp:`fetchIntervalCap`,schema:R.number().optional()},fetchIntervalMs:{mcp:`fetchIntervalMs`,schema:R.number().optional()},refresh:{mcp:`refresh`,schema:R.boolean().optional()}};function k9(e){return Object.fromEntries(e.map(e=>{let t=$ee[e];return[t.mcp,t.schema]}))}const A9=R.union([D9,R.string().regex(/^(?:today|yesterday|\d+daysAgo)$/)]).describe(`Use YYYY-MM-DD or a Google Analytics relative date.`);function ete(e,t={}){e.registerTool(`seo_ai_referrals`,{description:`Find AI referral traffic detected in Google Analytics. maxRows bounds retained provider rows; resultLimit bounds returned landing pages.`,inputSchema:{property:R.string().trim().min(1),startDate:A9.optional(),endDate:A9.optional(),maxRows:R.number().int().min(1).max(1e5).describe(`Maximum retained Google Analytics rows. If limit is also supplied, both values must match.`).optional(),limit:R.number().int().min(1).max(1e5).describe(`Legacy alias for maxRows. If maxRows is also supplied, both values must match.`).optional(),resultLimit:R.number().int().min(1).max(1e3).describe(`Maximum ranked landing pages returned. Defaults to 25.`).optional(),refresh:R.boolean().optional()}},async({property:e,startDate:n,endDate:r,maxRows:i,limit:a,resultLimit:o,refresh:s})=>{try{if(i!==void 0&&a!==void 0&&i!==a)throw new P(`INVALID_INPUT`,`maxRows and the legacy limit option must match when both are provided.`);let c=await(t.aiReferralsReport??Nc)({property:e,startDate:n,endDate:r,maxRows:i,limit:a,resultLimit:o,refresh:s});return E9(`${$M(c.summary.sessions,`AI referral session`)} detected across ${$M(c.summary.sources,`source`)}; evidence is ${c.dataStatus}.`,c)}catch(e){return T9(e)}}),e.registerTool(`seo_page_opportunities`,{description:`Find first-party traffic growth opportunities for one URL from GSC and page content`,inputSchema:{...k9([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`verifyContent`,`refresh`,`js`]),days:R.number().int().min(1).max(548).optional(),limit:R.number().int().min(1).max(100).optional(),minImpressions:R.number().int().positive().optional(),url:R.string().url()}},async({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:l})=>{try{let u=await(t.pageOpportunitiesReport??jT)({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:O9(l,`auto`)});return E9(u.summary.verdict,u)}catch(e){return T9(e)}}),e.registerTool(`seo_content_optimization`,{description:`Build a content optimization brief for one URL from first-party GSC queries and page content checks`,inputSchema:{...k9([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`verifyContent`,`refresh`,`js`]),days:R.number().int().min(1).max(548).optional(),limit:R.number().int().min(1).max(100).optional(),minImpressions:R.number().int().positive().optional(),url:R.string().url()}},async({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:l})=>{try{let u=await(t.contentOptimizationReport??VT)({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:O9(l,`auto`)});return E9(u.summary.verdict,u)}catch(e){return T9(e)}}),e.registerTool(`seo_performance_audit`,{description:`Run a local Lighthouse lab audit and optional device-specific CrUX field Core Web Vitals. Configure CrUX with SEO_CRUX_API_KEY.`,inputSchema:{url:R.string().url(),strategy:R.enum([`mobile`,`desktop`]).optional(),refresh:R.boolean().optional()}},async({url:e,strategy:t,refresh:n})=>{try{let r=await Rz({url:e,strategy:t,refresh:n});return E9(r.headline,r)}catch(e){return T9(e)}})}function j9(e,t={}){let n=e.requestEvidenceStatus===`available`?`Processed ${e.requests.length} URL requests into ${e.summary.totalPages} unique documents.`:e.requestEvidenceStatus===`partial`?`Observed ${e.requests.length} URL requests and retained ${e.summary.totalPages} unique documents; some started requests were still in flight when the crawl stopped.`:`Loaded ${e.summary.totalPages} unique documents; request evidence is unavailable for this legacy report.`,r={id:e.id,definitionId:e.definitionId,headline:`${n} Found ${e.summary.highIssues} high, ${e.summary.mediumIssues} medium, and ${e.summary.lowIssues} low issues.`,status:e.status,requestEvidenceStatus:e.requestEvidenceStatus,configHash:e.configHash,config:e.config,access:e.access,summary:e.summary,dataSources:e.dataSources,ai:e.ai?{robotsTxt:e.ai.robotsTxt,llmsTxt:e.ai.llmsTxt,agentResources:e.ai.agentResources}:void 0,topFixes:UD(e,{limit:1e3}),reviewObservations:WD(e,{limit:1e3}),issueGroupsComplete:!0,warnings:e.warnings,caveats:e.caveats};return t.includeIssues&&(r.issues=e.issues),t.includePages&&(r.requests=e.requests,r.pages=e.pages),r}const M9=R.number().int().min(1).max(YE).optional(),N9=R.number().int().min(0).max(64).optional(),P9=R.number().int().min(1).max(16).optional(),F9=R.string().regex(/^\d{1,30}$/u).optional();function I9(e){if(e.googleAnalyticsPropertyId&&e.clickySiteId)throw new P(`INVALID_INPUT`,`Pass either googleAnalyticsPropertyId or clickySiteId, not both.`);return e.clickySiteId?{provider:`clicky`,siteId:e.clickySiteId}:void 0}function L9(e){if(e.fetchConcurrency!==void 0||e.fetchIntervalCap!==void 0||e.fetchIntervalMs!==void 0)return{concurrency:e.fetchConcurrency,intervalCap:e.fetchIntervalCap,intervalMs:e.fetchIntervalMs}}function tte(e){e.registerTool(`seo_crawl_site`,{description:`Run a site crawl. Start with health=true for a fast uncached sitemap status and redirect pass, especially on large or unknown sites. Run the full crawl second when content-level evidence is needed. The compact result includes crawler identity and access-block guidance.`,inputSchema:{url:R.string().url().optional().describe(`Site start URL. Optional when sitemapUrl supplies the health-pass scope.`),health:R.boolean().optional().describe(`Run the fast sitemap health pass before a full crawl. Downloads no page bodies and writes no page cache entries.`),sitemapUrl:R.string().url().optional().describe(`Explicit sitemap or sitemap index URL for the health pass.`),site:R.string().optional(),googleAnalyticsPropertyId:R.string().optional(),clickySiteId:F9,maxPages:M9,maxDepth:N9,concurrency:P9,fetchIntervalCap:R.number().int().positive().optional(),fetchIntervalMs:R.number().int().positive().optional(),refresh:R.boolean().optional(),include:R.array(R.string()).optional(),exclude:R.array(R.string()).optional(),useSitemap:R.boolean().optional(),respectRobots:R.boolean().optional(),js:R.boolean().optional(),includePages:R.boolean().optional(),includeIssues:R.boolean().optional()}},async({url:e,health:t,sitemapUrl:n,site:r,googleAnalyticsPropertyId:i,clickySiteId:a,maxPages:o,maxDepth:s,concurrency:c,fetchIntervalCap:l,fetchIntervalMs:u,refresh:d,include:f,exclude:p,useSitemap:m,respectRobots:h,js:g,includePages:_,includeIssues:v})=>{try{let y=I9({googleAnalyticsPropertyId:i,clickySiteId:a}),b=e??(n?new URL(`/`,n).toString():void 0);if(!b)throw new P(`INVALID_INPUT`,`Pass url or an explicit sitemapUrl.`);let x=await gM({url:b,mode:t||n?`sitemap`:`site`,strategy:t?`health`:`full`,sitemapUrl:n,site:r,googleAnalyticsPropertyId:i,analyticsConnection:y,maxPages:o,maxDepth:s,concurrency:c,refresh:d,fetchRate:L9({fetchConcurrency:c,fetchIntervalCap:l,fetchIntervalMs:u}),include:f,exclude:p,useSitemap:m,respectRobots:h,js:!!g});return E9(`${t?`Sitemap health pass`:`Crawl`} complete for ${b}. Found ${x.issues.length} issues across ${x.summary.totalPages} pages.`,j9(x,{includePages:_,includeIssues:v}))}catch(e){return T9(e)}}),e.registerTool(`seo_audit_urls`,{description:`Audit an explicit list of URLs with technical SEO checks. The compact result separates prioritised fixes from review observations. Set includePages/includeIssues for raw data.`,inputSchema:{urls:R.array(R.string().url()).min(1).max(YE),site:R.string().optional(),googleAnalyticsPropertyId:R.string().optional(),clickySiteId:F9,maxPages:M9,concurrency:P9,fetchIntervalCap:R.number().int().positive().optional(),fetchIntervalMs:R.number().int().positive().optional(),refresh:R.boolean().optional(),includePages:R.boolean().optional(),includeIssues:R.boolean().optional()}},async({urls:e,site:t,googleAnalyticsPropertyId:n,clickySiteId:r,maxPages:i,concurrency:a,fetchIntervalCap:o,fetchIntervalMs:s,refresh:c,includePages:l,includeIssues:u})=>{try{let d=I9({googleAnalyticsPropertyId:n,clickySiteId:r}),f=await gM({url:e[0]??``,urls:e,mode:`list`,site:t,googleAnalyticsPropertyId:n,analyticsConnection:d,maxPages:i??e.length,concurrency:a,refresh:c,fetchRate:L9({fetchConcurrency:a,fetchIntervalCap:o,fetchIntervalMs:s}),useSitemap:!1});return E9(`URL audit complete. Found ${f.issues.length} issues across ${f.summary.totalPages} pages.`,j9(f,{includePages:l,includeIssues:u}))}catch(e){return T9(e)}}),e.registerTool(`seo_top_fixes`,{description:`Return top technical SEO fixes for a URL by running a compact crawl.`,inputSchema:{url:R.string().url(),site:R.string().optional(),maxPages:M9,maxDepth:N9,fetchIntervalCap:R.number().int().positive().optional(),fetchIntervalMs:R.number().int().positive().optional(),refresh:R.boolean().optional(),category:R.string().optional(),limit:R.number().int().min(1).max(1e3).optional()}},async({url:e,site:t,maxPages:n,maxDepth:r,fetchIntervalCap:i,fetchIntervalMs:a,refresh:o,category:s,limit:c})=>{try{let l=await gM({url:e,site:t,maxPages:n,maxDepth:r,refresh:o,fetchRate:L9({fetchIntervalCap:i,fetchIntervalMs:a})}),u=UD(l,{category:s,limit:c}),d=l.status===`completed`?``:` Coverage is ${l.status}: ${$M(l.summary.crawledUrls,`URL`)} crawled from ${$M(l.summary.discoveredUrls,`discovered URL`)}. Review the returned warnings and caveats before treating this as sitewide.`;return E9(`Found ${$M(u.length,`top fix group`)} for ${l.config.url}.${d}`,{url:l.config.url,reportId:l.id,summary:l.summary,dataSources:l.dataSources,topFixes:u,warnings:l.warnings,caveats:l.caveats})}catch(e){return T9(e)}}),e.registerTool(`seo_explain_issue`,{description:`Explain a crawler rule in plain English: why it matters, how to fix it, and how to verify it.`,inputSchema:{ruleId:R.string()}},async({ruleId:e})=>{let t=Yn(e);return t?E9(`Rule guidance for ${e}.`,t):T9(`Unknown rule: ${e}`)}),e.registerTool(`seo_list_rules`,{description:`List crawler rule ids and guidance metadata. Use this before the explain-crawl-issue report when you need valid rule ids.`,inputSchema:{category:uO.optional()}},async({category:e})=>{let t=Jn().filter(t=>!e||t.category===e);return E9(`Found ${$M(t.length,`crawler rule`)}.`,{rules:t})})}function R9(e,t={}){e.registerTool(`seo_doctor`,{description:`Check the local database, auth, scopes, config, and defaults`,inputSchema:{}},async()=>{try{let e=await O0();return E9(e.ok?`Local seo setup is ready.`:`Local seo setup needs attention.`,e)}catch(e){return T9(e)}}),e.registerTool(`seo_segment_impact`,{description:`Compare matched retained GSC segments across adjacent equal-length periods without treating missing rows as zero`,inputSchema:{site:R.string().trim().min(1),days:R.number().int().min(1).max(240).optional(),limit:R.number().int().min(1).max(100).optional(),refresh:R.boolean().optional(),dimension:R.enum([`page`,`query`,`country`,`device`]).optional(),compareDays:R.number().int().min(1).max(240).optional(),startDate:D9.optional(),endDate:D9.optional(),maxRows:R.number().int().min(1).max(25e4).optional(),unmatchedLimit:R.number().int().min(0).max(100).optional()}},async({site:e,dimension:n,days:r,compareDays:i,startDate:a,endDate:o,limit:s,maxRows:c,unmatchedLimit:l,refresh:u})=>{try{let d=await(t.segmentImpact??xN)({site:e,dimension:n,days:r,compareDays:i,startDate:a,endDate:o,limit:s,maxRows:c,unmatchedLimit:l,refresh:u});return E9(d.summary.verdict,d)}catch(e){return T9(e)}}),e.registerTool(`seo_striking_distance`,{description:`Find position 11-20 query/page opportunities from GSC`,inputSchema:{...k9([`site`,`days`,`minImpressions`,`limit`,`verifyContent`,`verifyLimit`,`includeBrand`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),days:R.number().int().min(1).max(548).optional(),minImpressions:R.number().int().min(0).max(1e9).optional(),limit:R.number().int().min(1).max(100).optional(),verifyLimit:R.number().int().min(0).max(100).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:R.number().int().min(1).max(16).optional(),fetchIntervalCap:R.number().int().min(1).max(60).optional(),fetchIntervalMs:R.number().int().min(100).max(6e4).optional()}},async({site:e,days:t,minImpressions:n,limit:r,verifyContent:i,verifyLimit:a,includeBrand:o,brandTerms:s,js:c,fetchConcurrency:l,fetchIntervalCap:u,fetchIntervalMs:d,refresh:f})=>{try{let p=await pI({site:e,days:t,minImpressions:n,limit:r,verifyContent:i,verifyLimit:a,includeBrand:o,brandTerms:s,js:O9(c,void 0),rate:L9({fetchConcurrency:l,fetchIntervalCap:u,fetchIntervalMs:d}),refresh:f});return E9(p.summary.verdict,p)}catch(e){return T9(e)}}),e.registerTool(`seo_traffic_anomaly`,{description:`Detect statistically significant recent GSC traffic movement`,inputSchema:{...k9([`site`,`days`,`recentDays`,`refresh`])}},async({site:e,days:t,recentDays:n,refresh:r})=>{try{let i=await VI({site:e,days:t,recentDays:n,refresh:r});return E9(`${i.anomalies.filter(e=>e.significant).length} significant anomalies found.`,i)}catch(e){return T9(e)}}),e.registerTool(`seo_update_correlate`,{description:`Overlay recent traffic anomalies against official Google ranking update windows`,inputSchema:{...k9([`site`,`days`,`recentDays`,`refresh`]),paddingDays:R.number().optional()}},async({site:e,days:t,recentDays:n,paddingDays:r,refresh:i})=>{try{let a=await HI({site:e,days:t,recentDays:n,paddingDays:r,refresh:i});return E9(`Classification: ${a.classification}.`,a)}catch(e){return T9(e)}})}function nte(e){e.registerTool(`seo_index_coverage`,{description:`Crawl the site, compare it and its sitemap with Search Console page results, then choose representative URLs for URL Inspection`,inputSchema:{site:R.string().min(1),url:R.string().url().optional().describe(`Start URL to crawl. Defaults to the home page.`),sitemaps:R.array(R.string().url()).min(1).max(20).optional(),days:R.number().int().min(1).max(548).optional(),rowLimit:R.number().int().min(1).max(25e4).optional(),maxSitemapUrls:R.number().int().min(1).max(25e4).optional(),itemsPerSection:R.number().int().min(1).max(1e3).optional(),templateClusters:R.number().int().min(1).max(200).optional(),templateSamples:R.number().int().min(1).max(25).optional(),refresh:R.boolean().optional()}},async({site:e,url:t,sitemaps:n,days:r,rowLimit:i,maxSitemapUrls:a,itemsPerSection:o,templateClusters:s,templateSamples:c,refresh:l})=>{try{let u=await ez({site:e,url:t,sitemaps:n,days:r,rowLimit:i,maxSitemapUrls:a,itemsPerSection:o,templateClusters:s,templateSamples:c,refresh:l});return E9(`${u.summary.retainedSearchVisibleUrls} URLs appeared in the returned Search Console data. ${u.summary.crawlableCandidatesWithoutRetainedSearchVisibility} crawlable URLs need evidence review before choosing representative URL Inspection checks.`,u)}catch(e){return T9(e)}}),e.registerTool(`seo_redirect_trace`,{description:`Trace redirects and report final indexability/canonical issues for a URL`,inputSchema:{url:R.string().url(),maxHops:R.number().optional(),refresh:R.boolean().optional(),js:R.boolean().optional()}},async({url:e,maxHops:t,refresh:n,js:r})=>{try{let i=await nz({url:e,maxHops:t,refresh:n,js:O9(r,`auto`)});return E9(`Traced ${i.summary.hops} hops. ${i.summary.finalStatus===null?`No final response (${i.summary.outcome}: ${i.summary.error??`unknown`}).`:`Final status ${i.summary.finalStatus}.`} ${i.summary.issues.length} issues.`,i)}catch(e){return T9(e)}}),e.registerTool(`seo_link_recover`,{description:`Find GSC search-value URLs that are now broken, blocked, or poorly redirected`,inputSchema:{...k9([`site`,`days`,`limit`,`minImpressions`,`refresh`,`js`]),minClicks:R.number().optional()}},async({site:e,days:t,limit:n,minClicks:r,minImpressions:i,refresh:a,js:o})=>{try{let s=await sz({site:e,days:t,limit:n,minClicks:r,minImpressions:i,refresh:a,js:O9(o,`auto`)});return E9(`Checked ${s.summary.checked} search-value URLs. ${s.summary.recoverable} recoverable issues.`,s)}catch(e){return T9(e)}})}const rte=R.enum([`dataforseo`,`ahrefs`]),z9=e=>R.string().trim().min(1).max(500).describe(e).optional(),ite=R.strictObject({keyword:z9(`Source column containing the search query.`),url:z9(`Source column containing the ranking URL.`),position:z9(`Source column containing grouped position.`),absolutePosition:z9(`Source column containing absolute result position.`),searchVolume:z9(`Source column containing monthly search volume.`),keywordDifficulty:z9(`Source column containing keyword difficulty.`),cpc:z9(`Source column containing cost per click.`),paidCompetition:z9(`Source column containing paid competition.`),intent:z9(`Source column containing search intent.`),resultCount:z9(`Source column containing estimated result count.`),estimatedTraffic:z9(`Source column containing estimated monthly visits.`),resultType:z9(`Source column containing result type.`),searchVolumeUpdatedAt:z9(`Source column containing the search volume update date.`)}).superRefine((e,t)=>{let n=/* @__PURE__ */ new Map;for(let[r,i]of Object.entries(e)){if(!i)continue;let e=IN(i),a=n.get(e);a?t.addIssue({code:`custom`,message:`Source column "${i}" is already mapped to "${a}".`,path:[r]}):n.set(e,r)}}).describe(`Optional canonical field to source column mapping. Named fields override automatic header matching.`),ate=R.array(R.strictObject({dataset:R.literal(`ranked-keywords`),file:R.string().trim().min(1).max(4096),provider:rte,exportedAt:R.string().trim().min(1).max(100),format:R.enum([`csv`,`json`,`jsonl`]).optional(),rowLimit:R.number().int().min(1).max(1e5).optional(),columns:ite.optional()})).min(1).max(4).describe(`One to four local ranked-keyword exports from the same provider and market.`);function ote(e,t={}){e.registerTool(`seo_cannibal`,{description:`Find multi-URL query exposure candidates for intent and technical review`,inputSchema:{...k9([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`refresh`]),days:R.number().int().min(1).max(548).optional(),limit:R.number().int().min(1).max(100).optional(),minImpressions:R.number().int().min(0).max(1e9).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional(),researchFiles:ate.optional()}},async({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o,researchFiles:s})=>{try{let c=s?await aF({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o,researchFiles:s}):await aF({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o});return E9(c.summary.verdict,c)}catch(e){return T9(e)}}),e.registerTool(`seo_decaying`,{description:`Find query/page click declines observed in both retained GSC windows and investigation signals`,inputSchema:{...k9([`site`,`days`,`limit`,`includeBrand`,`refresh`]),days:R.number().int().min(1).max(548).optional(),limit:R.number().int().min(1).max(100).optional(),comparison:R.enum([`previous-period`,`year-over-year`]).optional(),minDropPct:R.number().min(0).max(100).optional(),minPreviousClicks:R.number().min(0).max(1e9).optional(),minClickLoss:R.number().min(0).max(1e9).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,days:t,limit:n,comparison:r,minDropPct:i,minPreviousClicks:a,minClickLoss:o,brandTerms:s,includeBrand:c,refresh:l})=>{try{let u=await SF({site:e,days:t,limit:n,comparison:r,minDropPct:i,minPreviousClicks:a,minClickLoss:o,brandTerms:s,includeBrand:c,refresh:l});return E9(u.summary.verdict,u)}catch(e){return T9(e)}}),e.registerTool(`seo_quick_wins`,{description:`Find quick-win CTR/position opportunities`,inputSchema:{...k9([`site`,`days`,`limit`,`minImpressions`,`verifyContent`,`verifyLimit`,`includeBrand`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),days:R.number().int().min(1).max(548).optional(),limit:R.number().int().min(1).max(100).optional(),minImpressions:R.number().int().min(0).max(1e9).optional(),verifyLimit:R.number().int().min(0).max(100).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:R.number().int().min(1).max(16).optional(),fetchIntervalCap:R.number().int().min(1).max(60).optional(),fetchIntervalMs:R.number().int().min(100).max(6e4).optional()}},async({site:e,days:n,limit:r,minImpressions:i,brandTerms:a,verifyContent:o,verifyLimit:s,includeBrand:c,js:l,fetchConcurrency:u,fetchIntervalCap:d,fetchIntervalMs:f,refresh:p})=>{try{let m=await(t.quickWinsReport??GF)({site:e,days:n,limit:r,minImpressions:i,brandTerms:a,verifyContent:o,verifyLimit:s,includeBrand:c,js:O9(l,void 0),rate:L9({fetchConcurrency:u,fetchIntervalCap:d,fetchIntervalMs:f}),refresh:p});return E9(m.summary.verdict,m)}catch(e){return T9(e)}}),e.registerTool(`seo_internal_links`,{description:`Internal links to add across a site, or to one target URL, placed in real sentences`,inputSchema:{...k9([`site`,`refresh`]),targetUrl:R.string().url().refine(e=>/^https?:\/\//.test(e),`Use an HTTP(S) URL.`).optional(),maxPages:R.number().int().min(1).max(oL).optional(),startDate:R.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),endDate:R.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional()}},async({site:e,targetUrl:n,maxPages:r,startDate:i,endDate:a,refresh:o})=>{try{let s=await(t.internalLinksReport??bR)({site:e,targetUrl:n,maxPages:r,startDate:i,endDate:a,refresh:o},await x0({site:n??e,refresh:o}));return E9(s.summary.verdict,s)}catch(e){return T9(e)}}),e.registerTool(`seo_ctr_underperformers`,{description:`Find high-impression queries underperforming CTR expectations`,inputSchema:{...k9([`site`,`minImpressions`,`limit`,`includeBrand`,`refresh`]),site:R.string().trim().min(1),minImpressions:R.number().int().min(1).max(1e9).optional(),limit:R.number().int().min(1).max(100).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,minImpressions:n,limit:r,brandTerms:i,includeBrand:a,refresh:o})=>{try{let s=await(t.ctrUnderperformersReport??ZM)({site:e,minImpressions:n,limit:r,brandTerms:i,includeBrand:a,refresh:o});return E9(s.summary.verdict,s)}catch(e){return T9(e)}}),e.registerTool(`seo_query_cluster`,{description:`Cluster queries by token overlap`,inputSchema:{...k9([`site`,`includeBrand`,`minImpressions`,`limit`,`refresh`]),site:R.string().trim().min(1),scope:R.string().trim().min(1).max(2e3).optional(),minImpressions:R.number().int().min(1).max(1e9).optional(),limit:R.number().int().min(1).max(100).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,scope:n,brandTerms:r,includeBrand:i,minImpressions:a,limit:o,refresh:s})=>{try{let c=await(t.queryClusterReport??aB)({site:e,scope:n,brand:r?.[0],brandTerms:r,includeBrand:i,minImpressions:a,limit:o,refresh:s});return E9(c.summary.verdict,c)}catch(e){return T9(e)}})}const ste={"ai-referrals":{readOrder:[`dataStatus, range, methodology, and dataSource partialReasons`,`possiblyTruncated and per-query statuses`,`selection.landingPages before treating landingPages as complete`,`sources observedSessionSources for attribution evidence`],doNotClaim:[`An empty result is not proof that no AI system sent or cited the site.`,`Referral sessions did not necessarily cause conversions and are not all AI traffic.`,`totalUsers is not additive and must not be reconstructed by summing rows.`],verify:`Compare complete like-for-like Google Analytics periods and check whether high-session landing pages answer the referring context.`,related:[]},"audit-page":{readOrder:[`fetchDiagnostics, warnings, and the final fetched URL`,`observed page fields and structured-data findings`,`issues and recommendations`],doNotClaim:[`One page cannot support a sitewide conclusion.`,`Title pixel width is a review estimator, not a Google limit.`,`The fetched version is not proof that Google indexed that version.`],verify:`Re-fetch the URL after the edit and confirm the observed field changed.`,related:[{id:`redirect-trace`,reason:`Debugs the redirect chain.`},{id:`performance-audit`,reason:`Adds page speed evidence.`},{id:`content-optimization`,reason:`Builds a query-led brief.`}]},"audit-urls":{readOrder:[`requested versus attempted, fetched, failed, retained, and omitted counts`,`topFixes AND reviewObservations together; the two lists are the complete grouped issue inventory, so carry every group from both into findings`,`response evidence and issue summaries`,`requestEvidenceStatus, warnings, and caveats`],doNotClaim:[`A successful sample does not prove the same template works everywhere.`,`A failed request may be transient network, not a persistent defect.`,`A bounded audit is never complete site coverage.`],verify:`Re-run the identical URL list after deployment; a URL dropped from the request is not a verified fix.`,related:[{id:`audit-page`,reason:`Inspects one page in depth.`},{id:`site-crawl`,reason:`Discovers pages instead.`},{id:`redirect-trace`,reason:`Traces a redirecting URL.`}]},cannibalisation:{readOrder:[`dataStatus and both source.pageExposure and source.propertyDemand with validation counts and completeness`,`selection to see why groups were excluded or suppressed`,`per-page clicks, impressions, position, impression share, reviewContext, and HHI`,`priority.score and suggestedOwnerUrl`,`dataSource plus evidence.imports file dates, hashes, and row quality when the run used researchFiles`],doNotClaim:[`URL overlap is a review candidate, not proven harmful cannibalisation.`,`suggestedOwnerUrl is a low-confidence mechanical pick that requires intent review.`,`priority.score is a heuristic, not estimated click lift, and a partial source cannot support an all-clear.`,`Research-import rows are provider estimates that support multiple-ranking-URL claims only, not traffic or Search Console-verified cannibalisation.`],verify:`Compare intent and live SERPs for the overlapping URLs before consolidating anything.`,related:[{id:`query-clusters`,reason:`Groups related query themes.`},{id:`internal-links`,reason:`Clarifies link ownership.`},{id:`content-optimization`,reason:`Differentiates page intent.`}]},"content-optimization":{readOrder:[`sourceReport dataStatus, selection, benchmark.possiblyTruncated, and verification.status`,`summary.score and primaryIntent as heuristics`,`topActions separating technical-check and unverified from verified observations`,`intentMix and the source query metrics`],doNotClaim:[`estimatedClickLift and score are prioritisation heuristics, not forecasts or quality grades.`,`Query wording is not a content mandate.`,`Adding suggested wording is not guaranteed traffic.`],verify:`Fetch the page after the edit and confirm the missing answer block or clearer framing is present.`,related:[{id:`page-opportunities`,reason:`Adds query-level opportunities.`},{id:`internal-links`,reason:`Finds contextual links.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`}]},"crawler-rules":{readOrder:[`each rule id, title, and category`,`default severity as triage metadata`,`guidance metadata`],doNotClaim:[`Listing a rule does not mean the site triggered it or that the convention is a search-engine requirement.`,`Default severity is generic triage metadata, not actual priority.`,`Similarly named rules may not share source semantics.`],verify:`Pass the exact rule id to explain-crawl-issue, then check the matching issues in a site crawl.`,related:[{id:`explain-crawl-issue`,reason:`Returns the rule contract.`}]},"ctr-underperformers":{readOrder:[`dataStatus, range, source.completeness, possiblyTruncated, and validation counts`,`brand terms used, then selection before the queue; rows at average position 4 or worse belong to quick-wins`,`per-item query, URL, impressions, position, observed CTR, target CTR, benchmark source, and queryFlags`,`estimated shortfall`],doNotClaim:[`The shortfall is directional prioritisation math, not a traffic forecast.`,`Page-one average position hides day, device, geography, and result-feature variation.`,`A partial empty result is not an all-clear.`],verify:`Inspect the current SERP and displayed title link, then compare a complete later period after testing framing.`,related:[{id:`quick-wins`,reason:`Ranks position 4-10 opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`},{id:`content-optimization`,reason:`Builds a page brief.`}]},"decaying-pages":{readOrder:[`dataStatus, ranges, and source.completeness`,`current and previous fetched rows, caps, truncation, and invalid rows in selection`,`summary.observedRetainedQueryClickLoss versus the returned subset`,`per-item clicks, impressions, CTR, position, and signals`],doNotClaim:[`A diagnosis such as lost_position or lost_ctr labels correlated movement, not a cause.`,`Missing retained rows are not zero traffic.`,`Do not sum capped rows into a property-wide loss.`],verify:`Check deployments, live indexability, and SERP composition for the affected URLs before editing.`,related:[{id:`refresh-priorities`,reason:`Combines decline signals.`},{id:`segment-impact`,reason:`Shows where movement concentrates.`}]},"explain-crawl-issue":{readOrder:[`category, default severity, and why it matters`,`fix steps and ignored impact`,`verification method and agent hints`],doNotClaim:[`Guidance describes the checked condition, not a search-engine penalty or guaranteed ranking effect.`,`Default severity is generic prioritization metadata, not actual urgency.`,`The rule definition alone does not prove any page triggered it.`],verify:`Pair the definition with the matching issues from a site crawl and confirm the per-URL evidence.`,related:[{id:`crawler-rules`,reason:`Finds a rule id.`},{id:`top-fixes`,reason:`Ranks the fix queue.`}]},"index-coverage":{readOrder:[`sources completeness, rowLimit, rowLimitReached, date range, and invalid rows`,`retainedSearchVisibility and crawlableWithoutRetainedSearchVisibility`,`blockedOrNonIndexable, sitemapOnly, searchConsoleOnly, and templateReview`,`each group count, returned, and omitted`],doNotClaim:[`A page is not indexed because it had Search Analytics visibility, nor unindexed because no row appeared.`,`A missing Search Analytics row is not proof a page is unindexed.`,`Do not turn a limited or incomplete source into a whole-site coverage percentage.`],verify:`Run seo page --url on representative URLs to collect exact URL Inspection verdicts.`,related:[{id:`site-crawl`,reason:`Provides the source crawl.`}]},"internal-links":{readOrder:[`dataStatus, target verification, aliases, canonical, and technical signals`,`source completeness and selection attempted, checked, failed, unchecked, and exclusions`,`per-item exact versus lexical matches and linkEvidence`,`per-item placement: the sentence where a link fits, its anchors, and contentSimilarity`],doNotClaim:[`The live check stops at 40 source pages, so unchecked candidates can remain and absence is not proven.`,`Query overlap does not prove a link belongs or that adding one improves rankings.`,`Priority is a heuristic, not estimated impact.`,`Placement sentences, anchors and contentSimilarity are text heuristics; they do not prove the link helps a reader.`],verify:`Read the source passage, add one contextual link if the target is genuinely useful, and re-crawl to confirm it.`,related:[{id:`cannibalisation`,reason:`Checks URL overlap.`},{id:`content-optimization`,reason:`Builds a page brief.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"link-recovery":{readOrder:[`range and summary.checked with severity totals`,`per-item original and final URL, GSC metrics, issue lists, and redirect trace`,`chain status, final-page indexability, canonicals, and warnings`],doNotClaim:[`clicksAtRisk and impressionsAtRisk describe the checked period, not a forecast of loss or recovery.`,`Prior visibility orders the queue but does not prove fixing a URL restores traffic.`,`Failed checks or selection limits constrain coverage.`],verify:`Add one direct 301 to the closest equivalent destination only after confirming the page should still exist, then re-trace.`,related:[{id:`redirect-trace`,reason:`Traces one URL chain.`},{id:`decaying-pages`,reason:`Shows click declines.`},{id:`audit-urls`,reason:`Runs bounded checks.`}]},"page-opportunities":{readOrder:[`dataStatus, range, source.targetRowsFetched, selection, and benchmark`,`benchmark.possiblyTruncated`,`verification.status and reason`,`per-item query metrics, opportunity type, and benchmark and verification evidence`],doNotClaim:[`Only verified results support live-page coverage observations.`,`estimatedCtrClickShortfall is a directional calculation, not a click forecast.`,`summary.opportunities is a review queue, not a defect count, and partial data is not an all-clear.`],verify:`Inspect the live SERP and resolve any status or indexability contradiction before editing.`,related:[{id:`content-optimization`,reason:`Builds a page brief.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`internal-links`,reason:`Finds contextual links.`}]},"performance-audit":{readOrder:[`dataStatus, source, labDataStatus, and fieldDataStatus`,`Lighthouse score, lab metrics, and labInsights`,`CrUX fieldData.metrics with scope, formFactor, and collectionPeriod`,`fetch-fallback fields when source is fetch-fallback`],doNotClaim:[`Origin-level CrUX data is not page-level evidence.`,`A fetch-fallback duration is the local fetch workflow, not TTFB, LCP, CLS, TBT, or INP, and never earns a score.`,`Do not combine lab and field values into a new score, compare mobile with desktop as equal populations, or claim a ranking outcome.`],verify:`Reproduce the relevant lab issue and re-run the audit after the change.`,related:[{id:`audit-page`,reason:`Runs an on-page audit.`},{id:`site-crawl`,reason:`Builds the site inventory.`}]},"query-clusters":{readOrder:[`summary cluster and query counts, clicks, impressions, threshold, limit, and brand filtering`,`per-cluster member queries, pages, demand, and performance`,`each cluster recommendation`],doNotClaim:[`Token overlap does not prove shared intent, justify a new page, or establish that current URLs compete.`,`Page-two clusters do not claim a CTR-only click lift.`,`Queries below the threshold or outside the cap are outside the conclusion, not absent demand.`],verify:`Check whether a cluster maps to one intent before changing section structure or navigation.`,related:[{id:`cannibalisation`,reason:`Checks URL overlap.`},{id:`content-optimization`,reason:`Builds a page brief.`}]},"quick-wins":{readOrder:[`dataStatus, date range, source row cap, possiblyTruncated, selection.invalidRows, and filters`,`methodology and each item benchmark confidence before using targetCtr`,`estimatedCtrClickShortfall and priority`,`verification requested, attempted, verified, failed, and technical counts`],doNotClaim:[`estimatedCtrClickShortfall and priority score are heuristics, explicitly not estimated lift.`,`Average position is not a stable rank, and an unverified item cannot support a content-coverage conclusion.`,`Filtered or capped evidence is not an all-clear.`],verify:`Inspect the live SERP, test clearer snippet framing, then compare a later complete window.`,related:[{id:`ctr-underperformers`,reason:`Adds CTR peer evidence.`},{id:`page-opportunities`,reason:`Reviews one URL.`},{id:`striking-distance`,reason:`Finds rows near page one.`}]},"redirect-trace":{readOrder:[`chain in order with requested URL, status, Location, resolved next, and duration`,`finalUrl versus finalPage and summary.finalStatus`,`summary.issues`,`metaRobots, xRobotsTag, canonical, and warnings`],doNotClaim:[`The trace is one observation from the machine and time that ran it, and CDNs, geography, cookies, or later deploys can differ.`,`A canonical elsewhere or a 302 can be intentional.`,`JavaScript rendering affects final-page extraction, not the HTTP chain.`],verify:`Re-run the trace after deployment and confirm the intended destination and status.`,related:[{id:`link-recovery`,reason:`Prioritises search-value URLs.`},{id:`audit-page`,reason:`Audits the final page.`},{id:`audit-urls`,reason:`Runs bounded checks.`}]},"refresh-priorities":{readOrder:[`workflow steps and skipped states`,`per-item source, impactKind, score breakdown, date window, completeness, verification status, and rationale`,`the top few URLs manually`],doNotClaim:[`A click decline, low CTR, second-page position, and Google Analytics session signal have different semantics and are not interchangeable.`,`Missing Google Analytics or failed fetches stay unavailable, not zero-weight proof.`,`The score is not expected clicks, revenue, ranking lift, or causal confidence.`],verify:`Confirm query intent, current content, and internal links for the top URLs before choosing a bounded edit.`,related:[{id:`decaying-pages`,reason:`Shows click declines.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`second-page`,reason:`Finds rows near page one.`}]},"search-performance-overview":{readOrder:[`workflow envelope with summary, steps, actions, and output`,`report dataStatus, skipped sections, and partial reasons`,`priorities`,`nested anomaly, update, segment, decay, cannibalisation, striking-distance, and quick-win results`],doNotClaim:[`One complete section must not hide a failed or capped neighbour.`,`Sparse data may legitimately skip a section.`,`Update overlap, opportunity scores, average position, and timing are investigation signals, not causation or forecasts.`],verify:`Run the focused report named in actions and confirm affected URLs and provider dates before editing.`,related:[{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`striking-distance`,reason:`Finds rows near page one.`}]},"second-page":{readOrder:[`source completeness, date range, selection, methodology, provenance, and brand filtering`,`per-item impressions, clicks, CTR, and average position`,`the priority value`],doNotClaim:[`Average position is aggregated across searches, locations, devices, and time and is not an exact rank.`,`Retained limits mean the output is not a complete inventory.`,`Priority is a transparent heuristic, not expected click lift, and one row is not cannibalisation.`],verify:`Inspect the live page and search intent and confirm the query suits the URL before one defensible change.`,related:[{id:`striking-distance`,reason:`Covers positions 11-20.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"segment-impact":{readOrder:[`before, after, and rangeDays`,`dataStatus and source.before, source.after, and completeness for caps and truncation`,`selection invalid, duplicate, conflicting, matched, unmatched, returned, and limited rows`,`per-item clickDelta, impressionDelta, and positionDelta, then unmatchedSegments`],doNotClaim:[`A positive positionDelta is worse because a larger average position is lower in results.`,`unmatchedSegments are retained in one window only and are not gains from or losses to zero.`,`A limited or truncated result cannot support an inventory-wide winner or loser.`],verify:`Audit the top matched movers pages and query intent before drawing a segment conclusion.`,related:[{id:`traffic-anomaly`,reason:`Confirms movement first.`},{id:`decaying-pages`,reason:`Shows click declines.`},{id:`update-postmortem`,reason:`Frames movement around an update.`}]},"setup-check":{readOrder:[`ok`,`each checks entry status, distinguishing fail from warn, with detail and fix`,`generatedAt`],doNotClaim:[`A passing result means local prerequisites look present, not that a token is still accepted by Google or that the account can access a property.`,`Missing saved defaults are usually warnings because explicit parameters can replace them.`,`A setup pass is not evidence about rankings, indexing, or site health.`],verify:`Apply the fix on a failed check, re-run setup-check, then run a small read-only report for the intended property.`,related:[{id:`search-performance-overview`,reason:`First report once setup passes.`}]},"site-crawl":{readOrder:[`config.strategy first; use health before full on large or unknown sites`,`status, requestEvidenceStatus, attempted and fetched counts, failures, retained pages, and pageLimitReached`,`access crawler identity, blockedRequests, provider counts, and samples`,`data-source states`,`topFixes AND reviewObservations together; the two lists are the complete grouped issue inventory, so carry every group from both into findings`,`warnings and caveats, then opt-in pages, requests, and issues`],doNotClaim:[`A partial or capped crawl cannot support an all-clear or a definitive zero.`,`A crawl is not an index, traffic source, or guarantee of complete site coverage.`,`A health pass checks response access, status, and redirects only. It does not download page bodies or evaluate content, metadata, canonicals, indexability directives, internal links, or rendered HTML. For full crawls, state when JavaScript rendering was disabled.`,`A User-Agent can be spoofed. Never ask the user for a broad firewall bypass based on crawler identity alone.`],verify:`Re-run the same health configuration first. Use a full crawl only when the health evidence is clean and the question needs page-body analysis.`,related:[{id:`top-fixes`,reason:`Ranks the fix queue.`},{id:`index-coverage`,reason:`Checks coverage signals.`}]},"striking-distance":{readOrder:[`range, rangeDays, dataStatus, and source`,`source.possiblyTruncated and retained-row completeness`,`selection invalid, out-of-range, branded, below-threshold, eligible, returned, and limited`,`methodology, then per-item metrics and contentVerification`],doNotClaim:[`The 11-20 band is a heuristic boundary and average position is not a literal second results page.`,`Unverified or failed pages keep lower confidence.`,`The priority score is not expected traffic or ranking lift.`],verify:`Audit a small number of high-impression candidates and fix verified technical problems first.`,related:[{id:`second-page`,reason:`Covers positions 10-20.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"top-fixes":{readOrder:[`dataSources, summary, warnings, and caveats`,`per-item rule id, affected count, sample URLs, scoreFactors, and whyThisRanks`,`effort, fix guidance, and verification`],doNotClaim:[`Rank means highest among retained eligible findings, not globally highest, because the crawl or category may be capped.`,`Missing provider joins stay unavailable and a numeric zero is meaningful only when the source is complete.`,`This is not a forecast of rankings, traffic, or revenue.`],verify:`Repeat the same crawl configuration after implementation and confirm the rule no longer triggers.`,related:[{id:`explain-crawl-issue`,reason:`Explains the rule.`},{id:`site-crawl`,reason:`Provides the source crawl.`}]},"traffic-anomaly":{readOrder:[`coverage with requested dates, expected versus observed days, missing days, invalid rows, and status`,`anomalies with metric, baseline and comparison dates, percentChange, zScore, and significanceMethod`,`direction and significant`,`detection, changeDate and the detection thresholds: a step change compares every day before its change date with every day from it`],doNotClaim:[`Statistical unusualness does not identify a cause, diagnose a defect, or prove an external event affected the property.`,`A null percentage from a zero baseline differs from zero change.`,`Partial coverage can change the baseline.`],verify:`If movement is significant and coverage is adequate, run segment-impact for pages and queries.`,related:[{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`update-correlation`,reason:`Adds update timing.`},{id:`decaying-pages`,reason:`Shows click declines.`}]},"update-correlation":{readOrder:[`classification with attribution and confidence, returned as not-established and none`,`anomalies, overlappingUpdates, and confounders`,`evidence, caveats, and source`],doNotClaim:[`Overlap cannot show the update caused a gain or loss even with large movement and no other recorded change.`,`update-overlap-without-significant-movement is not an impact result and no-update-overlap does not explain remaining movement.`,`Temporal overlap is not a penalty, reward, or confirmed effect.`],verify:`Test saved deploys, redirects, and content changes that overlap the window before attributing movement.`,related:[{id:`update-postmortem`,reason:`Maps winners and losers.`},{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`traffic-anomaly`,reason:`Confirms movement first.`}]},"update-postmortem":{readOrder:[`workflow step statuses, finalized date windows, and source completeness`,`failed measurements, retained limits, and caveats`,`update, insights, templateMovement, and segments`],doNotClaim:[`The cause remains not established even when dates overlap.`,`Retained winners and losers are not a complete inventory when sources are capped or filtered.`,`Do not claim update causation, recovery probability, or future traffic.`],verify:`Inspect representative URLs from affected segments and reproduce technical changes before any rollback.`,related:[{id:`update-correlation`,reason:`Adds update timing.`},{id:`segment-impact`,reason:`Shows where movement sits.`}]}},B9={"ai-referrals":{name:`AI referral traffic`,description:`Find visits from known AI products in Google Analytics and see a ranked, bounded set of landing pages that received them.`,useWhen:[`You want measured AI referral traffic from Google Analytics.`,`You need the landing pages and sources behind those visits.`],avoidWhen:[`Google Analytics is not connected or does not track the site.`,`You want to measure citations or unclicked mentions inside AI answers.`],outcome:`A source and landing-page breakdown of identifiable AI referrals.`},"audit-page":{name:`Single-page SEO audit`,description:`Check one URL for response, indexability, metadata, headings, links, and page content evidence.`,useWhen:[`One page needs a technical review before you change it.`,`A broader report points to a specific URL.`],avoidWhen:[`You need to discover issues across a whole site.`,`The page requires a logged-in browser session.`],outcome:`A page-level audit that separates observed evidence from review advice.`},"audit-urls":{name:`Selected URL audit`,description:`Audit a specific list of pages without crawling the rest of the site.`,useWhen:[`You already know which URLs need checking.`,`You want a repeatable pre-release or post-release check for key pages.`],avoidWhen:[`You need the crawler to discover pages for you.`,`You only need a deep review of one page.`],outcome:`Consistent technical checks for each supplied URL.`},cannibalisation:{name:`Query and URL overlap`,description:`Find search queries that appear across several URLs and decide whether the overlap needs attention.`,useWhen:[`Several pages may be competing for the same search intent.`,`You want query-level evidence before merging or redirecting pages.`],avoidWhen:[`You plan to treat every multi-URL query as a problem.`,`The site has too little Search Console data for meaningful overlap.`],outcome:`A ranked review list of queries, URLs, and their share of search exposure.`},"content-optimization":{name:`Search-led content brief`,description:`Turn a page and its Search Console queries into a practical brief for improving relevance and coverage.`,useWhen:[`An existing page has search demand but needs a clearer improvement plan.`,`You want first-party query evidence beside the current page content.`],avoidWhen:[`The URL has no useful Search Console history.`,`You want generated copy or a traffic forecast.`],outcome:`A page brief with query evidence, content checks, and specific review points.`},"crawler-rules":{name:`Crawler rule catalog`,description:`Find the available technical check IDs and the evidence each crawler rule looks for.`,useWhen:[`You need a valid rule ID for another crawl report.`,`You want to see which technical checks are available by category.`],avoidWhen:[`You need affected pages or live crawl results.`],outcome:`A searchable catalog of crawler rules, severity, and guidance.`},"ctr-underperformers":{name:`CTR underperformers`,description:`Find high-impression queries whose click-through rate trails comparable queries at similar positions.`,useWhen:[`You want title or snippet review candidates backed by Search Console data.`,`You need to compare CTR fairly across similar average positions.`],avoidWhen:[`You want a promised click uplift.`,`The comparison groups have too little data.`],outcome:`A ranked list of query and page pairs with CTR comparison evidence.`},"decaying-pages":{name:`Pages losing search clicks`,description:`Find pages and queries with meaningful click declines across comparable Search Console periods.`,useWhen:[`You want to investigate a sustained organic search decline.`,`You need the pages and queries behind lost clicks.`],avoidWhen:[`The newer period is incomplete or not comparable.`,`You want to assume every decline is caused by old content.`],outcome:`A ranked investigation list with before-and-after search evidence.`},"explain-crawl-issue":{name:`Explain a crawl issue`,description:`Explain what one crawler rule means, why it may matter, and how to verify a fix.`,useWhen:[`A crawl returned a rule ID you do not recognize.`,`You need implementation and verification guidance before creating work.`],avoidWhen:[`You need the URLs affected by the rule.`,`You have not selected a valid crawler rule ID.`],outcome:`A plain-English rule explanation with fix and verification steps.`},"index-coverage":{name:`Index coverage signals`,description:`Compare the pages your site exposes with pages that had Google Search visibility, then choose representative URLs for URL Inspection.`,useWhen:[`You need to find crawlable pages that did not appear in the Search Console results returned for the selected period.`,`You want a focused review list before spending URL Inspection quota.`],avoidWhen:[`You need proof that a URL is indexed or excluded. Use URL Inspection for that URL.`,`The site blocks crawlers, so the crawl cannot list its pages.`],outcome:`Cross-source URL groups with clear evidence limits and a representative review queue for URL Inspection.`},"internal-links":{name:`Internal links`,description:`Crawl a site and find the internal links it is missing, across the whole site or to one target URL, each placed in a real sentence with a real phrase as anchor text.`,useWhen:[`Pages that belong together do not link to each other.`,`A target page needs more contextual links from the rest of the site.`],avoidWhen:[`You want links added automatically.`,`The site cannot be crawled from this machine.`],outcome:`Links to add with the source sentence and anchor, judged by Jev when a TypeSafe key is set, plus orphan and weakly linked pages.`},"link-recovery":{name:`Recover broken search-value URLs`,description:`Find URLs that previously earned search clicks but now fail, redirect poorly, or block indexing.`,useWhen:[`You suspect valuable URLs broke during a migration or release.`,`You want to prioritize technical recovery using Search Console evidence.`],avoidWhen:[`You want a backlink report.`,`You have no Search Console page history for the site.`],outcome:`A ranked recovery list with current URL checks and prior search value.`},"page-opportunities":{name:`Opportunities for one page`,description:`Find Search Console queries and page evidence that point to useful improvements for one URL.`,useWhen:[`You want to improve an existing page using its own search demand.`,`You need query themes and page checks in one result.`],avoidWhen:[`The page has no useful Search Console data.`,`You want a guaranteed traffic gain.`],outcome:`A ranked page improvement list tied to real queries and current content.`},"performance-audit":{name:`Page performance audit`,description:`Run Lighthouse lab checks and add CrUX field Core Web Vitals when that data is available.`,useWhen:[`You need actionable performance diagnostics for a page.`,`You want lab findings kept separate from real-user field data.`],avoidWhen:[`You want Lighthouse scores presented as field Core Web Vitals.`,`The page cannot be fetched from the local machine.`],outcome:`Lab diagnostics plus clearly labelled field metrics when available.`},"query-clusters":{name:`Search query clusters`,description:`Group related Search Console queries so repeated demand themes are easier to review.`,useWhen:[`A large query list needs a clearer topic structure.`,`You want to find repeated wording within a site section.`],avoidWhen:[`You need semantic or intent classification beyond shared query terms.`,`You want clusters turned into new pages automatically.`],outcome:`Stable query groups with the search demand behind each theme.`},"quick-wins":{name:`Page-one CTR opportunities`,description:`Find page-one query and URL pairs whose CTR deserves a closer look.`,useWhen:[`You want high-impression title and snippet review candidates.`,`You need page-one opportunities ranked from Search Console data.`],avoidWhen:[`You want a promised click gain.`,`You plan to treat a CTR heuristic as a Google requirement.`],outcome:`A ranked review queue with CTR, position, impressions, and comparison evidence.`},"redirect-trace":{name:`Redirect trace`,description:`Follow every redirect hop and check the final page, indexability, and canonical signals.`,useWhen:[`A URL redirects unexpectedly or through several hops.`,`You need to verify the final destination after a migration.`],avoidWhen:[`You need to discover redirect issues across a whole site.`,`The URL requires a signed-in browser session.`],outcome:`The complete redirect chain with final response and page checks.`},"refresh-priorities":{name:`Content refresh priorities`,description:`Combine search declines and near-term opportunities into a ranked content review queue.`,useWhen:[`You need to decide which existing pages to review first.`,`You want several Search Console signals ranked in one queue.`],avoidWhen:[`You need a technical crawl plan.`,`You want the ranking treated as a traffic forecast.`],outcome:`A focused list of pages and queries to investigate next, with reasons.`},"search-performance-overview":{name:`Search performance overview`,description:`Find where Google Search performance changed and choose the next focused report to inspect it.`,useWhen:[`You are starting an investigation and do not yet know which pages or queries moved.`,`You want one view of declines, gains, overlap, and near-term opportunities.`],avoidWhen:[`You already know the exact question and can run a focused report.`,`You need a technical crawl without Search Console analysis.`],outcome:`A clear search performance summary with a short list of next reports.`},"second-page":{name:`Second-page opportunities`,description:`Find URLs averaging positions 11 to 20 and see the queries behind each opportunity.`,useWhen:[`You want existing pages that may deserve closer review near page one.`,`You need page-level evidence across all matching queries.`],avoidWhen:[`You want average position treated as a fixed rank.`,`You need proof that a change will move the page to page one.`],outcome:`A ranked URL list with query, click, impression, and position evidence.`},"segment-impact":{name:`Search impact by segment`,description:`Compare page or query groups across equal periods to find which parts of a site moved.`,useWhen:[`A traffic change may be concentrated in one directory, page type, or query group.`,`You need to separate broad movement from a local segment issue.`],avoidWhen:[`The periods are incomplete or not comparable.`,`Missing Search Console rows would be mistaken for zero activity.`],outcome:`A segment comparison showing where clicks and impressions changed.`},"setup-check":{name:`Check local setup`,description:`Check Google login, scopes, local configuration, and saved defaults before running reports.`,useWhen:[`Authentication or site selection is failing.`,`You want to verify the local setup before investigating report errors.`],avoidWhen:[`You need SEO findings rather than a setup check.`],outcome:`A local setup status with the exact problems that need fixing.`},"site-crawl":{name:`Sitemap health pass and technical site crawl`,description:`Start with a lightweight sitemap health pass, then run a full technical crawl only when page bodies and content-level evidence are needed.`,useWhen:[`You need a fast first check of sitemap URLs, statuses, redirects, robots decisions, or access blocks.`,`You need to discover technical issues across linked pages.`,`You want a crawl snapshot for later filtering or comparison.`],avoidWhen:[`You only need to check one page or a known URL list.`,`Do not run a full crawl on a large or unknown site before health=true, or when important content requires browser rendering that is not enabled.`],outcome:`A fast sitemap response gate or a full crawl summary with page evidence, technical findings, crawler identity and access guidance.`},"striking-distance":{name:`Queries near page one`,description:`Find Search Console query and page pairs averaging positions 11 to 20.`,useWhen:[`You want existing search demand close to page one.`,`You need a compact list of queries and URLs for content review.`],avoidWhen:[`You want average position treated as an exact daily rank.`,`You need a promised ranking or click gain.`],outcome:`A ranked list of near-page-one query and URL pairs with search evidence.`},"top-fixes":{name:`Top technical SEO fixes`,description:`Turn crawl findings into a short, ranked queue of technical issues to investigate first.`,useWhen:[`A crawl contains too many findings to review at once.`,`You need representative URLs and reasons for the highest priorities.`],avoidWhen:[`You need every affected URL for one rule.`,`You plan to treat rank as proof of business impact.`],outcome:`A focused technical fix queue with issue evidence and example URLs.`},"traffic-anomaly":{name:`Unusual search traffic changes`,description:`Find recent clicks or impressions that moved beyond the site's normal Search Console pattern.`,useWhen:[`You want an early signal of an unusual search change.`,`You need to know whether recent movement stands out from normal variation.`],avoidWhen:[`There is too little history for a useful baseline.`,`You want the report to identify the cause of the change.`],outcome:`A statistical movement signal with the dates, baseline, and limits shown.`},"update-correlation":{name:`Google update correlation`,description:`Compare search movement dates with official Google ranking update windows.`,useWhen:[`A traffic change overlaps a confirmed Google ranking update.`,`You need a timeline before investigating affected pages and queries.`],avoidWhen:[`You want overlap presented as proof of causation.`,`The traffic window does not cover the update dates.`],outcome:`A traffic and update timeline with overlaps clearly labelled as correlation.`},"update-postmortem":{name:`Google update impact review`,description:`Find the pages and queries that gained or lost around a confirmed Google ranking update.`,useWhen:[`You need winners and losers around a known update window.`,`You want to compare affected segments and known site changes.`],avoidWhen:[`You want the report to claim the update caused every change.`,`The comparison periods are incomplete or contain major unrecorded changes.`],outcome:`A post-update review of winners, losers, confounders, and next checks.`}};function V9(e){let t=B9[e],n=ste[e];if(t&&n)return{...t,...n}}function cte(e){e.registerTool(`seo_audit_page`,{description:`Run a single-page technical and content audit`,inputSchema:{url:R.string().url(),site:R.string().optional(),js:R.boolean().optional(),refresh:R.boolean().optional()}},async({url:e,site:t,js:n,refresh:r})=>{try{let i=await VC({url:e,site:t,js:O9(n,`auto`),refresh:r});return E9(`Audit complete for ${e}. Found ${i.issues.length} issues.`,i)}catch(e){return T9(e)}})}const lte=k9([`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]);function ute(e){return{verifyContent:e.verifyContent,verifyLimit:e.verifyLimit,js:O9(e.js,void 0),rate:L9({fetchConcurrency:e.fetchConcurrency,fetchIntervalCap:e.fetchIntervalCap,fetchIntervalMs:e.fetchIntervalMs}),refresh:e.refresh}}function dte(e){e.registerTool(`seo_second_page`,{description:`Find URLs with GSC average position above 10 through 20 and return evidence-grounded investigation prompts`,inputSchema:{...k9([`site`,`range`,`minImpressions`,`limit`,`includeBrand`]),...lte,range:R.number().int().min(1).max(548).optional(),minImpressions:R.number().int().min(0).max(1e9).optional(),limit:R.number().int().min(1).max(100).optional(),verifyLimit:R.number().int().min(0).max(100).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:R.number().int().min(1).max(16).optional(),fetchIntervalCap:R.number().int().min(1).max(60).optional(),fetchIntervalMs:R.number().int().min(100).max(6e4).optional()}},async({site:e,range:t,minImpressions:n,limit:r,includeBrand:i,brandTerms:a,...o})=>{try{let s=await JB({site:e,range:t,minImpressions:n,limit:r,includeBrand:i,brandTerms:a,...ute(o)});return E9(s.summary.verdict,s)}catch(e){return T9(e)}})}function fte(e){cte(e),dte(e)}function H9(e){let t=CV(e),n=w9({...e,presentation:t});return E9(e.summary,n,{markdown:wV(e)})}function U9(e){e.registerTool(`seo_workflow_diagnose_property`,{description:`Run the full agent workflow for property diagnosis and next actions`,inputSchema:{...k9([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`refresh`])}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,refresh:a})=>{try{return H9(await mV({site:e,days:t,recentDays:n,limit:r,includeBrand:i,refresh:a}))}catch(e){return T9(e)}}),e.registerTool(`seo_workflow_update_postmortem`,{description:`Run winner/loser postmortem analysis for recent Google update exposure`,inputSchema:{...k9([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`refresh`]),knownConfounders:R.array(R.string()).optional()}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,knownConfounders:a,refresh:o})=>{try{return H9(await eH({site:e,days:t,recentDays:n,limit:r,includeBrand:i,knownConfounders:a,refresh:o}))}catch(e){return T9(e)}}),e.registerTool(`seo_workflow_refresh_priorities`,{description:`Rank decay, striking-distance, quick-win, cannibalisation, and diagnosis signals into an action queue`,inputSchema:{...k9([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`refresh`]),googleAnalyticsPropertyId:R.string().optional()}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,googleAnalyticsPropertyId:a,verifyContent:o,verifyLimit:s,refresh:c})=>{try{return H9(await LV({site:e,days:t,recentDays:n,limit:r,includeBrand:i,googleAnalyticsPropertyId:a,verifyContent:o,verifyLimit:s,refresh:c}))}catch(e){return T9(e)}})}const pte=[`ai-search`,`crawl`,`diagnosis`,`monitoring`,`opportunities`,`reporting`,`setup`,`workflows`],mte=[],hte=[{category:`setup`,register:R9,names:[`seo_doctor`]},{category:`diagnosis`,register:R9,names:[`seo_segment_impact`,`seo_striking_distance`,`seo_traffic_anomaly`,`seo_update_correlate`]},{category:`opportunities`,register:ote,names:[`seo_cannibal`,`seo_ctr_underperformers`,`seo_decaying`,`seo_internal_links`,`seo_query_cluster`,`seo_quick_wins`]},{category:`ai-search`,register:ete,names:[`seo_ai_referrals`,`seo_content_optimization`,`seo_page_opportunities`,`seo_performance_audit`]},{category:`crawl`,register:tte,names:[`seo_audit_urls`,`seo_crawl_site`,`seo_explain_issue`,`seo_list_rules`,`seo_top_fixes`]},{category:`monitoring`,register:nte,names:[`seo_index_coverage`,`seo_link_recover`,`seo_redirect_trace`]},{category:`reporting`,register:fte,names:[`seo_audit_page`,`seo_second_page`]},{category:`workflows`,register:U9,names:[`seo_workflow_diagnose_property`,`seo_workflow_refresh_priorities`,`seo_workflow_update_postmortem`]}],gte={cannibal:`cannibalisation`,decaying:`decaying-pages`,"crawl-site":`site-crawl`,"link-recover":`link-recovery`,"query-cluster":`query-clusters`,"workflow-refresh-priorities":`refresh-priorities`,"workflow-update-postmortem":`update-postmortem`,"workflow-diagnose-property":`search-performance-overview`,doctor:`setup-check`,"update-correlate":`update-correlation`,"list-rules":`crawler-rules`,"explain-issue":`explain-crawl-issue`};function _te(e){let t=e.replace(/^seo_/,``).replaceAll(`_`,`-`);return gte[t]??t}function vte(e,t){return e.id<t.id?-1:+(e.id>t.id)}function yte(e){let t=/* @__PURE__ */ new Map;return e({registerTool(e,n,r){t.set(e,{inputSchema:n.inputSchema,handler:r})}}),t}function bte(e){return e instanceof R.ZodObject?e:R.strictObject(e??{})}function xte(){let e=/* @__PURE__ */ new Map,t=mte.map(e=>{let t=V9(e.id);if(!t)throw Error(`MCP report registry is missing guidance for ${e.id}.`);return{...e,...t}});for(let n of hte){let r=e.get(n.register);r||(r=yte(n.register),e.set(n.register,r));for(let e of n.names){let i=r.get(e);if(!i)throw Error(`MCP report registry references missing tool ${e}.`);let a=_te(e),o=V9(a);if(!o)throw Error(`MCP report registry is missing guidance for ${a}.`);t.push({id:a,category:n.category,...o,inputSchema:bte(i.inputSchema),handler:i.handler})}}return t.sort(vte)}const W9=xte(),Ste=new Set(W9.map(e=>e.id)),G9=Object.keys(B9).filter(e=>!Ste.has(e));if(G9.length>0)throw Error(`MCP report guidance references unknown reports: ${G9.join(`, `)}.`);const Cte=new Map(W9.map(e=>[e.id,e]));function K9(e){return W9.filter(t=>!e||t.category===e).map(({id:e,name:t,description:n,category:r})=>({id:e,category:r,name:t,description:n}))}function wte(e){return Cte.get(e)}function Tte(e){return e.issues.map(e=>`${e.path.length>0?e.path.join(`.`):`input`}: ${e.message}`).join(`; `)}const q9={"affected-urls":`seo crawl`,"agent-readiness":null,"ai-mention-research":null,"ai-prompt-observations":null,"ai-readiness":null,"ai-search-scorecard":null,"bing-webmaster-overview":null,"community-intent":null,"compare-crawls":`seo crawl`,"competitive-opportunities":`seo research`,"competitor-keyword-gap":`seo research competitors`,"crawl-diff":`seo crawl`,"crawl-history":`seo crawl`,"crawl-report":`seo crawl`,"domain-overview":`seo research ranked_keywords`,"domain-rating":`seo research`,"entity-readiness":null,"generate-llms-txt":null,"geo-gaps":null,"index-coverage-plan":`seo index`,"index-monitor":`seo index`,"index-watch":`seo page --url <url>`,"keyword-metrics":`seo research keyword_metrics`,"keyword-opportunities":`seo research`,"keyword-research":`seo research keyword_metrics`,"link-evidence":`seo research backlinks`,"llms-txt-audit":null,"local-search-demand":null,"measure-change":`seo compare --date <date>`,"monthly-action-plan":`seo report`,"monthly-report":`seo report`,"narrative-report":`seo report`,"okf-build":null,"okf-validate":null,"pseo-audit":null,"pseo-opportunities":null,"pseo-patterns":null,"rank-tracking":null,"ranked-keywords":`seo research ranked_keywords`,"ranking-pages":`seo research ranked_keywords`,"saved-keywords":null,"seo-to-ai-query":null,"serp-competitors":`seo research competitors`,"serp-results":`seo research serp`,"server-log-analysis":null,"technical-watch":`seo crawl`},Ete={cannibalization:`cannibalisation`,"content-decay":`decaying-pages`,"low-ctr":`ctr-underperformers`,"traffic-drop":`traffic-anomaly`};function J9(e){let t=Ete[e]??e;if(Object.hasOwn(q9,t)){let e=q9[t];throw new P(`INVALID_INPUT`,e?`The ${t} report was removed. Use \`${e}\` instead.`:`The ${t} report was removed. Run \`seo help\` for the commands.`)}let n=wte(t);if(!n)throw new P(`INVALID_INPUT`,`Unknown report: ${t}. Reports: ${K9().map(e=>e.id).join(`, `)}.`);return n}function Dte(e){return K9(e)}function Ote(e){let t=J9(e);return{id:t.id,category:t.category,name:t.name,description:t.description,useWhen:t.useWhen,avoidWhen:t.avoidWhen,outcome:t.outcome,readOrder:t.readOrder,doNotClaim:t.doNotClaim,verify:t.verify,related:t.related,agentWorkflow:{actionView:{mcp:{id:t.id,view:`actions`},cli:`seo reports run ${t.id} --params '<json>' --actions-only --json`},readOrder:[`findings.coverage and report-level caveats`,`findings.items in returned priority order`,`inventories row by row when present`],completion:`Use each finding type and its allowed outcomes. Fix items support fixed, deferred, or not-needed. Review items support changed, no-change, or deferred. Verify changed items and rerun this report before closing them.`},inputSchema:R.toJSONSchema(t.inputSchema)}}async function Y9(e,t={},n={}){let r=J9(e),i=r.inputSchema.safeParse(t);if(!i.success)throw new P(`INVALID_INPUT`,`Invalid parameters for ${e}: ${Tte(i.error)}`);let a=await r.handler(i.data);if(a.isError||!a.structuredContent)return a;let o={reportId:r.id,verify:r.verify},s=n.view===`actions`?hr(a.structuredContent,o):a.structuredContent;return{...a,structuredContent:w9(s)}}const X9={readOnlyHint:!0,destructiveHint:!1,openWorldHint:!0};function Z9(e){return{content:[{type:`text`,text:e}]}}async function kte(e,t,n,r){let i=n?m$(e,{section:typeof t.section==`string`?t.section:void 0,action:typeof t.action==`string`?t.action:void 0}):null;i&&n&&aa(i,n());try{let e=await r();return i&&n&&(e.isError?sa(i,e.structuredContent?.error,n()):oa(i,n())),e}catch(e){let t=T0(e);return i&&n&&sa(i,t,n()),T9(t)}}async function Q9(e,t,n,r){let i=await kte(e,t,n,r),a=v4();return a?{...i,content:[...i.content,{type:`text`,text:a}]}:i}function Ate(e,t={}){let n={deps:m0({call:$$}),resolveSite:e=>C0(e),keys:b0,refreshClicky:S0,drKey:null,researchStore:h0(),installedSerp:h2,accounts:y0,signIn:Es.signIn,connect:"run `seo login` to use your seoskill.dev account (Google, Bing, Index My Site and keys in one place), or `seo auth login`, `seo providers bing connect`, `seo providers indexmysite connect` and `seo providers dataforseo connect` or `seo providers ahrefs connect` on this machine only.",readFiles:e=>L0(e)};for(let r of Y$)e.registerTool(r.name,{title:r.title,description:r.description,inputSchema:(r.localInput??r.input).shape,annotations:K$(r)},async e=>Q9(r.command,e,t.telemetry,async()=>Z9((await Z$(r,n,e,!0)).text)));e.registerTool(`seo_crawl`,{title:`Crawl a site`,description:`Crawls a site from this machine and returns technical issues and the URLs they affect. The crawl is saved locally for later reports.`,inputSchema:{url:R.url()},annotations:X9},async({url:e})=>Q9(`crawl`,{},t.telemetry,()=>Y9(`site-crawl`,{url:e,saveReport:!0}))),e.registerTool(`seo_internal_links`,{title:`Internal links`,description:`Internal links to add, crawled from this machine. Send site to audit a whole site, or url to find links to one page. Each link names a real sentence on the source and a real phrase from it as anchor text. With a TypeSafe key (TYPESAFE_API_KEY or the seoskill.dev account), Jev classifies pages and judges each link; without one the result says Jev was not used. Search Console query overlap is added when this login has the property.`,inputSchema:{site:R.string().min(1).optional().describe(`Site to audit: a domain, URL or Search Console property.`),url:R.url().optional().describe(`One page to find links to.`),max_pages:R.number().int().min(1).max(oL).optional().describe(`site only: pages to crawl, 500 by default, up to 5,000.`),start_date:R.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD for Search Console. Optional; send with end_date.`),end_date:R.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD. Optional; send with start_date.`),detail:R.enum([`summary`,`rows`,`full`]).default(`summary`).describe(`summary first. rows: the next page of links. full: every field as JSON.`),offset:R.number().int().min(0).default(0).describe(`rows only: the first link to return.`)},annotations:X9},async({site:e,url:n,max_pages:r,start_date:i,end_date:a,detail:o,offset:s})=>Q9(`internal-links`,{},t.telemetry,async()=>{try{if(!!e==!!n)throw new P(`INVALID_INPUT`,`Send site to audit a whole site, or url to find links to one page.`);let t=n??e;return Z9(SJ(await bR({site:t,targetUrl:n,maxPages:r,startDate:i,endDate:a},await x0({site:t})),{detail:o,offset:s,more:(t,i)=>$$(`internal-links`,{...n?{url:n}:{site:e},...r?{max_pages:r}:{},detail:t,offset:i})}))}catch(e){return T9(T0(e))}}))}function jte(){for(let e of[`../skills/seo/SKILL.md`,`../../../skills/seo/SKILL.md`])try{return Ut(new URL(e,import.meta.url),`utf8`)}catch{}return null}function $9(e={}){let t=new Gee({...Q$,title:`SEO Skill (local)`,description:`${Q$.description} Runs on your machine.`,version:Ai},{capabilities:{logging:{}},instructions:`SEO Skill reads the person's own Search Console, Google Analytics, Bing Webmaster Tools, Clicky, Simple Analytics and optional keyword accounts, and returns facts with their dates and limits. It gives no advice.
|
|
477
|
+
`}var Zee=class{constructor(e=jn.stdin,t=jn.stdout,n){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}},this._onerror=e=>{this.onerror?.(e)},this._readBuffer=new Jee({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=Xee(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function x9(e){return Buffer.byteLength(JSON.stringify(e))}function S9(e){let t=x9(e);for(;e.outputBudget.returnedBytes!==t;)e.outputBudget.returnedBytes=t,t=x9(e);return t}function C9(e,t,n,r){if(typeof e==`string`)return e.length<=n.stringLimit?e:(r.push({path:t,kind:`string`,available:e.length,returned:n.stringLimit}),`${e.slice(0,Math.max(1,n.stringLimit-3)).trimEnd()}...`);if(Array.isArray(e))return e.length>n.arrayLimit&&r.push({path:t,kind:`array`,available:e.length,returned:n.arrayLimit}),e.slice(0,n.arrayLimit).map((e,i)=>C9(e,`${t}[${i}]`,n,r));if(!e||typeof e!=`object`)return e;let i={};for(let[a,o]of Object.entries(e)){let e=t?`${t}.${a}`:a;!t&&n.preserveAgentContract&&(a===`findings`||a===`inventories`)?i[a]=o:a===`markdown`?r.push({path:e,kind:`field`}):i[a]=C9(o,e,n,r)}return i}function w9(e,t={}){let n=t.maxBytes??98304,r=e,i=e.findings,a=i?.schemaVersion===1&&i.scope===`returned-report`&&Array.isArray(i.items),o=x9(r),s={...r,outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:!1,omissions:[],omissionsTruncated:!1,detail:`The complete structured report fits within the agent output budget.`}};if(S9(s)<=n)return s;let c=[{arrayLimit:10,stringLimit:4e3,preserveAgentContract:a},{arrayLimit:5,stringLimit:2e3,preserveAgentContract:a},{arrayLimit:3,stringLimit:1e3,preserveAgentContract:a},{arrayLimit:1,stringLimit:500,preserveAgentContract:a}];for(let e of c){let t=[],i={...C9(r,``,e,t),outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:t.length>0,arrayLimit:e.arrayLimit,stringLimit:e.stringLimit,omissions:t.slice(0,100),omissionsTruncated:t.length>100,detail:`Counts, provenance, caveats, and compact evidence are retained. Run the related focused report when more rows are needed.`}};if(S9(i)<=n)return i}let l={...hr(r),outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:!0,fallback:!0,omissionsTruncated:!1,omissions:[{path:`reportBody`,kind:`field`}],detail:`The detailed report exceeded the budget, so the complete findings and retained inventories are returned instead.`}};if(S9(l)<=n)return l;throw Error(`The complete findings and inventories exceed the ${n}-byte agent output budget. Run a focused report with a narrower bounded scope; actionable rows were not truncated.`)}function T9(e){let t=Se(e);return{content:[{type:`text`,text:`Error: ${t.error.message}`}],structuredContent:t,isError:!0}}function E9(e,t,n={}){return{content:[{type:`text`,text:n.markdown??e}],structuredContent:t}}function Qee(e){e.registerTool(`seo_list_providers`,{description:`List provider packages installed through the seo CLI. Package installation requires human approval in a terminal.`,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async()=>{try{let e=await q0();return E9(`${e.installed.length} provider packages are installed.`,e)}catch(e){return T9(e)}}),e.registerTool(`seo_describe_provider`,{description:`Describe one installed provider, its shared capabilities, and its agent action schemas`,inputSchema:{id:R.string().trim().min(1).max(64)},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async({id:e})=>{try{let t=await J0(e);return E9(`${t.id}: ${t.description}`,t)}catch(e){return T9(e)}}),e.registerTool(`seo_run_provider`,{description:`Run one action from an installed provider after reading its schema with seo_describe_provider`,inputSchema:{id:R.string().trim().min(1).max(64),action:R.string().trim().min(1).max(64),account:R.record(R.string(),R.string()).optional(),params:R.record(R.string(),R.unknown()).optional(),refresh:R.boolean().optional()},annotations:{readOnlyHint:!1,destructiveHint:!1}},async({id:e,action:t,account:n,params:r,refresh:i})=>{try{let a=await U0({providerId:e,actionId:t,account:n??W0(e),params:r??{},refresh:i});return E9(`Provider ${e} completed action ${t}.`,w9(a))}catch(e){return T9(e)}})}const D9=R.iso.date(`Use a YYYY-MM-DD date.`);function O9(e,t){return e===void 0?t:e}const $ee={site:{mcp:`site`,schema:R.string()},days:{mcp:`days`,schema:R.number().optional()},recentDays:{mcp:`recentDays`,schema:R.number().optional()},range:{mcp:`range`,schema:R.number().optional()},limit:{mcp:`limit`,schema:R.number().optional()},checkLimit:{mcp:`checkLimit`,schema:R.number().optional()},minImpressions:{mcp:`minImpressions`,schema:R.number().optional()},includeBrand:{mcp:`includeBrand`,schema:R.boolean().optional()},verifyContent:{mcp:`verifyContent`,schema:R.boolean().optional()},verifyLimit:{mcp:`verifyLimit`,schema:R.number().optional()},js:{mcp:`js`,schema:R.boolean().optional()},fetchConcurrency:{mcp:`fetchConcurrency`,schema:R.number().optional()},fetchIntervalCap:{mcp:`fetchIntervalCap`,schema:R.number().optional()},fetchIntervalMs:{mcp:`fetchIntervalMs`,schema:R.number().optional()},refresh:{mcp:`refresh`,schema:R.boolean().optional()}};function k9(e){return Object.fromEntries(e.map(e=>{let t=$ee[e];return[t.mcp,t.schema]}))}const A9=R.union([D9,R.string().regex(/^(?:today|yesterday|\d+daysAgo)$/)]).describe(`Use YYYY-MM-DD or a Google Analytics relative date.`);function ete(e,t={}){e.registerTool(`seo_ai_referrals`,{description:`Find AI referral traffic detected in Google Analytics. maxRows bounds retained provider rows; resultLimit bounds returned landing pages.`,inputSchema:{property:R.string().trim().min(1),startDate:A9.optional(),endDate:A9.optional(),maxRows:R.number().int().min(1).max(1e5).describe(`Maximum retained Google Analytics rows. If limit is also supplied, both values must match.`).optional(),limit:R.number().int().min(1).max(1e5).describe(`Legacy alias for maxRows. If maxRows is also supplied, both values must match.`).optional(),resultLimit:R.number().int().min(1).max(1e3).describe(`Maximum ranked landing pages returned. Defaults to 25.`).optional(),refresh:R.boolean().optional()}},async({property:e,startDate:n,endDate:r,maxRows:i,limit:a,resultLimit:o,refresh:s})=>{try{if(i!==void 0&&a!==void 0&&i!==a)throw new P(`INVALID_INPUT`,`maxRows and the legacy limit option must match when both are provided.`);let c=await(t.aiReferralsReport??Nc)({property:e,startDate:n,endDate:r,maxRows:i,limit:a,resultLimit:o,refresh:s});return E9(`${$M(c.summary.sessions,`AI referral session`)} detected across ${$M(c.summary.sources,`source`)}; evidence is ${c.dataStatus}.`,c)}catch(e){return T9(e)}}),e.registerTool(`seo_page_opportunities`,{description:`Find first-party traffic growth opportunities for one URL from GSC and page content`,inputSchema:{...k9([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`verifyContent`,`refresh`,`js`]),days:R.number().int().min(1).max(548).optional(),limit:R.number().int().min(1).max(100).optional(),minImpressions:R.number().int().positive().optional(),url:R.string().url()}},async({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:l})=>{try{let u=await(t.pageOpportunitiesReport??jT)({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:O9(l,`auto`)});return E9(u.summary.verdict,u)}catch(e){return T9(e)}}),e.registerTool(`seo_content_optimization`,{description:`Build a content optimization brief for one URL from first-party GSC queries and page content checks`,inputSchema:{...k9([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`verifyContent`,`refresh`,`js`]),days:R.number().int().min(1).max(548).optional(),limit:R.number().int().min(1).max(100).optional(),minImpressions:R.number().int().positive().optional(),url:R.string().url()}},async({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:l})=>{try{let u=await(t.contentOptimizationReport??VT)({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:O9(l,`auto`)});return E9(u.summary.verdict,u)}catch(e){return T9(e)}}),e.registerTool(`seo_performance_audit`,{description:`Run a local Lighthouse lab audit and optional device-specific CrUX field Core Web Vitals. Configure CrUX with SEO_CRUX_API_KEY.`,inputSchema:{url:R.string().url(),strategy:R.enum([`mobile`,`desktop`]).optional(),refresh:R.boolean().optional()}},async({url:e,strategy:t,refresh:n})=>{try{let r=await Rz({url:e,strategy:t,refresh:n});return E9(r.headline,r)}catch(e){return T9(e)}})}function j9(e,t={}){let n=e.requestEvidenceStatus===`available`?`Processed ${e.requests.length} URL requests into ${e.summary.totalPages} unique documents.`:e.requestEvidenceStatus===`partial`?`Observed ${e.requests.length} URL requests and retained ${e.summary.totalPages} unique documents; some started requests were still in flight when the crawl stopped.`:`Loaded ${e.summary.totalPages} unique documents; request evidence is unavailable for this legacy report.`,r={id:e.id,definitionId:e.definitionId,headline:`${n} Found ${e.summary.highIssues} high, ${e.summary.mediumIssues} medium, and ${e.summary.lowIssues} low issues.`,status:e.status,requestEvidenceStatus:e.requestEvidenceStatus,configHash:e.configHash,config:e.config,access:e.access,summary:e.summary,dataSources:e.dataSources,ai:e.ai?{robotsTxt:e.ai.robotsTxt,llmsTxt:e.ai.llmsTxt,agentResources:e.ai.agentResources}:void 0,topFixes:UD(e,{limit:1e3}),reviewObservations:WD(e,{limit:1e3}),issueGroupsComplete:!0,warnings:e.warnings,caveats:e.caveats};return t.includeIssues&&(r.issues=e.issues),t.includePages&&(r.requests=e.requests,r.pages=e.pages),r}const M9=R.number().int().min(1).max(YE).optional(),N9=R.number().int().min(0).max(64).optional(),P9=R.number().int().min(1).max(16).optional(),F9=R.string().regex(/^\d{1,30}$/u).optional();function I9(e){if(e.googleAnalyticsPropertyId&&e.clickySiteId)throw new P(`INVALID_INPUT`,`Pass either googleAnalyticsPropertyId or clickySiteId, not both.`);return e.clickySiteId?{provider:`clicky`,siteId:e.clickySiteId}:void 0}function L9(e){if(e.fetchConcurrency!==void 0||e.fetchIntervalCap!==void 0||e.fetchIntervalMs!==void 0)return{concurrency:e.fetchConcurrency,intervalCap:e.fetchIntervalCap,intervalMs:e.fetchIntervalMs}}function tte(e){e.registerTool(`seo_crawl_site`,{description:`Run a site crawl. Start with health=true for a fast uncached sitemap status and redirect pass, especially on large or unknown sites. Run the full crawl second when content-level evidence is needed. The compact result includes crawler identity and access-block guidance.`,inputSchema:{url:R.string().url().optional().describe(`Site start URL. Optional when sitemapUrl supplies the health-pass scope.`),health:R.boolean().optional().describe(`Run the fast sitemap health pass before a full crawl. Downloads no page bodies and writes no page cache entries.`),sitemapUrl:R.string().url().optional().describe(`Explicit sitemap or sitemap index URL for the health pass.`),site:R.string().optional(),googleAnalyticsPropertyId:R.string().optional(),clickySiteId:F9,maxPages:M9,maxDepth:N9,concurrency:P9,fetchIntervalCap:R.number().int().positive().optional(),fetchIntervalMs:R.number().int().positive().optional(),refresh:R.boolean().optional(),include:R.array(R.string()).optional(),exclude:R.array(R.string()).optional(),useSitemap:R.boolean().optional(),respectRobots:R.boolean().optional(),js:R.boolean().optional(),includePages:R.boolean().optional(),includeIssues:R.boolean().optional()}},async({url:e,health:t,sitemapUrl:n,site:r,googleAnalyticsPropertyId:i,clickySiteId:a,maxPages:o,maxDepth:s,concurrency:c,fetchIntervalCap:l,fetchIntervalMs:u,refresh:d,include:f,exclude:p,useSitemap:m,respectRobots:h,js:g,includePages:_,includeIssues:v})=>{try{let y=I9({googleAnalyticsPropertyId:i,clickySiteId:a}),b=e??(n?new URL(`/`,n).toString():void 0);if(!b)throw new P(`INVALID_INPUT`,`Pass url or an explicit sitemapUrl.`);let x=await gM({url:b,mode:t||n?`sitemap`:`site`,strategy:t?`health`:`full`,sitemapUrl:n,site:r,googleAnalyticsPropertyId:i,analyticsConnection:y,maxPages:o,maxDepth:s,concurrency:c,refresh:d,fetchRate:L9({fetchConcurrency:c,fetchIntervalCap:l,fetchIntervalMs:u}),include:f,exclude:p,useSitemap:m,respectRobots:h,js:!!g});return E9(`${t?`Sitemap health pass`:`Crawl`} complete for ${b}. Found ${x.issues.length} issues across ${x.summary.totalPages} pages.`,j9(x,{includePages:_,includeIssues:v}))}catch(e){return T9(e)}}),e.registerTool(`seo_audit_urls`,{description:`Audit an explicit list of URLs with technical SEO checks. The compact result separates prioritised fixes from review observations. Set includePages/includeIssues for raw data.`,inputSchema:{urls:R.array(R.string().url()).min(1).max(YE),site:R.string().optional(),googleAnalyticsPropertyId:R.string().optional(),clickySiteId:F9,maxPages:M9,concurrency:P9,fetchIntervalCap:R.number().int().positive().optional(),fetchIntervalMs:R.number().int().positive().optional(),refresh:R.boolean().optional(),includePages:R.boolean().optional(),includeIssues:R.boolean().optional()}},async({urls:e,site:t,googleAnalyticsPropertyId:n,clickySiteId:r,maxPages:i,concurrency:a,fetchIntervalCap:o,fetchIntervalMs:s,refresh:c,includePages:l,includeIssues:u})=>{try{let d=I9({googleAnalyticsPropertyId:n,clickySiteId:r}),f=await gM({url:e[0]??``,urls:e,mode:`list`,site:t,googleAnalyticsPropertyId:n,analyticsConnection:d,maxPages:i??e.length,concurrency:a,refresh:c,fetchRate:L9({fetchConcurrency:a,fetchIntervalCap:o,fetchIntervalMs:s}),useSitemap:!1});return E9(`URL audit complete. Found ${f.issues.length} issues across ${f.summary.totalPages} pages.`,j9(f,{includePages:l,includeIssues:u}))}catch(e){return T9(e)}}),e.registerTool(`seo_top_fixes`,{description:`Return top technical SEO fixes for a URL by running a compact crawl.`,inputSchema:{url:R.string().url(),site:R.string().optional(),maxPages:M9,maxDepth:N9,fetchIntervalCap:R.number().int().positive().optional(),fetchIntervalMs:R.number().int().positive().optional(),refresh:R.boolean().optional(),category:R.string().optional(),limit:R.number().int().min(1).max(1e3).optional()}},async({url:e,site:t,maxPages:n,maxDepth:r,fetchIntervalCap:i,fetchIntervalMs:a,refresh:o,category:s,limit:c})=>{try{let l=await gM({url:e,site:t,maxPages:n,maxDepth:r,refresh:o,fetchRate:L9({fetchIntervalCap:i,fetchIntervalMs:a})}),u=UD(l,{category:s,limit:c}),d=l.status===`completed`?``:` Coverage is ${l.status}: ${$M(l.summary.crawledUrls,`URL`)} crawled from ${$M(l.summary.discoveredUrls,`discovered URL`)}. Review the returned warnings and caveats before treating this as sitewide.`;return E9(`Found ${$M(u.length,`top fix group`)} for ${l.config.url}.${d}`,{url:l.config.url,reportId:l.id,summary:l.summary,dataSources:l.dataSources,topFixes:u,warnings:l.warnings,caveats:l.caveats})}catch(e){return T9(e)}}),e.registerTool(`seo_explain_issue`,{description:`Explain a crawler rule in plain English: why it matters, how to fix it, and how to verify it.`,inputSchema:{ruleId:R.string()}},async({ruleId:e})=>{let t=Yn(e);return t?E9(`Rule guidance for ${e}.`,t):T9(`Unknown rule: ${e}`)}),e.registerTool(`seo_list_rules`,{description:`List crawler rule ids and guidance metadata. Use this before the explain-crawl-issue report when you need valid rule ids.`,inputSchema:{category:uO.optional()}},async({category:e})=>{let t=Jn().filter(t=>!e||t.category===e);return E9(`Found ${$M(t.length,`crawler rule`)}.`,{rules:t})})}function R9(e,t={}){e.registerTool(`seo_doctor`,{description:`Check the local database, auth, scopes, config, and defaults`,inputSchema:{}},async()=>{try{let e=await O0();return E9(e.ok?`Local seo setup is ready.`:`Local seo setup needs attention.`,e)}catch(e){return T9(e)}}),e.registerTool(`seo_segment_impact`,{description:`Compare matched retained GSC segments across adjacent equal-length periods without treating missing rows as zero`,inputSchema:{site:R.string().trim().min(1),days:R.number().int().min(1).max(240).optional(),limit:R.number().int().min(1).max(100).optional(),refresh:R.boolean().optional(),dimension:R.enum([`page`,`query`,`country`,`device`]).optional(),compareDays:R.number().int().min(1).max(240).optional(),startDate:D9.optional(),endDate:D9.optional(),maxRows:R.number().int().min(1).max(25e4).optional(),unmatchedLimit:R.number().int().min(0).max(100).optional()}},async({site:e,dimension:n,days:r,compareDays:i,startDate:a,endDate:o,limit:s,maxRows:c,unmatchedLimit:l,refresh:u})=>{try{let d=await(t.segmentImpact??xN)({site:e,dimension:n,days:r,compareDays:i,startDate:a,endDate:o,limit:s,maxRows:c,unmatchedLimit:l,refresh:u});return E9(d.summary.verdict,d)}catch(e){return T9(e)}}),e.registerTool(`seo_striking_distance`,{description:`Find position 11-20 query/page opportunities from GSC`,inputSchema:{...k9([`site`,`days`,`minImpressions`,`limit`,`verifyContent`,`verifyLimit`,`includeBrand`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),days:R.number().int().min(1).max(548).optional(),minImpressions:R.number().int().min(0).max(1e9).optional(),limit:R.number().int().min(1).max(100).optional(),verifyLimit:R.number().int().min(0).max(100).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:R.number().int().min(1).max(16).optional(),fetchIntervalCap:R.number().int().min(1).max(60).optional(),fetchIntervalMs:R.number().int().min(100).max(6e4).optional()}},async({site:e,days:t,minImpressions:n,limit:r,verifyContent:i,verifyLimit:a,includeBrand:o,brandTerms:s,js:c,fetchConcurrency:l,fetchIntervalCap:u,fetchIntervalMs:d,refresh:f})=>{try{let p=await pI({site:e,days:t,minImpressions:n,limit:r,verifyContent:i,verifyLimit:a,includeBrand:o,brandTerms:s,js:O9(c,void 0),rate:L9({fetchConcurrency:l,fetchIntervalCap:u,fetchIntervalMs:d}),refresh:f});return E9(p.summary.verdict,p)}catch(e){return T9(e)}}),e.registerTool(`seo_traffic_anomaly`,{description:`Detect statistically significant recent GSC traffic movement`,inputSchema:{...k9([`site`,`days`,`recentDays`,`refresh`])}},async({site:e,days:t,recentDays:n,refresh:r})=>{try{let i=await VI({site:e,days:t,recentDays:n,refresh:r});return E9(`${i.anomalies.filter(e=>e.significant).length} significant anomalies found.`,i)}catch(e){return T9(e)}}),e.registerTool(`seo_update_correlate`,{description:`Overlay recent traffic anomalies against official Google ranking update windows`,inputSchema:{...k9([`site`,`days`,`recentDays`,`refresh`]),paddingDays:R.number().optional()}},async({site:e,days:t,recentDays:n,paddingDays:r,refresh:i})=>{try{let a=await HI({site:e,days:t,recentDays:n,paddingDays:r,refresh:i});return E9(`Classification: ${a.classification}.`,a)}catch(e){return T9(e)}})}function nte(e){e.registerTool(`seo_index_coverage`,{description:`Crawl the site, compare it and its sitemap with Search Console page results, then choose representative URLs for URL Inspection`,inputSchema:{site:R.string().min(1),url:R.string().url().optional().describe(`Start URL to crawl. Defaults to the home page.`),sitemaps:R.array(R.string().url()).min(1).max(20).optional(),days:R.number().int().min(1).max(548).optional(),rowLimit:R.number().int().min(1).max(25e4).optional(),maxSitemapUrls:R.number().int().min(1).max(25e4).optional(),itemsPerSection:R.number().int().min(1).max(1e3).optional(),templateClusters:R.number().int().min(1).max(200).optional(),templateSamples:R.number().int().min(1).max(25).optional(),refresh:R.boolean().optional()}},async({site:e,url:t,sitemaps:n,days:r,rowLimit:i,maxSitemapUrls:a,itemsPerSection:o,templateClusters:s,templateSamples:c,refresh:l})=>{try{let u=await ez({site:e,url:t,sitemaps:n,days:r,rowLimit:i,maxSitemapUrls:a,itemsPerSection:o,templateClusters:s,templateSamples:c,refresh:l});return E9(`${u.summary.retainedSearchVisibleUrls} URLs appeared in the returned Search Console data. ${u.summary.crawlableCandidatesWithoutRetainedSearchVisibility} crawlable URLs need evidence review before choosing representative URL Inspection checks.`,u)}catch(e){return T9(e)}}),e.registerTool(`seo_redirect_trace`,{description:`Trace redirects and report final indexability/canonical issues for a URL`,inputSchema:{url:R.string().url(),maxHops:R.number().optional(),refresh:R.boolean().optional(),js:R.boolean().optional()}},async({url:e,maxHops:t,refresh:n,js:r})=>{try{let i=await nz({url:e,maxHops:t,refresh:n,js:O9(r,`auto`)});return E9(`Traced ${i.summary.hops} hops. ${i.summary.finalStatus===null?`No final response (${i.summary.outcome}: ${i.summary.error??`unknown`}).`:`Final status ${i.summary.finalStatus}.`} ${i.summary.issues.length} issues.`,i)}catch(e){return T9(e)}}),e.registerTool(`seo_link_recover`,{description:`Find GSC search-value URLs that are now broken, blocked, or poorly redirected`,inputSchema:{...k9([`site`,`days`,`limit`,`minImpressions`,`refresh`,`js`]),minClicks:R.number().optional()}},async({site:e,days:t,limit:n,minClicks:r,minImpressions:i,refresh:a,js:o})=>{try{let s=await sz({site:e,days:t,limit:n,minClicks:r,minImpressions:i,refresh:a,js:O9(o,`auto`)});return E9(`Checked ${s.summary.checked} search-value URLs. ${s.summary.recoverable} recoverable issues.`,s)}catch(e){return T9(e)}})}const rte=R.enum([`dataforseo`,`ahrefs`]),z9=e=>R.string().trim().min(1).max(500).describe(e).optional(),ite=R.strictObject({keyword:z9(`Source column containing the search query.`),url:z9(`Source column containing the ranking URL.`),position:z9(`Source column containing grouped position.`),absolutePosition:z9(`Source column containing absolute result position.`),searchVolume:z9(`Source column containing monthly search volume.`),keywordDifficulty:z9(`Source column containing keyword difficulty.`),cpc:z9(`Source column containing cost per click.`),paidCompetition:z9(`Source column containing paid competition.`),intent:z9(`Source column containing search intent.`),resultCount:z9(`Source column containing estimated result count.`),estimatedTraffic:z9(`Source column containing estimated monthly visits.`),resultType:z9(`Source column containing result type.`),searchVolumeUpdatedAt:z9(`Source column containing the search volume update date.`)}).superRefine((e,t)=>{let n=/* @__PURE__ */ new Map;for(let[r,i]of Object.entries(e)){if(!i)continue;let e=IN(i),a=n.get(e);a?t.addIssue({code:`custom`,message:`Source column "${i}" is already mapped to "${a}".`,path:[r]}):n.set(e,r)}}).describe(`Optional canonical field to source column mapping. Named fields override automatic header matching.`),ate=R.array(R.strictObject({dataset:R.literal(`ranked-keywords`),file:R.string().trim().min(1).max(4096),provider:rte,exportedAt:R.string().trim().min(1).max(100),format:R.enum([`csv`,`json`,`jsonl`]).optional(),rowLimit:R.number().int().min(1).max(1e5).optional(),columns:ite.optional()})).min(1).max(4).describe(`One to four local ranked-keyword exports from the same provider and market.`);function ote(e,t={}){e.registerTool(`seo_cannibal`,{description:`Find multi-URL query exposure candidates for intent and technical review`,inputSchema:{...k9([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`refresh`]),days:R.number().int().min(1).max(548).optional(),limit:R.number().int().min(1).max(100).optional(),minImpressions:R.number().int().min(0).max(1e9).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional(),researchFiles:ate.optional()}},async({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o,researchFiles:s})=>{try{let c=s?await aF({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o,researchFiles:s}):await aF({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o});return E9(c.summary.verdict,c)}catch(e){return T9(e)}}),e.registerTool(`seo_decaying`,{description:`Find query/page click declines observed in both retained GSC windows and investigation signals`,inputSchema:{...k9([`site`,`days`,`limit`,`includeBrand`,`refresh`]),days:R.number().int().min(1).max(548).optional(),limit:R.number().int().min(1).max(100).optional(),comparison:R.enum([`previous-period`,`year-over-year`]).optional(),minDropPct:R.number().min(0).max(100).optional(),minPreviousClicks:R.number().min(0).max(1e9).optional(),minClickLoss:R.number().min(0).max(1e9).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,days:t,limit:n,comparison:r,minDropPct:i,minPreviousClicks:a,minClickLoss:o,brandTerms:s,includeBrand:c,refresh:l})=>{try{let u=await SF({site:e,days:t,limit:n,comparison:r,minDropPct:i,minPreviousClicks:a,minClickLoss:o,brandTerms:s,includeBrand:c,refresh:l});return E9(u.summary.verdict,u)}catch(e){return T9(e)}}),e.registerTool(`seo_quick_wins`,{description:`Find quick-win CTR/position opportunities`,inputSchema:{...k9([`site`,`days`,`limit`,`minImpressions`,`verifyContent`,`verifyLimit`,`includeBrand`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),days:R.number().int().min(1).max(548).optional(),limit:R.number().int().min(1).max(100).optional(),minImpressions:R.number().int().min(0).max(1e9).optional(),verifyLimit:R.number().int().min(0).max(100).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:R.number().int().min(1).max(16).optional(),fetchIntervalCap:R.number().int().min(1).max(60).optional(),fetchIntervalMs:R.number().int().min(100).max(6e4).optional()}},async({site:e,days:n,limit:r,minImpressions:i,brandTerms:a,verifyContent:o,verifyLimit:s,includeBrand:c,js:l,fetchConcurrency:u,fetchIntervalCap:d,fetchIntervalMs:f,refresh:p})=>{try{let m=await(t.quickWinsReport??GF)({site:e,days:n,limit:r,minImpressions:i,brandTerms:a,verifyContent:o,verifyLimit:s,includeBrand:c,js:O9(l,void 0),rate:L9({fetchConcurrency:u,fetchIntervalCap:d,fetchIntervalMs:f}),refresh:p});return E9(m.summary.verdict,m)}catch(e){return T9(e)}}),e.registerTool(`seo_internal_links`,{description:`Internal links to add across a site, or to one target URL, placed in real sentences`,inputSchema:{...k9([`site`,`refresh`]),targetUrl:R.string().url().refine(e=>/^https?:\/\//.test(e),`Use an HTTP(S) URL.`).optional(),maxPages:R.number().int().min(1).max(oL).optional(),startDate:R.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),endDate:R.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional()}},async({site:e,targetUrl:n,maxPages:r,startDate:i,endDate:a,refresh:o})=>{try{let s=await(t.internalLinksReport??bR)({site:e,targetUrl:n,maxPages:r,startDate:i,endDate:a,refresh:o},await x0({site:n??e,refresh:o}));return E9(s.summary.verdict,s)}catch(e){return T9(e)}}),e.registerTool(`seo_ctr_underperformers`,{description:`Find high-impression queries underperforming CTR expectations`,inputSchema:{...k9([`site`,`minImpressions`,`limit`,`includeBrand`,`refresh`]),site:R.string().trim().min(1),minImpressions:R.number().int().min(1).max(1e9).optional(),limit:R.number().int().min(1).max(100).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,minImpressions:n,limit:r,brandTerms:i,includeBrand:a,refresh:o})=>{try{let s=await(t.ctrUnderperformersReport??ZM)({site:e,minImpressions:n,limit:r,brandTerms:i,includeBrand:a,refresh:o});return E9(s.summary.verdict,s)}catch(e){return T9(e)}}),e.registerTool(`seo_query_cluster`,{description:`Cluster queries by token overlap`,inputSchema:{...k9([`site`,`includeBrand`,`minImpressions`,`limit`,`refresh`]),site:R.string().trim().min(1),scope:R.string().trim().min(1).max(2e3).optional(),minImpressions:R.number().int().min(1).max(1e9).optional(),limit:R.number().int().min(1).max(100).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,scope:n,brandTerms:r,includeBrand:i,minImpressions:a,limit:o,refresh:s})=>{try{let c=await(t.queryClusterReport??aB)({site:e,scope:n,brand:r?.[0],brandTerms:r,includeBrand:i,minImpressions:a,limit:o,refresh:s});return E9(c.summary.verdict,c)}catch(e){return T9(e)}})}const ste={"ai-referrals":{readOrder:[`dataStatus, range, methodology, and dataSource partialReasons`,`possiblyTruncated and per-query statuses`,`selection.landingPages before treating landingPages as complete`,`sources observedSessionSources for attribution evidence`],doNotClaim:[`An empty result is not proof that no AI system sent or cited the site.`,`Referral sessions did not necessarily cause conversions and are not all AI traffic.`,`totalUsers is not additive and must not be reconstructed by summing rows.`],verify:`Compare complete like-for-like Google Analytics periods and check whether high-session landing pages answer the referring context.`,related:[]},"audit-page":{readOrder:[`fetchDiagnostics, warnings, and the final fetched URL`,`observed page fields and structured-data findings`,`issues and recommendations`],doNotClaim:[`One page cannot support a sitewide conclusion.`,`Title pixel width is a review estimator, not a Google limit.`,`The fetched version is not proof that Google indexed that version.`],verify:`Re-fetch the URL after the edit and confirm the observed field changed.`,related:[{id:`redirect-trace`,reason:`Debugs the redirect chain.`},{id:`performance-audit`,reason:`Adds page speed evidence.`},{id:`content-optimization`,reason:`Builds a query-led brief.`}]},"audit-urls":{readOrder:[`requested versus attempted, fetched, failed, retained, and omitted counts`,`topFixes AND reviewObservations together; the two lists are the complete grouped issue inventory, so carry every group from both into findings`,`response evidence and issue summaries`,`requestEvidenceStatus, warnings, and caveats`],doNotClaim:[`A successful sample does not prove the same template works everywhere.`,`A failed request may be transient network, not a persistent defect.`,`A bounded audit is never complete site coverage.`],verify:`Re-run the identical URL list after deployment; a URL dropped from the request is not a verified fix.`,related:[{id:`audit-page`,reason:`Inspects one page in depth.`},{id:`site-crawl`,reason:`Discovers pages instead.`},{id:`redirect-trace`,reason:`Traces a redirecting URL.`}]},cannibalisation:{readOrder:[`dataStatus and both source.pageExposure and source.propertyDemand with validation counts and completeness`,`selection to see why groups were excluded or suppressed`,`per-page clicks, impressions, position, impression share, reviewContext, and HHI`,`priority.score and suggestedOwnerUrl`,`dataSource plus evidence.imports file dates, hashes, and row quality when the run used researchFiles`],doNotClaim:[`URL overlap is a review candidate, not proven harmful cannibalisation.`,`suggestedOwnerUrl is a low-confidence mechanical pick that requires intent review.`,`priority.score is a heuristic, not estimated click lift, and a partial source cannot support an all-clear.`,`Research-import rows are provider estimates that support multiple-ranking-URL claims only, not traffic or Search Console-verified cannibalisation.`],verify:`Compare intent and live SERPs for the overlapping URLs before consolidating anything.`,related:[{id:`query-clusters`,reason:`Groups related query themes.`},{id:`internal-links`,reason:`Clarifies link ownership.`},{id:`content-optimization`,reason:`Differentiates page intent.`}]},"content-optimization":{readOrder:[`sourceReport dataStatus, selection, benchmark.possiblyTruncated, and verification.status`,`summary.score and primaryIntent as heuristics`,`topActions separating technical-check and unverified from verified observations`,`intentMix and the source query metrics`],doNotClaim:[`estimatedClickLift and score are prioritisation heuristics, not forecasts or quality grades.`,`Query wording is not a content mandate.`,`Adding suggested wording is not guaranteed traffic.`],verify:`Fetch the page after the edit and confirm the missing answer block or clearer framing is present.`,related:[{id:`page-opportunities`,reason:`Adds query-level opportunities.`},{id:`internal-links`,reason:`Finds contextual links.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`}]},"crawler-rules":{readOrder:[`each rule id, title, and category`,`default severity as triage metadata`,`guidance metadata`],doNotClaim:[`Listing a rule does not mean the site triggered it or that the convention is a search-engine requirement.`,`Default severity is generic triage metadata, not actual priority.`,`Similarly named rules may not share source semantics.`],verify:`Pass the exact rule id to explain-crawl-issue, then check the matching issues in a site crawl.`,related:[{id:`explain-crawl-issue`,reason:`Returns the rule contract.`}]},"ctr-underperformers":{readOrder:[`dataStatus, range, source.completeness, possiblyTruncated, and validation counts`,`brand terms used, then selection before the queue; rows at average position 4 or worse belong to quick-wins`,`per-item query, URL, impressions, position, observed CTR, target CTR, benchmark source, and queryFlags`,`estimated shortfall`],doNotClaim:[`The shortfall is directional prioritisation math, not a traffic forecast.`,`Page-one average position hides day, device, geography, and result-feature variation.`,`A partial empty result is not an all-clear.`],verify:`Inspect the current SERP and displayed title link, then compare a complete later period after testing framing.`,related:[{id:`quick-wins`,reason:`Ranks position 4-10 opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`},{id:`content-optimization`,reason:`Builds a page brief.`}]},"decaying-pages":{readOrder:[`dataStatus, ranges, and source.completeness`,`current and previous fetched rows, caps, truncation, and invalid rows in selection`,`summary.observedRetainedQueryClickLoss versus the returned subset`,`per-item clicks, impressions, CTR, position, and signals`],doNotClaim:[`A diagnosis such as lost_position or lost_ctr labels correlated movement, not a cause.`,`Missing retained rows are not zero traffic.`,`Do not sum capped rows into a property-wide loss.`],verify:`Check deployments, live indexability, and SERP composition for the affected URLs before editing.`,related:[{id:`refresh-priorities`,reason:`Combines decline signals.`},{id:`segment-impact`,reason:`Shows where movement concentrates.`}]},"explain-crawl-issue":{readOrder:[`category, default severity, and why it matters`,`fix steps and ignored impact`,`verification method and agent hints`],doNotClaim:[`Guidance describes the checked condition, not a search-engine penalty or guaranteed ranking effect.`,`Default severity is generic prioritization metadata, not actual urgency.`,`The rule definition alone does not prove any page triggered it.`],verify:`Pair the definition with the matching issues from a site crawl and confirm the per-URL evidence.`,related:[{id:`crawler-rules`,reason:`Finds a rule id.`},{id:`top-fixes`,reason:`Ranks the fix queue.`}]},"index-coverage":{readOrder:[`sources completeness, rowLimit, rowLimitReached, date range, and invalid rows`,`retainedSearchVisibility and crawlableWithoutRetainedSearchVisibility`,`blockedOrNonIndexable, sitemapOnly, searchConsoleOnly, and templateReview`,`each group count, returned, and omitted`],doNotClaim:[`A page is not indexed because it had Search Analytics visibility, nor unindexed because no row appeared.`,`A missing Search Analytics row is not proof a page is unindexed.`,`Do not turn a limited or incomplete source into a whole-site coverage percentage.`],verify:`Run seo page --url on representative URLs to collect exact URL Inspection verdicts.`,related:[{id:`site-crawl`,reason:`Provides the source crawl.`}]},"internal-links":{readOrder:[`dataStatus, target verification, aliases, canonical, and technical signals`,`source completeness and selection attempted, checked, failed, unchecked, and exclusions`,`per-item exact versus lexical matches and linkEvidence`,`per-item placement: the sentence where a link fits, its anchors, and contentSimilarity`],doNotClaim:[`The live check stops at 40 source pages, so unchecked candidates can remain and absence is not proven.`,`Query overlap does not prove a link belongs or that adding one improves rankings.`,`Priority is a heuristic, not estimated impact.`,`Placement sentences, anchors and contentSimilarity are text heuristics; they do not prove the link helps a reader.`],verify:`Read the source passage, add one contextual link if the target is genuinely useful, and re-crawl to confirm it.`,related:[{id:`cannibalisation`,reason:`Checks URL overlap.`},{id:`content-optimization`,reason:`Builds a page brief.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"link-recovery":{readOrder:[`range and summary.checked with severity totals`,`per-item original and final URL, GSC metrics, issue lists, and redirect trace`,`chain status, final-page indexability, canonicals, and warnings`],doNotClaim:[`clicksAtRisk and impressionsAtRisk describe the checked period, not a forecast of loss or recovery.`,`Prior visibility orders the queue but does not prove fixing a URL restores traffic.`,`Failed checks or selection limits constrain coverage.`],verify:`Add one direct 301 to the closest equivalent destination only after confirming the page should still exist, then re-trace.`,related:[{id:`redirect-trace`,reason:`Traces one URL chain.`},{id:`decaying-pages`,reason:`Shows click declines.`},{id:`audit-urls`,reason:`Runs bounded checks.`}]},"page-opportunities":{readOrder:[`dataStatus, range, source.targetRowsFetched, selection, and benchmark`,`benchmark.possiblyTruncated`,`verification.status and reason`,`per-item query metrics, opportunity type, and benchmark and verification evidence`],doNotClaim:[`Only verified results support live-page coverage observations.`,`estimatedCtrClickShortfall is a directional calculation, not a click forecast.`,`summary.opportunities is a review queue, not a defect count, and partial data is not an all-clear.`],verify:`Inspect the live SERP and resolve any status or indexability contradiction before editing.`,related:[{id:`content-optimization`,reason:`Builds a page brief.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`internal-links`,reason:`Finds contextual links.`}]},"performance-audit":{readOrder:[`dataStatus, source, labDataStatus, and fieldDataStatus`,`Lighthouse score, lab metrics, and labInsights`,`CrUX fieldData.metrics with scope, formFactor, and collectionPeriod`,`fetch-fallback fields when source is fetch-fallback`],doNotClaim:[`Origin-level CrUX data is not page-level evidence.`,`A fetch-fallback duration is the local fetch workflow, not TTFB, LCP, CLS, TBT, or INP, and never earns a score.`,`Do not combine lab and field values into a new score, compare mobile with desktop as equal populations, or claim a ranking outcome.`],verify:`Reproduce the relevant lab issue and re-run the audit after the change.`,related:[{id:`audit-page`,reason:`Runs an on-page audit.`},{id:`site-crawl`,reason:`Builds the site inventory.`}]},"query-clusters":{readOrder:[`summary cluster and query counts, clicks, impressions, threshold, limit, and brand filtering`,`per-cluster member queries, pages, demand, and performance`,`each cluster recommendation`],doNotClaim:[`Token overlap does not prove shared intent, justify a new page, or establish that current URLs compete.`,`Page-two clusters do not claim a CTR-only click lift.`,`Queries below the threshold or outside the cap are outside the conclusion, not absent demand.`],verify:`Check whether a cluster maps to one intent before changing section structure or navigation.`,related:[{id:`cannibalisation`,reason:`Checks URL overlap.`},{id:`content-optimization`,reason:`Builds a page brief.`}]},"quick-wins":{readOrder:[`dataStatus, date range, source row cap, possiblyTruncated, selection.invalidRows, and filters`,`methodology and each item benchmark confidence before using targetCtr`,`estimatedCtrClickShortfall and priority`,`verification requested, attempted, verified, failed, and technical counts`],doNotClaim:[`estimatedCtrClickShortfall and priority score are heuristics, explicitly not estimated lift.`,`Average position is not a stable rank, and an unverified item cannot support a content-coverage conclusion.`,`Filtered or capped evidence is not an all-clear.`],verify:`Inspect the live SERP, test clearer snippet framing, then compare a later complete window.`,related:[{id:`ctr-underperformers`,reason:`Adds CTR peer evidence.`},{id:`page-opportunities`,reason:`Reviews one URL.`},{id:`striking-distance`,reason:`Finds rows near page one.`}]},"redirect-trace":{readOrder:[`chain in order with requested URL, status, Location, resolved next, and duration`,`finalUrl versus finalPage and summary.finalStatus`,`summary.issues`,`metaRobots, xRobotsTag, canonical, and warnings`],doNotClaim:[`The trace is one observation from the machine and time that ran it, and CDNs, geography, cookies, or later deploys can differ.`,`A canonical elsewhere or a 302 can be intentional.`,`JavaScript rendering affects final-page extraction, not the HTTP chain.`],verify:`Re-run the trace after deployment and confirm the intended destination and status.`,related:[{id:`link-recovery`,reason:`Prioritises search-value URLs.`},{id:`audit-page`,reason:`Audits the final page.`},{id:`audit-urls`,reason:`Runs bounded checks.`}]},"refresh-priorities":{readOrder:[`workflow steps and skipped states`,`per-item source, impactKind, score breakdown, date window, completeness, verification status, and rationale`,`the top few URLs manually`],doNotClaim:[`A click decline, low CTR, second-page position, and Google Analytics session signal have different semantics and are not interchangeable.`,`Missing Google Analytics or failed fetches stay unavailable, not zero-weight proof.`,`The score is not expected clicks, revenue, ranking lift, or causal confidence.`],verify:`Confirm query intent, current content, and internal links for the top URLs before choosing a bounded edit.`,related:[{id:`decaying-pages`,reason:`Shows click declines.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`second-page`,reason:`Finds rows near page one.`}]},"search-performance-overview":{readOrder:[`workflow envelope with summary, steps, actions, and output`,`report dataStatus, skipped sections, and partial reasons`,`priorities`,`nested anomaly, update, segment, decay, cannibalisation, striking-distance, and quick-win results`],doNotClaim:[`One complete section must not hide a failed or capped neighbour.`,`Sparse data may legitimately skip a section.`,`Update overlap, opportunity scores, average position, and timing are investigation signals, not causation or forecasts.`],verify:`Run the focused report named in actions and confirm affected URLs and provider dates before editing.`,related:[{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`striking-distance`,reason:`Finds rows near page one.`}]},"second-page":{readOrder:[`source completeness, date range, selection, methodology, provenance, and brand filtering`,`per-item impressions, clicks, CTR, and average position`,`the priority value`],doNotClaim:[`Average position is aggregated across searches, locations, devices, and time and is not an exact rank.`,`Retained limits mean the output is not a complete inventory.`,`Priority is a transparent heuristic, not expected click lift, and one row is not cannibalisation.`],verify:`Inspect the live page and search intent and confirm the query suits the URL before one defensible change.`,related:[{id:`striking-distance`,reason:`Covers positions 11-20.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"segment-impact":{readOrder:[`before, after, and rangeDays`,`dataStatus and source.before, source.after, and completeness for caps and truncation`,`selection invalid, duplicate, conflicting, matched, unmatched, returned, and limited rows`,`per-item clickDelta, impressionDelta, and positionDelta, then unmatchedSegments`],doNotClaim:[`A positive positionDelta is worse because a larger average position is lower in results.`,`unmatchedSegments are retained in one window only and are not gains from or losses to zero.`,`A limited or truncated result cannot support an inventory-wide winner or loser.`],verify:`Audit the top matched movers pages and query intent before drawing a segment conclusion.`,related:[{id:`traffic-anomaly`,reason:`Confirms movement first.`},{id:`decaying-pages`,reason:`Shows click declines.`},{id:`update-postmortem`,reason:`Frames movement around an update.`}]},"setup-check":{readOrder:[`ok`,`each checks entry status, distinguishing fail from warn, with detail and fix`,`generatedAt`],doNotClaim:[`A passing result means local prerequisites look present, not that a token is still accepted by Google or that the account can access a property.`,`Missing saved defaults are usually warnings because explicit parameters can replace them.`,`A setup pass is not evidence about rankings, indexing, or site health.`],verify:`Apply the fix on a failed check, re-run setup-check, then run a small read-only report for the intended property.`,related:[{id:`search-performance-overview`,reason:`First report once setup passes.`}]},"site-crawl":{readOrder:[`config.strategy first; use health before full on large or unknown sites`,`status, requestEvidenceStatus, attempted and fetched counts, failures, retained pages, and pageLimitReached`,`access crawler identity, blockedRequests, provider counts, and samples`,`data-source states`,`topFixes AND reviewObservations together; the two lists are the complete grouped issue inventory, so carry every group from both into findings`,`warnings and caveats, then opt-in pages, requests, and issues`],doNotClaim:[`A partial or capped crawl cannot support an all-clear or a definitive zero.`,`A crawl is not an index, traffic source, or guarantee of complete site coverage.`,`A health pass checks response access, status, and redirects only. It does not download page bodies or evaluate content, metadata, canonicals, indexability directives, internal links, or rendered HTML. For full crawls, state when JavaScript rendering was disabled.`,`A User-Agent can be spoofed. Never ask the user for a broad firewall bypass based on crawler identity alone.`],verify:`Re-run the same health configuration first. Use a full crawl only when the health evidence is clean and the question needs page-body analysis.`,related:[{id:`top-fixes`,reason:`Ranks the fix queue.`},{id:`index-coverage`,reason:`Checks coverage signals.`}]},"striking-distance":{readOrder:[`range, rangeDays, dataStatus, and source`,`source.possiblyTruncated and retained-row completeness`,`selection invalid, out-of-range, branded, below-threshold, eligible, returned, and limited`,`methodology, then per-item metrics and contentVerification`],doNotClaim:[`The 11-20 band is a heuristic boundary and average position is not a literal second results page.`,`Unverified or failed pages keep lower confidence.`,`The priority score is not expected traffic or ranking lift.`],verify:`Audit a small number of high-impression candidates and fix verified technical problems first.`,related:[{id:`second-page`,reason:`Covers positions 10-20.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"top-fixes":{readOrder:[`dataSources, summary, warnings, and caveats`,`per-item rule id, affected count, sample URLs, scoreFactors, and whyThisRanks`,`effort, fix guidance, and verification`],doNotClaim:[`Rank means highest among retained eligible findings, not globally highest, because the crawl or category may be capped.`,`Missing provider joins stay unavailable and a numeric zero is meaningful only when the source is complete.`,`This is not a forecast of rankings, traffic, or revenue.`],verify:`Repeat the same crawl configuration after implementation and confirm the rule no longer triggers.`,related:[{id:`explain-crawl-issue`,reason:`Explains the rule.`},{id:`site-crawl`,reason:`Provides the source crawl.`}]},"traffic-anomaly":{readOrder:[`coverage with requested dates, expected versus observed days, missing days, invalid rows, and status`,`anomalies with metric, baseline and comparison dates, percentChange, zScore, and significanceMethod`,`direction and significant`,`detection, changeDate and the detection thresholds: a step change compares every day before its change date with every day from it`],doNotClaim:[`Statistical unusualness does not identify a cause, diagnose a defect, or prove an external event affected the property.`,`A null percentage from a zero baseline differs from zero change.`,`Partial coverage can change the baseline.`],verify:`If movement is significant and coverage is adequate, run segment-impact for pages and queries.`,related:[{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`update-correlation`,reason:`Adds update timing.`},{id:`decaying-pages`,reason:`Shows click declines.`}]},"update-correlation":{readOrder:[`classification with attribution and confidence, returned as not-established and none`,`anomalies, overlappingUpdates, and confounders`,`evidence, caveats, and source`],doNotClaim:[`Overlap cannot show the update caused a gain or loss even with large movement and no other recorded change.`,`update-overlap-without-significant-movement is not an impact result and no-update-overlap does not explain remaining movement.`,`Temporal overlap is not a penalty, reward, or confirmed effect.`],verify:`Test saved deploys, redirects, and content changes that overlap the window before attributing movement.`,related:[{id:`update-postmortem`,reason:`Maps winners and losers.`},{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`traffic-anomaly`,reason:`Confirms movement first.`}]},"update-postmortem":{readOrder:[`workflow step statuses, finalized date windows, and source completeness`,`failed measurements, retained limits, and caveats`,`update, insights, templateMovement, and segments`],doNotClaim:[`The cause remains not established even when dates overlap.`,`Retained winners and losers are not a complete inventory when sources are capped or filtered.`,`Do not claim update causation, recovery probability, or future traffic.`],verify:`Inspect representative URLs from affected segments and reproduce technical changes before any rollback.`,related:[{id:`update-correlation`,reason:`Adds update timing.`},{id:`segment-impact`,reason:`Shows where movement sits.`}]}},B9={"ai-referrals":{name:`AI referral traffic`,description:`Find visits from known AI products in Google Analytics and see a ranked, bounded set of landing pages that received them.`,useWhen:[`You want measured AI referral traffic from Google Analytics.`,`You need the landing pages and sources behind those visits.`],avoidWhen:[`Google Analytics is not connected or does not track the site.`,`You want to measure citations or unclicked mentions inside AI answers.`],outcome:`A source and landing-page breakdown of identifiable AI referrals.`},"audit-page":{name:`Single-page SEO audit`,description:`Check one URL for response, indexability, metadata, headings, links, and page content evidence.`,useWhen:[`One page needs a technical review before you change it.`,`A broader report points to a specific URL.`],avoidWhen:[`You need to discover issues across a whole site.`,`The page requires a logged-in browser session.`],outcome:`A page-level audit that separates observed evidence from review advice.`},"audit-urls":{name:`Selected URL audit`,description:`Audit a specific list of pages without crawling the rest of the site.`,useWhen:[`You already know which URLs need checking.`,`You want a repeatable pre-release or post-release check for key pages.`],avoidWhen:[`You need the crawler to discover pages for you.`,`You only need a deep review of one page.`],outcome:`Consistent technical checks for each supplied URL.`},cannibalisation:{name:`Query and URL overlap`,description:`Find search queries that appear across several URLs and decide whether the overlap needs attention.`,useWhen:[`Several pages may be competing for the same search intent.`,`You want query-level evidence before merging or redirecting pages.`],avoidWhen:[`You plan to treat every multi-URL query as a problem.`,`The site has too little Search Console data for meaningful overlap.`],outcome:`A ranked review list of queries, URLs, and their share of search exposure.`},"content-optimization":{name:`Search-led content brief`,description:`Turn a page and its Search Console queries into a practical brief for improving relevance and coverage.`,useWhen:[`An existing page has search demand but needs a clearer improvement plan.`,`You want first-party query evidence beside the current page content.`],avoidWhen:[`The URL has no useful Search Console history.`,`You want generated copy or a traffic forecast.`],outcome:`A page brief with query evidence, content checks, and specific review points.`},"crawler-rules":{name:`Crawler rule catalog`,description:`Find the available technical check IDs and the evidence each crawler rule looks for.`,useWhen:[`You need a valid rule ID for another crawl report.`,`You want to see which technical checks are available by category.`],avoidWhen:[`You need affected pages or live crawl results.`],outcome:`A searchable catalog of crawler rules, severity, and guidance.`},"ctr-underperformers":{name:`CTR underperformers`,description:`Find high-impression queries whose click-through rate trails comparable queries at similar positions.`,useWhen:[`You want title or snippet review candidates backed by Search Console data.`,`You need to compare CTR fairly across similar average positions.`],avoidWhen:[`You want a promised click uplift.`,`The comparison groups have too little data.`],outcome:`A ranked list of query and page pairs with CTR comparison evidence.`},"decaying-pages":{name:`Pages losing search clicks`,description:`Find pages and queries with meaningful click declines across comparable Search Console periods.`,useWhen:[`You want to investigate a sustained organic search decline.`,`You need the pages and queries behind lost clicks.`],avoidWhen:[`The newer period is incomplete or not comparable.`,`You want to assume every decline is caused by old content.`],outcome:`A ranked investigation list with before-and-after search evidence.`},"explain-crawl-issue":{name:`Explain a crawl issue`,description:`Explain what one crawler rule means, why it may matter, and how to verify a fix.`,useWhen:[`A crawl returned a rule ID you do not recognize.`,`You need implementation and verification guidance before creating work.`],avoidWhen:[`You need the URLs affected by the rule.`,`You have not selected a valid crawler rule ID.`],outcome:`A plain-English rule explanation with fix and verification steps.`},"index-coverage":{name:`Index coverage signals`,description:`Compare the pages your site exposes with pages that had Google Search visibility, then choose representative URLs for URL Inspection.`,useWhen:[`You need to find crawlable pages that did not appear in the Search Console results returned for the selected period.`,`You want a focused review list before spending URL Inspection quota.`],avoidWhen:[`You need proof that a URL is indexed or excluded. Use URL Inspection for that URL.`,`The site blocks crawlers, so the crawl cannot list its pages.`],outcome:`Cross-source URL groups with clear evidence limits and a representative review queue for URL Inspection.`},"internal-links":{name:`Internal links`,description:`Crawl a site and find the internal links it is missing, across the whole site or to one target URL, each placed in a real sentence with a real phrase as anchor text.`,useWhen:[`Pages that belong together do not link to each other.`,`A target page needs more contextual links from the rest of the site.`],avoidWhen:[`You want links added automatically.`,`The site cannot be crawled from this machine.`],outcome:`Links to add with the source sentence and anchor, judged by Jev when a TypeSafe key is set, plus orphan and weakly linked pages.`},"link-recovery":{name:`Recover broken search-value URLs`,description:`Find URLs that previously earned search clicks but now fail, redirect poorly, or block indexing.`,useWhen:[`You suspect valuable URLs broke during a migration or release.`,`You want to prioritize technical recovery using Search Console evidence.`],avoidWhen:[`You want a backlink report.`,`You have no Search Console page history for the site.`],outcome:`A ranked recovery list with current URL checks and prior search value.`},"page-opportunities":{name:`Opportunities for one page`,description:`Find Search Console queries and page evidence that point to useful improvements for one URL.`,useWhen:[`You want to improve an existing page using its own search demand.`,`You need query themes and page checks in one result.`],avoidWhen:[`The page has no useful Search Console data.`,`You want a guaranteed traffic gain.`],outcome:`A ranked page improvement list tied to real queries and current content.`},"performance-audit":{name:`Page performance audit`,description:`Run Lighthouse lab checks and add CrUX field Core Web Vitals when that data is available.`,useWhen:[`You need actionable performance diagnostics for a page.`,`You want lab findings kept separate from real-user field data.`],avoidWhen:[`You want Lighthouse scores presented as field Core Web Vitals.`,`The page cannot be fetched from the local machine.`],outcome:`Lab diagnostics plus clearly labelled field metrics when available.`},"query-clusters":{name:`Search query clusters`,description:`Group related Search Console queries so repeated demand themes are easier to review.`,useWhen:[`A large query list needs a clearer topic structure.`,`You want to find repeated wording within a site section.`],avoidWhen:[`You need semantic or intent classification beyond shared query terms.`,`You want clusters turned into new pages automatically.`],outcome:`Stable query groups with the search demand behind each theme.`},"quick-wins":{name:`Page-one CTR opportunities`,description:`Find page-one query and URL pairs whose CTR deserves a closer look.`,useWhen:[`You want high-impression title and snippet review candidates.`,`You need page-one opportunities ranked from Search Console data.`],avoidWhen:[`You want a promised click gain.`,`You plan to treat a CTR heuristic as a Google requirement.`],outcome:`A ranked review queue with CTR, position, impressions, and comparison evidence.`},"redirect-trace":{name:`Redirect trace`,description:`Follow every redirect hop and check the final page, indexability, and canonical signals.`,useWhen:[`A URL redirects unexpectedly or through several hops.`,`You need to verify the final destination after a migration.`],avoidWhen:[`You need to discover redirect issues across a whole site.`,`The URL requires a signed-in browser session.`],outcome:`The complete redirect chain with final response and page checks.`},"refresh-priorities":{name:`Content refresh priorities`,description:`Combine search declines and near-term opportunities into a ranked content review queue.`,useWhen:[`You need to decide which existing pages to review first.`,`You want several Search Console signals ranked in one queue.`],avoidWhen:[`You need a technical crawl plan.`,`You want the ranking treated as a traffic forecast.`],outcome:`A focused list of pages and queries to investigate next, with reasons.`},"search-performance-overview":{name:`Search performance overview`,description:`Find where Google Search performance changed and choose the next focused report to inspect it.`,useWhen:[`You are starting an investigation and do not yet know which pages or queries moved.`,`You want one view of declines, gains, overlap, and near-term opportunities.`],avoidWhen:[`You already know the exact question and can run a focused report.`,`You need a technical crawl without Search Console analysis.`],outcome:`A clear search performance summary with a short list of next reports.`},"second-page":{name:`Second-page opportunities`,description:`Find URLs averaging positions 11 to 20 and see the queries behind each opportunity.`,useWhen:[`You want existing pages that may deserve closer review near page one.`,`You need page-level evidence across all matching queries.`],avoidWhen:[`You want average position treated as a fixed rank.`,`You need proof that a change will move the page to page one.`],outcome:`A ranked URL list with query, click, impression, and position evidence.`},"segment-impact":{name:`Search impact by segment`,description:`Compare page or query groups across equal periods to find which parts of a site moved.`,useWhen:[`A traffic change may be concentrated in one directory, page type, or query group.`,`You need to separate broad movement from a local segment issue.`],avoidWhen:[`The periods are incomplete or not comparable.`,`Missing Search Console rows would be mistaken for zero activity.`],outcome:`A segment comparison showing where clicks and impressions changed.`},"setup-check":{name:`Check local setup`,description:`Check Google login, scopes, local configuration, and saved defaults before running reports.`,useWhen:[`Authentication or site selection is failing.`,`You want to verify the local setup before investigating report errors.`],avoidWhen:[`You need SEO findings rather than a setup check.`],outcome:`A local setup status with the exact problems that need fixing.`},"site-crawl":{name:`Sitemap health pass and technical site crawl`,description:`Start with a lightweight sitemap health pass, then run a full technical crawl only when page bodies and content-level evidence are needed.`,useWhen:[`You need a fast first check of sitemap URLs, statuses, redirects, robots decisions, or access blocks.`,`You need to discover technical issues across linked pages.`,`You want a crawl snapshot for later filtering or comparison.`],avoidWhen:[`You only need to check one page or a known URL list.`,`Do not run a full crawl on a large or unknown site before health=true, or when important content requires browser rendering that is not enabled.`],outcome:`A fast sitemap response gate or a full crawl summary with page evidence, technical findings, crawler identity and access guidance.`},"striking-distance":{name:`Queries near page one`,description:`Find Search Console query and page pairs averaging positions 11 to 20.`,useWhen:[`You want existing search demand close to page one.`,`You need a compact list of queries and URLs for content review.`],avoidWhen:[`You want average position treated as an exact daily rank.`,`You need a promised ranking or click gain.`],outcome:`A ranked list of near-page-one query and URL pairs with search evidence.`},"top-fixes":{name:`Top technical SEO fixes`,description:`Turn crawl findings into a short, ranked queue of technical issues to investigate first.`,useWhen:[`A crawl contains too many findings to review at once.`,`You need representative URLs and reasons for the highest priorities.`],avoidWhen:[`You need every affected URL for one rule.`,`You plan to treat rank as proof of business impact.`],outcome:`A focused technical fix queue with issue evidence and example URLs.`},"traffic-anomaly":{name:`Unusual search traffic changes`,description:`Find recent clicks or impressions that moved beyond the site's normal Search Console pattern.`,useWhen:[`You want an early signal of an unusual search change.`,`You need to know whether recent movement stands out from normal variation.`],avoidWhen:[`There is too little history for a useful baseline.`,`You want the report to identify the cause of the change.`],outcome:`A statistical movement signal with the dates, baseline, and limits shown.`},"update-correlation":{name:`Google update correlation`,description:`Compare search movement dates with official Google ranking update windows.`,useWhen:[`A traffic change overlaps a confirmed Google ranking update.`,`You need a timeline before investigating affected pages and queries.`],avoidWhen:[`You want overlap presented as proof of causation.`,`The traffic window does not cover the update dates.`],outcome:`A traffic and update timeline with overlaps clearly labelled as correlation.`},"update-postmortem":{name:`Google update impact review`,description:`Find the pages and queries that gained or lost around a confirmed Google ranking update.`,useWhen:[`You need winners and losers around a known update window.`,`You want to compare affected segments and known site changes.`],avoidWhen:[`You want the report to claim the update caused every change.`,`The comparison periods are incomplete or contain major unrecorded changes.`],outcome:`A post-update review of winners, losers, confounders, and next checks.`}};function V9(e){let t=B9[e],n=ste[e];if(t&&n)return{...t,...n}}function cte(e){e.registerTool(`seo_audit_page`,{description:`Run a single-page technical and content audit`,inputSchema:{url:R.string().url(),site:R.string().optional(),js:R.boolean().optional(),refresh:R.boolean().optional()}},async({url:e,site:t,js:n,refresh:r})=>{try{let i=await VC({url:e,site:t,js:O9(n,`auto`),refresh:r});return E9(`Audit complete for ${e}. Found ${i.issues.length} issues.`,i)}catch(e){return T9(e)}})}const lte=k9([`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]);function ute(e){return{verifyContent:e.verifyContent,verifyLimit:e.verifyLimit,js:O9(e.js,void 0),rate:L9({fetchConcurrency:e.fetchConcurrency,fetchIntervalCap:e.fetchIntervalCap,fetchIntervalMs:e.fetchIntervalMs}),refresh:e.refresh}}function dte(e){e.registerTool(`seo_second_page`,{description:`Find URLs with GSC average position above 10 through 20 and return evidence-grounded investigation prompts`,inputSchema:{...k9([`site`,`range`,`minImpressions`,`limit`,`includeBrand`]),...lte,range:R.number().int().min(1).max(548).optional(),minImpressions:R.number().int().min(0).max(1e9).optional(),limit:R.number().int().min(1).max(100).optional(),verifyLimit:R.number().int().min(0).max(100).optional(),brandTerms:R.array(R.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:R.number().int().min(1).max(16).optional(),fetchIntervalCap:R.number().int().min(1).max(60).optional(),fetchIntervalMs:R.number().int().min(100).max(6e4).optional()}},async({site:e,range:t,minImpressions:n,limit:r,includeBrand:i,brandTerms:a,...o})=>{try{let s=await JB({site:e,range:t,minImpressions:n,limit:r,includeBrand:i,brandTerms:a,...ute(o)});return E9(s.summary.verdict,s)}catch(e){return T9(e)}})}function fte(e){cte(e),dte(e)}function H9(e){let t=CV(e),n=w9({...e,presentation:t});return E9(e.summary,n,{markdown:wV(e)})}function U9(e){e.registerTool(`seo_workflow_diagnose_property`,{description:`Run the full agent workflow for property diagnosis and next actions`,inputSchema:{...k9([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`refresh`])}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,refresh:a})=>{try{return H9(await mV({site:e,days:t,recentDays:n,limit:r,includeBrand:i,refresh:a}))}catch(e){return T9(e)}}),e.registerTool(`seo_workflow_update_postmortem`,{description:`Run winner/loser postmortem analysis for recent Google update exposure`,inputSchema:{...k9([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`refresh`]),knownConfounders:R.array(R.string()).optional()}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,knownConfounders:a,refresh:o})=>{try{return H9(await eH({site:e,days:t,recentDays:n,limit:r,includeBrand:i,knownConfounders:a,refresh:o}))}catch(e){return T9(e)}}),e.registerTool(`seo_workflow_refresh_priorities`,{description:`Rank decay, striking-distance, quick-win, cannibalisation, and diagnosis signals into an action queue`,inputSchema:{...k9([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`refresh`]),googleAnalyticsPropertyId:R.string().optional()}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,googleAnalyticsPropertyId:a,verifyContent:o,verifyLimit:s,refresh:c})=>{try{return H9(await LV({site:e,days:t,recentDays:n,limit:r,includeBrand:i,googleAnalyticsPropertyId:a,verifyContent:o,verifyLimit:s,refresh:c}))}catch(e){return T9(e)}})}const pte=[`ai-search`,`crawl`,`diagnosis`,`monitoring`,`opportunities`,`reporting`,`setup`,`workflows`],mte=[],hte=[{category:`setup`,register:R9,names:[`seo_doctor`]},{category:`diagnosis`,register:R9,names:[`seo_segment_impact`,`seo_striking_distance`,`seo_traffic_anomaly`,`seo_update_correlate`]},{category:`opportunities`,register:ote,names:[`seo_cannibal`,`seo_ctr_underperformers`,`seo_decaying`,`seo_internal_links`,`seo_query_cluster`,`seo_quick_wins`]},{category:`ai-search`,register:ete,names:[`seo_ai_referrals`,`seo_content_optimization`,`seo_page_opportunities`,`seo_performance_audit`]},{category:`crawl`,register:tte,names:[`seo_audit_urls`,`seo_crawl_site`,`seo_explain_issue`,`seo_list_rules`,`seo_top_fixes`]},{category:`monitoring`,register:nte,names:[`seo_index_coverage`,`seo_link_recover`,`seo_redirect_trace`]},{category:`reporting`,register:fte,names:[`seo_audit_page`,`seo_second_page`]},{category:`workflows`,register:U9,names:[`seo_workflow_diagnose_property`,`seo_workflow_refresh_priorities`,`seo_workflow_update_postmortem`]}],gte={cannibal:`cannibalisation`,decaying:`decaying-pages`,"crawl-site":`site-crawl`,"link-recover":`link-recovery`,"query-cluster":`query-clusters`,"workflow-refresh-priorities":`refresh-priorities`,"workflow-update-postmortem":`update-postmortem`,"workflow-diagnose-property":`search-performance-overview`,doctor:`setup-check`,"update-correlate":`update-correlation`,"list-rules":`crawler-rules`,"explain-issue":`explain-crawl-issue`};function _te(e){let t=e.replace(/^seo_/,``).replaceAll(`_`,`-`);return gte[t]??t}function vte(e,t){return e.id<t.id?-1:+(e.id>t.id)}function yte(e){let t=/* @__PURE__ */ new Map;return e({registerTool(e,n,r){t.set(e,{inputSchema:n.inputSchema,handler:r})}}),t}function bte(e){return e instanceof R.ZodObject?e:R.strictObject(e??{})}function xte(){let e=/* @__PURE__ */ new Map,t=mte.map(e=>{let t=V9(e.id);if(!t)throw Error(`MCP report registry is missing guidance for ${e.id}.`);return{...e,...t}});for(let n of hte){let r=e.get(n.register);r||(r=yte(n.register),e.set(n.register,r));for(let e of n.names){let i=r.get(e);if(!i)throw Error(`MCP report registry references missing tool ${e}.`);let a=_te(e),o=V9(a);if(!o)throw Error(`MCP report registry is missing guidance for ${a}.`);t.push({id:a,category:n.category,...o,inputSchema:bte(i.inputSchema),handler:i.handler})}}return t.sort(vte)}const W9=xte(),Ste=new Set(W9.map(e=>e.id)),G9=Object.keys(B9).filter(e=>!Ste.has(e));if(G9.length>0)throw Error(`MCP report guidance references unknown reports: ${G9.join(`, `)}.`);const Cte=new Map(W9.map(e=>[e.id,e]));function K9(e){return W9.filter(t=>!e||t.category===e).map(({id:e,name:t,description:n,category:r})=>({id:e,category:r,name:t,description:n}))}function wte(e){return Cte.get(e)}function Tte(e){return e.issues.map(e=>`${e.path.length>0?e.path.join(`.`):`input`}: ${e.message}`).join(`; `)}const q9={"affected-urls":`seo crawl`,"agent-readiness":null,"ai-mention-research":null,"ai-prompt-observations":null,"ai-readiness":null,"ai-search-scorecard":null,"bing-webmaster-overview":null,"community-intent":null,"compare-crawls":`seo crawl`,"competitive-opportunities":`seo research`,"competitor-keyword-gap":`seo research competitors`,"crawl-diff":`seo crawl`,"crawl-history":`seo crawl`,"crawl-report":`seo crawl`,"domain-overview":`seo research ranked_keywords`,"domain-rating":`seo research`,"entity-readiness":null,"generate-llms-txt":null,"geo-gaps":null,"index-coverage-plan":`seo index`,"index-monitor":`seo index`,"index-watch":`seo page --url <url>`,"keyword-metrics":`seo research keyword_metrics`,"keyword-opportunities":`seo research`,"keyword-research":`seo research keyword_metrics`,"link-evidence":`seo research backlinks`,"llms-txt-audit":null,"local-search-demand":null,"measure-change":`seo compare --date <date>`,"monthly-action-plan":`seo report`,"monthly-report":`seo report`,"narrative-report":`seo report`,"okf-build":null,"okf-validate":null,"pseo-audit":null,"pseo-opportunities":null,"pseo-patterns":null,"rank-tracking":null,"ranked-keywords":`seo research ranked_keywords`,"ranking-pages":`seo research ranked_keywords`,"saved-keywords":null,"seo-to-ai-query":null,"serp-competitors":`seo research competitors`,"serp-results":`seo research serp`,"server-log-analysis":null,"technical-watch":`seo crawl`},Ete={cannibalization:`cannibalisation`,"content-decay":`decaying-pages`,"low-ctr":`ctr-underperformers`,"traffic-drop":`traffic-anomaly`};function J9(e){let t=Ete[e]??e;if(Object.hasOwn(q9,t)){let e=q9[t];throw new P(`INVALID_INPUT`,e?`The ${t} report was removed. Use \`${e}\` instead.`:`The ${t} report was removed. Run \`seo help\` for the commands.`)}let n=wte(t);if(!n)throw new P(`INVALID_INPUT`,`Unknown report: ${t}. Reports: ${K9().map(e=>e.id).join(`, `)}.`);return n}function Dte(e){return K9(e)}function Ote(e){let t=J9(e);return{id:t.id,category:t.category,name:t.name,description:t.description,useWhen:t.useWhen,avoidWhen:t.avoidWhen,outcome:t.outcome,readOrder:t.readOrder,doNotClaim:t.doNotClaim,verify:t.verify,related:t.related,agentWorkflow:{actionView:{mcp:{id:t.id,view:`actions`},cli:`seo reports run ${t.id} --params '<json>' --actions-only --json`},readOrder:[`findings.coverage and report-level caveats`,`findings.items in returned priority order`,`inventories row by row when present`],completion:`Use each finding type and its allowed outcomes. Fix items support fixed, deferred, or not-needed. Review items support changed, no-change, or deferred. Verify changed items and rerun this report before closing them.`},inputSchema:R.toJSONSchema(t.inputSchema)}}async function Y9(e,t={},n={}){let r=J9(e),i=r.inputSchema.safeParse(t);if(!i.success)throw new P(`INVALID_INPUT`,`Invalid parameters for ${e}: ${Tte(i.error)}`);let a=await r.handler(i.data);if(a.isError||!a.structuredContent)return a;let o={reportId:r.id,verify:r.verify},s=n.view===`actions`?hr(a.structuredContent,o):a.structuredContent;return{...a,structuredContent:w9(s)}}const X9={readOnlyHint:!0,destructiveHint:!1,openWorldHint:!0};function Z9(e){return{content:[{type:`text`,text:e}]}}async function kte(e,t,n,r){let i=n?m$(e,{section:typeof t.section==`string`?t.section:void 0,action:typeof t.action==`string`?t.action:void 0}):null;i&&n&&aa(i,n());try{let e=await r();return i&&n&&(e.isError?sa(i,e.structuredContent?.error,n()):oa(i,n())),e}catch(e){let t=T0(e);return i&&n&&sa(i,t,n()),T9(t)}}async function Q9(e,t,n,r){let i=await kte(e,t,n,r),a=v4();return a?{...i,content:[...i.content,{type:`text`,text:a}]}:i}function Ate(e,t={}){let n={deps:m0({call:$$}),resolveSite:e=>C0(e),keys:b0,refreshClicky:S0,drKey:null,researchStore:h0(),installedSerp:h2,accounts:y0,signIn:Es.signIn,connect:"run `seo login` to use your seoskill.dev account (Google, Bing, Index My Site and keys in one place), or `seo auth login`, `seo providers bing connect`, `seo providers indexmysite connect` and `seo providers dataforseo connect` or `seo providers ahrefs connect` on this machine only.",readFiles:e=>L0(e)};for(let r of Y$)e.registerTool(r.name,{title:r.title,description:r.description,inputSchema:(r.localInput??r.input).shape,annotations:K$(r)},async e=>Q9(r.command,e,t.telemetry,async()=>Z9((await Z$(r,n,e,!0)).text)));e.registerTool(`seo_crawl`,{title:`Crawl a site`,description:`Crawls a site from this machine and returns technical issues and the URLs they affect.`,inputSchema:{url:R.url()},annotations:X9},async({url:e})=>Q9(`crawl`,{},t.telemetry,()=>Y9(`site-crawl`,{url:e}))),e.registerTool(`seo_internal_links`,{title:`Internal links`,description:`Internal links to add, crawled from this machine. Send site to audit a whole site, or url to find links to one page. Each link names a real sentence on the source and a real phrase from it as anchor text. With a TypeSafe key (TYPESAFE_API_KEY or the seoskill.dev account), Jev classifies pages and judges each link; without one the result says Jev was not used. Search Console query overlap is added when this login has the property.`,inputSchema:{site:R.string().min(1).optional().describe(`Site to audit: a domain, URL or Search Console property.`),url:R.url().optional().describe(`One page to find links to.`),max_pages:R.number().int().min(1).max(oL).optional().describe(`site only: pages to crawl, 500 by default, up to 5,000.`),start_date:R.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD for Search Console. Optional; send with end_date.`),end_date:R.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD. Optional; send with start_date.`),detail:R.enum([`summary`,`rows`,`full`]).default(`summary`).describe(`summary first. rows: the next page of links. full: every field as JSON.`),offset:R.number().int().min(0).default(0).describe(`rows only: the first link to return.`)},annotations:X9},async({site:e,url:n,max_pages:r,start_date:i,end_date:a,detail:o,offset:s})=>Q9(`internal-links`,{},t.telemetry,async()=>{try{if(!!e==!!n)throw new P(`INVALID_INPUT`,`Send site to audit a whole site, or url to find links to one page.`);let t=n??e;return Z9(SJ(await bR({site:t,targetUrl:n,maxPages:r,startDate:i,endDate:a},await x0({site:t})),{detail:o,offset:s,more:(t,i)=>$$(`internal-links`,{...n?{url:n}:{site:e},...r?{max_pages:r}:{},detail:t,offset:i})}))}catch(e){return T9(T0(e))}}))}function jte(){for(let e of[`../skills/seo/SKILL.md`,`../../../skills/seo/SKILL.md`])try{return Ut(new URL(e,import.meta.url),`utf8`)}catch{}return null}function $9(e={}){let t=new Gee({...Q$,title:`SEO Skill (local)`,description:`${Q$.description} Runs on your machine.`,version:Ai},{capabilities:{logging:{}},instructions:`SEO Skill reads the person's own Search Console, Google Analytics, Bing Webmaster Tools, Clicky, Simple Analytics and optional keyword accounts, and returns facts with their dates and limits. It gives no advice.
|
|
478
478
|
1. seo_sites: the properties the connected accounts can read.
|
|
479
479
|
2. seo_report: start here. Without site it summarises last week across every site in the weekly site audit and names the site to ask about next. With site it shows that property's overview and every section's count and top rows; then ask for the one section you need. Section issues keeps a list of what it found for the site between sessions; mark records which the person fixed or wants ignored.
|
|
480
480
|
3. seo_page for one URL, seo_compare for before and after a date, seo_index for Google's indexing reasons and pages that lost their clicks, seo_research for keyword, competitor and backlink data, and whether AI answers cite the site, from the DataForSEO or Ahrefs key the person saved, seo_data for raw rows, including Google Analytics, Bing, Clicky and Simple Analytics.
|
|
@@ -482,4 +482,4 @@ if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid
|
|
|
482
482
|
5. seo_lint checks copy you are writing or editing (a landing page, blog post, title or meta description) for patterns common in AI-written text and for title and description length. It reads only the text or files you give it.
|
|
483
483
|
seo_crawl and seo_internal_links run on this machine. Keys and Google sign-in come from \`seo start\` and \`seo providers <name> connect\`.`}),n=()=>({clientName:t.server.getClientVersion()?.name});Ate(t,{telemetry:e.telemetry===!1?void 0:n}),Qee(t);let r=jte();if(r){let{name:e,uri:n,...i}=e1;t.registerResource(e,n,i,async e=>({contents:[{uri:e.href,mimeType:i.mimeType,text:r}]}))}return e.telemetry!==!1&&(t.server.oninitialized=()=>{ra(n())}),t}async function Mte(e={}){let t=$9();if(e.test){process.stdout.write(`seo MCP server constructed successfully.
|
|
484
484
|
`);return}let n=new Zee;await t.connect(n),v4()}export{g1 as $,bo as $n,GF as $t,b0 as A,jT as An,Rr as Ar,cG as At,K1 as B,Nc as Bn,LV as Bt,U0 as C,JD as Cn,iee as Cr,Fq as Ct,T0 as D,KE as Dn,ai as Dr,MG as Dt,y0 as E,UD as En,Di as Er,VK as Et,Z1 as F,Fx as Fn,tH as Ft,M1 as G,Es as Gn,sz as Gt,k1 as H,cc as Hn,JB as Ht,Q1 as I,Lx as In,aH as It,D1 as J,ds as Jn,bR as Jt,C1 as K,Ss as Kn,nz as Kt,F1 as L,Ix as Ln,nH as Lt,m0 as M,TC as Mn,Jn as Mr,lG as Mt,J1 as N,vC as Nn,oG as Nt,x0 as O,HE as On,ii as Or,NG as Ot,$1 as P,hC as Pn,aG as Pt,f1 as Q,xo as Qn,pI as Qt,I1 as R,Wx as Rn,rH as Rt,G0 as S,$D as Sn,aa as Sr,Pq as St,O0 as T,WD as Tn,Ei as Tr,Sq as Tt,P1 as U,ac as Un,aB as Ut,W1 as V,oee as Vn,pV as Vt,N1 as W,rc as Wn,Rz as Wt,_1 as X,ko as Xn,HI as Xt,E1 as Y,wo as Yn,VI as Yt,m1 as Z,To as Zn,hI as Zt,u2 as _,zA as _n,Vi as _r,EY as _t,Y9 as a,_M as an,va as ar,LQ as at,K0 as b,QD as bn,oa as br,SJ as bt,h4 as c,Lj as cn,Va as cr,IZ as ct,X2 as d,dj as dn,Ha as dr,IX as dt,SF as en,So as er,B$ as et,T2 as f,fj as fn,za as fr,dX as ft,l2 as g,RA as gn,ra as gr,wY as gt,c2 as h,NA as hn,ea as hr,RY as ht,Ote as i,ZM as in,Ia as ir,$Q as it,h0 as j,VC as jn,Yn as jr,sG as jt,S0 as k,VT as kn,Pr as kr,OG as kt,v4 as l,Mj as ln,Ba as lr,KZ as lt,h2 as m,BA as mn,qi as mr,jX as mt,w9 as n,xN as nn,Oo as nr,a$ as nt,Dte as o,DM as on,La as or,xQ as ot,v2 as p,kA as pn,Ra as pr,MX as pt,O1 as q,ps as qn,ez as qt,$9 as r,$M as rn,la as rr,d$ as rt,Mte as s,gM as sn,pa as sr,FZ as st,pte as t,aF as tn,Eo as tr,m$ as tt,d4 as u,pj as un,Ea as ur,uZ as ut,J0 as v,YD as vn,ta as vr,_Y as vt,L0 as w,XD as wn,Ai as wr,uq as wt,W0 as x,ZD as xn,sa as xr,tJ as xt,q0 as y,qD as yn,ree as yr,wJ as yt,q1 as z,qx as zn,eH as zt};
|
|
485
|
-
//# sourceMappingURL=dist-
|
|
485
|
+
//# sourceMappingURL=dist-BqfqFOEM.js.map
|