@a2f0/agent-tool 0.1.69 → 0.1.70

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.
@@ -0,0 +1,250 @@
1
+ /**
2
+ * `agent-tool seo probe`: a host's live search and preview metadata, for the
3
+ * seo-optimization skill. It reports what the deployed site serves before
4
+ * JavaScript runs; it changes nothing, but it requests whatever URLs its
5
+ * arguments and the fetched pages name.
6
+ */
7
+ import { writeSync } from "node:fs";
8
+ import {
9
+ attr, attrValues, canonicalOf, clip, collapse, contentOf, first, internalLinks, isSitemapDocument,
10
+ length, lines, locs, matches, names, pngSize, robotsMeta, titleOf,
11
+ } from "./html";
12
+ import { follow, request, type Followed, type Reply, type RequestOptions } from "./http";
13
+
14
+ export const USAGE = `Usage: agent-tool seo probe [--page|--headers|--links|--sitemap] <host> [path...]
15
+
16
+ seo probe <host> [path] page report, then site files
17
+ seo probe --page <host> [path] page report only
18
+ seo probe --headers <host> <path>... one line per path, redirects not
19
+ followed: status, X-Robots-Tag,
20
+ type, Location
21
+ seo probe --links <host> [path] internal links on the page that do
22
+ not answer 200 directly; resolved
23
+ against the final URL, not <base>
24
+ seo probe --sitemap <host> every sitemap URL: status, canonical,
25
+ robots, duplicate titles/descriptions;
26
+ follows one level of sitemap index
27
+
28
+ The host is a hostname with an optional port, and each path starts with /.
29
+ --links and --sitemap exit 1 when they find a problem. An unreachable host
30
+ exits 1 and a usage error exits 2. Set SEO_PROBE_USER_AGENT to send a browser
31
+ user agent; SEO_PROBE_SCHEME (default https) exists for tests.`;
32
+
33
+ type Mode = "full" | "page" | "headers" | "links" | "sitemap";
34
+ const MODES: Record<string, Mode> = { "--page": "page", "--headers": "headers", "--links": "links", "--sitemap": "sitemap" };
35
+
36
+ export interface ProbeOptions {
37
+ mode: Mode;
38
+ host: string;
39
+ paths: string[];
40
+ scheme: "http" | "https";
41
+ userAgent: string;
42
+ }
43
+
44
+ class UsageError extends Error {}
45
+
46
+ /** Bun before 1.4 keeps only the last of repeated response headers, which can hide an X-Robots-Tag noindex. */
47
+ export function keepsRepeatedHeaders(version: string): boolean {
48
+ const [major = 0, minor = 0] = version.split(".").map(Number);
49
+ return major > 1 || (major === 1 && minor >= 4);
50
+ }
51
+
52
+ export function parseProbe(args: string[], env: NodeJS.ProcessEnv): ProbeOptions {
53
+ const rest = [...args];
54
+ const mode = rest[0] !== undefined && Object.hasOwn(MODES, rest[0]) ? MODES[rest.shift()!]! : "full";
55
+ const host = rest.shift();
56
+ if (!host || host.startsWith("-")) throw new UsageError(host ? `Unknown option '${host}'.` : "A host is required.");
57
+ // A host with a path, query, or user info could send the probe somewhere else entirely.
58
+ if (/[/?#@\\\s]/.test(host) || !URL.canParse(`http://${host}/`)) throw new UsageError(`'${host}' is not a hostname with an optional port.`);
59
+ for (const value of rest) {
60
+ if (value.startsWith("-")) throw new UsageError(`Unknown option '${value}'; the mode flag comes first.`);
61
+ if (!value.startsWith("/")) throw new UsageError(`Path '${value}' must start with /.`);
62
+ }
63
+ if (mode === "headers" && rest.length === 0) throw new UsageError("--headers needs at least one path.");
64
+ if (mode === "sitemap" && rest.length > 0) throw new UsageError("--sitemap takes no path.");
65
+ if (mode !== "headers" && rest.length > 1) throw new UsageError("Only --headers takes more than one path.");
66
+ const scheme = env.SEO_PROBE_SCHEME || "https";
67
+ if (scheme !== "http" && scheme !== "https") throw new UsageError("SEO_PROBE_SCHEME must be http or https.");
68
+ return { mode, host, paths: rest, scheme, userAgent: env.SEO_PROBE_USER_AGENT || "seo-probe" };
69
+ }
70
+
71
+ const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes);
72
+ /** "first-status [-> location] => final-status content-type", or just the final part without a redirect. */
73
+ function describe({ first: hop, final }: Followed): string {
74
+ const result = `${final.code} ${final.contentType}`;
75
+ return hop.location ? `${hop.code} -> ${hop.location} => ${result}` : result;
76
+ }
77
+ const okHtml = (result: string) => result.startsWith("200 text/html") || result.includes("=> 200 text/html");
78
+ const okStatus = (result: string) => result.startsWith("200 ") || result.includes("=> 200 ");
79
+ const tag = (reply: Reply) => reply.robotsTag || "(absent)";
80
+
81
+ /** Run one probe, printing each line as it is known; resolves to the exit status. */
82
+ export async function probe(options: ProbeOptions, print: (line: string) => void): Promise<number> {
83
+ const { host, paths, mode } = options;
84
+ const origin = `${options.scheme}://${host}`;
85
+ const bust = `seo-probe=${Math.floor(Date.now() / 1000)}`;
86
+ const withBust = (url: string) => `${url}${url.includes("?") ? "&" : "?"}${bust}`;
87
+ const unbust = (url: string) => url.replace(new RegExp(`[?&]${bust}`), "");
88
+ const web = (seconds: number, body = true): RequestOptions => ({ userAgent: options.userAgent, seconds, body });
89
+
90
+ const reachable = await request(`${origin}/`, web(15, false));
91
+ if (reachable.code === "000") { print(`### ${host} does not respond: ${reachable.error ?? ""}`); return 1; }
92
+
93
+ if (mode === "headers") {
94
+ for (const path of paths) {
95
+ const reply = await request(withBust(origin + path), web(20, false));
96
+ const location = unbust(reply.location);
97
+ print(`${host}${path} ${reply.code} x-robots-tag: ${tag(reply)} type: ${reply.contentType || "-"}${location ? ` -> ${location}` : ""}`);
98
+ }
99
+ return 0;
100
+ }
101
+
102
+ if (mode === "links") {
103
+ const path = paths[0] ?? "/";
104
+ const page = await follow(withBust(origin + path), web(20));
105
+ const pageResult = describe(page);
106
+ if (!okHtml(pageResult)) { print(`### ${host}${path} page: ${pageResult} (cannot audit its links)`); return 1; }
107
+ const finalUrl = new URL(page.final.url);
108
+ const finalOrigin = `${finalUrl.protocol}//${finalUrl.host}`;
109
+ const links = internalLinks(collapse(decode(page.final.body)), finalUrl);
110
+ let bad = 0;
111
+ for (const link of links) {
112
+ const reply = await request(withBust(link), web(20, false));
113
+ if (reply.code === "200") continue;
114
+ bad++;
115
+ print(` ${link.startsWith(finalOrigin) ? link.slice(finalOrigin.length) : link} ${reply.code}${reply.location ? ` -> ${reply.location}` : ""}`);
116
+ }
117
+ if (finalUrl.host !== new URL(origin).host) print(` (links resolved against ${finalOrigin} after a redirect)`);
118
+ print(`### ${host}${path} internal links in the static HTML: ${links.length}, not a direct 200: ${bad}`);
119
+ if (links.length === 0) print(" (no links in the static HTML; a client-rendered page needs a browser check)");
120
+ return bad === 0 ? 0 : 1;
121
+ }
122
+
123
+ if (mode === "sitemap") return sitemap(host, origin, withBust, web, print);
124
+
125
+ const path = paths[0] ?? "/";
126
+ const page = await follow(withBust(origin + path), web(20));
127
+ const body = collapse(decode(page.final.body));
128
+ const title = titleOf(body);
129
+ const description = contentOf(body, "description");
130
+ print(`### ${host}${path} [${describe(page)}]`);
131
+ print(` x-robots-tag: ${tag(page.final)}`);
132
+ print(` title (${length(title)} chars): ${title}`);
133
+ print(` description (${length(description)} chars): ${clip(description)}`);
134
+ print(` canonical: ${canonicalOf(body)}`);
135
+ print(` robots meta: ${robotsMeta(body)}`);
136
+ print(` lang: ${attr(first(body, '<html[^>]*lang="[^"]*"'), "lang")}`);
137
+ print(` theme-color: ${matches(body, '<meta[^>]+name="theme-color"[^>]*>').flatMap(meta => attrValues(meta, "content")).map(value => `${value} `).join("")}`);
138
+ print(` og: ${names(body, 'property="og:[a-z_:]+"').replace(/property=/g, "")}`);
139
+ print(` og:url: ${contentOf(body, "og:url")}`);
140
+ print(` twitter:card: ${contentOf(body, "twitter:card")}`);
141
+ print(` json-ld blocks: ${matches(body, "application/ld\\+json").length}`);
142
+ print(` json-ld types (including nested): ${names(body, '"@type": *("[A-Za-z]+"|\\[[^\\]]*\\])').replace(/"@type": */g, "")}`);
143
+ print(` h1 count (static HTML, before JavaScript): ${matches(body, "<h1[ >]").length}`);
144
+ const image = contentOf(body, "og:image");
145
+ if (image) {
146
+ const fetched = await follow(withBust(image), web(20));
147
+ const size = pngSize(fetched.final.body);
148
+ print(` og:image: ${image} [${describe(fetched)}] ${size ? `size ${size}` : ""} x-robots-tag: ${tag(fetched.final)}`);
149
+ } else {
150
+ print(" og:image: none");
151
+ }
152
+ if (mode === "page") return 0;
153
+
154
+ const robots = await follow(withBust(`${origin}/robots.txt`), web(20));
155
+ const robotsText = decode(robots.final.body);
156
+ const robotsLines = lines(robotsText);
157
+ let robotsResult = describe(robots);
158
+ if (robotsResult.includes("text/html")) robotsResult += " (HTML, not a robots file)";
159
+ if (robotsText.includes("BEGIN Cloudflare Managed")) robotsResult += " (includes Cloudflare managed content)";
160
+ else if (robotsLines.some(line => /^#.*content signals/i.test(line))) robotsResult += " (Cloudflare content-signals file)";
161
+ const directives = robotsLines.filter(line => !/^#|^\s*$/.test(line));
162
+ if (robotsLines.some(line => !line.startsWith("#") && /^content-signal:/i.test(line))) robotsResult += " (has Content-Signal directives)";
163
+ else if (robots.final.body.length > 0 && directives.length === 0) robotsResult += " (comments only: no directives)";
164
+ print(` robots.txt: ${robotsResult} x-robots-tag: ${tag(robots.final)}`);
165
+ if (!robotsResult.includes("HTML")) {
166
+ for (const line of directives.slice(0, 15)) print(` | ${line}`);
167
+ if (directives.length > 15) {
168
+ const sitemaps = directives.filter(line => /^sitemap:/i.test(line));
169
+ print(` | ... ${sitemaps.length} Sitemap line(s):`);
170
+ for (const line of sitemaps) print(` | ${line.replace(/\r/g, "")}`);
171
+ }
172
+ }
173
+ const sitemapReply = await follow(withBust(`${origin}/sitemap.xml`), web(20));
174
+ let sitemapResult = describe(sitemapReply);
175
+ if (sitemapResult.includes("text/html")) sitemapResult += " (HTML, not a sitemap)";
176
+ print(` sitemap.xml: ${sitemapResult} urls: ${decode(sitemapReply.final.body).split("<loc>").length - 1}`);
177
+ const missing = await follow(withBust(`${origin}/seo-probe-missing-page`), web(20));
178
+ print(` missing path: ${describe(missing)} body: ${missing.final.body.length} bytes title: ${titleOf(collapse(decode(missing.final.body)))}`);
179
+ const nested = await follow(withBust(`${origin}/seo-probe/missing/page`), web(20));
180
+ print(` nested missing path: ${describe(nested)} body: ${nested.final.body.length} bytes`);
181
+ const error = await follow(withBust(`${origin}/404`), web(20));
182
+ print(` /404: ${describe(error)} robots meta: ${robotsMeta(collapse(decode(error.final.body)))} x-robots-tag: ${tag(error.final)}`);
183
+ const http = await request(withBust(`http://${host}/`), web(15, false));
184
+ const httpResult = unbust(`${http.code} ${http.location}`);
185
+ const httpNote = /^30[178] https:\/\//.test(httpResult) ? "redirects to HTTPS" : "does not redirect to HTTPS";
186
+ print(` http:// root: ${httpResult} (${httpNote}) x-robots-tag: ${tag(http)}`);
187
+ return 0;
188
+ }
189
+
190
+ /** Every URL in the sitemap, through one level of sitemap index, without following redirects. */
191
+ async function sitemap(host: string, origin: string, withBust: (url: string) => string, web: (seconds: number, body?: boolean) => RequestOptions, print: (line: string) => void): Promise<number> {
192
+ const index = await follow(withBust(`${origin}/sitemap.xml`), web(20));
193
+ const indexResult = describe(index);
194
+ const indexBody = decode(index.final.body);
195
+ if (!okStatus(indexResult) || !isSitemapDocument(indexBody)) { print(`### ${host} sitemap.xml: ${indexResult} (not a sitemap document)`); return 1; }
196
+ let urls = locs(indexBody);
197
+ let problems = 0;
198
+ if (indexBody.includes("<sitemapindex")) {
199
+ const children: string[] = [];
200
+ for (const child of urls) {
201
+ const reply = await follow(withBust(child), web(20));
202
+ const result = describe(reply);
203
+ const body = decode(reply.final.body);
204
+ if (okStatus(result) && isSitemapDocument(body) && body.includes("<urlset")) children.push(...locs(body));
205
+ else { problems++; print(` ${child}: child sitemap ${result}, not a urlset;`); }
206
+ }
207
+ urls = children;
208
+ }
209
+ const titles: string[] = [], descriptions: string[] = [];
210
+ for (const url of urls) {
211
+ const reply = await request(withBust(url), web(20));
212
+ const body = collapse(decode(reply.body));
213
+ const canonical = canonicalOf(body);
214
+ const robots = ` ${`${reply.robotsTag} ${robotsMeta(body)}`.toLowerCase()} `;
215
+ let note = "";
216
+ if (reply.code !== "200") note += ` status ${reply.code};`;
217
+ if (canonical !== url) note += ` canonical ${canonical || "missing"};`;
218
+ if (robots.includes("noindex") || /[ ,:]none[ ,]/.test(robots)) note += " noindex;";
219
+ if (note) { problems++; print(` ${url}:${note}`); }
220
+ titles.push(titleOf(body));
221
+ descriptions.push(contentOf(body, "description"));
222
+ }
223
+ for (const [kind, values] of [["titles", titles], ["descriptions", descriptions]] as const) {
224
+ const counts = new Map<string, number>();
225
+ for (const value of values) if (value) counts.set(value, (counts.get(value) ?? 0) + 1);
226
+ const duplicates = [...counts].filter(([, count]) => count > 1).sort(([a, x], [b, y]) => y - x || (a < b ? 1 : a > b ? -1 : 0));
227
+ problems += duplicates.length;
228
+ for (const [value, count] of duplicates.slice(0, 5)) print(` duplicate ${kind} (count, text): ${count} ${value}`);
229
+ }
230
+ if (urls.length === 0) { problems++; print(" (the sitemap lists no URLs)"); }
231
+ print(`### ${host} sitemap URLs: ${urls.length}, with problems: ${problems}`);
232
+ return problems === 0 ? 0 : 1;
233
+ }
234
+
235
+ /** `agent-tool seo <action>`: exit 0, 1 for a found problem or an unreachable host, 2 for usage. */
236
+ export async function seoCommand(args: string[], env: NodeJS.ProcessEnv = process.env, print = (line: string) => { writeSync(1, `${line}\n`); }, version = Bun.version): Promise<number> {
237
+ const [action, ...rest] = args;
238
+ if (action === "probe" && (rest[0] === "--help" || rest[0] === "-h") && rest.length === 1) { print(USAGE); return 0; }
239
+ let options: ProbeOptions;
240
+ try {
241
+ if (action !== "probe") throw new UsageError(action ? `Unknown seo command '${action}'.` : "An seo command is required.");
242
+ options = parseProbe(rest, env);
243
+ } catch (error) {
244
+ if (!(error instanceof UsageError)) throw error;
245
+ writeSync(2, `${error.message}\n\n${USAGE}\n`);
246
+ return 2;
247
+ }
248
+ if (!keepsRepeatedHeaders(version)) throw new Error(`seo probe needs Bun 1.4 or newer, which keeps every repeated response header such as X-Robots-Tag; this is Bun ${version}.`);
249
+ return probe(options, print);
250
+ }