agentface 0.5.2 → 0.7.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.
Files changed (2) hide show
  1. package/dist/agentface.mjs +1065 -74
  2. package/package.json +2 -2
@@ -3,10 +3,447 @@
3
3
  // cli/agentface.mts
4
4
  import { parseArgs } from "node:util";
5
5
 
6
+ // cli/connect.mts
7
+ import { execFile } from "node:child_process";
8
+ import { createHash, randomBytes } from "node:crypto";
9
+ import { chmod, mkdir, open as openFile, readFile, rm, stat, writeFile } from "node:fs/promises";
10
+ import { createServer } from "node:http";
11
+ import { homedir } from "node:os";
12
+ import path from "node:path";
13
+ var DEFAULT_SERVER = "https://agentface.com";
14
+ var MCP_PATH = "/mcp";
15
+ var PROTOCOL = "2025-06-18";
16
+ var LOGIN_WAIT_MS = 5 * 6e4;
17
+ var configDirOf = (env = process.env) => env.AGENTFACE_CONFIG_DIR || path.join(env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "agentface");
18
+ var fileIn = (dir) => path.join(dir, "credentials.json");
19
+ var normal = (server) => server.replace(/\/+$/, "");
20
+ async function readKept(dir, server) {
21
+ const all = JSON.parse(await readFile(fileIn(dir), "utf8").catch(() => "{}"));
22
+ return all[server] ?? null;
23
+ }
24
+ async function writeKept(dir, server, kept) {
25
+ const all = JSON.parse(await readFile(fileIn(dir), "utf8").catch(() => "{}"));
26
+ if (kept) all[server] = kept;
27
+ else delete all[server];
28
+ if (!Object.keys(all).length) return rm(fileIn(dir), { force: true });
29
+ await mkdir(dir, { recursive: true, mode: 448 });
30
+ await writeFile(fileIn(dir), `${JSON.stringify(all, null, 2)}
31
+ `, { mode: 384 });
32
+ await chmod(fileIn(dir), 384);
33
+ }
34
+ var LOCK_STALE_MS = 3e4;
35
+ async function alone(dir, work) {
36
+ const lock = path.join(dir, "credentials.lock");
37
+ await mkdir(dir, { recursive: true, mode: 448 });
38
+ for (; ; ) {
39
+ try {
40
+ await (await openFile(lock, "wx", 384)).close();
41
+ break;
42
+ } catch (error) {
43
+ if (error.code !== "EEXIST") throw error;
44
+ const made = await stat(lock).catch(() => null);
45
+ if (!made || Date.now() - made.mtimeMs > LOCK_STALE_MS) await rm(lock, { force: true });
46
+ else await new Promise((done) => setTimeout(done, 50));
47
+ }
48
+ }
49
+ try {
50
+ return await work();
51
+ } finally {
52
+ await rm(lock, { force: true });
53
+ }
54
+ }
55
+ async function json(fetcher, url, init2, server) {
56
+ let response;
57
+ try {
58
+ response = await fetcher(url, init2);
59
+ } catch (error) {
60
+ throw new Error(`Could not reach agentface at ${server}: ${error.message}`, { cause: error });
61
+ }
62
+ const body = await response.json().catch(() => null);
63
+ return { response, body };
64
+ }
65
+ var said = (body, fallback) => typeof body?.error_description === "string" && body.error_description ? body.error_description : fallback;
66
+ async function discover(fetcher, server) {
67
+ const resource = await json(
68
+ fetcher,
69
+ `${server}/.well-known/oauth-protected-resource${MCP_PATH}`,
70
+ { headers: { accept: "application/json" } },
71
+ server
72
+ );
73
+ const issuers = resource.body?.authorization_servers;
74
+ const issuer = Array.isArray(issuers) && typeof issuers[0] === "string" ? normal(issuers[0]) : server;
75
+ const found = await json(
76
+ fetcher,
77
+ `${issuer}/.well-known/oauth-authorization-server`,
78
+ { headers: { accept: "application/json" } },
79
+ server
80
+ );
81
+ const text = (name) => typeof found.body?.[name] === "string" ? found.body[name] : "";
82
+ const [register2, authorize, token] = [
83
+ text("registration_endpoint"),
84
+ text("authorization_endpoint"),
85
+ text("token_endpoint")
86
+ ];
87
+ if (!found.response.ok || !register2 || !authorize || !token)
88
+ throw new Error(`${server} doesn't say how an agent signs in to it. Is that agentface's address?`);
89
+ return { register: register2, authorize, token, revoke: text("revocation_endpoint") || null };
90
+ }
91
+ function openInBrowser(url) {
92
+ const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
93
+ return new Promise((done) => execFile(command, args, (error) => done(!error)));
94
+ }
95
+ var page = (title, words) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>agentface</title><meta name="viewport" content="width=device-width, initial-scale=1"></head><body style="font-family: system-ui, sans-serif; max-width: 30rem; margin: 20vh auto; padding: 0 1.5rem; line-height: 1.5"><h1 style="font-size: 1.25rem">${title}</h1><p>${words}</p></body></html>`;
96
+ async function login({
97
+ server = DEFAULT_SERVER,
98
+ fetch: fetcher = fetch,
99
+ log = console.log,
100
+ configDir = configDirOf(),
101
+ open = openInBrowser,
102
+ now = Date.now
103
+ } = {}) {
104
+ server = normal(server);
105
+ const endpoints = await discover(fetcher, server);
106
+ const state = randomBytes(16).toString("base64url");
107
+ const verifier = randomBytes(32).toString("base64url");
108
+ let arrived = () => {
109
+ };
110
+ const came = new Promise((done) => arrived = done);
111
+ const listener = createServer((req, res) => {
112
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
113
+ if (url.pathname !== "/callback") {
114
+ res.writeHead(404).end();
115
+ return;
116
+ }
117
+ const ours = url.searchParams.get("state") === state;
118
+ const code = url.searchParams.get("code");
119
+ const error = url.searchParams.get("error");
120
+ const ok = ours && !!code;
121
+ res.writeHead(ok ? 200 : 400, {
122
+ "content-type": "text/html; charset=utf-8",
123
+ "cache-control": "no-store",
124
+ connection: "close"
125
+ });
126
+ res.end(
127
+ ok ? page(
128
+ "This machine is connected to agentface.",
129
+ "You can close this tab and go back to the terminal."
130
+ ) : page(
131
+ "Nothing was connected.",
132
+ ours && error === "access_denied" ? "You didn\u2019t allow it. Run the command again to start over." : "This isn\u2019t the answer the command was waiting for. Run it again to start over."
133
+ )
134
+ );
135
+ if (ours) arrived(code ? { code } : { error: error ?? "no code came back" });
136
+ });
137
+ await new Promise((done) => listener.listen(0, "127.0.0.1", done));
138
+ const redirect = `http://127.0.0.1:${listener.address().port}/callback`;
139
+ try {
140
+ const registered = await json(
141
+ fetcher,
142
+ endpoints.register,
143
+ {
144
+ method: "POST",
145
+ headers: { "content-type": "application/json", accept: "application/json" },
146
+ body: JSON.stringify({
147
+ client_name: "agentface CLI",
148
+ redirect_uris: [redirect],
149
+ token_endpoint_auth_method: "none"
150
+ })
151
+ },
152
+ server
153
+ );
154
+ const clientId = registered.body?.client_id;
155
+ if (!registered.response.ok || typeof clientId !== "string")
156
+ throw new Error(
157
+ `agentface didn't take the sign-in: ${said(registered.body, `it answered ${registered.response.status}`)}`
158
+ );
159
+ const ask = new URL(endpoints.authorize);
160
+ for (const [name, value] of Object.entries({
161
+ response_type: "code",
162
+ client_id: clientId,
163
+ redirect_uri: redirect,
164
+ code_challenge: createHash("sha256").update(verifier).digest("base64url"),
165
+ code_challenge_method: "S256",
166
+ state,
167
+ resource: `${server}${MCP_PATH}`
168
+ }))
169
+ ask.searchParams.set(name, value);
170
+ const opened = await open(ask.href);
171
+ log(
172
+ opened ? "Your browser is opening agentface. Allow the connection there." : "Open this address in your browser, and allow the connection there:"
173
+ );
174
+ log(`
175
+ ${ask.href}
176
+ `);
177
+ let timer;
178
+ const answer = await Promise.race([
179
+ came,
180
+ new Promise(
181
+ (done) => timer = setTimeout(() => done({ error: "nobody allowed it in five minutes" }), LOGIN_WAIT_MS)
182
+ )
183
+ ]);
184
+ clearTimeout(timer);
185
+ if ("error" in answer)
186
+ throw new Error(
187
+ answer.error === "access_denied" ? "Nothing was connected: you didn\u2019t allow it." : `Nothing was connected: ${answer.error}.`
188
+ );
189
+ const traded = await json(
190
+ fetcher,
191
+ endpoints.token,
192
+ {
193
+ method: "POST",
194
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
195
+ body: new URLSearchParams({
196
+ grant_type: "authorization_code",
197
+ code: answer.code,
198
+ code_verifier: verifier,
199
+ client_id: clientId,
200
+ redirect_uri: redirect
201
+ }).toString()
202
+ },
203
+ server
204
+ );
205
+ const kept = keptFrom(
206
+ traded.body,
207
+ { server, clientId, tokenEndpoint: endpoints.token, revocationEndpoint: endpoints.revoke },
208
+ now()
209
+ );
210
+ if (!traded.response.ok || !kept)
211
+ throw new Error(
212
+ `agentface didn't finish the sign-in: ${said(traded.body, `it answered ${traded.response.status}`)}`
213
+ );
214
+ await writeKept(configDir, server, kept);
215
+ log(`Connected to ${server}. Try: agentface mcp tools`);
216
+ } finally {
217
+ listener.closeAllConnections?.();
218
+ listener.close();
219
+ }
220
+ }
221
+ function keptFrom(body, rest, at) {
222
+ if (typeof body?.access_token !== "string" || typeof body.refresh_token !== "string") return null;
223
+ const seconds = typeof body.expires_in === "number" ? body.expires_in : 3600;
224
+ return { ...rest, access: body.access_token, refresh: body.refresh_token, expiresAt: at + seconds * 1e3 };
225
+ }
226
+ async function logout({
227
+ server = DEFAULT_SERVER,
228
+ fetch: fetcher = fetch,
229
+ log = console.log,
230
+ configDir = configDirOf()
231
+ } = {}) {
232
+ server = normal(server);
233
+ const kept = await readKept(configDir, server);
234
+ if (!kept) return log(`This machine isn't connected to ${server}.`);
235
+ if (kept.revocationEndpoint) {
236
+ const ended = await fetcher(kept.revocationEndpoint, {
237
+ method: "POST",
238
+ headers: { "content-type": "application/x-www-form-urlencoded" },
239
+ body: new URLSearchParams({ token: kept.refresh }).toString()
240
+ }).then(
241
+ (response) => response.ok,
242
+ () => false
243
+ );
244
+ if (!ended)
245
+ throw new Error(
246
+ `agentface at ${server} couldn't be reached, so the connection is still open. Run the command again in a moment, or disconnect this machine at ${server}/account.`
247
+ );
248
+ }
249
+ await writeKept(configDir, server, null);
250
+ log(`Disconnected from ${server}.`);
251
+ }
252
+ var NOT_CONNECTED = (server) => `This machine isn't connected to ${server}. Run: npx agentface login${server === DEFAULT_SERVER ? "" : ` --server ${server}`}`;
253
+ async function current({
254
+ server,
255
+ fetcher,
256
+ configDir,
257
+ now,
258
+ force = false
259
+ }) {
260
+ const fresh = (kept) => kept.expiresAt - now() > 6e4;
261
+ const first = await readKept(configDir, server);
262
+ if (!first) throw new Error(NOT_CONNECTED(server));
263
+ if (!force && fresh(first)) return first;
264
+ return alone(configDir, () => renew({ server, fetcher, configDir, now, used: first }));
265
+ }
266
+ async function renew({
267
+ server,
268
+ fetcher,
269
+ configDir,
270
+ now,
271
+ used
272
+ }) {
273
+ const kept = await readKept(configDir, server);
274
+ if (!kept) throw new Error(NOT_CONNECTED(server));
275
+ if (kept.access !== used.access && kept.expiresAt - now() > 6e4) return kept;
276
+ const renewed = await json(
277
+ fetcher,
278
+ kept.tokenEndpoint,
279
+ {
280
+ method: "POST",
281
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
282
+ body: new URLSearchParams({
283
+ grant_type: "refresh_token",
284
+ refresh_token: kept.refresh,
285
+ client_id: kept.clientId
286
+ }).toString()
287
+ },
288
+ server
289
+ );
290
+ const next = keptFrom(renewed.body, kept, now());
291
+ if (!renewed.response.ok || !next) {
292
+ if (renewed.response.status === 400 || renewed.response.status === 401) {
293
+ await writeKept(configDir, server, null);
294
+ throw new Error(
295
+ `The connection to ${server} has ended. Run: npx agentface login${server === DEFAULT_SERVER ? "" : ` --server ${server}`}`
296
+ );
297
+ }
298
+ throw new Error(
299
+ `agentface couldn't renew the connection: ${said(renewed.body, `it answered ${renewed.response.status}`)}`
300
+ );
301
+ }
302
+ await writeKept(configDir, server, next);
303
+ return next;
304
+ }
305
+ async function post(fetcher, server, access, message, negotiated) {
306
+ let response;
307
+ try {
308
+ response = await fetcher(`${server}${MCP_PATH}`, {
309
+ method: "POST",
310
+ headers: {
311
+ authorization: `Bearer ${access}`,
312
+ "content-type": "application/json",
313
+ accept: "application/json, text/event-stream",
314
+ ...negotiated ? { "mcp-protocol-version": negotiated } : {}
315
+ },
316
+ body: JSON.stringify(message)
317
+ });
318
+ } catch (error) {
319
+ throw new Error(`Could not reach agentface at ${server}: ${error.message}`, { cause: error });
320
+ }
321
+ const text = await response.text();
322
+ if (!text) return { status: response.status, reply: null };
323
+ const data = /event-stream/.test(response.headers.get("content-type") ?? "") ? text.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).at(-1) : text;
324
+ try {
325
+ return { status: response.status, reply: JSON.parse(data ?? "") };
326
+ } catch {
327
+ return { status: response.status, reply: null };
328
+ }
329
+ }
330
+ async function request(method, params, options = {}) {
331
+ const { fetch: fetcher = fetch, configDir = configDirOf(), now = Date.now } = options;
332
+ const server = normal(options.server ?? DEFAULT_SERVER);
333
+ let kept = await current({ server, fetcher, configDir, now });
334
+ const hello = {
335
+ jsonrpc: "2.0",
336
+ id: 1,
337
+ method: "initialize",
338
+ params: {
339
+ protocolVersion: PROTOCOL,
340
+ capabilities: {},
341
+ clientInfo: { name: "agentface-cli", version: "1" }
342
+ }
343
+ };
344
+ let greeted = await post(fetcher, server, kept.access, hello);
345
+ if (greeted.status === 401) {
346
+ kept = await current({ server, fetcher, configDir, now, force: true });
347
+ greeted = await post(fetcher, server, kept.access, hello);
348
+ }
349
+ if (greeted.status === 401) throw new Error(NOT_CONNECTED(server));
350
+ if (!greeted.reply?.result)
351
+ throw new Error(
352
+ `agentface didn't answer (${greeted.status})${greeted.reply?.error ? `: ${greeted.reply.error.message}` : ""}. Try again in a moment.`
353
+ );
354
+ const version = typeof greeted.reply.result.protocolVersion === "string" ? greeted.reply.result.protocolVersion : PROTOCOL;
355
+ await post(fetcher, server, kept.access, { jsonrpc: "2.0", method: "notifications/initialized" }, version);
356
+ const { status, reply } = await post(
357
+ fetcher,
358
+ server,
359
+ kept.access,
360
+ { jsonrpc: "2.0", id: 2, method, params },
361
+ version
362
+ );
363
+ if (reply?.error) throw new Error(reply.error.message);
364
+ if (!reply?.result) throw new Error(`agentface didn't answer (${status}). Try again in a moment.`);
365
+ return reply.result;
366
+ }
367
+ function readArguments(given) {
368
+ if (given.length === 1 && given[0].trim().startsWith("{")) {
369
+ let parsed;
370
+ try {
371
+ parsed = JSON.parse(given[0]);
372
+ } catch {
373
+ throw new Error("The arguments aren\u2019t JSON. Write them as key=value, or as one JSON object in quotes.");
374
+ }
375
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
376
+ throw new Error("The arguments are one JSON object.");
377
+ return parsed;
378
+ }
379
+ const args = {};
380
+ for (const pair of given) {
381
+ const at = pair.indexOf("=");
382
+ if (at < 1)
383
+ throw new Error(`"${pair}" isn't an argument. Write each as key=value, such as siteId=site-shop.`);
384
+ const value = pair.slice(at + 1);
385
+ args[pair.slice(0, at)] = /^(-?\d+(\.\d+)?|true|false|null)$/.test(value) ? JSON.parse(value) : value;
386
+ }
387
+ return args;
388
+ }
389
+ var MCP_HELP = `Usage:
390
+ agentface mcp tools List agentface's functions, with what each takes.
391
+ agentface mcp call <name> [key=value \u2026] Call one, and print what it returned.
392
+ Arguments can also be one JSON object in quotes.
393
+
394
+ Options:
395
+ --json Print the answer as JSON, as the protocol carries it
396
+ --server agentface's address (default ${DEFAULT_SERVER})
397
+
398
+ Connect this machine first with: agentface login`;
399
+ async function mcp(args, options = {}) {
400
+ const { log = console.log } = options;
401
+ const [action, name, ...rest] = args;
402
+ if (!action || action === "help") {
403
+ log(MCP_HELP);
404
+ return 0;
405
+ }
406
+ if (action === "tools" || action === "list") {
407
+ const result = await request("tools/list", {}, options);
408
+ const tools = Array.isArray(result.tools) ? result.tools : [];
409
+ if (options.json) {
410
+ log(JSON.stringify(result, null, 2));
411
+ return 0;
412
+ }
413
+ for (const tool of tools) {
414
+ const properties = tool.inputSchema?.properties ?? {};
415
+ const required = tool.inputSchema?.required ?? [];
416
+ const takes = Object.entries(properties).map(([key, value]) => {
417
+ const kind = value.enum ? value.enum.join("|") : value.type ?? "value";
418
+ return required.includes(key) ? `${key}=<${kind}>` : `[${key}=<${kind}>]`;
419
+ });
420
+ log(
421
+ `${tool.name}${takes.length ? ` ${takes.join(" ")}` : ""}${tool.annotations?.readOnlyHint === false ? " (changes something)" : ""}`
422
+ );
423
+ if (tool.description) log(` ${tool.description}`);
424
+ }
425
+ return 0;
426
+ }
427
+ if (action === "call") {
428
+ if (!name) throw new Error(`Which function? agentface mcp tools lists them.
429
+
430
+ ${MCP_HELP}`);
431
+ const result = await request("tools/call", { name, arguments: readArguments(rest) }, options);
432
+ if (options.json) log(JSON.stringify(result, null, 2));
433
+ else
434
+ for (const part of Array.isArray(result.content) ? result.content : [])
435
+ if (part.type === "text" && typeof part.text === "string") log(part.text);
436
+ return result.isError === true ? 1 : 0;
437
+ }
438
+ throw new Error(`Unknown: agentface mcp ${action}.
439
+
440
+ ${MCP_HELP}`);
441
+ }
442
+
6
443
  // cli/init.mts
7
- import { execFile as execFile2 } from "node:child_process";
8
- import { mkdir, readFile as readFile2, rm, writeFile } from "node:fs/promises";
9
- import path2 from "node:path";
444
+ import { execFile as execFile3 } from "node:child_process";
445
+ import { mkdir as mkdir2, readFile as readFile3, rm as rm2, rmdir, writeFile as writeFile2 } from "node:fs/promises";
446
+ import path3 from "node:path";
10
447
 
11
448
  // worker/origin.ts
12
449
  var PRIVATE_NAMES = /(?:^|\.)(?:localhost|local|internal|lan|intranet|corp|home|arpa)$/;
@@ -41,9 +478,9 @@ function siteNotice(serviceOrigin, id) {
41
478
  }
42
479
 
43
480
  // cli/heads.mts
44
- import { execFile } from "node:child_process";
45
- import { readdir, readFile, stat } from "node:fs/promises";
46
- import path from "node:path";
481
+ import { execFile as execFile2 } from "node:child_process";
482
+ import { readdir, readFile as readFile2, stat as stat2 } from "node:fs/promises";
483
+ import path2 from "node:path";
47
484
 
48
485
  // worker/head.ts
49
486
  var ATTRIBUTES = String.raw`(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^>"'{/]|\/(?!>))*`;
@@ -57,6 +494,60 @@ function headEnd(html) {
57
494
  return -1;
58
495
  }
59
496
 
497
+ // cli/zip.mts
498
+ import { deflateRawSync } from "node:zlib";
499
+ var CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
500
+ let c = n;
501
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
502
+ return c >>> 0;
503
+ });
504
+ function crc32(data) {
505
+ let c = 4294967295;
506
+ for (const byte of data) c = CRC_TABLE[(c ^ byte) & 255] ^ c >>> 8;
507
+ return (c ^ 4294967295) >>> 0;
508
+ }
509
+ function zip(files2, date = /* @__PURE__ */ new Date()) {
510
+ const time = date.getHours() << 11 | date.getMinutes() << 5 | date.getSeconds() >> 1;
511
+ const day = date.getFullYear() - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate();
512
+ const parts = [];
513
+ const directory = [];
514
+ let offset = 0;
515
+ for (const [name, text] of Object.entries(files2)) {
516
+ const data = Buffer.from(text);
517
+ const packed = deflateRawSync(data);
518
+ const path4 = Buffer.from(name);
519
+ const shared = Buffer.alloc(26);
520
+ shared.writeUInt16LE(20, 0);
521
+ shared.writeUInt16LE(2048, 2);
522
+ shared.writeUInt16LE(8, 4);
523
+ shared.writeUInt16LE(time, 6);
524
+ shared.writeUInt16LE(day, 8);
525
+ shared.writeUInt32LE(crc32(data), 10);
526
+ shared.writeUInt32LE(packed.length, 14);
527
+ shared.writeUInt32LE(data.length, 18);
528
+ shared.writeUInt16LE(path4.length, 22);
529
+ const local = Buffer.alloc(4);
530
+ local.writeUInt32LE(67324752);
531
+ parts.push(local, shared, path4, packed);
532
+ const entry = Buffer.alloc(46);
533
+ entry.writeUInt32LE(33639248, 0);
534
+ entry.writeUInt16LE(788, 4);
535
+ shared.copy(entry, 6);
536
+ entry.writeUInt32LE(33188 * 65536, 38);
537
+ entry.writeUInt32LE(offset, 42);
538
+ directory.push(entry, path4);
539
+ offset += 4 + shared.length + path4.length + packed.length;
540
+ }
541
+ const size = directory.reduce((total, part) => total + part.length, 0);
542
+ const end = Buffer.alloc(22);
543
+ end.writeUInt32LE(101010256, 0);
544
+ end.writeUInt16LE(Object.keys(files2).length, 8);
545
+ end.writeUInt16LE(Object.keys(files2).length, 10);
546
+ end.writeUInt32LE(size, 12);
547
+ end.writeUInt32LE(offset, 16);
548
+ return Buffer.concat([...parts, ...directory, end]);
549
+ }
550
+
60
551
  // cli/heads.mts
61
552
  var EXTENSIONS = [
62
553
  "html",
@@ -74,6 +565,7 @@ var EXTENSIONS = [
74
565
  "jinja2",
75
566
  "j2",
76
567
  "tmpl",
568
+ "tpl",
77
569
  "astro"
78
570
  ];
79
571
  var MARKUP = new RegExp(`\\.(?:${EXTENSIONS.join("|")})$`, "i");
@@ -130,11 +622,69 @@ var FRAMEWORKS = [
130
622
  ["@vue/cli-service", "Vue CLI"],
131
623
  ["vite", "Vite"]
132
624
  ];
133
- var read = (file) => readFile(file, "utf8").catch(() => null);
134
- var exists = (file) => stat(file).then(
625
+ var read = (file) => readFile2(file, "utf8").catch(() => null);
626
+ var exists = (file) => stat2(file).then(
135
627
  () => true,
136
628
  () => false
137
629
  );
630
+ var THEME = /^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name\s*:/im;
631
+ async function isWordPress(dir) {
632
+ if (THEME.test((await read(path2.join(dir, "style.css")) ?? "").slice(0, 8192))) return true;
633
+ for (const name of ["wp-content", "wp-includes"]) if (await exists(path2.join(dir, name))) return true;
634
+ for (let at = path2.resolve(dir); ; at = path2.dirname(at)) {
635
+ if (path2.basename(at) === "wp-content" || await exists(path2.join(at, "wp-config.php"))) return true;
636
+ if (path2.dirname(at) === at) return false;
637
+ }
638
+ }
639
+ async function contentFolder(dir) {
640
+ const here = path2.resolve(dir);
641
+ for (let at = here; ; at = path2.dirname(at)) {
642
+ if (path2.basename(at) === "wp-content") return at;
643
+ const content = path2.join(at, "wp-content");
644
+ if ((at === here || await exists(path2.join(at, "wp-config.php"))) && await exists(content))
645
+ return content;
646
+ if (path2.dirname(at) === at) return null;
647
+ }
648
+ }
649
+ async function wordPressFile(dir) {
650
+ const content = await contentFolder(dir);
651
+ return content && path2.relative(dir, path2.join(content, "mu-plugins", "agentface.php")).split(path2.sep).join("/");
652
+ }
653
+ var wordPressPage = (html) => /\/wp-(?:content|includes)\/|["']https:\/\/api\.w\.org\/["']|<meta\b[^>]*\bcontent=["']WordPress\b/i.test(
654
+ html
655
+ );
656
+ var WORDPRESS_STEPS = (tag, notice) => [
657
+ 'In the WordPress admin, open Plugins > Add New Plugin, search for WPCode, then install and activate "WPCode \u2013 Insert Headers and Footers".',
658
+ "Open Code Snippets > Header & Footer.",
659
+ `Paste this line in the Header box:
660
+
661
+ ${tag}`,
662
+ ...notice ? [`Paste this line in the Body box:
663
+
664
+ ${notice}`] : [],
665
+ "Click Save Changes. If the site has a caching plugin, clear its cache, so the homepage shows the change."
666
+ ].map((step, i) => ` ${i + 1}. ${step}`).join("\n\n") + "\n";
667
+ var wordPressManual = (lead) => ({
668
+ reason: `${lead} Run in the site's folder, the one with wp-config.php, init adds a plugin of its own that puts the tag on every page. It never edits WordPress's, its plugins' or its theme's files: updates put them back and take the tag away, and a header plugin or page builder, such as Elementor's, can replace the theme's header, so that a tag put there reaches no page.`,
669
+ how: "Or add it with a plugin that has boxes for the site's head and body, such as the free WPCode",
670
+ steps: WORDPRESS_STEPS
671
+ });
672
+ var SHOP = /\b_PS_[A-Z_]+_\b/;
673
+ var PRESTASHOP_MODULE_FILE = "agentface/agentface.php";
674
+ async function shopFolder(dir) {
675
+ for (let at = path2.resolve(dir); ; at = path2.dirname(at)) {
676
+ if (SHOP.test(await read(path2.join(at, "config", "defines.inc.php")) ?? "")) return at;
677
+ if (path2.dirname(at) === at) return null;
678
+ }
679
+ }
680
+ async function prestaShopFile(dir) {
681
+ const shop = await shopFolder(dir);
682
+ return shop && path2.relative(dir, path2.join(shop, "modules", PRESTASHOP_MODULE_FILE)).split(path2.sep).join("/");
683
+ }
684
+ async function prestaShopTheme(dir) {
685
+ return /^name\s*:/m.test(await read(path2.join(dir, "config", "theme.yml")) ?? "") && await exists(path2.join(dir, "templates"));
686
+ }
687
+ var prestaShopPage = (html) => /\bvar\s+prestashop\s*=/.test(html);
138
688
  var KEY = /\/s\/(site-[a-z0-9-]+)\.js(?=[?#"'`\s]|$)/;
139
689
  var ATTRIBUTES2 = String.raw`(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|[^>])*?`;
140
690
  var TAG = new RegExp(
@@ -155,12 +705,14 @@ function indentUnit(source) {
155
705
  return source.match(/^(\t| {2,4})\S/m)?.[1] ?? " ";
156
706
  }
157
707
  var indentOf = (line) => line.match(/^[ \t]*/)[0];
708
+ var NONCE = /\snonce\s*=\s*(\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^\s>]+)/i;
158
709
  function addTag(source, tag) {
159
710
  let first = true;
160
711
  const replaced = source.replace(onItsLine(TAG), (match, line) => {
161
712
  if (!first) return "";
162
713
  first = false;
163
- return (line ?? "") + tag;
714
+ const nonce = match.match(NONCE)?.[1];
715
+ return (line ?? "") + (nonce ? tag.replace(/^<script\b/, () => `<script nonce=${nonce}`) : tag);
164
716
  });
165
717
  if (!first) return replaced;
166
718
  const eol = source.includes("\r\n") ? "\r\n" : "\n";
@@ -205,7 +757,7 @@ function addNotice(source, notice) {
205
757
  }
206
758
  function gitFiles(dir) {
207
759
  return new Promise((resolve) => {
208
- execFile(
760
+ execFile2(
209
761
  "git",
210
762
  ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
211
763
  { cwd: dir, maxBuffer: 64 * 1024 * 1024 },
@@ -223,7 +775,7 @@ async function files(dir, skip) {
223
775
  };
224
776
  const found = [];
225
777
  const visit = async (rel) => {
226
- const entries = await readdir(path.join(dir, rel), { withFileTypes: true }).catch(() => []);
778
+ const entries = await readdir(path2.join(dir, rel), { withFileTypes: true }).catch(() => []);
227
779
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
228
780
  const file = rel ? `${rel}/${entry.name}` : entry.name;
229
781
  if (entry.isDirectory()) {
@@ -235,13 +787,13 @@ async function files(dir, skip) {
235
787
  return { git: false, files: found };
236
788
  }
237
789
  async function contents(dir, file) {
238
- const info = await stat(path.join(dir, file)).catch(() => null);
239
- return info?.isFile() && info.size <= MAX_BYTES ? read(path.join(dir, file)) : null;
790
+ const info = await stat2(path2.join(dir, file)).catch(() => null);
791
+ return info?.isFile() && info.size <= MAX_BYTES ? read(path2.join(dir, file)) : null;
240
792
  }
241
793
  async function siteGenerator(dir) {
242
794
  for (const file of ["hugo.toml", "hugo.yaml", "hugo.json", "config.toml"])
243
- if (/\bbaseURL\b/i.test(await read(path.join(dir, file)) ?? "")) return "Hugo";
244
- if (await exists(path.join(dir, "_config.yml")) || await exists(path.join(dir, "_layouts")))
795
+ if (/\bbaseURL\b/i.test(await read(path2.join(dir, file)) ?? "")) return "Hugo";
796
+ if (await exists(path2.join(dir, "_config.yml")) || await exists(path2.join(dir, "_layouts")))
245
797
  return "Jekyll";
246
798
  return null;
247
799
  }
@@ -280,19 +832,76 @@ ${text ? ` setPreBodyComponents([React.createElement('noscript', { key: 'agentf
280
832
  ` : ""}};
281
833
  `;
282
834
  };
835
+ var MU_PLUGIN = (tag, notice) => `<?php
836
+ /**
837
+ * Plugin Name: Agentface
838
+ * Description: Puts the Agentface tag in every page's head${notice ? ", and its notice first in the body" : ""}.
839
+ */
840
+ // ${OURS}. WordPress runs it on every page, and \`npx agentface uninstall\` deletes it.
841
+
842
+ add_action('wp_head', function () {
843
+ echo '${tag}' . "\\n";
844
+ }, PHP_INT_MAX);
845
+ ${notice ? `
846
+ add_action('wp_body_open', function () {
847
+ echo '${notice}' . "\\n";
848
+ }, PHP_INT_MIN);
849
+ ` : ""}`;
850
+ var PRESTASHOP_MODULE = (tag, notice) => `<?php
851
+ // ${OURS}. PrestaShop runs it on every page once it's installed in Modules > Module Manager, and \`npx agentface uninstall\` deletes it.
852
+ if (!defined('_PS_VERSION_')) {
853
+ exit;
854
+ }
855
+
856
+ class Agentface extends Module
857
+ {
858
+ public function __construct()
859
+ {
860
+ $this->name = 'agentface';
861
+ $this->tab = 'front_office_features';
862
+ $this->version = '1.0.0';
863
+ $this->author = 'Agentface';
864
+ $this->need_instance = 0;
865
+ $this->ps_versions_compliancy = ['min' => '1.7.0.0', 'max' => _PS_VERSION_];
866
+ parent::__construct();
867
+ $this->displayName = 'Agentface';
868
+ $this->description = "Puts the Agentface tag in every page's head${notice ? ", and its notice first in the body" : ""}.";
869
+ }
870
+
871
+ public function install()
872
+ {
873
+ return parent::install()
874
+ && $this->registerHook('displayHeader')${notice ? `
875
+ && $this->registerHook('displayAfterBodyOpeningTag')` : ""};
876
+ }
877
+
878
+ public function hookDisplayHeader()
879
+ {
880
+ return '${tag}' . "\\n";
881
+ }
882
+ ${notice ? `
883
+ public function hookDisplayAfterBodyOpeningTag()
884
+ {
885
+ return '${notice}' . "\\n";
886
+ }
887
+ ` : ""}}
888
+ `;
889
+ var prestaShopZip = (tag, notice) => zip({ [PRESTASHOP_MODULE_FILE]: PRESTASHOP_MODULE(tag, notice) });
283
890
  async function project(dir) {
284
- const pkg = JSON.parse(await read(path.join(dir, "package.json")) ?? "null");
891
+ const pkg = JSON.parse(await read(path2.join(dir, "package.json")) ?? "null");
285
892
  const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
286
893
  const generator = await siteGenerator(dir);
287
894
  const skip = new Set(SKIP);
288
895
  if (generator === "Hugo") for (const name of ["public", "resources", "themes"]) skip.add(name);
289
896
  if (deps.gatsby) skip.add("public");
290
- const framework = FRAMEWORKS.find(([dependency]) => deps[dependency])?.[1] ?? generator ?? (pkg ? "JavaScript" : "HTML");
897
+ const framework = (await prestaShopTheme(dir) ? "PrestaShop theme" : null) ?? FRAMEWORKS.find(([dependency]) => deps[dependency])?.[1] ?? generator ?? (pkg ? "JavaScript" : "HTML");
291
898
  const { files: list2, git } = await files(dir, skip);
292
899
  return { deps, framework, list: list2, git };
293
900
  }
294
901
  async function findTags(dir) {
295
902
  const { list: list2 } = await project(dir);
903
+ const plugin = await isWordPress(dir) && await wordPressFile(dir) || await prestaShopFile(dir);
904
+ if (plugin && !list2.includes(plugin)) list2.push(plugin);
296
905
  const tagged = [];
297
906
  for (const file of list2) {
298
907
  const source = await contents(dir, file);
@@ -309,6 +918,8 @@ function madeByInit(source) {
309
918
  const text = gatsby(/createElement\('noscript', \{ key: 'agentface' \}, '([^']*)'\)/);
310
919
  const made = [
311
920
  [NEXT_DOCUMENT, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
921
+ [MU_PLUGIN, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
922
+ [PRESTASHOP_MODULE, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
312
923
  [
313
924
  GATSBY_SSR,
314
925
  load && src && `<script ${load} src="${src}"${about ? ` ${attribute}="${about}"` : ""}></script>`,
@@ -327,7 +938,7 @@ function removeTag(source) {
327
938
  source
328
939
  );
329
940
  }
330
- async function byHand(dir, list2, framework, reason, how) {
941
+ async function byHand(dir, list2, framework, manual) {
331
942
  const tagged = [];
332
943
  const noticed = [];
333
944
  for (const file of list2) {
@@ -341,28 +952,57 @@ async function byHand(dir, list2, framework, reason, how) {
341
952
  heads: [],
342
953
  bodies: [],
343
954
  creates: [],
344
- manual: { reason, how },
955
+ manual,
345
956
  tagged,
346
957
  noticed,
347
958
  key: tagged[0]?.key ?? null
348
959
  };
349
960
  }
350
961
  async function findHeads(dir) {
962
+ if (await isWordPress(dir)) {
963
+ const file = await wordPressFile(dir);
964
+ if (file) {
965
+ const source = await read(path2.join(dir, file));
966
+ return {
967
+ framework: "WordPress",
968
+ heads: [],
969
+ bodies: [],
970
+ creates: [{ file, content: MU_PLUGIN, source }],
971
+ key: source === null ? null : tagKey(source)
972
+ };
973
+ }
974
+ return byHand(
975
+ dir,
976
+ (await project(dir)).list,
977
+ "WordPress",
978
+ wordPressManual(
979
+ "This folder is a WordPress theme, or part of a WordPress site, but init can't find the site's wp-content folder from here."
980
+ )
981
+ );
982
+ }
983
+ const moduleFile = await prestaShopFile(dir);
984
+ if (moduleFile) {
985
+ const source = await read(path2.join(dir, moduleFile));
986
+ return {
987
+ framework: "PrestaShop",
988
+ heads: [],
989
+ bodies: [],
990
+ creates: [{ file: moduleFile, content: PRESTASHOP_MODULE, source }],
991
+ key: source === null ? null : tagKey(source)
992
+ };
993
+ }
351
994
  const { deps, framework, list: list2, git } = await project(dir);
352
995
  for (const [dependency, [name, where]] of Object.entries(CONFIG_HEAD))
353
996
  if (deps[dependency])
354
- return byHand(
355
- dir,
356
- list2,
357
- name,
358
- `${name} sets the page head in its config, which init can't edit yet.`,
359
- `Add it by hand through ${where}, with this tag's src`
360
- );
997
+ return byHand(dir, list2, name, {
998
+ reason: `${name} sets the page head in its config, which init can't edit yet.`,
999
+ how: `Add it by hand through ${where}, with this tag's src`
1000
+ });
361
1001
  const heads = [];
362
1002
  const bodies = [];
363
1003
  for (const file of list2) {
364
1004
  const markup = MARKUP.test(file);
365
- if (!markup && !LAYOUTS.some((layout) => layout.test(file)) || MAIL.test(path.posix.basename(file)))
1005
+ if (!markup && !LAYOUTS.some((layout) => layout.test(file)) || MAIL.test(path2.posix.basename(file)))
366
1006
  continue;
367
1007
  const text = await contents(dir, file);
368
1008
  if (text === null) continue;
@@ -373,42 +1013,249 @@ async function findHeads(dir) {
373
1013
  const creates = [];
374
1014
  if (deps.next && !heads.some(({ file }) => /(?:^|\/)app\//.test(file))) {
375
1015
  if (!heads.some(({ file }) => /pages\/_document\./.test(file))) {
376
- const pages = await exists(path.join(dir, "pages")) ? "pages" : "src/pages";
377
- if (await exists(path.join(dir, pages)))
1016
+ const pages = await exists(path2.join(dir, "pages")) ? "pages" : "src/pages";
1017
+ if (await exists(path2.join(dir, pages)))
378
1018
  creates.push({ file: `${pages}/_document.js`, content: NEXT_DOCUMENT });
379
1019
  }
380
1020
  }
381
1021
  if (deps.gatsby && !heads.length) {
382
1022
  const own = ["js", "jsx", "ts", "tsx"].map((ext) => `gatsby-ssr.${ext}`);
383
1023
  const present = [];
384
- for (const file of own) if (await exists(path.join(dir, file))) present.push(file);
385
- const text = present.length === 1 ? await read(path.join(dir, present[0])) : null;
1024
+ for (const file of own) if (await exists(path2.join(dir, file))) present.push(file);
1025
+ const text = present.length === 1 ? await read(path2.join(dir, present[0])) : null;
386
1026
  if (present.length && !(present[0] === "gatsby-ssr.js" && text?.includes(OURS)))
387
- return byHand(
388
- dir,
389
- list2,
390
- framework,
391
- `This Gatsby site has its own ${present[0]}, which init can't edit yet.`,
392
- "Add it by hand through setHeadComponents in onRenderBody, with this tag's src"
393
- );
1027
+ return byHand(dir, list2, framework, {
1028
+ reason: `This Gatsby site has its own ${present[0]}, which init can't edit yet.`,
1029
+ how: "Add it by hand through setHeadComponents in onRenderBody, with this tag's src"
1030
+ });
394
1031
  creates.push({ file: "gatsby-ssr.js", content: GATSBY_SSR, source: text });
395
1032
  }
396
1033
  if (!heads.length && !creates.length)
397
- return byHand(
398
- dir,
399
- list2,
400
- framework,
401
- `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.`,
402
- "Add this line by hand, last in the <head> of the layout or template every page uses"
403
- );
1034
+ return byHand(dir, list2, framework, {
1035
+ reason: `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.`,
1036
+ how: "Add this line by hand, last in the <head> of the layout or template every page uses",
1037
+ none: true
1038
+ });
404
1039
  const sources = [...heads.map(({ source }) => source), ...creates.map(({ source }) => source ?? "")];
405
1040
  return { framework, heads, bodies, creates, key: sources.map(tagKey).find(Boolean) ?? null };
406
1041
  }
407
1042
 
1043
+ // worker/html.ts
1044
+ var ATTRIBUTE = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
1045
+ function attributesOf(text) {
1046
+ const values = {};
1047
+ for (const [, name, ...value] of text.matchAll(ATTRIBUTE))
1048
+ values[name.toLowerCase()] ??= decodeEntities(value.find((v) => v !== void 0) ?? "");
1049
+ return values;
1050
+ }
1051
+ function decodeEntities(s) {
1052
+ return s.replace(/&(#x?[0-9a-f]+|amp|lt|gt|quot|apos|nbsp);/gi, (m, e) => {
1053
+ const named = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " }[e.toLowerCase()];
1054
+ if (named) return named;
1055
+ const code = e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
1056
+ return code >= 0 && code <= 1114111 ? String.fromCodePoint(code) : m;
1057
+ });
1058
+ }
1059
+
1060
+ // worker/http.ts
1061
+ var USER_AGENT = "AgentfaceFetcher/0.1 (+https://agentface.com)";
1062
+ async function readStart(response, limit) {
1063
+ if (!response.body) return "";
1064
+ const reader = response.body.getReader();
1065
+ const chunks = [];
1066
+ let length = 0;
1067
+ while (length < limit) {
1068
+ const { done, value } = await reader.read();
1069
+ if (done) break;
1070
+ chunks.push(value);
1071
+ length += value.byteLength;
1072
+ }
1073
+ await reader.cancel().catch(() => {
1074
+ });
1075
+ return new TextDecoder().decode(concat(chunks, length).subarray(0, limit));
1076
+ }
1077
+ function concat(chunks, length) {
1078
+ const bytes = new Uint8Array(length);
1079
+ let offset = 0;
1080
+ for (const chunk of chunks) {
1081
+ bytes.set(chunk, offset);
1082
+ offset += chunk.byteLength;
1083
+ }
1084
+ return bytes;
1085
+ }
1086
+
1087
+ // cli/policy.mts
1088
+ function parsePolicy(text, where) {
1089
+ const directives = /* @__PURE__ */ new Map();
1090
+ for (const part of text.split(";")) {
1091
+ const [name, ...sources] = part.trim().split(/[\t\n\f\r ]+/);
1092
+ if (name && !directives.has(name.toLowerCase())) directives.set(name.toLowerCase(), sources);
1093
+ }
1094
+ return { where, directives };
1095
+ }
1096
+ var NOT_MARKUP = /<!--[\s\S]*?(?:-->|$)|<(script|style|noscript|template|textarea|title)\b[^>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi;
1097
+ var META = /<meta\b((?:"[^"]*"|'[^']*'|[^>"'])*)>/gi;
1098
+ function pagePolicies(header, html) {
1099
+ const policies = (header ?? "").split(",").filter((text) => text.trim()).map((text) => parsePolicy(text, "header"));
1100
+ const end = headEnd(html);
1101
+ const head = (end === -1 ? html : html.slice(0, end)).replace(NOT_MARKUP, "");
1102
+ for (const [, text] of head.matchAll(META)) {
1103
+ const attributes = attributesOf(text);
1104
+ if (attributes["http-equiv"]?.trim().toLowerCase() === "content-security-policy" && attributes.content)
1105
+ policies.push(parsePolicy(attributes.content, "meta"));
1106
+ }
1107
+ return policies.filter((policy) => policy.directives.size);
1108
+ }
1109
+ var scheme = (url) => url.protocol.slice(0, -1);
1110
+ var DEFAULT_PORT = { http: "80", https: "443", ws: "80", wss: "443" };
1111
+ var schemeMatches = (a, b) => a === b || a === "http" && b === "https" || a === "ws" && ["wss", "http", "https"].includes(b) || a === "wss" && b === "https";
1112
+ var decode = (segment) => {
1113
+ try {
1114
+ return decodeURIComponent(segment);
1115
+ } catch {
1116
+ return segment;
1117
+ }
1118
+ };
1119
+ function pathMatches(a, b) {
1120
+ if (!a || a === "/" && !b) return true;
1121
+ const exact = !a.endsWith("/");
1122
+ const listA = a.split("/");
1123
+ const listB = b.split("/");
1124
+ if (listA.length > listB.length || exact && listA.length !== listB.length) return false;
1125
+ if (!exact) listA.pop();
1126
+ return listA.every((segment, i) => decode(segment) === decode(listB[i]));
1127
+ }
1128
+ var HOST_SOURCE = /^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::(\d+|\*))?(\/[^?#]*)?$/i;
1129
+ function sourceMatches(source, url, page2) {
1130
+ const lower = source.toLowerCase();
1131
+ if (lower === "*") return ["http", "https", "ws", "wss", scheme(page2)].includes(scheme(url));
1132
+ if (lower === "'self'")
1133
+ return url.hostname === page2.hostname && (url.origin === page2.origin || scheme(page2) === "http" && scheme(url) === "https" && !url.port);
1134
+ if (/^[a-z][a-z0-9+.-]*:$/.test(lower)) return schemeMatches(lower.slice(0, -1), scheme(url));
1135
+ const [, sourceScheme, host, port, path4] = source.match(HOST_SOURCE) ?? [];
1136
+ if (!host) return false;
1137
+ if (!schemeMatches(sourceScheme?.toLowerCase() ?? scheme(page2), scheme(url))) return false;
1138
+ const name = host.toLowerCase();
1139
+ if (name.startsWith("*.") ? !url.hostname.endsWith(name.slice(1)) : name !== "*" && name !== url.hostname)
1140
+ return false;
1141
+ if (port === void 0 ? url.port !== "" : port !== "*" && port !== (url.port || DEFAULT_PORT[scheme(url)]))
1142
+ return false;
1143
+ return pathMatches(path4 ?? "", url.pathname);
1144
+ }
1145
+ var keyword = (sources, word) => sources.some((source) => source.toLowerCase() === word);
1146
+ var hasNonce = (sources, nonce) => sources.some((source) => /^'nonce-/i.test(source) && source.slice(7, -1) === nonce && source.endsWith("'"));
1147
+ var governing = (policy, names) => names.find((name) => policy.directives.has(name));
1148
+ function fix(policy, decides, name, origin) {
1149
+ const sources = policy.directives.get(decides).filter((source) => source.toLowerCase() !== "'none'");
1150
+ return { name, line: [name, ...sources, origin].join(" "), created: decides !== name };
1151
+ }
1152
+ function blockedBy(policies, load) {
1153
+ const page2 = new URL(load.page);
1154
+ const script = new URL(load.script);
1155
+ const events = new URL(load.events);
1156
+ const blocked = [];
1157
+ for (const policy of policies) {
1158
+ const result = { where: policy.where, script: false, connect: false, nonce: null, fixes: [] };
1159
+ const scripts = governing(policy, ["script-src-elem", "script-src", "default-src"]);
1160
+ if (scripts) {
1161
+ const sources = policy.directives.get(scripts);
1162
+ const dynamic = keyword(sources, "'strict-dynamic'");
1163
+ const allowed = load.nonce && hasNonce(sources, load.nonce) || (dynamic ? load.added : sources.some((source) => sourceMatches(source, script, page2)));
1164
+ if (!allowed) {
1165
+ result.script = true;
1166
+ if (dynamic) result.nonce = { directive: scripts, named: sources.some((s) => /^'nonce-/i.test(s)) };
1167
+ else
1168
+ result.fixes.push(
1169
+ fix(policy, scripts, scripts === "default-src" ? "script-src" : scripts, script.origin)
1170
+ );
1171
+ }
1172
+ }
1173
+ const connects = governing(policy, ["connect-src", "default-src"]);
1174
+ if (connects && !policy.directives.get(connects).some((source) => sourceMatches(source, events, page2))) {
1175
+ result.connect = true;
1176
+ result.fixes.push(fix(policy, connects, "connect-src", events.origin));
1177
+ }
1178
+ if (result.script || result.connect) blocked.push(result);
1179
+ }
1180
+ return blocked;
1181
+ }
1182
+ var WHERE = {
1183
+ header: "In the Content-Security-Policy header the site sends with its pages",
1184
+ meta: "In the Content-Security-Policy <meta> tag in the head of its pages"
1185
+ };
1186
+ var and = (names) => names.join(" and ");
1187
+ var or = (names) => names.join(" or ");
1188
+ function advice(blocked, host) {
1189
+ const script = blocked.some((b) => b.script);
1190
+ const connect = blocked.some((b) => b.connect);
1191
+ const effect = script && connect ? "load the Agentface script or send its events" : script ? "load the Agentface script" : "send the Agentface script's events";
1192
+ const paragraphs = blocked.map(({ where, nonce, fixes }) => {
1193
+ let text = !nonce ? "" : nonce.named ? `${WHERE[where]}, ${nonce.directive} has 'strict-dynamic': browsers then ignore the hosts it lists, and load only a script that carries the nonce the page gives its own scripts, or that such a script adds. Give the Agentface tag that nonce, the way the site gives it to its other script tags.` : `${WHERE[where]}, ${nonce.directive} has 'strict-dynamic' and no nonce: browsers then ignore the hosts it lists, and load only a script it lists by hash, or that such a script adds. Add a nonce to ${nonce.directive}, as 'nonce-' and a random value the server makes anew for each page, and give the Agentface tag the same value in its nonce attribute. Or add the tag from a script the page already runs.`;
1194
+ const existing = fixes.filter((f) => !f.created).map(({ name }) => name);
1195
+ const created = fixes.filter((f) => f.created).map(({ name }) => name);
1196
+ const what = [
1197
+ existing.length && `${host} at the end of ${and(existing)}, after the hosts ${existing.length === 1 ? "it already lists" : "they already list"}`,
1198
+ created.length && `${created.length === 1 ? "a " : ""}${and(created)} ${created.length === 1 ? "line" : "lines"} with ${existing.length ? "it" : host}`
1199
+ ].filter(Boolean);
1200
+ if (fixes.length)
1201
+ text += `${nonce ? " Also" : `${WHERE[where]},`} add ${what.join(", and ")}, so ${fixes.length === 1 ? "it reads" : "they read"}:
1202
+
1203
+ ` + fixes.map(({ line }) => ` ${line}`).join("\n");
1204
+ if (created.length)
1205
+ text += `
1206
+
1207
+ It has no ${or(created)} yet, so ${created.length === 1 ? "the new line starts" : "each new line starts"} with what its default-src allows: the rest of the site works as before.`;
1208
+ return text;
1209
+ });
1210
+ return { effect, fixes: paragraphs.join("\n\n") + "\n" };
1211
+ }
1212
+ async function readHomepage(origin, fetcher) {
1213
+ try {
1214
+ const response = await fetcher(origin + "/", {
1215
+ headers: { accept: "text/html", "user-agent": USER_AGENT },
1216
+ redirect: "follow",
1217
+ signal: AbortSignal.timeout(1e4)
1218
+ });
1219
+ if (!response.ok) {
1220
+ await response.body?.cancel();
1221
+ return { unread: `it answered HTTP ${response.status}` };
1222
+ }
1223
+ const html = await readStart(response, 2e5);
1224
+ const policies = pagePolicies(response.headers.get("content-security-policy"), html);
1225
+ return { url: response.url || origin + "/", html, policies };
1226
+ } catch (error) {
1227
+ const { name, message, cause } = error;
1228
+ return {
1229
+ unread: name === "TimeoutError" ? "it didn't answer within 10 seconds" : `the request failed (${cause?.message ?? message})`
1230
+ };
1231
+ }
1232
+ }
1233
+ var SCRIPT = /<script\b((?:"[^"]*"|'[^']*'|[^>"'])*)>/gi;
1234
+ function liveNonce(html, id) {
1235
+ for (const [, text] of html.matchAll(SCRIPT)) {
1236
+ const attributes = attributesOf(text);
1237
+ if ((attributes.src ?? "").split(/[?#]/)[0].endsWith(`/s/${id}.js`)) return attributes.nonce || null;
1238
+ }
1239
+ return void 0;
1240
+ }
1241
+ function tagBlocked(homepage, site, { added = false } = {}) {
1242
+ const src = site.tag.match(/\bsrc="([^"]+)"/)?.[1];
1243
+ if ("unread" in homepage || !homepage.policies.length || !src) return null;
1244
+ const nonce = liveNonce(homepage.html, site.id);
1245
+ const blocked = blockedBy(homepage.policies, {
1246
+ page: homepage.url,
1247
+ script: src,
1248
+ events: new URL("/e", src).href,
1249
+ nonce,
1250
+ added: nonce === void 0 && added
1251
+ });
1252
+ return blocked.length ? advice(blocked, new URL(src).origin) : null;
1253
+ }
1254
+
408
1255
  // cli/init.mts
409
1256
  var DEFAULT_SERVICE = "https://cdn.agentfacehq.com";
410
1257
  var BRANCH = "agentface";
411
- var readJson = async (file) => JSON.parse(await readFile2(file, "utf8").catch(() => "null"));
1258
+ var readJson = async (file) => JSON.parse(await readFile3(file, "utf8").catch(() => "null"));
412
1259
  var when = (iso) => iso.slice(0, 16).replace("T", " ") + " UTC";
413
1260
  async function reach(service, url, init2, fetcher) {
414
1261
  try {
@@ -456,14 +1303,14 @@ async function confirm(service, id, fetcher = fetch) {
456
1303
  var option = (source, name) => source?.match(new RegExp(`^\\s*${name}["']?\\s*[:=]\\s*["'\`]?([^"'\`\\s]+)`, "m"))?.[1] ?? null;
457
1304
  var config = async (dir, names) => {
458
1305
  for (const name of names) {
459
- const source = await readFile2(path2.join(dir, name), "utf8").catch(() => null);
1306
+ const source = await readFile3(path3.join(dir, name), "utf8").catch(() => null);
460
1307
  if (source !== null) return { source, name };
461
1308
  }
462
1309
  return { source: null };
463
1310
  };
464
1311
  async function siteUrl(dir, exec = run) {
465
1312
  for (const file of ["CNAME", "public/CNAME", "static/CNAME"]) {
466
- const host = (await readFile2(path2.join(dir, file), "utf8").catch(() => "")).trim().split(/\s+/)[0];
1313
+ const host = (await readFile3(path3.join(dir, file), "utf8").catch(() => "")).trim().split(/\s+/)[0];
467
1314
  if (host) return { url: `https://${host}/`, from: file };
468
1315
  }
469
1316
  for (const [names, key] of [
@@ -475,7 +1322,7 @@ async function siteUrl(dir, exec = run) {
475
1322
  const url = option(source, key);
476
1323
  if (/^https?:\/\//i.test(url ?? "")) return { url, from: name };
477
1324
  }
478
- const homepage = (await readJson(path2.join(dir, "package.json")))?.homepage;
1325
+ const homepage = (await readJson(path3.join(dir, "package.json")))?.homepage;
479
1326
  if (/^https?:\/\//i.test(homepage ?? "")) return { url: homepage, from: 'package.json "homepage"' };
480
1327
  const remote = await exec("git", ["remote", "get-url", "origin"], { cwd: dir }).catch(() => "");
481
1328
  const [, owner, repo] = remote.match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/i) ?? [];
@@ -485,7 +1332,7 @@ async function siteUrl(dir, exec = run) {
485
1332
  }
486
1333
  function run(command, args, { cwd }) {
487
1334
  return new Promise((resolve, reject) => {
488
- execFile2(command, args, { cwd }, (error, stdout, stderr) => {
1335
+ execFile3(command, args, { cwd }, (error, stdout, stderr) => {
489
1336
  if (error)
490
1337
  reject(
491
1338
  new Error(`${command} ${args.join(" ")} failed: ${(stderr || error.message).trim()}`)
@@ -568,23 +1415,35 @@ async function siteFor({
568
1415
  }
569
1416
  var serviceFlag = (service) => service === DEFAULT_SERVICE ? "" : ` --service ${service}`;
570
1417
  var list = (files2) => files2.length <= 3 ? files2.join(", ") : `${files2.slice(0, 3).join(", ")} and ${files2.length - 3} more`;
571
- function nextSteps(site, service) {
572
- const check2 = `npx agentface check${serviceFlag(service)}`;
1418
+ function nextSteps(site, service, own) {
1419
+ const saved = own === "plugin";
1420
+ const check2 = `npx agentface check${saved ? ` --site ${site.id}` : ""}${serviceFlag(service)}`;
1421
+ if (own === "file")
1422
+ return site.expiresAt ? `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.` : `Then \`${check2}\` shows whether ${site.origin}'s homepage has the tag.`;
1423
+ if (saved)
1424
+ return site.expiresAt ? `Then run \`${check2}\`: 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)}. To see these steps again without registering the site another time, run \`npx agentface init ${site.id}${serviceFlag(service)}\`.` : `Then \`${check2}\` shows whether ${site.origin}'s homepage has the tag.`;
573
1425
  return site.expiresAt ? `Deploy it as usual, then run \`${check2}\` here: once ${site.origin}'s homepage has the tag, in its HTML or in the Google Tag Manager container it loads, 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.`;
574
1426
  }
575
- function prBody(site, files2, service = DEFAULT_SERVICE) {
1427
+ function policyWarning(site, advice2) {
1428
+ return advice2 ? `${site.origin}'s Content Security Policy, the list of hosts its pages may use, doesn't let them ${advice2.effect}. ${advice2.fixes}` : null;
1429
+ }
1430
+ var markdown = (warning) => warning.trim().replaceAll("<meta>", "`<meta>`").replace(/(?:^ {2}\S.*\n?)+/gm, (lines) => "```\n" + lines.replace(/^ {2}/gm, "").trimEnd() + "\n```\n").trimEnd();
1431
+ function prBody(site, files2, service = DEFAULT_SERVICE, warning = null) {
576
1432
  const src = site.tag.match(/\bsrc="([^"]+)"/)?.[1];
577
1433
  const notice = site.notice ? ` A \`<noscript>\` line first in the body links agents that read pages without running them, and so never get the tools, to a list of them. Browsers that run scripts don't show it.` : "";
578
1434
  return `Adds the Agentface tag to ${site.origin}, so AI agents that use the site in a browser get tools made for them.
579
1435
 
580
- **What it does.** It changes ${files2.map((file) => `\`${file}\``).join(", ")}. One \`<script defer>\` line in the head 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.${notice} People visiting the site see no change, and it sets no cookies.
1436
+ **What it does.** It changes ${files2.map((file) => `\`${file}\``).join(", ")}. One \`<script defer>\` line in the head 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 they are used: which tools, how long they took and their error codes. A visit that calls a tool is an agent's, and for those it also reports the pages opened and what was clicked, typed and asked, for the site's owner to read. A password, a payment detail and a one-time code are never sent, and a visit that calls no tool sends nothing it typed, clicked or read.${notice} People visiting the site see no change, and it sets no cookies.
1437
+
1438
+ ${warning ? `**Content Security Policy.** ${markdown(warning)}
581
1439
 
582
- **Check it.** ${nextSteps(site, service)}
1440
+ ` : ""}**Check it.** ${nextSteps(site, service)}
583
1441
 
584
1442
  **Uninstall.** Revert this pull request, or delete ${site.notice ? "the two lines" : "the line"}.
585
1443
  `;
586
1444
  }
587
- var GTM_HOW = "Can't change the site's code? Add the same line in Google Tag Manager instead: Tags > New > Custom HTML, paste it, set the trigger to Initialization - All Pages, then Submit and Publish the container.";
1445
+ var GTM_WHY = "Why: once loaded, the line registers the site's tools for AI agents, and ask_site when the site has it. AI agents never click a cookie banner, so a line held until someone accepts analytics or marketing cookies never loads, and agent visits get no tools. It sets no cookies and writes nothing to local storage. In first-party session storage, cleared when the tab closes, it keeps a random id for the tab (agentface:sid), the number of the visit's next step (agentface:n), the visit's last steps until an AI agent first uses a tool (agentface:steps), and a note that a tool was used (agentface:tool). If session storage is blocked, these are held only in the page's memory and each page counts as a visit of its own. It sends anonymous page-load and tool-use counts under that tab id, with the page's path but not its query string, and the visit's category, which is worked out in the browser. The visit's steps (pages opened, clicks, typed fields, questions asked) are sent only for a visit in which an AI agent uses a tool. Passwords, payment details, one-time codes and chosen files are never sent: such a field is sent only as hidden. The visitor's IP address is not stored. No sample of the browser's request is kept until Google Consent Mode reports analytics_storage as granted, never while it is denied or unknown, and not on a site with no consent manager. A visitor whose name is marked -User (for example ChatGPT-User) is a classic assistant when they run this line, and a crawler visit in its own bucket, with no visit steps, when they fetch the site's tool list, ask a question or leave a message without running it. Search and training crawlers are not counted as visits. There is no lasting visitor id today. If one is added, it will be written only once Google Consent Mode reports analytics_storage as granted, never while it is denied or unknown. On these facts it is reasonable to class the line as functional or necessary. The site's consent banner, privacy notice and lawful basis stay the site owner's call. This is information, not legal advice. Everything the line stores and agentface receives: https://agentface.com/docs/snippet-storage";
1446
+ var GTM_HOW = `Can't change the site's code? Add the same line in Google Tag Manager instead: Tags > New > Custom HTML, paste it, set the trigger to Initialization - All Pages, then Submit and Publish the container. Under Consent Settings choose No additional consent required: don't make it wait for a Consent Mode signal such as analytics_storage, and don't mark it as an analytics or ads tag. ${GTM_WHY}`;
588
1447
  function noticeByHand(site, noticed, log) {
589
1448
  if (site.notice && !noticed.includes(site.id))
590
1449
  log(
@@ -594,19 +1453,22 @@ function noticeByHand(site, noticed, log) {
594
1453
  `
595
1454
  );
596
1455
  }
597
- function byHand2({ manual, tagged, noticed }, site, service, dryRun, log) {
598
- const current = tagged.filter(({ key }) => key === site.id).map(({ file }) => file);
599
- if (current.length) {
1456
+ function byHand2({ manual, tagged, noticed }, site, service, dryRun, warning, log) {
1457
+ if (manual.steps) return withPlugin({ manual, tagged }, site, service, dryRun, warning, log);
1458
+ const current2 = tagged.filter(({ key }) => key === site.id).map(({ file }) => file);
1459
+ if (current2.length) {
600
1460
  log(
601
- `${list(current)} already ${current.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`
1461
+ `${list(current2)} already ${current2.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`
602
1462
  );
603
1463
  noticeByHand(site, noticed, log);
1464
+ if (warning) log(warning);
604
1465
  log(nextSteps(site, service));
605
1466
  return { site, files: [], written: false };
606
1467
  }
607
1468
  log(manual.reason);
608
1469
  if (dryRun) {
609
1470
  log(`${manual.how}. Without --dry-run, init prints the tag with the site's key.`);
1471
+ if (warning) log(warning);
610
1472
  return { site, files: [], written: false };
611
1473
  }
612
1474
  const old = tagged.map(({ file }) => file);
@@ -618,9 +1480,37 @@ function byHand2({ manual, tagged, noticed }, site, service, dryRun, log) {
618
1480
  );
619
1481
  if (!old.length) log(GTM_HOW);
620
1482
  noticeByHand(site, noticed, log);
1483
+ if (warning) log(warning);
621
1484
  log(nextSteps(site, service));
622
1485
  return { site, files: [], written: false };
623
1486
  }
1487
+ function withPlugin({ manual, tagged }, site, service, dryRun, warning, log) {
1488
+ log(manual.reason);
1489
+ if (dryRun) {
1490
+ log(`${manual.how}. Without --dry-run, init prints the steps, with the tag for the site's key.`);
1491
+ if (warning) log(warning);
1492
+ return { site, files: [], written: false };
1493
+ }
1494
+ log(`${manual.how}:
1495
+
1496
+ ${manual.steps(site.tag, site.notice)}`);
1497
+ const files2 = tagged.map(({ file }) => file);
1498
+ if (files2.length)
1499
+ log(
1500
+ `${list(files2)} ${files2.length === 1 ? "has" : "have"} an Agentface tag already, from an earlier init or added by hand. Take it out, so that no page loads the tag twice: \`npx agentface uninstall\` does it.`
1501
+ );
1502
+ if (warning) log(warning);
1503
+ log(nextSteps(site, service, "plugin"));
1504
+ return { site, files: [], written: false };
1505
+ }
1506
+ function prestaShopSteps(file) {
1507
+ const what = `That file is a PrestaShop module of Agentface's own, which puts the tag on every page of the shop whatever its theme, and which updates of PrestaShop and of the theme leave alone.`;
1508
+ const cache = "If the shop has a cache module, clear its cache, so that the pages show the tag.";
1509
+ if (file.endsWith(".zip"))
1510
+ return `${what} In the shop's back office, open Modules > Module Manager, click Upload a module and choose ${file}: PrestaShop installs it. ${cache}`;
1511
+ return `${what} If this folder is a copy of the shop rather than the live one, first upload the agentface folder to the shop's modules folder there. PrestaShop runs a module only once it's installed: in the shop's back office, open Modules > Module Manager, search for Agentface and click Install. ${cache}`;
1512
+ }
1513
+ var PRESTASHOP_THEME = "If this theme isn't yours, such as PrestaShop's own Classic, its next update puts those layouts back without the tag. Run init in the shop's folder instead, the one with config/defines.inc.php: there it adds a module that no update replaces.";
624
1514
  async function readyForPr(dir, exec) {
625
1515
  if (await exec("git", ["status", "--porcelain"], { cwd: dir }))
626
1516
  throw new Error("Commit or stash your changes first: the pull request should contain only Agentface.");
@@ -641,41 +1531,64 @@ async function init({
641
1531
  exec = run,
642
1532
  log = console.log
643
1533
  }) {
644
- const found = await findHeads(dir);
1534
+ let found = await findHeads(dir);
645
1535
  if (found.manual && pr)
646
1536
  throw new Error(
647
1537
  `${found.manual.reason} --pr only commits what init writes: run init without it to get the tag to add by hand.`
648
1538
  );
649
1539
  if (pr && !dryRun) await readyForPr(dir, exec);
650
1540
  const site = await siteFor({ id, url, dir, found, service, fetcher, exec, dryRun, log });
651
- if (found.manual) return byHand2(found, site, service, dryRun, log);
1541
+ const homepage = await readHomepage(site.origin, fetcher);
1542
+ const warning = policyWarning(site, tagBlocked(homepage, site));
1543
+ if (found.manual?.none && "html" in homepage && wordPressPage(homepage.html))
1544
+ found = {
1545
+ ...found,
1546
+ framework: "WordPress",
1547
+ manual: wordPressManual(`${site.origin}'s homepage comes from WordPress.`)
1548
+ };
1549
+ else if (found.manual?.none && "html" in homepage && prestaShopPage(homepage.html))
1550
+ found = {
1551
+ framework: "PrestaShop",
1552
+ heads: [],
1553
+ bodies: [],
1554
+ creates: [{ file: "agentface.zip", content: prestaShopZip }],
1555
+ key: null
1556
+ };
1557
+ if (found.manual) return byHand2(found, site, service, dryRun, warning, log);
652
1558
  const before = /* @__PURE__ */ new Map();
653
1559
  const after = /* @__PURE__ */ new Map();
1560
+ const edited = /* @__PURE__ */ new Map();
654
1561
  for (const { file, source } of found.heads) {
655
1562
  before.set(file, source);
656
- after.set(file, addTag(source, site.tag));
1563
+ edited.set(file, addTag(source, site.tag));
657
1564
  }
658
1565
  if (site.notice)
659
1566
  for (const { file, source } of found.bodies) {
660
1567
  before.set(file, source);
661
- after.set(file, addNotice(after.get(file) ?? source, site.notice) ?? after.get(file) ?? source);
1568
+ edited.set(file, addNotice(edited.get(file) ?? source, site.notice) ?? edited.get(file) ?? source);
662
1569
  }
1570
+ for (const [file, content] of edited) after.set(file, content);
663
1571
  for (const { file, content, source } of found.creates) {
664
1572
  before.set(file, source);
665
1573
  after.set(file, content(site.tag, site.notice));
666
1574
  }
667
1575
  const writes = [...after].filter(([file, content]) => content !== before.get(file));
668
1576
  const files2 = writes.map(([file]) => file);
1577
+ const own = found.creates.some(({ file }) => file.endsWith(".zip")) ? "plugin" : found.framework === "WordPress" || found.framework === "PrestaShop" ? "file" : void 0;
1578
+ const shop = found.framework === "PrestaShop" ? prestaShopSteps(found.creates[0].file) : null;
669
1579
  const noticed = site.notice && (found.bodies.length || found.creates.length);
670
1580
  const what = `the Agentface tag${noticed ? " and its notice" : ""}`;
671
1581
  if (!writes.length) {
672
1582
  const tagged = [...found.heads, ...found.creates].map(({ file }) => file);
673
1583
  log(`${list(tagged)} already ${tagged.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`);
674
- log(nextSteps(site, service));
1584
+ if (shop) log(shop);
1585
+ if (warning) log(warning);
1586
+ log(nextSteps(site, service, own));
675
1587
  return { site, files: files2, written: false };
676
1588
  }
677
1589
  if (dryRun) {
678
1590
  log(`Would add ${what} to ${list(files2)} (${found.framework}) for ${site.origin}.`);
1591
+ if (warning) log(warning);
679
1592
  return { site, files: files2, written: false };
680
1593
  }
681
1594
  let returnTo;
@@ -684,12 +1597,19 @@ async function init({
684
1597
  await exec("git", ["switch", "-C", BRANCH], { cwd: dir });
685
1598
  }
686
1599
  for (const [file, content] of writes) {
687
- await mkdir(path2.dirname(path2.join(dir, file)), { recursive: true });
688
- await writeFile(path2.join(dir, file), content);
1600
+ await mkdir2(path3.dirname(path3.join(dir, file)), { recursive: true });
1601
+ await writeFile2(path3.join(dir, file), content);
689
1602
  }
690
1603
  log(`Added ${what} to ${list(files2)} (${found.framework}) for ${site.origin}.`);
1604
+ if (shop) log(shop);
1605
+ if (found.framework === "PrestaShop theme") log(PRESTASHOP_THEME);
1606
+ if (found.framework === "WordPress")
1607
+ log(
1608
+ `WordPress runs that file on every page by itself, as a must-use plugin: there's nothing to activate, and updates of WordPress, its plugins and its theme leave it alone. If this folder is a copy of the site rather than the live one, upload the file to the same folder there. If the site has a caching plugin, clear its cache, so that the pages show the tag.`
1609
+ );
1610
+ if (warning) log(warning);
691
1611
  if (!pr) {
692
- log(nextSteps(site, service));
1612
+ log(nextSteps(site, service, own));
693
1613
  return { site, files: files2, written: true };
694
1614
  }
695
1615
  try {
@@ -716,7 +1636,7 @@ async function init({
716
1636
  "--title",
717
1637
  "Add Agentface for AI agents",
718
1638
  "--body",
719
- prBody(site, files2, service)
1639
+ prBody(site, files2, service, warning)
720
1640
  ],
721
1641
  { cwd: dir }
722
1642
  );
@@ -736,13 +1656,36 @@ async function check({
736
1656
  if (!id) {
737
1657
  const found = await findHeads(dir);
738
1658
  id = found.key;
1659
+ if (!id && found.manual?.steps)
1660
+ throw new Error(
1661
+ "On WordPress the tag isn't in the site's files, so check can't find the site key here. Pass it: npx agentface check --site <site key>. It's in the tag init printed, after /s/."
1662
+ );
739
1663
  if (!id)
740
1664
  throw new Error(
741
1665
  'No Agentface tag in this project. Run "npx agentface init" first, or pass the site key with --site.'
742
1666
  );
743
1667
  }
744
1668
  const site = await lookupSite(service, id, fetcher);
745
- const result = await confirm(service, id, fetcher);
1669
+ const [result, homepage] = await Promise.all([
1670
+ confirm(service, id, fetcher),
1671
+ readHomepage(site.origin, fetcher)
1672
+ ]);
1673
+ if (result.ok && "unread" in homepage) {
1674
+ log(
1675
+ `${site.expiresAt ? `Confirmed: ${site.origin}'s homepage has the tag, so ${id} is yours and Agentface keeps it. But` : `${site.origin}'s homepage has the tag for ${id}, but`} check couldn't read the homepage from here to see whether the site's Content Security Policy lets browsers load the tag: ${homepage.unread}. Run \`npx agentface check${serviceFlag(service)}\` again. If it keeps failing, open the homepage in a browser: its developer console names anything the policy blocks.`
1676
+ );
1677
+ return 1;
1678
+ }
1679
+ const advice2 = tagBlocked(homepage, site, { added: result.ok });
1680
+ if (result.ok && advice2) {
1681
+ log(
1682
+ `Blocked: ${site.origin}'s homepage has the tag for ${id}, but the site's Content Security Policy, the list of hosts its pages may use, doesn't let them ${advice2.effect}. ${advice2.fixes}`
1683
+ );
1684
+ log(
1685
+ `${site.expiresAt ? `The tag still confirms the site is yours, so Agentface keeps ${id}. ` : ""}Deploy the change to the policy, then run \`npx agentface check${serviceFlag(service)}\` again.`
1686
+ );
1687
+ return 1;
1688
+ }
746
1689
  if (result.ok) {
747
1690
  log(
748
1691
  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}.`
@@ -750,8 +1693,15 @@ async function check({
750
1693
  return 0;
751
1694
  }
752
1695
  log(result.message);
1696
+ const module = await prestaShopFile(dir);
1697
+ if (module && await readFile3(path3.join(dir, module)).catch(() => null))
1698
+ log(
1699
+ `PrestaShop runs ${module} only once it's installed. If it isn't yet, open Modules > Module Manager in the shop's back office, search for Agentface and click Install.`
1700
+ );
753
1701
  if (result.status === 422 && site.expiresAt)
754
1702
  log(`Until it's confirmed, Agentface deletes ${id} at ${when(site.expiresAt)}.`);
1703
+ const warning = policyWarning(site, advice2);
1704
+ if (warning) log(warning);
755
1705
  return 1;
756
1706
  }
757
1707
  async function uninstall({
@@ -762,6 +1712,11 @@ async function uninstall({
762
1712
  log = console.log
763
1713
  }) {
764
1714
  const tagged = await findTags(dir);
1715
+ const plugin = await isWordPress(dir) && await wordPressFile(dir);
1716
+ if (plugin !== false && !tagged.some(({ file }) => file === plugin))
1717
+ log(
1718
+ "On WordPress, take the Agentface tag and its notice out of the plugin's boxes for the head and the body, where init said to paste them, and save: in WPCode, that's Code Snippets > Header & Footer."
1719
+ );
765
1720
  if (!tagged.length) {
766
1721
  log("No Agentface tag in this project.");
767
1722
  return { files: [], deleted: [], byHand: [] };
@@ -776,9 +1731,14 @@ async function uninstall({
776
1731
  else edits.push([file, content]);
777
1732
  }
778
1733
  const files2 = edits.map(([file]) => file);
1734
+ const module = await prestaShopFile(dir);
779
1735
  if (!dryRun) {
780
- for (const [file, content] of edits) await writeFile(path2.join(dir, file), content);
781
- for (const file of deleted) await rm(path2.join(dir, file));
1736
+ for (const [file, content] of edits) await writeFile2(path3.join(dir, file), content);
1737
+ for (const file of deleted) {
1738
+ await rm2(path3.join(dir, file));
1739
+ if (file === module) await rmdir(path3.dirname(path3.join(dir, file))).catch(() => {
1740
+ });
1741
+ }
782
1742
  }
783
1743
  const would = (done, undone) => dryRun ? undone : done;
784
1744
  if (files2.length) log(`${would("Removed", "Would remove")} the Agentface tag from ${list(files2)}.`);
@@ -807,13 +1767,27 @@ var HELP = `Usage:
807
1767
  time, that confirms the site is yours.
808
1768
  agentface uninstall Remove the Agentface tag from this folder's pages.
809
1769
 
1770
+ agentface login Connect this machine to your agentface account, in your
1771
+ browser. logout ends the connection.
1772
+ agentface mcp tools List what you can do on agentface from here: your websites,
1773
+ their numbers and sessions, starting a run.
1774
+ agentface mcp call <name> [key=value \u2026]
1775
+ Do one of them, and print what it returned.
1776
+
810
1777
  Options:
811
1778
  --url The site's address, like https://example.com (init finds it when it can)
812
1779
  --site check: the site key (check finds it in the project when it can)
813
1780
  --pr init: commit the change on a new branch and open a pull request (needs git and gh)
814
1781
  --dry-run Show what would change, without registering or writing anything
815
- --service Agentface service URL (default ${DEFAULT_SERVICE})`;
816
- async function main(argv, { log = console.log, dir = process.cwd(), fetch: fetcher = fetch } = {}) {
1782
+ --service Agentface service URL (default ${DEFAULT_SERVICE})
1783
+ --server login, logout, mcp: agentface's own address (default ${DEFAULT_SERVER})
1784
+ --json mcp: print the answer as JSON`;
1785
+ async function main(argv, {
1786
+ log = console.log,
1787
+ dir = process.cwd(),
1788
+ fetch: fetcher = fetch,
1789
+ connect = {}
1790
+ } = {}) {
817
1791
  const { values, positionals } = parseArgs({
818
1792
  args: argv,
819
1793
  allowPositionals: true,
@@ -823,6 +1797,8 @@ async function main(argv, { log = console.log, dir = process.cwd(), fetch: fetch
823
1797
  pr: { type: "boolean" },
824
1798
  "dry-run": { type: "boolean" },
825
1799
  service: { type: "string" },
1800
+ server: { type: "string" },
1801
+ json: { type: "boolean" },
826
1802
  help: { type: "boolean", short: "h" }
827
1803
  }
828
1804
  });
@@ -832,6 +1808,21 @@ async function main(argv, { log = console.log, dir = process.cwd(), fetch: fetch
832
1808
  log(HELP);
833
1809
  return 0;
834
1810
  }
1811
+ const account = {
1812
+ ...connect,
1813
+ server: values.server ?? process.env.AGENTFACE_SERVER ?? DEFAULT_SERVER,
1814
+ fetch: fetcher,
1815
+ log
1816
+ };
1817
+ if (command === "login") {
1818
+ await login(account);
1819
+ return 0;
1820
+ }
1821
+ if (command === "logout") {
1822
+ await logout(account);
1823
+ return 0;
1824
+ }
1825
+ if (command === "mcp") return mcp(positionals.slice(1), { ...account, json: values.json });
835
1826
  if (command === "init") {
836
1827
  await init({
837
1828
  site: arg,