agentface 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
1
  # agentface
2
2
 
3
- Installer for Agentface, which makes a website agent-ready. Not released yet.
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).
@@ -0,0 +1,734 @@
1
+ #!/usr/bin/env node
2
+
3
+ // cli/agentface.mjs
4
+ import { parseArgs } from "node:util";
5
+
6
+ // cli/init.mjs
7
+ import { readFile, writeFile, readdir, mkdir, stat } from "node:fs/promises";
8
+ import { execFile } from "node:child_process";
9
+ 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"
24
+ ];
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
58
+ });
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);
90
+ }
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 }) {
171
+ 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 });
200
+ };
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
+ `;
219
+ }
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
+ ];
232
+ }
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
+ `;
248
+ }
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;
264
+ }
265
+
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"
276
+ };
277
+ var exists = async (file) => {
278
+ try {
279
+ await stat(file);
280
+ return true;
281
+ } catch {
282
+ return false;
283
+ }
284
+ };
285
+ var readJson = async (file) => {
286
+ try {
287
+ return JSON.parse(await readFile(file, "utf8"));
288
+ } catch {
289
+ return null;
290
+ }
291
+ };
292
+ async function lookupSite(service, id, fetcher = fetch) {
293
+ let response;
294
+ try {
295
+ response = await fetcher(`${service}/s/${encodeURIComponent(id)}/_agent/health`, {
296
+ headers: { accept: "application/json" }
297
+ });
298
+ } catch (error) {
299
+ throw new Error(`Could not reach Agentface at ${service}: ${error.message}`, { cause: error });
300
+ }
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
+ }
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;
311
+ }
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;
329
+ }
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));
337
+ }
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
+ };
373
+ }
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
+ };
385
+ }
386
+ return {
387
+ framework,
388
+ file: path.join(base, name + ".js"),
389
+ update: false,
390
+ ownLink: await setsOwnLink(dir),
391
+ next
392
+ };
393
+ }
394
+ function run(command, args, { cwd }) {
395
+ return new Promise((resolve, reject) => {
396
+ execFile(command, args, { cwd }, (error, stdout, stderr) => {
397
+ if (error)
398
+ reject(new Error(`${command} ${args.join(" ")} failed: ${(stderr || error.message).trim()}`));
399
+ else resolve(stdout.trim());
400
+ });
401
+ });
402
+ }
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:
418
+
419
+ \`\`\`sh
420
+ npx agentface check <preview URL> --site ${site.id}${serviceFlag}
421
+ \`\`\`
422
+
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.
424
+
425
+ **Uninstall.** Revert this pull request, or delete \`${file}\`${entries.length ? ` and Agentface's entries in \`vercel.json\` (${entries.join(" and ")})` : ""}.
426
+ `;
427
+ }
428
+ async function init({
429
+ site: id,
430
+ dir = process.cwd(),
431
+ service = DEFAULT_SERVICE,
432
+ pr = false,
433
+ dryRun = false,
434
+ fetch: fetcher = fetch,
435
+ exec = run,
436
+ log = console.log
437
+ }) {
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)
446
+ log(
447
+ "Your project sets its own Link header, so Agentface adds none (it would replace yours). Agents still find everything through /.well-known."
448
+ );
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 ");
454
+ if (dryRun) {
455
+ log(`Would ${target.update ? "update" : "write"} ${written} (${target.framework}) for ${site.origin}.`);
456
+ return { site, file, files, written: false };
457
+ }
458
+ let returnTo;
459
+ 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
+ returnTo = await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd: dir });
472
+ await exec("git", ["switch", "-C", BRANCH], { cwd: dir });
473
+ }
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");
479
+ }
480
+ log(`${target.update ? "Updated" : "Wrote"} ${written} (${target.framework}) for ${site.origin}.`);
481
+ 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 };
487
+ }
488
+ try {
489
+ await exec("git", ["add", "--", ...files], { cwd: dir });
490
+ await exec(
491
+ "git",
492
+ [
493
+ "commit",
494
+ "-m",
495
+ "Add the Agentface connector",
496
+ "-m",
497
+ "Sends agent-only requests to Agentface; everything else is unchanged."
498
+ ],
499
+ { cwd: dir }
500
+ );
501
+ await exec("git", ["push", "-u", "origin", BRANCH], { cwd: dir });
502
+ const url = await exec(
503
+ "gh",
504
+ [
505
+ "pr",
506
+ "create",
507
+ "--head",
508
+ BRANCH,
509
+ "--title",
510
+ "Add Agentface for AI agents",
511
+ "--body",
512
+ prBody(site, files, service, { next: target.next, link })
513
+ ],
514
+ { cwd: dir }
515
+ );
516
+ log(`Opened ${url}`);
517
+ return { site, file, files, written: true, pr: url };
518
+ } finally {
519
+ await exec("git", ["switch", returnTo], { cwd: dir });
520
+ }
521
+ }
522
+
523
+ // src/install-check.js
524
+ async function checkInstall({
525
+ site,
526
+ url = site.origin,
527
+ fetch: fetcher = fetch,
528
+ headers = {},
529
+ timeoutMs = 12e3
530
+ }) {
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 {
574
+ }
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
+ };
589
+ }
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 };
667
+ }
668
+
669
+ // cli/agentface.mjs
670
+ 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
673
+
674
+ 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
678
+ --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 } = {}) {
684
+ const { values, positionals } = parseArgs({
685
+ args: argv,
686
+ allowPositionals: true,
687
+ options: {
688
+ pr: { type: "boolean" },
689
+ "dry-run": { type: "boolean" },
690
+ site: { type: "string" },
691
+ bypass: { type: "string" },
692
+ service: { type: "string" },
693
+ help: { type: "boolean", short: "h" }
694
+ }
695
+ });
696
+ const [command, arg] = positionals;
697
+ const service = (values.service ?? DEFAULT_SERVICE).replace(/\/$/, "");
698
+ if (values.help || !command) {
699
+ log(HELP);
700
+ return 0;
701
+ }
702
+ if (command === "init") {
703
+ await init({ site: arg, service, pr: values.pr, dryRun: values["dry-run"], log });
704
+ return 0;
705
+ }
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
+ }
720
+ throw new Error(`Unknown command "${command}".
721
+
722
+ ${HELP}`);
723
+ }
724
+
725
+ // cli/bin.mjs
726
+ main(process.argv.slice(2)).then(
727
+ (code) => {
728
+ process.exitCode = code;
729
+ },
730
+ (error) => {
731
+ console.error(error.message);
732
+ process.exitCode = 1;
733
+ }
734
+ );
package/package.json CHANGED
@@ -1,10 +1,16 @@
1
1
  {
2
2
  "name": "agentface",
3
- "version": "0.0.1",
4
- "description": "Agentface: make a website agent-ready. Installer CLI, not released yet.",
5
- "bin": { "agentface": "index.js" },
6
- "files": ["index.js"],
3
+ "version": "0.1.0",
4
+ "description": "Make a website agent-ready: add the Agentface connector to your project, and check an install.",
5
+ "bin": {
6
+ "agentface": "dist/agentface.mjs"
7
+ },
8
+ "files": [
9
+ "dist/agentface.mjs"
10
+ ],
7
11
  "type": "module",
8
- "engines": { "node": ">=18" },
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
9
15
  "license": "UNLICENSED"
10
16
  }
package/index.js DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- console.log('The Agentface installer is not released yet.');