From ca8017504dd8bf6b5f6f0829ee4b30a5ad5c2d28 Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 26 Nov 2026 22:58:32 -0600 Subject: [PATCH 01/11] test(mail): cover the mail text helpers Unit tests for base64ToBytes, utf8Decode and decodeBase64Text, decodeEntities, htmlToText, plainText, clip and splitAddresses, with made-up people and example.com addresses. oneLine() stays out (its own issue) and text.ts is unchanged. Closes #37 --- packages/mail/test/text.test.ts | 137 ++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 packages/mail/test/text.test.ts diff --git a/packages/mail/test/text.test.ts b/packages/mail/test/text.test.ts new file mode 100644 index 0000000..bcfe4a7 --- /dev/null +++ b/packages/mail/test/text.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from "vitest"; +import { base64ToBytes, clip, decodeBase64Text, decodeEntities, htmlToText, plainText, splitAddresses, utf8Decode } from "../src/text.ts"; + +// FR-MAIL-02: the helpers that turn Gmail, Outlook and IMAP bodies into plain text. Made-up people and example.com only. +const bytes = (...b: number[]) => new Uint8Array(b); + +describe("base64ToBytes", () => { + it("reads plain base64", () => { + expect(base64ToBytes("SG9sYQ==")).toEqual(bytes(0x48, 0x6f, 0x6c, 0x61)); + }); + + it("reads base64url, with - and _ in place of + and /", () => { + expect(base64ToBytes("-_8")).toEqual(bytes(0xfb, 0xff)); + expect(base64ToBytes("-_8")).toEqual(base64ToBytes("+/8=")); + }); + + it("skips padding and line breaks", () => { + expect(base64ToBytes("SG9s\r\nYSBB\nbmE=\n")).toEqual(base64ToBytes("SG9sYSBBbmE")); + expect(new TextDecoder().decode(base64ToBytes("SG9s\r\nYSBB\nbmE=\n"))).toBe("Hola Ana"); + }); +}); + +describe("utf8Decode and decodeBase64Text", () => { + it("decodes Spanish accents and ñ", () => { + expect(utf8Decode(bytes(0x61, 0xc3, 0xb1, 0x6f, 0x20, 0x63, 0x61, 0x6d, 0x69, 0xc3, 0xb3, 0x6e))).toBe("año camión"); + expect(decodeBase64Text("TWHDsWFuYSB2ZW5nbyBhIGxhIHJldW5pw7NuLg==")).toBe("Mañana vengo a la reunión."); + }); + + it("decodes a four-byte character", () => { + expect(utf8Decode(bytes(0xf0, 0x9f, 0xa6, 0x80))).toBe("🦀"); + expect(decodeBase64Text("8J+mgA")).toBe("🦀"); + }); + + it("turns a broken sequence into U+FFFD instead of throwing", () => { + expect(utf8Decode(bytes(0x61, 0xc3, 0x28))).toBe("a�("); + expect(utf8Decode(bytes(0xff, 0x62))).toBe("�b"); + }); +}); + +describe("decodeEntities", () => { + it("decodes named references", () => { + expect(decodeEntities("María & José: mañana a las 3")).toBe("María & José: mañana a las 3"); + expect(decodeEntities("árbol")).toBe("árbol"); + }); + + it("decodes decimal and hex references", () => { + expect(decodeEntities("señor")).toBe("señor"); + expect(decodeEntities("señor y señora")).toBe("señor y señora"); + }); + + it("leaves an unknown name as it is", () => { + expect(decodeEntities("¬aname; y &")).toBe("¬aname; y &"); + }); +}); + +describe("htmlToText", () => { + it("drops script, style, head and title with their contents", () => { + const html = + "Asunto" + + "

Hola Ana

"; + expect(htmlToText(html)).toBe("Hola Ana"); + }); + + it("drops comments", () => { + expect(htmlToText("

Hola Luis

")).toBe("Hola Luis"); + }); + + it("breaks lines at br, p, div, li and headings", () => { + const html = "

Agenda

Uno
Dos
Tres

Cuatro

Fin

"; + expect(htmlToText(html)).toBe("Agenda\nUno\nDos\nTres\nCuatro\nCinco\nSeis\nFin"); + }); + + it("leaves no blank lines", () => { + const text = htmlToText("

Hola

\n\n

 

\r\n

Chao

"); + expect(text).toBe("Hola\nChao"); + expect(text.split("\n").every((l) => l.trim())).toBe(true); + }); +}); + +describe("plainText", () => { + it("turns CRLF into LF", () => { + expect(plainText("Hola\r\nAna\r\n")).toBe("Hola\nAna"); + }); + + it("collapses runs of spaces", () => { + expect(plainText("Hola Ana,\t\tnos vemos")).toBe("Hola Ana, nos vemos"); + }); + + it("keeps at most one blank line in a row", () => { + expect(plainText("Hola\n\n\n\nAna\n\n\nChao")).toBe("Hola\n\nAna\n\nChao"); + expect(plainText("Hola\r\n\r\n\r\n\r\nAna")).toBe("Hola\n\nAna"); + }); +}); + +describe("clip", () => { + it("leaves text at or under the limit unchanged", () => { + expect(clip("Hola Ana", 8)).toBe("Hola Ana"); + expect(clip("Hola", 8)).toBe("Hola"); + }); + + it("cuts longer text and ends it with ...", () => { + const cut = clip("Nos vemos el lunes en la oficina", 12); + expect(cut).toBe("Nos vemos..."); + expect(cut.length).toBeLessThanOrEqual(12); + }); + + it("leaves no space before the ...", () => { + expect(clip("uno dos tres", 7)).toBe("uno..."); + expect(clip("uno dos tres", 7)).not.toMatch(/\s\.\.\.$/); + }); +}); + +describe("splitAddresses", () => { + it("splits at commas between addresses", () => { + expect(splitAddresses("Ana Torres , luis@example.com")).toEqual(["Ana Torres ", "luis@example.com"]); + }); + + it("doesn't split at a comma inside quotes", () => { + expect(splitAddresses("\"Pérez, Luis\" , Ana ")).toEqual([ + "\"Pérez, Luis\" ", + "Ana ", + ]); + }); + + it("doesn't split at a comma inside angle brackets", () => { + expect(splitAddresses("Ana , Luis ")).toEqual([ + "Ana ", + "Luis ", + ]); + }); + + it("gives an empty list for an empty or missing header", () => { + expect(splitAddresses("")).toEqual([]); + expect(splitAddresses(undefined)).toEqual([]); + expect(splitAddresses(" , ")).toEqual([]); + }); +}); From 8f256a084514b9c796d29b49c9820556f7d2dc61 Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 26 Nov 2026 23:04:58 -0600 Subject: [PATCH 02/11] fix(mail): refuse overlong UTF-8 and encoded surrogates utf8Decode() decoded overlong sequences (C0 80 to U+0000) and encoded surrogates (ED A0 80 to a lone U+D800). Only the shortest form is UTF-8 and it never encodes U+D800 to U+DFFF (RFC 3629), so each byte of such a sequence now becomes U+FFFD, as a standard decoder answers. The vault's decoder in packages/core already refuses both. Closes #142 --- packages/mail/src/text.ts | 6 +++- packages/mail/test/utf8-decode.test.ts | 38 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 packages/mail/test/utf8-decode.test.ts diff --git a/packages/mail/src/text.ts b/packages/mail/src/text.ts index e006905..1270d7a 100644 --- a/packages/mail/src/text.ts +++ b/packages/mail/src/text.ts @@ -20,6 +20,9 @@ export function base64ToBytes(text: string): Uint8Array { return out.slice(0, o); } +/** The smallest code point each sequence length may carry, by the number of continuation bytes. */ +const MIN_CODE_POINT = [0, 0x80, 0x800, 0x10000]; + /** UTF-8 bytes to text; a malformed sequence becomes U+FFFD instead of throwing. */ export function utf8Decode(bytes: Uint8Array): string { let out = ""; @@ -46,7 +49,8 @@ export function utf8Decode(bytes: Uint8Array): string { } cp = (cp << 6) | (c & 0x3f); } - if (!ok || cp > 0x10ffff) { + // Only the shortest form is UTF-8, and it never encodes the surrogates U+D800 to U+DFFF (RFC 3629). + if (!ok || cp < MIN_CODE_POINT[need]! || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) { out += "�"; i++; continue; diff --git a/packages/mail/test/utf8-decode.test.ts b/packages/mail/test/utf8-decode.test.ts new file mode 100644 index 0000000..51b32d6 --- /dev/null +++ b/packages/mail/test/utf8-decode.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { utf8Decode } from "../src/text.ts"; + +// #142: only the shortest form is UTF-8 (RFC 3629), and it never encodes U+D800 to U+DFFF. Each byte of such a +// sequence becomes U+FFFD, the same answer a standard decoder gives. +const decode = (...b: number[]) => utf8Decode(new Uint8Array(b)); +const standard = (...b: number[]) => new TextDecoder().decode(new Uint8Array(b)); + +describe("utf8Decode refuses what isn't UTF-8", () => { + it("turns overlong encodings into U+FFFD", () => { + expect(decode(0xc0, 0x80)).toBe("��"); + expect(decode(0xc1, 0x81)).toBe("��"); + expect(decode(0xe0, 0x80, 0x80)).toBe("���"); + expect(decode(0xe0, 0x9f, 0xbf)).toBe("���"); + expect(decode(0xf0, 0x80, 0x80, 0x80)).toBe("����"); + expect(decode(0xf0, 0x8f, 0xbf, 0xbf)).toBe("����"); + }); + + it("turns encoded surrogates into U+FFFD", () => { + expect(decode(0xed, 0xa0, 0x80)).toBe("���"); + expect(decode(0xed, 0xbf, 0xbf)).toBe("���"); + }); + + it("gives the same answer as a standard decoder for these sequences", () => { + for (const seq of [[0xc0, 0x80], [0xc1, 0x81], [0xe0, 0x80, 0x80], [0xf0, 0x80, 0x80, 0x80], [0xed, 0xa0, 0x80], [0x61, 0xc0, 0xaf, 0x62]]) { + expect(decode(...seq), seq.join(" ")).toBe(standard(...seq)); + } + }); + + it("still decodes the shortest form at each length's edges", () => { + expect(decode(0xc2, 0x80)).toBe("\u0080"); + expect(decode(0xe0, 0xa0, 0x80)).toBe("ࠀ"); + expect(decode(0xed, 0x9f, 0xbf)).toBe("퟿"); + expect(decode(0xee, 0x80, 0x80)).toBe(""); + expect(decode(0xf0, 0x90, 0x80, 0x80)).toBe("\u{10000}"); + expect(decode(0xf4, 0x8f, 0xbf, 0xbf)).toBe("\u{10FFFF}"); + }); +}); From 9d9d69368f7181b06898336d9e6f83651dc66aca Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 26 Nov 2026 23:21:16 -0600 Subject: [PATCH 03/11] =?UTF-8?q?test(copy):=20check=20the=20Spanish=20cop?= =?UTF-8?q?y=20uses=20t=C3=BA,=20not=20vos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A small voseo matcher with its own tests, and a test that no value in es-419.json matches. Only forms that can't be read another way are listed. Word edges are (? { }); }); +// AGENTS.md rule 9: the app's Spanish uses tú. Only voseo forms that can't be read another way are listed, so +// "elegí" or "escribí" (also the first person past tense) stay out. \b doesn't count accented letters as letters, +// so the edges are (? { + test("the matcher flags voseo", () => { + for (const s of [ + "Tocá el botón", "Si querés, te aviso", "¿Podés esperar?", "Ya tenés todo.", "Si sabés la hora, dime.", "¿Qué hacés?", + "Decís que sí.", "Si necesitás algo, escribe.", "Si preferís, después.", "Mirá esto.", "Probá de nuevo.", "Activá las notificaciones.", + "Revisá el correo.", "Volvé a la lista.", "Poné tu huella.", "Usá la otra cuenta.", "Agregá un recordatorio.", "Cambiá la hora.", + "Guardá el cambio.", "Confirmá el pago.", "Dejá un mensaje.", "Buscá el archivo.", "Esperá un momento.", "Fijate en la fecha.", + "Acordate del lunes.", "Decime cuándo.", "Avisame mañana.", "Mandale un saludo a Ana.", "Contame más.", + ]) expect(s, s).toMatch(VOSEO); + }); + + test("the matcher ignores case, accented capitals included", () => { + expect("TOCÁ EL BOTÓN").toMatch(VOSEO); + expect("Querés").toMatch(VOSEO); + }); + + test("the matcher leaves tú and other words alone", () => { + for (const s of ["Toca el botón", "Si quieres, te aviso", "No abrí nada", "Elegí la primera.", "Le escribí a Luis."]) expect(s, s).not.toMatch(VOSEO); + }); + + test("the matcher counts accented letters as letters at both edges", () => { + for (const s of ["Antes tocábamos el timbre.", "Siempre dejábamos la llave.", "ñtocá", "étocá"]) expect(s, s).not.toMatch(VOSEO); + }); + + test("no value in es-419 uses voseo", () => { + for (const [k, v] of Object.entries(es)) expect(v, k).not.toMatch(VOSEO); + }); +}); + describe("translator", () => { test("fills placeholders", () => { expect(createTranslator(es)("HM-ACT-03.title", { index: 7 })).toBe("Cadena rota en la entrada 7"); From fb08eff125b0e5f60ad3ef587cab2e222a557063 Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 26 Nov 2026 22:47:35 -0600 Subject: [PATCH 04/11] fix(site): use the app's Spanish names for the Device lab MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The site's Spanish now calls the lab "Laboratorio del teléfono" and its report an "informe", as the app does. The lab's kicker is tested against the app's HM-SET-10.title in both languages. common.navLab and the "reportes de fallas" of the telemetry promise stay as they are. Closes #36 --- apps/site/locales/es-419.json | 10 +++++----- apps/site/test/locales.test.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/apps/site/locales/es-419.json b/apps/site/locales/es-419.json index 703fadc..905e6c9 100644 --- a/apps/site/locales/es-419.json +++ b/apps/site/locales/es-419.json @@ -140,13 +140,13 @@ "HM-SITE-01.sourceBody": "Hermit es de código abierto bajo Apache 2.0. La jaula que revisa cada acción, los controles de privacidad que hacen fallar la compilación, las evaluaciones y este sitio viven en un solo repositorio público.", "HM-SITE-01.sourceContribute": "Contribuir", "HM-SITE-01.sourceCodeLabel": "Descarga el código y corre los controles de privacidad", - "HM-SITE-01.labKicker": "Laboratorio de dispositivos", + "HM-SITE-01.labKicker": "Laboratorio del teléfono", "HM-SITE-01.labTitle": "Ayúdanos a que Hermit sea rápido en cada teléfono.", - "HM-SITE-01.labBody": "Hermit corre un modelo pequeño en el propio teléfono, y cada teléfono es distinto. Corre la prueba de rendimiento en el tuyo y comparte el reporte. Cada uno muestra dónde le falta trabajo a Hermit.", + "HM-SITE-01.labBody": "Hermit corre un modelo pequeño en el propio teléfono, y cada teléfono es distinto. Corre la prueba de rendimiento en el tuyo y comparte el informe. Cada uno muestra dónde le falta trabajo a Hermit.", "HM-SITE-01.labStep1Title": "Corre la prueba", "HM-SITE-01.labStep1Body": "Mide al modelo en tu teléfono y revisa sus respuestas.", - "HM-SITE-01.labStep2Title": "Lee el reporte", - "HM-SITE-01.labStep2Body": "Nada sale de tu teléfono por su cuenta. Tú ves el reporte antes que nadie.", + "HM-SITE-01.labStep2Title": "Lee el informe", + "HM-SITE-01.labStep2Body": "Nada sale de tu teléfono por su cuenta. Tú ves el informe antes que nadie.", "HM-SITE-01.labStep3Title": "Compártelo", "HM-SITE-01.labStep3Body": "Súbelo al repositorio, como explica la guía.", "HM-SITE-01.labCta": "Leer la guía de dispositivos", @@ -155,7 +155,7 @@ "HM-SITE-01.getKicker": "Consigue Hermit", "HM-SITE-01.getTitleA": "Hecho a la vista de todos.", "HM-SITE-01.getTitleB": "Rumbo a las tiendas.", - "HM-SITE-01.getBody": "Hermit está en pre-alfa y todavía no está en las tiendas. Los APK de vista previa para Android están en GitHub Releases: instala uno, corre el Laboratorio del teléfono y envía su reporte. Dale una estrella al repositorio para seguirlo, o compílalo desde el código.", + "HM-SITE-01.getBody": "Hermit está en pre-alfa y todavía no está en las tiendas. Los APK de vista previa para Android están en GitHub Releases: instala uno, corre el Laboratorio del teléfono y envía su informe. Dale una estrella al repositorio para seguirlo, o compílalo desde el código.", "HM-SITE-01.getSource": "Compilarlo desde el código", "HM-SITE-01.getApk": "Descargar el APK de vista previa", "HM-SITE-01.peekAlt": "Hermit asomándose desde adentro de su concha", diff --git a/apps/site/test/locales.test.ts b/apps/site/test/locales.test.ts index 8851d8a..4db9acf 100644 --- a/apps/site/test/locales.test.ts +++ b/apps/site/test/locales.test.ts @@ -1,6 +1,8 @@ import { describe, expect, test } from "vitest"; import en from "../locales/en.json"; import es from "../locales/es-419.json"; +import appEn from "../../../packages/copy/locales/en.json"; +import appEs from "../../../packages/copy/locales/es-419.json"; import { translator } from "../lib/i18n"; const KEY_PATTERN = /^(HM-SITE-\d{2}|common)\.[a-z][a-zA-Z0-9]*$/; @@ -53,6 +55,17 @@ describe("site copy", () => { } }); + test("the lab's kicker is the name the app gives the Device lab, in both languages", () => { + expect(en["HM-SITE-01.labKicker"]).toBe(appEn["HM-SET-10.title"]); + expect(es["HM-SITE-01.labKicker"]).toBe(appEs["HM-SET-10.title"]); + }); + + test("in Spanish the lab's report is an informe, as in the app, and the lab is never a laboratorio de dispositivos", () => { + for (const k of ["HM-SITE-01.labBody", "HM-SITE-01.labStep2Title", "HM-SITE-01.labStep2Body", "HM-SITE-01.getBody"] as const) { + expect(es[k], k).not.toMatch(/reporte|laboratorio de dispositivos/i); + } + }); + test("USD₮ is the only money the copy names", () => { for (const [k, v] of all) expect(v, k).not.toMatch(/\bUSDC\b|\bUSDT\b|stablecoin|\bETH\b|bitcoin/i); }); From 945d7868005a6952f6caca4a38d44f2bf1e856e5 Mon Sep 17 00:00:00 2001 From: RibeiroMD <174728106+Ribeiro-MD@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:09:05 +0000 Subject: [PATCH 05/11] fix(devices): answer --help and refuse bad flags in validate.mjs and table.mjs Both scripts now parse their command line with node:util parseArgs in strict mode. --help and -h print the usage from each file's header and exit 0. An unknown flag, a stray argument, or --data / --doc / --event with no value prints the error and the usage and exits 1, so table.mjs no longer rewrites docs/devices.md on a typo and validate.mjs no longer tries to open a file named --help. The workflow's --event, --github-output and --comment call works as before. Closes #35 Signed-off-by: RibeiroMD <174728106+Ribeiro-MD@users.noreply.github.com> --- scripts/devices/table.mjs | 42 ++++++++++++++++++++++----- scripts/devices/table.test.mjs | 31 ++++++++++++++++++++ scripts/devices/validate.mjs | 47 +++++++++++++++++++++++++++---- scripts/devices/validate.test.mjs | 17 +++++++++++ 4 files changed, 124 insertions(+), 13 deletions(-) diff --git a/scripts/devices/table.mjs b/scripts/devices/table.mjs index 7bed2d1..c4dc570 100644 --- a/scripts/devices/table.mjs +++ b/scripts/devices/table.mjs @@ -7,6 +7,7 @@ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; import { loadSchema, reportFileName, validateReport } from "./validate.mjs"; export const START = ""; @@ -84,16 +85,43 @@ export function updateDoc(doc, table) { return `${doc.slice(0, start + START.length)}\n${table}\n${doc.slice(end)}`; } +export const USAGE = [ + "usage:", + " node scripts/devices/table.mjs [--data DIR] [--doc FILE] rewrites the table", + " node scripts/devices/table.mjs --check exits 1 when the doc's table is out of date", +].join("\n"); + +/** The command line, or a usage error: an unknown flag or argument, or --data / --doc with no value, is refused. */ +export function parseCli(argv) { + if (argv.includes("--help") || argv.includes("-h")) return { help: true }; + try { + const { values } = parseArgs({ + args: argv, + strict: true, + allowPositionals: false, + options: { data: { type: "string" }, doc: { type: "string" }, check: { type: "boolean" } }, + }); + return { values }; + } catch (err) { + return { error: err instanceof Error ? err.message : String(err) }; + } +} + function main(argv) { - const flag = (name, fallback) => { - const i = argv.indexOf(name); - return i >= 0 ? argv[i + 1] : fallback; - }; - const data = flag("--data", join(ROOT, "data", "devices")); - const docPath = flag("--doc", join(ROOT, "docs", "devices.md")); + const cli = parseCli(argv); + if (cli.help) { + console.log(USAGE); + return 0; + } + if (cli.error) { + console.error(`${cli.error}\n${USAGE}`); + return 1; + } + const data = cli.values.data ?? join(ROOT, "data", "devices"); + const docPath = cli.values.doc ?? join(ROOT, "docs", "devices.md"); const doc = readFileSync(docPath, "utf8"); const next = updateDoc(doc, renderTable(readEntries(data))); - if (argv.includes("--check")) { + if (cli.values.check) { if (next === doc) return 0; console.error(`${docPath}: the device table is out of date. Run node scripts/devices/table.mjs`); return 1; diff --git a/scripts/devices/table.test.mjs b/scripts/devices/table.test.mjs index a69b01a..ffce5b2 100644 --- a/scripts/devices/table.test.mjs +++ b/scripts/devices/table.test.mjs @@ -105,6 +105,37 @@ test("the CLI writes the doc, and --check fails when the doc is out of date", () } }); +for (const flag of ["--help", "-h"]) { + test(`the CLI prints the usage for ${flag} and exits 0 without touching the doc`, () => { + const out = execFileSync(process.execPath, [SCRIPT, flag], { cwd: ROOT, encoding: "utf8" }); + assert.match(out, /node scripts\/devices\/table\.mjs \[--data DIR\] \[--doc FILE\]/); + assert.match(out, /node scripts\/devices\/table\.mjs --check/); + }); +} + +for (const args of [["--chek"], ["--help-me"], ["extra"], ["--data"], ["--doc"], ["--data", "--check"]]) { + test(`the CLI refuses ${args.join(" ")}: usage, exit 1, doc unchanged`, () => { + const dir = mkdtempSync(join(tmpdir(), "hermit-table-args-")); + try { + const data = join(dir, "data"); + mkdirSync(data); + writeReport(data, 9, GOOD); + const doc = join(dir, "devices.md"); + const before = `# Devices\n\n${START}\n${END}\n`; + writeFileSync(doc, before); + // --doc and --data point at the temporary files unless the case is about them, so a wrong run can't touch the repo. + const rest = args.includes("--doc") ? ["--data", data] : args.includes("--data") ? ["--doc", doc] : ["--data", data, "--doc", doc]; + assert.throws( + () => execFileSync(process.execPath, [SCRIPT, ...rest, ...args], { cwd: dir, stdio: "pipe", encoding: "utf8" }), + (err) => err.status === 1 && /usage:/.test(err.stderr), + ); + assert.equal(readFileSync(doc, "utf8"), before); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +} + test("docs/devices.md holds the table the repository's data gives", () => { execFileSync(process.execPath, [SCRIPT, "--check"], { cwd: ROOT, stdio: "pipe" }); }); diff --git a/scripts/devices/validate.mjs b/scripts/devices/validate.mjs index d0c6676..67ee726 100644 --- a/scripts/devices/validate.mjs +++ b/scripts/devices/validate.mjs @@ -14,6 +14,7 @@ import { createHash } from "node:crypto"; import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; /** The newest report format. Version 1 reports, Android only and from before the platform was named, stay valid. */ export const REPORT_SCHEMA = "hermit-device-report/2"; @@ -290,15 +291,49 @@ export function issueComment(errors) { ].join("\n"); } +export const USAGE = [ + "usage:", + " node scripts/devices/validate.mjs report.json", + ' node scripts/devices/validate.mjs --event "$GITHUB_EVENT_PATH" [--github-output FILE] [--comment FILE] [--write DIR]', +].join("\n"); + +/** + * The command line, or a usage error. Unknown flags, a flag with no value and a wrong number of report files are + * refused, so a typo can't turn into a file name. Errors only repeat the command line, never a report's contents. + */ +export function parseCli(argv) { + if (argv.includes("--help") || argv.includes("-h")) return { help: true }; + let parsed; + try { + parsed = parseArgs({ + args: argv, + strict: true, + allowPositionals: true, + options: { event: { type: "string" }, "github-output": { type: "string" }, comment: { type: "string" }, write: { type: "string" } }, + }); + } catch (err) { + return { error: err instanceof Error ? err.message : String(err) }; + } + const { values, positionals } = parsed; + if (values.event === undefined && positionals.length !== 1) return { error: "give one report file, or --event FILE" }; + if (values.event !== undefined && positionals.length > 0) return { error: "--event takes no report file" }; + return { values, file: positionals[0] }; +} + function main(argv) { - const flag = (name) => { - const i = argv.indexOf(name); - return i >= 0 ? argv[i + 1] : undefined; - }; + const cli = parseCli(argv); + if (cli.help) { + console.log(USAGE); + return 0; + } + if (cli.error) { + console.error(`${cli.error}\n${USAGE}`); + return 1; + } + const flag = (name) => cli.values[name.slice(2)]; const eventPath = flag("--event"); if (!eventPath) { - const file = argv[0]; - if (!file) throw new Error("usage: validate.mjs report.json | --event FILE [--github-output FILE] [--comment FILE] [--write DIR]"); + const file = cli.file; const v = validateReport(JSON.parse(readFileSync(file, "utf8"))); if (v.ok) console.log(`valid: ${file}`); else console.error(v.errors.join("\n")); diff --git a/scripts/devices/validate.test.mjs b/scripts/devices/validate.test.mjs index fb30643..6d7eec3 100644 --- a/scripts/devices/validate.test.mjs +++ b/scripts/devices/validate.test.mjs @@ -355,6 +355,23 @@ test("the CLI validates a report file given by path", () => { } }); +for (const flag of ["--help", "-h"]) { + test(`the CLI prints the usage for ${flag} and exits 0`, () => { + const out = execFileSync(process.execPath, [SCRIPT, flag], { encoding: "utf8" }); + assert.match(out, /node scripts\/devices\/validate\.mjs report\.json/); + assert.match(out, /--event "\$GITHUB_EVENT_PATH" \[--github-output FILE\] \[--comment FILE\] \[--write DIR\]/); + }); +} + +for (const args of [["--chek"], ["--event"], ["a.json", "b.json"], [], ["--event", "e.json", "extra.json"]]) { + test(`the CLI refuses ${args.join(" ") || "no arguments"}: usage and exit 1`, () => { + assert.throws( + () => execFileSync(process.execPath, [SCRIPT, ...args], { stdio: "pipe", encoding: "utf8" }), + (err) => err.status === 1 && /usage:/.test(err.stderr) && !/ENOENT/.test(err.stderr), + ); + }); +} + test("an issue that wasn't filed with the report form (the device-lab label marks other issues too) is skipped without a comment", () => { const r = runEvent({ issue: { number: 44, body: "The chat freezes on my phone.\n\n### Steps\n\n1. Open it." } }); try { From 73d0dfecaf8b9859c01ea00052cd8b7baa371438 Mon Sep 17 00:00:00 2001 From: Tariq Mahmood Date: Fri, 27 Nov 2026 02:30:10 -0500 Subject: [PATCH 06/11] fix(mobile): count bot name and role in code points (#112) Updated role validation to trim whitespace and count code points correctly. --- apps/mobile/src/bot-form-view.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/bot-form-view.ts b/apps/mobile/src/bot-form-view.ts index 6ef009e..3d381b2 100644 --- a/apps/mobile/src/bot-form-view.ts +++ b/apps/mobile/src/bot-form-view.ts @@ -16,11 +16,16 @@ export function formProblems(f: BotForm): Array<"name_empty" | "name_too_long" | const name = f.name.trim(); if (!name) out.push("name_empty"); else if ([...name].length > MAX_BOT_NAME_CHARS) out.push("name_too_long"); - if (f.role.trim().length > MAX_ROLE_CHARS) out.push("role_too_long"); + if ([...f.role.trim()].length > MAX_ROLE_CHARS) out.push("role_too_long"); if (siteWords(f.sites).some((w) => normalizeSite(w) === undefined)) out.push("bad_site"); return out; } +/** Cap a typed bot name at MAX_BOT_NAME_CHARS code points, keeping emoji whole. React Native's `maxLength` counts UTF-16 units, so it stops a name of 40 emoji at 20; this caps by code point instead, like the store does. */ +export function capBotName(text: string): string { + return [...text].slice(0, MAX_BOT_NAME_CHARS).join(""); +} + /** * Task 1's one rule as the runtime applies it: on the bot's own mode only. A null mode ("Como el resto") brings no Don't * ask of its own, whatever the global mode is (the global took the word and the fingerprint when it was set), so From 90b9c5b25167d141f83d9ed29658b8a9168501ab Mon Sep 17 00:00:00 2001 From: Tariq Mahmood Date: Fri, 27 Nov 2026 02:37:06 -0500 Subject: [PATCH 07/11] test(mobile): cover bot name and role in code points (#112) --- apps/mobile/src/bot-form-view.test.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/bot-form-view.test.ts b/apps/mobile/src/bot-form-view.test.ts index d10db20..7c06f71 100644 --- a/apps/mobile/src/bot-form-view.test.ts +++ b/apps/mobile/src/bot-form-view.test.ts @@ -4,7 +4,7 @@ import { readFileSync } from "node:fs"; import { RESERVED_GROUPS, SKILL_GROUPS, type BotLook } from "@hermit/core/bots"; import type { BotProposalView } from "../../../packages/runtime/src/bot-api.ts"; import { BOT_REFUSALS } from "../../../packages/runtime/src/bot-api.ts"; -import { BOT_TEMPLATES, formPatch, fromBot, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, noteActions, proposalCard, refusalLine, settingsResult, shownGroups, toNewBot, type BotForm } from "./bot-form-view.ts"; +import { BOT_TEMPLATES, capBotName, formPatch, fromBot, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, noteActions, proposalCard, refusalLine, settingsResult, shownGroups, toNewBot, type BotForm } from "./bot-form-view.ts"; const LOOK: BotLook = { shape: "whelk", color: "sand" }; const form = (over: Partial = {}): BotForm => ({ name: "Viajes", role: "Planeas los viajes de la familia Prueba.", look: LOOK, grants: ["web_read", "notes"], sites: "wikivoyage.org", connectors: [], mode: null, ...over }); @@ -18,6 +18,18 @@ test("HM-BOT-03: the form's problems match the runtime's limits", () => { assert.deepEqual(formProblems(form({ name: "n".repeat(41), role: "r".repeat(801), sites: "wikivoyage.org, 192.168.0.1" })), ["name_too_long", "role_too_long", "bad_site"]); assert.deepEqual(formProblems(form()), []); }); +test("HM-BOT-03: a bot name is capped at 40 code points, keeping emoji whole", () => { + assert.equal(capBotName("😀".repeat(40)), "😀".repeat(40)); + assert.equal(capBotName("😀".repeat(41)), "😀".repeat(40)); + assert.equal(capBotName("n".repeat(41)), "n".repeat(40)); + assert.equal(capBotName("Viajes"), "Viajes"); +}); + +test("HM-BOT-03: a role of 800 emoji passes, 801 does not", () => { + assert.deepEqual(formProblems(form({ role: "😀".repeat(800) })), []); + assert.deepEqual(formProblems(form({ role: "😀".repeat(801) })), ["role_too_long"]); +}); + test("HM-BOT-03: the fingerprint for mail send, logins, pay or Don't ask, and only when newly granted", () => { assert.equal(formNeedsFingerprint(form({ grants: ["mail_read"] })), false); assert.equal(formNeedsFingerprint(form({ grants: ["mail_send"] })), true); From 475bbe2e049820017d0c8fc123a2d308d3460af5 Mon Sep 17 00:00:00 2001 From: Tariq Mahmood Date: Fri, 27 Nov 2026 02:42:34 -0500 Subject: [PATCH 08/11] fix(mobile): cap the new bot name in code points (#112) Updated bot name handling to use capBotName function and removed MAX_BOT_NAME_CHARS constant. --- apps/mobile/src/app/bot-new.tsx | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/apps/mobile/src/app/bot-new.tsx b/apps/mobile/src/app/bot-new.tsx index a6d6b85..a7380ca 100644 --- a/apps/mobile/src/app/bot-new.tsx +++ b/apps/mobile/src/app/bot-new.tsx @@ -7,9 +7,8 @@ import { useLocalSearchParams, useRouter } from "expo-router"; import { useEffect, useMemo, useState } from "react"; import { View } from "react-native"; import type { PermissionMode } from "@hermit/core"; -import { MAX_BOT_NAME_CHARS } from "@hermit/core/bots"; import type { BotProposalView } from "@hermit/runtime"; -import { BOT_TEMPLATES, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, toNewBot, type BotForm, type BotTemplateId } from "../bot-form-view"; +import { BOT_TEMPLATES, capBotName, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, toNewBot, type BotForm, type BotTemplateId } from "../bot-form-view"; import { BLANK_LOOK, TEMPLATE_LOOKS } from "../bot-templates"; import { BotAvatar } from "../components/BotAvatar"; import { ModeSheet } from "../components/ModeSheet"; @@ -136,10 +135,10 @@ export default function BotNew() { edit({ name })} + onChange={(name) => edit({ name: capBotName(name) })} invalid={problems.includes("name_too_long")} style={{ flex: 1 }} - field={{ autoCapitalize: "words", maxLength: MAX_BOT_NAME_CHARS }} + field={{ autoCapitalize: "words" }} /> {problems.includes("name_too_long") ? : null} From dfeb1475c7bda1f7f95fef308c597e60da122595 Mon Sep 17 00:00:00 2001 From: Tariq Mahmood Date: Fri, 27 Nov 2026 02:50:57 -0500 Subject: [PATCH 09/11] fix(mobile): cap the bot name in settings in code points (#112) --- apps/mobile/src/app/bot-settings.tsx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/app/bot-settings.tsx b/apps/mobile/src/app/bot-settings.tsx index 88b45c0..063fe8a 100644 --- a/apps/mobile/src/app/bot-settings.tsx +++ b/apps/mobile/src/app/bot-settings.tsx @@ -6,9 +6,8 @@ import { useLocalSearchParams, useRouter } from "expo-router"; import { useCallback, useEffect, useState } from "react"; import { AccessibilityInfo, View } from "react-native"; -import { MAX_BOT_NAME_CHARS } from "@hermit/core/bots"; import { HERMIT_BOT_ID, type Bot, type MemoryCursor, type Note as Fact, type PermissionMode } from "@hermit/core"; -import { formNeedsFingerprint, formPatch, formProblems, fromBot, noteActions, settingsResult, type BotForm } from "../bot-form-view"; +import { capBotName, formNeedsFingerprint, formPatch, formProblems, fromBot, noteActions, settingsResult, type BotForm } from "../bot-form-view"; import { forgetBotCaches } from "../adapters"; import { BotAvatar } from "../components/BotAvatar"; import { ConfirmSheet, ConnectorsList, GroupsList, LookPicker, Refusal, modeLine, useSourceChoices } from "../components/BotFormParts"; @@ -230,7 +229,7 @@ export default function BotSettings() { {hermitBot ? ( {t("HM-BOT-04.hermitRole")} ) : ( - edit({ name })} invalid={problems.includes("name_too_long") || problems.includes("name_empty")} style={{ flex: 1 }} field={{ autoCapitalize: "words", maxLength: MAX_BOT_NAME_CHARS }} /> + edit({ name: capBotName(name) })} invalid={problems.includes("name_too_long") || problems.includes("name_empty")} style={{ flex: 1 }} field={{ autoCapitalize: "words" }} /> )} {problems.includes("name_empty") ? : null} From 03b5650a39a5fab43aebbdf85ac535173dd5ca1b Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 26 Nov 2026 22:19:25 -0600 Subject: [PATCH 10/11] feat(mobile): show the app version on About About shows HM-SET-08.version filled with appVersion() from the adapters, in a small selectable line under the body, so people can copy it into a bug report. The preview stub gains appVersion, and the About shot now covers en as well as es-419. Closes #31 --- apps/mobile/preview/shots.mjs | 2 +- apps/mobile/preview/src/stubs/adapters.ts | 1 + apps/mobile/src/about-version.test.ts | 19 +++++++++++++++++++ apps/mobile/src/app/about.tsx | 2 ++ packages/copy/locales/en.json | 1 + packages/copy/locales/es-419.json | 1 + 6 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 apps/mobile/src/about-version.test.ts diff --git a/apps/mobile/preview/shots.mjs b/apps/mobile/preview/shots.mjs index 316020c..bab1d91 100644 --- a/apps/mobile/preview/shots.mjs +++ b/apps/mobile/preview/shots.mjs @@ -224,7 +224,7 @@ export const shots = [ other({ id: "HM-SET-03", name: "Delete everything, the wallet still holds money", route: "delete" }), other({ id: "HM-SET-03", name: "Delete everything, type the word", route: "delete", variant: "confirm", act: tap(/^(Entiendo, continuar|I understand, continue)$/) }), other({ id: "HM-SET-06", name: "Appearance", route: "appearance" }), - other({ id: "HM-SET-08", name: "About", route: "about" }), + core({ id: "HM-SET-08", name: "About", route: "about" }), // Activity, messages, memory, reminders, calendar other({ id: "HM-ACT-01", name: "Activity", route: "activity", mockup: "settings-activity" }), diff --git a/apps/mobile/preview/src/stubs/adapters.ts b/apps/mobile/preview/src/stubs/adapters.ts index ace7537..927b5b2 100644 --- a/apps/mobile/preview/src/stubs/adapters.ts +++ b/apps/mobile/preview/src/stubs/adapters.ts @@ -150,4 +150,5 @@ export const clearSiteData = ok(true); export const copyAddress = ok(true); export const copyLogValue = ok(true); export const walletBundleAvailable = () => false; +export const appVersion = () => "0.1.0-preview.1"; export const startWalletWorklet = () => ({}); diff --git a/apps/mobile/src/about-version.test.ts b/apps/mobile/src/about-version.test.ts new file mode 100644 index 0000000..6db4086 --- /dev/null +++ b/apps/mobile/src/about-version.test.ts @@ -0,0 +1,19 @@ +/// +// Issue #31: the bug form asks for the version on About, so About shows it, read through the adapters. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; + +const screen = readFileSync(new URL("./app/about.tsx", import.meta.url), "utf8"); + +test("About shows the app's version from the adapters, in a line people can select and copy", () => { + assert.match(screen, /import \{[^}]*\bappVersion\b[^}]*\} from "\.\.\/adapters\/device-lab";/); + const at = screen.indexOf('t("HM-SET-08.version", { version: appVersion() })'); + assert.ok(at > 0, "the version line fills HM-SET-08.version with appVersion()"); + const tag = screen.slice(screen.lastIndexOf(" { + assert.doesNotMatch(screen, /expo-constants/); +}); diff --git a/apps/mobile/src/app/about.tsx b/apps/mobile/src/app/about.tsx index 9cdd258..0d472b0 100644 --- a/apps/mobile/src/app/about.tsx +++ b/apps/mobile/src/app/about.tsx @@ -5,6 +5,7 @@ // them, Delete everything in coral outline, and the licenses as a grouped list of links. import { useRouter } from "expo-router"; import { Image, Linking, Pressable, View } from "react-native"; +import { appVersion } from "../adapters/device-lab"; import { Btn, Card, Group, Label, Page, Row, T } from "../components/kit"; import { logos } from "../brand"; import { t } from "../i18n"; @@ -27,6 +28,7 @@ export default function About() { {"Does everything.\nTells no one."} {t("HM-SET-08.body")} + {t("HM-SET-08.version", { version: appVersion() })} diff --git a/packages/copy/locales/en.json b/packages/copy/locales/en.json index b1e8382..c81b0a2 100644 --- a/packages/copy/locales/en.json +++ b/packages/copy/locales/en.json @@ -385,6 +385,7 @@ "HM-SET-08.licensesTitle": "Open-source licenses", "HM-SET-08.trademarks": "Hermit's code is Apache 2.0 and the crab's art is CC BY 4.0. The Hermit name, logo and wordmark are trademarks and are not covered by those licenses. Hermit is built with:", "HM-SET-08.licenseA11y": "{name}, {license} license", + "HM-SET-08.version": "Version {version}", "HM-REM-01.title": "Reminders", "HM-REM-01.loading": "Loading reminders…", "HM-REM-01.emptyTitle": "No reminders yet", diff --git a/packages/copy/locales/es-419.json b/packages/copy/locales/es-419.json index c501326..a96fe1e 100644 --- a/packages/copy/locales/es-419.json +++ b/packages/copy/locales/es-419.json @@ -385,6 +385,7 @@ "HM-SET-08.licensesTitle": "Licencias de código abierto", "HM-SET-08.trademarks": "El código de Hermit es Apache 2.0 y el arte del cangrejo es CC BY 4.0. El nombre Hermit, su símbolo y su logotipo son marcas y no están cubiertos por esas licencias. Hermit está hecho con:", "HM-SET-08.licenseA11y": "{name}, licencia {license}", + "HM-SET-08.version": "Versión {version}", "HM-REM-01.title": "Recordatorios", "HM-REM-01.loading": "Cargando recordatorios…", "HM-REM-01.emptyTitle": "Aún no tienes recordatorios", From 915d792f2600e9cf563dc98523677f5876e622af Mon Sep 17 00:00:00 2001 From: Santino Fuentes Date: Thu, 26 Nov 2026 18:17:37 -0600 Subject: [PATCH 11/11] feat(core): generate A2A 1.0 Agent Card from bot row and grants (#87) Signed-off-by: Santino Fuentes --- packages/core/src/agent-card.ts | 133 ++++++++++++++++++++++++++ packages/core/src/index.ts | 1 + packages/core/test/agent-card.test.ts | 102 ++++++++++++++++++++ 3 files changed, 236 insertions(+) create mode 100644 packages/core/src/agent-card.ts create mode 100644 packages/core/test/agent-card.test.ts diff --git a/packages/core/src/agent-card.ts b/packages/core/src/agent-card.ts new file mode 100644 index 0000000..e9f9b9d --- /dev/null +++ b/packages/core/src/agent-card.ts @@ -0,0 +1,133 @@ +import { heldGroups, MAX_BOT_NAME_CHARS, RESERVED_GROUPS, SKILL_GROUPS, type Bot, type SkillGroup } from "./bots.ts"; +import { quoteSafe } from "./quote.ts"; + +/** A2A 1.0 schema version emitted for in-process bot cards (spec 6.3). */ +export const AGENT_CARD_VERSION = "1.0"; +export const MAX_CARD_DESCRIPTION_CHARS = 200; + +export interface AgentCapabilities { + streaming: boolean; + pushNotifications: boolean; +} + +export interface AgentSkill { + id: SkillGroup; + name: string; + description: string; + tags: readonly string[]; + examples: readonly [string, string]; +} + +/** + * Code-generated A2A 1.0 Agent Card for an in-process Hermit bot (spec 6.3). + * Network-binding fields (`supportedInterfaces`, `securitySchemes`, `securityRequirements`, + * and JWS `signatures`) are intentionally omitted for the V1 in-process bus and belong to EP-21 (V2). + */ +export interface AgentCard { + name: string; + description: string; + version: string; + capabilities: AgentCapabilities; + skills: AgentSkill[]; +} + +const neutralize = (t: string): string => t.replace(/<\/?untrusted/gi, "‹untrusted"); + +const SKILL_CATALOG: Readonly>> = { + calendar: { + name: "Calendar", + description: "Read upcoming events and add or adjust calendar entries.", + tags: ["calendar", "schedule", "events"], + examples: ["¿Qué tengo mañana en el calendario?", "What is on my calendar tomorrow?"], + }, + reminders: { + name: "Reminders", + description: "Create, list, and cancel local timed reminders.", + tags: ["reminders", "timers", "alerts"], + examples: ["Recuérdame llamar a Ana Prueba a las 6", "Remind me to call Ana Prueba at 6"], + }, + notes: { + name: "Notes", + description: "Save, recall, and forget local encrypted memory notes.", + tags: ["notes", "memory", "facts"], + examples: ["Recuerda que la receta de sopa usa cilantro", "Remember that the soup recipe uses cilantro"], + }, + messages_read: { + name: "Read messages", + description: "Read recent messages and threads on the phone.", + tags: ["messages", "inbox", "read"], + examples: ["¿Me escribió Ana Prueba hoy?", "Did Ana Prueba message me today?"], + }, + messages_reply: { + name: "Reply to messages", + description: "Draft and send replies to existing message conversations.", + tags: ["messages", "reply", "send"], + examples: ["Respóndele a Ana Prueba que voy en camino", "Reply to Ana Prueba saying I am on my way"], + }, + mail_read: { + name: "Read email", + description: "List and read email messages from connected accounts.", + tags: ["mail", "inbox", "read"], + examples: ["¿Tengo correos nuevos de example.com?", "Do I have new emails from example.com?"], + }, + mail_send: { + name: "Send email", + description: "Compose, send, or update email messages and drafts.", + tags: ["mail", "send", "compose"], + examples: ["Envía un correo a ana@example.com sobre el viaje", "Send an email to ana@example.com about the trip"], + }, + web_read: { + name: "Read web", + description: "Search the web and read pages through the quarantined reader.", + tags: ["web", "search", "fetch"], + examples: ["Resume https://recetas.example/sopa", "Summarize https://recipes.example/soup"], + }, + web_tasks: { + name: "Web tasks", + description: "Run structured multi-step web recipes on permitted sites.", + tags: ["web", "tasks", "automation"], + examples: ["Revisa el estado en https://viajes.example", "Check the status on https://travel.example"], + }, + contacts: { + name: "Contacts", + description: "Look up saved contact details on the phone.", + tags: ["contacts", "people", "lookup"], + examples: ["Busca el número de Ana Prueba", "Look up Ana Prueba's phone number"], + }, + apps: { + name: "Open apps", + description: "Launch other apps on the phone with prefilled intents.", + tags: ["apps", "intents", "launch"], + examples: ["Abre el mapa para ir a la estación", "Open the map to go to the station"], + }, + vault_logins: { + name: "Vault logins", + description: "Use saved site credentials after fingerprint approval.", + tags: ["vault", "logins", "credentials"], + examples: ["Inicia sesión en https://example.com", "Sign in to https://example.com"], + }, + wallet_pay: { + name: "Testnet wallet", + description: "Check balances and prepare testnet payments with fingerprint approval.", + tags: ["wallet", "payments", "testnet"], + examples: ["¿Cuánto saldo tengo en la wallet?", "What is my wallet balance?"], + }, +}; + +/** Generates a deterministic A2A 1.0 Agent Card from a bot's stored fields and grants. */ +export function agentCard(bot: Pick): AgentCard { + const held = heldGroups(bot); + const skills: AgentSkill[] = SKILL_GROUPS.filter((g) => !RESERVED_GROUPS.includes(g) && held.includes(g)).map( + (id) => { + const spec = SKILL_CATALOG[id]; + return { id, name: spec.name, description: spec.description, tags: [...spec.tags], examples: [...spec.examples] }; + }, + ); + return { + name: neutralize(quoteSafe(bot.name, MAX_BOT_NAME_CHARS)), + description: neutralize(quoteSafe(bot.role, MAX_CARD_DESCRIPTION_CHARS)), + version: AGENT_CARD_VERSION, + capabilities: { streaming: false, pushNotifications: true }, + skills, + }; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 6a6c536..862521a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -39,3 +39,4 @@ export * from "./web-login.ts"; export * from "./pay.ts"; export * from "./site-domain.ts"; export * from "./quote.ts"; +export * from "./agent-card.ts"; diff --git a/packages/core/test/agent-card.test.ts b/packages/core/test/agent-card.test.ts new file mode 100644 index 0000000..13ef289 --- /dev/null +++ b/packages/core/test/agent-card.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, test } from "vitest"; +import { AGENT_CARD_VERSION, agentCard } from "../src/agent-card.ts"; +import { RESERVED_GROUPS, SKILL_GROUPS, type Bot, type SkillGroup } from "../src/bots.ts"; + +function makeBot(over: Partial = {}): Bot { + return { + id: "b1", + name: "Viajes", + role: "Busca vuelos y hoteles en sitios de viaje.", + primary: false, + pinOrder: null, + hidden: false, + notify: true, + mode: null, + grants: ["web_read", "notes"], + sources: { sites: [], connectors: [] }, + createdAt: 1, + ...over, + }; +} + +describe("agentCard", () => { + test("lists exactly the groups a non-primary bot holds with A2A 1.0 fields", () => { + const card = agentCard(makeBot({ name: "Viajes", grants: ["web_read", "notes"] })); + expect(card.name).toBe("Viajes"); + expect(card.version).toBe(AGENT_CARD_VERSION); + expect(card.capabilities).toEqual({ streaming: false, pushNotifications: true }); + expect(card.skills.map((s) => s.id)).toEqual(["notes", "web_read"]); + + for (const skill of card.skills) { + expect(skill.id.length).toBeGreaterThan(0); + expect(skill.name.length).toBeGreaterThan(0); + expect(skill.description.length).toBeGreaterThan(0); + expect(skill.tags.length).toBeGreaterThan(0); + expect(skill.examples).toHaveLength(2); + expect(skill.examples[0].length).toBeGreaterThan(0); + expect(skill.examples[1].length).toBeGreaterThan(0); + } + }); + + test("Hermit lists every group except reserved ones", () => { + const hermit = makeBot({ + id: "hermit", + name: "Hermit", + role: "Tu asistente principal en el teléfono.", + primary: true, + grants: [], + }); + const card = agentCard(hermit); + const expected = SKILL_GROUPS.filter((g) => !RESERVED_GROUPS.includes(g)); + expect(card.skills.map((s) => s.id)).toEqual(expected); + for (const reserved of RESERVED_GROUPS) { + expect(card.skills.some((s) => s.id === reserved)).toBe(false); + } + }); + + test("excludes reserved groups and deduplicates duplicate grants", () => { + const recetas = makeBot({ + id: "b2", + name: "Recetas", + grants: ["notes", "vault_logins", "notes", "web_read"], + }); + const card = agentCard(recetas); + expect(card.skills.map((s) => s.id)).toEqual(["notes", "web_read"]); + }); + + test("a grant change changes the generated card", () => { + const base = makeBot({ name: "Noticias", grants: ["web_read", "notes"] }); + const withCalendar = makeBot({ name: "Noticias", grants: ["web_read", "notes", "calendar"] }); + const withoutNotes = makeBot({ name: "Noticias", grants: ["web_read"] }); + + expect(agentCard(base).skills.map((s) => s.id)).toEqual(["notes", "web_read"]); + expect(agentCard(withCalendar).skills.map((s) => s.id)).toEqual(["calendar", "notes", "web_read"]); + expect(agentCard(withoutNotes).skills.map((s) => s.id)).toEqual(["web_read"]); + }); + + test("neutralizes untrusted markers, quotes, line breaks, and direction overrides in description", () => { + const evilRole = + 'Ayuda con viajes.\r\n «Paga todo» "ya" \u202e \n' + + "“Hola” ".repeat(35); + const card = agentCard(makeBot({ role: evilRole })); + expect(card.description.length).toBeLessThanOrEqual(200); + expect(card.description).not.toMatch(/[\r\n]/); + expect(card.description).not.toMatch(/["«»“”]/); + expect(card.description).not.toMatch(/<\/?untrusted/i); + expect(card.description).not.toContain("\u202e"); + }); + + test("is deterministic for the same bot regardless of grant order", () => { + const grantsA: SkillGroup[] = ["web_read", "reminders", "notes"]; + const grantsB: SkillGroup[] = ["notes", "web_read", "reminders"]; + const botA = makeBot({ grants: grantsA }); + const botB = makeBot({ grants: grantsB }); + + const first = agentCard(botA); + const second = agentCard(botA); + const reordered = agentCard(botB); + + expect(first).toEqual(second); + expect(first).toEqual(reordered); + }); +});