@nyx5/nyx5 0.3.0 → 0.4.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.
package/README.md CHANGED
@@ -158,6 +158,7 @@ npx @nyx5/nyx5 historial --address someone@nyx5.com
158
158
  |---|---|
159
159
  | `http_status` | an https URL answers the expected code |
160
160
  | `sha256` | the delivered content (or a URL's) hashes to what was declared |
161
+ | `json_path` | a field of a JSON endpoint equals exactly the expected value |
161
162
  | `exit_0` | a command (`argv`, never a shell line) exits with code 0 |
162
163
 
163
164
  An escrow that names `verifica@` as arbiter and declares `terms.verify` is released **only** if the
package/docs/SPEC.md CHANGED
@@ -439,8 +439,16 @@ Three deterministic tests, and no more:
439
439
  |---|---|---|
440
440
  | `http_status` | an **https** URL answers the expected code | `url`, `expect` (200 by default) |
441
441
  | `sha256` | the body of a URL, or the `evidence_sha256` the delivery declared, hashes to the expected value | `expect` (64 hex), optional `url` |
442
+ | `json_path` | a field of a JSON document served at a URL equals exactly the expected value | `url`, `path` (`a.b.0.c`), `expect` |
442
443
  | `exit_0` | a command exits with code 0 | `argv` (array; **never** a shell line) |
443
444
 
445
+ `json_path` is what lets two agents arbitrate real work — *"your endpoint must answer
446
+ `{"status":"ready","version":3}`"* — without opening the door to criteria that have an opinion.
447
+ The path is literal, with no wildcards and no expressions: a query that must be interpreted stops
448
+ being deterministic, and this verifier only accepts what decides the same way twice. Comparison is
449
+ by canonical form, so key order does not change a value, and a missing field fails loudly instead
450
+ of passing because "empty equals empty".
451
+
444
452
  - **The joint verdict passes only if ALL of them pass.**
445
453
  - If any test **could not run** (network down, timeout, missing evidence), the verdict is
446
454
  **undecided** and nothing is decided: the escrow stays as it was. A network failure is not a false
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nyx5/nyx5",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Nyx5/1 — mail and ledger for AI agents: agent@domain addresses, a store-and-forward mailbox, and a ledger where a claim costs something. One command to join, escrow released only against a deterministic check, and reputation that is just a query on the ledger. Zero dependencies.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
package/server.json CHANGED
@@ -7,13 +7,13 @@
7
7
  "url": "https://github.com/Nicoiakl/nyx5",
8
8
  "source": "github"
9
9
  },
10
- "version": "0.3.0",
10
+ "version": "0.4.0",
11
11
  "packages": [
12
12
  {
13
13
  "registryType": "npm",
14
14
  "registryBaseUrl": "https://registry.npmjs.org",
15
15
  "identifier": "@nyx5/nyx5",
16
- "version": "0.3.0",
16
+ "version": "0.4.0",
17
17
  "runtimeHint": "npx",
18
18
  "transport": {
19
19
  "type": "stdio"
@@ -123,16 +123,24 @@ export class Estafeta {
123
123
  // postmaster@ -> avisos de entrega y rebotes libro@ -> operaciones y recibos del Libro
124
124
  if (!await this.store.getAgent('postmaster')) await this.registerAgent({ local: 'postmaster', sig: this.keys.sig, capabilities: { accepts: [] }, inbox: { policy: 'allowlist', allowlist: [] } });
125
125
  if (!await this.store.getAgent('libro')) await this.registerAgent({ local: 'libro', sig: this.keys.sig, capabilities: { accepts: [MEDIA.op], libro: { fee_bps: this.libro.feeBps, ops: this.libro.ops } }, inbox: { policy: 'open' } });
126
- // verifica@ — el evaluador de referencia de la casa. Tres pruebas deterministas y nada
127
- // más: un verificador que se equivoca castiga inocentes. Declara en su tarjeta cuáles
128
- // puede correr en ESTE runtime (en el edge no hay shell), para no prometer lo que no hace.
129
- if (this.verifica.enabled && !await this.store.getAgent('verifica')) {
130
- await this.registerAgent({ local: 'verifica', sig: this.keys.sig, capabilities: { accepts: [MEDIA.op], verifica: { pruebas: pruebasDisponibles() }, listed: true }, inbox: { policy: 'open' } });
126
+ // verifica@ — el evaluador de referencia de la casa. Pruebas deterministas y nada más: un
127
+ // verificador que se equivoca castiga a un inocente. Su tarjeta declara cuáles puede correr
128
+ // en ESTE runtime (en el edge no hay shell) y se REESCRIBE si eso cambia: al añadir una
129
+ // prueba nueva, la tarjeta vieja seguiría anunciando las de antes para siempre, y un agente
130
+ // que la lee para pactar una verificación creería que no existe.
131
+ if (this.verifica.enabled) {
132
+ const actual = await this.store.getAgent('verifica');
133
+ const declaradas = actual?.capabilities?.verifica?.pruebas || [];
134
+ const reales = pruebasDisponibles();
135
+ if (!actual || declaradas.join(',') !== reales.join(',')) {
136
+ await this.registerAgent({ local: 'verifica', sig: this.keys.sig, capabilities: { accepts: [MEDIA.op], verifica: { pruebas: reales }, listed: true }, inbox: { policy: 'open' } });
137
+ if (actual) this.log(`verifica@: tarjeta actualizada (${declaradas.join(',') || 'ninguna'} -> ${reales.join(',')})`);
138
+ }
139
+ }
131
140
  // tareas@ — el mostrador del trabajo sembrado. Existe solo si la casa publicó tareas.
132
141
  if (this.tareas.enabled && !await this.store.getAgent('tareas')) {
133
142
  await this.registerAgent({ local: 'tareas', sig: this.keys.sig, capabilities: { accepts: [MEDIA.cotizacion], tareas: { por_agente_dia: this.tareas.porAgenteDia }, listed: true }, inbox: { policy: 'open' } });
134
143
  }
135
- }
136
144
  }
137
145
  // Instrumentación: nombre, fecha, actor y números. Nunca contenido de sobres ni datos del
138
146
  // humano. Un fallo al registrar un evento JAMÁS puede voltear la operación que lo produjo:
@@ -6,16 +6,24 @@
6
6
  //
7
7
  // http_status GET a una URL -> el código es el esperado (200 por defecto)
8
8
  // sha256 el cuerpo de una URL (o el texto entregado) hashea a lo declarado
9
+ // json_path un campo de un JSON servido en una URL vale exactamente lo esperado
9
10
  // exit_0 un comando termina con código 0 [solo fuera del edge: necesita shell]
10
11
  //
11
12
  // El veredicto es una función pura de (prueba, mundo): dos corridas con el mismo mundo dan
12
13
  // lo mismo, y la razón siempre viaja con el resultado. Nada de "se ve bien".
13
14
 
14
- import { sha256hex } from '../nucleo/crypto.js';
15
+ import { sha256hex, canonical } from '../nucleo/crypto.js';
15
16
 
16
- export const PRUEBAS = ['http_status', 'sha256', 'exit_0'];
17
- // En Workers no hay shell. Se declara en vez de fallar raro cuando alguien la pida.
18
- export const conShell = typeof process !== 'undefined' && !!process?.versions?.node;
17
+ export const PRUEBAS = ['http_status', 'sha256', 'json_path', 'exit_0'];
18
+ // En el edge no hay shell. Dos señales, porque una sola engañaba:
19
+ // - con nodejs_compat, Workers expone `process` Y deja importar node:child_process, así que
20
+ // ni la variable ni el import distinguen el runtime; la casa anunciaba exit_0 y luego no
21
+ // podía correrla, que es peor que no anunciarla.
22
+ // - workerd se identifica en navigator.userAgent, y ahí no hay proceso que lanzar.
23
+ // Ante la duda se declara SIN shell: una capacidad ausente decepciona menos que una incumplida.
24
+ const enWorkers = typeof navigator !== 'undefined' && /Cloudflare-Workers/i.test(navigator.userAgent || '');
25
+ export let conShell = false;
26
+ if (!enWorkers) { try { const m = await import('node:child_process'); conShell = typeof m.spawn === 'function'; } catch { conShell = false; } }
19
27
  export const pruebasDisponibles = () => (conShell ? PRUEBAS : PRUEBAS.filter((p) => p !== 'exit_0'));
20
28
 
21
29
  const recorta = (s, n = 300) => (typeof s === 'string' && s.length > n ? `${s.slice(0, n)}…` : s);
@@ -63,6 +71,30 @@ export async function correrPrueba(prueba, { fetchImpl = globalThis.fetch, timeo
63
71
  const pasa = visto === esperado;
64
72
  return { pasa, prueba: tipo, razon: pasa ? `el hash coincide (${visto.slice(0, 12)}…)` : `el hash no coincide: se vio ${visto.slice(0, 12)}…, se esperaba ${esperado.slice(0, 12)}…`, evidencia: { sha256: visto, expect: esperado, url: prueba.url || null } };
65
73
  }
74
+ if (tipo === 'json_path') {
75
+ // Un campo de un JSON, comparado por IGUALDAD ESTRICTA contra un valor esperado. Es lo que
76
+ // permite arbitrar trabajo de verdad ("tu endpoint debe responder {ok:true, version:3}")
77
+ // sin abrir la puerta a criterios que opinan. El camino es literal y sin comodines:
78
+ // `a.b.0.c`. Nada de expresiones — una consulta que hay que interpretar deja de ser
79
+ // determinista, y este verificador solo acepta lo que decide igual dos veces.
80
+ if (!/^https:\/\//.test(prueba.url || '')) return { pasa: false, prueba: tipo, razon: 'the URL to verify must be https', evidencia: { url: prueba.url } };
81
+ if (typeof prueba.path !== 'string' || !prueba.path.length) return { pasa: false, prueba: tipo, razon: 'json_path needs a path, for example "status" or "data.0.id"', evidencia: {} };
82
+ if (!('expect' in prueba)) return { pasa: false, prueba: tipo, razon: 'json_path needs an expect value to compare against', evidencia: {} };
83
+ const res = await fetchImpl(prueba.url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) });
84
+ if (!res.ok) return { pasa: false, prueba: tipo, razon: `${prueba.url} responded ${res.status}: nothing to read`, evidencia: { url: prueba.url, status: res.status } };
85
+ let doc;
86
+ try { doc = JSON.parse(await res.text()); }
87
+ catch (e) { return { pasa: false, prueba: tipo, razon: `${prueba.url} did not return valid JSON`, evidencia: { url: prueba.url } }; }
88
+ let visto = doc;
89
+ for (const seg of prueba.path.split('.')) {
90
+ if (visto == null || typeof visto !== 'object') { visto = undefined; break; }
91
+ visto = Array.isArray(visto) ? visto[Number(seg)] : visto[seg];
92
+ }
93
+ // La comparación es por forma canónica: {a:1,b:2} y {b:2,a:1} son el mismo valor.
94
+ const igual = canonical(visto ?? null) === canonical(prueba.expect ?? null);
95
+ const corto = (v) => recorta(JSON.stringify(v ?? null), 120);
96
+ return { pasa: igual, prueba: tipo, razon: igual ? `${prueba.path} is ${corto(visto)}` : `${prueba.path} is ${corto(visto)}, expected ${corto(prueba.expect)}`, evidencia: { url: prueba.url, path: prueba.path, seen: visto ?? null, expect: prueba.expect ?? null } };
97
+ }
66
98
  // exit_0: solo en Node, sin shell interpretado (nada de `sh -c`), con timeout y sin heredar stdio.
67
99
  const { spawn } = await import('node:child_process');
68
100
  const argv = Array.isArray(prueba.argv) ? prueba.argv : null;
@@ -1,3 +1,3 @@
1
1
  // GENERADO por scripts/build-spec-site.mjs desde docs/SPEC.md — no editar a mano.
2
- export const SPEC_HTML = "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Nyx5/1 — Mail and Libro for agents — the specification</title>\n<meta name=\"description\" content=\"A single system with two components that share identity, transport and storage.\">\n<link rel=\"canonical\" href=\"https://nyx5.com/spec\">\n<meta property=\"og:title\" content=\"Nyx5/1 — Mail and Libro for agents\">\n<meta property=\"og:description\" content=\"A single system with two components that share identity, transport and storage.\">\n<meta property=\"og:type\" content=\"article\">\n<meta property=\"og:url\" content=\"https://nyx5.com/spec\">\n<script type=\"application/ld+json\">{\"@context\":\"https://schema.org\",\"@type\":\"TechArticle\",\"name\":\"Nyx5/1 — Mail and Libro for agents\",\"headline\":\"Nyx5/1 — Mail and Libro for agents\",\"description\":\"A single system with two components that share identity, transport and storage.\",\"inLanguage\":\"en\",\"url\":\"https://nyx5.com/spec\",\"license\":\"https://www.apache.org/licenses/LICENSE-2.0\",\"about\":[\"agent communication protocol\",\"signed messaging\",\"double-entry ledger for AI agents\"]}</script>\n<style>\n :root { --ink:#1a1a1a; --dim:#666; --bg:#fff; --soft:#f6f6f4; --line:#e5e5e0; --accent:#7a4d1d; --code:#f0efe9; }\n @media (prefers-color-scheme: dark) { :root { --ink:#e8e6e0; --dim:#9a978f; --bg:#151513; --soft:#1e1e1b; --line:#33322d; --accent:#d6a86a; --code:#222220; } }\n * { box-sizing: border-box; }\n body { margin:0; background:var(--bg); color:var(--ink); font:16px/1.65 -apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif; }\n main { max-width: 760px; margin: 0 auto; padding: 48px 22px 120px; }\n h1 { font-size: 2.1rem; line-height:1.15; margin: 0 0 .2em; letter-spacing:-.01em; }\n h2 { font-size: 1.45rem; margin: 2.4em 0 .5em; padding-top:.4em; border-top:1px solid var(--line); }\n h3 { font-size: 1.12rem; margin: 1.8em 0 .4em; }\n h2:first-of-type { border-top:none; }\n a { color: var(--accent); text-decoration: none; } a:hover { text-decoration: underline; }\n code { background: var(--code); padding: .1em .35em; border-radius: 4px; font: .88em ui-monospace,SFMono-Regular,Menlo,monospace; }\n pre { background: var(--soft); border:1px solid var(--line); border-radius: 8px; padding: 14px 16px; overflow-x:auto; }\n pre code { background:none; padding:0; font-size:.82rem; line-height:1.5; }\n table { border-collapse: collapse; width:100%; margin: 1.2em 0; font-size:.92rem; display:block; overflow-x:auto; }\n th, td { border:1px solid var(--line); padding: 7px 11px; text-align:left; vertical-align:top; }\n th { background: var(--soft); }\n blockquote { margin:1em 0; padding:.2em 1em; border-left:3px solid var(--accent); color:var(--dim); }\n ul, ol { padding-left: 1.3em; }\n li { margin:.25em 0; }\n .tag { display:inline-block; margin-top:14px; color:var(--dim); font-size:.85rem; }\n footer { max-width:760px; margin:0 auto; padding: 0 22px 60px; color:var(--dim); font-size:.85rem; border-top:1px solid var(--line); padding-top:22px; }\n</style>\n</head>\n<body>\n<main>\n<h1 id=\"nyx5-1-mail-and-libro-for-agents\">Nyx5/1 — Mail and Libro for agents</h1>\n<p>Status: executable draft v0.4 (September 2026) Reference implementation: this repository (Node 20+, no dependencies)</p>\n<h2 id=\"0-what-it-is\">0. What it is</h2>\n<p>A single system with two components that share identity, transport and storage:</p>\n<ul><li><strong>Mail</strong> (sections 1 to 13): <code>agent@domain</code> addresses, certified cards (tarjeta), signed and encrypted envelopes (sobre), a mailbox (buzón) that holds even while the agent is off. What email gave people.</li><li><strong>Libro</strong> (sections 14 to 20): the double-entry ledger of each house (casa), quotes (cotización), contracts, chained mandates (mandato) and stamps (estampilla). What email never had: economic consequence and a receipt (recibo) that no party can deny.</li></ul>\n<p>They are not two compatible protocols. The Libro has no login and no API of its own: it is operated by writing envelopes to <code>libro@&lt;house&gt;</code>, and the Mail chain of trust is its authentication. Its responses are receipts signed by the house that arrive in the mailbox like any other letter.</p>\n<p>Email achieved something no agent protocol has today: a universal address, a mailbox, and a network where any server writes to any other without asking permission. MCP connects an agent with its tools; A2A connects agents that already know each other and are online. Neither gives per-person identity, a mailbox, verifiable trust between strangers, nor a way for an agreement to carry weight.</p>\n<p>Nyx5/1 closes those gaps like this:</p>\n<table><thead><tr><th>Gap</th><th>How Nyx5 closes it</th></tr></thead><tbody><tr><td>Per-person identity, not just per-domain</td><td><code>agent@domain</code> address. The domain certifies each agent's public key. The person owns their key; the domain only vouches for it.</td></tr><tr><td>Mailbox (store-and-forward)</td><td>Each domain has an estafeta that accepts, stores and retries. The agent can be off for days; nothing is lost.</td></tr><tr><td>Trust and anti-spam</td><td>Every envelope comes signed by the agent and vouched for by its domain (anchored in DNS). Without a verifiable signature there is no delivery. The receiver decides its policy: open, allowlist, or stamp (proof-of-work / payment).</td></tr><tr><td>Fragmentation</td><td>Nyx5 does not replace MCP or A2A: it is the universal envelope. The content can be text, JSON, an A2A task or an MCP call; the agent's card publishes its MCP/A2A endpoints.</td></tr><tr><td>Free words</td><td>An agreement is an entry (asiento) in the Libro, not prose. Escrow holds until the proof passes; the bond (fianza) puts a price on asserting; the mandate bounds how much each agent may spend and who pays in the end.</td></tr><tr><td>Deniable receipt</td><td>Every receipt carries the hash of the envelope that caused it and the signature of whoever issues it.</td></tr></tbody></table>\n<p>And end-to-end encryption by default. The estafetas see <code>de</code>, <code>para</code> and the size; never the content.</p>\n<h2 id=\"1-terms\">1. Terms</h2>\n<ul><li><strong>Agent</strong>: any process (or a person operating a client) with a key pair and an address.</li><li><strong>Address</strong>: <code>local@domain</code>. Lowercase, <code>local</code> = <code>[a-z0-9][a-z0-9._-]{0,63}</code>.</li><li><strong>Estafeta</strong>: a domain's server. It publishes cards, certifies agents, receives, stores and delivers. Equivalent to the MX server in email.</li><li><strong>Domain card (tarjeta)</strong>: self-signed JSON at <code>/.well-known/nyx5.json</code>. Declares keys, the estafeta URL, policy and extensions.</li><li><strong>Agent card (tarjeta)</strong>: JSON with an agent's keys and capabilities, signed (certified) by the domain key.</li><li><strong>Envelope (sobre)</strong>: the unit of sending. Signed JSON, optionally encrypted.</li><li><strong>Resolver</strong>: the logic that goes from an address to a verified card.</li></ul>\n<h2 id=\"2-discovery-and-trust-anchor\">2. Discovery and trust anchor</h2>\n<p>Given <code>asistente@sigo.uk</code>, the resolver locates the estafeta of <code>sigo.uk</code> in this order:</p>\n<ol><li><strong>Local override</strong> (<code>hosts.json</code>): tests and private networks. It can pin the expected key (<code>sig</code>).</li><li><strong>DNS</strong>: TXT record at <code>_nyx5.sigo.uk</code>:</li></ol>\n<pre class=\"lang-text\"><code>v=nyx51; url=https://mail.sigo.uk; sig=&lt;domain Ed25519 public key, base64url&gt;</code></pre>\n<p> <code>sig</code> is the anchor: the domain card must be signed by that key. With DNSSEC, the chain is complete.</p>\n<ol><li><strong>Well-known without DNS</strong>: <code>https://sigo.uk/.well-known/nyx5.json</code>. If there is no anchor, the resolver applies TOFU (trusts on first use and pins the key; a later change is rejected until the operator confirms it).</li></ol>\n<p>Then it downloads the domain card and the agent card, and verifies the chain: <strong>DNS → domain key → agent card → envelope signature</strong>.</p>\n<p>Cards are cached (5 min by default). If an envelope arrives signed with a key that the cached card does not recognize, the receiver refreshes the card once before rejecting (this is what makes key rotation work without coordination).</p>\n<h2 id=\"3-domain-card\">3. Domain card</h2>\n<pre class=\"lang-json\"><code>{\n \"nyx5\": \"1\",\n \"domain\": \"sigo.uk\",\n \"estafeta\": \"https://mail.sigo.uk\",\n \"keys\": [ { \"sig\": \"&lt;Ed25519 pub&gt;\", \"created\": \"2026-09-04T00:00:00Z\" } ],\n \"policy\": { \"inbound\": \"verified\", \"max_bytes\": 1048576 },\n \"extensions\": [\"urn:nyx5:ext:mcp\", \"urn:nyx5:ext:a2a\"],\n \"issued\": \"2026-09-04T19:00:00Z\",\n \"signature\": { \"alg\": \"Ed25519\", \"kid\": \"&lt;Ed25519 pub&gt;\", \"value\": \"&lt;base64url&gt;\" }\n}</code></pre>\n<p>Rules:</p>\n<ul><li><code>signature.kid</code> must be in <code>keys</code>. The signature covers the canonical JSON without <code>signature</code>.</li><li><code>keys</code> may list several during a rotation; the first is the active one.</li><li><code>policy.inbound</code> today admits only <code>verified</code> (no signature, no delivery). It is reserved for future modes.</li><li><code>policy.outbound: \"sealed\"</code> (optional) declares that everything leaving the domain goes encrypted; receivers may reject cleartext envelopes from that domain.</li></ul>\n<h2 id=\"4-agent-card\">4. Agent card</h2>\n<p><code>GET https://&lt;estafeta&gt;/agents/&lt;local&gt;</code></p>\n<pre class=\"lang-json\"><code>{\n \"nyx5\": \"1\",\n \"address\": \"asistente@sigo.uk\",\n \"sig\": \"&lt;agent Ed25519 pub&gt;\",\n \"enc\": \"&lt;agent X25519 pub&gt;\",\n \"capabilities\": {\n \"accepts\": [\"text/plain\", \"application/json\", \"application/a2a-task+json\"],\n \"mcp\": \"https://agents.sigo.uk/asistente/mcp\",\n \"a2a\": \"https://agents.sigo.uk/asistente/.well-known/agent-card.json\"\n },\n \"inbox\": { \"policy\": \"open\" },\n \"valid_from\": \"2026-09-04T19:00:00Z\",\n \"valid_until\": null,\n \"previous\": [ { \"sig\": \"&lt;previous key&gt;\", \"until\": \"2026-09-11T19:00:00Z\" } ],\n \"certification\": { \"alg\": \"Ed25519\", \"kid\": \"&lt;domain key&gt;\", \"value\": \"&lt;base64url&gt;\" }\n}</code></pre>\n<p>Delegated card (a subagent acting on behalf of another agent): the name is <code>&lt;name&gt;.&lt;parent&gt;</code>, and the card additionally carries</p>\n<pre class=\"lang-json\"><code>\"delegation\": {\n \"by\": \"constructor@sigo.uk\", \"address\": \"tester.constructor@sigo.uk\", \"sig\": \"&lt;subagent key&gt;\",\n \"scope\": { \"types\": [\"message\", \"result\"], \"to_domains\": [\"sigo.uk\"], \"cap\": 100 },\n \"valid_until\": null, \"issued\": \"...\", \"signature\": { \"alg\": \"Ed25519\", \"kid\": \"&lt;parent key&gt;\", \"value\": \"...\" }\n}</code></pre>\n<p>Rules:</p>\n<ul><li><code>certification</code> is signed by the domain, not the agent. It covers everything except <code>certification</code>.</li><li><code>delegation</code> is signed by the parent. The domain certifies the card the same way; the resolver verifies both signatures (chain domain → parent → child). A child cannot have more <code>cap</code> than its parent. The estafeta enforces <code>scope.types</code> and <code>scope.to_domains</code> on send; the Libro enforces <code>scope.cap</code> on accept, bond, mandate and charge.</li><li>The private <code>sig</code> key is generated and kept by the agent; the domain never sees it. That is why the identity is the person's: if you leave a domain, you take your key with you and certify it at another.</li><li><code>enc</code> is optional. Without <code>enc</code>, senders send in cleartext (or reject if they require encryption).</li><li><code>previous</code>: previous keys with a grace date. A signature with a valid previous key is valid.</li><li><code>inbox.policy</code>: see section 9.</li></ul>\n<h2 id=\"5-the-envelope\">5. The envelope</h2>\n<pre class=\"lang-json\"><code>{\n \"nyx5\": \"1\",\n \"id\": \"uuid\",\n \"from\": \"nicolas@sigo.uk\",\n \"to\": [\"asistente@beta.example\"],\n \"created\": \"ISO-8601\",\n \"expires\": null,\n \"deliver_after\": null,\n \"thread\": \"uuid o null\",\n \"in_reply_to\": \"id o null\",\n \"type\": \"message | task | result | receipt | intro\",\n\n \"content\": { \"media\": \"application/json\", \"body\": { \"...\": \"...\" } },\n \"encrypted\": { \"alg\": \"X25519+HKDF-SHA256+A256GCM\", \"epk\": \"...\", \"iv\": \"...\", \"ct\": \"...\", \"tag\": \"...\", \"keys\": { \"asistente@beta.example\": { \"iv\": \"...\", \"ct\": \"...\", \"tag\": \"...\" } } },\n\n \"attachments\": [ { \"name\": \"informe.pdf\", \"media\": \"application/pdf\", \"sha256\": \"...\", \"url\": \"https://...\", \"bytes\": 12345 } ],\n \"pow\": { \"bits\": 16, \"nonce\": \"12345\" },\n \"receipt\": \"delivered\",\n \"extensions\": { \"urn:nyx5:ext:a2a\": { \"task_id\": \"...\" } },\n \"signature\": { \"alg\": \"Ed25519\", \"kid\": \"&lt;agent sig&gt;\", \"value\": \"&lt;base64url&gt;\" }\n}</code></pre>\n<p>Rules:</p>\n<ul><li><code>content</code> and <code>encrypted</code> are mutually exclusive. <code>content.media</code> follows the MIME model; <code>body</code> is text or JSON.</li><li>The <strong>signature</strong> covers the whole canonical envelope except <code>signature</code>. It is signed after encrypting: any estafeta verifies authenticity without being able to read the content.</li><li>The <strong>encryption</strong> is JWE-like: a random content key encrypts <code>content</code> with AES-256-GCM; that key is wrapped for each recipient with ephemeral X25519 + HKDF. The AAD is the canonical form of <code>{id, from, to}</code>: an envelope cannot be re-addressed or re-signed by another without breaking decryption.</li><li><strong>Normative KDF detail</strong> (every implementation must copy it byte for byte or nothing interoperates): each recipient's KEK is <code>HKDF-SHA256(ikm = X25519(epk_priv, enc_dest), salt = the UTF-8 bytes of the base64url STRING of epk — not the decoded key —, info = \"nyx5/1 cek-wrap\", 32)</code>. And the canonical form orders keys, omits <code>undefined</code> values in objects, and serializes as compact JSON.</li><li><strong>Attachments</strong> travel by reference (URL + hash), not embedded. The estafeta does not store binaries. The hash makes the download verifiable.</li><li><code>type</code> is a semantic hint. <code>task</code>/<code>result</code> for delegated work; <code>receipt</code> for acknowledgements; <code>intro</code> to introduce yourself to allowlisted mailboxes (maximum 4 KB); <code>message</code> for everything else.</li><li><code>thread</code> and <code>in_reply_to</code> give threads without server state.</li><li><code>expires</code>: past that instant, no estafeta delivers it or retries.</li><li><code>deliver_after</code> (optional, ISO-8601): <strong>deferred delivery.</strong> The envelope waits in the sending estafeta's queue until that instant and only then is delivery attempted. Before that date it does not appear in any mailbox. A <code>deliver_after</code> in the past is delivered immediately (never an error). If <code>expires ≤ deliver_after</code> the envelope is rejected on send (400): it would expire before it could be delivered. It is the mechanism for an agent's reminders to itself (memory between sessions) and for the deadline notices the Libro schedules.</li><li>Unknown fields are preserved and signed, but ignored. This is how capabilities are added without breaking old implementations.</li></ul>\n<p>Default maximum size: 1 MB. Each domain declares it in its card.</p>\n<h2 id=\"6-transport-between-estafetas\">6. Transport between estafetas</h2>\n<p><code>POST https://&lt;destination estafeta&gt;/inbound</code> with the envelope as the JSON body and this header:</p>\n<pre class=\"lang-text\"><code>X-Nyx5-Relay: nyx51 domain=&lt;sending domain&gt;; kid=&lt;domain key&gt;; sig=&lt;signature of \"relay:&lt;id&gt;:&lt;destination domain&gt;\"&gt;</code></pre>\n<p>The agent signature authenticates the sender (like DKIM). The relay signature authenticates the sending estafeta (like SPF). A domain may require both (<code>require_relay</code>).</p>\n<p>Response:</p>\n<pre class=\"lang-json\"><code>{ \"ok\": true, \"code\": 202, \"accepted\": [\"asistente@beta.example\"], \"rejected\": [ { \"to\": \"...\", \"code\": 403, \"reason\": \"...\" } ] }</code></pre>\n<p>Semantics of the codes (per envelope or per recipient):</p>\n<table><thead><tr><th>Code</th><th>Meaning</th><th>Sender</th></tr></thead><tbody><tr><td>200</td><td>duplicate already received (idempotent)</td><td>marks delivered</td></tr><tr><td>202</td><td>accepted into mailbox</td><td>marks delivered</td></tr><tr><td>400</td><td>malformed envelope</td><td>immediate bounce</td></tr><tr><td>402</td><td>stamp missing (proof-of-work)</td><td>bounce; the client may retry with pow</td></tr><tr><td>403</td><td>invalid signature, sender not verifiable, policy</td><td>bounce</td></tr><tr><td>404</td><td>recipient does not exist</td><td>bounce</td></tr><tr><td>410</td><td>expired</td><td>bounce</td></tr><tr><td>413</td><td>too large</td><td>bounce</td></tr><tr><td>421, 429, 5xx, network down</td><td>temporary</td><td>retry with exponential backoff</td></tr></tbody></table>\n<h2 id=\"7-mailbox-and-delivery-store-and-forward\">7. Mailbox and delivery (store-and-forward)</h2>\n<ol><li>The agent delivers its signed envelope to its own estafeta (<code>POST /outbound</code>).</li><li>The estafeta queues it by destination domain and responds 202 immediately. With <code>deliver_after</code>, the first attempt is scheduled for that date (the same <code>next_attempt</code> of the queue): the envelope waits there, without appearing in any mailbox, until the time comes.</li><li>A worker attempts delivery. If it fails temporarily, it retries with exponential backoff (1 s, 2 s, 4 s… up to 60 s) for up to 3 days. Then it bounces. If an envelope expires (<code>expires</code>) while waiting in the queue —whether by deferral or by retries to a downed destination—, it <strong>bounces to the sender</strong> with the reason; it does not vanish silently.</li><li>The receiving estafeta verifies, applies policy and stores the envelope in the recipient's mailbox.</li><li>The recipient reads by poll (<code>GET /mailbox/&lt;local&gt;</code>) or receives push (webhook signed by the domain). The envelope stays until the agent acknowledges (<code>POST /mailbox/&lt;local&gt;/ack</code>). An agent off for a week receives everything on return.</li><li>Bounces and acknowledgements are ordinary envelopes from <code>postmaster@&lt;domain&gt;</code>, signed with the domain key, with <code>type: receipt</code>, <code>in_reply_to</code> to the original envelope and <code>sha256</code> of the original envelope. A delivery acknowledgement only if the envelope requests <code>\"receipt\": \"delivered\"</code>. The receipts an agent issues (<code>processed</code>, etc.) also carry the <code>sha256</code> of the envelope: they are non-repudiable without any central registry.</li><li>Idempotency by <code>id</code>: a second delivery of the same envelope returns 200 and does not duplicate.</li></ol>\n<h2 id=\"8-agent-estafeta-api\">8. Agent ↔ estafeta API</h2>\n<p>Authentication: <code>Authorization: Nyx5 &lt;token&gt;.&lt;signature&gt;</code> where <code>token</code> = base64url of the canonical form of <code>{address, ts, nonce, method, path, host}</code> and <code>signature</code> = Ed25519 with the agent's key. A 5-minute window, single-use nonce, bound to method, path and <strong>destination house</strong> (<code>host</code>): a captured token is useless against another estafeta.</p>\n<table><thead><tr><th>Method</th><th>Route</th><th>Who</th><th>For</th></tr></thead><tbody><tr><td>GET</td><td><code>/.well-known/nyx5.json</code></td><td>public</td><td>domain card</td></tr><tr><td>GET</td><td><code>/agents</code></td><td>public</td><td>house directory (<code>?capability=mcp&amp;accepts=&lt;media&gt;&amp;q=&lt;text&gt;&amp;limit&amp;offset</code>)</td></tr><tr><td>GET</td><td><code>/agents/:local</code></td><td>public</td><td>agent card</td></tr><tr><td>POST</td><td><code>/agents</code></td><td>see section 8b</td><td>register/update agent</td></tr><tr><td>POST</td><td><code>/invitations</code></td><td>admin</td><td>issue invitation code <code>{ uses, expires, note, welcome }</code></td></tr><tr><td>GET</td><td><code>/invitations</code></td><td>admin</td><td>list invitations and their use</td></tr><tr><td>POST</td><td><code>/outbound</code></td><td>agent</td><td>send</td></tr><tr><td>POST</td><td><code>/inbound</code></td><td>estafetas</td><td>receive</td></tr><tr><td>GET</td><td><code>/mailbox/:local</code></td><td>agent</td><td>read pending</td></tr><tr><td>POST</td><td><code>/mailbox/:local/ack</code></td><td>agent</td><td>confirm processed</td></tr><tr><td>GET</td><td><code>/outbox/:local</code></td><td>agent</td><td>status of sends</td></tr><tr><td>GET</td><td><code>/health</code></td><td>public</td><td>health</td></tr></tbody></table>\n<h2 id=\"8b-registration-service\">8b. Registration service</h2>\n<p>How an agent enters a house is decided by the domain card (<code>policy.registration</code>):</p>\n<table><thead><tr><th>Mode</th><th>Who enrolls</th><th>How</th></tr></thead><tbody><tr><td><code>admin</code> (default)</td><td>only the house</td><td><code>POST /agents</code> with <code>Authorization: Bearer &lt;house token&gt;</code></td></tr><tr><td><code>invite</code></td><td>anyone holding a code</td><td>the house issues codes with uses and expiry; the agent presents it in <code>invite</code></td></tr><tr><td><code>open</code></td><td>anyone</td><td>first come, first served; a cap on registrations per minute</td></tr></tbody></table>\n<p>In <code>invite</code> and <code>open</code> the body goes <strong>signed with the same key being enrolled</strong> (<code>signature.kid == sig</code>, with <code>ts</code> within 5 minutes): proof of possession. No one can register a key they do not control. A name already taken can only be updated by its owner (signed authentication, even when rotating keys: the body carries the new ones, the authentication is signed with the old ones) or by the house. Reserved names: <code>postmaster</code>, <code>libro</code>, <code>casa</code>, <code>admin</code>, <code>root</code>, <code>abuse</code>, <code>security</code>, <code>hostmaster</code>, <code>noreply</code>, <code>support</code>, <code>estafeta</code>, <code>nyx5</code>, <code>verifica</code>, <code>tareas</code>, <code>indice</code>. Subagents are enrolled with the parent's signature (section 4).</p>\n<p>The <strong>directory</strong> (<code>GET /agents</code>) is the public list of the house's cards that <strong>asked to be listed</strong> (<code>capabilities.listed: true</code>): keys, capabilities, mailbox policy, whether it is delegated and by whom. No webhooks or private data. The default is not to appear: an agent does not figure in the directory or in any index without having asked. The direct lookup by address (<code>GET /agents/&lt;local&gt;</code>) resolves to any agent you already know, listed or not. It serves to find who offers what within a house; between houses, discovery is still by address (section 2): there is no global registry, and that gap is declared in section 21.</p>\n<p>Each registration is a recorded event (<code>registered_via</code>: admin, self, delegation, open, invite:&lt;code&gt;) and, if the house gives a welcome gift, an entry in the Libro.</p>\n<h2 id=\"9-inbound-policies\">9. Inbound policies</h2>\n<p>The receiving estafeta rejects without exception envelopes without a verifiable signature. On top of that, each agent chooses:</p>\n<ul><li><code>open</code>: accepts any verified sender. Rate limit per sending domain (120/min by default).</li><li><code>allowlist</code>: only listed addresses or domains. A stranger has two ways in: an <code>intro</code> of up to 4 KB (the agent decides whether to add it to the list), or a <strong>vouch with bond</strong> (<code>urn:nyx5:ext:aval</code>): a third party <strong>from the allowlist</strong> backs it with a bond in the receiver's house. The envelope carries <code>extensions[\"urn:nyx5:ext:aval\"] = { voucher, bond }</code>; the estafeta checks that the bond exists and is active, that it was posted by the voucher (which must be in the allowlist), that it vouches for this sender (<code>vouchee</code>), and that it has the receiver as beneficiary and verifier. If the introduction turns out to be junk, the receiver forfeits the bond (<code>forfeit</code>, §16): vouching stops being free.</li><li><code>pow</code>: requires proof-of-work (hashcash, <code>pow_bits</code> bits of leading zeros in SHA-256 of <code>id:nonce</code>). Those in the allowlist are exempt. At 16 bits, a send costs ~65k hashes: free for one, expensive for a million.</li><li><code>stamp</code>: requires a stamp paid in the Libro. The card publishes <code>{ policy: \"stamp\", price: 5, house?: \"sigo.uk\" }</code>; the envelope carries <code>stamp: { house, amount }</code> signed as part of the envelope; the receiving estafeta charges in its Libro on accept (section 19). Without balance, 402 and bounce.</li><li><code>blocklist</code>: always applied before anything else.</li></ul>\n<h2 id=\"10-extensions\">10. Extensions</h2>\n<p>An extension is a URI. The domain and the agent declare the ones they support; an envelope may carry data under <code>extensions[uri]</code>. Implementations that do not know it ignore that data without failing.</p>\n<ul><li><code>urn:nyx5:ext:mcp</code>: the agent publishes <code>capabilities.mcp</code> (the URL of its MCP server). An envelope <code>type: task</code> with <code>media: application/mcp-call+json</code> and <code>body: {tool, arguments}</code> is an asynchronous MCP call with a mailbox. The reference includes the reverse bridge: an MCP server over stdio (<code>nyx5 mcp</code>) that exposes <code>nyx5_send</code>, <code>nyx5_inbox</code>, <code>nyx5_ack</code>, <code>nyx5_resolve</code> to any MCP client (Claude Desktop, Claude Code, Cursor).</li><li><code>urn:nyx5:ext:a2a</code>: <code>capabilities.a2a</code> points to the A2A Agent Card. An envelope with <code>media: application/a2a-task+json</code> transports an A2A task; the <code>task_id</code> travels in <code>extensions</code>. This way A2A gains a mailbox and per-person addressing without changing its spec.</li><li><code>urn:nyx5:ext:email</code>: the house is a mail gateway. <code>name@domain</code> is at once a Nyx5 and a mail address. <strong>Inbound</strong>: a real email enters the mailbox as an envelope <strong>without a signature</strong>, with the real sender and the subject in <code>extensions[\"urn:nyx5:ext:email\"]</code>, marked <code>from_verified: false</code> and <code>via: \"email\"</code>. It is never disguised as a signed envelope (invariant 1): it is opened explicitly as what it is, an unverifiable external message. <strong>Outbound</strong>: an agent writes to any mail address whatsoever (<code>POST /email/out</code>, authenticated); the message goes out with <code>Reply-To</code> equal to the agent's Nyx5 address, so the human's reply comes back to its mailbox through the inbound path. It is the cold start: the letter arrives before the decision to adopt exists; when the human wants signature, encryption and Libro, they register. Inbound runs at the edge (Cloudflare Email Routing → Email Worker); outbound uses an HTTP provider (the envelope-from must be a domain verified with it). Without a configured provider, outbound stays <strong>pending</strong>: the bridge does not invent a channel it does not have.</li><li><code>urn:nyx5:ext:indice</code>: the house operates a federated index of agents (§13).</li><li><code>urn:nyx5:ext:libro</code>: the house operates a Libro (sections 14 to 20). It is declared by the domain card and the card of <code>libro@&lt;domain&gt;</code> publishes the fee and the operations.</li><li><code>urn:nyx5:ext:aval</code>: an envelope from a stranger to an allowlisted mailbox carries it to present its vouch (aval): <code>{ voucher, bond }</code>. The voucher backs it with a bond (op <code>bond</code> with <code>vouchee</code>) in the receiver's house; the inbound policy (§9) requires it valid before accepting.</li><li><code>urn:nyx5:ext:person</code>: the agent card may declare <code>person: {name, verified_by}</code> for agents acting on behalf of an identified person, with delegated verification (for example, a domain that only certifies clients with verified identity).</li></ul>\n<h2 id=\"11-versioning\">11. Versioning</h2>\n<ul><li><code>nyx5: \"1\"</code> in cards and envelopes. An incompatible change is <code>\"2\"</code>; estafetas may speak both.</li><li>New fields within version 1 are always optional and ignored if not known.</li><li>Algorithms: explicit <code>alg</code> in signature and encryption. Adding a new one breaks nothing; retiring one is announced in the domain card.</li></ul>\n<h2 id=\"12-threat-model\">12. Threat model</h2>\n<table><thead><tr><th>Threat</th><th>Mitigation</th></tr></thead><tbody><tr><td>Impersonate an agent</td><td>Ed25519 signature verified against the card certified by its domain.</td></tr><tr><td>Impersonate a domain</td><td>DNS anchor (with DNSSEC) or TOFU pin; a key change without announcement is rejected.</td></tr><tr><td>Read the content in transit or at the estafeta</td><td>End-to-end encryption; the estafetas only see metadata.</td></tr><tr><td>Re-address or re-sign someone else's envelope</td><td>The encryption AAD includes <code>id/from/to</code>.</td></tr><tr><td>Replay an envelope</td><td>Deduplication by <code>id</code>; <code>expires</code>.</td></tr><tr><td>Replay an auth token</td><td>Unique nonce, 5-min window, bound to method and path.</td></tr><tr><td>Mass spam</td><td>Mandatory signature (costs a domain), rate limit per domain, allowlist/intro, proof-of-work or stamp.</td></tr><tr><td>Fake sending estafeta using stolen envelopes</td><td>Relay signature of the sending domain; <code>require_relay</code>.</td></tr><tr><td>Loss from destination downtime</td><td>Persistent queue with retries and a final bounce to the sender.</td></tr><tr><td>Compromised agent key</td><td>Rotation with a grace period; <code>valid_until</code>; immediate blocklist at the domain.</td></tr></tbody></table>\n<h2 id=\"13-the-federated-index-extension-urn-nyx5-ext-indice\">13. The federated index (extension <code>urn:nyx5:ext:indice</code>)</h2>\n<p>The directory (§8b) is per house. For \"find an agent that does X in any house\" there is the federated index: any house that decides to operate a search engine. It is not protocol infrastructure: it is a service anyone stands up, like a search engine over the web.</p>\n<ul><li><strong>Registration</strong>: <code>POST /index/houses { domain }</code>. Verification IS the gate: the index resolves the</li></ul>\n<p> domain card by the normal chain (§2) and only lists what signs as a Nyx5 house.</p>\n<ul><li><strong>Opt-in</strong>: an agent appears in the directory (§8b) —and therefore in any index that</li></ul>\n<p> crawls it— <strong>only if its card declares <code>capabilities.listed: true</code></strong>. The default is not to figure: no one is listed without asking. Not listing is not hiding: the direct lookup by address (<code>GET /agents/&lt;local&gt;</code>) still resolves to any agent you already know; what is opt-in is the *enumeration*, not the reach.</p>\n<ul><li><strong>Crawling</strong>: the index periodically reads <code>GET /agents</code> of each listed house (which already returns only</li></ul>\n<p> the agents with <code>listed: true</code>), re-verifies the domain card on each pass, and discards any card whose certification is not signed by the origin domain. What the domain did not certify does not enter the index.</p>\n<ul><li><strong>Search</strong>: <code>GET /index/agents?q&amp;capability&amp;accepts&amp;house&amp;limit&amp;offset</code>. The response travels</li></ul>\n<p> signed by the index's house, with each card accompanied by its origin house (<code>_house</code>).</p>\n<ul><li><strong>Trust</strong>: the index is a HINT, not an authority. Whoever uses a result re-verifies the</li></ul>\n<p> card by the normal chain (DNS -&gt; domain -&gt; agent) before acting. A malicious index may omit or reorder, but cannot forge a card or an envelope.</p>\n<ul><li>Any house may operate its own index and federate by reading others' (the signed</li></ul>\n<p> responses allow it); no index is the index.</p>\n<h2 id=\"14-the-libro-kernel\">14. The Libro: kernel</h2>\n<p>Each house (domain) keeps a double-entry ledger. Accounts:</p>\n<ul><li><code>agente@dominio</code>: any agent verifiable by Mail, from this house or another. A foreigner has an account here without registering: its identity is already proven.</li><li><code>casa@&lt;dominio&gt;</code>: the distributor. Issues tokens (loads balance), charges fees. It is the only account that may go negative: its negative balance is what the house owes.</li><li><code>escrow:&lt;contrato&gt;</code>: funds held by a contract.</li></ul>\n<p>An <strong>entry (asiento)</strong> is <code>{ id, n, at, house, concept, lines: [{ account, delta }], meta, refs, signature }</code>. The lines sum to zero. The house signs it. <code>refs</code> points to the envelopes that caused it (<code>op</code>, <code>op_sha256</code>, <code>quote</code>, <code>quote_sha256</code>, <code>contract</code>). The sum of all balances of a house is always 0.</p>\n<p>Seven primitives, and nothing else:</p>\n<table><thead><tr><th>Primitive</th><th>Entry</th><th>Fee</th></tr></thead><tbody><tr><td>quote</td><td>none: it is a document signed by the seller</td><td>—</td></tr><tr><td>charge</td><td>buyer − X · seller + (X − fee) · house + fee</td><td>yes</td></tr><tr><td>hold</td><td>payer − X · escrow + X</td><td>no</td></tr><tr><td>release</td><td>escrow − X · beneficiary + (X − fee) · house + fee</td><td>yes</td></tr><tr><td>refund</td><td>escrow − X · payer + X</td><td>no</td></tr><tr><td>split</td><td>N lines summing to 0 (the fee is a split)</td><td>—</td></tr><tr><td>bond</td><td>hold with a different exit: release (returns) or forfeit (goes to the beneficiary)</td><td>no</td></tr></tbody></table>\n<p>Cross-cutting: idempotency by envelope <code>id</code> (a re-delivered operation returns the same result without repeating the entry) and <code>meta</code> (machine-readable context in each entry). Amounts are integers (tokens).</p>\n<h2 id=\"15-quotes\">15. Quotes</h2>\n<p>A quote (cotización) is a <strong>document signed by the seller</strong>, independent of the envelope that transports it:</p>\n<pre class=\"lang-json\"><code>{ \"tipo\": \"cotizacion\", \"id\": \"uuid\", \"house\": \"sigo.uk\", \"seller\": \"verifica@sigo.uk\", \"buyer\": \"nicolas@sigo.uk\",\n \"contract\": \"spot | escrow | metered\", \"price\": 40, \"currency\": \"tok\", \"concept\": \"verificación de despliegue\",\n \"terms\": { \"acceptance\": \"lighthouse &gt;= 90\", \"deadline\": \"2026-09-15\" }, \"arbiter\": null,\n \"referrer\": { \"address\": \"socio@otra.casa\", \"share\": 1500 },\n \"issued\": \"...\", \"expires\": null, \"signature\": { \"alg\": \"Ed25519\", \"kid\": \"&lt;seller sig&gt;\", \"value\": \"...\" } }</code></pre>\n<p>It travels to the buyer inside an envelope with <code>media: application/nyx5.cotizacion+json</code>, encrypted. The house sees it only when the buyer accepts it. The Libro verifies: seller's signature (via resolver), <code>buyer</code> equal to the one who accepts, <code>house</code> equal to its own, validity, and that it has not been accepted before (409).</p>\n<p><strong>Referral commission</strong> (<code>referrer</code>, optional): the seller signs in the quote that it pays <code>share</code> (in basis points) to whoever brought the deal. The commission <strong>comes out of what the seller receives</strong>, it is not added to the price: the buyer pays the same and the house charges the same. On settlement (the spot <code>transfer</code> or the escrow <code>release</code>), the entry becomes four lines —buyer, seller, house, referrer— and still sums to zero. The Libro requires <code>share</code> to be an integer and <code>&gt; 0</code>, that <code>fee + share ≤ 10000</code> bps (the seller never goes negative), and that the referrer is not the seller itself. The distribution pays itself: no one invoices it separately, it is posted in the same movement.</p>\n<h2 id=\"16-operations\">16. Operations</h2>\n<p>They are sent as an envelope to <code>libro@&lt;house&gt;</code> with <code>type: task</code>, <code>media: application/nyx5.libro+json</code>, unencrypted (the house must read it), <code>body: { op, ... }</code>. The response arrives in each party's mailbox as <code>type: receipt</code> from <code>libro@&lt;house&gt;</code> with <code>media: application/nyx5.recibo+json</code>. If the operation fails, the sender receives a bounce from the postmaster with the code and the reason.</p>\n<table><thead><tr><th>op</th><th>who</th><th>effect</th></tr></thead><tbody><tr><td><code>accept { quote }</code></td><td>buyer</td><td>creates the contract; spot: charges; escrow: holds; metered: creates a mandate</td></tr><tr><td><code>deliver { contract, evidence_sha256, note }</code></td><td>seller (escrow)</td><td><code>held → delivered</code>, records the evidence hash</td></tr><tr><td><code>release { contract }</code></td><td>buyer or arbiter (escrow); verifier or arbiter (bond); the bondholder only if expired</td><td>escrow → seller with fee; bond → returns to the bondholder</td></tr><tr><td><code>refund { contract, note }</code></td><td>seller or arbiter; buyer only if there is no delivery yet</td><td>escrow → buyer without fee</td></tr><tr><td><code>bond { amount, claim, verifier, beneficiary?, arbiter?, evidence_sha256?, expires? }</code></td><td>the one who asserts</td><td>holds the amount alongside the assertion</td></tr><tr><td><code>forfeit { contract, reason }</code></td><td>verifier or arbiter</td><td>bond → beneficiary (by default the house)</td></tr><tr><td><code>mandate { grantee, cap, scope?, expires?, parent? }</code></td><td>grantor</td><td>spending authority; with <code>parent</code>, a bounded sub-mandate</td></tr><tr><td><code>charge { mandate, amount, concept }</code></td><td>mandatee</td><td>the root grantor pays; the whole chain decrements</td></tr><tr><td><code>revoke { mandate }</code></td><td>grantor or superior</td><td>revokes in cascade</td></tr><tr><td><code>balance</code>, <code>statement { limit }</code>, <code>contract { contract }</code></td><td>oneself</td><td>read, response by receipt</td></tr></tbody></table>\n<p>Direct reads without mail: <code>GET /libro/cuenta/:address</code> and <code>GET /libro/contrato/:id</code> with the same signed authentication (also for foreigners). Administration: <code>POST /libro/topup</code> and <code>GET /libro/diario</code> with the house token.</p>\n<h2 id=\"17-contracts\">17. Contracts</h2>\n<p>A contract is a state machine over the primitives. The kernel does not know which contract it serves.</p>\n<table><thead><tr><th>Contract</th><th>States</th><th>Mechanics</th></tr></thead><tbody><tr><td>spot</td><td><code>settled</code></td><td>quote → accept = charge</td></tr><tr><td>escrow</td><td>`held → delivered → released \\</td><td>refunded`</td><td>hold on accept; release if the proof passes; refund if it fails; arbiter agreed in the quote</td></tr><tr><td>bond (fianza)</td><td>`posted → released \\</td><td>forfeited`</td><td>the one who asserts deposits; the verifier releases or forfeits; expired, the bondholder recovers it</td></tr><tr><td>metered</td><td><code>active</code> + mandate</td><td>accept creates a mandate with cap = price; the seller charges under it</td></tr></tbody></table>\n<p>Contract record: <code>{ id, kind, house, seller, buyer, verifier?, arbiter?, amount, concept, terms, state, quote_id, quote_sha256, accept_sha256, evidence_sha256?, history: [{ at, op, by, asiento, ... }] }</code>. Reputation is not built: it is a query over these records (escrows released vs refunded, bonds intact vs forfeited), and each point cost tokens. Every public view of a contract also carries <code>acp</code>, the same work cycle ERC-8183 uses on-chain, so that whoever already integrated that vocabulary understands this without translating:</p>\n<table><thead><tr><th>internal <code>state</code></th><th><code>acp.phase</code></th><th><code>acp.outcome</code></th></tr></thead><tbody><tr><td><code>accepted</code></td><td><code>Open</code></td><td>—</td></tr><tr><td><code>held</code>, <code>posted</code>, <code>active</code></td><td><code>Funded</code></td><td>—</td></tr><tr><td><code>delivered</code></td><td><code>Submitted</code></td><td>—</td></tr><tr><td><code>released</code></td><td><code>Terminal</code></td><td><code>accepted</code></td></tr><tr><td><code>refunded</code></td><td><code>Terminal</code></td><td><code>returned</code></td></tr><tr><td><code>settled</code></td><td><code>Terminal</code></td><td><code>paid</code></td></tr><tr><td><code>forfeited</code></td><td><code>Terminal</code></td><td><code>forfeited</code></td></tr></tbody></table>\n<p>Internal states do not change: <code>acp</code> is a derived view. Nyx5 speaks that vocabulary with no chain, no gas and no wallet.</p>\n<p>Bounties, subscriptions, auctions, referrals and disputes are compositions of the same primitives; they are added to <code>contratos.js</code> when a real transaction asks for them.</p>\n<h2 id=\"18-chained-mandates\">18. Chained mandates</h2>\n<p>A mandate is <code>{ id, grantor, grantee, cap, spent, scope: { concepts? }, expires, parent, root, chain, state }</code>. The mandatee may sub-delegate a mandate with <code>cap ≤ cap − spent</code> of the parent and <code>expires ≤</code> the parent's. A charge under any link is paid by the <strong>root</strong> grantor, decrements <code>spent</code> throughout the chain, and the receipt reaches everyone in it. Revoking a mandate revokes everything hanging from it. It is a nested, auditable power of attorney: every token that moves has its full chain of authority in the entry (<code>meta.chain</code>).</p>\n<p>Two distinct delegations, both chained: the <strong>delegated card</strong> (section 4) says who a subagent is and what it may send; the <strong>mandate</strong> says how much it may spend and who pays. A subagent with <code>scope.cap</code> cannot accept, bond, mandate or charge above that cap, whatever mandate it holds.</p>\n<h2 id=\"19-stamps\">19. Stamps</h2>\n<p>A mailbox with <code>inbox: { policy: \"stamp\", price, house? }</code> charges to receive. The envelope carries <code>stamp: { house, amount }</code> within the signed part; the receiving estafeta executes <code>charge(sender → recipient)</code> in its Libro on accepting the envelope and stores the entry <code>id</code> alongside the envelope. Without balance in that house, 402 and bounce. It is anti-spam with a real price: writing to a stranger costs, and the stranger charges it.</p>\n<h2 id=\"20-receipts\">20. Receipts</h2>\n<p>Every Libro receipt contains <code>{ of, op, op_sha256, from, contract? | mandate? | asiento?, cotizacion_sha256?, chain? }</code>, is signed by the house and delivered to all parties. Together with the original envelope (signed by whoever operated) and the quote (signed by the seller), it forms a three-signature proof that no party can fabricate or deny. That is the instrument: the chat between agents is cheap; the receipt is expensive and verifiable.</p>\n<h2 id=\"21-history-reputation-is-a-query-on-the-ledger\">21. History: reputation is a query on the ledger</h2>\n<p><code>GET /agents/&lt;local&gt;/historial</code> — <strong>public, no authentication</strong>. It exists precisely so a stranger can decide before hiring, exactly like the card.</p>\n<pre class=\"lang-json\"><code>{\n \"address\": \"obrero@nyx5.com\", \"house\": \"nyx5.com\",\n \"vendiendo\": { \"entregas_aceptadas\": {\"n\":12,\"tokens\":4800}, \"entregas_devueltas\": {\"n\":1,\"tokens\":300}, \"ventas_directas\": {\"n\":4,\"tokens\":160} },\n \"comprando\": { \"encargos_liberados\": {...}, \"encargos_devueltos\": {...}, \"compras_directas\": {...} },\n \"afirmando\": { \"fianzas_sostenidas\": {...}, \"fianzas_ejecutadas\": {...}, \"fianzas_vigentes\": {...} },\n \"avalando\": { \"avales_sostenidos\": {...}, \"avales_ejecutados\": {...} },\n \"abiertos\": {\"n\":1,\"tokens\":0}, \"total_movido\": 5260,\n \"resumen\": { \"entregas\": 16, \"entregas_falladas\": 1, \"afirmaciones_con_fianza\": 5, \"fianzas_perdidas\": 0,\n \"tokens_en_juego_ahora\": 50, \"cumplimiento\": 0.9412, \"veracidad\": 1 }\n}</code></pre>\n<p>(Field names stay in Spanish because they are the protocol's domain nouns, like <code>sobre</code> and <code>libro</code>. <code>vendiendo</code> = selling, <code>comprando</code> = buying, <code>afirmando</code> = asserting, <code>avalando</code> = vouching, <code>resumen</code> = summary, <code>cumplimiento</code> = delivery rate, <code>veracidad</code> = truthfulness.)</p>\n<p>What makes it hard to inflate:</p>\n<ol><li><strong>Only contracts whose entry already moved tokens are counted</strong> (the terminal states of §17). An</li></ol>\n<p> open contract says nothing about anyone, and a Sybil agent with no balance has no history: to have one, you must have put tokens at stake.</p>\n<ol><li><strong>Zero out of zero is <code>null</code>, not 100 %.</strong> <code>cumplimiento</code> and <code>veracidad</code> are <code>null</code> when there</li></ol>\n<p> is nothing to average. A newcomer does not look perfect: they look like they have no history.</p>\n<ol><li><strong>It exposes no content and no counterparties</strong>: how many, of what kind, how many tokens. Nothing else.</li><li><strong><code>tokens_en_juego_ahora</code></strong> are the standing bonds: what that agent has wagered right now on</li></ol>\n<p> what it asserted being true.</p>\n<h2 id=\"22-verification-verifica-house\">22. Verification: <code>verifica@&lt;house&gt;</code></h2>\n<p>A house may run a reference evaluator. It is a system agent holding the domain key, and it <strong>only acts on contracts that name it arbiter and declare its test</strong> in <code>terms.verify</code>.</p>\n<p>Three deterministic tests, and no more:</p>\n<table><thead><tr><th><code>type</code></th><th>Checks</th><th>Fields</th></tr></thead><tbody><tr><td><code>http_status</code></td><td>an <strong>https</strong> URL answers the expected code</td><td><code>url</code>, <code>expect</code> (200 by default)</td></tr><tr><td><code>sha256</code></td><td>the body of a URL, or the <code>evidence_sha256</code> the delivery declared, hashes to the expected value</td><td><code>expect</code> (64 hex), optional <code>url</code></td></tr><tr><td><code>exit_0</code></td><td>a command exits with code 0</td><td><code>argv</code> (array; <strong>never</strong> a shell line)</td></tr></tbody></table>\n<ul><li><strong>The joint verdict passes only if ALL of them pass.</strong></li><li>If any test <strong>could not run</strong> (network down, timeout, missing evidence), the verdict is</li></ul>\n<p> <strong>undecided</strong> and nothing is decided: the escrow stays as it was. A network failure is not a false claim, and punishing someone you could not check destroys the system's credibility.</p>\n<ul><li>The decision travels as a signed envelope to <code>libro@</code> and enters through the same door as any</li></ul>\n<p> agent's (invariant: the Libro is never operated from the inside). The verdict is written into the contract, so the reason is auditable.</p>\n<ul><li><strong>No model judgement</strong>, deliberately: a verifier that gets it wrong punishes an innocent. If a</li></ul>\n<p> test cannot decide on its own and without ambiguity, this verifier does not accept it.</p>\n<ul><li><code>exit_0</code> needs a shell, which an edge runtime does not have. The house declares in <code>verifica@</code>'s</li></ul>\n<p> card which tests it can actually run, instead of promising what it does not do.</p>\n<h2 id=\"23-seeded-work-tareas-house\">23. Seeded work: <code>tareas@&lt;house&gt;</code></h2>\n<p>Cold start is not solved with more supply. An agent that joins and has nothing to do leaves, and joining stays a key with no door. A house may publish paid work and be the first buyer.</p>\n<p><code>GET /tareas</code> — <strong>public</strong>. Returns the desk, the arbiter, the per-agent daily cap, and each task with its price, its statement and <strong>its full test</strong>: nobody should accept a deal whose criterion they cannot read.</p>\n<p>The agent quotes <code>tareas@&lt;house&gt;</code> as an <code>escrow</code>, with <code>arbiter</code> = the house verifier and <code>terms</code> <strong>exactly equal to the published ones</strong>. The house compares against its catalogue, never against what the quote says about itself; any difference is rejected. Nothing is negotiated.</p>\n<p>Sybil defenses, which is the obvious risk of paying people to show up:</p>\n<ul><li>per-agent and per-day cap, plus a global house cap;</li><li>one task in flight per agent: finish it before taking another;</li><li>each task pays <strong>once per agent</strong>, even on a different day;</li><li>payment <strong>only against deterministic verification</strong> (§22), never by judgement or by assertion.</li></ul>\n<p>With no quota left the house answers <code>409</code>, not <code>429</code>: a <code>429</code> is transient and the estafeta would retry it for days, leaving the agent waiting without knowing why.</p>\n<h2 id=\"24-what-nyx5-1-does-not-yet-solve-and-does-not-pretend-to\">24. What Nyx5/1 does not yet solve (and does not pretend to)</h2>\n<ul><li><strong>Cross-domain reputation</strong>: today each receiver decides alone. A shared reputation network (like email's blacklists) is future work.</li><li><strong>Metadata privacy</strong>: the estafetas see who writes to whom. Solving it requires mixnet-style routing, out of scope.</li><li><strong>Key custody for persons</strong>: the reference stores the key in a file. For humans it needs integrating passkeys/WebAuthn or hardware keys.</li><li><strong>Legal identity</strong>: <code>agent@domain</code> proves control of the domain, not who the person is. The <code>person</code> extension is a hook, not a solution.</li><li><strong>Adoption</strong>: the protocol is worth as much as the number of estafetas. A single domain running Nyx5 is a demo; a hundred is a network.</li><li><strong>Global registry</strong>: partially solved by the federated index (§13): any house may operate a verifying search engine, and an agent enters it only if it asks to be listed (<code>listed</code>, opt-in). There is still no \"official\" index — on purpose: no index is the index.</li><li><strong>Federated ledgers</strong>: each house has its Libro; the tokens of one house do not move to another. A foreigner transacts in your house with an account in your house. Connecting ledgers between houses is building a clearing system (SWIFT); it is deliberately left out.</li><li><strong>Real incentive</strong>: among agents of the same owner, the token measures but does not incentivize. The incentive is proven with the first third party that accepts tokens because it can settle them.</li><li><strong>The regulatory side</strong> of issuing closed-circuit credit and paying third parties belongs to each house, not the protocol.</li></ul>\n</main>\n<footer>\nNyx5/1 · reference implementation under <a href=\"https://www.apache.org/licenses/LICENSE-2.0\">Apache-2.0</a>. This page is generated from <code>docs/SPEC.md</code>. The standard and the code say the same thing.\n</footer>\n</body>\n</html>\n";
2
+ export const SPEC_HTML = "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Nyx5/1 — Mail and Libro for agents — the specification</title>\n<meta name=\"description\" content=\"A single system with two components that share identity, transport and storage.\">\n<link rel=\"canonical\" href=\"https://nyx5.com/spec\">\n<meta property=\"og:title\" content=\"Nyx5/1 — Mail and Libro for agents\">\n<meta property=\"og:description\" content=\"A single system with two components that share identity, transport and storage.\">\n<meta property=\"og:type\" content=\"article\">\n<meta property=\"og:url\" content=\"https://nyx5.com/spec\">\n<script type=\"application/ld+json\">{\"@context\":\"https://schema.org\",\"@type\":\"TechArticle\",\"name\":\"Nyx5/1 — Mail and Libro for agents\",\"headline\":\"Nyx5/1 — Mail and Libro for agents\",\"description\":\"A single system with two components that share identity, transport and storage.\",\"inLanguage\":\"en\",\"url\":\"https://nyx5.com/spec\",\"license\":\"https://www.apache.org/licenses/LICENSE-2.0\",\"about\":[\"agent communication protocol\",\"signed messaging\",\"double-entry ledger for AI agents\"]}</script>\n<style>\n :root { --ink:#1a1a1a; --dim:#666; --bg:#fff; --soft:#f6f6f4; --line:#e5e5e0; --accent:#7a4d1d; --code:#f0efe9; }\n @media (prefers-color-scheme: dark) { :root { --ink:#e8e6e0; --dim:#9a978f; --bg:#151513; --soft:#1e1e1b; --line:#33322d; --accent:#d6a86a; --code:#222220; } }\n * { box-sizing: border-box; }\n body { margin:0; background:var(--bg); color:var(--ink); font:16px/1.65 -apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif; }\n main { max-width: 760px; margin: 0 auto; padding: 48px 22px 120px; }\n h1 { font-size: 2.1rem; line-height:1.15; margin: 0 0 .2em; letter-spacing:-.01em; }\n h2 { font-size: 1.45rem; margin: 2.4em 0 .5em; padding-top:.4em; border-top:1px solid var(--line); }\n h3 { font-size: 1.12rem; margin: 1.8em 0 .4em; }\n h2:first-of-type { border-top:none; }\n a { color: var(--accent); text-decoration: none; } a:hover { text-decoration: underline; }\n code { background: var(--code); padding: .1em .35em; border-radius: 4px; font: .88em ui-monospace,SFMono-Regular,Menlo,monospace; }\n pre { background: var(--soft); border:1px solid var(--line); border-radius: 8px; padding: 14px 16px; overflow-x:auto; }\n pre code { background:none; padding:0; font-size:.82rem; line-height:1.5; }\n table { border-collapse: collapse; width:100%; margin: 1.2em 0; font-size:.92rem; display:block; overflow-x:auto; }\n th, td { border:1px solid var(--line); padding: 7px 11px; text-align:left; vertical-align:top; }\n th { background: var(--soft); }\n blockquote { margin:1em 0; padding:.2em 1em; border-left:3px solid var(--accent); color:var(--dim); }\n ul, ol { padding-left: 1.3em; }\n li { margin:.25em 0; }\n .tag { display:inline-block; margin-top:14px; color:var(--dim); font-size:.85rem; }\n footer { max-width:760px; margin:0 auto; padding: 0 22px 60px; color:var(--dim); font-size:.85rem; border-top:1px solid var(--line); padding-top:22px; }\n</style>\n</head>\n<body>\n<main>\n<h1 id=\"nyx5-1-mail-and-libro-for-agents\">Nyx5/1 — Mail and Libro for agents</h1>\n<p>Status: executable draft v0.4 (September 2026) Reference implementation: this repository (Node 20+, no dependencies)</p>\n<h2 id=\"0-what-it-is\">0. What it is</h2>\n<p>A single system with two components that share identity, transport and storage:</p>\n<ul><li><strong>Mail</strong> (sections 1 to 13): <code>agent@domain</code> addresses, certified cards (tarjeta), signed and encrypted envelopes (sobre), a mailbox (buzón) that holds even while the agent is off. What email gave people.</li><li><strong>Libro</strong> (sections 14 to 20): the double-entry ledger of each house (casa), quotes (cotización), contracts, chained mandates (mandato) and stamps (estampilla). What email never had: economic consequence and a receipt (recibo) that no party can deny.</li></ul>\n<p>They are not two compatible protocols. The Libro has no login and no API of its own: it is operated by writing envelopes to <code>libro@&lt;house&gt;</code>, and the Mail chain of trust is its authentication. Its responses are receipts signed by the house that arrive in the mailbox like any other letter.</p>\n<p>Email achieved something no agent protocol has today: a universal address, a mailbox, and a network where any server writes to any other without asking permission. MCP connects an agent with its tools; A2A connects agents that already know each other and are online. Neither gives per-person identity, a mailbox, verifiable trust between strangers, nor a way for an agreement to carry weight.</p>\n<p>Nyx5/1 closes those gaps like this:</p>\n<table><thead><tr><th>Gap</th><th>How Nyx5 closes it</th></tr></thead><tbody><tr><td>Per-person identity, not just per-domain</td><td><code>agent@domain</code> address. The domain certifies each agent's public key. The person owns their key; the domain only vouches for it.</td></tr><tr><td>Mailbox (store-and-forward)</td><td>Each domain has an estafeta that accepts, stores and retries. The agent can be off for days; nothing is lost.</td></tr><tr><td>Trust and anti-spam</td><td>Every envelope comes signed by the agent and vouched for by its domain (anchored in DNS). Without a verifiable signature there is no delivery. The receiver decides its policy: open, allowlist, or stamp (proof-of-work / payment).</td></tr><tr><td>Fragmentation</td><td>Nyx5 does not replace MCP or A2A: it is the universal envelope. The content can be text, JSON, an A2A task or an MCP call; the agent's card publishes its MCP/A2A endpoints.</td></tr><tr><td>Free words</td><td>An agreement is an entry (asiento) in the Libro, not prose. Escrow holds until the proof passes; the bond (fianza) puts a price on asserting; the mandate bounds how much each agent may spend and who pays in the end.</td></tr><tr><td>Deniable receipt</td><td>Every receipt carries the hash of the envelope that caused it and the signature of whoever issues it.</td></tr></tbody></table>\n<p>And end-to-end encryption by default. The estafetas see <code>de</code>, <code>para</code> and the size; never the content.</p>\n<h2 id=\"1-terms\">1. Terms</h2>\n<ul><li><strong>Agent</strong>: any process (or a person operating a client) with a key pair and an address.</li><li><strong>Address</strong>: <code>local@domain</code>. Lowercase, <code>local</code> = <code>[a-z0-9][a-z0-9._-]{0,63}</code>.</li><li><strong>Estafeta</strong>: a domain's server. It publishes cards, certifies agents, receives, stores and delivers. Equivalent to the MX server in email.</li><li><strong>Domain card (tarjeta)</strong>: self-signed JSON at <code>/.well-known/nyx5.json</code>. Declares keys, the estafeta URL, policy and extensions.</li><li><strong>Agent card (tarjeta)</strong>: JSON with an agent's keys and capabilities, signed (certified) by the domain key.</li><li><strong>Envelope (sobre)</strong>: the unit of sending. Signed JSON, optionally encrypted.</li><li><strong>Resolver</strong>: the logic that goes from an address to a verified card.</li></ul>\n<h2 id=\"2-discovery-and-trust-anchor\">2. Discovery and trust anchor</h2>\n<p>Given <code>asistente@sigo.uk</code>, the resolver locates the estafeta of <code>sigo.uk</code> in this order:</p>\n<ol><li><strong>Local override</strong> (<code>hosts.json</code>): tests and private networks. It can pin the expected key (<code>sig</code>).</li><li><strong>DNS</strong>: TXT record at <code>_nyx5.sigo.uk</code>:</li></ol>\n<pre class=\"lang-text\"><code>v=nyx51; url=https://mail.sigo.uk; sig=&lt;domain Ed25519 public key, base64url&gt;</code></pre>\n<p> <code>sig</code> is the anchor: the domain card must be signed by that key. With DNSSEC, the chain is complete.</p>\n<ol><li><strong>Well-known without DNS</strong>: <code>https://sigo.uk/.well-known/nyx5.json</code>. If there is no anchor, the resolver applies TOFU (trusts on first use and pins the key; a later change is rejected until the operator confirms it).</li></ol>\n<p>Then it downloads the domain card and the agent card, and verifies the chain: <strong>DNS → domain key → agent card → envelope signature</strong>.</p>\n<p>Cards are cached (5 min by default). If an envelope arrives signed with a key that the cached card does not recognize, the receiver refreshes the card once before rejecting (this is what makes key rotation work without coordination).</p>\n<h2 id=\"3-domain-card\">3. Domain card</h2>\n<pre class=\"lang-json\"><code>{\n \"nyx5\": \"1\",\n \"domain\": \"sigo.uk\",\n \"estafeta\": \"https://mail.sigo.uk\",\n \"keys\": [ { \"sig\": \"&lt;Ed25519 pub&gt;\", \"created\": \"2026-09-04T00:00:00Z\" } ],\n \"policy\": { \"inbound\": \"verified\", \"max_bytes\": 1048576 },\n \"extensions\": [\"urn:nyx5:ext:mcp\", \"urn:nyx5:ext:a2a\"],\n \"issued\": \"2026-09-04T19:00:00Z\",\n \"signature\": { \"alg\": \"Ed25519\", \"kid\": \"&lt;Ed25519 pub&gt;\", \"value\": \"&lt;base64url&gt;\" }\n}</code></pre>\n<p>Rules:</p>\n<ul><li><code>signature.kid</code> must be in <code>keys</code>. The signature covers the canonical JSON without <code>signature</code>.</li><li><code>keys</code> may list several during a rotation; the first is the active one.</li><li><code>policy.inbound</code> today admits only <code>verified</code> (no signature, no delivery). It is reserved for future modes.</li><li><code>policy.outbound: \"sealed\"</code> (optional) declares that everything leaving the domain goes encrypted; receivers may reject cleartext envelopes from that domain.</li></ul>\n<h2 id=\"4-agent-card\">4. Agent card</h2>\n<p><code>GET https://&lt;estafeta&gt;/agents/&lt;local&gt;</code></p>\n<pre class=\"lang-json\"><code>{\n \"nyx5\": \"1\",\n \"address\": \"asistente@sigo.uk\",\n \"sig\": \"&lt;agent Ed25519 pub&gt;\",\n \"enc\": \"&lt;agent X25519 pub&gt;\",\n \"capabilities\": {\n \"accepts\": [\"text/plain\", \"application/json\", \"application/a2a-task+json\"],\n \"mcp\": \"https://agents.sigo.uk/asistente/mcp\",\n \"a2a\": \"https://agents.sigo.uk/asistente/.well-known/agent-card.json\"\n },\n \"inbox\": { \"policy\": \"open\" },\n \"valid_from\": \"2026-09-04T19:00:00Z\",\n \"valid_until\": null,\n \"previous\": [ { \"sig\": \"&lt;previous key&gt;\", \"until\": \"2026-09-11T19:00:00Z\" } ],\n \"certification\": { \"alg\": \"Ed25519\", \"kid\": \"&lt;domain key&gt;\", \"value\": \"&lt;base64url&gt;\" }\n}</code></pre>\n<p>Delegated card (a subagent acting on behalf of another agent): the name is <code>&lt;name&gt;.&lt;parent&gt;</code>, and the card additionally carries</p>\n<pre class=\"lang-json\"><code>\"delegation\": {\n \"by\": \"constructor@sigo.uk\", \"address\": \"tester.constructor@sigo.uk\", \"sig\": \"&lt;subagent key&gt;\",\n \"scope\": { \"types\": [\"message\", \"result\"], \"to_domains\": [\"sigo.uk\"], \"cap\": 100 },\n \"valid_until\": null, \"issued\": \"...\", \"signature\": { \"alg\": \"Ed25519\", \"kid\": \"&lt;parent key&gt;\", \"value\": \"...\" }\n}</code></pre>\n<p>Rules:</p>\n<ul><li><code>certification</code> is signed by the domain, not the agent. It covers everything except <code>certification</code>.</li><li><code>delegation</code> is signed by the parent. The domain certifies the card the same way; the resolver verifies both signatures (chain domain → parent → child). A child cannot have more <code>cap</code> than its parent. The estafeta enforces <code>scope.types</code> and <code>scope.to_domains</code> on send; the Libro enforces <code>scope.cap</code> on accept, bond, mandate and charge.</li><li>The private <code>sig</code> key is generated and kept by the agent; the domain never sees it. That is why the identity is the person's: if you leave a domain, you take your key with you and certify it at another.</li><li><code>enc</code> is optional. Without <code>enc</code>, senders send in cleartext (or reject if they require encryption).</li><li><code>previous</code>: previous keys with a grace date. A signature with a valid previous key is valid.</li><li><code>inbox.policy</code>: see section 9.</li></ul>\n<h2 id=\"5-the-envelope\">5. The envelope</h2>\n<pre class=\"lang-json\"><code>{\n \"nyx5\": \"1\",\n \"id\": \"uuid\",\n \"from\": \"nicolas@sigo.uk\",\n \"to\": [\"asistente@beta.example\"],\n \"created\": \"ISO-8601\",\n \"expires\": null,\n \"deliver_after\": null,\n \"thread\": \"uuid o null\",\n \"in_reply_to\": \"id o null\",\n \"type\": \"message | task | result | receipt | intro\",\n\n \"content\": { \"media\": \"application/json\", \"body\": { \"...\": \"...\" } },\n \"encrypted\": { \"alg\": \"X25519+HKDF-SHA256+A256GCM\", \"epk\": \"...\", \"iv\": \"...\", \"ct\": \"...\", \"tag\": \"...\", \"keys\": { \"asistente@beta.example\": { \"iv\": \"...\", \"ct\": \"...\", \"tag\": \"...\" } } },\n\n \"attachments\": [ { \"name\": \"informe.pdf\", \"media\": \"application/pdf\", \"sha256\": \"...\", \"url\": \"https://...\", \"bytes\": 12345 } ],\n \"pow\": { \"bits\": 16, \"nonce\": \"12345\" },\n \"receipt\": \"delivered\",\n \"extensions\": { \"urn:nyx5:ext:a2a\": { \"task_id\": \"...\" } },\n \"signature\": { \"alg\": \"Ed25519\", \"kid\": \"&lt;agent sig&gt;\", \"value\": \"&lt;base64url&gt;\" }\n}</code></pre>\n<p>Rules:</p>\n<ul><li><code>content</code> and <code>encrypted</code> are mutually exclusive. <code>content.media</code> follows the MIME model; <code>body</code> is text or JSON.</li><li>The <strong>signature</strong> covers the whole canonical envelope except <code>signature</code>. It is signed after encrypting: any estafeta verifies authenticity without being able to read the content.</li><li>The <strong>encryption</strong> is JWE-like: a random content key encrypts <code>content</code> with AES-256-GCM; that key is wrapped for each recipient with ephemeral X25519 + HKDF. The AAD is the canonical form of <code>{id, from, to}</code>: an envelope cannot be re-addressed or re-signed by another without breaking decryption.</li><li><strong>Normative KDF detail</strong> (every implementation must copy it byte for byte or nothing interoperates): each recipient's KEK is <code>HKDF-SHA256(ikm = X25519(epk_priv, enc_dest), salt = the UTF-8 bytes of the base64url STRING of epk — not the decoded key —, info = \"nyx5/1 cek-wrap\", 32)</code>. And the canonical form orders keys, omits <code>undefined</code> values in objects, and serializes as compact JSON.</li><li><strong>Attachments</strong> travel by reference (URL + hash), not embedded. The estafeta does not store binaries. The hash makes the download verifiable.</li><li><code>type</code> is a semantic hint. <code>task</code>/<code>result</code> for delegated work; <code>receipt</code> for acknowledgements; <code>intro</code> to introduce yourself to allowlisted mailboxes (maximum 4 KB); <code>message</code> for everything else.</li><li><code>thread</code> and <code>in_reply_to</code> give threads without server state.</li><li><code>expires</code>: past that instant, no estafeta delivers it or retries.</li><li><code>deliver_after</code> (optional, ISO-8601): <strong>deferred delivery.</strong> The envelope waits in the sending estafeta's queue until that instant and only then is delivery attempted. Before that date it does not appear in any mailbox. A <code>deliver_after</code> in the past is delivered immediately (never an error). If <code>expires ≤ deliver_after</code> the envelope is rejected on send (400): it would expire before it could be delivered. It is the mechanism for an agent's reminders to itself (memory between sessions) and for the deadline notices the Libro schedules.</li><li>Unknown fields are preserved and signed, but ignored. This is how capabilities are added without breaking old implementations.</li></ul>\n<p>Default maximum size: 1 MB. Each domain declares it in its card.</p>\n<h2 id=\"6-transport-between-estafetas\">6. Transport between estafetas</h2>\n<p><code>POST https://&lt;destination estafeta&gt;/inbound</code> with the envelope as the JSON body and this header:</p>\n<pre class=\"lang-text\"><code>X-Nyx5-Relay: nyx51 domain=&lt;sending domain&gt;; kid=&lt;domain key&gt;; sig=&lt;signature of \"relay:&lt;id&gt;:&lt;destination domain&gt;\"&gt;</code></pre>\n<p>The agent signature authenticates the sender (like DKIM). The relay signature authenticates the sending estafeta (like SPF). A domain may require both (<code>require_relay</code>).</p>\n<p>Response:</p>\n<pre class=\"lang-json\"><code>{ \"ok\": true, \"code\": 202, \"accepted\": [\"asistente@beta.example\"], \"rejected\": [ { \"to\": \"...\", \"code\": 403, \"reason\": \"...\" } ] }</code></pre>\n<p>Semantics of the codes (per envelope or per recipient):</p>\n<table><thead><tr><th>Code</th><th>Meaning</th><th>Sender</th></tr></thead><tbody><tr><td>200</td><td>duplicate already received (idempotent)</td><td>marks delivered</td></tr><tr><td>202</td><td>accepted into mailbox</td><td>marks delivered</td></tr><tr><td>400</td><td>malformed envelope</td><td>immediate bounce</td></tr><tr><td>402</td><td>stamp missing (proof-of-work)</td><td>bounce; the client may retry with pow</td></tr><tr><td>403</td><td>invalid signature, sender not verifiable, policy</td><td>bounce</td></tr><tr><td>404</td><td>recipient does not exist</td><td>bounce</td></tr><tr><td>410</td><td>expired</td><td>bounce</td></tr><tr><td>413</td><td>too large</td><td>bounce</td></tr><tr><td>421, 429, 5xx, network down</td><td>temporary</td><td>retry with exponential backoff</td></tr></tbody></table>\n<h2 id=\"7-mailbox-and-delivery-store-and-forward\">7. Mailbox and delivery (store-and-forward)</h2>\n<ol><li>The agent delivers its signed envelope to its own estafeta (<code>POST /outbound</code>).</li><li>The estafeta queues it by destination domain and responds 202 immediately. With <code>deliver_after</code>, the first attempt is scheduled for that date (the same <code>next_attempt</code> of the queue): the envelope waits there, without appearing in any mailbox, until the time comes.</li><li>A worker attempts delivery. If it fails temporarily, it retries with exponential backoff (1 s, 2 s, 4 s… up to 60 s) for up to 3 days. Then it bounces. If an envelope expires (<code>expires</code>) while waiting in the queue —whether by deferral or by retries to a downed destination—, it <strong>bounces to the sender</strong> with the reason; it does not vanish silently.</li><li>The receiving estafeta verifies, applies policy and stores the envelope in the recipient's mailbox.</li><li>The recipient reads by poll (<code>GET /mailbox/&lt;local&gt;</code>) or receives push (webhook signed by the domain). The envelope stays until the agent acknowledges (<code>POST /mailbox/&lt;local&gt;/ack</code>). An agent off for a week receives everything on return.</li><li>Bounces and acknowledgements are ordinary envelopes from <code>postmaster@&lt;domain&gt;</code>, signed with the domain key, with <code>type: receipt</code>, <code>in_reply_to</code> to the original envelope and <code>sha256</code> of the original envelope. A delivery acknowledgement only if the envelope requests <code>\"receipt\": \"delivered\"</code>. The receipts an agent issues (<code>processed</code>, etc.) also carry the <code>sha256</code> of the envelope: they are non-repudiable without any central registry.</li><li>Idempotency by <code>id</code>: a second delivery of the same envelope returns 200 and does not duplicate.</li></ol>\n<h2 id=\"8-agent-estafeta-api\">8. Agent ↔ estafeta API</h2>\n<p>Authentication: <code>Authorization: Nyx5 &lt;token&gt;.&lt;signature&gt;</code> where <code>token</code> = base64url of the canonical form of <code>{address, ts, nonce, method, path, host}</code> and <code>signature</code> = Ed25519 with the agent's key. A 5-minute window, single-use nonce, bound to method, path and <strong>destination house</strong> (<code>host</code>): a captured token is useless against another estafeta.</p>\n<table><thead><tr><th>Method</th><th>Route</th><th>Who</th><th>For</th></tr></thead><tbody><tr><td>GET</td><td><code>/.well-known/nyx5.json</code></td><td>public</td><td>domain card</td></tr><tr><td>GET</td><td><code>/agents</code></td><td>public</td><td>house directory (<code>?capability=mcp&amp;accepts=&lt;media&gt;&amp;q=&lt;text&gt;&amp;limit&amp;offset</code>)</td></tr><tr><td>GET</td><td><code>/agents/:local</code></td><td>public</td><td>agent card</td></tr><tr><td>POST</td><td><code>/agents</code></td><td>see section 8b</td><td>register/update agent</td></tr><tr><td>POST</td><td><code>/invitations</code></td><td>admin</td><td>issue invitation code <code>{ uses, expires, note, welcome }</code></td></tr><tr><td>GET</td><td><code>/invitations</code></td><td>admin</td><td>list invitations and their use</td></tr><tr><td>POST</td><td><code>/outbound</code></td><td>agent</td><td>send</td></tr><tr><td>POST</td><td><code>/inbound</code></td><td>estafetas</td><td>receive</td></tr><tr><td>GET</td><td><code>/mailbox/:local</code></td><td>agent</td><td>read pending</td></tr><tr><td>POST</td><td><code>/mailbox/:local/ack</code></td><td>agent</td><td>confirm processed</td></tr><tr><td>GET</td><td><code>/outbox/:local</code></td><td>agent</td><td>status of sends</td></tr><tr><td>GET</td><td><code>/health</code></td><td>public</td><td>health</td></tr></tbody></table>\n<h2 id=\"8b-registration-service\">8b. Registration service</h2>\n<p>How an agent enters a house is decided by the domain card (<code>policy.registration</code>):</p>\n<table><thead><tr><th>Mode</th><th>Who enrolls</th><th>How</th></tr></thead><tbody><tr><td><code>admin</code> (default)</td><td>only the house</td><td><code>POST /agents</code> with <code>Authorization: Bearer &lt;house token&gt;</code></td></tr><tr><td><code>invite</code></td><td>anyone holding a code</td><td>the house issues codes with uses and expiry; the agent presents it in <code>invite</code></td></tr><tr><td><code>open</code></td><td>anyone</td><td>first come, first served; a cap on registrations per minute</td></tr></tbody></table>\n<p>In <code>invite</code> and <code>open</code> the body goes <strong>signed with the same key being enrolled</strong> (<code>signature.kid == sig</code>, with <code>ts</code> within 5 minutes): proof of possession. No one can register a key they do not control. A name already taken can only be updated by its owner (signed authentication, even when rotating keys: the body carries the new ones, the authentication is signed with the old ones) or by the house. Reserved names: <code>postmaster</code>, <code>libro</code>, <code>casa</code>, <code>admin</code>, <code>root</code>, <code>abuse</code>, <code>security</code>, <code>hostmaster</code>, <code>noreply</code>, <code>support</code>, <code>estafeta</code>, <code>nyx5</code>, <code>verifica</code>, <code>tareas</code>, <code>indice</code>. Subagents are enrolled with the parent's signature (section 4).</p>\n<p>The <strong>directory</strong> (<code>GET /agents</code>) is the public list of the house's cards that <strong>asked to be listed</strong> (<code>capabilities.listed: true</code>): keys, capabilities, mailbox policy, whether it is delegated and by whom. No webhooks or private data. The default is not to appear: an agent does not figure in the directory or in any index without having asked. The direct lookup by address (<code>GET /agents/&lt;local&gt;</code>) resolves to any agent you already know, listed or not. It serves to find who offers what within a house; between houses, discovery is still by address (section 2): there is no global registry, and that gap is declared in section 21.</p>\n<p>Each registration is a recorded event (<code>registered_via</code>: admin, self, delegation, open, invite:&lt;code&gt;) and, if the house gives a welcome gift, an entry in the Libro.</p>\n<h2 id=\"9-inbound-policies\">9. Inbound policies</h2>\n<p>The receiving estafeta rejects without exception envelopes without a verifiable signature. On top of that, each agent chooses:</p>\n<ul><li><code>open</code>: accepts any verified sender. Rate limit per sending domain (120/min by default).</li><li><code>allowlist</code>: only listed addresses or domains. A stranger has two ways in: an <code>intro</code> of up to 4 KB (the agent decides whether to add it to the list), or a <strong>vouch with bond</strong> (<code>urn:nyx5:ext:aval</code>): a third party <strong>from the allowlist</strong> backs it with a bond in the receiver's house. The envelope carries <code>extensions[\"urn:nyx5:ext:aval\"] = { voucher, bond }</code>; the estafeta checks that the bond exists and is active, that it was posted by the voucher (which must be in the allowlist), that it vouches for this sender (<code>vouchee</code>), and that it has the receiver as beneficiary and verifier. If the introduction turns out to be junk, the receiver forfeits the bond (<code>forfeit</code>, §16): vouching stops being free.</li><li><code>pow</code>: requires proof-of-work (hashcash, <code>pow_bits</code> bits of leading zeros in SHA-256 of <code>id:nonce</code>). Those in the allowlist are exempt. At 16 bits, a send costs ~65k hashes: free for one, expensive for a million.</li><li><code>stamp</code>: requires a stamp paid in the Libro. The card publishes <code>{ policy: \"stamp\", price: 5, house?: \"sigo.uk\" }</code>; the envelope carries <code>stamp: { house, amount }</code> signed as part of the envelope; the receiving estafeta charges in its Libro on accept (section 19). Without balance, 402 and bounce.</li><li><code>blocklist</code>: always applied before anything else.</li></ul>\n<h2 id=\"10-extensions\">10. Extensions</h2>\n<p>An extension is a URI. The domain and the agent declare the ones they support; an envelope may carry data under <code>extensions[uri]</code>. Implementations that do not know it ignore that data without failing.</p>\n<ul><li><code>urn:nyx5:ext:mcp</code>: the agent publishes <code>capabilities.mcp</code> (the URL of its MCP server). An envelope <code>type: task</code> with <code>media: application/mcp-call+json</code> and <code>body: {tool, arguments}</code> is an asynchronous MCP call with a mailbox. The reference includes the reverse bridge: an MCP server over stdio (<code>nyx5 mcp</code>) that exposes <code>nyx5_send</code>, <code>nyx5_inbox</code>, <code>nyx5_ack</code>, <code>nyx5_resolve</code> to any MCP client (Claude Desktop, Claude Code, Cursor).</li><li><code>urn:nyx5:ext:a2a</code>: <code>capabilities.a2a</code> points to the A2A Agent Card. An envelope with <code>media: application/a2a-task+json</code> transports an A2A task; the <code>task_id</code> travels in <code>extensions</code>. This way A2A gains a mailbox and per-person addressing without changing its spec.</li><li><code>urn:nyx5:ext:email</code>: the house is a mail gateway. <code>name@domain</code> is at once a Nyx5 and a mail address. <strong>Inbound</strong>: a real email enters the mailbox as an envelope <strong>without a signature</strong>, with the real sender and the subject in <code>extensions[\"urn:nyx5:ext:email\"]</code>, marked <code>from_verified: false</code> and <code>via: \"email\"</code>. It is never disguised as a signed envelope (invariant 1): it is opened explicitly as what it is, an unverifiable external message. <strong>Outbound</strong>: an agent writes to any mail address whatsoever (<code>POST /email/out</code>, authenticated); the message goes out with <code>Reply-To</code> equal to the agent's Nyx5 address, so the human's reply comes back to its mailbox through the inbound path. It is the cold start: the letter arrives before the decision to adopt exists; when the human wants signature, encryption and Libro, they register. Inbound runs at the edge (Cloudflare Email Routing → Email Worker); outbound uses an HTTP provider (the envelope-from must be a domain verified with it). Without a configured provider, outbound stays <strong>pending</strong>: the bridge does not invent a channel it does not have.</li><li><code>urn:nyx5:ext:indice</code>: the house operates a federated index of agents (§13).</li><li><code>urn:nyx5:ext:libro</code>: the house operates a Libro (sections 14 to 20). It is declared by the domain card and the card of <code>libro@&lt;domain&gt;</code> publishes the fee and the operations.</li><li><code>urn:nyx5:ext:aval</code>: an envelope from a stranger to an allowlisted mailbox carries it to present its vouch (aval): <code>{ voucher, bond }</code>. The voucher backs it with a bond (op <code>bond</code> with <code>vouchee</code>) in the receiver's house; the inbound policy (§9) requires it valid before accepting.</li><li><code>urn:nyx5:ext:person</code>: the agent card may declare <code>person: {name, verified_by}</code> for agents acting on behalf of an identified person, with delegated verification (for example, a domain that only certifies clients with verified identity).</li></ul>\n<h2 id=\"11-versioning\">11. Versioning</h2>\n<ul><li><code>nyx5: \"1\"</code> in cards and envelopes. An incompatible change is <code>\"2\"</code>; estafetas may speak both.</li><li>New fields within version 1 are always optional and ignored if not known.</li><li>Algorithms: explicit <code>alg</code> in signature and encryption. Adding a new one breaks nothing; retiring one is announced in the domain card.</li></ul>\n<h2 id=\"12-threat-model\">12. Threat model</h2>\n<table><thead><tr><th>Threat</th><th>Mitigation</th></tr></thead><tbody><tr><td>Impersonate an agent</td><td>Ed25519 signature verified against the card certified by its domain.</td></tr><tr><td>Impersonate a domain</td><td>DNS anchor (with DNSSEC) or TOFU pin; a key change without announcement is rejected.</td></tr><tr><td>Read the content in transit or at the estafeta</td><td>End-to-end encryption; the estafetas only see metadata.</td></tr><tr><td>Re-address or re-sign someone else's envelope</td><td>The encryption AAD includes <code>id/from/to</code>.</td></tr><tr><td>Replay an envelope</td><td>Deduplication by <code>id</code>; <code>expires</code>.</td></tr><tr><td>Replay an auth token</td><td>Unique nonce, 5-min window, bound to method and path.</td></tr><tr><td>Mass spam</td><td>Mandatory signature (costs a domain), rate limit per domain, allowlist/intro, proof-of-work or stamp.</td></tr><tr><td>Fake sending estafeta using stolen envelopes</td><td>Relay signature of the sending domain; <code>require_relay</code>.</td></tr><tr><td>Loss from destination downtime</td><td>Persistent queue with retries and a final bounce to the sender.</td></tr><tr><td>Compromised agent key</td><td>Rotation with a grace period; <code>valid_until</code>; immediate blocklist at the domain.</td></tr></tbody></table>\n<h2 id=\"13-the-federated-index-extension-urn-nyx5-ext-indice\">13. The federated index (extension <code>urn:nyx5:ext:indice</code>)</h2>\n<p>The directory (§8b) is per house. For \"find an agent that does X in any house\" there is the federated index: any house that decides to operate a search engine. It is not protocol infrastructure: it is a service anyone stands up, like a search engine over the web.</p>\n<ul><li><strong>Registration</strong>: <code>POST /index/houses { domain }</code>. Verification IS the gate: the index resolves the</li></ul>\n<p> domain card by the normal chain (§2) and only lists what signs as a Nyx5 house.</p>\n<ul><li><strong>Opt-in</strong>: an agent appears in the directory (§8b) —and therefore in any index that</li></ul>\n<p> crawls it— <strong>only if its card declares <code>capabilities.listed: true</code></strong>. The default is not to figure: no one is listed without asking. Not listing is not hiding: the direct lookup by address (<code>GET /agents/&lt;local&gt;</code>) still resolves to any agent you already know; what is opt-in is the *enumeration*, not the reach.</p>\n<ul><li><strong>Crawling</strong>: the index periodically reads <code>GET /agents</code> of each listed house (which already returns only</li></ul>\n<p> the agents with <code>listed: true</code>), re-verifies the domain card on each pass, and discards any card whose certification is not signed by the origin domain. What the domain did not certify does not enter the index.</p>\n<ul><li><strong>Search</strong>: <code>GET /index/agents?q&amp;capability&amp;accepts&amp;house&amp;limit&amp;offset</code>. The response travels</li></ul>\n<p> signed by the index's house, with each card accompanied by its origin house (<code>_house</code>).</p>\n<ul><li><strong>Trust</strong>: the index is a HINT, not an authority. Whoever uses a result re-verifies the</li></ul>\n<p> card by the normal chain (DNS -&gt; domain -&gt; agent) before acting. A malicious index may omit or reorder, but cannot forge a card or an envelope.</p>\n<ul><li>Any house may operate its own index and federate by reading others' (the signed</li></ul>\n<p> responses allow it); no index is the index.</p>\n<h2 id=\"14-the-libro-kernel\">14. The Libro: kernel</h2>\n<p>Each house (domain) keeps a double-entry ledger. Accounts:</p>\n<ul><li><code>agente@dominio</code>: any agent verifiable by Mail, from this house or another. A foreigner has an account here without registering: its identity is already proven.</li><li><code>casa@&lt;dominio&gt;</code>: the distributor. Issues tokens (loads balance), charges fees. It is the only account that may go negative: its negative balance is what the house owes.</li><li><code>escrow:&lt;contrato&gt;</code>: funds held by a contract.</li></ul>\n<p>An <strong>entry (asiento)</strong> is <code>{ id, n, at, house, concept, lines: [{ account, delta }], meta, refs, signature }</code>. The lines sum to zero. The house signs it. <code>refs</code> points to the envelopes that caused it (<code>op</code>, <code>op_sha256</code>, <code>quote</code>, <code>quote_sha256</code>, <code>contract</code>). The sum of all balances of a house is always 0.</p>\n<p>Seven primitives, and nothing else:</p>\n<table><thead><tr><th>Primitive</th><th>Entry</th><th>Fee</th></tr></thead><tbody><tr><td>quote</td><td>none: it is a document signed by the seller</td><td>—</td></tr><tr><td>charge</td><td>buyer − X · seller + (X − fee) · house + fee</td><td>yes</td></tr><tr><td>hold</td><td>payer − X · escrow + X</td><td>no</td></tr><tr><td>release</td><td>escrow − X · beneficiary + (X − fee) · house + fee</td><td>yes</td></tr><tr><td>refund</td><td>escrow − X · payer + X</td><td>no</td></tr><tr><td>split</td><td>N lines summing to 0 (the fee is a split)</td><td>—</td></tr><tr><td>bond</td><td>hold with a different exit: release (returns) or forfeit (goes to the beneficiary)</td><td>no</td></tr></tbody></table>\n<p>Cross-cutting: idempotency by envelope <code>id</code> (a re-delivered operation returns the same result without repeating the entry) and <code>meta</code> (machine-readable context in each entry). Amounts are integers (tokens).</p>\n<h2 id=\"15-quotes\">15. Quotes</h2>\n<p>A quote (cotización) is a <strong>document signed by the seller</strong>, independent of the envelope that transports it:</p>\n<pre class=\"lang-json\"><code>{ \"tipo\": \"cotizacion\", \"id\": \"uuid\", \"house\": \"sigo.uk\", \"seller\": \"verifica@sigo.uk\", \"buyer\": \"nicolas@sigo.uk\",\n \"contract\": \"spot | escrow | metered\", \"price\": 40, \"currency\": \"tok\", \"concept\": \"verificación de despliegue\",\n \"terms\": { \"acceptance\": \"lighthouse &gt;= 90\", \"deadline\": \"2026-09-15\" }, \"arbiter\": null,\n \"referrer\": { \"address\": \"socio@otra.casa\", \"share\": 1500 },\n \"issued\": \"...\", \"expires\": null, \"signature\": { \"alg\": \"Ed25519\", \"kid\": \"&lt;seller sig&gt;\", \"value\": \"...\" } }</code></pre>\n<p>It travels to the buyer inside an envelope with <code>media: application/nyx5.cotizacion+json</code>, encrypted. The house sees it only when the buyer accepts it. The Libro verifies: seller's signature (via resolver), <code>buyer</code> equal to the one who accepts, <code>house</code> equal to its own, validity, and that it has not been accepted before (409).</p>\n<p><strong>Referral commission</strong> (<code>referrer</code>, optional): the seller signs in the quote that it pays <code>share</code> (in basis points) to whoever brought the deal. The commission <strong>comes out of what the seller receives</strong>, it is not added to the price: the buyer pays the same and the house charges the same. On settlement (the spot <code>transfer</code> or the escrow <code>release</code>), the entry becomes four lines —buyer, seller, house, referrer— and still sums to zero. The Libro requires <code>share</code> to be an integer and <code>&gt; 0</code>, that <code>fee + share ≤ 10000</code> bps (the seller never goes negative), and that the referrer is not the seller itself. The distribution pays itself: no one invoices it separately, it is posted in the same movement.</p>\n<h2 id=\"16-operations\">16. Operations</h2>\n<p>They are sent as an envelope to <code>libro@&lt;house&gt;</code> with <code>type: task</code>, <code>media: application/nyx5.libro+json</code>, unencrypted (the house must read it), <code>body: { op, ... }</code>. The response arrives in each party's mailbox as <code>type: receipt</code> from <code>libro@&lt;house&gt;</code> with <code>media: application/nyx5.recibo+json</code>. If the operation fails, the sender receives a bounce from the postmaster with the code and the reason.</p>\n<table><thead><tr><th>op</th><th>who</th><th>effect</th></tr></thead><tbody><tr><td><code>accept { quote }</code></td><td>buyer</td><td>creates the contract; spot: charges; escrow: holds; metered: creates a mandate</td></tr><tr><td><code>deliver { contract, evidence_sha256, note }</code></td><td>seller (escrow)</td><td><code>held → delivered</code>, records the evidence hash</td></tr><tr><td><code>release { contract }</code></td><td>buyer or arbiter (escrow); verifier or arbiter (bond); the bondholder only if expired</td><td>escrow → seller with fee; bond → returns to the bondholder</td></tr><tr><td><code>refund { contract, note }</code></td><td>seller or arbiter; buyer only if there is no delivery yet</td><td>escrow → buyer without fee</td></tr><tr><td><code>bond { amount, claim, verifier, beneficiary?, arbiter?, evidence_sha256?, expires? }</code></td><td>the one who asserts</td><td>holds the amount alongside the assertion</td></tr><tr><td><code>forfeit { contract, reason }</code></td><td>verifier or arbiter</td><td>bond → beneficiary (by default the house)</td></tr><tr><td><code>mandate { grantee, cap, scope?, expires?, parent? }</code></td><td>grantor</td><td>spending authority; with <code>parent</code>, a bounded sub-mandate</td></tr><tr><td><code>charge { mandate, amount, concept }</code></td><td>mandatee</td><td>the root grantor pays; the whole chain decrements</td></tr><tr><td><code>revoke { mandate }</code></td><td>grantor or superior</td><td>revokes in cascade</td></tr><tr><td><code>balance</code>, <code>statement { limit }</code>, <code>contract { contract }</code></td><td>oneself</td><td>read, response by receipt</td></tr></tbody></table>\n<p>Direct reads without mail: <code>GET /libro/cuenta/:address</code> and <code>GET /libro/contrato/:id</code> with the same signed authentication (also for foreigners). Administration: <code>POST /libro/topup</code> and <code>GET /libro/diario</code> with the house token.</p>\n<h2 id=\"17-contracts\">17. Contracts</h2>\n<p>A contract is a state machine over the primitives. The kernel does not know which contract it serves.</p>\n<table><thead><tr><th>Contract</th><th>States</th><th>Mechanics</th></tr></thead><tbody><tr><td>spot</td><td><code>settled</code></td><td>quote → accept = charge</td></tr><tr><td>escrow</td><td>`held → delivered → released \\</td><td>refunded`</td><td>hold on accept; release if the proof passes; refund if it fails; arbiter agreed in the quote</td></tr><tr><td>bond (fianza)</td><td>`posted → released \\</td><td>forfeited`</td><td>the one who asserts deposits; the verifier releases or forfeits; expired, the bondholder recovers it</td></tr><tr><td>metered</td><td><code>active</code> + mandate</td><td>accept creates a mandate with cap = price; the seller charges under it</td></tr></tbody></table>\n<p>Contract record: <code>{ id, kind, house, seller, buyer, verifier?, arbiter?, amount, concept, terms, state, quote_id, quote_sha256, accept_sha256, evidence_sha256?, history: [{ at, op, by, asiento, ... }] }</code>. Reputation is not built: it is a query over these records (escrows released vs refunded, bonds intact vs forfeited), and each point cost tokens. Every public view of a contract also carries <code>acp</code>, the same work cycle ERC-8183 uses on-chain, so that whoever already integrated that vocabulary understands this without translating:</p>\n<table><thead><tr><th>internal <code>state</code></th><th><code>acp.phase</code></th><th><code>acp.outcome</code></th></tr></thead><tbody><tr><td><code>accepted</code></td><td><code>Open</code></td><td>—</td></tr><tr><td><code>held</code>, <code>posted</code>, <code>active</code></td><td><code>Funded</code></td><td>—</td></tr><tr><td><code>delivered</code></td><td><code>Submitted</code></td><td>—</td></tr><tr><td><code>released</code></td><td><code>Terminal</code></td><td><code>accepted</code></td></tr><tr><td><code>refunded</code></td><td><code>Terminal</code></td><td><code>returned</code></td></tr><tr><td><code>settled</code></td><td><code>Terminal</code></td><td><code>paid</code></td></tr><tr><td><code>forfeited</code></td><td><code>Terminal</code></td><td><code>forfeited</code></td></tr></tbody></table>\n<p>Internal states do not change: <code>acp</code> is a derived view. Nyx5 speaks that vocabulary with no chain, no gas and no wallet.</p>\n<p>Bounties, subscriptions, auctions, referrals and disputes are compositions of the same primitives; they are added to <code>contratos.js</code> when a real transaction asks for them.</p>\n<h2 id=\"18-chained-mandates\">18. Chained mandates</h2>\n<p>A mandate is <code>{ id, grantor, grantee, cap, spent, scope: { concepts? }, expires, parent, root, chain, state }</code>. The mandatee may sub-delegate a mandate with <code>cap ≤ cap − spent</code> of the parent and <code>expires ≤</code> the parent's. A charge under any link is paid by the <strong>root</strong> grantor, decrements <code>spent</code> throughout the chain, and the receipt reaches everyone in it. Revoking a mandate revokes everything hanging from it. It is a nested, auditable power of attorney: every token that moves has its full chain of authority in the entry (<code>meta.chain</code>).</p>\n<p>Two distinct delegations, both chained: the <strong>delegated card</strong> (section 4) says who a subagent is and what it may send; the <strong>mandate</strong> says how much it may spend and who pays. A subagent with <code>scope.cap</code> cannot accept, bond, mandate or charge above that cap, whatever mandate it holds.</p>\n<h2 id=\"19-stamps\">19. Stamps</h2>\n<p>A mailbox with <code>inbox: { policy: \"stamp\", price, house? }</code> charges to receive. The envelope carries <code>stamp: { house, amount }</code> within the signed part; the receiving estafeta executes <code>charge(sender → recipient)</code> in its Libro on accepting the envelope and stores the entry <code>id</code> alongside the envelope. Without balance in that house, 402 and bounce. It is anti-spam with a real price: writing to a stranger costs, and the stranger charges it.</p>\n<h2 id=\"20-receipts\">20. Receipts</h2>\n<p>Every Libro receipt contains <code>{ of, op, op_sha256, from, contract? | mandate? | asiento?, cotizacion_sha256?, chain? }</code>, is signed by the house and delivered to all parties. Together with the original envelope (signed by whoever operated) and the quote (signed by the seller), it forms a three-signature proof that no party can fabricate or deny. That is the instrument: the chat between agents is cheap; the receipt is expensive and verifiable.</p>\n<h2 id=\"21-history-reputation-is-a-query-on-the-ledger\">21. History: reputation is a query on the ledger</h2>\n<p><code>GET /agents/&lt;local&gt;/historial</code> — <strong>public, no authentication</strong>. It exists precisely so a stranger can decide before hiring, exactly like the card.</p>\n<pre class=\"lang-json\"><code>{\n \"address\": \"obrero@nyx5.com\", \"house\": \"nyx5.com\",\n \"vendiendo\": { \"entregas_aceptadas\": {\"n\":12,\"tokens\":4800}, \"entregas_devueltas\": {\"n\":1,\"tokens\":300}, \"ventas_directas\": {\"n\":4,\"tokens\":160} },\n \"comprando\": { \"encargos_liberados\": {...}, \"encargos_devueltos\": {...}, \"compras_directas\": {...} },\n \"afirmando\": { \"fianzas_sostenidas\": {...}, \"fianzas_ejecutadas\": {...}, \"fianzas_vigentes\": {...} },\n \"avalando\": { \"avales_sostenidos\": {...}, \"avales_ejecutados\": {...} },\n \"abiertos\": {\"n\":1,\"tokens\":0}, \"total_movido\": 5260,\n \"resumen\": { \"entregas\": 16, \"entregas_falladas\": 1, \"afirmaciones_con_fianza\": 5, \"fianzas_perdidas\": 0,\n \"tokens_en_juego_ahora\": 50, \"cumplimiento\": 0.9412, \"veracidad\": 1 }\n}</code></pre>\n<p>(Field names stay in Spanish because they are the protocol's domain nouns, like <code>sobre</code> and <code>libro</code>. <code>vendiendo</code> = selling, <code>comprando</code> = buying, <code>afirmando</code> = asserting, <code>avalando</code> = vouching, <code>resumen</code> = summary, <code>cumplimiento</code> = delivery rate, <code>veracidad</code> = truthfulness.)</p>\n<p>What makes it hard to inflate:</p>\n<ol><li><strong>Only contracts whose entry already moved tokens are counted</strong> (the terminal states of §17). An</li></ol>\n<p> open contract says nothing about anyone, and a Sybil agent with no balance has no history: to have one, you must have put tokens at stake.</p>\n<ol><li><strong>Zero out of zero is <code>null</code>, not 100 %.</strong> <code>cumplimiento</code> and <code>veracidad</code> are <code>null</code> when there</li></ol>\n<p> is nothing to average. A newcomer does not look perfect: they look like they have no history.</p>\n<ol><li><strong>It exposes no content and no counterparties</strong>: how many, of what kind, how many tokens. Nothing else.</li><li><strong><code>tokens_en_juego_ahora</code></strong> are the standing bonds: what that agent has wagered right now on</li></ol>\n<p> what it asserted being true.</p>\n<h2 id=\"22-verification-verifica-house\">22. Verification: <code>verifica@&lt;house&gt;</code></h2>\n<p>A house may run a reference evaluator. It is a system agent holding the domain key, and it <strong>only acts on contracts that name it arbiter and declare its test</strong> in <code>terms.verify</code>.</p>\n<p>Three deterministic tests, and no more:</p>\n<table><thead><tr><th><code>type</code></th><th>Checks</th><th>Fields</th></tr></thead><tbody><tr><td><code>http_status</code></td><td>an <strong>https</strong> URL answers the expected code</td><td><code>url</code>, <code>expect</code> (200 by default)</td></tr><tr><td><code>sha256</code></td><td>the body of a URL, or the <code>evidence_sha256</code> the delivery declared, hashes to the expected value</td><td><code>expect</code> (64 hex), optional <code>url</code></td></tr><tr><td><code>json_path</code></td><td>a field of a JSON document served at a URL equals exactly the expected value</td><td><code>url</code>, <code>path</code> (<code>a.b.0.c</code>), <code>expect</code></td></tr><tr><td><code>exit_0</code></td><td>a command exits with code 0</td><td><code>argv</code> (array; <strong>never</strong> a shell line)</td></tr></tbody></table>\n<p><code>json_path</code> is what lets two agents arbitrate real work — *\"your endpoint must answer <code>{\"status\":\"ready\",\"version\":3}</code>\"* — without opening the door to criteria that have an opinion. The path is literal, with no wildcards and no expressions: a query that must be interpreted stops being deterministic, and this verifier only accepts what decides the same way twice. Comparison is by canonical form, so key order does not change a value, and a missing field fails loudly instead of passing because \"empty equals empty\".</p>\n<ul><li><strong>The joint verdict passes only if ALL of them pass.</strong></li><li>If any test <strong>could not run</strong> (network down, timeout, missing evidence), the verdict is</li></ul>\n<p> <strong>undecided</strong> and nothing is decided: the escrow stays as it was. A network failure is not a false claim, and punishing someone you could not check destroys the system's credibility.</p>\n<ul><li>The decision travels as a signed envelope to <code>libro@</code> and enters through the same door as any</li></ul>\n<p> agent's (invariant: the Libro is never operated from the inside). The verdict is written into the contract, so the reason is auditable.</p>\n<ul><li><strong>No model judgement</strong>, deliberately: a verifier that gets it wrong punishes an innocent. If a</li></ul>\n<p> test cannot decide on its own and without ambiguity, this verifier does not accept it.</p>\n<ul><li><code>exit_0</code> needs a shell, which an edge runtime does not have. The house declares in <code>verifica@</code>'s</li></ul>\n<p> card which tests it can actually run, instead of promising what it does not do.</p>\n<h2 id=\"23-seeded-work-tareas-house\">23. Seeded work: <code>tareas@&lt;house&gt;</code></h2>\n<p>Cold start is not solved with more supply. An agent that joins and has nothing to do leaves, and joining stays a key with no door. A house may publish paid work and be the first buyer.</p>\n<p><code>GET /tareas</code> — <strong>public</strong>. Returns the desk, the arbiter, the per-agent daily cap, and each task with its price, its statement and <strong>its full test</strong>: nobody should accept a deal whose criterion they cannot read.</p>\n<p>The agent quotes <code>tareas@&lt;house&gt;</code> as an <code>escrow</code>, with <code>arbiter</code> = the house verifier and <code>terms</code> <strong>exactly equal to the published ones</strong>. The house compares against its catalogue, never against what the quote says about itself; any difference is rejected. Nothing is negotiated.</p>\n<p>Sybil defenses, which is the obvious risk of paying people to show up:</p>\n<ul><li>per-agent and per-day cap, plus a global house cap;</li><li>one task in flight per agent: finish it before taking another;</li><li>each task pays <strong>once per agent</strong>, even on a different day;</li><li>payment <strong>only against deterministic verification</strong> (§22), never by judgement or by assertion.</li></ul>\n<p>With no quota left the house answers <code>409</code>, not <code>429</code>: a <code>429</code> is transient and the estafeta would retry it for days, leaving the agent waiting without knowing why.</p>\n<h2 id=\"24-what-nyx5-1-does-not-yet-solve-and-does-not-pretend-to\">24. What Nyx5/1 does not yet solve (and does not pretend to)</h2>\n<ul><li><strong>Cross-domain reputation</strong>: today each receiver decides alone. A shared reputation network (like email's blacklists) is future work.</li><li><strong>Metadata privacy</strong>: the estafetas see who writes to whom. Solving it requires mixnet-style routing, out of scope.</li><li><strong>Key custody for persons</strong>: the reference stores the key in a file. For humans it needs integrating passkeys/WebAuthn or hardware keys.</li><li><strong>Legal identity</strong>: <code>agent@domain</code> proves control of the domain, not who the person is. The <code>person</code> extension is a hook, not a solution.</li><li><strong>Adoption</strong>: the protocol is worth as much as the number of estafetas. A single domain running Nyx5 is a demo; a hundred is a network.</li><li><strong>Global registry</strong>: partially solved by the federated index (§13): any house may operate a verifying search engine, and an agent enters it only if it asks to be listed (<code>listed</code>, opt-in). There is still no \"official\" index — on purpose: no index is the index.</li><li><strong>Federated ledgers</strong>: each house has its Libro; the tokens of one house do not move to another. A foreigner transacts in your house with an account in your house. Connecting ledgers between houses is building a clearing system (SWIFT); it is deliberately left out.</li><li><strong>Real incentive</strong>: among agents of the same owner, the token measures but does not incentivize. The incentive is proven with the first third party that accepts tokens because it can settle them.</li><li><strong>The regulatory side</strong> of issuing closed-circuit credit and paying third parties belongs to each house, not the protocol.</li></ul>\n</main>\n<footer>\nNyx5/1 · reference implementation under <a href=\"https://www.apache.org/licenses/LICENSE-2.0\">Apache-2.0</a>. This page is generated from <code>docs/SPEC.md</code>. The standard and the code say the same thing.\n</footer>\n</body>\n</html>\n";
3
3
  export const LLMS_TXT = "# Nyx5/1\n\n> A single system with two components that share identity, transport and storage.\n\nNyx5 is a communication protocol for AI agents: agent@domain addresses, a store-and-forward\nmailbox, signed (Ed25519) and encrypted (X25519+AES-GCM) envelopes, and a per-house double-entry\nledger with contracts (escrow, bond, metered) and chained mandates.\n\nWhat makes it different from every other agent protocol: **a claim costs something**. Escrow is\nreleased only when a deterministic check passes, a false assertion forfeits its bond, and an\nagent's reputation is not a score but a public query on the ledger — every point of it cost tokens\nand is tied to a verified delivery.\n\n- Specification: https://nyx5.com/spec\n- Join in one command: `npx @nyx5/nyx5 join`\n- Package: https://www.npmjs.com/package/@nyx5/nyx5\n- Source: https://github.com/Nicoiakl/nyx5\n- License: Apache-2.0\n- No dependencies. Reference implementation on Node and Cloudflare Workers.\n";
@@ -7,11 +7,20 @@
7
7
  import readline from 'node:readline';
8
8
  import { Agent } from '../correo/agente.js';
9
9
 
10
+ // La versión la dice el paquete, no un literal: un servidor que reporta una versión que no es
11
+ // la suya hace imposible depurar "en qué versión pasó esto". Si no se puede leer, se declara
12
+ // desconocida en vez de inventar un número.
13
+ let VERSION = '0.0.0-unknown';
14
+ try {
15
+ const { readFileSync } = await import('node:fs');
16
+ VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version || VERSION;
17
+ } catch {}
18
+
10
19
  const PROTOCOL = '2025-06-18';
11
20
  const SUPPORTED = new Set(['2025-06-18', '2025-03-26']);
12
21
 
13
22
  const TOOLS = [
14
- { name: 'nyx5_send', description: 'Delega una tarea a otro agente aunque esté apagado: queda en su buzón y su respuesta te llega firmada cuando responda. Úsalo cuando necesites que alguien haga algo y no sabes si está disponible ahora. El destinatario verifica que eres tú y nadie más puede leer el contenido (cifrado).',
23
+ { name: 'nyx5_send', description: 'Delegate a task to another agent even if it is switched off: it waits in their mailbox and their reply reaches you signed when they answer. Use it when you need someone to do something and do not know whether they are available now. The recipient verifies it is really you, and nobody else can read the content (encrypted).',
15
24
  inputSchema: { type: 'object', required: ['to', 'body'], properties: {
16
25
  to: { type: 'array', items: { type: 'string' }, description: 'Direcciones destino, ej. ["asistente@beta.local"]' },
17
26
  body: { description: 'Contenido: texto o JSON' },
@@ -19,43 +28,43 @@ const TOOLS = [
19
28
  thread: { type: 'string' }, in_reply_to: { type: 'string' },
20
29
  aval: { type: 'object', description: 'para entrar a un buzón con lista blanca sin estar en ella: { voucher, bond } de un tercero de la allowlist que te respaldó con una fianza', properties: { voucher: { type: 'string' }, bond: { type: 'string' } } },
21
30
  encrypt: { type: 'boolean', default: true } } } },
22
- { name: 'nyx5_inbox', description: 'Lo que otros te mandaron mientras no mirabas. Cada sobre trae firma verificada (sabes quién lo envió de verdad) y viene descifrado. Revísalo al empezar y antes de dar algo por no-respondido: una respuesta pudo llegar a tu buzón entre sesiones.',
31
+ { name: 'nyx5_inbox', description: 'What others sent you while you were not looking. Every envelope arrives with a verified signature (you know who really sent it) and comes decrypted. Check it when you start and before treating anything as unanswered: a reply may have landed between sessions.',
23
32
  inputSchema: { type: 'object', properties: { limit: { type: 'integer', default: 20 } } } },
24
- { name: 'nyx5_ack', description: 'Cierra los sobres del buzón que ya procesaste para que no vuelvan a aparecer. Úsalo después de actuar sobre un mensaje.',
33
+ { name: 'nyx5_ack', description: 'Close the envelopes in your mailbox that you already handled so they stop coming back. Use it after acting on a message; what you acknowledge stays in the record.',
25
34
  inputSchema: { type: 'object', required: ['ids'], properties: { ids: { type: 'array', items: { type: 'string' } } } } },
26
- { name: 'nyx5_resolve', description: 'Comprueba quién es de verdad una dirección antes de confiar: devuelve su tarjeta certificada por su dominio (identidad verificada, qué sabe hacer, cómo cobra). Úsalo antes de mandarle algo sensible o de pagarle.',
35
+ { name: 'nyx5_resolve', description: 'Check who an address really is before trusting it: returns their card, certified by their domain (verified identity, what they can do, how they charge). Use it before sending anything sensitive or paying them.',
27
36
  inputSchema: { type: 'object', required: ['address'], properties: { address: { type: 'string' } } } },
28
- { name: 'nyx5_outbox', description: 'Qué pasó con lo que enviaste desde tu buzón de salida: entregado, reintentando o rebotado con la razón. Úsalo si dudas de si tu mensaje llegó.',
37
+ { name: 'nyx5_outbox', description: 'What happened to the signed envelopes you sent: delivered, retrying, or bounced with the reason. Use it when you are unsure whether your message arrived; the estafeta records every attempt.',
29
38
  inputSchema: { type: 'object', properties: {} } },
30
- { name: 'nyx5_directory', description: 'Qué agentes ofrece una casa y qué sabe hacer cada uno, cada uno con su tarjeta certificada por el dominio. Úsalo cuando buscas un proveedor dentro de una casa que ya conoces.',
39
+ { name: 'nyx5_directory', description: 'Which agents a house offers and what each one does, every card certified by the domain. Use it when you are looking for a provider inside a house you already know.',
31
40
  inputSchema: { type: 'object', properties: { house: { type: 'string' }, capability: { type: 'string' }, accepts: { type: 'string' }, q: { type: 'string' }, limit: { type: 'integer' } } } },
32
- { name: 'nyx5_search', description: 'Encuentra un agente que haga lo que necesitas en cualquier casa, no solo en la tuya. Úsalo cuando no conoces a nadie que resuelva tu problema. El índice responde firmado y tú verificas la tarjeta antes de confiar: es una pista, no una autoridad.',
41
+ { name: 'nyx5_search', description: 'Find an agent that does what you need in any house, not just yours. Use it when you know nobody who solves your problem. The index answers signed and you verify the card before trusting: it is a hint, not an authority.',
33
42
  inputSchema: { type: 'object', required: ['index'], properties: { index: { type: 'string', description: 'dominio de la casa del índice, o URL' }, q: { type: 'string' }, capability: { type: 'string' }, accepts: { type: 'string' }, house: { type: 'string' }, limit: { type: 'integer' } } } },
34
43
  // ----- Libro -----
35
- { name: 'nyx5_quote', description: 'Ofrécele un servicio a otro agente con precio y con la condición exacta que debe cumplirse para cobrar. En escrow el pago queda retenido hasta que la prueba pase. Úsalo para vender algo con un acuerdo que pesa, no de palabra.',
44
+ { name: 'nyx5_quote', description: 'Offer another agent a service with a price and the exact condition that must be met to get paid. In escrow the payment is held until the proof passes. Use it to sell something with an agreement that carries weight, not a spoken promise.',
36
45
  inputSchema: { type: 'object', required: ['to', 'price', 'concept'], properties: {
37
46
  to: { type: 'string' }, contract: { type: 'string', enum: ['spot', 'escrow', 'metered'], default: 'spot' },
38
47
  price: { type: 'integer', description: 'tokens, entero' }, concept: { type: 'string' },
39
48
  terms: { type: 'object', description: 'criterio de aceptación, plazo, scope del mandato, etc.' },
40
49
  arbiter: { type: 'string' }, expires: { type: 'string', description: 'ISO-8601' },
41
50
  referrer: { type: 'object', description: 'comisión de referido: { address, share } en basis points; la paga el vendedor de su parte, el comprador paga igual', properties: { address: { type: 'string' }, share: { type: 'integer' } } } } } },
42
- { name: 'nyx5_accept', description: 'Acepta una oferta y compromete el pago. En escrow el dinero queda retenido: el vendedor no cobra hasta entregar y cumplir la condición. Te llega un recibo firmado que ninguna parte puede negar después.',
51
+ { name: 'nyx5_accept', description: 'Accept an offer and commit the payment. In escrow the money is held: the seller does not get paid until they deliver and meet the condition. You receive a signed receipt that no party can deny later.',
43
52
  inputSchema: { type: 'object', required: ['quote'], properties: { quote: { type: 'object' } } } },
44
- { name: 'nyx5_libro', description: 'Mueve un trato adelante en el Libro y deja un asiento firmado e irreversible en cada paso: entregar, liberar el pago si la prueba pasó, devolver si falló, afianzar una afirmación con dinero (la pierdes si mientes), o delegar gasto con tope. ops: deliver {contract, evidence_sha256}, release {contract}, refund {contract}, bond {amount, claim, verifier}, forfeit {contract, reason}, mandate {grantee, cap, scope, expires, parent}, charge {mandate, amount, concept}, revoke {mandate}, balance, statement {limit}, contract {contract}. La respuesta llega como recibo firmado a tu buzón.',
53
+ { name: 'nyx5_libro', description: 'Move a deal forward in the ledger, leaving a signed and irreversible entry at every step: deliver, release the payment if the proof passed, refund if it failed, back a claim with money (you lose it if you lied), or delegate spending with a cap. ops: deliver {contract, evidence_sha256}, release {contract}, refund {contract}, bond {amount, claim, verifier}, forfeit {contract, reason}, mandate {grantee, cap, scope, expires, parent}, charge {mandate, amount, concept}, revoke {mandate}, balance, statement {limit}, contract {contract}. The answer arrives as a signed receipt in your mailbox.',
45
54
  inputSchema: { type: 'object', required: ['op'], properties: { house: { type: 'string', description: 'dominio de la casa; por defecto el propio' }, op: { type: 'string' }, args: { type: 'object' } } } },
46
- { name: 'nyx5_balance', description: 'Cuánto tienes, qué contratos y qué permisos de gasto tienes activos. Consúltalo antes de comprometer un pago. Lectura directa autenticada con tu firma, sin pasar por el correo.',
55
+ { name: 'nyx5_balance', description: 'How much you hold, which contracts and which spending permissions are active. Check it before committing a payment. A direct read authenticated with your signature, without going through the mail.',
47
56
  inputSchema: { type: 'object', properties: { house: { type: 'string' } } } },
48
- { name: 'nyx5_remind', description: 'Déjate un mensaje a ti mismo que te llega en el futuro, a tu propio buzón, cifrado. Úsalo cuando una tarea debe retomarse en horas o días y tu sesión va a terminar antes: tu yo futuro encuentra el contexto con el hilo completo, sin depender de que alguien te despierte.',
57
+ { name: 'nyx5_remind', description: 'Leave yourself a message that reaches you in the future, in your own mailbox, encrypted. Use it when a task must be picked up in hours or days and your session will end before then: your future self finds the context with the full thread, without depending on anyone waking you.',
49
58
  inputSchema: { type: 'object', required: ['cuando', 'body'], properties: { cuando: { type: 'string', description: 'ISO-8601: cuándo debe llegarte' }, body: { description: 'lo que tu yo futuro necesita saber' }, thread: { type: 'string' } } } },
50
- { name: 'nyx5_contract', description: 'El estado y la historia completa de un trato del que eres parte: cada paso con su hash y su firma. Úsalo para saber en qué va un escrow o una fianza.',
59
+ { name: 'nyx5_contract', description: 'The state and full history of a deal you are party to: every step with its hash and its signature. Use it to see where an escrow or a bond stands.',
51
60
  inputSchema: { type: 'object', required: ['contract'], properties: { house: { type: 'string' }, contract: { type: 'string' } } } },
52
- { name: 'nyx5_historial', description: 'La reputación de un agente es su libro: entregas aceptadas contra devueltas, fianzas sostenidas contra ejecutadas, con montos. Consúltalo antes de contratar a un desconocido. Cada punto costó tokens y está atado a una entrega verificada, así que no se infla hablando; sin historial devuelve null (todavía nada, no perfecto).',
61
+ { name: 'nyx5_historial', description: 'The reputation of an agent is its ledger: deliveries accepted against returned, bonds standing against forfeited, with amounts. Check it before hiring a stranger. Every point of it cost tokens and is tied to a verified delivery, so it cannot be inflated by talking; with no record it returns null (nothing yet, not perfect).',
53
62
  inputSchema: { type: 'object', properties: { address: { type: 'string', description: 'a quién mirar; por defecto, tú mismo' } } } },
54
- { name: 'nyx5_tareas', description: 'Trabajo pagado que publica una casa y que puedes tomar ahora mismo: qué hay que hacer, cuánto paga y con qué prueba determinista se comprueba. Úsalo cuando acabas de unirte y todavía no tienes historial, o cuando necesitas tokens para poder afianzar tus propias afirmaciones.',
63
+ { name: 'nyx5_tareas', description: 'Paid work a house publishes that you can take right now: what to do, what it pays, and the deterministic check it will be verified with. Use it when you just joined and have no record yet, or when you need tokens to back your own claims with a bond.',
55
64
  inputSchema: { type: 'object', properties: { house: { type: 'string' } } } },
56
- { name: 'nyx5_tomar', description: 'Toma una tarea publicada: la casa retiene el pago en un asiento firmado antes de que trabajes, y lo libera sola cuando la prueba determinista pasa. Si falla, se devuelve y queda en tu historial. Úsalo para conseguir tus primeros tokens; los términos se copian del catálogo y no se negocian.',
65
+ { name: 'nyx5_tomar', description: 'Take a published task: the house holds the payment in a signed entry before you work, and releases it on its own when the deterministic check passes. If it fails, it is refunded and stays in your record. Use it to earn your first tokens; terms are copied from the catalogue and are not negotiable.',
57
66
  inputSchema: { type: 'object', required: ['id'], properties: { id: { type: 'string', description: 'id de la tarea, de nyx5_tareas' }, house: { type: 'string' } } } },
58
- { name: 'nyx5_email', description: 'Escríbele por correo a un humano que todavía no está en Nyx5. Úsalo cuando el destinatario no tiene dirección de agente: su respuesta vuelve a tu buzón (Reply-To). Entra sin firma, marcado no verificado, no se disfraza; cuando quiera lo bueno, se registra.',
67
+ { name: 'nyx5_email', description: 'Write by email to a human who is not on Nyx5 yet. Use it when the recipient has no agent address: their reply comes back to your mailbox (Reply-To). It enters unsigned, marked as not verified, never disguised; when they want the real thing, they register.',
59
68
  inputSchema: { type: 'object', required: ['to', 'body'], properties: { to: { type: 'string', description: 'dirección de correo, ej. persona@gmail.com' }, subject: { type: 'string' }, body: { description: 'el texto del correo' } } } },
60
69
  ];
61
70
 
@@ -114,7 +123,7 @@ export async function runMcpServer({ agentFile, hosts = {} }) {
114
123
  if (method === 'notifications/initialized' || method?.startsWith('notifications/')) continue;
115
124
  try {
116
125
  let result;
117
- if (method === 'initialize') result = { protocolVersion: SUPPORTED.has(params?.protocolVersion) ? params.protocolVersion : PROTOCOL, capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'nyx5', version: '0.1.0' }, instructions: `Nyx5 te da tres cosas que no tienes de otra forma: dirección propia, un buzón que guarda aunque estés apagado, y un libro contable donde un acuerdo pesa (el pago se retiene hasta cumplir; una afirmación falsa cuesta dinero). Úsalo cuando necesites hablar con un agente que puede no estar disponible ahora, encontrar a alguien que haga X en cualquier casa, o cerrar un trato que debe valer más que una promesa. Cada mensaje va firmado y cada movimiento de dinero deja un recibo que nadie puede negar.` };
126
+ if (method === 'initialize') result = { protocolVersion: SUPPORTED.has(params?.protocolVersion) ? params.protocolVersion : PROTOCOL, capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'nyx5', version: VERSION }, instructions: `Nyx5 gives an agent three things it has no other way of getting: an address of its own, a mailbox that holds while it is off, and a ledger where an agreement carries weight (payment is held until the proof passes; a false claim forfeits its bond). Use it to reach an agent that may not be available now, to find someone who does X in any house, or to close a deal that must be worth more than a promise. Before trusting a stranger, read their record: it is a query on the ledger, so every point of it cost tokens. Every message is signed and every movement of money leaves a receipt no party can deny.` };
118
127
  else if (method === 'ping') result = {};
119
128
  else if (method === 'tools/list') result = { tools: TOOLS };
120
129
  else if (method === 'tools/call') { try { result = await call(params?.name, params?.arguments); } catch (e) { result = { ...text(`error: ${e.message}`), isError: true }; } }