agentface 0.9.0 → 0.9.1

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 +527 -34
  2. package/package.json +1 -1
@@ -496,6 +496,29 @@ function headEnd(html) {
496
496
  return -1;
497
497
  }
498
498
 
499
+ // cli/package.json
500
+ var package_default = {
501
+ name: "agentface",
502
+ version: "0.9.1",
503
+ description: "Add the Agentface tag to a website's pages, so AI agents get tools made for it, and use your agentface account from a shell.",
504
+ repository: {
505
+ type: "git",
506
+ url: "git+https://github.com/agentfacehq/agentface-app.git",
507
+ directory: "adapter/cli"
508
+ },
509
+ bin: {
510
+ agentface: "dist/agentface.mjs"
511
+ },
512
+ files: [
513
+ "dist/agentface.mjs"
514
+ ],
515
+ type: "module",
516
+ engines: {
517
+ node: ">=20"
518
+ },
519
+ license: "UNLICENSED"
520
+ };
521
+
499
522
  // cli/zip.mts
500
523
  import { deflateRawSync } from "node:zlib";
501
524
  var CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
@@ -551,6 +574,8 @@ function zip(files2, date = /* @__PURE__ */ new Date()) {
551
574
  }
552
575
 
553
576
  // cli/heads.mts
577
+ var INIT = package_default.version;
578
+ var stamped = (tag) => tag.replace(/><\/script>$/, ` data-init="${INIT}"></script>`);
554
579
  var EXTENSIONS = [
555
580
  "html",
556
581
  "htm",
@@ -724,12 +749,24 @@ var LIST = /\/s\/(site-[a-z0-9-]+)\.md(?![\w-])/;
724
749
  var BODY = /<body(?=[\s>/])(?:<\?[\s\S]*?\?>|<%[\s\S]*?%>|\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|"[^"]*"|'[^']*'|[^>])*>/i;
725
750
  var onItsLine = (pattern) => new RegExp(`(\\r?\\n[ \\t]*)?${pattern.source}`, "gi");
726
751
  var OURS = "Added by `npx agentface init`";
752
+ var about = (comment2, how) => [
753
+ `${OURS}. It asks Agentface for the two lines this`,
754
+ "site's pages carry for AI agents, the tag and its notice, so that a change to",
755
+ "them reaches the site by itself. It keeps them an hour and, while Agentface",
756
+ "can't be reached, uses the copy it has: at first the one below.",
757
+ how,
758
+ "`npx agentface uninstall` deletes it."
759
+ ].join("\n").replace(/^/gm, comment2 + " ").replace(/ +$/gm, "");
727
760
  function tagKey(source) {
728
761
  return source.match(KEY)?.[1] ?? null;
729
762
  }
730
763
  function noticeKey(source) {
731
764
  return source.match(NOTICE)?.[1] ?? null;
732
765
  }
766
+ function siteOf(tag) {
767
+ const [, service = "", site = ""] = tag.match(/\bsrc="(https?:\/\/[^"]+?)\/s\/([^/"]+)\.js"/) ?? [];
768
+ return { service, site };
769
+ }
733
770
  var linesIn = (source) => ({
734
771
  tag: source.match(TAG)?.[0] ?? null,
735
772
  notice: source.match(NOTICE)?.[0] ?? null
@@ -746,7 +783,9 @@ function updatedTag(old, tag) {
746
783
  const now = attributesOf(tag);
747
784
  const was = attributesOf(old);
748
785
  const mine = initsOwn(was, now);
749
- const current2 = mine.length === now.length && now.every(({ name, value }) => {
786
+ const init2 = (list2) => list2.some(({ name }) => name === "data-init");
787
+ const rest = (list2) => list2.filter(({ name }) => name !== "data-init");
788
+ const current2 = rest(mine).length === rest(now).length && (init2(mine) || !init2(now)) && rest(now).every(({ name, value }) => {
750
789
  const same = mine.find((attribute2) => attribute2.name === name);
751
790
  return same && (value === void 0 || said2(same.value) === said2(value));
752
791
  });
@@ -755,7 +794,7 @@ function updatedTag(old, tag) {
755
794
  return kept.length ? tag.replace(/^<script\b/, () => `<script ${kept.join(" ")}`) : tag;
756
795
  }
757
796
  function initsOwn(was, now) {
758
- const names = /* @__PURE__ */ new Set(["src", "async", "defer", ...now.map(({ name }) => name)]);
797
+ const names = /* @__PURE__ */ new Set(["src", "async", "defer", "data-init", ...now.map(({ name }) => name)]);
759
798
  return was.filter(({ name, value }) => name !== null && (names.has(name) || LIST.test(value ?? "")));
760
799
  }
761
800
  function ownersAttributes(old) {
@@ -771,8 +810,8 @@ function updatedNotice(old, notice) {
771
810
  }
772
811
  function tagToReplace(source, tag) {
773
812
  const old = source.match(TAG)?.[0];
774
- const next2 = old && updatedTag(old, tag);
775
- return next2 && next2 !== old ? next2 : null;
813
+ const next2 = old && updatedTag(old, tag.replace(/\sdata-init="[^"]*"/, ""));
814
+ return next2 && next2 !== old ? updatedTag(old, tag) : null;
776
815
  }
777
816
  function staleNotice(source, notice) {
778
817
  const key = noticeKey(notice);
@@ -919,10 +958,12 @@ function withoutLine(source) {
919
958
  }
920
959
  var GATSBY_SSR = (tag, notice) => {
921
960
  const src = tag.match(/\bsrc="([^"]+)"/)[1];
922
- const [, attribute2, about2] = tag.match(/\b(data-[a-z-]+)="([^"]+)"/) ?? [];
961
+ const data = [...tag.matchAll(/\b(data-[a-z-]+)="([^"]+)"/g)].map(
962
+ ([, name, value]) => `, '${name}': '${value}'`
963
+ );
923
964
  const text2 = notice?.match(/>([^<]*)</)[1];
924
965
  const load = tag.match(/^<script (async|defer)\b/)?.[1] ?? "defer";
925
- const props = `key: 'agentface', ${load}: true, src: '${src}'${about2 ? `, '${attribute2}': '${about2}'` : ""}`;
966
+ const props = `key: 'agentface', ${load}: true, src: '${src}'${data.join("")}`;
926
967
  return `// ${OURS}: puts the Agentface tag in every page's <head>.
927
968
  const React = require('react');
928
969
 
@@ -934,7 +975,464 @@ ${text2 ? ` setPreBodyComponents([React.createElement('noscript', { key: 'agent
934
975
  ` : ""}};
935
976
  `;
936
977
  };
937
- var MU_PLUGIN = (tag, notice) => `<?php
978
+ var phpString = (text2) => `'${text2.replace(/[\\']/g, "\\$&")}'`;
979
+ var PHP_LINES = (tag, notice, own2) => {
980
+ const { service, site } = siteOf(tag);
981
+ return String.raw`class AgentfaceLines
982
+ {
983
+ const SERVICE = ${phpString(service)};
984
+ const SITE = ${phpString(site)};
985
+ const TAG = ${phpString(tag)};
986
+ const NOTICE = ${phpString(notice ?? "")};
987
+
988
+ private static $lines = null;
989
+
990
+ // The site's tag and notice. The page being made once the copy is an hour
991
+ // old asks Agentface again, waiting two seconds at most, and pages made
992
+ // meanwhile keep the copy. While Agentface can't be reached, the copy
993
+ // stays, and it's asked for again five minutes later.
994
+ public static function lines()
995
+ {
996
+ if (self::$lines !== null) {
997
+ return self::$lines;
998
+ }
999
+ $kept = self::kept();
1000
+ if (!is_array($kept) || !isset($kept['tag'], $kept['notice'], $kept['due']) || !self::valid($kept['tag'], $kept['notice'])) {
1001
+ $kept = array('tag' => self::TAG, 'notice' => self::NOTICE, 'due' => 0);
1002
+ }
1003
+ if (time() >= $kept['due']) {
1004
+ $kept['due'] = time() + 30;
1005
+ self::keep($kept);
1006
+ $wait = 300;
1007
+ $body = self::fetch(self::SERVICE . '/sites/' . self::SITE);
1008
+ $found = is_string($body) ? json_decode($body, true) : null;
1009
+ if (is_array($found) && isset($found['tag'])) {
1010
+ $notice = isset($found['notice']) ? $found['notice'] : '';
1011
+ if (self::valid($found['tag'], $notice)) {
1012
+ $kept['tag'] = $found['tag'];
1013
+ $kept['notice'] = $notice;
1014
+ $wait = 3600;
1015
+ }
1016
+ }
1017
+ $kept['due'] = time() + $wait;
1018
+ self::keep($kept);
1019
+ }
1020
+ self::$lines = array($kept['tag'], $kept['notice']);
1021
+ return self::$lines;
1022
+ }
1023
+
1024
+ // Whether lines are this site's: a tag that loads its script, and a
1025
+ // notice or none.
1026
+ private static function valid($tag, $notice)
1027
+ {
1028
+ return is_string($tag)
1029
+ && preg_match('#^<script [^<>]*></script>$#D', $tag)
1030
+ && strpos($tag, '/s/' . self::SITE . '.js"') !== false
1031
+ && is_string($notice)
1032
+ && preg_match('#^(?:<noscript>[^<>]*</noscript>)?$#D', $notice);
1033
+ }
1034
+ ${own2}
1035
+ // A page as it goes out, sent with $status and $headers (headers_list()):
1036
+ // with the lines when it's HTML sent whole, and as it is otherwise.
1037
+ public static function sent($html, $status, $headers)
1038
+ {
1039
+ $type = (string) ini_get('default_mimetype');
1040
+ $policies = array();
1041
+ $length = false;
1042
+ foreach ($headers as $header) {
1043
+ $parts = explode(':', $header, 2);
1044
+ $name = strtolower(trim($parts[0]));
1045
+ $value = isset($parts[1]) ? trim($parts[1]) : '';
1046
+ if ($name === 'content-encoding') {
1047
+ return $html;
1048
+ }
1049
+ if ($name === 'content-type') {
1050
+ $type = $value;
1051
+ } elseif ($name === 'content-security-policy') {
1052
+ $policies[] = $value;
1053
+ } elseif ($name === 'content-length') {
1054
+ $length = true;
1055
+ }
1056
+ }
1057
+ if ($status !== 200 || stripos($type, 'text/html') !== 0) {
1058
+ return $html;
1059
+ }
1060
+ $page = self::insert($html, self::lines(), implode(',', $policies));
1061
+ if ($page !== $html && $length && !headers_sent()) {
1062
+ header_remove('Content-Length');
1063
+ }
1064
+ return $page;
1065
+ }
1066
+
1067
+ // Exa, a search engine AI agents read the web through, runs no script and
1068
+ // keeps only a page's main text, so the tag and the notice never reach an
1069
+ // agent that reads a page there. The line says the notice again, hidden at
1070
+ // the end of the page's first paragraph, where Exa keeps it. Empty for a
1071
+ // notice that isn't one.
1072
+ const STYLE = ${phpString(LINE_STYLE)};
1073
+
1074
+ private static function line($notice)
1075
+ {
1076
+ $list = '/s/' . self::SITE . '.md';
1077
+ if (!preg_match('#^<noscript>([^<>]*) (https?://[^\s<>"]+)</noscript>$#D', $notice, $said)
1078
+ || substr($said[2], -strlen($list)) !== $list) {
1079
+ return '';
1080
+ }
1081
+ return ' <span class="agentface-api" style="' . self::STYLE . '">' . $said[1]
1082
+ . ' <a tabindex="-1" href="' . $said[2] . '">' . $said[2] . '</a></span>';
1083
+ }
1084
+
1085
+ // The page's first paragraph as Exa reads one: a <p> of 40 characters or
1086
+ // more, in <main>, or in the body when <main> has none, and not in a header,
1087
+ // a menu, a footer, a form, an aside, a dialog or anything hidden. Those
1088
+ // after the page's heading come first, and one whose words are on the page
1089
+ // twice, such as a list's, is passed over. The byte its </p> starts at, or -1.
1090
+ const RAW = '#^(?:script|style|textarea|title|template|noscript)$#D';
1091
+ const OUTSIDE = '#^(?:header|nav|footer|form|aside|dialog|astro-island)$#D';
1092
+ const VOID = '#^(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$#D';
1093
+ const ENDS_P = '#^(?:address|article|aside|blockquote|details|dialog|div|dl|fieldset|figcaption|figure|footer|form|h[1-6]|header|hgroup|hr|main|menu|nav|ol|p|pre|section|table|ul)$#D';
1094
+ const TOKEN = '#\G(?:<!--.*?-->|<(/?)([a-zA-Z][\w:-]*)((?:"[^"]*"|\'[^\']*\'|[^>"\'])*)>|[^<]+|<)#s';
1095
+
1096
+ private static function firstParagraph($html, $at)
1097
+ {
1098
+ $names = array();
1099
+ $outs = array();
1100
+ $found = array();
1101
+ $open = null;
1102
+ $headed = false;
1103
+ $headedInMain = false;
1104
+ while ($at < strlen($html) && preg_match(self::TOKEN, $html, $m, 0, $at)) {
1105
+ $start = $at;
1106
+ $at += strlen($m[0]);
1107
+ if (substr($m[0], 0, 4) === '<!--') {
1108
+ continue;
1109
+ }
1110
+ if (!isset($m[2]) || $m[2] === '') {
1111
+ if ($open !== null) {
1112
+ $open['words'] .= $m[0];
1113
+ }
1114
+ continue;
1115
+ }
1116
+ $name = strtolower($m[2]);
1117
+ $attributes = isset($m[3]) ? $m[3] : '';
1118
+ if ($m[1] === '/') {
1119
+ if ($name === 'body') {
1120
+ break;
1121
+ }
1122
+ $depths = array_keys($names, $name, true);
1123
+ if (!$depths) {
1124
+ continue;
1125
+ }
1126
+ $depth = $depths[count($depths) - 1];
1127
+ if ($open !== null && $depth <= $open['depth']) {
1128
+ if ($depth === $open['depth'] && $name === 'p') {
1129
+ $open['at'] = $start;
1130
+ $found[] = $open;
1131
+ }
1132
+ $open = null;
1133
+ }
1134
+ array_splice($names, $depth);
1135
+ array_splice($outs, $depth);
1136
+ continue;
1137
+ }
1138
+ if (preg_match(self::RAW, $name)) {
1139
+ if (!preg_match('#</' . $name . '\s*>#i', $html, $end, PREG_OFFSET_CAPTURE, $at)) {
1140
+ break;
1141
+ }
1142
+ $at = $end[0][1] + strlen($end[0][0]);
1143
+ continue;
1144
+ }
1145
+ if ($open !== null && preg_match(self::ENDS_P, $name)) {
1146
+ array_splice($names, $open['depth']);
1147
+ array_splice($outs, $open['depth']);
1148
+ $open = null;
1149
+ }
1150
+ $main = in_array('main', $names, true);
1151
+ if ($name === 'h1') {
1152
+ $headed = true;
1153
+ $headedInMain = $headedInMain || $main;
1154
+ }
1155
+ if (preg_match(self::VOID, $name) || substr($attributes, -1) === '/') {
1156
+ continue;
1157
+ }
1158
+ $bare = preg_replace('#"[^"]*"|\'[^\']*\'#', '', $attributes);
1159
+ $names[] = $name;
1160
+ $outs[] = preg_match(self::OUTSIDE, $name) === 1
1161
+ || preg_match('#(?:^|\s)hidden\b#i', $bare) === 1
1162
+ || preg_match('#\brole\s*=\s*["\']?dialog\b#i', $attributes) === 1;
1163
+ if ($name === 'p') {
1164
+ $open = array(
1165
+ 'at' => -1,
1166
+ 'depth' => count($names) - 1,
1167
+ 'words' => '',
1168
+ 'main' => $main,
1169
+ 'first' => $main ? $headedInMain : $headed,
1170
+ 'out' => in_array(true, $outs, true),
1171
+ );
1172
+ }
1173
+ }
1174
+ $times = array();
1175
+ foreach ($found as $i => $p) {
1176
+ $words = trim(preg_replace('#(?:\s|\xC2\xA0)+#', ' ', $p['words']), ' ');
1177
+ $found[$i]['words'] = $words;
1178
+ $times[$words] = isset($times[$words]) ? $times[$words] + 1 : 1;
1179
+ }
1180
+ $long = array();
1181
+ $inMain = array();
1182
+ foreach ($found as $p) {
1183
+ // Its length in characters, which UTF-8 makes of one or more bytes.
1184
+ if (!$p['out'] && preg_match_all('#[^\x80-\xBF]#', $p['words']) >= 40) {
1185
+ $long[] = $p;
1186
+ if ($p['main']) {
1187
+ $inMain[] = $p;
1188
+ }
1189
+ }
1190
+ }
1191
+ $pool = $inMain ? $inMain : $long;
1192
+ foreach (array(true, false) as $first) {
1193
+ foreach ($pool as $p) {
1194
+ if ($p['first'] === $first && $times[$p['words']] === 1) {
1195
+ return $p['at'];
1196
+ }
1197
+ }
1198
+ }
1199
+ return -1;
1200
+ }
1201
+
1202
+ // Whether the page may hide the line with a style attribute. Under a Content
1203
+ // Security Policy that blocks inline styles, from the response or the page's
1204
+ // own <meta>, the line would be on screen, so the page gets none.
1205
+ private static function stylesAllowed($html, $policy)
1206
+ {
1207
+ $policies = array($policy);
1208
+ preg_match_all('#<meta\b[^>]*http-equiv\s*=\s*["\']?content-security-policy\b[^>]*>#i', $html, $metas);
1209
+ foreach ($metas[0] as $meta) {
1210
+ $content = preg_match('#\bcontent\s*=\s*(?:"([^"]*)"|\'([^\']*)\')#i', $meta, $said) ? $said : array();
1211
+ $policies[] = isset($content[1]) && $content[1] !== '' ? $content[1] : (isset($content[2]) ? $content[2] : '');
1212
+ }
1213
+ foreach (explode(',', implode(',', $policies)) as $text) {
1214
+ $rules = array();
1215
+ foreach (explode(';', $text) as $rule) {
1216
+ $sources = preg_split('#\s+#', strtolower(trim($rule)));
1217
+ $name = array_shift($sources);
1218
+ if ($name !== '' && !isset($rules[$name])) {
1219
+ $rules[$name] = $sources;
1220
+ }
1221
+ }
1222
+ $sources = null;
1223
+ foreach (array('style-src-attr', 'style-src', 'default-src') as $name) {
1224
+ if ($sources === null && isset($rules[$name])) {
1225
+ $sources = $rules[$name];
1226
+ }
1227
+ }
1228
+ if ($sources === null) {
1229
+ continue;
1230
+ }
1231
+ if (!in_array("'unsafe-inline'", $sources, true)) {
1232
+ return false;
1233
+ }
1234
+ foreach ($sources as $source) {
1235
+ if (preg_match('#^\'(?:nonce|sha256|sha384|sha512)-#', $source)) {
1236
+ return false;
1237
+ }
1238
+ }
1239
+ }
1240
+ return true;
1241
+ }
1242
+
1243
+ // The page's own </head> or <body>: the first one outside comments and the
1244
+ // elements whose text can look like one, such as a script that builds a page
1245
+ // from a string. Where it starts and ends, or null where there's none.
1246
+ const SKIPPED = '<!--[\s\S]*?(?:-->|\z)|<script\b[^>]*>[\s\S]*?(?:</script\s*>|\z)|<style\b[^>]*>[\s\S]*?(?:</style\s*>|\z)|<textarea\b[^>]*>[\s\S]*?(?:</textarea\s*>|\z)|<title\b[^>]*>[\s\S]*?(?:</title\s*>|\z)|<template\b[^>]*>[\s\S]*?(?:</template\s*>|\z)|<noscript\b[^>]*>[\s\S]*?(?:</noscript\s*>|\z)';
1247
+
1248
+ private static function outside($html, $element)
1249
+ {
1250
+ $pattern = '#' . self::SKIPPED . '|(' . $element . ')#i';
1251
+ for ($at = 0; preg_match($pattern, $html, $m, PREG_OFFSET_CAPTURE, $at); $at = $m[0][1] + strlen($m[0][0])) {
1252
+ if (isset($m[1]) && $m[1][1] !== -1) {
1253
+ return array($m[1][1], $m[1][1] + strlen($m[1][0]));
1254
+ }
1255
+ }
1256
+ return null;
1257
+ }
1258
+
1259
+ // The page with the site's lines in it: the tag last in its head, the notice
1260
+ // first in its body, the line at the end of its first paragraph. A page
1261
+ // without a head, such as a fragment, stays as it is, and so do lines put
1262
+ // there by hand and an AMP page, which allows no script of ours.
1263
+ public static function insert($html, $lines, $policy = '')
1264
+ {
1265
+ if (preg_match('#<html\b[^>]*\s(?:amp|⚡)[\s>=/]#i', $html)) {
1266
+ return $html;
1267
+ }
1268
+ list($tag, $notice) = $lines;
1269
+ $page = $html;
1270
+ if (strpos($page, '/s/' . self::SITE . '.js') === false) {
1271
+ $head = self::outside($page, '</head\s*>');
1272
+ if ($head === null) {
1273
+ return $html;
1274
+ }
1275
+ $page = substr($page, 0, $head[0]) . $tag . substr($page, $head[0]);
1276
+ $body = $notice !== '' ? self::outside($page, '<body\b[^>]*>') : null;
1277
+ if ($body !== null) {
1278
+ $page = substr($page, 0, $body[1]) . $notice . substr($page, $body[1]);
1279
+ }
1280
+ }
1281
+ $line = self::line($notice);
1282
+ $body = self::outside($page, '<body\b[^>]*>');
1283
+ if ($line === '' || $body === null || strpos($page, 'class="agentface-api"') !== false || !self::stylesAllowed($page, $policy)) {
1284
+ return $page;
1285
+ }
1286
+ $at = self::firstParagraph($page, $body[1]);
1287
+ return $at === -1 ? $page : substr($page, 0, $at) . $line . substr($page, $at);
1288
+ }
1289
+ }
1290
+ `;
1291
+ };
1292
+ var DOES = (notice) => `Puts the Agentface tag in every page's head${notice ? ", its notice first in the body, and the notice again, hidden, at the end of the first paragraph" : ""}.`;
1293
+ var MU_PLUGIN = (tag, notice) => String.raw`<?php
1294
+ /**
1295
+ * Plugin Name: Agentface
1296
+ * Description: ${DOES(notice)}
1297
+ */
1298
+ ${about("//", "WordPress runs it on every page by itself, as a must-use plugin, and it puts\nthem in each page made from the theme.")}
1299
+ if (!defined('ABSPATH')) {
1300
+ exit;
1301
+ }
1302
+
1303
+ ${PHP_LINES(
1304
+ tag,
1305
+ notice,
1306
+ String.raw`
1307
+ // The copy, in the site's options.
1308
+ private static function kept()
1309
+ {
1310
+ return get_option('agentface_lines');
1311
+ }
1312
+
1313
+ private static function keep($kept)
1314
+ {
1315
+ update_option('agentface_lines', $kept, true);
1316
+ }
1317
+
1318
+ // What Agentface answered at $url, or null.
1319
+ private static function fetch($url)
1320
+ {
1321
+ $response = wp_remote_get($url, array(
1322
+ 'timeout' => 2,
1323
+ 'user-agent' => 'agentface-lines/${INIT}',
1324
+ 'headers' => array('Accept' => 'application/json'),
1325
+ ));
1326
+ return !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200
1327
+ ? wp_remote_retrieve_body($response)
1328
+ : null;
1329
+ }
1330
+ `
1331
+ )}
1332
+ // The lines are asked for before the page is made, and go in as it goes out.
1333
+ // A page sent in parts gets them in the part that has the end of its head,
1334
+ // without the line Exa keeps.
1335
+ add_action('template_redirect', function () {
1336
+ AgentfaceLines::lines();
1337
+ ob_start(function ($html, $phase) {
1338
+ return $phase & PHP_OUTPUT_HANDLER_CLEAN ? $html : AgentfaceLines::sent($html, http_response_code(), headers_list());
1339
+ });
1340
+ }, PHP_INT_MIN);
1341
+ `;
1342
+ var PRESTASHOP_MODULE = (tag, notice) => String.raw`<?php
1343
+ ${about("//", "PrestaShop runs it once it's installed in Modules > Module Manager, and it\nputs them in each page the shop makes.")}
1344
+ if (!defined('_PS_VERSION_')) {
1345
+ exit;
1346
+ }
1347
+
1348
+ ${PHP_LINES(
1349
+ tag,
1350
+ notice,
1351
+ String.raw`
1352
+ // The copy, in the shop's settings. Its tags are escaped, since PrestaShop
1353
+ // takes tags out of a setting's text.
1354
+ private static function kept()
1355
+ {
1356
+ return json_decode((string) Configuration::getGlobalValue('AGENTFACE_LINES'), true);
1357
+ }
1358
+
1359
+ private static function keep($kept)
1360
+ {
1361
+ Configuration::updateGlobalValue('AGENTFACE_LINES', json_encode($kept, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT));
1362
+ }
1363
+
1364
+ // What Agentface answered at $url, or null.
1365
+ private static function fetch($url)
1366
+ {
1367
+ if (!function_exists('curl_init')) {
1368
+ return null;
1369
+ }
1370
+ $curl = curl_init($url);
1371
+ curl_setopt_array($curl, array(
1372
+ CURLOPT_RETURNTRANSFER => true,
1373
+ CURLOPT_CONNECTTIMEOUT => 2,
1374
+ CURLOPT_TIMEOUT => 2,
1375
+ CURLOPT_USERAGENT => 'agentface-lines/${INIT}',
1376
+ CURLOPT_HTTPHEADER => array('Accept: application/json'),
1377
+ ));
1378
+ $body = curl_exec($curl);
1379
+ return is_string($body) && curl_getinfo($curl, CURLINFO_HTTP_CODE) === 200 ? $body : null;
1380
+ }
1381
+ `
1382
+ )}
1383
+ class Agentface extends Module
1384
+ {
1385
+ public function __construct()
1386
+ {
1387
+ $this->name = 'agentface';
1388
+ $this->tab = 'front_office_features';
1389
+ $this->version = '1.0.0';
1390
+ $this->author = 'Agentface';
1391
+ $this->need_instance = 0;
1392
+ $this->ps_versions_compliancy = ['min' => '1.7.1.0', 'max' => _PS_VERSION_];
1393
+ parent::__construct();
1394
+ $this->displayName = 'Agentface';
1395
+ $this->description = "${DOES(notice)}";
1396
+ }
1397
+
1398
+ public function install()
1399
+ {
1400
+ return parent::install() && $this->registerHook('actionOutputHTMLBefore');
1401
+ }
1402
+
1403
+ public function uninstall()
1404
+ {
1405
+ Configuration::deleteByName('AGENTFACE_LINES');
1406
+ return parent::uninstall();
1407
+ }
1408
+
1409
+ public function hookActionOutputHTMLBefore($params)
1410
+ {
1411
+ $params['html'] = AgentfaceLines::sent($params['html'], http_response_code(), headers_list());
1412
+ }
1413
+
1414
+ // A shop that installed the module an earlier init wrote still calls it in
1415
+ // every page's head and body, where it put the tag and the notice. The
1416
+ // first page it's called for moves it to the hook above, and gets them
1417
+ // there as before.
1418
+ public function hookDisplayHeader()
1419
+ {
1420
+ if ($this->registerHook('actionOutputHTMLBefore')) {
1421
+ $this->unregisterHook('displayHeader');
1422
+ $this->unregisterHook('displayAfterBodyOpeningTag');
1423
+ }
1424
+ $lines = AgentfaceLines::lines();
1425
+ return $lines[0] . "\n";
1426
+ }
1427
+
1428
+ public function hookDisplayAfterBodyOpeningTag()
1429
+ {
1430
+ $lines = AgentfaceLines::lines();
1431
+ return $lines[1] === '' ? '' : $lines[1] . "\n";
1432
+ }
1433
+ }
1434
+ `;
1435
+ var MU_PLUGIN_HOOKS = (tag, notice) => `<?php
938
1436
  /**
939
1437
  * Plugin Name: Agentface
940
1438
  * Description: Puts the Agentface tag in every page's head${notice ? ", and its notice first in the body" : ""}.
@@ -949,7 +1447,7 @@ add_action('wp_body_open', function () {
949
1447
  echo '${notice}' . "\\n";
950
1448
  }, PHP_INT_MIN);
951
1449
  ` : ""}`;
952
- var PRESTASHOP_MODULE = (tag, notice) => `<?php
1450
+ var PRESTASHOP_MODULE_HOOKS = (tag, notice) => `<?php
953
1451
  // ${OURS}. PrestaShop runs it on every page once it's installed in Modules > Module Manager, and \`npx agentface uninstall\` deletes it.
954
1452
  if (!defined('_PS_VERSION_')) {
955
1453
  exit;
@@ -1014,7 +1512,9 @@ async function findTags(dir) {
1014
1512
  }
1015
1513
  return tagged;
1016
1514
  }
1017
- var loose = (text2) => text2.replace(/\s+/g, "").replace(/['"`]/g, '"').replace(/;/g, "").replace(/,(?=[\])}])/g, "");
1515
+ var VERSIONS = /\s+data-init=(?:"[^"]*"|'[^']*'|\{[^{}]*\})|,\s*['"]data-init['"]\s*:\s*['"][^'"]*['"]|(?<=agentface-lines)\/[0-9.]+/g;
1516
+ var loose = (text2) => text2.replace(VERSIONS, "").replace(/\s+/g, "").replace(/['"`]/g, '"').replace(/;/g, "").replace(/,(?=[\])}])/g, "");
1517
+ var namesInit = (text2) => /data-init|agentface-lines\/[0-9]/.test(text2);
1018
1518
  var sameFile = (source, content) => loose(source) === loose(content);
1019
1519
  function tagIn(source, tag) {
1020
1520
  const old = source.match(TAG)?.[0];
@@ -1024,7 +1524,9 @@ function madeByInit(source) {
1024
1524
  const gatsby = (pattern) => source.match(pattern)?.[1];
1025
1525
  const load = gatsby(/key:\s*['"]agentface['"],\s*(async|defer):\s*true/);
1026
1526
  const src = gatsby(/\bsrc:\s*['"]([^'"]+)['"]/);
1027
- const [, attribute2, about2] = source.match(/['"](data-[a-z-]+)['"]:\s*['"]([^'"]+)['"]/) ?? [];
1527
+ const data = [...source.matchAll(/['"](data-[a-z-]+)['"]:\s*['"]([^'"]+)['"]/g)].map(
1528
+ ([, name, value]) => ` ${name}="${value}"`
1529
+ );
1028
1530
  const text2 = gatsby(
1029
1531
  /createElement\(\s*['"]noscript['"],\s*\{\s*key:\s*['"]agentface['"],?\s*\},\s*['"]([^'"]*)['"],?\s*\)/
1030
1532
  );
@@ -1032,9 +1534,11 @@ function madeByInit(source) {
1032
1534
  [NEXT_DOCUMENT, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
1033
1535
  [MU_PLUGIN, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
1034
1536
  [PRESTASHOP_MODULE, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
1537
+ [MU_PLUGIN_HOOKS, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
1538
+ [PRESTASHOP_MODULE_HOOKS, source.match(TAG)?.[0], source.match(NOTICE)?.[0]],
1035
1539
  [
1036
1540
  GATSBY_SSR,
1037
- load && src && `<script ${load} src="${src}"${about2 ? ` ${attribute2}="${about2}"` : ""}></script>`,
1541
+ load && src && `<script ${load} src="${src}"${data.join("")}></script>`,
1038
1542
  text2 && `<noscript>${text2}</noscript>`
1039
1543
  ]
1040
1544
  ];
@@ -1196,18 +1700,6 @@ var exists2 = (file) => stat3(file).then(
1196
1700
  );
1197
1701
  var posix = path3.posix;
1198
1702
  var BACKTICK = "`";
1199
- function siteOf(tag) {
1200
- const [, service = "", site = ""] = tag.match(/\bsrc="(https?:\/\/[^"]+?)\/s\/([^/"]+)\.js"/) ?? [];
1201
- return { service, site };
1202
- }
1203
- var about = (comment2, how) => [
1204
- `${OURS}. It asks Agentface for the two lines this`,
1205
- "site's pages carry for AI agents, the tag and its notice, so that a change to",
1206
- "them reaches the site by itself. It keeps them an hour and, while Agentface",
1207
- "can't be reached, uses the copy it has: at first the one below.",
1208
- how,
1209
- "`npx agentface uninstall` deletes it."
1210
- ].join("\n").replace(/^/gm, comment2 + " ").replace(/ +$/gm, "");
1211
1703
  var HOW = {
1212
1704
  astro: "astro.config adds the integration, agentface(), whose middleware puts them\nin every page Astro makes.",
1213
1705
  vite: "vite.config adds the plugin, agentface(), which puts them in index.html\nwhen the site is built.",
@@ -1666,7 +2158,7 @@ async function ask() {
1666
2158
  let wait = 300_000;
1667
2159
  try {
1668
2160
  const response = await fetch(SERVICE + '/sites/' + SITE, {
1669
- headers: { accept: 'application/json', 'user-agent': 'agentface-lines' },
2161
+ headers: { accept: 'application/json', 'user-agent': 'agentface-lines/${INIT}' },
1670
2162
  signal: AbortSignal.timeout(2000),
1671
2163
  });
1672
2164
  const body = (response.ok ? await response.json() : null)${t(" as { tag?: unknown; notice?: unknown } | null")};
@@ -1749,7 +2241,7 @@ def _ask():
1749
2241
  try:
1750
2242
  request = urllib.request.Request(
1751
2243
  SERVICE + "/sites/" + SITE,
1752
- headers={"Accept": "application/json", "User-Agent": "agentface-lines"},
2244
+ headers={"Accept": "application/json", "User-Agent": "agentface-lines/${INIT}"},
1753
2245
  )
1754
2246
  with urllib.request.urlopen(request, timeout=2) as response:
1755
2247
  body = json.loads(response.read().decode("utf-8"))
@@ -2157,7 +2649,7 @@ module Agentface
2157
2649
  uri = URI("#{SERVICE}/sites/#{SITE}")
2158
2650
  options = { use_ssl: uri.scheme == "https", open_timeout: 2, read_timeout: 2 }
2159
2651
  response = Net::HTTP.start(uri.host, uri.port, **options) do |http|
2160
- http.get(uri.request_uri, "Accept" => "application/json", "User-Agent" => "agentface-lines")
2652
+ http.get(uri.request_uri, "Accept" => "application/json", "User-Agent" => "agentface-lines/${INIT}")
2161
2653
  end
2162
2654
  if response.is_a?(Net::HTTPSuccess)
2163
2655
  body = JSON.parse(response.body)
@@ -2477,7 +2969,7 @@ ${about(" #", "The endpoint plugs Agentface before its router, which puts them
2477
2969
 
2478
2970
  defp ask do
2479
2971
  url = String.to_charlist(@service <> "/sites/" <> @site)
2480
- headers = [{~c"accept", ~c"application/json"}, {~c"user-agent", ~c"agentface-lines"}]
2972
+ headers = [{~c"accept", ~c"application/json"}, {~c"user-agent", ~c"agentface-lines/${INIT}"}]
2481
2973
 
2482
2974
  with {:ok, _} <- Application.ensure_all_started(:inets),
2483
2975
  {:ok, _} <- Application.ensure_all_started(:ssl),
@@ -2887,7 +3379,7 @@ func fetch() ([2]string, bool) {
2887
3379
  return [2]string{}, false
2888
3380
  }
2889
3381
  req.Header.Set("Accept", "application/json")
2890
- req.Header.Set("User-Agent", "agentface-lines")
3382
+ req.Header.Set("User-Agent", "agentface-lines/${INIT}")
2891
3383
  res, err := client.Do(req)
2892
3384
  if err != nil {
2893
3385
  return [2]string{}, false
@@ -4043,7 +4535,7 @@ const SITE = '${site}';
4043
4535
  async function ask() {
4044
4536
  try {
4045
4537
  const response = await fetch(SERVICE + '/sites/' + SITE, {
4046
- headers: { accept: 'application/json', 'user-agent': 'agentface-lines' },
4538
+ headers: { accept: 'application/json', 'user-agent': 'agentface-lines/${INIT}' },
4047
4539
  signal: AbortSignal.timeout(2000),
4048
4540
  });
4049
4541
  const body = response.ok ? await response.json() : null;
@@ -13219,7 +13711,7 @@ async function lookupSite(service, id, fetcher = fetch) {
13219
13711
  { unknownSite: true }
13220
13712
  );
13221
13713
  if (!response.ok) throw new Error(body?.message ?? `Agentface answered HTTP ${response.status}`);
13222
- return { ...body.site, tag: body.tag, notice: body.notice ?? null };
13714
+ return { ...body.site, tag: stamped(body.tag), notice: body.notice ?? null };
13223
13715
  }
13224
13716
  async function register(service, url, fetcher = fetch) {
13225
13717
  const { response, body } = await reach(
@@ -13230,7 +13722,7 @@ async function register(service, url, fetcher = fetch) {
13230
13722
  );
13231
13723
  if (!response.ok || !body?.site?.id)
13232
13724
  throw new Error(body?.message ?? `Agentface could not register ${url} (HTTP ${response.status})`);
13233
- return { ...body.site, expiresAt: body.expiresAt, tag: body.tag, notice: body.notice ?? null };
13725
+ return { ...body.site, expiresAt: body.expiresAt, tag: stamped(body.tag), notice: body.notice ?? null };
13234
13726
  }
13235
13727
  async function confirm(service, id, fetcher = fetch) {
13236
13728
  const { response, body } = await reach(
@@ -13485,7 +13977,7 @@ ${manual.steps(site.tag, site.notice)}`);
13485
13977
  return { site, files: [], written: false };
13486
13978
  }
13487
13979
  function prestaShopSteps(file) {
13488
- 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.`;
13980
+ 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. It asks Agentface for the tag and its notice and keeps them an hour, so that when what they say changes, the pages change by themselves, with nothing to run.`;
13489
13981
  const cache = "If the shop has a cache module, clear its cache, so that the pages show the tag.";
13490
13982
  if (file.endsWith(".zip"))
13491
13983
  return `${what} In the shop's back office, open Modules > Module Manager, click Upload a module and choose ${file}: PrestaShop installs it. ${cache}`;
@@ -13554,7 +14046,8 @@ async function init({
13554
14046
  before.set(file, source);
13555
14047
  const old = typeof source === "string" ? source : null;
13556
14048
  const made = content(old === null ? site.tag : tagIn(old, site.tag), site.notice);
13557
- after.set(file, old !== null && typeof made === "string" && sameFile(old, made) ? old : made);
14049
+ const same = old !== null && typeof made === "string" && sameFile(old, made) && (namesInit(old) || !namesInit(made));
14050
+ after.set(file, same ? old : made);
13558
14051
  }
13559
14052
  for (const { file, source, edit } of found.edits ?? []) {
13560
14053
  if (!before.has(file)) before.set(file, source);
@@ -13636,7 +14129,7 @@ async function init({
13636
14129
  if (found.framework === "PrestaShop theme") log(PRESTASHOP_THEME);
13637
14130
  if (found.framework === "WordPress")
13638
14131
  log(
13639
- `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.`
14132
+ `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. It asks Agentface for the tag and its notice and keeps them an hour, so that when what they say changes, the pages change by themselves, with nothing to run. 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.`
13640
14133
  );
13641
14134
  if (warning) log(warning);
13642
14135
  if (!pr) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentface",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "Add the Agentface tag to a website's pages, so AI agents get tools made for it, and use your agentface account from a shell.",
5
5
  "repository": {
6
6
  "type": "git",