agentface 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,429 +4,483 @@
4
4
  import { parseArgs } from "node:util";
5
5
 
6
6
  // cli/init.mjs
7
- import { readFile, writeFile, readdir, mkdir, stat } from "node:fs/promises";
7
+ import { execFile as execFile2 } from "node:child_process";
8
+ import { mkdir, readFile as readFile2, writeFile } from "node:fs/promises";
9
+ import path2 from "node:path";
10
+
11
+ // worker/origin.js
12
+ var PRIVATE_NAMES = /(?:^|\.)(?:localhost|local|internal|lan|intranet|corp|home|arpa)$/;
13
+ function registrableOrigin(input) {
14
+ const text = String(input ?? "").trim();
15
+ let url;
16
+ try {
17
+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : "https://" + text);
18
+ } catch {
19
+ throw new Error(`"${text}" isn't a web address`);
20
+ }
21
+ const host = url.hostname.replace(/\.$/, "");
22
+ if (url.protocol !== "https:") throw new Error(`Agentface needs the site's https:// address`);
23
+ if (/^[\d.]+$/.test(host) || host.startsWith("["))
24
+ throw new Error("Use the site's domain name, not an IP address");
25
+ if (!host.includes(".") || PRIVATE_NAMES.test(host)) throw new Error(`${host} isn't a public domain name`);
26
+ if (url.port) throw new Error(`Use the site's address without a port`);
27
+ if (url.username || url.password) throw new Error("Leave the user name and password out of the address");
28
+ const origin = `https://${host}`;
29
+ if (url.pathname !== "/" || url.search || url.hash)
30
+ throw new Error(`Agentface works on whole domains: register ${origin}, not a page under it`);
31
+ return origin;
32
+ }
33
+
34
+ // cli/heads.mjs
8
35
  import { execFile } from "node:child_process";
36
+ import { readdir, readFile, stat } from "node:fs/promises";
9
37
  import path from "node:path";
10
-
11
- // src/routes.js
12
- var WELL_KNOWN_DOCS = [
13
- "api-catalog",
14
- "ai-catalog.json",
15
- "poppy.json",
16
- "http-message-signatures-directory",
17
- "agent-card.json",
18
- "oauth-authorization-server",
19
- "oauth-protected-resource",
20
- "oauth-authorization-server/_agent/oauth",
21
- "oauth-protected-resource/_agent/mcp",
22
- "ucp",
23
- "acp.json"
38
+ var EXTENSIONS = [
39
+ "html",
40
+ "htm",
41
+ "php",
42
+ "njk",
43
+ "liquid",
44
+ "hbs",
45
+ "handlebars",
46
+ "mustache",
47
+ "ejs",
48
+ "erb",
49
+ "twig",
50
+ "jinja",
51
+ "jinja2",
52
+ "j2",
53
+ "tmpl",
54
+ "astro"
24
55
  ];
25
- var WELL_KNOWN_DIRS = ["agent-skills", "mcp"];
26
- var FETCH_HEADER = "x-agentface-fetch";
27
- var MARKDOWN_PREFIX = "/_agent/md/";
28
-
29
- // src/connector-core.js
30
- var LINK = '</.well-known/api-catalog>; rel="api-catalog", </_agent/docs>; rel="service-doc"; type="text/markdown", </_agent/openapi.json>; rel="service-desc"; type="application/vnd.oai.openapi+json"';
31
-
32
- // src/generated/connector.js
33
- var CONNECTOR_SCRIPT = `var AgentfaceConnector = (() => {
34
- var __defProp = Object.defineProperty;
35
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
36
- var __getOwnPropNames = Object.getOwnPropertyNames;
37
- var __hasOwnProp = Object.prototype.hasOwnProperty;
38
- var __export = (target, all) => {
39
- for (var name in all)
40
- __defProp(target, name, { get: all[name], enumerable: true });
41
- };
42
- var __copyProps = (to, from, except, desc) => {
43
- if (from && typeof from === "object" || typeof from === "function") {
44
- for (let key of __getOwnPropNames(from))
45
- if (!__hasOwnProp.call(to, key) && key !== except)
46
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
47
- }
48
- return to;
49
- };
50
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
51
-
52
- // src/connector-runtime.js
53
- var connector_runtime_exports = {};
54
- __export(connector_runtime_exports, {
55
- LINK_VALUE: () => LINK_VALUE,
56
- createConnector: () => createConnector,
57
- createMiddleware: () => createMiddleware
56
+ var MARKUP = new RegExp(`\\.(?:${EXTENSIONS.join("|")})$`, "i");
57
+ var LAYOUTS = [
58
+ /(?:^|\/)app\/(?:.+\/)?layout\.[cm]?[jt]sx?$/,
59
+ /(?:^|\/)pages\/_document\.[cm]?[jt]sx?$/,
60
+ /(?:^|\/)app\/root\.[cm]?[jt]sx?$/,
61
+ /(?:^|\/)routes\/__root\.[cm]?[jt]sx?$/,
62
+ /(?:^|\/)src\/html\.[cm]?[jt]sx?$/
63
+ ];
64
+ var SKIP = /* @__PURE__ */ new Set([
65
+ "node_modules",
66
+ "bower_components",
67
+ "vendor",
68
+ "dist",
69
+ "build",
70
+ "out",
71
+ "_site",
72
+ "coverage",
73
+ "tmp",
74
+ "temp",
75
+ "test",
76
+ "tests",
77
+ "__tests__",
78
+ "__mocks__",
79
+ "fixtures",
80
+ "__fixtures__",
81
+ "e2e",
82
+ "cypress",
83
+ "playwright",
84
+ "storybook-static",
85
+ "wp-admin",
86
+ "wp-includes"
87
+ ]);
88
+ var MAIL = /mail/i;
89
+ var MAX_FILES = 2e4;
90
+ var MAX_BYTES = 1e6;
91
+ var CONFIG_HEAD = {
92
+ nuxt: ["Nuxt", "`app.head.script` in nuxt.config"],
93
+ "@docusaurus/core": ["Docusaurus", "`scripts` in docusaurus.config"],
94
+ vitepress: ["VitePress", "`head` in .vitepress/config"]
95
+ };
96
+ var FRAMEWORKS = [
97
+ ["next", "Next.js"],
98
+ ["@tanstack/react-start", "TanStack Start"],
99
+ ["@react-router/dev", "React Router"],
100
+ ["@remix-run/dev", "Remix"],
101
+ ["gatsby", "Gatsby"],
102
+ ["@sveltejs/kit", "SvelteKit"],
103
+ ["astro", "Astro"],
104
+ ["@11ty/eleventy", "Eleventy"],
105
+ ["@angular/core", "Angular"],
106
+ ["react-scripts", "Create React App"],
107
+ ["@vue/cli-service", "Vue CLI"],
108
+ ["vite", "Vite"]
109
+ ];
110
+ var read = (file) => readFile(file, "utf8").catch(() => null);
111
+ var exists = (file) => stat(file).then(
112
+ () => true,
113
+ () => false
114
+ );
115
+ var KEY = /\/s\/(site-[a-z0-9-]+)\.js(?=[?#"'`\s]|$)/;
116
+ var TAG = new RegExp(`<script\\b[^>]*?${KEY.source}[^>]*?(?:\\/>|>\\s*<\\/script\\s*>)`, "gi");
117
+ var OURS = "Added by `npx agentface init`";
118
+ function tagKey(source) {
119
+ return source.match(KEY)?.[1] ?? null;
120
+ }
121
+ function indentUnit(source) {
122
+ return source.match(/^(\t| {2,4})\S/m)?.[1] ?? " ";
123
+ }
124
+ var indentOf = (line) => line.match(/^[ \t]*/)[0];
125
+ function addTag(source, tag) {
126
+ let first = true;
127
+ const replaced = source.replace(new RegExp(`(\\r?\\n[ \\t]*)?${TAG.source}`, "gi"), (match, line) => {
128
+ if (!first) return "";
129
+ first = false;
130
+ return (line ?? "") + tag;
58
131
  });
59
-
60
- // src/routes.js
61
- var WELL_KNOWN_DOCS = [
62
- "api-catalog",
63
- "ai-catalog.json",
64
- "poppy.json",
65
- "http-message-signatures-directory",
66
- "agent-card.json",
67
- "oauth-authorization-server",
68
- "oauth-protected-resource",
69
- "oauth-authorization-server/_agent/oauth",
70
- "oauth-protected-resource/_agent/mcp",
71
- "ucp",
72
- "acp.json"
73
- ];
74
- var WELL_KNOWN_DIRS = ["agent-skills", "mcp"];
75
- var AGENT_PREFIX = "/_agent/";
76
- var FETCH_HEADER = "x-agentface-fetch";
77
- function isWellKnownPath(path) {
78
- if (!path.startsWith("/.well-known/")) return false;
79
- const rest = path.slice("/.well-known/".length);
80
- return WELL_KNOWN_DOCS.includes(rest) || WELL_KNOWN_DIRS.some((dir) => rest.startsWith(dir + "/"));
81
- }
82
- var MARKDOWN_PREFIX = "/_agent/md/";
83
- function markdownPage(path) {
84
- return path.startsWith(MARKDOWN_PREFIX) ? path.slice(MARKDOWN_PREFIX.length - 1) : null;
85
- }
86
- function wantsMarkdown(accept) {
87
- const q = parseAccept(accept);
88
- const md = q.get("text/markdown") ?? 0;
89
- return md > 0 && md >= (q.get("text/html") ?? 0);
132
+ if (!first) return replaced;
133
+ const eol = source.includes("\r\n") ? "\r\n" : "\n";
134
+ const close = source.search(/<\/head\s*>/i);
135
+ if (close !== -1) {
136
+ const lineStart = source.lastIndexOf("\n", close - 1) + 1;
137
+ const before = source.slice(lineStart, close);
138
+ if (!/^[ \t]*$/.test(before)) return source.slice(0, close) + tag + source.slice(close);
139
+ const previous = source.slice(0, lineStart).split(/\r?\n/).findLast((line) => line.trim());
140
+ const sibling = indentOf(previous ?? "");
141
+ const indent = previous && !/<head\b[^>]*>\s*$/i.test(previous) && sibling.startsWith(before) ? sibling : before + indentUnit(source);
142
+ return source.slice(0, lineStart) + indent + tag + eol + source.slice(lineStart);
90
143
  }
91
- function wantsMarkdownPage(accept) {
92
- return !parseAccept(accept).has("text/markdown") || wantsMarkdown(accept);
93
- }
94
- function parseAccept(accept = "") {
95
- const q = /* @__PURE__ */ new Map();
96
- for (const entry of (accept || "").toLowerCase().split(",")) {
97
- const [type, ...params] = entry.split(";").map((s) => s.trim());
98
- if (!type) continue;
99
- const qp = params.find((p) => p.startsWith("q="));
100
- const value = qp ? Number(qp.slice(2)) : 1;
101
- q.set(type, Number.isFinite(value) ? value : 0);
102
- }
103
- return q;
104
- }
105
- var HEALTH_PATH = "/_agent/health";
106
- var PASS_HEADER = "x-agentface-pass";
107
- var ACTION_HEADER = "x-agentface-action";
108
- function agentFeature({ method = "GET", path, accept }) {
109
- if (path === HEALTH_PATH) return "health";
110
- if (path === "/robots.txt") return "robots";
111
- const reading = method === "GET" || method === "HEAD";
112
- if (markdownPage(path) !== null) return reading && wantsMarkdownPage(accept) ? "markdown" : null;
113
- if (path === "/auth.md" || path.startsWith(AGENT_PREFIX) || isWellKnownPath(path)) return "discovery";
114
- return reading && wantsMarkdown(accept) ? "markdown" : null;
115
- }
116
-
117
- // src/connector-core.js
118
- var TIMEOUT_MS = 5e3;
119
- var WRITE_TIMEOUT_MS = 2e4;
120
- var LINK = '</.well-known/api-catalog>; rel="api-catalog", </_agent/docs>; rel="service-doc"; type="text/markdown", </_agent/openapi.json>; rel="service-desc"; type="application/vnd.oai.openapi+json"';
121
- function featureOf(request) {
122
- if (request.headers.has(FETCH_HEADER)) return null;
123
- return agentFeature({
124
- method: request.method,
125
- path: new URL(request.url).pathname,
126
- accept: request.headers.get("accept")
127
- });
128
- }
129
- function isOwnFetch(request) {
130
- return request.headers.has(FETCH_HEADER);
131
- }
132
- var OWN_FETCH_HEADERS = { "cache-control": "private, no-store", vary: FETCH_HEADER };
133
- function mirroredPage(request) {
134
- const url = new URL(request.url);
135
- const page = markdownPage(url.pathname);
136
- return page === null ? null : new URL(page + url.search, url);
137
- }
138
- async function answer(request, service) {
139
- if (!featureOf(request)) return null;
140
- const url = new URL(request.url);
141
- const headers = new Headers(request.headers);
142
- headers.delete("cookie");
143
- headers.delete("host");
144
- headers.set("accept-encoding", "identity");
145
- headers.set(PASS_HEADER, "1");
146
- const target = service + url.pathname + url.search;
147
- const readOnly = ["GET", "HEAD", "OPTIONS"].includes(request.method);
148
- const controller = new AbortController();
149
- const timer = setTimeout(() => controller.abort(), readOnly ? TIMEOUT_MS : WRITE_TIMEOUT_MS);
150
- const init = { method: request.method, headers, redirect: "manual", signal: controller.signal };
151
- try {
152
- if (readOnly) {
153
- const response = await fetch(target, init);
154
- return response.headers.get(ACTION_HEADER) === "origin" || response.status >= 500 ? null : response;
155
- }
156
- return await fetch(target, { ...init, body: request.body, duplex: "half" });
157
- } catch {
158
- if (readOnly) return null;
159
- return new Response('{"error":"agentface_unavailable"}', {
160
- status: 503,
161
- headers: { "content-type": "application/json", "retry-after": "30" }
162
- });
163
- } finally {
164
- clearTimeout(timer);
165
- }
166
- }
167
-
168
- // src/connector-runtime.js
169
- var LINK_VALUE = LINK;
170
- function createConnector({ service }) {
144
+ const html = /<html\b[^>]*>/.exec(source);
145
+ if (!html) return null;
146
+ const end = html.index + html[0].length;
147
+ const child = source.slice(end).match(/^\r?\n([ \t]*)\S/)?.[1];
148
+ if (child === void 0) return source.slice(0, end) + `<head>${tag}</head>` + source.slice(end);
149
+ const outer = indentOf(source.slice(source.lastIndexOf("\n", html.index) + 1));
150
+ const step = child.length > outer.length && child.startsWith(outer) ? child.slice(outer.length) : indentUnit(source);
151
+ const lines = [`${child}<head>`, `${child}${step}${tag}`, `${child}</head>`];
152
+ return source.slice(0, end) + eol + lines.join(eol) + source.slice(end);
153
+ }
154
+ function gitFiles(dir) {
155
+ return new Promise((resolve) => {
156
+ execFile(
157
+ "git",
158
+ ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
159
+ { cwd: dir, maxBuffer: 64 * 1024 * 1024 },
160
+ (error, stdout) => resolve(error ? null : [...new Set(stdout.split("\0").filter(Boolean))].sort())
161
+ );
162
+ });
163
+ }
164
+ async function files(dir, skip) {
165
+ const kept = (name) => !name.startsWith(".") && !skip.has(name) && !MAIL.test(name);
166
+ const tracked = await gitFiles(dir);
167
+ if (tracked)
171
168
  return {
172
- async fetch(request) {
173
- const ours = await answer(request, service);
174
- if (ours) return ours;
175
- const page = mirroredPage(request);
176
- const response = await fetch(page ? new Request(page, request) : request);
177
- if (isOwnFetch(request)) {
178
- const out2 = new Response(response.body, response);
179
- out2.headers.set("cache-control", OWN_FETCH_HEADERS["cache-control"]);
180
- out2.headers.append("vary", OWN_FETCH_HEADERS.vary);
181
- return out2;
182
- }
183
- if (!(response.headers.get("content-type") || "").includes("text/html")) return response;
184
- const out = new Response(response.body, response);
185
- out.headers.append("link", LINK);
186
- out.headers.append("vary", "Accept");
187
- return out;
188
- }
189
- };
190
- }
191
- function createMiddleware({ service }) {
192
- return async function middleware(request) {
193
- const ours = await answer(request, service);
194
- if (ours) return ours;
195
- const page = mirroredPage(request);
196
- if (page) return new Response(null, { headers: { "x-middleware-rewrite": page.href } });
197
- const headers = { "x-middleware-next": "1" };
198
- if (isOwnFetch(request)) Object.assign(headers, OWN_FETCH_HEADERS);
199
- return new Response(null, { headers });
169
+ git: true,
170
+ files: tracked.filter((file) => file.split("/").slice(0, -1).every(kept)).slice(0, MAX_FILES)
200
171
  };
201
- }
202
- return __toCommonJS(connector_runtime_exports);
203
- })();
204
- `;
205
-
206
- // src/connectors.js
207
- function header(site, serviceOrigin, lines, uninstall = "Delete this file to uninstall.") {
208
- return `// Agentface connector for ${site.origin}.
209
- ${lines.map((line) => "// " + line).join("\n")}
210
- // Forwards agent-only requests to Agentface; everything else goes to your site
211
- // untouched. If Agentface is down, slow or failing, agent requests are answered
212
- // by your site as if this file weren't here.
213
- // ${uninstall}
214
- /* eslint-disable */
215
- const SERVICE = ${JSON.stringify(`${serviceOrigin}/s/${site.id}`)};
216
-
217
- ${CONNECTOR_SCRIPT}
218
- `;
172
+ const found = [];
173
+ const visit = async (rel) => {
174
+ const entries = await readdir(path.join(dir, rel), { withFileTypes: true }).catch(() => []);
175
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
176
+ const file = rel ? `${rel}/${entry.name}` : entry.name;
177
+ if (entry.isDirectory()) {
178
+ if (kept(entry.name)) await visit(file);
179
+ } else if (entry.isFile() && found.length < MAX_FILES) found.push(file);
180
+ }
181
+ };
182
+ await visit("");
183
+ return { git: false, files: found };
219
184
  }
220
- var STATIC_FILES = "avif|bmp|css|eot|gif|gz|ico|jpe?g|js|json|map|mjs|mp3|mp4|ogg|otf|pdf|png|svg|ttf|txt|wasm|wav|webm|webmanifest|webp|woff2?|xml|zip";
221
- var PAGES = `(?!_next/|_vercel/|_agent/|api/|\\.well-known/|auth\\.md$|.*\\.(?:${STATIC_FILES})$).*`;
222
- var ACCEPTS_MARKDOWN = { type: "header", key: "accept", value: ".*text/markdown.*" };
223
- function vercelMatchers({ next = true } = {}) {
224
- return [
225
- ...next ? [{ source: `/(${PAGES})`, has: [ACCEPTS_MARKDOWN] }] : [],
226
- "/robots.txt",
227
- "/auth.md",
228
- "/_agent/:path*",
229
- ...WELL_KNOWN_DOCS.map((doc) => `/.well-known/${doc}`),
230
- ...WELL_KNOWN_DIRS.map((dir) => `/.well-known/${dir}/:path*`)
231
- ];
185
+ async function contents(dir, file) {
186
+ const info = await stat(path.join(dir, file)).catch(() => null);
187
+ return info?.isFile() && info.size <= MAX_BYTES ? read(path.join(dir, file)) : null;
232
188
  }
233
- function vercelMiddleware(site, serviceOrigin, { next = true } = {}) {
234
- return header(
235
- site,
236
- serviceOrigin,
237
- [
238
- next ? "Next.js middleware (proxy.js from Next.js 16). Pages run it only when an agent asks for Markdown." : "Vercel Routing Middleware. vercel.json sends agents asking for a page as Markdown to /_agent/md/."
239
- ],
240
- "To uninstall, delete this file and Agentface's entries in vercel.json."
241
- ) + `
242
- export const config = {
243
- matcher: ${JSON.stringify(vercelMatchers({ next }), null, 4).replace(/\n\]$/, "\n ]")},
244
- };
245
-
246
- export default AgentfaceConnector.createMiddleware({ service: SERVICE });
247
- `;
189
+ async function siteGenerator(dir) {
190
+ for (const file of ["hugo.toml", "hugo.yaml", "hugo.json", "config.toml"])
191
+ if (/\bbaseURL\b/i.test(await read(path.join(dir, file)) ?? "")) return "Hugo";
192
+ if (await exists(path.join(dir, "_config.yml")) || await exists(path.join(dir, "_layouts")))
193
+ return "Jekyll";
194
+ return null;
248
195
  }
249
- function vercelConfig({ next = true, link = true } = {}) {
250
- const config = {};
251
- if (link) config.headers = [{ source: `/(${PAGES})`, headers: [{ key: "Link", value: LINK }] }];
252
- if (!next)
253
- config.redirects = [
254
- {
255
- source: `/:path(${PAGES})`,
256
- has: [ACCEPTS_MARKDOWN],
257
- // Our own fetches of the site get the page.
258
- missing: [{ type: "header", key: FETCH_HEADER }],
259
- destination: `${MARKDOWN_PREFIX}:path`,
260
- permanent: false
261
- }
262
- ];
263
- return config;
196
+ var NEXT_DOCUMENT = (tag) => `// ${OURS}: Next.js's own document, plus the Agentface tag.
197
+ import { Html, Head, Main, NextScript } from 'next/document';
198
+
199
+ export default function Document() {
200
+ return (
201
+ <Html>
202
+ <Head>
203
+ ${tag}
204
+ </Head>
205
+ <body>
206
+ <Main />
207
+ <NextScript />
208
+ </body>
209
+ </Html>
210
+ );
264
211
  }
212
+ `;
213
+ var GATSBY_SSR = (tag) => {
214
+ const src = tag.match(/\bsrc="([^"]+)"/)[1];
215
+ return `// ${OURS}: puts the Agentface tag in every page's <head>.
216
+ const React = require('react');
265
217
 
266
- // cli/init.mjs
267
- var DEFAULT_SERVICE = "https://connect.agentfacehq.com";
268
- var MARKER = "// Agentface connector for ";
269
- var BRANCH = "agentface-connector";
270
- var OWN_MIDDLEWARE = {
271
- astro: "Astro",
272
- "@sveltejs/kit": "SvelteKit",
273
- nuxt: "Nuxt",
274
- "@remix-run/dev": "Remix",
275
- "@react-router/dev": "React Router"
218
+ exports.onRenderBody = ({ setHeadComponents }) => {
219
+ setHeadComponents([
220
+ React.createElement('script', { key: 'agentface', async: true, src: '${src}' }),
221
+ ]);
276
222
  };
277
- var exists = async (file) => {
278
- try {
279
- await stat(file);
280
- return true;
281
- } catch {
282
- return false;
283
- }
223
+ `;
284
224
  };
285
- var readJson = async (file) => {
286
- try {
287
- return JSON.parse(await readFile(file, "utf8"));
288
- } catch {
289
- return null;
225
+ async function byHand(dir, list2, framework, reason, how) {
226
+ const tagged = [];
227
+ for (const file of list2) {
228
+ const text = await contents(dir, file);
229
+ const key = text === null ? null : tagKey(text);
230
+ if (key) tagged.push({ file, key });
290
231
  }
291
- };
292
- async function lookupSite(service, id, fetcher = fetch) {
293
- let response;
232
+ return { framework, heads: [], creates: [], manual: { reason, how }, tagged, key: tagged[0]?.key ?? null };
233
+ }
234
+ async function findHeads(dir) {
235
+ const pkg = JSON.parse(await read(path.join(dir, "package.json")) ?? "null");
236
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
237
+ const generator = await siteGenerator(dir);
238
+ const skip = new Set(SKIP);
239
+ if (generator === "Hugo") for (const name of ["public", "resources", "themes"]) skip.add(name);
240
+ if (deps.gatsby) skip.add("public");
241
+ const framework = FRAMEWORKS.find(([dependency]) => deps[dependency])?.[1] ?? generator ?? (pkg ? "JavaScript" : "HTML");
242
+ const { files: list2, git } = await files(dir, skip);
243
+ for (const [dependency, [name, where]] of Object.entries(CONFIG_HEAD))
244
+ if (deps[dependency])
245
+ return byHand(
246
+ dir,
247
+ list2,
248
+ name,
249
+ `${name} sets the page head in its config, which init can't edit yet.`,
250
+ `Add it by hand through ${where}, with this tag's src`
251
+ );
252
+ const heads = [];
253
+ for (const file of list2) {
254
+ const markup = MARKUP.test(file);
255
+ if (!markup && !LAYOUTS.some((layout) => layout.test(file)) || MAIL.test(path.posix.basename(file)))
256
+ continue;
257
+ const text = await contents(dir, file);
258
+ if (text === null) continue;
259
+ const head = markup ? /<\/head\s*>/i.test(text) : /<\/head\s*>|<html\b/i.test(text);
260
+ if (head) heads.push({ file, source: text });
261
+ }
262
+ const creates = [];
263
+ if (deps.next && !heads.some(({ file }) => /(?:^|\/)app\//.test(file))) {
264
+ if (!heads.some(({ file }) => /pages\/_document\./.test(file))) {
265
+ const pages = await exists(path.join(dir, "pages")) ? "pages" : "src/pages";
266
+ if (await exists(path.join(dir, pages)))
267
+ creates.push({ file: `${pages}/_document.js`, content: NEXT_DOCUMENT });
268
+ }
269
+ }
270
+ if (deps.gatsby && !heads.length) {
271
+ const own = ["js", "jsx", "ts", "tsx"].map((ext) => `gatsby-ssr.${ext}`);
272
+ const present = [];
273
+ for (const file of own) if (await exists(path.join(dir, file))) present.push(file);
274
+ const text = present.length === 1 ? await read(path.join(dir, present[0])) : null;
275
+ if (present.length && !(present[0] === "gatsby-ssr.js" && text?.includes(OURS)))
276
+ return byHand(
277
+ dir,
278
+ list2,
279
+ framework,
280
+ `This Gatsby site has its own ${present[0]}, which init can't edit yet.`,
281
+ "Add it by hand through setHeadComponents in onRenderBody, with this tag's src"
282
+ );
283
+ creates.push({ file: "gatsby-ssr.js", content: GATSBY_SSR, source: text });
284
+ }
285
+ if (!heads.length && !creates.length)
286
+ return byHand(
287
+ dir,
288
+ list2,
289
+ framework,
290
+ `init found no <head> to put the tag in. It looks in this folder${git ? ", leaving out what git ignores," : ""} for templates that close a </head> (${EXTENSIONS.map((ext) => "." + ext).join(", ")}) and for the root layouts of Next.js, Remix, React Router, TanStack Start and Gatsby. A head that comes from a theme or a package needs its template copied into the project first.`,
291
+ "Add this line by hand, last in the <head> of the layout or template every page uses"
292
+ );
293
+ const sources = [...heads.map(({ source }) => source), ...creates.map(({ source }) => source ?? "")];
294
+ return { framework, heads, creates, key: sources.map(tagKey).find(Boolean) ?? null };
295
+ }
296
+
297
+ // cli/init.mjs
298
+ var DEFAULT_SERVICE = "https://cdn.agentfacehq.com";
299
+ var BRANCH = "agentface";
300
+ var readJson = async (file) => JSON.parse(await readFile2(file, "utf8").catch(() => "null"));
301
+ var when = (iso) => iso.slice(0, 16).replace("T", " ") + " UTC";
302
+ async function reach(service, url, init2, fetcher) {
294
303
  try {
295
- response = await fetcher(`${service}/s/${encodeURIComponent(id)}/_agent/health`, {
296
- headers: { accept: "application/json" }
304
+ const response = await fetcher(url, {
305
+ ...init2,
306
+ headers: { accept: "application/json", ...init2?.headers }
297
307
  });
308
+ return { response, body: await response.json().catch(() => null) };
298
309
  } catch (error) {
299
310
  throw new Error(`Could not reach Agentface at ${service}: ${error.message}`, { cause: error });
300
311
  }
301
- const health = response.ok ? await response.json().catch(() => null) : null;
302
- if (health?.site !== id || !health.origin)
303
- throw new Error(`Agentface has no site "${id}". Copy the command from your Agentface preview.`);
304
- return { id: health.site, origin: health.origin };
305
312
  }
306
- async function nextMajor(dir, range) {
307
- const installed = await readJson(path.join(dir, "node_modules/next/package.json"));
308
- const version = installed?.version ?? range;
309
- const major = Number(String(version).match(/\d+/)?.[0]);
310
- return Number.isFinite(major) ? major : null;
313
+ async function lookupSite(service, id, fetcher = fetch) {
314
+ const { response, body } = await reach(service, `${service}/sites/${encodeURIComponent(id)}`, {}, fetcher);
315
+ if (response.status === 404 || response.ok && body?.site?.id !== id)
316
+ throw Object.assign(
317
+ new Error(
318
+ `Agentface has no site "${id}". Check the key, or run "npx agentface init" without one to register your site.`
319
+ ),
320
+ { unknownSite: true }
321
+ );
322
+ if (!response.ok) throw new Error(body?.message ?? `Agentface answered HTTP ${response.status}`);
323
+ return { ...body.site, tag: body.tag };
311
324
  }
312
- var isLinkHeader = (header2) => /^link$/i.test(header2?.key ?? "");
313
- var isOurHeaderRule = (rule) => Boolean(
314
- rule?.headers?.some?.(
315
- (header2) => isLinkHeader(header2) && String(header2.value).includes("</_agent/docs>")
316
- )
317
- );
318
- var isOurRedirect = (rule) => String(rule?.destination ?? "").startsWith(MARKDOWN_PREFIX);
319
- function withAgentface(config, ours) {
320
- const out = { ...config };
321
- for (const [key, isOurs] of [
322
- ["headers", isOurHeaderRule],
323
- ["redirects", isOurRedirect]
324
- ]) {
325
- const rules = [...(config[key] ?? []).filter((rule) => !isOurs(rule)), ...ours[key] ?? []];
326
- if (rules.length || key in config) out[key] = rules;
327
- }
328
- return out;
325
+ async function register(service, url, fetcher = fetch) {
326
+ const { response, body } = await reach(
327
+ service,
328
+ `${service}/sites`,
329
+ { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ url }) },
330
+ fetcher
331
+ );
332
+ if (!response.ok || !body?.site?.id)
333
+ throw new Error(body?.message ?? `Agentface could not register ${url} (HTTP ${response.status})`);
334
+ return { ...body.site, expiresAt: body.expiresAt, tag: body.tag };
329
335
  }
330
- async function setsOwnLink(dir) {
331
- for (const file of ["next.config.js", "next.config.mjs", "next.config.cjs", "next.config.ts"]) {
332
- const source = await readFile(path.join(dir, file), "utf8").catch(() => "");
333
- if (/["']?key["']?\s*:\s*["']link["']/i.test(source)) return true;
334
- }
335
- const config = await readJson(path.join(dir, "vercel.json"));
336
- return (config?.headers ?? []).some((rule) => !isOurHeaderRule(rule) && rule.headers?.some?.(isLinkHeader));
336
+ async function confirm(service, id, fetcher = fetch) {
337
+ const { response, body } = await reach(
338
+ service,
339
+ `${service}/sites/${encodeURIComponent(id)}/confirm`,
340
+ { method: "POST" },
341
+ fetcher
342
+ );
343
+ return { ok: response.ok, status: response.status, message: body?.message ?? `HTTP ${response.status}` };
337
344
  }
338
- async function configProblem(dir) {
339
- for (const file2 of ["vercel.ts", "vercel.mts", "vercel.js", "vercel.mjs", "vercel.cjs"])
340
- if (await exists(path.join(dir, file2)))
341
- return `This project configures Vercel in ${file2}, which init can't edit yet. Use "Send to your developer" in your Agentface preview.`;
342
- const file = path.join(dir, "vercel.json");
343
- if (!await exists(file)) return null;
344
- const config = await readJson(file);
345
- if (!config || typeof config !== "object" || Array.isArray(config))
346
- return "This project's vercel.json isn't valid JSON. Fix it, then run this again.";
347
- if (config.routes)
348
- return `This project's vercel.json uses "routes", which Vercel doesn't allow together with the "headers" and "redirects" Agentface adds. Use "Send to your developer" in your Agentface preview.`;
349
- return null;
350
- }
351
- async function plan(dir) {
352
- const pkg = await readJson(path.join(dir, "package.json"));
353
- const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
354
- const own = Object.keys(OWN_MIDDLEWARE).find((name2) => deps[name2]);
355
- if (own)
356
- return {
357
- error: `${OWN_MIDDLEWARE[own]} has its own middleware, which this connector doesn't support yet. Use another install option from your Agentface preview.`
358
- };
359
- let framework, base = ".", name = "middleware";
360
- if (deps.next) {
361
- const major = await nextMajor(dir, deps.next);
362
- framework = major ? `Next.js ${major}` : "Next.js";
363
- if (major >= 16) name = "proxy";
364
- const rootApp = await exists(path.join(dir, "app")) || await exists(path.join(dir, "pages"));
365
- const srcApp = await exists(path.join(dir, "src/app")) || await exists(path.join(dir, "src/pages"));
366
- if (!rootApp && srcApp) base = "src";
367
- } else if (await exists(path.join(dir, "vercel.json")) || await exists(path.join(dir, ".vercel/project.json"))) {
368
- framework = "Vercel";
369
- } else {
370
- return {
371
- error: "This doesn't look like a Next.js app or a Vercel project. Run this in your site's project folder, or use another install option from your Agentface preview."
372
- };
345
+ var option = (source, name) => source?.match(new RegExp(`^\\s*${name}["']?\\s*[:=]\\s*["'\`]?([^"'\`\\s]+)`, "m"))?.[1] ?? null;
346
+ var config = async (dir, names) => {
347
+ for (const name of names) {
348
+ const source = await readFile2(path2.join(dir, name), "utf8").catch(() => null);
349
+ if (source !== null) return { source, name };
373
350
  }
374
- const problem = await configProblem(dir);
375
- if (problem) return { error: problem };
376
- const next = Boolean(deps.next);
377
- const files = await readdir(path.join(dir, base)).catch(() => []);
378
- for (const file of files.filter((f) => /^(middleware|proxy)\.(c|m)?[jt]sx?$/.test(f))) {
379
- const relative = path.join(base, file);
380
- if ((await readFile(path.join(dir, relative), "utf8")).includes(MARKER))
381
- return { framework, file: relative, update: true, ownLink: await setsOwnLink(dir), next };
382
- return {
383
- error: `This project already has ${relative}. Agentface needs to run before it; adding that to an existing middleware isn't automated yet. Use "Send to your developer" in your Agentface preview.`
384
- };
351
+ return { source: null };
352
+ };
353
+ async function siteUrl(dir, exec = run) {
354
+ for (const file of ["CNAME", "public/CNAME", "static/CNAME"]) {
355
+ const host = (await readFile2(path2.join(dir, file), "utf8").catch(() => "")).trim().split(/\s+/)[0];
356
+ if (host) return { url: `https://${host}/`, from: file };
385
357
  }
386
- return {
387
- framework,
388
- file: path.join(base, name + ".js"),
389
- update: false,
390
- ownLink: await setsOwnLink(dir),
391
- next
392
- };
358
+ for (const [names, key] of [
359
+ [["astro.config.mjs", "astro.config.ts", "astro.config.js"], "site"],
360
+ [["hugo.toml", "config.toml"], "baseURL"],
361
+ [["_config.yml"], "url"]
362
+ ]) {
363
+ const { source, name } = await config(dir, names);
364
+ const url = option(source, key);
365
+ if (/^https?:\/\//i.test(url ?? "")) return { url, from: name };
366
+ }
367
+ const homepage = (await readJson(path2.join(dir, "package.json")))?.homepage;
368
+ if (/^https?:\/\//i.test(homepage ?? "")) return { url: homepage, from: 'package.json "homepage"' };
369
+ const remote = await exec("git", ["remote", "get-url", "origin"], { cwd: dir }).catch(() => "");
370
+ const [, owner, repo] = remote.match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/i) ?? [];
371
+ if (owner && repo.toLowerCase() === `${owner.toLowerCase()}.github.io`)
372
+ return { url: `https://${owner.toLowerCase()}.github.io/`, from: "its GitHub repository" };
373
+ return null;
393
374
  }
394
375
  function run(command, args, { cwd }) {
395
376
  return new Promise((resolve, reject) => {
396
- execFile(command, args, { cwd }, (error, stdout, stderr) => {
377
+ execFile2(command, args, { cwd }, (error, stdout, stderr) => {
397
378
  if (error)
398
379
  reject(new Error(`${command} ${args.join(" ")} failed: ${(stderr || error.message).trim()}`));
399
380
  else resolve(stdout.trim());
400
381
  });
401
382
  });
402
383
  }
403
- function prBody(site, files, service = DEFAULT_SERVICE, { next = true, link = true } = {}) {
404
- const [file] = files;
405
- const serviceFlag = service === DEFAULT_SERVICE ? "" : ` --service ${service}`;
406
- const config = [
407
- link && "adds one `Link` header to pages, so agents find the rest",
408
- !next && "sends agents asking for a page as Markdown (`Accept: text/markdown`) to `/_agent/md/<page>`"
409
- ].filter(Boolean);
410
- const entries = [link && "the `Link` header rule", !next && "the `/_agent/md/` redirect"].filter(Boolean);
411
- return `Adds Agentface to ${site.origin}, so AI agents can discover and use the site.
412
-
413
- **What it does.** \`${file}\` sends agent-only requests to Agentface: \`/robots.txt\`, \`/auth.md\`, a few \`/.well-known/\` documents, \`/_agent/\` endpoints${next ? ", and pages requested with `Accept: text/markdown`" : ""}.${files.includes("vercel.json") ? ` \`vercel.json\` ${config.join(", and ")}.` : ""} Everything else, including every request from a browser, goes to your site untouched and runs no code.
414
-
415
- **Safety.** No dependencies and no secrets. If Agentface is down, slow or failing, those requests are answered by your site as if the file weren't there. Your own robots.txt rules are kept as they are.
416
-
417
- **Check it.** Once the preview deployment is up:
384
+ async function siteFor({ id, url, dir, found, service, fetcher, exec, dryRun, log }) {
385
+ if (id) return lookupSite(service, id, fetcher);
386
+ if (found.key) {
387
+ try {
388
+ return await lookupSite(service, found.key, fetcher);
389
+ } catch (error) {
390
+ if (!error.unknownSite) throw error;
391
+ log(
392
+ `Agentface no longer has ${found.key}, the site this project's tag names (an unconfirmed site is deleted after a day). Registering it again.`
393
+ );
394
+ }
395
+ }
396
+ if (!url) {
397
+ const address = await siteUrl(dir, exec);
398
+ if (!address)
399
+ throw new Error(
400
+ "Which site is this? Run this again with its address: npx agentface init --url https://example.com"
401
+ );
402
+ try {
403
+ registrableOrigin(address.url);
404
+ } catch (error) {
405
+ throw new Error(
406
+ `This project's address, ${address.url} (from ${address.from}), can't be registered. ${error.message}. If the site is served from another address, pass it with --url.`,
407
+ { cause: error }
408
+ );
409
+ }
410
+ log(`Using ${address.url} (from ${address.from}). For another address, pass --url.`);
411
+ url = address.url;
412
+ }
413
+ let origin;
414
+ try {
415
+ origin = registrableOrigin(url);
416
+ } catch (error) {
417
+ throw new Error(`Can't register ${url}. ${error.message}.`, { cause: error });
418
+ }
419
+ if (dryRun) {
420
+ log(`Would register ${origin} with Agentface.`);
421
+ return {
422
+ id: "site-new",
423
+ origin,
424
+ tag: `<script async src="${service}/s/site-new.js"></script>`
425
+ };
426
+ }
427
+ const site = await register(service, origin + "/", fetcher);
428
+ log(`Registered ${site.origin} with Agentface as ${site.id}.`);
429
+ return site;
430
+ }
431
+ var serviceFlag = (service) => service === DEFAULT_SERVICE ? "" : ` --service ${service}`;
432
+ var list = (files2) => files2.length <= 3 ? files2.join(", ") : `${files2.slice(0, 3).join(", ")} and ${files2.length - 3} more`;
433
+ function nextSteps(site, service) {
434
+ const check2 = `npx agentface check${serviceFlag(service)}`;
435
+ return site.expiresAt ? `Deploy it as usual, then run \`${check2}\` here: once ${site.origin}'s homepage has the tag, that confirms the site is yours. Agentface also confirms it by itself when the site's first events arrive, but a quiet site may send none in time: until it's confirmed, Agentface deletes ${site.id} at ${when(site.expiresAt)}. If that happens first, run \`npx agentface init\` again.` : `Deploy it as usual. \`${check2}\` shows whether ${site.origin}'s homepage has the tag.`;
436
+ }
437
+ function prBody(site, files2, service = DEFAULT_SERVICE) {
438
+ const src = site.tag.match(/\bsrc="([^"]+)"/)?.[1];
439
+ return `Adds the Agentface tag to ${site.origin}, so AI agents that use the site in a browser get tools made for them.
418
440
 
419
- \`\`\`sh
420
- npx agentface check <preview URL> --site ${site.id}${serviceFlag}
421
- \`\`\`
441
+ **What it does.** One \`<script async>\` line in ${files2.map((file) => `\`${file}\``).join(", ")} loads ${src} on every page. It gives browser agents tools for this site (read a page as Markdown, search the site, fill in forms, close pop-ups) and reports how agents use them: which tools, how long they took and their error codes, never what anyone typed or read. People visiting the site see no change, and it sets no cookies.
422
442
 
423
- If your previews are protected, add \`--bypass <secret>\` with the project's Protection Bypass for Automation secret (Vercel \u2192 Settings \u2192 Deployment Protection), or run the check on your production URL after merging.
443
+ **Check it.** ${nextSteps(site, service)}
424
444
 
425
- **Uninstall.** Revert this pull request, or delete \`${file}\`${entries.length ? ` and Agentface's entries in \`vercel.json\` (${entries.join(" and ")})` : ""}.
445
+ **Uninstall.** Revert this pull request, or delete the line.
426
446
  `;
427
447
  }
448
+ function byHand2({ manual, tagged }, site, service, dryRun, log) {
449
+ const current = tagged.filter(({ key }) => key === site.id).map(({ file }) => file);
450
+ if (current.length) {
451
+ log(
452
+ `${list(current)} already ${current.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`
453
+ );
454
+ log(nextSteps(site, service));
455
+ return { site, files: [], written: false };
456
+ }
457
+ log(manual.reason);
458
+ if (dryRun) {
459
+ log(`${manual.how}. Without --dry-run, init prints the tag with the site's key.`);
460
+ return { site, files: [], written: false };
461
+ }
462
+ const old = tagged.map(({ file }) => file);
463
+ log(
464
+ `${old.length ? `Replace the Agentface tag in ${list(old)} with this line` : manual.how}:
465
+
466
+ ${site.tag}
467
+ `
468
+ );
469
+ log(nextSteps(site, service));
470
+ return { site, files: [], written: false };
471
+ }
472
+ async function readyForPr(dir, exec) {
473
+ if (await exec("git", ["status", "--porcelain"], { cwd: dir }))
474
+ throw new Error("Commit or stash your changes first: the pull request should contain only Agentface.");
475
+ await exec("gh", ["auth", "status"], { cwd: dir });
476
+ if (await exec("git", ["ls-remote", "--heads", "origin", BRANCH], { cwd: dir }))
477
+ throw new Error(
478
+ `The branch ${BRANCH} already exists on origin, probably from an earlier pull request. Merge or close it and delete the branch, then run this again.`
479
+ );
480
+ }
428
481
  async function init({
429
482
  site: id,
483
+ url,
430
484
  dir = process.cwd(),
431
485
  service = DEFAULT_SERVICE,
432
486
  pr = false,
@@ -435,71 +489,65 @@ async function init({
435
489
  exec = run,
436
490
  log = console.log
437
491
  }) {
438
- if (!id) throw new Error("Usage: agentface init <site-id> [--pr]");
439
- const site = await lookupSite(service, id, fetcher);
440
- const target = await plan(dir);
441
- if (target.error) throw new Error(target.error);
442
- const source = vercelMiddleware(site, service, { next: target.next });
443
- const file = target.file;
444
- const link = !target.ownLink;
445
- if (!link)
492
+ const found = await findHeads(dir);
493
+ if (found.manual && pr)
494
+ throw new Error(
495
+ `${found.manual.reason} --pr only commits what init writes: run init without it to get the tag to add by hand.`
496
+ );
497
+ if (pr && !dryRun) await readyForPr(dir, exec);
498
+ const site = await siteFor({ id, url, dir, found, service, fetcher, exec, dryRun, log });
499
+ if (found.manual) return byHand2(found, site, service, dryRun, log);
500
+ const writes = [];
501
+ for (const { file, source } of found.heads) {
502
+ const content = addTag(source, site.tag);
503
+ if (content !== source) writes.push([file, content]);
504
+ }
505
+ for (const { file, content, source } of found.creates) {
506
+ const made = content(site.tag);
507
+ if (made !== source) writes.push([file, made]);
508
+ }
509
+ const files2 = writes.map(([file]) => file);
510
+ const where = list([...found.heads.map(({ file }) => file), ...found.creates.map(({ file }) => file)]);
511
+ if (!writes.length) {
446
512
  log(
447
- "Your project sets its own Link header, so Agentface adds none (it would replace yours). Agents still find everything through /.well-known."
513
+ `${where} already ${found.heads.length + found.creates.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`
448
514
  );
449
- const raw = await readFile(path.join(dir, "vercel.json"), "utf8").catch(() => null);
450
- const current = raw === null ? {} : JSON.parse(raw);
451
- const config = withAgentface(current, vercelConfig({ next: target.next, link }));
452
- const files = [file, ...JSON.stringify(config) === JSON.stringify(current) ? [] : ["vercel.json"]];
453
- const written = files.join(" and ");
515
+ log(nextSteps(site, service));
516
+ return { site, files: files2, written: false };
517
+ }
454
518
  if (dryRun) {
455
- log(`Would ${target.update ? "update" : "write"} ${written} (${target.framework}) for ${site.origin}.`);
456
- return { site, file, files, written: false };
519
+ log(`Would add the Agentface tag to ${list(files2)} (${found.framework}) for ${site.origin}.`);
520
+ return { site, files: files2, written: false };
457
521
  }
458
522
  let returnTo;
459
523
  if (pr) {
460
- const status = await exec("git", ["status", "--porcelain"], { cwd: dir });
461
- if (status)
462
- throw new Error(
463
- "Commit or stash your changes first: the pull request should contain only the connector."
464
- );
465
- await exec("gh", ["auth", "status"], { cwd: dir });
466
- if (await exec("git", ["ls-remote", "--heads", "origin", BRANCH], { cwd: dir })) {
467
- throw new Error(
468
- `The branch ${BRANCH} already exists on origin, probably from an earlier pull request. Merge or close it and delete the branch, then run this again.`
469
- );
470
- }
471
524
  returnTo = await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd: dir });
472
525
  await exec("git", ["switch", "-C", BRANCH], { cwd: dir });
473
526
  }
474
- await mkdir(path.dirname(path.join(dir, file)), { recursive: true });
475
- await writeFile(path.join(dir, file), source);
476
- if (files.includes("vercel.json")) {
477
- const indent = raw?.match(/^[ \t]+(?=")/m)?.[0] ?? " ";
478
- await writeFile(path.join(dir, "vercel.json"), JSON.stringify(config, null, indent) + "\n");
527
+ for (const [file, content] of writes) {
528
+ await mkdir(path2.dirname(path2.join(dir, file)), { recursive: true });
529
+ await writeFile(path2.join(dir, file), content);
479
530
  }
480
- log(`${target.update ? "Updated" : "Wrote"} ${written} (${target.framework}) for ${site.origin}.`);
531
+ log(`Added the Agentface tag to ${list(files2)} (${found.framework}) for ${site.origin}.`);
481
532
  if (!pr) {
482
- const flag = service === DEFAULT_SERVICE ? "" : ` --service ${service}`;
483
- log(
484
- `Deploy it as usual, then check it with: npx agentface check ${site.origin} --site ${site.id}${flag}`
485
- );
486
- return { site, file, files, written: true };
533
+ log(nextSteps(site, service));
534
+ return { site, files: files2, written: true };
487
535
  }
488
536
  try {
489
- await exec("git", ["add", "--", ...files], { cwd: dir });
537
+ await exec("git", ["add", "--", ...files2], { cwd: dir });
490
538
  await exec(
491
539
  "git",
492
540
  [
493
541
  "commit",
494
542
  "-m",
495
- "Add the Agentface connector",
543
+ "Add the Agentface tag",
496
544
  "-m",
497
- "Sends agent-only requests to Agentface; everything else is unchanged."
545
+ "Gives AI agents tools for the site; pages are unchanged."
498
546
  ],
499
547
  { cwd: dir }
500
548
  );
501
549
  await exec("git", ["push", "-u", "origin", BRANCH], { cwd: dir });
502
- const url = await exec(
550
+ const opened = await exec(
503
551
  "gh",
504
552
  [
505
553
  "pr",
@@ -509,186 +557,67 @@ async function init({
509
557
  "--title",
510
558
  "Add Agentface for AI agents",
511
559
  "--body",
512
- prBody(site, files, service, { next: target.next, link })
560
+ prBody(site, files2, service)
513
561
  ],
514
562
  { cwd: dir }
515
563
  );
516
- log(`Opened ${url}`);
517
- return { site, file, files, written: true, pr: url };
564
+ log(`Opened ${opened}`);
565
+ return { site, files: files2, written: true, pr: opened };
518
566
  } finally {
519
567
  await exec("git", ["switch", returnTo], { cwd: dir });
520
568
  }
521
569
  }
522
-
523
- // src/install-check.js
524
- async function checkInstall({
525
- site,
526
- url = site.origin,
570
+ async function check({
571
+ site: id,
572
+ dir = process.cwd(),
573
+ service = DEFAULT_SERVICE,
527
574
  fetch: fetcher = fetch,
528
- headers = {},
529
- timeoutMs = 12e3
575
+ log = console.log
530
576
  }) {
531
- const base = new URL(url).origin;
532
- const checks = [];
533
- const probe = async (name, fn) => {
534
- const check = { name, ok: false };
535
- checks.push(check);
536
- try {
537
- await fn();
538
- check.ok = true;
539
- } catch (error) {
540
- check.message = error.message;
541
- }
542
- };
543
- const expect = (condition, message) => {
544
- if (!condition) throw new Error(message);
545
- };
546
- const get = (path2, { accept = "*/*", bypass = false, method = "GET" } = {}) => fetcher(base + path2, {
547
- method,
548
- redirect: "manual",
549
- signal: AbortSignal.timeout(timeoutMs),
550
- headers: {
551
- ...headers,
552
- accept,
553
- "user-agent": "AgentfaceInstallCheck/1",
554
- ...bypass ? { [FETCH_HEADER]: "1" } : {}
555
- }
556
- });
557
- const type = (response) => response.headers.get("content-type") ?? "";
558
- const follow = async (path2, options) => {
559
- let response = await get(path2, options);
560
- for (let hops = 0; hops < 3 && response.status >= 300 && response.status < 400; hops++) {
561
- const next = new URL(response.headers.get("location") ?? "", base + path2);
562
- if (next.origin !== new URL(base).origin) break;
563
- await response.body?.cancel();
564
- path2 = next.pathname + next.search;
565
- response = await get(path2, options);
566
- }
567
- return response;
568
- };
569
- let gate;
570
- try {
571
- gate = await get("/_agent/health", { accept: "application/json" });
572
- await gate.body?.cancel();
573
- } catch {
577
+ if (!id) {
578
+ const found = await findHeads(dir);
579
+ id = found.key;
580
+ if (!id)
581
+ throw new Error(
582
+ 'No Agentface tag in this project. Run "npx agentface init" first, or pass the site key with --site.'
583
+ );
574
584
  }
575
- if (/_vercel_sso_nonce=/.test(gate?.headers.get("set-cookie") ?? "") || /^https:\/\/vercel\.com\/sso-api/.test(gate?.headers.get("location") ?? "")) {
576
- return {
577
- ok: false,
578
- url: base,
579
- checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
580
- protectedBy: "vercel",
581
- checks: [
582
- {
583
- name: "The deployment is reachable",
584
- ok: false,
585
- message: "Vercel Deployment Protection answered instead of the site"
586
- }
587
- ]
588
- };
585
+ const site = await lookupSite(service, id, fetcher);
586
+ const result = await confirm(service, id, fetcher);
587
+ if (result.ok) {
588
+ log(
589
+ site.expiresAt ? `Confirmed: ${site.origin}'s homepage has the tag, so ${id} is yours and Agentface keeps it.` : `${site.origin}'s homepage has the tag for ${id}.`
590
+ );
591
+ return 0;
589
592
  }
590
- await Promise.all([
591
- probe("Health reaches this site on Agentface", async () => {
592
- const response = await get("/_agent/health");
593
- expect(
594
- response.ok && type(response).includes("json"),
595
- `/_agent/health answered ${response.status}, not Agentface`
596
- );
597
- expect((await response.json()).site === site.id, "Health answered for a different site");
598
- }),
599
- probe("API catalog", async () => {
600
- const response = await get("/.well-known/api-catalog");
601
- expect(
602
- response.ok && type(response).includes("application/linkset+json"),
603
- "The API catalog is not a linkset"
604
- );
605
- expect(Array.isArray((await response.json()).linkset), "The API catalog has no linkset");
606
- }),
607
- probe("OAuth discovery", async () => {
608
- const response = await get("/.well-known/oauth-authorization-server/_agent/oauth");
609
- expect(
610
- response.ok && (await response.json()).issuer === site.origin + "/_agent/oauth",
611
- "OAuth discovery is missing or names another issuer"
612
- );
613
- }),
614
- probe("Markdown for agents that ask for it", async () => {
615
- for (const method of ["GET", "HEAD"]) {
616
- const response = await follow("/", { accept: "text/markdown", method });
617
- expect(
618
- response.ok && (type(response).includes("text/markdown") || method === "HEAD" && !type(response)),
619
- `${method} with Accept: text/markdown did not get Markdown`
620
- );
621
- expect(/\baccept\b/i.test(response.headers.get("vary") ?? ""), "Markdown is missing Vary: Accept");
622
- const body = await response.text();
623
- expect(
624
- method === "HEAD" ? body.length === 0 : body.length > 0,
625
- `${method} returned an unexpected body`
626
- );
627
- }
628
- }),
629
- probe("HTML pages unchanged, with the discovery Link header", async () => {
630
- const [html, prefersHtml] = await Promise.all([
631
- get("/", { accept: "text/html" }),
632
- follow("/", { accept: "text/markdown;q=0.1, text/html" })
633
- ]);
634
- expect(html.ok && type(html).includes("text/html"), "The home page no longer returns HTML");
635
- expect(
636
- prefersHtml.ok && type(prefersHtml).includes("text/html"),
637
- "A client preferring HTML got another format"
638
- );
639
- if (html.headers.has("x-vercel-id"))
640
- expect(
641
- html.headers.get("link")?.includes('rel="service-doc"'),
642
- "The discovery Link header is missing"
643
- );
644
- }),
645
- probe("robots.txt is merged and keeps every original rule", async () => {
646
- const [original, routed] = await Promise.all([
647
- get("/robots.txt", { bypass: true }),
648
- get("/robots.txt")
649
- ]);
650
- const [raw, merged] = await Promise.all([original.text(), routed.text()]);
651
- expect(routed.ok && merged.includes("Agentmap:"), "robots.txt does not reach Agentface");
652
- if (original.ok) {
653
- const kept = new Set(merged.split(/\r?\n/).map((line) => line.trim()));
654
- for (const line of raw.split(/\r?\n/).map((line2) => line2.trim()).filter((line2) => /^(?:Disallow|Allow|Sitemap):/i.test(line2))) {
655
- expect(kept.has(line), `An original rule was lost: ${line}`);
656
- }
657
- }
658
- }),
659
- probe("The site's own /.well-known files are untouched", async () => {
660
- const path2 = "/.well-known/apple-app-site-association";
661
- const [original, routed] = await Promise.all([get(path2, { bypass: true }), get(path2)]);
662
- expect(original.status === routed.status, `${path2} changed status`);
663
- if (original.ok) expect(await original.text() === await routed.text(), `${path2} changed content`);
664
- })
665
- ]);
666
- return { ok: checks.every((check) => check.ok), url: base, checkedAt: (/* @__PURE__ */ new Date()).toISOString(), checks };
593
+ log(result.message);
594
+ if (result.status === 422 && site.expiresAt)
595
+ log(`Until it's confirmed, Agentface deletes ${id} at ${when(site.expiresAt)}.`);
596
+ return 1;
667
597
  }
668
598
 
669
599
  // cli/agentface.mjs
670
600
  var HELP = `Usage:
671
- agentface init <site-id> [--pr] [--dry-run] Add the Agentface connector to this project
672
- agentface check <url> --site <site-id> Check an install from the outside
601
+ agentface init [<site-key>] Add the Agentface tag to the pages of the site in this
602
+ folder. Without a site key, registers the site first.
603
+ agentface check Check that the deployed homepage has the tag. The first
604
+ time, that confirms the site is yours.
673
605
 
674
606
  Options:
675
- --pr Commit the connector on a new branch and open a pull request (needs git and gh)
676
- --dry-run Show what would change without writing anything
677
- --bypass Check a protected Vercel preview, with its Protection Bypass for Automation secret
607
+ --url The site's address, like https://example.com (init finds it when it can)
608
+ --site check: the site key (check finds it in the project when it can)
609
+ --pr Commit the change on a new branch and open a pull request (needs git and gh)
610
+ --dry-run Show what would change, without registering or writing anything
678
611
  --service Agentface service URL (default ${DEFAULT_SERVICE})`;
679
- var BYPASS_HINT = `
680
- To check a protected preview, run this again with --bypass <secret>. The secret is in
681
- your Vercel project under Settings \u2192 Deployment Protection \u2192 Protection Bypass for
682
- Automation. Or check your production URL instead.`;
683
- async function main(argv, { log = console.log } = {}) {
612
+ async function main(argv, { log = console.log, dir = process.cwd(), fetch: fetcher = fetch } = {}) {
684
613
  const { values, positionals } = parseArgs({
685
614
  args: argv,
686
615
  allowPositionals: true,
687
616
  options: {
617
+ url: { type: "string" },
618
+ site: { type: "string" },
688
619
  pr: { type: "boolean" },
689
620
  "dry-run": { type: "boolean" },
690
- site: { type: "string" },
691
- bypass: { type: "string" },
692
621
  service: { type: "string" },
693
622
  help: { type: "boolean", short: "h" }
694
623
  }
@@ -700,23 +629,19 @@ async function main(argv, { log = console.log } = {}) {
700
629
  return 0;
701
630
  }
702
631
  if (command === "init") {
703
- await init({ site: arg, service, pr: values.pr, dryRun: values["dry-run"], log });
632
+ await init({
633
+ site: arg,
634
+ url: values.url,
635
+ dir,
636
+ service,
637
+ pr: values.pr,
638
+ dryRun: values["dry-run"],
639
+ fetch: fetcher,
640
+ log
641
+ });
704
642
  return 0;
705
643
  }
706
- if (command === "check") {
707
- if (!arg || !values.site) throw new Error("Usage: agentface check <url> --site <site-id>");
708
- const site = await lookupSite(service, values.site);
709
- const headers = values.bypass ? { "x-vercel-protection-bypass": values.bypass } : {};
710
- const result = await checkInstall({ site, url: arg, headers });
711
- for (const check of result.checks)
712
- log(`${check.ok ? "PASS" : "FAIL"} ${check.name}${check.message ? ` \u2014 ${check.message}` : ""}`);
713
- if (result.protectedBy === "vercel")
714
- log(values.bypass ? "\nVercel did not accept the --bypass secret." : BYPASS_HINT);
715
- log(result.ok ? `
716
- ${result.url} is set up.` : `
717
- ${result.url} isn't fully set up yet.`);
718
- return result.ok ? 0 : 1;
719
- }
644
+ if (command === "check") return check({ site: values.site ?? arg, dir, service, fetch: fetcher, log });
720
645
  throw new Error(`Unknown command "${command}".
721
646
 
722
647
  ${HELP}`);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agentface",
3
- "version": "0.1.0",
4
- "description": "Make a website agent-ready: add the Agentface connector to your project, and check an install.",
3
+ "version": "0.3.0",
4
+ "description": "Add the Agentface tag to a website's pages, so AI agents get tools made for it.",
5
5
  "bin": {
6
6
  "agentface": "dist/agentface.mjs"
7
7
  },
package/README.md DELETED
@@ -1,36 +0,0 @@
1
- # agentface
2
-
3
- Make a website agent-ready: add the Agentface connector to your project, and check an install.
4
-
5
- ```sh
6
- npx agentface init <site-id> # write the connector and vercel.json entries
7
- npx agentface init <site-id> --pr # ...on a new branch, and open a pull request
8
- npx agentface check <url> --site <site-id>
9
- ```
10
-
11
- `init` supports Next.js (any host) and other Vercel projects. Besides the connector it
12
- adds a `Link` header rule to `vercel.json`, and outside Next.js a redirect that sends
13
- agents asking for Markdown to `/_agent/md/<page>`, so browsers never run Agentface code.
14
- It refuses projects it would break: frameworks with their own middleware, projects
15
- that already have a middleware or proxy file, and Vercel config it can't edit
16
- (`vercel.ts`, or `vercel.json` with `routes`). A connector it wrote earlier is updated
17
- in place, and so are its `vercel.json` entries. Add `--dry-run` to see what it would
18
- change.
19
-
20
- `--pr` needs a clean working tree, `git` and an authenticated `gh`. The connector and
21
- `vercel.json` are committed on the `agentface-connector` branch and you're switched
22
- back to your branch.
23
-
24
- `check` requests the site the way an agent would: health, discovery, Markdown for
25
- agents that ask for it, and HTML with the discovery `Link` header for everyone else.
26
- Run it against the site or a preview deployment. For a preview behind Vercel
27
- Deployment Protection, add `--bypass <secret>` with the project's Protection Bypass
28
- for Automation secret.
29
-
30
- Requires Node.js 20 or later.
31
-
32
- ## Development
33
-
34
- This package is built from `cli/` in the agentface-router repository:
35
- `npm run build:cli` bundles it into one dependency-free file, `cli/dist/agentface.mjs`
36
- (not committed).