agentface 0.5.1 → 0.6.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 +609 -54
  2. package/package.json +6 -1
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // cli/agentface.mjs
3
+ // cli/agentface.mts
4
4
  import { parseArgs } from "node:util";
5
5
 
6
- // cli/init.mjs
6
+ // cli/init.mts
7
7
  import { execFile as execFile2 } from "node:child_process";
8
- import { mkdir, readFile as readFile2, rm, writeFile } from "node:fs/promises";
8
+ import { mkdir, readFile as readFile2, rm, rmdir, writeFile } from "node:fs/promises";
9
9
  import path2 from "node:path";
10
10
 
11
- // worker/origin.js
11
+ // worker/origin.ts
12
12
  var PRIVATE_NAMES = /(?:^|\.)(?:localhost|local|internal|lan|intranet|corp|home|arpa)$/;
13
13
  function registrableOrigin(input) {
14
14
  const text = String(input ?? "").trim();
@@ -31,7 +31,7 @@ function registrableOrigin(input) {
31
31
  return origin;
32
32
  }
33
33
 
34
- // worker/tag.js
34
+ // worker/tag.ts
35
35
  var toolListUrl = (serviceOrigin, id) => `${serviceOrigin}/s/${id}.md`;
36
36
  function siteTag(serviceOrigin, id) {
37
37
  return `<script defer src="${serviceOrigin}/s/${id}.js" data-api="This site has an API in its pages. What each function returns: ${toolListUrl(serviceOrigin, id)}"></script>`;
@@ -40,10 +40,78 @@ function siteNotice(serviceOrigin, id) {
40
40
  return `<noscript>This site has an API that runs in its pages, in a browser. What each function returns: ${toolListUrl(serviceOrigin, id)}</noscript>`;
41
41
  }
42
42
 
43
- // cli/heads.mjs
43
+ // cli/heads.mts
44
44
  import { execFile } from "node:child_process";
45
45
  import { readdir, readFile, stat } from "node:fs/promises";
46
46
  import path from "node:path";
47
+
48
+ // worker/head.ts
49
+ var ATTRIBUTES = String.raw`(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^>"'{/]|\/(?!>))*`;
50
+ var HEAD_END = new RegExp(
51
+ String.raw`<!--[\s\S]*?(?:-->|$)|<(script|style|template|textarea|title|noscript)\b${ATTRIBUTES}(?:\/>|>[\s\S]*?(?:<\/\1\s*>|$))|<\/head\s*>|<body[\s/>]`,
52
+ "gi"
53
+ );
54
+ function headEnd(html) {
55
+ HEAD_END.lastIndex = 0;
56
+ for (let m; m = HEAD_END.exec(html); ) if (!m[1] && !m[0].startsWith("<!--")) return m.index;
57
+ return -1;
58
+ }
59
+
60
+ // cli/zip.mts
61
+ import { deflateRawSync } from "node:zlib";
62
+ var CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
63
+ let c = n;
64
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
65
+ return c >>> 0;
66
+ });
67
+ function crc32(data) {
68
+ let c = 4294967295;
69
+ for (const byte of data) c = CRC_TABLE[(c ^ byte) & 255] ^ c >>> 8;
70
+ return (c ^ 4294967295) >>> 0;
71
+ }
72
+ function zip(files2, date = /* @__PURE__ */ new Date()) {
73
+ const time = date.getHours() << 11 | date.getMinutes() << 5 | date.getSeconds() >> 1;
74
+ const day = date.getFullYear() - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate();
75
+ const parts = [];
76
+ const directory = [];
77
+ let offset = 0;
78
+ for (const [name, text] of Object.entries(files2)) {
79
+ const data = Buffer.from(text);
80
+ const packed = deflateRawSync(data);
81
+ const path3 = Buffer.from(name);
82
+ const shared = Buffer.alloc(26);
83
+ shared.writeUInt16LE(20, 0);
84
+ shared.writeUInt16LE(2048, 2);
85
+ shared.writeUInt16LE(8, 4);
86
+ shared.writeUInt16LE(time, 6);
87
+ shared.writeUInt16LE(day, 8);
88
+ shared.writeUInt32LE(crc32(data), 10);
89
+ shared.writeUInt32LE(packed.length, 14);
90
+ shared.writeUInt32LE(data.length, 18);
91
+ shared.writeUInt16LE(path3.length, 22);
92
+ const local = Buffer.alloc(4);
93
+ local.writeUInt32LE(67324752);
94
+ parts.push(local, shared, path3, packed);
95
+ const entry = Buffer.alloc(46);
96
+ entry.writeUInt32LE(33639248, 0);
97
+ entry.writeUInt16LE(788, 4);
98
+ shared.copy(entry, 6);
99
+ entry.writeUInt32LE(33188 * 65536, 38);
100
+ entry.writeUInt32LE(offset, 42);
101
+ directory.push(entry, path3);
102
+ offset += 4 + shared.length + path3.length + packed.length;
103
+ }
104
+ const size = directory.reduce((total, part) => total + part.length, 0);
105
+ const end = Buffer.alloc(22);
106
+ end.writeUInt32LE(101010256, 0);
107
+ end.writeUInt16LE(Object.keys(files2).length, 8);
108
+ end.writeUInt16LE(Object.keys(files2).length, 10);
109
+ end.writeUInt32LE(size, 12);
110
+ end.writeUInt32LE(offset, 16);
111
+ return Buffer.concat([...parts, ...directory, end]);
112
+ }
113
+
114
+ // cli/heads.mts
47
115
  var EXTENSIONS = [
48
116
  "html",
49
117
  "htm",
@@ -60,6 +128,7 @@ var EXTENSIONS = [
60
128
  "jinja2",
61
129
  "j2",
62
130
  "tmpl",
131
+ "tpl",
63
132
  "astro"
64
133
  ];
65
134
  var MARKUP = new RegExp(`\\.(?:${EXTENSIONS.join("|")})$`, "i");
@@ -121,8 +190,70 @@ var exists = (file) => stat(file).then(
121
190
  () => true,
122
191
  () => false
123
192
  );
193
+ var THEME = /^(?:[ \t]*<\?php)?[ \t/*#@]*Theme Name\s*:/im;
194
+ async function isWordPress(dir) {
195
+ if (THEME.test((await read(path.join(dir, "style.css")) ?? "").slice(0, 8192))) return true;
196
+ for (const name of ["wp-content", "wp-includes"]) if (await exists(path.join(dir, name))) return true;
197
+ for (let at = path.resolve(dir); ; at = path.dirname(at)) {
198
+ if (path.basename(at) === "wp-content" || await exists(path.join(at, "wp-config.php"))) return true;
199
+ if (path.dirname(at) === at) return false;
200
+ }
201
+ }
202
+ async function contentFolder(dir) {
203
+ const here = path.resolve(dir);
204
+ for (let at = here; ; at = path.dirname(at)) {
205
+ if (path.basename(at) === "wp-content") return at;
206
+ const content = path.join(at, "wp-content");
207
+ if ((at === here || await exists(path.join(at, "wp-config.php"))) && await exists(content))
208
+ return content;
209
+ if (path.dirname(at) === at) return null;
210
+ }
211
+ }
212
+ async function wordPressFile(dir) {
213
+ const content = await contentFolder(dir);
214
+ return content && path.relative(dir, path.join(content, "mu-plugins", "agentface.php")).split(path.sep).join("/");
215
+ }
216
+ var wordPressPage = (html) => /\/wp-(?:content|includes)\/|["']https:\/\/api\.w\.org\/["']|<meta\b[^>]*\bcontent=["']WordPress\b/i.test(
217
+ html
218
+ );
219
+ var WORDPRESS_STEPS = (tag, notice) => [
220
+ 'In the WordPress admin, open Plugins > Add New Plugin, search for WPCode, then install and activate "WPCode \u2013 Insert Headers and Footers".',
221
+ "Open Code Snippets > Header & Footer.",
222
+ `Paste this line in the Header box:
223
+
224
+ ${tag}`,
225
+ ...notice ? [`Paste this line in the Body box:
226
+
227
+ ${notice}`] : [],
228
+ "Click Save Changes. If the site has a caching plugin, clear its cache, so the homepage shows the change."
229
+ ].map((step, i) => ` ${i + 1}. ${step}`).join("\n\n") + "\n";
230
+ var wordPressManual = (lead) => ({
231
+ 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.`,
232
+ how: "Or add it with a plugin that has boxes for the site's head and body, such as the free WPCode",
233
+ steps: WORDPRESS_STEPS
234
+ });
235
+ var SHOP = /\b_PS_[A-Z_]+_\b/;
236
+ var PRESTASHOP_MODULE_FILE = "agentface/agentface.php";
237
+ async function shopFolder(dir) {
238
+ for (let at = path.resolve(dir); ; at = path.dirname(at)) {
239
+ if (SHOP.test(await read(path.join(at, "config", "defines.inc.php")) ?? "")) return at;
240
+ if (path.dirname(at) === at) return null;
241
+ }
242
+ }
243
+ async function prestaShopFile(dir) {
244
+ const shop = await shopFolder(dir);
245
+ return shop && path.relative(dir, path.join(shop, "modules", PRESTASHOP_MODULE_FILE)).split(path.sep).join("/");
246
+ }
247
+ async function prestaShopTheme(dir) {
248
+ return /^name\s*:/m.test(await read(path.join(dir, "config", "theme.yml")) ?? "") && await exists(path.join(dir, "templates"));
249
+ }
250
+ var prestaShopPage = (html) => /\bvar\s+prestashop\s*=/.test(html);
124
251
  var KEY = /\/s\/(site-[a-z0-9-]+)\.js(?=[?#"'`\s]|$)/;
125
- var TAG = new RegExp(`<script\\b[^>]*?${KEY.source}[^>]*?(?:\\/>|>\\s*<\\/script\\s*>)`, "gi");
252
+ var ATTRIBUTES2 = String.raw`(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|[^>])*?`;
253
+ var TAG = new RegExp(
254
+ `<script\\b${ATTRIBUTES2}${KEY.source}${ATTRIBUTES2}(?:\\/>|>\\s*<\\/script\\s*>)`,
255
+ "gi"
256
+ );
126
257
  var NOTICE = /<noscript\b[^>]*>[^<]*\/s\/(site-[a-z0-9-]+)\.md[^<]*<\/noscript\s*>/i;
127
258
  var BODY = /<body(?=[\s>/])(?:<\?[\s\S]*?\?>|<%[\s\S]*?%>|\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^>])*>/i;
128
259
  var onItsLine = (pattern) => new RegExp(`(\\r?\\n[ \\t]*)?${pattern.source}`, "gi");
@@ -137,16 +268,19 @@ function indentUnit(source) {
137
268
  return source.match(/^(\t| {2,4})\S/m)?.[1] ?? " ";
138
269
  }
139
270
  var indentOf = (line) => line.match(/^[ \t]*/)[0];
271
+ var NONCE = /\snonce\s*=\s*(\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^\s>]+)/i;
140
272
  function addTag(source, tag) {
141
273
  let first = true;
142
274
  const replaced = source.replace(onItsLine(TAG), (match, line) => {
143
275
  if (!first) return "";
144
276
  first = false;
145
- return (line ?? "") + tag;
277
+ const nonce = match.match(NONCE)?.[1];
278
+ return (line ?? "") + (nonce ? tag.replace(/^<script\b/, () => `<script nonce=${nonce}`) : tag);
146
279
  });
147
280
  if (!first) return replaced;
148
281
  const eol = source.includes("\r\n") ? "\r\n" : "\n";
149
- const close = source.search(/<\/head\s*>/i);
282
+ const at = headEnd(source);
283
+ const close = at !== -1 && /^<\/head\s*>/i.test(source.slice(at)) ? at : -1;
150
284
  if (close !== -1) {
151
285
  const lineStart = source.lastIndexOf("\n", close - 1) + 1;
152
286
  const before = source.slice(lineStart, close);
@@ -261,6 +395,61 @@ ${text ? ` setPreBodyComponents([React.createElement('noscript', { key: 'agentf
261
395
  ` : ""}};
262
396
  `;
263
397
  };
398
+ var MU_PLUGIN = (tag, notice) => `<?php
399
+ /**
400
+ * Plugin Name: Agentface
401
+ * Description: Puts the Agentface tag in every page's head${notice ? ", and its notice first in the body" : ""}.
402
+ */
403
+ // ${OURS}. WordPress runs it on every page, and \`npx agentface uninstall\` deletes it.
404
+
405
+ add_action('wp_head', function () {
406
+ echo '${tag}' . "\\n";
407
+ }, PHP_INT_MAX);
408
+ ${notice ? `
409
+ add_action('wp_body_open', function () {
410
+ echo '${notice}' . "\\n";
411
+ }, PHP_INT_MIN);
412
+ ` : ""}`;
413
+ var PRESTASHOP_MODULE = (tag, notice) => `<?php
414
+ // ${OURS}. PrestaShop runs it on every page once it's installed in Modules > Module Manager, and \`npx agentface uninstall\` deletes it.
415
+ if (!defined('_PS_VERSION_')) {
416
+ exit;
417
+ }
418
+
419
+ class Agentface extends Module
420
+ {
421
+ public function __construct()
422
+ {
423
+ $this->name = 'agentface';
424
+ $this->tab = 'front_office_features';
425
+ $this->version = '1.0.0';
426
+ $this->author = 'Agentface';
427
+ $this->need_instance = 0;
428
+ $this->ps_versions_compliancy = ['min' => '1.7.0.0', 'max' => _PS_VERSION_];
429
+ parent::__construct();
430
+ $this->displayName = 'Agentface';
431
+ $this->description = "Puts the Agentface tag in every page's head${notice ? ", and its notice first in the body" : ""}.";
432
+ }
433
+
434
+ public function install()
435
+ {
436
+ return parent::install()
437
+ && $this->registerHook('displayHeader')${notice ? `
438
+ && $this->registerHook('displayAfterBodyOpeningTag')` : ""};
439
+ }
440
+
441
+ public function hookDisplayHeader()
442
+ {
443
+ return '${tag}' . "\\n";
444
+ }
445
+ ${notice ? `
446
+ public function hookDisplayAfterBodyOpeningTag()
447
+ {
448
+ return '${notice}' . "\\n";
449
+ }
450
+ ` : ""}}
451
+ `;
452
+ var prestaShopZip = (tag, notice) => zip({ [PRESTASHOP_MODULE_FILE]: PRESTASHOP_MODULE(tag, notice) });
264
453
  async function project(dir) {
265
454
  const pkg = JSON.parse(await read(path.join(dir, "package.json")) ?? "null");
266
455
  const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
@@ -268,12 +457,14 @@ async function project(dir) {
268
457
  const skip = new Set(SKIP);
269
458
  if (generator === "Hugo") for (const name of ["public", "resources", "themes"]) skip.add(name);
270
459
  if (deps.gatsby) skip.add("public");
271
- const framework = FRAMEWORKS.find(([dependency]) => deps[dependency])?.[1] ?? generator ?? (pkg ? "JavaScript" : "HTML");
460
+ const framework = (await prestaShopTheme(dir) ? "PrestaShop theme" : null) ?? FRAMEWORKS.find(([dependency]) => deps[dependency])?.[1] ?? generator ?? (pkg ? "JavaScript" : "HTML");
272
461
  const { files: list2, git } = await files(dir, skip);
273
462
  return { deps, framework, list: list2, git };
274
463
  }
275
464
  async function findTags(dir) {
276
465
  const { list: list2 } = await project(dir);
466
+ const plugin = await isWordPress(dir) && await wordPressFile(dir) || await prestaShopFile(dir);
467
+ if (plugin && !list2.includes(plugin)) list2.push(plugin);
277
468
  const tagged = [];
278
469
  for (const file of list2) {
279
470
  const source = await contents(dir, file);
@@ -290,6 +481,8 @@ function madeByInit(source) {
290
481
  const text = gatsby(/createElement\('noscript', \{ key: 'agentface' \}, '([^']*)'\)/);
291
482
  const made = [
292
483
  [NEXT_DOCUMENT, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
484
+ [MU_PLUGIN, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
485
+ [PRESTASHOP_MODULE, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
293
486
  [
294
487
  GATSBY_SSR,
295
488
  load && src && `<script ${load} src="${src}"${about ? ` ${attribute}="${about}"` : ""}></script>`,
@@ -308,7 +501,7 @@ function removeTag(source) {
308
501
  source
309
502
  );
310
503
  }
311
- async function byHand(dir, list2, framework, reason, how) {
504
+ async function byHand(dir, list2, framework, manual) {
312
505
  const tagged = [];
313
506
  const noticed = [];
314
507
  for (const file of list2) {
@@ -322,23 +515,52 @@ async function byHand(dir, list2, framework, reason, how) {
322
515
  heads: [],
323
516
  bodies: [],
324
517
  creates: [],
325
- manual: { reason, how },
518
+ manual,
326
519
  tagged,
327
520
  noticed,
328
521
  key: tagged[0]?.key ?? null
329
522
  };
330
523
  }
331
524
  async function findHeads(dir) {
525
+ if (await isWordPress(dir)) {
526
+ const file = await wordPressFile(dir);
527
+ if (file) {
528
+ const source = await read(path.join(dir, file));
529
+ return {
530
+ framework: "WordPress",
531
+ heads: [],
532
+ bodies: [],
533
+ creates: [{ file, content: MU_PLUGIN, source }],
534
+ key: source === null ? null : tagKey(source)
535
+ };
536
+ }
537
+ return byHand(
538
+ dir,
539
+ (await project(dir)).list,
540
+ "WordPress",
541
+ wordPressManual(
542
+ "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."
543
+ )
544
+ );
545
+ }
546
+ const moduleFile = await prestaShopFile(dir);
547
+ if (moduleFile) {
548
+ const source = await read(path.join(dir, moduleFile));
549
+ return {
550
+ framework: "PrestaShop",
551
+ heads: [],
552
+ bodies: [],
553
+ creates: [{ file: moduleFile, content: PRESTASHOP_MODULE, source }],
554
+ key: source === null ? null : tagKey(source)
555
+ };
556
+ }
332
557
  const { deps, framework, list: list2, git } = await project(dir);
333
558
  for (const [dependency, [name, where]] of Object.entries(CONFIG_HEAD))
334
559
  if (deps[dependency])
335
- return byHand(
336
- dir,
337
- list2,
338
- name,
339
- `${name} sets the page head in its config, which init can't edit yet.`,
340
- `Add it by hand through ${where}, with this tag's src`
341
- );
560
+ return byHand(dir, list2, name, {
561
+ reason: `${name} sets the page head in its config, which init can't edit yet.`,
562
+ how: `Add it by hand through ${where}, with this tag's src`
563
+ });
342
564
  const heads = [];
343
565
  const bodies = [];
344
566
  for (const file of list2) {
@@ -365,28 +587,235 @@ async function findHeads(dir) {
365
587
  for (const file of own) if (await exists(path.join(dir, file))) present.push(file);
366
588
  const text = present.length === 1 ? await read(path.join(dir, present[0])) : null;
367
589
  if (present.length && !(present[0] === "gatsby-ssr.js" && text?.includes(OURS)))
368
- return byHand(
369
- dir,
370
- list2,
371
- framework,
372
- `This Gatsby site has its own ${present[0]}, which init can't edit yet.`,
373
- "Add it by hand through setHeadComponents in onRenderBody, with this tag's src"
374
- );
590
+ return byHand(dir, list2, framework, {
591
+ reason: `This Gatsby site has its own ${present[0]}, which init can't edit yet.`,
592
+ how: "Add it by hand through setHeadComponents in onRenderBody, with this tag's src"
593
+ });
375
594
  creates.push({ file: "gatsby-ssr.js", content: GATSBY_SSR, source: text });
376
595
  }
377
596
  if (!heads.length && !creates.length)
378
- return byHand(
379
- dir,
380
- list2,
381
- framework,
382
- `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.`,
383
- "Add this line by hand, last in the <head> of the layout or template every page uses"
384
- );
597
+ return byHand(dir, list2, framework, {
598
+ 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.`,
599
+ how: "Add this line by hand, last in the <head> of the layout or template every page uses",
600
+ none: true
601
+ });
385
602
  const sources = [...heads.map(({ source }) => source), ...creates.map(({ source }) => source ?? "")];
386
603
  return { framework, heads, bodies, creates, key: sources.map(tagKey).find(Boolean) ?? null };
387
604
  }
388
605
 
389
- // cli/init.mjs
606
+ // worker/html.ts
607
+ var ATTRIBUTE = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
608
+ function attributesOf(text) {
609
+ const values = {};
610
+ for (const [, name, ...value] of text.matchAll(ATTRIBUTE))
611
+ values[name.toLowerCase()] ??= decodeEntities(value.find((v) => v !== void 0) ?? "");
612
+ return values;
613
+ }
614
+ function decodeEntities(s) {
615
+ return s.replace(/&(#x?[0-9a-f]+|amp|lt|gt|quot|apos|nbsp);/gi, (m, e) => {
616
+ const named = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " }[e.toLowerCase()];
617
+ if (named) return named;
618
+ const code = e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
619
+ return code >= 0 && code <= 1114111 ? String.fromCodePoint(code) : m;
620
+ });
621
+ }
622
+
623
+ // worker/http.ts
624
+ var USER_AGENT = "AgentfaceFetcher/0.1 (+https://agentface.com)";
625
+ async function readStart(response, limit) {
626
+ if (!response.body) return "";
627
+ const reader = response.body.getReader();
628
+ const chunks = [];
629
+ let length = 0;
630
+ while (length < limit) {
631
+ const { done, value } = await reader.read();
632
+ if (done) break;
633
+ chunks.push(value);
634
+ length += value.byteLength;
635
+ }
636
+ await reader.cancel().catch(() => {
637
+ });
638
+ return new TextDecoder().decode(concat(chunks, length).subarray(0, limit));
639
+ }
640
+ function concat(chunks, length) {
641
+ const bytes = new Uint8Array(length);
642
+ let offset = 0;
643
+ for (const chunk of chunks) {
644
+ bytes.set(chunk, offset);
645
+ offset += chunk.byteLength;
646
+ }
647
+ return bytes;
648
+ }
649
+
650
+ // cli/policy.mts
651
+ function parsePolicy(text, where) {
652
+ const directives = /* @__PURE__ */ new Map();
653
+ for (const part of text.split(";")) {
654
+ const [name, ...sources] = part.trim().split(/[\t\n\f\r ]+/);
655
+ if (name && !directives.has(name.toLowerCase())) directives.set(name.toLowerCase(), sources);
656
+ }
657
+ return { where, directives };
658
+ }
659
+ var NOT_MARKUP = /<!--[\s\S]*?(?:-->|$)|<(script|style|noscript|template|textarea|title)\b[^>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi;
660
+ var META = /<meta\b((?:"[^"]*"|'[^']*'|[^>"'])*)>/gi;
661
+ function pagePolicies(header, html) {
662
+ const policies = (header ?? "").split(",").filter((text) => text.trim()).map((text) => parsePolicy(text, "header"));
663
+ const end = headEnd(html);
664
+ const head = (end === -1 ? html : html.slice(0, end)).replace(NOT_MARKUP, "");
665
+ for (const [, text] of head.matchAll(META)) {
666
+ const attributes = attributesOf(text);
667
+ if (attributes["http-equiv"]?.trim().toLowerCase() === "content-security-policy" && attributes.content)
668
+ policies.push(parsePolicy(attributes.content, "meta"));
669
+ }
670
+ return policies.filter((policy) => policy.directives.size);
671
+ }
672
+ var scheme = (url) => url.protocol.slice(0, -1);
673
+ var DEFAULT_PORT = { http: "80", https: "443", ws: "80", wss: "443" };
674
+ var schemeMatches = (a, b) => a === b || a === "http" && b === "https" || a === "ws" && ["wss", "http", "https"].includes(b) || a === "wss" && b === "https";
675
+ var decode = (segment) => {
676
+ try {
677
+ return decodeURIComponent(segment);
678
+ } catch {
679
+ return segment;
680
+ }
681
+ };
682
+ function pathMatches(a, b) {
683
+ if (!a || a === "/" && !b) return true;
684
+ const exact = !a.endsWith("/");
685
+ const listA = a.split("/");
686
+ const listB = b.split("/");
687
+ if (listA.length > listB.length || exact && listA.length !== listB.length) return false;
688
+ if (!exact) listA.pop();
689
+ return listA.every((segment, i) => decode(segment) === decode(listB[i]));
690
+ }
691
+ var HOST_SOURCE = /^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::(\d+|\*))?(\/[^?#]*)?$/i;
692
+ function sourceMatches(source, url, page) {
693
+ const lower = source.toLowerCase();
694
+ if (lower === "*") return ["http", "https", "ws", "wss", scheme(page)].includes(scheme(url));
695
+ if (lower === "'self'")
696
+ return url.hostname === page.hostname && (url.origin === page.origin || scheme(page) === "http" && scheme(url) === "https" && !url.port);
697
+ if (/^[a-z][a-z0-9+.-]*:$/.test(lower)) return schemeMatches(lower.slice(0, -1), scheme(url));
698
+ const [, sourceScheme, host, port, path3] = source.match(HOST_SOURCE) ?? [];
699
+ if (!host) return false;
700
+ if (!schemeMatches(sourceScheme?.toLowerCase() ?? scheme(page), scheme(url))) return false;
701
+ const name = host.toLowerCase();
702
+ if (name.startsWith("*.") ? !url.hostname.endsWith(name.slice(1)) : name !== "*" && name !== url.hostname)
703
+ return false;
704
+ if (port === void 0 ? url.port !== "" : port !== "*" && port !== (url.port || DEFAULT_PORT[scheme(url)]))
705
+ return false;
706
+ return pathMatches(path3 ?? "", url.pathname);
707
+ }
708
+ var keyword = (sources, word) => sources.some((source) => source.toLowerCase() === word);
709
+ var hasNonce = (sources, nonce) => sources.some((source) => /^'nonce-/i.test(source) && source.slice(7, -1) === nonce && source.endsWith("'"));
710
+ var governing = (policy, names) => names.find((name) => policy.directives.has(name));
711
+ function fix(policy, decides, name, origin) {
712
+ const sources = policy.directives.get(decides).filter((source) => source.toLowerCase() !== "'none'");
713
+ return { name, line: [name, ...sources, origin].join(" "), created: decides !== name };
714
+ }
715
+ function blockedBy(policies, load) {
716
+ const page = new URL(load.page);
717
+ const script = new URL(load.script);
718
+ const events = new URL(load.events);
719
+ const blocked = [];
720
+ for (const policy of policies) {
721
+ const result = { where: policy.where, script: false, connect: false, nonce: null, fixes: [] };
722
+ const scripts = governing(policy, ["script-src-elem", "script-src", "default-src"]);
723
+ if (scripts) {
724
+ const sources = policy.directives.get(scripts);
725
+ const dynamic = keyword(sources, "'strict-dynamic'");
726
+ const allowed = load.nonce && hasNonce(sources, load.nonce) || (dynamic ? load.added : sources.some((source) => sourceMatches(source, script, page)));
727
+ if (!allowed) {
728
+ result.script = true;
729
+ if (dynamic) result.nonce = { directive: scripts, named: sources.some((s) => /^'nonce-/i.test(s)) };
730
+ else
731
+ result.fixes.push(
732
+ fix(policy, scripts, scripts === "default-src" ? "script-src" : scripts, script.origin)
733
+ );
734
+ }
735
+ }
736
+ const connects = governing(policy, ["connect-src", "default-src"]);
737
+ if (connects && !policy.directives.get(connects).some((source) => sourceMatches(source, events, page))) {
738
+ result.connect = true;
739
+ result.fixes.push(fix(policy, connects, "connect-src", events.origin));
740
+ }
741
+ if (result.script || result.connect) blocked.push(result);
742
+ }
743
+ return blocked;
744
+ }
745
+ var WHERE = {
746
+ header: "In the Content-Security-Policy header the site sends with its pages",
747
+ meta: "In the Content-Security-Policy <meta> tag in the head of its pages"
748
+ };
749
+ var and = (names) => names.join(" and ");
750
+ var or = (names) => names.join(" or ");
751
+ function advice(blocked, host) {
752
+ const script = blocked.some((b) => b.script);
753
+ const connect = blocked.some((b) => b.connect);
754
+ const effect = script && connect ? "load the Agentface script or send its events" : script ? "load the Agentface script" : "send the Agentface script's events";
755
+ const paragraphs = blocked.map(({ where, nonce, fixes }) => {
756
+ 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.`;
757
+ const existing = fixes.filter((f) => !f.created).map(({ name }) => name);
758
+ const created = fixes.filter((f) => f.created).map(({ name }) => name);
759
+ const what = [
760
+ existing.length && `${host} at the end of ${and(existing)}, after the hosts ${existing.length === 1 ? "it already lists" : "they already list"}`,
761
+ created.length && `${created.length === 1 ? "a " : ""}${and(created)} ${created.length === 1 ? "line" : "lines"} with ${existing.length ? "it" : host}`
762
+ ].filter(Boolean);
763
+ if (fixes.length)
764
+ text += `${nonce ? " Also" : `${WHERE[where]},`} add ${what.join(", and ")}, so ${fixes.length === 1 ? "it reads" : "they read"}:
765
+
766
+ ` + fixes.map(({ line }) => ` ${line}`).join("\n");
767
+ if (created.length)
768
+ text += `
769
+
770
+ 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.`;
771
+ return text;
772
+ });
773
+ return { effect, fixes: paragraphs.join("\n\n") + "\n" };
774
+ }
775
+ async function readHomepage(origin, fetcher) {
776
+ try {
777
+ const response = await fetcher(origin + "/", {
778
+ headers: { accept: "text/html", "user-agent": USER_AGENT },
779
+ redirect: "follow",
780
+ signal: AbortSignal.timeout(1e4)
781
+ });
782
+ if (!response.ok) {
783
+ await response.body?.cancel();
784
+ return { unread: `it answered HTTP ${response.status}` };
785
+ }
786
+ const html = await readStart(response, 2e5);
787
+ const policies = pagePolicies(response.headers.get("content-security-policy"), html);
788
+ return { url: response.url || origin + "/", html, policies };
789
+ } catch (error) {
790
+ const { name, message, cause } = error;
791
+ return {
792
+ unread: name === "TimeoutError" ? "it didn't answer within 10 seconds" : `the request failed (${cause?.message ?? message})`
793
+ };
794
+ }
795
+ }
796
+ var SCRIPT = /<script\b((?:"[^"]*"|'[^']*'|[^>"'])*)>/gi;
797
+ function liveNonce(html, id) {
798
+ for (const [, text] of html.matchAll(SCRIPT)) {
799
+ const attributes = attributesOf(text);
800
+ if ((attributes.src ?? "").split(/[?#]/)[0].endsWith(`/s/${id}.js`)) return attributes.nonce || null;
801
+ }
802
+ return void 0;
803
+ }
804
+ function tagBlocked(homepage, site, { added = false } = {}) {
805
+ const src = site.tag.match(/\bsrc="([^"]+)"/)?.[1];
806
+ if ("unread" in homepage || !homepage.policies.length || !src) return null;
807
+ const nonce = liveNonce(homepage.html, site.id);
808
+ const blocked = blockedBy(homepage.policies, {
809
+ page: homepage.url,
810
+ script: src,
811
+ events: new URL("/e", src).href,
812
+ nonce,
813
+ added: nonce === void 0 && added
814
+ });
815
+ return blocked.length ? advice(blocked, new URL(src).origin) : null;
816
+ }
817
+
818
+ // cli/init.mts
390
819
  var DEFAULT_SERVICE = "https://cdn.agentfacehq.com";
391
820
  var BRANCH = "agentface";
392
821
  var readJson = async (file) => JSON.parse(await readFile2(file, "utf8").catch(() => "null"));
@@ -468,14 +897,26 @@ function run(command, args, { cwd }) {
468
897
  return new Promise((resolve, reject) => {
469
898
  execFile2(command, args, { cwd }, (error, stdout, stderr) => {
470
899
  if (error)
471
- reject(new Error(`${command} ${args.join(" ")} failed: ${(stderr || error.message).trim()}`));
900
+ reject(
901
+ new Error(`${command} ${args.join(" ")} failed: ${(stderr || error.message).trim()}`)
902
+ );
472
903
  else resolve(stdout.trim());
473
904
  });
474
905
  });
475
906
  }
476
907
  var bare = (origin) => origin.replace(/^https:\/\/www\./, "https://");
477
908
  var sameSite = (a, b) => bare(a) === bare(b);
478
- async function siteFor({ id, url, dir, found, service, fetcher, exec, dryRun, log }) {
909
+ async function siteFor({
910
+ id,
911
+ url,
912
+ dir,
913
+ found,
914
+ service,
915
+ fetcher,
916
+ exec,
917
+ dryRun,
918
+ log
919
+ }) {
479
920
  let origin;
480
921
  if (url) {
481
922
  try {
@@ -537,22 +978,34 @@ async function siteFor({ id, url, dir, found, service, fetcher, exec, dryRun, lo
537
978
  }
538
979
  var serviceFlag = (service) => service === DEFAULT_SERVICE ? "" : ` --service ${service}`;
539
980
  var list = (files2) => files2.length <= 3 ? files2.join(", ") : `${files2.slice(0, 3).join(", ")} and ${files2.length - 3} more`;
540
- function nextSteps(site, service) {
541
- const check2 = `npx agentface check${serviceFlag(service)}`;
542
- return site.expiresAt ? `Deploy it as usual, then run \`${check2}\` here: once ${site.origin}'s homepage has the tag, that confirms the site is yours. Agentface also confirms it by itself when the site's first events arrive, but a quiet site may send none in time: until it's confirmed, Agentface deletes ${site.id} at ${when(site.expiresAt)}. If that happens first, run \`npx agentface init\` again.` : `Deploy it as usual. \`${check2}\` shows whether ${site.origin}'s homepage has the tag.`;
981
+ function nextSteps(site, service, own) {
982
+ const saved = own === "plugin";
983
+ const check2 = `npx agentface check${saved ? ` --site ${site.id}` : ""}${serviceFlag(service)}`;
984
+ if (own === "file")
985
+ 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.`;
986
+ if (saved)
987
+ 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.`;
988
+ 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.`;
543
989
  }
544
- function prBody(site, files2, service = DEFAULT_SERVICE) {
990
+ function policyWarning(site, advice2) {
991
+ 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;
992
+ }
993
+ var markdown = (warning) => warning.trim().replaceAll("<meta>", "`<meta>`").replace(/(?:^ {2}\S.*\n?)+/gm, (lines) => "```\n" + lines.replace(/^ {2}/gm, "").trimEnd() + "\n```\n").trimEnd();
994
+ function prBody(site, files2, service = DEFAULT_SERVICE, warning = null) {
545
995
  const src = site.tag.match(/\bsrc="([^"]+)"/)?.[1];
546
996
  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.` : "";
547
997
  return `Adds the Agentface tag to ${site.origin}, so AI agents that use the site in a browser get tools made for them.
548
998
 
549
- **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.
999
+ **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.
1000
+
1001
+ ${warning ? `**Content Security Policy.** ${markdown(warning)}
550
1002
 
551
- **Check it.** ${nextSteps(site, service)}
1003
+ ` : ""}**Check it.** ${nextSteps(site, service)}
552
1004
 
553
1005
  **Uninstall.** Revert this pull request, or delete ${site.notice ? "the two lines" : "the line"}.
554
1006
  `;
555
1007
  }
1008
+ 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.";
556
1009
  function noticeByHand(site, noticed, log) {
557
1010
  if (site.notice && !noticed.includes(site.id))
558
1011
  log(
@@ -562,19 +1015,22 @@ function noticeByHand(site, noticed, log) {
562
1015
  `
563
1016
  );
564
1017
  }
565
- function byHand2({ manual, tagged, noticed }, site, service, dryRun, log) {
1018
+ function byHand2({ manual, tagged, noticed }, site, service, dryRun, warning, log) {
1019
+ if (manual.steps) return withPlugin({ manual, tagged }, site, service, dryRun, warning, log);
566
1020
  const current = tagged.filter(({ key }) => key === site.id).map(({ file }) => file);
567
1021
  if (current.length) {
568
1022
  log(
569
1023
  `${list(current)} already ${current.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`
570
1024
  );
571
1025
  noticeByHand(site, noticed, log);
1026
+ if (warning) log(warning);
572
1027
  log(nextSteps(site, service));
573
1028
  return { site, files: [], written: false };
574
1029
  }
575
1030
  log(manual.reason);
576
1031
  if (dryRun) {
577
1032
  log(`${manual.how}. Without --dry-run, init prints the tag with the site's key.`);
1033
+ if (warning) log(warning);
578
1034
  return { site, files: [], written: false };
579
1035
  }
580
1036
  const old = tagged.map(({ file }) => file);
@@ -584,10 +1040,39 @@ function byHand2({ manual, tagged, noticed }, site, service, dryRun, log) {
584
1040
  ${site.tag}
585
1041
  `
586
1042
  );
1043
+ if (!old.length) log(GTM_HOW);
587
1044
  noticeByHand(site, noticed, log);
1045
+ if (warning) log(warning);
588
1046
  log(nextSteps(site, service));
589
1047
  return { site, files: [], written: false };
590
1048
  }
1049
+ function withPlugin({ manual, tagged }, site, service, dryRun, warning, log) {
1050
+ log(manual.reason);
1051
+ if (dryRun) {
1052
+ log(`${manual.how}. Without --dry-run, init prints the steps, with the tag for the site's key.`);
1053
+ if (warning) log(warning);
1054
+ return { site, files: [], written: false };
1055
+ }
1056
+ log(`${manual.how}:
1057
+
1058
+ ${manual.steps(site.tag, site.notice)}`);
1059
+ const files2 = tagged.map(({ file }) => file);
1060
+ if (files2.length)
1061
+ log(
1062
+ `${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.`
1063
+ );
1064
+ if (warning) log(warning);
1065
+ log(nextSteps(site, service, "plugin"));
1066
+ return { site, files: [], written: false };
1067
+ }
1068
+ function prestaShopSteps(file) {
1069
+ 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.`;
1070
+ const cache = "If the shop has a cache module, clear its cache, so that the pages show the tag.";
1071
+ if (file.endsWith(".zip"))
1072
+ return `${what} In the shop's back office, open Modules > Module Manager, click Upload a module and choose ${file}: PrestaShop installs it. ${cache}`;
1073
+ 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}`;
1074
+ }
1075
+ 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.";
591
1076
  async function readyForPr(dir, exec) {
592
1077
  if (await exec("git", ["status", "--porcelain"], { cwd: dir }))
593
1078
  throw new Error("Commit or stash your changes first: the pull request should contain only Agentface.");
@@ -608,41 +1093,64 @@ async function init({
608
1093
  exec = run,
609
1094
  log = console.log
610
1095
  }) {
611
- const found = await findHeads(dir);
1096
+ let found = await findHeads(dir);
612
1097
  if (found.manual && pr)
613
1098
  throw new Error(
614
1099
  `${found.manual.reason} --pr only commits what init writes: run init without it to get the tag to add by hand.`
615
1100
  );
616
1101
  if (pr && !dryRun) await readyForPr(dir, exec);
617
1102
  const site = await siteFor({ id, url, dir, found, service, fetcher, exec, dryRun, log });
618
- if (found.manual) return byHand2(found, site, service, dryRun, log);
1103
+ const homepage = await readHomepage(site.origin, fetcher);
1104
+ const warning = policyWarning(site, tagBlocked(homepage, site));
1105
+ if (found.manual?.none && "html" in homepage && wordPressPage(homepage.html))
1106
+ found = {
1107
+ ...found,
1108
+ framework: "WordPress",
1109
+ manual: wordPressManual(`${site.origin}'s homepage comes from WordPress.`)
1110
+ };
1111
+ else if (found.manual?.none && "html" in homepage && prestaShopPage(homepage.html))
1112
+ found = {
1113
+ framework: "PrestaShop",
1114
+ heads: [],
1115
+ bodies: [],
1116
+ creates: [{ file: "agentface.zip", content: prestaShopZip }],
1117
+ key: null
1118
+ };
1119
+ if (found.manual) return byHand2(found, site, service, dryRun, warning, log);
619
1120
  const before = /* @__PURE__ */ new Map();
620
1121
  const after = /* @__PURE__ */ new Map();
1122
+ const edited = /* @__PURE__ */ new Map();
621
1123
  for (const { file, source } of found.heads) {
622
1124
  before.set(file, source);
623
- after.set(file, addTag(source, site.tag));
1125
+ edited.set(file, addTag(source, site.tag));
624
1126
  }
625
1127
  if (site.notice)
626
1128
  for (const { file, source } of found.bodies) {
627
1129
  before.set(file, source);
628
- after.set(file, addNotice(after.get(file) ?? source, site.notice) ?? after.get(file) ?? source);
1130
+ edited.set(file, addNotice(edited.get(file) ?? source, site.notice) ?? edited.get(file) ?? source);
629
1131
  }
1132
+ for (const [file, content] of edited) after.set(file, content);
630
1133
  for (const { file, content, source } of found.creates) {
631
1134
  before.set(file, source);
632
1135
  after.set(file, content(site.tag, site.notice));
633
1136
  }
634
1137
  const writes = [...after].filter(([file, content]) => content !== before.get(file));
635
1138
  const files2 = writes.map(([file]) => file);
1139
+ const own = found.creates.some(({ file }) => file.endsWith(".zip")) ? "plugin" : found.framework === "WordPress" || found.framework === "PrestaShop" ? "file" : void 0;
1140
+ const shop = found.framework === "PrestaShop" ? prestaShopSteps(found.creates[0].file) : null;
636
1141
  const noticed = site.notice && (found.bodies.length || found.creates.length);
637
1142
  const what = `the Agentface tag${noticed ? " and its notice" : ""}`;
638
1143
  if (!writes.length) {
639
1144
  const tagged = [...found.heads, ...found.creates].map(({ file }) => file);
640
1145
  log(`${list(tagged)} already ${tagged.length === 1 ? "has" : "have"} the Agentface tag for ${site.id}.`);
641
- log(nextSteps(site, service));
1146
+ if (shop) log(shop);
1147
+ if (warning) log(warning);
1148
+ log(nextSteps(site, service, own));
642
1149
  return { site, files: files2, written: false };
643
1150
  }
644
1151
  if (dryRun) {
645
1152
  log(`Would add ${what} to ${list(files2)} (${found.framework}) for ${site.origin}.`);
1153
+ if (warning) log(warning);
646
1154
  return { site, files: files2, written: false };
647
1155
  }
648
1156
  let returnTo;
@@ -655,8 +1163,15 @@ async function init({
655
1163
  await writeFile(path2.join(dir, file), content);
656
1164
  }
657
1165
  log(`Added ${what} to ${list(files2)} (${found.framework}) for ${site.origin}.`);
1166
+ if (shop) log(shop);
1167
+ if (found.framework === "PrestaShop theme") log(PRESTASHOP_THEME);
1168
+ if (found.framework === "WordPress")
1169
+ log(
1170
+ `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.`
1171
+ );
1172
+ if (warning) log(warning);
658
1173
  if (!pr) {
659
- log(nextSteps(site, service));
1174
+ log(nextSteps(site, service, own));
660
1175
  return { site, files: files2, written: true };
661
1176
  }
662
1177
  try {
@@ -683,7 +1198,7 @@ async function init({
683
1198
  "--title",
684
1199
  "Add Agentface for AI agents",
685
1200
  "--body",
686
- prBody(site, files2, service)
1201
+ prBody(site, files2, service, warning)
687
1202
  ],
688
1203
  { cwd: dir }
689
1204
  );
@@ -703,13 +1218,36 @@ async function check({
703
1218
  if (!id) {
704
1219
  const found = await findHeads(dir);
705
1220
  id = found.key;
1221
+ if (!id && found.manual?.steps)
1222
+ throw new Error(
1223
+ "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/."
1224
+ );
706
1225
  if (!id)
707
1226
  throw new Error(
708
1227
  'No Agentface tag in this project. Run "npx agentface init" first, or pass the site key with --site.'
709
1228
  );
710
1229
  }
711
1230
  const site = await lookupSite(service, id, fetcher);
712
- const result = await confirm(service, id, fetcher);
1231
+ const [result, homepage] = await Promise.all([
1232
+ confirm(service, id, fetcher),
1233
+ readHomepage(site.origin, fetcher)
1234
+ ]);
1235
+ if (result.ok && "unread" in homepage) {
1236
+ log(
1237
+ `${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.`
1238
+ );
1239
+ return 1;
1240
+ }
1241
+ const advice2 = tagBlocked(homepage, site, { added: result.ok });
1242
+ if (result.ok && advice2) {
1243
+ log(
1244
+ `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}`
1245
+ );
1246
+ log(
1247
+ `${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.`
1248
+ );
1249
+ return 1;
1250
+ }
713
1251
  if (result.ok) {
714
1252
  log(
715
1253
  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}.`
@@ -717,8 +1255,15 @@ async function check({
717
1255
  return 0;
718
1256
  }
719
1257
  log(result.message);
1258
+ const module = await prestaShopFile(dir);
1259
+ if (module && await readFile2(path2.join(dir, module)).catch(() => null))
1260
+ log(
1261
+ `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.`
1262
+ );
720
1263
  if (result.status === 422 && site.expiresAt)
721
1264
  log(`Until it's confirmed, Agentface deletes ${id} at ${when(site.expiresAt)}.`);
1265
+ const warning = policyWarning(site, advice2);
1266
+ if (warning) log(warning);
722
1267
  return 1;
723
1268
  }
724
1269
  async function uninstall({
@@ -729,6 +1274,11 @@ async function uninstall({
729
1274
  log = console.log
730
1275
  }) {
731
1276
  const tagged = await findTags(dir);
1277
+ const plugin = await isWordPress(dir) && await wordPressFile(dir);
1278
+ if (plugin !== false && !tagged.some(({ file }) => file === plugin))
1279
+ log(
1280
+ "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."
1281
+ );
732
1282
  if (!tagged.length) {
733
1283
  log("No Agentface tag in this project.");
734
1284
  return { files: [], deleted: [], byHand: [] };
@@ -743,9 +1293,14 @@ async function uninstall({
743
1293
  else edits.push([file, content]);
744
1294
  }
745
1295
  const files2 = edits.map(([file]) => file);
1296
+ const module = await prestaShopFile(dir);
746
1297
  if (!dryRun) {
747
1298
  for (const [file, content] of edits) await writeFile(path2.join(dir, file), content);
748
- for (const file of deleted) await rm(path2.join(dir, file));
1299
+ for (const file of deleted) {
1300
+ await rm(path2.join(dir, file));
1301
+ if (file === module) await rmdir(path2.dirname(path2.join(dir, file))).catch(() => {
1302
+ });
1303
+ }
749
1304
  }
750
1305
  const would = (done, undone) => dryRun ? undone : done;
751
1306
  if (files2.length) log(`${would("Removed", "Would remove")} the Agentface tag from ${list(files2)}.`);
@@ -766,7 +1321,7 @@ async function uninstall({
766
1321
  return { files: files2, deleted, byHand: byHand3 };
767
1322
  }
768
1323
 
769
- // cli/agentface.mjs
1324
+ // cli/agentface.mts
770
1325
  var HELP = `Usage:
771
1326
  agentface init [<site-key>] Add the Agentface tag to the pages of the site in this
772
1327
  folder. Without a site key, registers the site first.
@@ -823,7 +1378,7 @@ async function main(argv, { log = console.log, dir = process.cwd(), fetch: fetch
823
1378
  ${HELP}`);
824
1379
  }
825
1380
 
826
- // cli/bin.mjs
1381
+ // cli/bin.mts
827
1382
  main(process.argv.slice(2)).then(
828
1383
  (code) => {
829
1384
  process.exitCode = code;
package/package.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
2
  "name": "agentface",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Add the Agentface tag to a website's pages, so AI agents get tools made for it.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/agentfacehq/agentface-app.git",
8
+ "directory": "adapter/cli"
9
+ },
5
10
  "bin": {
6
11
  "agentface": "dist/agentface.mjs"
7
12
  },