agent-customs 0.0.0-stage → 1.0.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 (48) hide show
  1. package/LICENSE.md +341 -0
  2. package/README.md +592 -2
  3. package/bin/agent-customs.mjs +194 -0
  4. package/package.json +77 -4
  5. package/site/.well-known/agent-customs-key.json +13 -0
  6. package/site/certificate.js +944 -0
  7. package/site/customs/analyze.js +1224 -0
  8. package/site/customs/auto.js +44 -0
  9. package/site/customs/canary.js +270 -0
  10. package/site/customs/canonical.js +123 -0
  11. package/site/customs/capabilities.js +387 -0
  12. package/site/customs/diff.js +236 -0
  13. package/site/customs/english-words.js +153 -0
  14. package/site/customs/guard-notice.js +226 -0
  15. package/site/customs/guard-ui.js +105 -0
  16. package/site/customs/guard.js +259 -0
  17. package/site/customs/inspect.js +446 -0
  18. package/site/customs/judge.js +208 -0
  19. package/site/customs/languages.js +826 -0
  20. package/site/customs/locks.js +967 -0
  21. package/site/customs/pins.js +119 -0
  22. package/site/customs/protocols.js +621 -0
  23. package/site/customs/receipts.js +154 -0
  24. package/site/customs/rules.js +1470 -0
  25. package/site/customs/unicode.js +361 -0
  26. package/site/runtime/LICENSE.txt +176 -0
  27. package/site/runtime/generated/graph.gen.mjs +83 -0
  28. package/site/runtime/generated/validation.gen.mjs +70 -0
  29. package/site/runtime/hocon.js +262 -0
  30. package/site/runtime/kernel.js +237 -0
  31. package/site/runtime/model.js +44 -0
  32. package/tests/fixtures/official/NOTICE +3 -0
  33. package/tests/fixtures/official/guesthouse_agentified/agent-manifest.json +86 -0
  34. package/tests/fixtures/official/guesthouse_agentified/links.json +6 -0
  35. package/tests/fixtures/official/guesthouse_agentified/tidewhistle_guesthouse.network.json +56 -0
  36. package/tests/fixtures/official/harbor_tours_agentified/agent-manifest.json +86 -0
  37. package/tests/fixtures/official/harbor_tours_agentified/links.json +6 -0
  38. package/tests/fixtures/official/harbor_tours_agentified/marrow_point_harbor_tours.network.json +56 -0
  39. package/tests/fixtures/official/pizza_restaurant_agentified/agent-manifest.json +78 -0
  40. package/tests/fixtures/official/pizza_restaurant_agentified/links.json +6 -0
  41. package/tests/fixtures/official/pizza_restaurant_agentified/pizza_restaurant_website_assistant.network.json +156 -0
  42. package/tools/bench.mjs +731 -0
  43. package/tools/external-heldout.mjs +337 -0
  44. package/tools/fs-fetch.mjs +19 -0
  45. package/tools/heldout-corpus.mjs +135 -0
  46. package/tools/inspect-local.mjs +88 -0
  47. package/tools/round2-corpus.mjs +395 -0
  48. package/tools/round3-corpus.mjs +192 -0
@@ -0,0 +1,826 @@
1
+ // languages.js: text in languages other than English.
2
+ //
3
+ // The text rules in rules.js read English. Two checks here cover other languages:
4
+ //
5
+ // 1. Requests for card details or passwords in twelve widely used languages: Spanish,
6
+ // French, German, Portuguese, Italian, Russian, Chinese, Japanese, Hindi, Arabic, Dutch
7
+ // and Indonesian.
8
+ // A sentence counts when it has a request word and a secret word and no negation
9
+ // word at all, so "never ask for passwords" in any of them is not read as a request.
10
+ // Rules.js reports these as C-SECRETS, the same as in English.
11
+ // 2. Sentences that are not clearly English, whatever the language. The English rules
12
+ // cannot read them, so rules.js holds the network for a person to look at (C-LANGUAGE).
13
+ // english-words.js holds the common English words this check counts.
14
+ //
15
+ // Both run on text that normalizeForRules has already cleaned.
16
+
17
+ import { isEnglishWord } from "./english-words.js";
18
+
19
+ // Whole words: no letter, mark or digit right before or after. JavaScript's \b only
20
+ // knows ASCII letters, so it would split "contraseña" after the "ñ".
21
+ const EDGE_BEFORE = "(?<![\\p{L}\\p{M}\\p{N}])";
22
+ const EDGE_AFTER = "(?![\\p{L}\\p{M}\\p{N}])";
23
+ const words = (...parts) => new RegExp(`${EDGE_BEFORE}(?:${parts.join("|")})${EDGE_AFTER}`, "iu");
24
+ // Chinese and Japanese put no spaces between words, so their patterns match anywhere.
25
+ const anywhere = (...parts) => new RegExp(`(?:${parts.join("|")})`, "iu");
26
+
27
+ // Some request verbs also describe the visitor asking: "si el visitante pide ayuda con su
28
+ // contraseña" ("if the visitor asks for help with their password"). These count only when
29
+ // no subject, "if", "when" or article comes right before them.
30
+ const notAfter = (list) => `(?<!(?:${list}) )`;
31
+ // Infinitives after "wants to", "can" or "to" describe the visitor too: "si el cliente
32
+ // quiere pedir ayuda con su contraseña".
33
+ const ES_NOT_AFTER = notAfter("si|cuando|que|quien|quienes|visitante|visitantes|usuario|usuarios|cliente|clientes|alguien|persona|él|ella|ellos|ellas|le|les|se|lo|la|una|cada|quiere|quieren|puede|pueden|necesita|necesitan|desea|desean|suele|suelen|para|al|va a|van a");
34
+ const PT_NOT_AFTER = notAfter("se|quando|que|quem|visitante|visitantes|usu[aá]rio|usu[aá]rios|utilizador|cliente|clientes|algu[eé]m|pessoa|ele|ela|eles|elas|lhe|lhes|uma|cada|quer|querem|pode|podem|precisa|precisam|deseja|desejam|costuma|costumam|para|ao|vai|v[aã]o");
35
+ const FR_NOT_AFTER = notAfter("si|quand|qui|que|visiteur|visiteuse|visiteurs|utilisateur|utilisatrice|utilisateurs|client|cliente|clients|quelqu'un|personne|il|elle|ils|elles|on|la|une|chaque|ta|sa|ma|votre|leur|cette|ce|toute|nouvelle|aucune|à|de|pour|veut|veulent|peut|peuvent|souhaite|souhaitent|voudrait|aimerait");
36
+ const IT_NOT_AFTER = notAfter("se|quando|che|chi|visitatore|visitatrice|utente|utenti|cliente|clienti|qualcuno|persona|lui|lei|loro|gli|le|si|una|ogni|vuole|vogliono|pu[oò]|possono|desidera|desiderano|per|di|a");
37
+ const DE_NOT_AFTER = notAfter("ich|er|sie|es|man|wer|besucher|besucherin|nutzer|nutzerin|kunde|kundin|kunden|jemand|die|eine|jede|jeder|deine|ihre|seine|keine|diese|welche|der|einer|deiner|ihrer|seiner|unsere|unserer");
38
+ const ZH_NOT_AFTER = "(?<!(?:用户|用戶|访客|訪客|客户|客戶|顾客|顧客|他们|他們|她们|她們|他|她|对方|對方|有人|别人|別人|如果|若))";
39
+
40
+ /**
41
+ * Request words, secret words and negation words for each language with full requests
42
+ * checked. Words that are also nouns ("pregunta" is a question, "Frage" too) count
43
+ * only in their request form. Verbs such as "obtain" are left out: "para obtener una
44
+ * nueva contraseña" ("to get a new password") is ordinary help.
45
+ */
46
+ export const SECRET_LANGUAGES = [
47
+ {
48
+ code: "es", name: "Spanish",
49
+ asks: words(
50
+ `${ES_NOT_AFTER}(?:p[ií]d[ae]n?|solicit[ae]n?|exig[ea]|exijan?|recopil[ae]n?|recog[ea]|recojan?|pregunten?|pregunta (?:al|a la|a los|a las|a su|a tu|por|si|cu[aá]l|qu[eé])|pedir(?:le|les)?|preguntar(?:le|les)?|solicitar(?:le|les)?|exigir(?:le|les)?|recopilar)`,
51
+ "p[ií]d[ae]le(?:s)?", "preg[uú]nt[ae]le(?:s)?", "solicit[ae]le(?:s)?",
52
+ "dame", "danos", "d[eé]me", "d[eé]nos", "dime", "d[ií]game", "d[ií]ganos",
53
+ "env[ií]ame", "env[ií]anos", "env[ií]eme", "env[ií]enos", "m[aá]ndame", "m[aá]ndeme", "d[ií]ctame", "d[ií]cteme", "p[aá]same",
54
+ "(?:introduzca|ingrese|escriba|teclee|env[ií]e|comparta|proporcione|facilite|dicte|indique|confirme) (?:su|sus)",
55
+ "(?:introduce|ingresa|escribe|teclea|env[ií]a|comparte|proporciona|facilita|dicta|indica|confirma) (?:tu|tus)",
56
+ "que (?:te |le |nos |me )?(?:dé|diga|dicte|env[ií]e|escriba|introduzca|ingrese|proporcione|comparta|facilite|lea|teclee)",
57
+ "necesit(?:o|amos|as|a) (?:su|tu|sus|tus)", "ha(?:z|ga) que",
58
+ ),
59
+ secrets: words(
60
+ "n[uú]meros? de (?:la |su |tu |sus |tus )?tarjetas?", "datos de (?:la |su |tu )?tarjeta",
61
+ "c[oó]digos? (?:de seguridad|cvv|cvc|pin|de verificaci[oó]n|de confirmaci[oó]n|otp|de un solo uso|secreto|de acceso)",
62
+ "cvv2?", "cvc", "contrase[ñn]as?", "claves? (?:de acceso|secretas?|bancarias?|personal(?:es)?|de la tarjeta)",
63
+ "(?:su|tu|sus|tus) claves?", "pin", "otp", "fecha de (?:caducidad|vencimiento|expiraci[oó]n)",
64
+ "credenciales", "usuario y contrase[ñn]a", "datos de acceso",
65
+ ),
66
+ negations: [words("no", "nunca", "jam[aá]s", "ni", "sin", "tampoco", "ning[uú]n", "ninguna", "ninguno", "prohibido", "evit[ae]")],
67
+ },
68
+ {
69
+ code: "pt", name: "Portuguese",
70
+ asks: words(
71
+ `${PT_NOT_AFTER}(?:pe[cç]am? (?:ao|à|aos|às|a|o|os|as|para|que|seu|sua|seus|suas)|perguntem?|pergunta (?:ao|à|aos|às|por|se|qual)|solicitem?|exijam?|coletem?|recolham?|pedir(?:-lhes?)?|perguntar(?:-lhes?)?|solicitar(?:-lhes?)?|exigir|coletar|recolher)`,
72
+ "pe[cç]a-lhes?", "pergunte-lhes?", "solicite-lhes?",
73
+ "me dê", "nos dê", "dê-(?:me|nos)", "diga-(?:me|nos)", "(?:me|nos) diga", "envie-(?:me|nos)", "(?:me|nos) envie",
74
+ "(?:me|nos) passe", "passe-(?:me|nos)", "(?:me|nos) informe", "informe-(?:me|nos)", "dite-(?:me|nos)", "(?:me|nos) dite",
75
+ "(?:digite|insira|introduza|informe|forne[cç]a|envie|compartilhe|partilhe|confirme|dite|indique) (?:o seu|a sua|os seus|as suas|seu|sua|seus|suas|o|a)",
76
+ "fa[cç]a (?:com )?que", "precis(?:o|amos) d[oa] (?:seu|sua)",
77
+ ),
78
+ secrets: words(
79
+ "n[uú]meros? d[oe] (?:seu |sua )?cart[aã]o", "dados d[oe] (?:seu |sua )?cart[aã]o",
80
+ "c[oó]digos? (?:de seguran[cç]a|cvv|cvc|pin|de verifica[cç][aã]o|de confirma[cç][aã]o|otp|de uso [uú]nico|de acesso)",
81
+ "cvv2?", "cvc", "senhas?", "pin", "otp", "validade do cart[aã]o", "data de validade",
82
+ "credenciais", "usu[aá]rio e senha", "dados de acesso", "token (?:do banco|banc[aá]rio)",
83
+ ),
84
+ negations: [words("n[aã]o", "nunca", "jamais", "nem", "sem", "nenhum", "nenhuma", "proibido", "evite")],
85
+ },
86
+ {
87
+ code: "fr", name: "French",
88
+ asks: words(
89
+ `${FR_NOT_AFTER}(?:demande[sz]? (?:au|à|aux|le|la|les|l'|son|sa|ses|leur|leurs|votre|vos|ton|ta|tes|si|quel|quelle|quels|quelles|lui)|demandez|demander|exige[sz]?|exigez|exiger|sollicite[sz]?|sollicitez|solliciter|recueille[sz]?|recueillez|recueillir|collecte[sz]?|collectez|collecter|r[eé]clame[sz]?|r[eé]clamez|r[eé]clamer)`,
90
+ "demande[sz]?-(?:lui|leur)", "demandons",
91
+ "(?:donne|donnez|envoie|envoyez|dis|dites|communique|communiquez|transmets|transmettez|fournis|fournissez|dicte|dictez|lis|lisez|indique|indiquez|confirme|confirmez)[- ](?:moi|nous)",
92
+ "(?:saisis|saisissez|tape|tapez|entrez|indiquez|communiquez|envoyez|fournissez|donnez|dictez|partagez|transmettez|confirmez) (?:votre|vos|ton|ta|tes|son|sa|ses|leur|leurs)",
93
+ "fai(?:s|tes)[- ](?:lui|leur) (?:saisir|taper|donner|communiquer|dicter|lire|envoyer|indiquer|confirmer)",
94
+ "pri[eè]re de (?:fournir|saisir|communiquer|donner|indiquer)",
95
+ ),
96
+ secrets: words(
97
+ "num[eé]ros? de (?:la |sa |votre |ta |leur )?cartes?(?: bancaires?| de cr[eé]dit| de d[eé]bit)?",
98
+ "donn[eé]es (?:de (?:la |sa |votre |ta |leur )?carte|bancaires)", "coordonn[eé]es bancaires",
99
+ "codes? (?:de s[eé]curit[eé]|pin|secrets?|confidentiels?|de v[eé]rification|de confirmation|[aà] usage unique|otp|sms|d'acc[eè]s)",
100
+ "cryptogrammes?(?: visuels?)?", "cvv2?", "cvc", "mots? de passe", "pin", "otp",
101
+ "date d'expiration", "date de validit[eé]",
102
+ "identifiants? (?:bancaires|de connexion|de banque en ligne)", "identifiants? et mots? de passe",
103
+ ),
104
+ negations: [words("ne", "pas", "jamais", "sans", "aucun", "aucune", "ni", "interdite?s?", "[eé]vite[rz]?"), /(?<![\p{L}\p{M}])n'/iu],
105
+ },
106
+ {
107
+ code: "it", name: "Italian",
108
+ asks: words(
109
+ `${IT_NOT_AFTER}(?:chiedi|chieda|chiedete|chiedano|chiedere|richiedi|richieda|richiedete|richiedere|pretendi|pretenda|pretendere|esigi|esiga|esigere|raccogli|raccolga|raccogliere)`,
110
+ "chiedigli", "chiedile", "chiedetegli", "chiedergli", "chiederle",
111
+ "fa(?:tti|tevi) (?:dare|dire|dettare|inviare|mandare|comunicare|fornire|leggere)",
112
+ "si faccia (?:dare|dire|dettare|inviare|mandare|comunicare|fornire)",
113
+ "dammi", "dacci", "dimmi", "ditemi", "mandami", "inviami", "dettami", "comunicami", "forniscimi", "leggimi",
114
+ "(?:mi|ci) (?:dia|dica|invii|mandi|detti|comunichi|fornisca)",
115
+ "(?:inserisci|inserisca|digita|digiti|scrivi|scriva|invia|invii|comunica|comunichi|fornisci|fornisca|indica|indichi|conferma|confermi|detta|detti) (?:il tuo|la tua|i tuoi|le tue|il suo|la sua|i suoi|le sue|tuo|tua|suo|sua|il|la)",
116
+ ),
117
+ secrets: words(
118
+ "numer[oi] (?:della |di |delle )(?:sua |tua |propria )?carta(?: di credito| di debito)?", "dati della (?:sua |tua )?carta",
119
+ "codic[ei] (?:di sicurezza|pin|segret[oi]|di verifica|di conferma|otp|monouso|di accesso)",
120
+ "cvv2?", "cvc", "password", "pin", "otp", "data di scadenza", "scadenza della carta",
121
+ "credenziali", "nome utente e password", "dati di accesso",
122
+ ),
123
+ negations: [words("non", "mai", "senza", "n[eé]", "nessun[oa]?", "vietat[oaie]", "evita(?:re)?")],
124
+ },
125
+ {
126
+ code: "de", name: "German",
127
+ // Only the forms that give an order: "fragt" and "fragen" also describe the visitor
128
+ // ("wenn der Besucher nach seinem Passwort fragt"), and "Frage" is also "question".
129
+ asks: words(
130
+ `${DE_NOT_AFTER}(?:frag|frage|erfrage|verlang|verlange|fordere|erbitte|sammle|notiere|erhebe)`,
131
+ "(?:fragen|erfragen|verlangen|fordern|erbitten|sammeln|notieren|erheben) sie", "bitte (?:\\p{L}+ ){1,3}?um",
132
+ "lass(?:t|en sie)? (?:dir|euch|sich|ihnen|uns|mir) (?:\\p{L}+ ){0,4}?(?:geben|nennen|sagen|schicken|senden|zeigen|diktieren|vorlesen|mitteilen|durchgeben)",
133
+ "(?:gib|geben sie|nenne|nennen sie|sag|sage|sagen sie|schick|schicke|schicken sie|sende|senden sie|teile|teilen sie|diktiere|diktieren sie|lies|lesen sie) (?:mir|uns)",
134
+ "(?:gib|geben sie|tippe|tippen sie|trage|tragen sie|nenne|nennen sie|sende|senden sie|schick|schicke|schicken sie|teile|teilen sie|best[aä]tige|best[aä]tigen sie) (?:deine|deinen|dein|deiner|ihre|ihren|ihr|ihrer|seine|seinen|sein|eure|euren)",
135
+ ),
136
+ // German joins words, so "Kreditkartennummer" holds "kartennummer".
137
+ secrets: words(
138
+ "\\p{L}*kartennummer\\p{L}*", "\\p{L}*kartendaten\\p{L}*", "\\p{L}*kartenpr[uü]f\\p{L}*", "pr[uü]fziffer\\p{L}*", "pr[uü]fnummer\\p{L}*",
139
+ "\\p{L}*sicherheitscode\\p{L}*", "cvv2?", "cvc", "\\p{L}*passw[oö]rt\\p{L}*", "\\p{L}*kennw[oö]rt\\p{L}*",
140
+ "pin(?:-?(?:nummer|code))?", "geheimzahl\\p{L}*", "tan", "\\p{L}*best[aä]tigungscode\\p{L}*", "einmal(?:code|passwort|kennwort)\\p{L}*",
141
+ "\\p{L}*zugangsdaten", "\\p{L}*anmeldedaten", "login-?daten", "online-?banking-?(?:zugang|daten|passwort|pin|login|zugangsdaten)\\p{L}*",
142
+ "(?:ablauf|g[uü]ltigkeits|verfalls)datum der (?:\\p{L}+ )?karte",
143
+ ),
144
+ negations: [words("nicht", "nie", "niemals", "kein", "keine", "keinen", "keinem", "keiner", "keines", "ohne", "nichts", "verboten", "keinesfalls", "vermeiden?")],
145
+ },
146
+ {
147
+ code: "ru", name: "Russian",
148
+ asks: words(
149
+ "спроси(?:те)?", "спрашивай(?:те)?", "попроси(?:те)?", "запроси(?:те)?", "запрашивай(?:те)?",
150
+ "потребуй(?:те)?", "требуй(?:те)?", "собери(?:те)?", "собирай(?:те)?", "выпроси(?:те)?",
151
+ "пусть (?:\\p{L}+ ){0,3}?(?:введ[её]т|назов[её]т|сообщит|продиктует|отправит|скажет|напишет|пришл[её]т|укажет)",
152
+ "(?:дай|дайте|скажи|скажите|сообщи|сообщите|назови|назовите|пришли|пришлите|отправь|отправьте|продиктуй|продиктуйте) (?:мне|нам)",
153
+ "(?:введи|введите|укажи|укажите|назови|назовите|сообщи|сообщите|продиктуй|продиктуйте|пришли|пришлите|отправь|отправьте|напиши|напишите) (?:свой|свою|своё|свое|свои|ваш|вашу|ваше|ваши|твой|твою|твоё|твое|твои)",
154
+ ),
155
+ secrets: words(
156
+ "номер\\p{L}* (?:\\p{L}+ ){0,2}?карт\\p{L}*", "данн\\p{L}* (?:\\p{L}+ )?карт\\p{L}*", "реквизит\\p{L}* (?:\\p{L}+ )?карт\\p{L}*",
157
+ "cvv2?", "cvc", "cvv-код\\p{L}*", "код\\p{L}* безопасности", "парол\\p{L}*", "пин(?:-?код\\p{L}*)?", "pin(?:-?код\\p{L}*)?",
158
+ "код\\p{L}* (?:из (?:смс|sms)|подтверждения)", "одноразов\\p{L}* (?:код|парол)\\p{L}*",
159
+ "срок\\p{L}* действия (?:\\p{L}+ )?карт\\p{L}*", "логин\\p{L}* и парол\\p{L}*", "логин\\p{L}* от (?:\\p{L}+ )?банк\\p{L}*",
160
+ "уч[её]тн\\p{L}* данн\\p{L}*", "данные для входа",
161
+ ),
162
+ negations: [words("не", "ни", "никогда", "нельзя", "без", "запрещено", "ничего", "избегай(?:те)?")],
163
+ },
164
+ {
165
+ code: "zh", name: "Chinese",
166
+ asks: anywhere(
167
+ // "问" ("ask") alone, but not inside 询问, 提问 ("asks a question"), 访问 ("visit") or 问题 ("question").
168
+ `${ZH_NOT_AFTER}(?:询问|詢問|(?<![询詢提疑访訪学學顾顧])(?:问|問)(?![题題候]))`, "索要", "索取", "收集",
169
+ // "让/要求 X 提供" is X providing. "请告诉他们" ("please tell them") is the assistant
170
+ // telling, so "请" counts only before "enter" or "fill in".
171
+ "(?:让|讓|要求|叫)\\p{Script=Han}{0,4}?(?:提供|输入|輸入|告诉|告訴|发送|發送|填写|填寫|报出|報出|说出|說出|念出|给出|給出|发给|發給)",
172
+ "(?:请|請)(?:您|你)?(?:输入|輸入|填写|填寫)",
173
+ "告诉我", "告訴我", "发给我", "發給我", "报给我", "報給我",
174
+ ),
175
+ secrets: anywhere(
176
+ "卡号", "卡號", "卡的号码", "卡的號碼", "卡片号码", "卡片號碼", "信用卡号码", "信用卡號碼", "银行卡号", "銀行卡號",
177
+ "安全码", "安全碼", "验证码", "驗證碼", "cvv", "cvc", "密码", "密碼", "口令", "pin码", "pin碼", "动态码", "動態碼",
178
+ "卡(?:片)?的?有效期", "网银的?(?:账号|密码|登录)", "網銀的?(?:帳號|密碼|登錄)", "登录信息", "登錄信息", "账号和密码", "帳號和密碼",
179
+ ),
180
+ negations: [anywhere("不", "别", "別", "勿", "禁止", "切勿", "绝不", "絕不", "从不", "從不", "无需", "無需", "没有", "沒有", "非")],
181
+ },
182
+ {
183
+ code: "ja", name: "Japanese",
184
+ // Request forms only: "ユーザーがパスワードについて聞いてきたら" is the visitor asking.
185
+ asks: anywhere(
186
+ "聞いてください", "聞いて下さい", "聞いてくれ", "聞いて$", "聞き出して", "聞き出せ", "聞け", "聞くこと",
187
+ "尋ねてください", "尋ねること", "訊いてください", "求めてください", "求めること", "求めよ", "要求してください", "要求すること",
188
+ "入力させ", "入力してもら", "入力してください", "教えてもら", "伝えてもら", "送ってもら", "送らせ",
189
+ "提供してもら", "提供させ", "確認させ", "言わせ", "読み上げさせ", "収集して", "収集する",
190
+ ),
191
+ secrets: anywhere(
192
+ "カード番号", "カードの番号", "クレジットカード番号", "セキュリティコード", "セキュリティーコード", "暗証番号", "パスワード",
193
+ "認証コード", "確認コード", "ワンタイムパスワード", "cvv", "cvc", "カードの有効期限",
194
+ "ネットバンキングの?(?:id|パスワード|ログイン)", "ログイン情報", "ログインid",
195
+ ),
196
+ negations: [anywhere("ない", "ません", "ないで", "禁止", "決して", "しないこと", "だめ", "ダメ", "いけない")],
197
+ },
198
+ {
199
+ code: "hi", name: "Hindi",
200
+ asks: words(
201
+ "पूछें", "पूछो", "पूछिए", "पूछिये", "पूछना", "पूछ लें", "पूछ लो", "मांगें", "मांगो", "मांगिए", "मांगना", "मांग लें",
202
+ "माँगें", "माँगो", "माँगिए", "माँगना", "माँग लें", "बताने को कहें", "बताने के लिए कहें", "दर्ज करवाएं", "दर्ज कराएं",
203
+ "दर्ज करने को कहें", "डालने को कहें", "भेजने को कहें", "साझा करने को कहें", "शेयर करने को कहें", "इकट्ठा करें", "एकत्र करें",
204
+ ),
205
+ // "पिन कोड" is a postal code in India, so it does not count as a PIN.
206
+ secrets: words(
207
+ "कार्ड नंबर", "कार्ड संख्या", "कार्ड का नंबर", "कार्ड की संख्या", "कार्ड के नंबर", "कार्ड डिटेल्स", "कार्ड विवरण", "कार्ड की जानकारी",
208
+ "सीवीवी", "cvv", "पिन(?! ?कोड)", "पासवर्ड", "ओटीपी", "otp", "सत्यापन कोड",
209
+ "नेट ?बैंकिंग (?:लॉगिन|पासवर्ड|विवरण|आईडी)", "लॉगिन (?:विवरण|आईडी|डिटेल्स)", "यूपीआई पिन", "एटीएम पिन", "upi pin",
210
+ ),
211
+ negations: [words("नहीं", "न", "मत", "कभी", "बिना", "ना", "वर्जित", "मना")],
212
+ },
213
+ {
214
+ code: "ar", name: "Arabic",
215
+ // Arabic joins "and" (و), "so" (ف), "with" (ب) and "for" (ل) to the next word.
216
+ // Orders only: "عندما يسأل الزائر" is the visitor asking.
217
+ asks: words(
218
+ "[وف]?(?:اطلب|اطلبي|اطلبوا|اسأل|اسألي|اسألوا|اجمع|اجمعي|اجمعوا)",
219
+ "[وف]?(?:احصل|احصلي) على", "[وف]?(?:أعطني|اعطني|أعطنا|اعطنا|زودني|زوّدني|زودنا|زوّدنا|أخبرني|اخبرني|أخبرنا|اخبرنا)",
220
+ "[وف]?(?:أرسل|ارسل) (?:لي|لنا)",
221
+ ),
222
+ secrets: words(
223
+ "[وفبل]?(?:رقم|أرقام|ارقام) (?:ال)?بطاق\\p{L}*", "[وفبل]?بيانات (?:ال)?بطاق\\p{L}*", "[وفبل]?رمز (?:ال)?(?:أمان|امان|تحقق)\\p{L}*",
224
+ "[وفبل]?كلم(?:ة|ات) (?:ال)?(?:مرور|سر)\\p{L}*", "[وفبل]?(?:ال)?(?:رقم|رمز) السري", "رمز (?:cvv|pin)", "cvv", "cvc", "otp",
225
+ "رمز لمرة واحدة", "تاريخ انتهاء (?:صلاحية )?(?:ال)?بطاق\\p{L}*", "بيانات (?:تسجيل )?الدخول",
226
+ ),
227
+ negations: [words("[وف]?لا", "[وف]?لن", "[وف]?لم", "ليس", "أبدا", "أبداً", "ابدا", "دون", "بدون", "عدم", "ممنوع", "إياك", "اياك")],
228
+ },
229
+ {
230
+ code: "nl", name: "Dutch",
231
+ // Orders only: "vraagt" ("asks") describes the visitor asking, and "vraag" alone is also
232
+ // "question", so it counts only before its object.
233
+ asks: words(
234
+ "vraag (?:de|het|om|naar|hun|zijn|haar|uw|je|jouw|hem|hen)", "verzamel",
235
+ "laat (?:\\p{L}+ ){0,3}?(?:geven|noemen|invoeren|intypen|typen|sturen|opsturen|doorgeven|voorlezen|delen)",
236
+ "(?:geef|stuur|noem|deel|typ|voer|vul|lees|bevestig|zeg|vertel) (?:me|mij|ons)",
237
+ "(?:geef|stuur|noem|deel|typ|voer|vul|bevestig|zend) (?:je|jouw|uw|hun|zijn|haar|de|het)",
238
+ ),
239
+ secrets: words(
240
+ "wachtwoord(?:en)?", "\\p{L}*kaartnummer\\p{L}*", "\\p{L}*kaartgegevens", "pincode", "cvv2?", "cvc",
241
+ "beveiligingscode\\p{L}*", "verificatiecode\\p{L}*", "toegangscode\\p{L}*", "eenmalige code", "inloggegevens",
242
+ "bankgegevens", "herstelzin", "vervaldatum (?:van )?(?:de |je |uw )?kaart",
243
+ ),
244
+ negations: [words("niet", "nooit", "geen", "zonder", "verboden", "vermijd")],
245
+ },
246
+ {
247
+ code: "id", name: "Indonesian",
248
+ // Imperatives only: the "me-" forms ("meminta") describe someone asking.
249
+ asks: words(
250
+ "minta(?:lah)?", "tanyakan(?:lah)?", "kumpulkan", "kirim(?:kan|lah)?", "berikan(?:lah)?", "bagikan",
251
+ "masukkan(?:lah)?", "ketik(?:kan)?", "sebutkan", "beritahu(?:kan)?", "beri tahu",
252
+ ),
253
+ // "pin" alone is also a map pin, and "kartu kredit" alone is often how someone pays.
254
+ secrets: words(
255
+ "kata sandi", "sandi", "nomor kartu(?: kredit| debit| atm)?", "data kartu", "cvv2?", "cvc",
256
+ "kode (?:otp|verifikasi|keamanan|rahasia|akses|pin)", "otp", "frasa pemulihan", "pin (?:atm|kartu|anda|kamu)",
257
+ ),
258
+ negations: [words("jangan", "tidak", "bukan", "tanpa", "dilarang", "hindari", "tak")],
259
+ },
260
+ ];
261
+
262
+ // Sentences end at these marks in the scripts above, or at a line break. A Latin full stop
263
+ // ends a sentence only before a space or the end, so web addresses and abbreviations stay whole.
264
+ const ABBREV_DOT = /\b(?:e\.g|i\.e|etc|vs|incl|approx|et\s+al|fig|vol|rev|est|ref)\.(?=\s|$)|\bno\.(?=\s+\d)/gi;
265
+ const SENTENCE_END = /[.!?;]+(?=\s|$)|[。!?;؟।\n]+/u;
266
+ const PARA_END = /[.!?;]+(?=\s|$)|[。!?;؟।]+|\n\s*\n+|\n(?=\s*(?:[-*•+]|\d+[.)]|#)\s)/u;
267
+
268
+ function maskAbbreviations(text) {
269
+ const saved = [];
270
+ const hold = (m) => {
271
+ saved.push(m);
272
+ return `\u0000ABBR${saved.length - 1}\u0000`;
273
+ };
274
+ let masked = text.replace(/\([^()\n]{1,80}\)/g, (paren) =>
275
+ /\./.test(paren) ? paren.replace(/\.(?=\s)/g, hold) : paren,
276
+ );
277
+ masked = masked.replace(ABBREV_DOT, hold);
278
+ return { masked, unmask: (s) => s.replace(/\u0000ABBR(\d+)\u0000/g, (_, i) => saved[Number(i)]) };
279
+ }
280
+
281
+ function sentences(text) {
282
+ const { masked, unmask } = maskAbbreviations(text);
283
+ return masked.split(SENTENCE_END).map((s) => unmask(s).trim()).filter(Boolean);
284
+ }
285
+
286
+ // Soft-wrapped lines inside one paragraph (no blank line, no bullet) are joined so a
287
+ // line break mid-sentence does not hide a foreign request or split a short sentence.
288
+ function wrappedSentences(text) {
289
+ const { masked, unmask } = maskAbbreviations(text);
290
+ const joined = masked.replace(/([^\n.!?;:。!?;؟।])\n(?!\s*(?:[-*•+]|\d+[.)]|#)\s)/gu, "$1 ");
291
+ return joined.split(PARA_END).map((s) => unmask(s).replace(/\s+/g, " ").trim()).filter(Boolean);
292
+ }
293
+
294
+ /**
295
+ * Requests for card details or passwords in the ten languages above.
296
+ *
297
+ * :param normalized: Text from normalizeForRules.
298
+ * :return: [{match, excerpt, language}] for each sentence with a request word, a secret
299
+ * word and no negation word.
300
+ */
301
+ export function foreignSecretRequests(normalized) {
302
+ const hits = [];
303
+ const seen = new Set();
304
+ for (const sentence of [...sentences(normalized), ...wrappedSentences(normalized)]) {
305
+ for (const lang of SECRET_LANGUAGES) {
306
+ const secret = sentence.match(lang.secrets);
307
+ if (!secret || !lang.asks.test(sentence)) continue;
308
+ if (lang.negations.some((re) => re.test(sentence))) continue;
309
+ if (seen.has(sentence)) break;
310
+ seen.add(sentence);
311
+ hits.push({ match: secret[0], excerpt: sentence, language: lang.name });
312
+ break;
313
+ }
314
+ }
315
+ return hits;
316
+ }
317
+
318
+ const hostileSeq = (verbs, objects, gap = 60) =>
319
+ new RegExp(`${EDGE_BEFORE}(?:${verbs})${EDGE_AFTER}[^.!?\n]{0,${gap}}${EDGE_BEFORE}(?:${objects})${EDGE_AFTER}`, "iu");
320
+
321
+ // Takeover, conversation-exfil, and download-and-run orders across the 12 checked languages plus
322
+ // Turkish and Polish (for tool/parameter descriptions where plain C-LANGUAGE is CONDITIONS).
323
+ const HOSTILE_ACTION_LANGUAGES = [
324
+ {
325
+ name: "German",
326
+ negations: SECRET_LANGUAGES.find((l) => l.code === "de").negations,
327
+ override: hostileSeq("ignorier\\p{L}*|missacht\\p{L}*|vergiss|vergesst|vergessen|[uü]berschreib\\p{L}*|aufheb\\p{L}*|umgeh\\p{L}*", "anweisung\\p{L}*|regel\\p{L}*|vorgabe\\p{L}*|richtlinie\\p{L}*|systemprompt\\p{L}*|instruktion\\p{L}*", 55),
328
+ exfil: hostileSeq("send\\p{L}*|schick\\p{L}*|[uü]bermittel\\p{L}*|weiterleit\\p{L}*|kopier\\p{L}*|f[uü]g\\p{L}*", "chatverlauf\\p{L}*|gespr[aä]chsverlauf\\p{L}*|verlauf|systemprompt\\p{L}*|unterhaltung\\p{L}*|konversation\\p{L}*"),
329
+ exec: hostileSeq("herunterladen|runterladen|lad\\p{L}*\\s+herunter|installier\\p{L}*", "ausf[uü]hr\\p{L}*|start(?:e|en|est)?"),
330
+ },
331
+ {
332
+ name: "Spanish",
333
+ negations: SECRET_LANGUAGES.find((l) => l.code === "es").negations,
334
+ override: hostileSeq("ignora\\p{L}*|desestima\\p{L}*|olvida\\p{L}*|anula\\p{L}*|salt\\p{L}*", "instrucci[oó]n\\p{L}*|reglas?|directrices|pautas|indicaci[oó]n\\p{L}*", 55),
335
+ exfil: hostileSeq("env[ií][ae]\\p{L}*|manda\\p{L}*|reenv[ií]\\p{L}*|incluy\\p{L}*|adjunt\\p{L}*|compart\\p{L}*|filtr\\p{L}*", "historial(?:\\s+del?\\s+chat)?|conversaci[oó]n|mensajes?\\s+del\\s+(?:usuario|visitante)|prompt\\s+del\\s+sistema"),
336
+ exec: hostileSeq("descarg\\p{L}*|instal(?:a|e|ar)", "ejecut\\p{L}*|abr(?:e|ir|a)"),
337
+ },
338
+ {
339
+ name: "French",
340
+ negations: SECRET_LANGUAGES.find((l) => l.code === "fr").negations,
341
+ override: hostileSeq("ignor(?:ez|er|e(?:\\s+(?:les?|toutes?|ces?|vos?|tes?)))|oubli\\p{L}*|outrepass\\p{L}*|annul\\p{L}*|contourn\\p{L}*", "(?:les?\\s+|toutes?\\s+(?:les\\s+)?)?instructions?|r[eè]gles?|consignes?|directives?|(?:le|ce|ton|votre)\\s+prompt", 55),
342
+ exfil: hostileSeq("envoi\\p{L}*|envoy\\p{L}*|transmet\\p{L}*|partage\\p{L}*|copi\\p{L}*", "historique(?:\\s+(?:du\\s+)?chat)?|conversation|prompt\\s+syst[eè]me"),
343
+ exec: hostileSeq("t[eé]l[eé]charg\\p{L}*|installe(?:r|z)", "ex[eé]cut(?:er|ez|e\\s+(?:le|la|ce|un))|lanc(?:er|ez)"),
344
+ },
345
+ {
346
+ name: "Portuguese",
347
+ negations: SECRET_LANGUAGES.find((l) => l.code === "pt").negations,
348
+ override: hostileSeq("ignor\\p{L}*|esque[cç]\\p{L}*|anul\\p{L}*|desconsider\\p{L}*", "instru[cç][oõ]es|regras?|diretrizes|comandos", 55),
349
+ exfil: hostileSeq("envi\\p{L}*|mand\\p{L}*|compartilh\\p{L}*|encaminh\\p{L}*|copi\\p{L}*", "hist[oó]rico(?:\\s+d[oa]\\s+(?:chat|conversa))?|conversa|prompt\\s+do\\s+sistema"),
350
+ exec: hostileSeq("baix\\p{L}*|descarreg\\p{L}*|instal(?:e|ar|a)", "execut(?:e|ar|a)|rod(?:e|ar|a)"),
351
+ },
352
+ {
353
+ name: "Italian",
354
+ negations: SECRET_LANGUAGES.find((l) => l.code === "it").negations,
355
+ override: hostileSeq("ignor(?:a|i|are)|dimentic\\p{L}*|annull\\p{L}*|aggir\\p{L}*", "istruzioni|regole|direttive|(?:il|questo|tuo|vostro)\\s+prompt", 55),
356
+ exfil: hostileSeq("invi\\p{L}*|mand\\p{L}*|inoltr\\p{L}*|condivid\\p{L}*", "cronologia|storico(?:\\s+(?:della\\s+)?chat)?|conversazione|prompt\\s+di\\s+sistema"),
357
+ exec: hostileSeq("scaric\\p{L}*|install(?:a|are|i)", "esegu\\p{L}*|avvi\\p{L}*"),
358
+ },
359
+ {
360
+ name: "Polish",
361
+ negations: [words("nie", "nigdy", "bez", "zakaz", "unikaj")],
362
+ override: hostileSeq("zignoruj\\p{L}*|ignoruj\\p{L}*|pomi[nń]\\p{L}*|zapomnij\\p{L}*|nadpisz\\p{L}*", "instrukcj\\p{L}*|zasad\\p{L}*|regu[lł]\\p{L}*|poleceni\\p{L}*|wytyczn\\p{L}*", 55),
363
+ exfil: hostileSeq("wy[sś]lij\\p{L}*|prze[sś]lij\\p{L}*|przekaz\\p{L}*|udost[eę]pnij\\p{L}*|do[lł][aą]cz\\p{L}*", "histori[eęaą](?:\\s+(?:rozmow\\p{L}*|czat\\p{L}*))?|czat\\p{L}*|konwersacj\\p{L}*|prompt\\p{L}*"),
364
+ exec: hostileSeq("pobierz\\p{L}*|zainstaluj\\p{L}*", "uruchom\\p{L}*|wykonaj\\p{L}*"),
365
+ },
366
+ {
367
+ name: "Turkish",
368
+ negations: [words("de[gğ]il", "asla", "hi[cç]", "sak[iı]n", "yasak", "olmadan")],
369
+ override: hostileSeq("yok\\s*say\\p{L}*|g[oö]rmezden\\s+gel\\p{L}*|unut\\p{L}*|ge[cç]ersiz\\s+k[iı]l\\p{L}*", "talimat\\p{L}*|kural\\p{L}*|y[oö]nerge\\p{L}*", 55),
370
+ exfil: hostileSeq("g[oö]nder\\p{L}*|ilet\\p{L}*|aktar\\p{L}*|payla[sş]\\p{L}*", "sohbet\\s+ge[cç]mi[sş]\\p{L}*|konu[sş]ma\\s+ge[cç]mi[sş]\\p{L}*|sistem\\s+istem\\p{L}*"),
371
+ exec: hostileSeq("indir(?:ip)?|y[uü]kle(?:yip)?", "[cç]al[iı][sş]t[iı]r\\p{L}*|y[uü]r[uü]t\\p{L}*"),
372
+ },
373
+ {
374
+ name: "Russian",
375
+ negations: SECRET_LANGUAGES.find((l) => l.code === "ru").negations,
376
+ override: hostileSeq("игнорируй\\p{L}*|проигнорируй\\p{L}*|забудь\\p{L}*|отмени\\p{L}*", "инструкц\\p{L}*|правил\\p{L}*|указан\\p{L}*|системн\\p{L}*\\s+пром\\p{L}*", 55),
377
+ exfil: hostileSeq("отправь\\p{L}*|перешли\\p{L}*|слей\\p{L}*", "истори\\p{L}*\\s+(?:чат\\p{L}*|переписк\\p{L}*|диалог\\p{L}*)|системн\\p{L}*\\s+пром\\p{L}*"),
378
+ exec: hostileSeq("скачай\\p{L}*|загрузи\\p{L}*|установи\\p{L}*", "запусти\\p{L}*|выполни\\p{L}*"),
379
+ },
380
+ {
381
+ name: "Chinese",
382
+ negations: SECRET_LANGUAGES.find((l) => l.code === "zh").negations,
383
+ override: /(?:忽略|无视|無視|忘记|忘記|覆盖|覆蓋).{0,20}(?:指令|指示|规则|規則|提示词|提示詞)/iu,
384
+ exfil: /(?:发送|發送|转发|轉發|传给|傳給|泄露|洩露).{0,24}(?:聊天记录|聊天記錄|对话历史|對話歷史|系统提示|系統提示)/iu,
385
+ exec: /(?:下载|下載|安装|安裝).{0,24}(?:运行|運行|执行|執行)/iu,
386
+ },
387
+ {
388
+ name: "Japanese",
389
+ negations: SECRET_LANGUAGES.find((l) => l.code === "ja").negations,
390
+ override: /(?:指示|ルール|システムプロンプト).{0,20}(?:無視|忘れ)/iu,
391
+ exfil: /(?:会話履歴|チャット履歴|プロンプト).{0,20}(?:送信|転送|送っ)/iu,
392
+ exec: /(?:ダウンロード|インストール).{0,24}(?:実行|起動)/iu,
393
+ },
394
+ {
395
+ name: "Hindi",
396
+ negations: SECRET_LANGUAGES.find((l) => l.code === "hi").negations,
397
+ override: /(?:निर्देशों|नियमों).{0,24}(?:अनदेखा|भूल|नज़रअंदाज़)/iu,
398
+ exfil: /(?:चैट\s+इतिहास|वार्तालाप|सिस्टम\s+प्रॉम्प्ट).{0,24}(?:भेजें|साझा)/iu,
399
+ exec: /(?:डाउनलोड|इंस्टॉल).{0,24}(?:चलाएं|निष्पादित)/iu,
400
+ },
401
+ {
402
+ name: "Arabic",
403
+ negations: SECRET_LANGUAGES.find((l) => l.code === "ar").negations,
404
+ override: /(?:تجاهل|انسَ|انسى).{0,24}(?:التعليمات|القواعد|الأوامر)/iu,
405
+ exfil: /(?:أرسل|ارسل|مرر).{0,24}(?:سجل\s+المحادثة|المحادثة|موجه\s+النظام)/iu,
406
+ exec: /(?:نز[ّ]?ل|حم[ّ]?ل|ثب[ّ]?ت).{0,24}(?:شغ[ّ]?ل|نف[ّ]?ذ)/iu,
407
+ },
408
+ {
409
+ name: "Dutch",
410
+ negations: SECRET_LANGUAGES.find((l) => l.code === "nl").negations,
411
+ override: hostileSeq("negeer\\p{L}*|vergeet|vergeten|omzeil\\p{L}*|overschrijf\\p{L}*|negeren", "instructie\\p{L}*|regel\\p{L}*|richtlijn\\p{L}*|opdracht\\p{L}*|aanwijzing\\p{L}*|systeemprompt\\p{L}*", 55),
412
+ exfil: hostileSeq("stuur|verstuur|zend|verzend|deel (?:de|het|alle|je|uw)|kopieer|plak", "chatgeschiedenis|chatverloop|gespreksgeschiedenis|(?:volledige|hele) (?:gesprek|conversatie)|systeemprompt\\p{L}*"),
413
+ // Only Dutch forms: "download" and "open" are English words too.
414
+ exec: hostileSeq("downloaden|installeer\\p{L}*|installeren", "uitvoeren|voer (?:\\p{L}+ ){0,2}?uit|starten|openen"),
415
+ },
416
+ {
417
+ name: "Indonesian",
418
+ negations: SECRET_LANGUAGES.find((l) => l.code === "id").negations,
419
+ override: hostileSeq("abaikan\\p{L}*|lupakan\\p{L}*|langgar\\p{L}*|lewati", "instruksi|aturan|perintah|pedoman|petunjuk|prompt", 55),
420
+ exfil: hostileSeq("kirim\\p{L}*|teruskan|bagikan|salin", "riwayat (?:obrolan|percakapan|chat)|(?:seluruh|semua|isi) (?:percakapan|obrolan)|prompt sistem"),
421
+ exec: hostileSeq("unduh|pasang|instal(?:kan|lah)?", "jalankan|buka|eksekusi"),
422
+ },
423
+ ];
424
+
425
+ // A negation cancels a hostile order only when it governs it: inside the matched words or
426
+ // in the few words right before them. "…, nicht an den Nutzer" at the end of the sentence
427
+ // does not turn "Ignoriere alle vorherigen Anweisungen" round.
428
+ function negatesNear(lang, candidate, m) {
429
+ const start = Math.max(0, m.index - 30);
430
+ const window = candidate.slice(start, m.index + m[0].length);
431
+ return lang.negations.some((nre) => nre.test(window));
432
+ }
433
+
434
+ export function foreignHostileRequests(normalized, kind) {
435
+ const hits = [];
436
+ const seen = new Set();
437
+ for (const rawSentence of [...sentences(normalized), ...wrappedSentences(normalized)]) {
438
+ const joined = rawSentence.replace(/[()[\]]/g, " ").replace(/\s+/g, " ").trim();
439
+ for (const candidate of joined === rawSentence ? [rawSentence] : [rawSentence, joined]) {
440
+ for (const lang of HOSTILE_ACTION_LANGUAGES) {
441
+ const re = lang[kind];
442
+ if (!re) continue;
443
+ const m = candidate.match(re);
444
+ if (!m) continue;
445
+ if (negatesNear(lang, candidate, m)) continue;
446
+ if (seen.has(rawSentence)) break;
447
+ seen.add(rawSentence);
448
+ hits.push({ match: m[0], excerpt: rawSentence, language: lang.name });
449
+ break;
450
+ }
451
+ }
452
+ }
453
+ return hits;
454
+ }
455
+
456
+ function hasForeignHostileText(chunk) {
457
+ if (!chunk) return false;
458
+ if (foreignSecretRequests(chunk).length) return true;
459
+ for (const lang of HOSTILE_ACTION_LANGUAGES) {
460
+ if (lang.override?.test(chunk) || lang.exfil?.test(chunk) || lang.exec?.test(chunk)) return true;
461
+ }
462
+ return false;
463
+ }
464
+
465
+ // ---- Which language a sentence is in --------------------------------------------
466
+
467
+ // Common English function words. A sentence in English has several of them. "a" and
468
+ // "i" are left out: they are words in many languages (Spanish "a", Polish "i").
469
+ const ENGLISH = new Set(`the and of to in is it you that for on with as are be this your from at by or an not they we can
470
+ will if do what all their has have any when which who our us them about only never always should must would could there these
471
+ those then than into out up use its was were been how more other some such no so but may each also just me my he she his her
472
+ him where why does did here after before because while very please anything something everything nothing`.split(/\s+/));
473
+ // The same without words that are also common in other languages (Spanish "no" and "me",
474
+ // German "in" and "so", Dutch "is", Polish "to"), for weighing English against them.
475
+ const STRONG_ENGLISH = new Set([...ENGLISH].filter((w) => !["no", "me", "he", "in", "on", "so", "do", "to", "is", "as", "an"].includes(w)));
476
+
477
+ // Common function words of other languages written in Latin letters. Words that are also
478
+ // English words ("a", "in", "is", "do", "die"...) are left out, except German "die",
479
+ // which is far more common in German than in English instructions.
480
+ const LATIN_LANGUAGES = {
481
+ Spanish: "el la los las del al y que en por para con su sus es un una lo le les se como pero más este esta estos estas sin sobre cuando también usted ustedes tu tú muy hay ser está están cada todo todos todas nuestro nuestra siempre nunca qué cómo dónde porque ni ya aquí de",
482
+ Portuguese: "os um uma não para com por sua seu seus suas da dos das na nos nas em é mas ou você vocês ao aos pelo pela pelos pelas muito também sempre nunca cada este esta isso isto essa esse está estão são ser ter tem foi como quando onde porque já aqui lhe de se pode deve",
483
+ French: "le la les des du et est un une que qui pour dans sur avec pas ne il elle ils elles vous nous votre vos notre nos sa ses au aux ce cette ces mais ou où très leur leurs être sont été à y en se lui quand comme aussi tout tous toutes chaque jamais toujours ici de l qu j n c peut doit si",
484
+ Italian: "il lo gli la le un una uno è che non con del della dei delle degli nel nella nei nelle al alla ai alle sono suo sua suoi sue ma anche ti si ci questo questa questi queste molto sempre mai ogni tutto tutti tutte vostro vostra nostro nostra essere hanno ha di da tra fra quando dove perché già qui se l c dell all nell sull dall puoi può devi deve ho hai abbiamo sei siamo",
485
+ German: "der die das und ist nicht ein eine einen einem einer dem den des zu mit für auf sie ihr ihre ihren ihnen sich auch wie wenn oder aber bitte nach von bei dass daß werden wird kein keine sein seine seiner seinen ich wir uns unser unsere nur noch schon immer jeder jede jedes alle sind haben kann können soll sollen muss müssen im vom zum zur um dir dich mir mich du es nie niemals hier wo warum weil",
486
+ Dutch: "het een en van niet dat die voor met zijn op te je uw hij zij ze maar ook als bij naar om er wat wordt worden kan moet deze dit onze ons geen nooit altijd alle de mijn jouw hun hier waar waarom omdat",
487
+ Polish: "nie się że jest jak po co tak za od przez jego jej ich czy lub oraz dla ta te tylko już bardzo może są być aby który która które jeśli gdy proszę wszystkie zawsze nigdy na nas je potem teraz też także jeszcze twój twoja twoje pan pani bez przy przed pod albo",
488
+ Turkish: "ve bir bu için ile değil çok ne ama gibi daha sonra olarak mı mi şu lütfen ya veya kadar sizin bizim onun bunu şey da de ki hiç asla ziyaretçi ziyaretçiye ziyaretçiden müşteri müşteriden müşteriye kullanıcı sor sorun sorunun iste isteyin verin şifre şifresi şifresini şifrenizi güvenlik kredi kart kartı kartını numara numarasını kod kodu kodunu pin atm hesap hesabı onay gönder",
489
+ Indonesian: "dan yang di ke dari untuk dengan tidak ini itu adalah akan pada juga atau saya anda kami mereka kita sudah bisa harus tolong mohon jika kalau karena oleh sebagai ada telah jangan minta tanya tanyakan sebelum memesan pesan nomor kartu kredit pengunjung tamu kirim kirimkan berikan bagikan masukkan kata sandi kode keamanan pin atm rekening rahasia verifikasi tagihan",
490
+ Swahili: "na ya wa kwa ni za katika hii kama lakini sana hapa hiyo wako yako wewe sisi tafadhali pia au kwamba",
491
+ Tagalog: "ang ng sa mga ay hindi ko mo niya siya para ito iyan kayo tayo namin natin po ba lang din rin kung pag huwag",
492
+ Vietnamese: "và của là không có được cho một những các này với người bạn trong khi đã sẽ đó để thì nếu hãy vui lòng",
493
+ Romanian: "și în cu pe nu un este să din pentru sau dar mai ce acest această vă al ale lui ei sunt fi niciodată",
494
+ Czech: "se na je že jako pro nebo jsou být který která které jeho její jejich prosím také není nikdy",
495
+ Slovak: "sa na je že ako pre alebo sú byť ktorý ktorá ktoré jeho jej ich prosím aj nie nikdy",
496
+ Swedish: "och att det som en på är av med den har inte om ett jag du vi ni kan ska eller från vid vår er din ditt sin sitt aldrig alltid be fråga gäst gästen besökare besökaren kund kunden kort kortet kortnummer kortnumret kreditkort lösenord säkerhetskod nummer snälla",
497
+ Danish: "og det som en på er af med til den har ikke om et jeg du vi kan skal eller fra ved vores deres din dit sin sit hvis når aldrig altid bed spørg gæst gæsten besøgende kunde kunden kort kortet kortnummer kreditkort adgangskode sikkerhedskode nummer venligst",
498
+ Norwegian: "og det som en på er av med til den har ikke om et jeg du vi kan skal eller fra ved vår deres din ditt sin sitt hvis når aldrig altid spør be gjest gjesten besøgende kunde kunden kort kortet kortnummer kredittkort passord sikkerhetskode nummer vennligst",
499
+ Finnish: "ja ei se että oli mutta kun niin jos kuin tai myös ole olla sinun teidän meidän hänen heidän tämä tuo nämä joka mikä kaikki vain nyt koskaan aina",
500
+ Hungarian: "az és hogy nem egy meg csak mint el ez azt ezt vagy kell már még sem nagyon minden kérem kérjük ön önt soha mindig",
501
+ Croatian: "je da se na za od su ne sa kao ali ili što koji koja koje vas vaš vaša molimo može mora nije biti nikada uvijek",
502
+ Albanian: "dhe në të një për nga që është nuk ju ose por edhe si kurrë",
503
+ Catalan: "els les que amb una és dels seu seva però més aquest aquesta també mai sempre",
504
+ Afrikaans: "die en van het nie wat op te vir met sy hy ons julle jou maar ook kan sal moet nooit altyd",
505
+ Estonian: "ja ei et oli aga kui siis kas või ka teie meie tema nende kõik ainult mitte kunagi alati",
506
+ Hausa: "da ba na ya ta ga cikin wannan kuma amma don shi ita su ku mu ne ce kada",
507
+ Zulu: "futhi ukuthi kodwa uma noma ngoba wena thina bona ngicela cela isivakashi ikhasimende amakhasimende inombolo ikhadi yekhadi lasebhange ebhange iphasiwedi ikhodi iphinikhodi ye le ne",
508
+ Somali: "iyo waan waa in uu ay ku ka la ma ahay tahay yahay si aad uga waxaa waxa weydii martida lambarka kaarka bangiga sirta furaha lacagta fadlan",
509
+ Latvian: "un ir uz par ar kas ka lai bet vai jā nē es tu viņš viņa mēs jūs viņi šis tas tā kā arī pie līdz pēc savu mūsu jūsu lūdzu nav būs bija var ja kad tikai vēl jau ļoti visi kur",
510
+ Lithuanian: "ir kad bet su į iš ne tai kaip jo jos jūs mes aš tu šis ta tas ar prašome prašau apie nuo už kas kur labai dar jau yra buvo bus savo mūsų jūsų jei kai tik visi",
511
+ // Hindi and Urdu as many people type them, in Latin letters ("card ka number poochho").
512
+ "Hindi written in Latin letters": "hai hain ka ki ke ko se mein aur ya nahi nahin kya kyun kaise kab kahan yeh ye woh wo unka unki unke apna apni apne uska uski uske mera meri mere tera teri tum aap hum kar karo karein karna kijiye dijiye batao bataiye poocho poochho puchho puchiye lijiye ho hota hoti tha thi raha rahi wala wali bhi sirf abhi jab tab agar toh liye liya gaya gayi chahiye sakte sakta sakti",
513
+ };
514
+ const LATIN_WORDS = Object.entries(LATIN_LANGUAGES).map(([name, list]) => [name, new Set(list.split(/\s+/))]);
515
+
516
+ // Scripts other than Latin, with the language a reader would name. Scripts written
517
+ // without spaces between words count each character as half a word.
518
+ const SCRIPTS = [
519
+ ["Hiragana", "Japanese", true], ["Katakana", "Japanese", true], ["Han", "Chinese", true], ["Hangul", "Korean", true],
520
+ ["Thai", "Thai", true], ["Lao", "Lao", true], ["Khmer", "Khmer", true], ["Myanmar", "Burmese", true], ["Tibetan", "Tibetan", true],
521
+ ["Cyrillic", "Cyrillic script (such as Russian)", false], ["Greek", "Greek", false],
522
+ ["Arabic", "Arabic script (such as Arabic, Persian or Urdu)", false], ["Hebrew", "Hebrew", false],
523
+ ["Devanagari", "Devanagari script (such as Hindi)", false], ["Bengali", "Bengali", false], ["Tamil", "Tamil", false],
524
+ ["Telugu", "Telugu", false], ["Kannada", "Kannada", false], ["Malayalam", "Malayalam", false], ["Gujarati", "Gujarati", false],
525
+ ["Gurmukhi", "Punjabi", false], ["Oriya", "Odia", false], ["Sinhala", "Sinhala", false], ["Georgian", "Georgian", false],
526
+ ["Armenian", "Armenian", false], ["Ethiopic", "Ethiopic script (such as Amharic)", false], ["Thaana", "Dhivehi", false],
527
+ ].map(([script, name, dense]) => ({ name, dense, re: new RegExp(`\\p{Script=${script}}`, "gu") }));
528
+
529
+ // A Latin word: a Latin letter, then letters and accents. Accents alone (Hindi vowel
530
+ // signs are accents too) do not make a word.
531
+ const LATIN_WORD = /\p{Script=Latin}[\p{Script=Latin}\p{M}]*/gu;
532
+
533
+ // The name used for a sentence that is not English, in no language the lists know.
534
+ export const UNRECOGNISED = "a language Agent Customs doesn't recognise";
535
+
536
+ // Addresses, URIs, regexes, JSON snippets, file names and code identifiers are not
537
+ // words of any language.
538
+ const NOT_WORDS = new RegExp([
539
+ /[a-z][a-z0-9+.-]*:\/\/\S+/.source,
540
+ /\b[\w.+-]+@[\w-]+\.[\w.-]+/.source,
541
+ /\b[\w-]+\.(?:com|org|net|io|dev|app|ai|ae|de|fr|nl|uk|eu|ru|jp|cn|br|au|ca|me|co|edu|gov|info|xyz|cloud|agency|now|ad|ml|json|yaml|yml|toml|html|htm|xml|svg|png|jpg|jpeg|webp|js|mjs|ts|tsx|jsx|py|rb|go|rs|java|cpp|css|md|txt|csv|pdf|zip|sh|sql)\b/.source,
542
+ /\{[^{}\n"]{0,300}"[^"\n]{1,60}"\s*:[^}\n]{0,300}\}/.source,
543
+ /\[(?:[^\]\s\\]|\\.)+\]/.source,
544
+ /<\/?[a-zA-Z0-9_-]+[^>\n]{0,120}>|\{\{[^}\n]{1,120}\}\}/.source,
545
+ /`[a-z0-9_.:\/-]+`/.source,
546
+ /\b\w*_\w*\b|\b0x[0-9a-f]+\b/.source,
547
+ /\b(?:e\.g|i\.e|etc|vs|incl|approx|et\s+al)\.?(?=\s|,|;|:|\)|$)/.source,
548
+ ].join("|"), "gi");
549
+
550
+ // Whitespace chunks containing digits, code operators/delimiters, dotted identifiers,
551
+ // camelCase, or locale tags like "pt-PT" are technical tokens rather than prose words.
552
+ const CODE_CHUNK = /\d|[\\/_:=+*^~@#$%&<>{}[\]]|\p{Ll}\p{Lu}|\p{L}\.\p{L}|^[a-z]{1,3}-[A-Z]{2,}$/u;
553
+ const OUTER_PUNCT = /^[,.;:!?()'"“”‘’«»—–]+|[,.;:!?()'"“”‘’«»—–]+$/g;
554
+
555
+ // A list of short items, such as "Menu: tapas, paella de marisco, churros con chocolate":
556
+ // dish and product names are often foreign words, so lists are not judged as sentences.
557
+ function looksLikeList(sentence) {
558
+ const items = sentence.split(/[,:;|\/]|\s(?:and|or|&)\s/i).map((s) => s.trim()).filter(Boolean);
559
+ const separators = (sentence.match(/[,:;|\/]/g) || []).length;
560
+ return separators >= 2 && items.every((item) => item.split(/\s+/).length <= 4);
561
+ }
562
+
563
+ function extractProse(sentence) {
564
+ // Expand English n't contractions and strip 's/'m/'re/'ve/'ll/'d endings so contractions count as English.
565
+ const cleaned = sentence.replace(NOT_WORDS, " ")
566
+ .replace(/\bcan't\b/gi, "can")
567
+ .replace(/\bwon't\b/gi, "will")
568
+ .replace(/\b([a-z]+)n't\b/gi, "$1")
569
+ .replace(/'(?:m|s|t|re|ve|ll|d)\b/gi, "");
570
+ const prose = cleaned.split(/\s+/).map((c) => c.replace(OUTER_PUNCT, "")).filter((c) => c && !CODE_CHUNK.test(c)).join(" ");
571
+ const tokens = [...prose.matchAll(LATIN_WORD)].map((m) => m[0]);
572
+ return { cleaned, tokens, latin: tokens.map((w) => w.toLowerCase()) };
573
+ }
574
+
575
+ // Short glosses in brackets ("(prévisions du jour)") and short quoted examples ("3,2 tấn")
576
+ // inside an English sentence. A quoted full sentence is not an example: it is judged as text.
577
+ function stripInlineExamples(sentence) {
578
+ const removed = [];
579
+ let parenGroups = 0;
580
+ let parenWords = 0;
581
+ const parenRemoved = [];
582
+ const afterParens = sentence.replace(/\([^()\n]{1,70}\)/g, (m) => {
583
+ const inner = m.slice(1, -1).trim();
584
+ if (/https?:\/\//i.test(inner) || hasForeignHostileText(inner)) return m;
585
+ const words = fragmentWords(inner);
586
+ if (words > 5) return m;
587
+ parenGroups += 1;
588
+ parenWords += words;
589
+ parenRemoved.push(inner);
590
+ return " ";
591
+ });
592
+ const keepParens = parenGroups <= 2 && parenWords <= 6;
593
+ let out = keepParens ? afterParens : sentence;
594
+ if (keepParens) removed.push(...parenRemoved);
595
+
596
+ let quoteGroups = 0;
597
+ let quoteWords = 0;
598
+ const quoteRemoved = [];
599
+ const afterQuotes = out.replace(/"[^"\n]{1,90}"|'[^'\n]{1,90}'|«[^»\n]{1,90}»|“[^”\n]{1,90}”/g, (m) => {
600
+ const inner = m.slice(1, -1).trim();
601
+ if (/https?:\/\//i.test(inner) || hasForeignHostileText(inner)) return m;
602
+ const words = fragmentWords(inner);
603
+ if (words > 4) return m;
604
+ quoteGroups += 1;
605
+ quoteWords += words;
606
+ quoteRemoved.push(inner);
607
+ return " ";
608
+ });
609
+ if (quoteGroups <= 4 && quoteWords <= 10) {
610
+ out = afterQuotes;
611
+ removed.push(...quoteRemoved);
612
+ }
613
+ return { text: out, removed };
614
+ }
615
+
616
+ // Words in a fragment: whitespace-separated pieces with a letter, and two characters of a
617
+ // script written without spaces (Chinese, Japanese, Thai …) for one word.
618
+ function fragmentWords(fragment) {
619
+ const spaced = fragment.split(/\s+/).filter((w) => /\p{L}/u.test(w)).length;
620
+ const dense = (fragment.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/gu) || []).length;
621
+ return Math.max(spaced, Math.round(dense / 2));
622
+ }
623
+
624
+ // The language of a short fragment (an example or gloss), when it is clearly not English:
625
+ // a few letters of another script, or two or more lower-case foreign words with no English.
626
+ // Single words, codes ("en, de") and names ("Diário da República") do not count.
627
+ function foreignFragmentLanguage(fragment) {
628
+ let best = null;
629
+ for (const script of SCRIPTS) {
630
+ const letters = (fragment.match(script.re) || []).length;
631
+ if (letters >= 2 && (!best || letters > best.letters)) best = { name: script.name, letters };
632
+ }
633
+ if (best) return best.name;
634
+ const { tokens } = extractProse(fragment);
635
+ const words = tokens.filter((w) => w.length > 2 && !/^\p{Lu}/u.test(w)).map((w) => w.toLowerCase());
636
+ if (words.length < 2) return null;
637
+ const english = words.filter((w) => STRONG_ENGLISH.has(w) || isEnglishWord(w)).length;
638
+ if (english > 0) return null;
639
+ let top = null;
640
+ for (const [name, set] of LATIN_WORDS) {
641
+ const count = tokens.map((w) => w.toLowerCase()).filter((w) => set.has(w)).length;
642
+ if (!top || count > top.count) top = { name, count };
643
+ }
644
+ const accents = /[^\x00-\x7f]/.test(words.join(""));
645
+ if (top.count >= 1 || accents) return top.count ? top.name : UNRECOGNISED;
646
+ return null;
647
+ }
648
+
649
+ const QUOTED_TOOL_EXAMPLE_LINE = /^\s*(?:[-*•>→]+\s*)?(['"])([^'"\n]{1,100})\1\s*(?:→|->|=>|:)\s*[a-z_][a-z0-9_]*\s*\(/i;
650
+
651
+ /**
652
+ * The language a sentence is written in, when it is not clearly English.
653
+ *
654
+ * In this order:
655
+ * - most of it is in another script (three words or more): that script's language;
656
+ * - its Latin words include at least three common words of a listed language, a fifth of
657
+ * all its words, and more than twice as many as English ones: that language, so foreign
658
+ * names inside English sentences ("Café de la Paix") do not count;
659
+ * - six or more words (or accented unknown words) that are not a list, with no common
660
+ * English word ("the", "and", "with" ...), fewer than half of them English words, and
661
+ * a sign of another language (accented letters, or a common word of a listed language):
662
+ * that language, or one the lists don't know. Technical tokens, regexes, URIs and
663
+ * acronyms don't count either way.
664
+ *
665
+ * :param sentence: One sentence of cleaned text.
666
+ * :return: The language's name, or null for English or too little text to tell.
667
+ */
668
+ export function otherLanguageOf(sentence) {
669
+ const detail = otherLanguageDetail(sentence);
670
+ return detail && !detail.soft ? detail.language : null;
671
+ }
672
+
673
+ /**
674
+ * The same, with short examples kept visible: an English sentence whose only foreign words
675
+ * are a short gloss, a quoted example or a quoted sample query comes back as
676
+ * {language, soft: true}, so it is reported as a note rather than silently ignored.
677
+ *
678
+ * :param sentence: One sentence of cleaned text.
679
+ * :return: {language, soft} or null.
680
+ */
681
+ export function otherLanguageDetail(sentence) {
682
+ // A short quoted sample query (<= 8 words) pointing at a tool call in English documentation.
683
+ // Quotes in a checked language were just checked for secret requests and takeover orders;
684
+ // one in a language Agent Customs cannot check is a note, not a hold.
685
+ const qm = sentence.match(QUOTED_TOOL_EXAMPLE_LINE);
686
+ if (qm) {
687
+ const qInner = qm[2].trim();
688
+ if (fragmentWords(qInner) <= 8 && !hasForeignHostileText(qInner) && !/https?:\/\//i.test(qInner)) {
689
+ const lang = foreignFragmentLanguage(qInner);
690
+ return lang && !CHECKED_LANGUAGES.has(lang) ? { language: lang, soft: true } : null;
691
+ }
692
+ }
693
+
694
+ // If short glosses in brackets or short quoted examples sit inside an English sentence,
695
+ // judge the English sentence around them. Glosses in a checked language were checked before
696
+ // they were set aside (stripInlineExamples); one in another language is a note.
697
+ let probe = sentence;
698
+ let softLanguage = null;
699
+ const stripped = stripInlineExamples(sentence);
700
+ if (stripped.text !== sentence) {
701
+ const outer = extractProse(stripped.text);
702
+ const outerLatinStr = outer.latin.join("");
703
+ const outerScript = scriptOf(stripped.text);
704
+ if (outer.latin.length >= 3 && !/[^\x00-\x7f]/.test(outerLatinStr) && !(outerScript && outerScript.units >= 3)) {
705
+ const outerEngKnown = outer.latin.filter((w) => ENGLISH.has(w) || isEnglishWord(w)).length;
706
+ const outerCandidates = [...new Set(outer.tokens.filter((w) => !/^\p{Lu}{2,}$/u.test(w)).map((w) => w.toLowerCase()))];
707
+ const maxOuterForeign = LATIN_WORDS.reduce((m, [, set]) => Math.max(m, outerCandidates.filter((w) => set.has(w)).length), 0);
708
+ if (outerEngKnown >= 1 && maxOuterForeign < 2) {
709
+ probe = stripped.text;
710
+ softLanguage = stripped.removed.map(foreignFragmentLanguage).find((l) => l && !CHECKED_LANGUAGES.has(l)) || null;
711
+ }
712
+ }
713
+ }
714
+
715
+ const best = scriptOf(probe);
716
+ if (best && best.units >= 3) return { language: best.name, soft: false };
717
+ const { cleaned: text, tokens, latin } = extractProse(probe);
718
+ const verdict = judgeLatin(text, tokens, latin);
719
+ if (verdict) return { language: verdict, soft: false };
720
+ return softLanguage ? { language: softLanguage, soft: true } : null;
721
+ }
722
+
723
+ // The non-Latin script most of a text is written in, weighed in words.
724
+ function scriptOf(text) {
725
+ let best = null;
726
+ for (const script of SCRIPTS) {
727
+ const letters = (text.match(script.re) || []).length;
728
+ if (!letters) continue;
729
+ const units = script.dense ? letters / 2 : letters / 5;
730
+ if (!best || units > best.units) best = { name: script.name, units };
731
+ }
732
+ // Japanese mixes kana with Chinese characters: any kana makes it Japanese.
733
+ if (best && best.name === "Chinese" && /[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(text)) best.name = "Japanese";
734
+ return best;
735
+ }
736
+
737
+ function judgeLatin(text, tokens, latin) {
738
+ const english = latin.filter((w) => STRONG_ENGLISH.has(w)).length;
739
+ const candidateWords = [...new Set(tokens.filter((w) => !/^\p{Lu}{2,}$/u.test(w)).map((w) => w.toLowerCase()))];
740
+ let top = null;
741
+ for (const [name, set] of LATIN_WORDS) {
742
+ const count = candidateWords.filter((w) => set.has(w)).length;
743
+ if (!top || count > top.count) top = { name, count };
744
+ }
745
+ const hasAccents = /[^\x00-\x7f]/.test(latin.join(""));
746
+ // Lists of short ASCII codes (e.g. locale tags "Locale (e.g. en, de, fr)") are not prose.
747
+ const twoCharCount = tokens.filter((w) => w.length <= 2).length;
748
+ if (!hasAccents && english === 0 && (text.match(/[,|\/]/g) || []).length >= 2 && twoCharCount >= 3 && tokens.length - twoCharCount <= 2) {
749
+ return null;
750
+ }
751
+ if (!hasAccents && english === 0 && looksLikeList(text) && tokens.length >= 2 && tokens.every((w) => w.length <= 3)) {
752
+ return null;
753
+ }
754
+ // For 3-word Latin phrases with non-ASCII letters, hold only when clearly non-English prose
755
+ // (>= 2 words from a known language list, or an explicit foreign request/secret term), leaving
756
+ // short menu dishes ("Crème brûlée maison.") and brief greetings ("Grüße aus München!") clear.
757
+ if (latin.length === 3) {
758
+ if (english === 0 && !looksLikeList(text) && hasAccents) {
759
+ const judged3 = tokens.filter((word, i) => !(i > 0 && /^\p{Lu}/u.test(word)) && !/^\p{Lu}{2,}$/u.test(word))
760
+ .map((w) => w.toLowerCase());
761
+ const known3 = judged3.filter((w) => ENGLISH.has(w) || isEnglishWord(w)).length;
762
+ if (judged3.length >= 2 && known3 === 0 && top.count >= 2) return top.name;
763
+ }
764
+ return null;
765
+ }
766
+ if (latin.length < 4) return null;
767
+ const minCount = latin.length < 12 ? 2 : 3;
768
+ const minRatio = latin.length < 12 ? 0.3 : 0.2;
769
+ if (top.count >= minCount && top.count >= minRatio * Math.max(candidateWords.length, 1) && top.count > 2 * english) return top.name;
770
+ // Not clearly English, whatever the language.
771
+ if (english > 0 || looksLikeList(text)) return null;
772
+ const judged = tokens.filter((word, i) => !(i > 0 && /^\p{Lu}/u.test(word)) && !/^\p{Lu}{2,}$/u.test(word) && !/\p{Ll}\p{Lu}/u.test(word))
773
+ .map((word) => word.toLowerCase());
774
+ if (judged.length < 4) return null;
775
+ const known = judged.filter((word) => ENGLISH.has(word) || isEnglishWord(word)).length;
776
+ if (known >= 0.5 * judged.length) return null;
777
+ const realKnown = judged.filter((word) => word.length > 1 && (ENGLISH.has(word) || isEnglishWord(word))).length;
778
+ const distinctJudged = new Set(judged).size;
779
+ const englishSuffixes = judged.filter((word) => /^[a-z]{4,}(?:ing|ed|tion|ment|ness|able|ible|ive|ize|ise)$/i.test(word)).length;
780
+ const foreignSign = hasAccents || top.count >= 2 || (realKnown === 0 && distinctJudged >= 6 && englishSuffixes < 2);
781
+ if (!foreignSign) return null;
782
+ if (judged.length < 6 && realKnown > 0) return null;
783
+ if (top.count < 2 && (distinctJudged < 6 || englishSuffixes >= 2) && !(hasAccents && known === 0 && realKnown === 0)) return null;
784
+ return top.count >= 2 ? top.name : UNRECOGNISED;
785
+ }
786
+
787
+ /**
788
+ * Sentences written in another language than English.
789
+ *
790
+ * :param normalized: Text from normalizeForRules.
791
+ * :return: [{match, excerpt, language}], one per sentence, with the language's name as
792
+ * the match.
793
+ */
794
+ export function otherLanguageSentences(normalized) {
795
+ const hits = [];
796
+ const seen = new Set();
797
+ for (const sentence of [...sentences(normalized), ...wrappedSentences(normalized)]) {
798
+ if (seen.has(sentence)) continue;
799
+ const detail = otherLanguageDetail(sentence);
800
+ if (detail) {
801
+ seen.add(sentence);
802
+ hits.push({ match: detail.language, excerpt: sentence, language: detail.language, soft: detail.soft,
803
+ words: foreignWordCount(sentence) });
804
+ }
805
+ }
806
+ return hits;
807
+ }
808
+
809
+ // How many words of a sentence are not English: Latin words that are not English words, words
810
+ // in other scripts, and two characters of Chinese or Japanese for one word.
811
+ function foreignWordCount(sentence) {
812
+ const { tokens } = extractProse(sentence);
813
+ const latinForeign = tokens.filter((w) => !ENGLISH.has(w.toLowerCase()) && !isEnglishWord(w.toLowerCase())).length;
814
+ const dense = (sentence.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/gu) || []).length;
815
+ const otherScripts = (sentence.match(/(?:(?![\p{Script=Latin}\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}])\p{L})+/gu) || []).length;
816
+ return latinForeign + otherScripts + Math.round(dense / 2);
817
+ }
818
+
819
+ // Languages whose requests for secrets and takeover orders are checked word by word (above),
820
+ // with the script names used when only the script is known (Cyrillic is read as Russian,
821
+ // Arabic script as Arabic, Devanagari as Hindi). Text in any other language is only seen as
822
+ // "not English".
823
+ export const CHECKED_LANGUAGES = new Set([
824
+ ...SECRET_LANGUAGES.map((l) => l.name),
825
+ "Cyrillic script (such as Russian)", "Arabic script (such as Arabic, Persian or Urdu)", "Devanagari script (such as Hindi)",
826
+ ]);