@jossuealcala/madre 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.en.md +106 -1
  2. package/CHANGELOG.md +106 -1
  3. package/NOTICE +30 -0
  4. package/README.en.md +59 -156
  5. package/README.md +60 -161
  6. package/TRADEMARKS.md +18 -0
  7. package/bin/madre.mjs +2 -2
  8. package/docs/REFERENCE.md +1 -1
  9. package/docs/SDK.md +25 -4
  10. package/docs/en/REFERENCE.md +1 -1
  11. package/docs/en/SDK.md +22 -2
  12. package/docs/madre-banner.png +0 -0
  13. package/package.json +1 -1
  14. package/public/app.js +1078 -239
  15. package/public/assets/manual/madre-manual-en.pdf +0 -0
  16. package/public/assets/manual/madre-manual-es.pdf +0 -0
  17. package/public/assets/manual/shots/en-agents.webp +0 -0
  18. package/public/assets/manual/shots/en-code.webp +0 -0
  19. package/public/assets/manual/shots/en-composer.webp +0 -0
  20. package/public/assets/manual/shots/en-connectors.webp +0 -0
  21. package/public/assets/manual/shots/en-continuity.webp +0 -0
  22. package/public/assets/manual/shots/en-coordinator.webp +0 -0
  23. package/public/assets/manual/shots/en-copilot.webp +0 -0
  24. package/public/assets/manual/shots/en-diagnostics.webp +0 -0
  25. package/public/assets/manual/shots/en-home.webp +0 -0
  26. package/public/assets/manual/shots/en-local.webp +0 -0
  27. package/public/assets/manual/shots/en-memory.webp +0 -0
  28. package/public/assets/manual/shots/en-modes.webp +0 -0
  29. package/public/assets/manual/shots/en-modules.webp +0 -0
  30. package/public/assets/manual/shots/en-notes.webp +0 -0
  31. package/public/assets/manual/shots/en-settings.webp +0 -0
  32. package/public/assets/manual/shots/en-windows.webp +0 -0
  33. package/public/assets/manual/shots/es-agents.webp +0 -0
  34. package/public/assets/manual/shots/es-code.webp +0 -0
  35. package/public/assets/manual/shots/es-composer.webp +0 -0
  36. package/public/assets/manual/shots/es-connectors.webp +0 -0
  37. package/public/assets/manual/shots/es-continuity.webp +0 -0
  38. package/public/assets/manual/shots/es-coordinator.webp +0 -0
  39. package/public/assets/manual/shots/es-copilot.webp +0 -0
  40. package/public/assets/manual/shots/es-diagnostics.webp +0 -0
  41. package/public/assets/manual/shots/es-home.webp +0 -0
  42. package/public/assets/manual/shots/es-local.webp +0 -0
  43. package/public/assets/manual/shots/es-memory.webp +0 -0
  44. package/public/assets/manual/shots/es-modes.webp +0 -0
  45. package/public/assets/manual/shots/es-modules.webp +0 -0
  46. package/public/assets/manual/shots/es-notes.webp +0 -0
  47. package/public/assets/manual/shots/es-settings.webp +0 -0
  48. package/public/assets/manual/shots/es-windows.webp +0 -0
  49. package/public/en.js +74 -0
  50. package/public/es.js +493 -136
  51. package/public/i18n.js +45 -7
  52. package/public/index.html +2 -3
  53. package/public/manual-content.js +657 -0
  54. package/public/manual-shots.js +43 -0
  55. package/public/manual.css +228 -0
  56. package/public/manual.html +15 -0
  57. package/public/manual.js +398 -0
  58. package/public/market-art.js +56 -0
  59. package/public/market-view.js +140 -22
  60. package/public/market.js +25 -14
  61. package/public/mcp-catalog.js +62 -0
  62. package/public/resay.js +1 -0
  63. package/public/salas-mac.css +178 -30
  64. package/public/salas-mac.html +5 -5
  65. package/public/salas-mac.js +432 -67
  66. package/public/styles.css +300 -42
  67. package/public/tour-chapters.js +98 -90
  68. package/public/tour.js +63 -21
  69. package/public/troubleshooting.js +145 -10
  70. package/src/adapters/cursor.mjs +56 -7
  71. package/src/adapters/gemini.mjs +12 -1
  72. package/src/adapters/madre.mjs +27 -6
  73. package/src/adapters/process.mjs +5 -2
  74. package/src/auth-probe.mjs +22 -3
  75. package/src/bridge/policy.mjs +1 -1
  76. package/src/bridge/server.mjs +1 -1
  77. package/src/capabilities.mjs +3 -3
  78. package/src/credentials.mjs +24 -2
  79. package/src/history.mjs +76 -0
  80. package/src/i18n.mjs +23 -1
  81. package/src/local-ai.mjs +10 -2
  82. package/src/looks.mjs +17 -5
  83. package/src/market-license.mjs +104 -0
  84. package/src/market-remote.mjs +17 -1
  85. package/src/mcp/notes-server.mjs +120 -0
  86. package/src/mcp/proxy.mjs +14 -3
  87. package/src/models.mjs +82 -9
  88. package/src/modules/index.mjs +3 -1
  89. package/src/modules/local-models.mjs +28 -0
  90. package/src/modules/notes.mjs +142 -0
  91. package/src/modules/ollama.mjs +39 -10
  92. package/src/modules/playwright.mjs +14 -3
  93. package/src/modules/reminders.mjs +345 -0
  94. package/src/modules/sdk.mjs +21 -5
  95. package/src/mother.mjs +11 -1
  96. package/src/ollama.mjs +2 -2
  97. package/src/opencode-health.mjs +63 -0
  98. package/src/outbound.mjs +25 -1
  99. package/src/reminder-time.mjs +127 -0
  100. package/src/room.mjs +19 -7
  101. package/src/runtime-detection.mjs +6 -2
  102. package/src/sentinel-errors.mjs +4 -3
  103. package/src/server.mjs +302 -70
  104. package/src/tour.mjs +24 -5
@@ -0,0 +1,76 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
3
+ // A project's history over a period, for modules (docs/SDK.md, `ctx.services.history`): what the
4
+ // human asked and to whom, how each agent answered, what it cost, which files a turn changed and
5
+ // whether that was undone, and the decisions the memory kept. Read from the ledgers as they are
6
+ // on disk, never written. GHOST turns are not here: what was said off the record stays off it.
7
+ // Built for the Market's first paid module (Informe de trabajo, 2026-10-19), and for any module
8
+ // that reports on the work: one documented shape instead of each one parsing the ledgers.
9
+
10
+ const TEXT_MAX = 600;
11
+ const at = (event) => String(event?.timestamp ?? '');
12
+ const inside = (when, since, until) => (!since || when >= since) && (!until || when < until);
13
+ const money = (value) => (Number.isFinite(value) && value > 0 ? value : 0);
14
+
15
+ // `chats`: [{ id, title, events }], each conversation's ledger already parsed, oldest first.
16
+ // `memories`: the archive's notes ({ created, kind, text, agent }). `since`/`until`: ISO strings.
17
+ export function summarizeHistory({ chats = [], memories = [], since = null, until = null } = {}) {
18
+ const requests = [];
19
+ const answers = [];
20
+ const changes = [];
21
+ const agents = {};
22
+ const conversations = [];
23
+ const agent = (id) => (agents[id] ??= { turns: 0, failed: 0, tokens: 0, costUsd: 0, local: false });
24
+ for (const chat of chats) {
25
+ let asked = 0;
26
+ const reverted = new Set();
27
+ for (const event of chat.events ?? []) if (event?.type === 'control.reverted' && event.payload?.checkpointId) reverted.add(event.payload.checkpointId);
28
+ for (const event of chat.events ?? []) {
29
+ if (!event || event.ghost || !inside(at(event), since, until)) continue;
30
+ const p = event.payload ?? {};
31
+ if (event.type === 'message.created' && p.role === 'user' && p.sender === 'you') {
32
+ asked += 1;
33
+ requests.push({ at: at(event), chat: chat.id, to: p.target ?? null, mode: Number.isFinite(p.mode) ? p.mode : null, text: String(p.text ?? '').slice(0, TEXT_MAX) });
34
+ } else if (event.type === 'message.created' && p.role === 'assistant' && p.sender && p.sender !== 'you') {
35
+ agent(p.sender).turns += 1;
36
+ answers.push({ at: at(event), chat: chat.id, agent: p.sender, text: String(p.text ?? '').slice(0, TEXT_MAX) });
37
+ } else if (event.type === 'message.failed') {
38
+ if (p.target) agent(p.target).failed += 1;
39
+ } else if (event.type === 'usage.recorded' && p.agent) {
40
+ const one = agent(p.agent);
41
+ one.tokens += Number.isFinite(p.usage?.totalTokens) ? p.usage.totalTokens : 0;
42
+ one.costUsd += money(p.usage?.costUsd);
43
+ if (p.usage?.local) one.local = true;
44
+ } else if (event.type === 'control.changed') {
45
+ changes.push({
46
+ at: at(event), chat: chat.id, agent: p.agent ?? null, mode: p.mode ?? null,
47
+ files: (p.files ?? []).filter((file) => file?.path).map((file) => ({ status: String(file.status ?? 'M'), path: String(file.path) })),
48
+ undone: reverted.has(p.checkpointId),
49
+ });
50
+ }
51
+ }
52
+ if (asked) conversations.push({ id: chat.id, title: chat.title ?? null, requests: asked });
53
+ }
54
+ const decisions = memories
55
+ .filter((note) => note?.kind === 'decision' && inside(String(note.created ?? ''), since, until))
56
+ .map((note) => ({ at: String(note.created), text: String(note.text ?? '').slice(0, TEXT_MAX), agent: note.agent ?? null }));
57
+ const byTime = (a, b) => a.at.localeCompare(b.at);
58
+ const files = new Map();
59
+ for (const change of changes) if (!change.undone) for (const file of change.files) files.set(file.path, file.status);
60
+ return {
61
+ since, until,
62
+ requests: requests.sort(byTime),
63
+ answers: answers.sort(byTime),
64
+ changes: changes.sort(byTime),
65
+ files: [...files].map(([path, status]) => ({ path, status })).sort((a, b) => a.path.localeCompare(b.path)),
66
+ decisions: decisions.sort(byTime),
67
+ agents,
68
+ conversations,
69
+ totals: {
70
+ requests: requests.length,
71
+ answers: answers.length,
72
+ tokens: Object.values(agents).reduce((sum, one) => sum + one.tokens, 0),
73
+ costUsd: Math.round(Object.values(agents).reduce((sum, one) => sum + one.costUsd, 0) * 10000) / 10000,
74
+ },
75
+ };
76
+ }
package/src/i18n.mjs CHANGED
@@ -15,9 +15,11 @@
15
15
  // what a reading means. Same rule as the page: the key is the English sentence, and a sentence
16
16
  // nobody has translated comes back in English, whole.
17
17
 
18
+ import { hostname } from 'node:os';
18
19
  import { ES } from '../public/es.js';
20
+ import { EN } from '../public/en.js';
19
21
 
20
- const CATALOGUES = { es: ES, en: {} };
22
+ const CATALOGUES = { es: ES, en: EN };
21
23
  let current = 'es';
22
24
 
23
25
  export const language = () => current;
@@ -30,9 +32,23 @@ export function setLanguage(id) {
30
32
  // it runs on says «computer» there. Same rule as public/i18n.js (hostWords); hardware named on
31
33
  // purpose («a Mac with an M chip») has no article in front and is left alone.
32
34
  let hostIsMac = process.platform === 'darwin';
35
+ // The machine's own name, said instead of «this computer» where it is not a Mac (2026-10-20).
36
+ const ownName = () => { try { return hostname().replace(/\.local$/i, '').trim().slice(0, 64) || null; } catch { return null; } };
37
+ let hostName = ownName();
33
38
  export const setHostIsMac = (value) => { hostIsMac = Boolean(value); return hostIsMac; };
39
+ export const setHostName = (value) => { hostName = typeof value === 'string' && value.trim() ? value.trim().slice(0, 64) : null; return hostName; };
40
+ // What the page is told about the machine it is served by (src/server.mjs puts it in a <meta>).
41
+ export const hostFacts = () => ({ os: process.platform, name: hostName });
34
42
  export function hostWords(text) {
35
43
  if (hostIsMac || typeof text !== 'string' || !text.includes('Mac')) return text;
44
+ // With the machine's own name (2026-10-20) a sentence about it names it: «Found on cotizapp2».
45
+ if (hostName) {
46
+ return text
47
+ .replace(/\b(on|in|from|to) (this|your|the) Mac\b/g, `$1 ${hostName}`)
48
+ .replace(/\b(this|your|the|This|Your|The) Mac\b/g, hostName)
49
+ .replace(/(^|[^\p{L}])(en|de|a|desde) (esta|tu|la) Mac\b/gu, `$1$2 ${hostName}`)
50
+ .replace(/(^|[^\p{L}])(esta|tu|la|Esta|Tu|La) Mac\b/gu, `$1${hostName}`);
51
+ }
36
52
  return text
37
53
  .replace(/\b(this|your|the|This|Your|The) Mac\b/g, '$1 computer')
38
54
  .replace(/(^|[^\p{L}])(esta|tu|la|Esta|Tu|La) Mac\b/gu, '$1$2 computadora');
@@ -66,7 +82,13 @@ export function t(text, vars = null) {
66
82
  // because those are not sentences and a translated id is a bug.
67
83
  const PROSE = new Set(['summary', 'detail', 'note', 'says', 'brief', 'what', 'when', 'where', 'why', 'hint', 'title', 'label', 'remedy', 'diagnosis', 'creates', 'requires']);
68
84
 
85
+ // A module's words in both languages, { es, en } (SDK, 2026-10-20): the one the room speaks, or the
86
+ // other when it only wrote one. Anything else comes back as it was.
87
+ export const isBilingual = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => key === 'es' || key === 'en') && Object.values(value).every((one) => typeof one === 'string');
88
+ export const inRoomLanguage = (value) => (isBilingual(value) ? value[current] ?? value.es ?? value.en : value);
89
+
69
90
  export function translate(value, key = null) {
91
+ if (isBilingual(value)) return value[current] ?? value.es ?? value.en;
70
92
  if (Array.isArray(value)) return value.map((one) => translate(one, key));
71
93
  if (value && typeof value === 'object') {
72
94
  const out = {};
package/src/local-ai.mjs CHANGED
@@ -11,6 +11,8 @@
11
11
  // 'pick' only the projects switched on. New ones start without it.
12
12
  // 'manual' each project decides in its own Settings. New ones start with it.
13
13
  // localAi.rooms { <room id>: true | false } what was switched, from Home or from the project.
14
+ // localAi.model the chat model the person chose (2026-10-20), one for the whole computer as
15
+ // Ollama is. Nothing written: MADRE picks the best one installed (src/ollama.mjs).
14
16
  //
15
17
  // With nothing written the mode is 'auto', which is what MADRE did before this existed. The
16
18
  // master switch (`modules.ollama.enabled`) still wins: off there is off everywhere. Home's own
@@ -23,9 +25,12 @@ export function localAiConfig(config = {}) {
23
25
  const mode = LOCAL_MODES.includes(raw.mode) ? raw.mode : 'auto';
24
26
  const rooms = {};
25
27
  for (const [id, on] of Object.entries(raw.rooms ?? {})) if (typeof on === 'boolean') rooms[id] = on;
26
- return { mode, rooms };
28
+ return { mode, rooms, model: MODEL_NAME.test(raw.model ?? '') ? raw.model : null };
27
29
  }
28
30
 
31
+ // A name as Ollama writes it: qwen2.5:7b, llama3.1:8b, someone/model:tag.
32
+ export const MODEL_NAME = /^[a-z0-9][a-z0-9._:/-]{1,80}$/i;
33
+
29
34
  // What one project gets. `on`: whether it uses the local AI now; `chosen`: what this project's
30
35
  // switch says, before the master switch; `editable`: whether its switch can be moved (not in auto).
31
36
  export function localAiFor(config = {}, roomId = null, { home = false } = {}) {
@@ -38,9 +43,12 @@ export function localAiFor(config = {}, roomId = null, { home = false } = {}) {
38
43
 
39
44
  // The patch for config.json: the whole `localAi` block, because updateConfig merges one level
40
45
  // down and a partial `rooms` would drop the projects it does not name.
41
- export function localAiPatch(config = {}, { mode, rooms } = {}) {
46
+ export function localAiPatch(config = {}, { mode, rooms, model } = {}) {
42
47
  const now = localAiConfig(config);
43
48
  const next = { mode: LOCAL_MODES.includes(mode) ? mode : now.mode, rooms: { ...now.rooms } };
49
+ // null goes back to MADRE's own pick; anything else that is not a model name changes nothing.
50
+ // Written as null, not left out: updateConfig merges one level down and would keep the old one.
51
+ next.model = model === null ? null : MODEL_NAME.test(model ?? '') ? model : now.model;
44
52
  for (const [id, on] of Object.entries(rooms ?? {})) {
45
53
  if (typeof id !== 'string' || !id || id.length > 200) continue;
46
54
  if (typeof on === 'boolean') next.rooms[id] = on;
package/src/looks.mjs CHANGED
@@ -35,10 +35,16 @@ const looksFile = (stateRoot) => join(stateRoot, 'looks.json');
35
35
  // It lives beside the shared looks, under `rooms`, by the room's id; every other look stays shared.
36
36
  const ROOM_ID = /^[\w .-]{1,120}$/;
37
37
  const readFileLooks = (stateRoot) => readFile(looksFile(stateRoot), 'utf8').then((text) => JSON.parse(text)).catch(() => null);
38
+ // And its own accent (1.0.5): chosen in a project, it is that project's; Home keeps the shared one,
39
+ // and a project that has none of its own wears Home's.
38
40
  function roomsOf(raw) {
39
41
  const rooms = {};
40
42
  for (const [id, own] of Object.entries(raw?.rooms ?? {})) {
41
- if (ROOM_ID.test(id) && typeof own?.wallpaper === 'string' && CHOICE.test(own.wallpaper)) rooms[id] = { wallpaper: own.wallpaper };
43
+ if (!ROOM_ID.test(id)) continue;
44
+ const kept = {};
45
+ if (typeof own?.wallpaper === 'string' && CHOICE.test(own.wallpaper)) kept.wallpaper = own.wallpaper;
46
+ if (typeof own?.accent === 'string' && CHOICE.test(own.accent)) kept.accent = own.accent;
47
+ if (Object.keys(kept).length) rooms[id] = kept;
42
48
  }
43
49
  return rooms;
44
50
  }
@@ -61,15 +67,21 @@ export async function readLooks(stateRoot, { room = null } = {}) {
61
67
  export async function roomLooks(stateRoot) {
62
68
  return roomsOf(await readFileLooks(stateRoot));
63
69
  }
64
- // A project's own wallpaper set, or taken away (`null`): it follows the shared one again.
65
- export function changeRoomLook(stateRoot, room, wallpaper) {
70
+ // A project's own wallpaper or accent set, or taken away (`null`): it follows the shared one again.
71
+ // `change` names what it changes ({ wallpaper }, { accent }); a bare value is the wallpaper, as before.
72
+ export function changeRoomLook(stateRoot, room, change) {
66
73
  return oneAtATime(looksFile(stateRoot), async () => {
67
74
  if (typeof room !== 'string' || !ROOM_ID.test(room)) return { error: 'room' };
68
- if (wallpaper !== null && (typeof wallpaper !== 'string' || !CHOICE.test(wallpaper))) return { error: 'value' };
75
+ const patch = change !== null && typeof change === 'object' ? change : { wallpaper: change };
76
+ const keys = Object.keys(patch).filter((key) => key === 'wallpaper' || key === 'accent');
77
+ if (!keys.length) return { error: 'value' };
78
+ for (const key of keys) if (patch[key] !== null && (typeof patch[key] !== 'string' || !CHOICE.test(patch[key]))) return { error: 'value' };
69
79
  const raw = await readFileLooks(stateRoot);
70
80
  const { looks } = await readLooks(stateRoot);
71
81
  const rooms = roomsOf(raw);
72
- if (wallpaper === null) delete rooms[room]; else rooms[room] = { wallpaper };
82
+ const own = { ...(rooms[room] ?? {}) };
83
+ for (const key of keys) { if (patch[key] === null) delete own[key]; else own[key] = patch[key]; }
84
+ if (Object.keys(own).length) rooms[room] = own; else delete rooms[room];
73
85
  await writeWhole(looksFile(stateRoot), `${JSON.stringify({ looks, ...(Object.keys(rooms).length ? { rooms } : {}), at: new Date().toISOString() }, null, 2)}\n`);
74
86
  return { own: rooms[room] ?? null };
75
87
  });
@@ -0,0 +1,104 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
3
+ // THE MARKET'S PAID MODULES (2026-10-19). A paid module is bought at its checkout (Lemon Squeezy,
4
+ // the seller of record, which charges and handles each country's taxes), and the key the buyer
5
+ // gets by email is pasted in MADRE once. MADRE asks Lemon Squeezy, that one time and because the
6
+ // person pressed «Activate», whether the key is good and is for this module: the answer must name
7
+ // the store and the product the signed catalog names, or the key is refused. Kept in
8
+ // ~/.pulse/market/licenses.json, readable only by this person, and never asked again: the module
9
+ // works offline from then on. «Release» gives the activation back, to use the key elsewhere.
10
+ //
11
+ // What travels: the key and a name for this computer made from MADRE's random install id
12
+ // («MADRE 1a2b3c4d»), never the computer's own name. The module's code is AGPL like MADRE: what is
13
+ // paid for is installing it from the Market, its updates and its support, not a lock on the code.
14
+
15
+ import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
16
+ import { join } from 'node:path';
17
+ import { t } from './i18n.mjs';
18
+
19
+ export const LICENSE_API = 'https://api.lemonsqueezy.com/v1/licenses';
20
+ const TIMEOUT_MS = 10000;
21
+ const KEY = /^[A-Za-z0-9-]{8,80}$/;
22
+
23
+ const file = (stateRoot) => join(stateRoot, 'market', 'licenses.json');
24
+ const readJson = (path) => readFile(path, 'utf8').then((raw) => JSON.parse(raw)).catch(() => null);
25
+ async function keep(stateRoot, licenses) {
26
+ await mkdir(join(stateRoot, 'market'), { recursive: true });
27
+ const temp = `${file(stateRoot)}.${process.pid}.${Date.now()}.tmp`;
28
+ await writeFile(temp, JSON.stringify(licenses, null, 2), { mode: 0o600 });
29
+ await rename(temp, file(stateRoot));
30
+ await chmod(file(stateRoot), 0o600).catch(() => {});
31
+ }
32
+
33
+ export const licensesFrom = async (stateRoot) => (await readJson(file(stateRoot))) ?? {};
34
+ // What the page may know: which modules are bought, never the keys.
35
+ export async function licensedIds(stateRoot) {
36
+ const licenses = await licensesFrom(stateRoot);
37
+ return Object.fromEntries(Object.entries(licenses).map(([id, one]) => [id, { at: one.at ?? null }]));
38
+ }
39
+ export const isLicensed = async (stateRoot, id) => Boolean((await licensesFrom(stateRoot))[id]?.key);
40
+ // A module that costs nothing needs no license; one with a price needs one kept here.
41
+ export const mayInstall = async (stateRoot, entry) => !(entry?.price > 0) || isLicensed(stateRoot, entry.id);
42
+
43
+ async function ask(fetchImpl, path, fields, api) {
44
+ const controller = new AbortController();
45
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
46
+ try {
47
+ const response = await fetchImpl(`${api}/${path}`, {
48
+ method: 'POST',
49
+ signal: controller.signal,
50
+ headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },
51
+ body: new URLSearchParams(fields).toString(),
52
+ });
53
+ const answer = await response.json().catch(() => null);
54
+ return { status: response.status, answer };
55
+ } catch {
56
+ throw new Error(t('MADRE could not reach Lemon Squeezy to check the license. Check your internet connection and try again.'));
57
+ } finally { clearTimeout(timer); }
58
+ }
59
+
60
+ // The catalog's own word on where a module is sold: Lemon Squeezy, and which store and product.
61
+ export function saleOf(entry) {
62
+ const license = entry?.license;
63
+ if (!(entry?.price > 0) || license?.provider !== 'lemonsqueezy') return null;
64
+ if (!Number.isInteger(license.store) || !Number.isInteger(license.product)) return null;
65
+ return { store: license.store, product: license.product };
66
+ }
67
+
68
+ export async function activateLicense({ stateRoot, entry, key, installId, fetchImpl = globalThis.fetch, api = LICENSE_API }) {
69
+ const sale = saleOf(entry);
70
+ if (!sale) throw new Error(t('This module is not sold through the Market.'));
71
+ const typed = String(key ?? '').trim();
72
+ if (!KEY.test(typed)) throw new Error(t('That does not look like a license key. Copy it whole from the purchase email.'));
73
+ const { answer } = await ask(fetchImpl, 'activate', { license_key: typed, instance_name: `MADRE ${String(installId ?? '').replace(/-/g, '').slice(0, 8) || 'sin-id'}` }, api);
74
+ if (!answer?.activated) {
75
+ const said = String(answer?.error ?? '');
76
+ if (/limit/i.test(said)) throw new Error(t('This license is already active on as many computers as it allows. Release it on another computer, or buy another one.'));
77
+ throw new Error(t('Lemon Squeezy did not accept that key: {error}', { error: said.slice(0, 200) || t('no reason given') }));
78
+ }
79
+ // A good key for something else is not a key for this module: given back at once.
80
+ const meta = answer.meta ?? {};
81
+ if (meta.store_id !== sale.store || meta.product_id !== sale.product) {
82
+ if (answer.instance?.id) await ask(fetchImpl, 'deactivate', { license_key: typed, instance_id: answer.instance.id }, api).catch(() => null);
83
+ throw new Error(t('That license is for another product, not for «{name}».', { name: entry.id }));
84
+ }
85
+ const licenses = await licensesFrom(stateRoot);
86
+ licenses[entry.id] = { provider: 'lemonsqueezy', key: typed, instance: answer.instance?.id ?? null, at: new Date().toISOString() };
87
+ await keep(stateRoot, licenses);
88
+ return { id: entry.id, at: licenses[entry.id].at };
89
+ }
90
+
91
+ // The activation given back to Lemon Squeezy, so the key can be used on another computer. The
92
+ // module stays installed; it is the Market's updates that stop until a key is active again.
93
+ export async function releaseLicense({ stateRoot, id, fetchImpl = globalThis.fetch, api = LICENSE_API }) {
94
+ const licenses = await licensesFrom(stateRoot);
95
+ const held = licenses[id];
96
+ if (!held?.key) throw new Error(t('There is no license for «{id}» on this computer.', { id }));
97
+ if (held.instance) {
98
+ const { answer } = await ask(fetchImpl, 'deactivate', { license_key: held.key, instance_id: held.instance }, api);
99
+ if (!answer?.deactivated && !/not found|invalid/i.test(String(answer?.error ?? ''))) throw new Error(t('Lemon Squeezy did not release the license: {error}', { error: String(answer?.error ?? '').slice(0, 200) || t('no reason given') }));
100
+ }
101
+ delete licenses[id];
102
+ await keep(stateRoot, licenses);
103
+ return { id };
104
+ }
@@ -25,6 +25,7 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
25
25
  import { join } from 'node:path';
26
26
  import { t } from './i18n.mjs';
27
27
  import { MARKET_PUBLIC_KEY } from './market-key.mjs';
28
+ import { mayInstall } from './market-license.mjs';
28
29
 
29
30
  export const MARKET_URL = 'https://madre.run/mercado/catalogo.json';
30
31
  const MAX_CATALOG = 1024 * 1024;
@@ -102,11 +103,20 @@ export function readCatalog(text, { url = MARKET_URL } = {}) {
102
103
  // Drawings are markup: they travel signed, and the page keeps only the shapes it knows (market.js).
103
104
  icon: typeof raw.icon === 'string' && raw.icon.length <= 8000 ? raw.icon : null,
104
105
  art: typeof raw.art === 'string' && raw.art.length <= 60000 ? raw.art : null,
106
+ // Two more pictures for its page (1.0.5), drawings like `art`.
107
+ shots: Array.isArray(raw.shots) ? raw.shots.filter((one) => typeof one === 'string' && one.length <= 60000).slice(0, 2) : [],
105
108
  version: typeof raw.version === 'string' && /^\d+\.\d+\.\d+$/.test(raw.version) ? raw.version : null,
106
109
  minMadre: typeof raw.minMadre === 'string' && /^\d+\.\d+\.\d+$/.test(raw.minMadre) ? raw.minMadre : null,
107
110
  changes: words(raw.changes, 400),
108
111
  file: null,
112
+ // Where a paid module is bought (an https page) and whose license opens it (market-license.mjs).
113
+ checkout: null,
114
+ license: null,
109
115
  };
116
+ if (entry.price > 0) {
117
+ try { const page = new URL(raw.checkout); if (page.protocol === 'https:') entry.checkout = page.href; } catch { /* no page to buy it */ }
118
+ if (raw.license?.provider === 'lemonsqueezy' && Number.isInteger(raw.license.store) && Number.isInteger(raw.license.product)) entry.license = { provider: 'lemonsqueezy', store: raw.license.store, product: raw.license.product };
119
+ }
110
120
  if (raw.file) {
111
121
  const href = fileUrl(raw.file.url, url);
112
122
  if (!href || !SHA.test(raw.file.sha256 ?? '') || !entry.version) continue;
@@ -149,7 +159,12 @@ export async function refreshCatalog({ stateRoot, env = process.env, fetchImpl =
149
159
  if (!force && kept && state.checkedAt && now() - Date.parse(state.checkedAt) < FRESH_MS) return { catalog: kept, fresh: false };
150
160
  const url = marketUrl(env);
151
161
  try {
152
- const [bytes, signature] = await Promise.all([bytesFrom(url, { fetchImpl, max: MAX_CATALOG }), bytesFrom(`${url}.sig`, { fetchImpl, max: MAX_SIGNATURE })]);
162
+ // Both answers are waited for, also when one fails: the other one used to be still out when
163
+ // the ask was over, and was written in the outbound log of a room already closed (2026-10-21).
164
+ const asked = await Promise.allSettled([bytesFrom(url, { fetchImpl, max: MAX_CATALOG }), bytesFrom(`${url}.sig`, { fetchImpl, max: MAX_SIGNATURE })]);
165
+ const refused = asked.find((one) => one.status === 'rejected');
166
+ if (refused) throw refused.reason;
167
+ const [bytes, signature] = asked.map((one) => one.value);
153
168
  if (!verifySigned(bytes, signature.toString('utf8'), publicKey)) throw new Error(t('The Market catalog is not signed with MADRE\'s key, so MADRE did not read it.'));
154
169
  const catalog = readCatalog(bytes.toString('utf8'), { url });
155
170
  if (kept && Date.parse(catalog.issued) < Date.parse(kept.issued)) throw new Error(t('The Market served a catalog older than the one this computer has, so MADRE kept its own.'));
@@ -173,6 +188,7 @@ export async function installFromMarket({ stateRoot, projectRoot, id, catalog, m
173
188
  const entry = catalog?.modules.find((one) => one.id === id && one.file);
174
189
  if (!entry) throw new Error(t('The Market has no module «{id}» to install.', { id }));
175
190
  if (!fitsVersion(madre, entry.minMadre)) throw new Error(t('This module needs MADRE {version} or newer.', { version: entry.minMadre }));
191
+ if (!(await mayInstall(stateRoot, entry))) throw new Error(t('«{name}» is a paid module: buy it, or activate the license you already have.', { name: entry.id }));
176
192
  const bytes = await bytesFrom(entry.file.url, { fetchImpl, max: MAX_MODULE });
177
193
  if (sha256(bytes) !== entry.file.sha256) throw new Error(t('The module file is not the one the Market signed, so MADRE did not install it.'));
178
194
  const text = bytes.toString('utf8');
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: AGPL-3.0-only
3
+ // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
4
+ // MADRE NOTES AND REMINDERS for an agent (2026-10-20): a small MCP server (stdio, JSON-RPC 2.0) that
5
+ // lets an agent make a note or set a reminder for the person when they ask for one — «/notas …»,
6
+ // «/recordatorios …», «hazme una nota con…», «recuérdame…». It only adds: it cannot read, change or
7
+ // delete the person's notes or reminders, which stay theirs (src/modules/notes.mjs, reminders.mjs).
8
+ // It writes the same files the page reads, beside the project's conversations, and nothing leaves
9
+ // this computer.
10
+ //
11
+ // Environment:
12
+ // PULSE_NOTES_DIR the project's room folder (~/.pulse/rooms/<id>): with it, create_note
13
+ // PULSE_REMINDERS_STATE ~/.pulse: with it, create_reminder
14
+ // PULSE_ROOM_ID the project's room id, kept on each reminder
15
+ // PULSE_PROJECT the project's name, for Home
16
+ // PULSE_REMINDER_HOUR the hour a day starts at for a reminder with no hour (Reminders' setting)
17
+
18
+ import { realpath } from 'node:fs/promises';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { NOTE_COLORS, saveNote } from '../modules/notes.mjs';
21
+ import { addReminder, taskFromWords } from '../modules/reminders.mjs';
22
+ import { parseWhen, tomorrowMorning } from '../reminder-time.mjs';
23
+
24
+ const SERVER_NAME = 'madre-notes';
25
+ const SERVER_VERSION = '1.0.0';
26
+ const SELF = fileURLToPath(import.meta.url);
27
+
28
+ const NOTE_TOOL = {
29
+ name: 'create_note',
30
+ description: 'Make a note for the person: a colored note that opens as a window in their project. Use it when they ask for a note (they may write /notas or /notes). Write it for them, short and clear, in their language. You cannot read their other notes.',
31
+ inputSchema: { type: 'object', properties: { text: { type: 'string', description: 'The note, as the person will read it.' }, color: { type: 'string', enum: NOTE_COLORS, description: 'Optional color.' } }, required: ['text'] },
32
+ };
33
+ const REMINDER_TOOL = {
34
+ name: 'create_reminder',
35
+ description: 'Set a reminder for the person. Use it when they ask to be reminded of something (they may write /recordatorios or /reminders). MADRE tells them when it is due, in Home and in this project.',
36
+ inputSchema: { type: 'object', properties: { what: { type: 'string', description: 'What to remember, short, in the person\'s language.' }, when: { type: 'string', description: 'When, in the person\'s own words: «mañana a las 5», «el lunes», «every day at 9», «in 2 hours». Empty for tomorrow morning.' } }, required: ['what'] },
37
+ };
38
+
39
+ export const toolsFor = (env = process.env) => [...(env.PULSE_NOTES_DIR ? [NOTE_TOOL] : []), ...(env.PULSE_REMINDERS_STATE ? [REMINDER_TOOL] : [])];
40
+
41
+ async function callTool(name, args, env) {
42
+ if (name === 'create_note') {
43
+ const text = String(args.text ?? '').trim();
44
+ if (!text) throw new Error('The note needs its text.');
45
+ const saved = await saveNote(env.PULSE_NOTES_DIR, { text, color: NOTE_COLORS.includes(args.color) ? args.color : undefined });
46
+ if (saved.error === 'full') throw new Error('This project already has as many notes as it can keep. Ask the person to delete one.');
47
+ if (saved.error) throw new Error('The note was not saved.');
48
+ return `Note made (${saved.note.color}). It opens on the person's screen when your answer ends.`;
49
+ }
50
+ if (name === 'create_reminder') {
51
+ const what = taskFromWords(String(args.what ?? '').trim());
52
+ if (!what) throw new Error('The reminder needs what to remember.');
53
+ const hour = Number(env.PULSE_REMINDER_HOUR) || 9;
54
+ const when = parseWhen(String(args.when ?? ''), new Date(), { hour }) ?? { due: tomorrowMorning(new Date(), hour), repeat: null };
55
+ const made = await addReminder(env.PULSE_REMINDERS_STATE, { text: what, due: when.due.toISOString(), repeat: when.repeat, room: env.PULSE_ROOM_ID || null, project: env.PULSE_PROJECT || null, why: 'asked' });
56
+ if (made.error) throw new Error('The reminder was not set.');
57
+ return `Reminder set: «${made.reminder.text}», due ${made.reminder.due}${made.reminder.repeat ? `, repeating ${made.reminder.repeat}` : ''}. Tell the person when, in their words.`;
58
+ }
59
+ throw new Error(`Unknown tool: ${name}`);
60
+ }
61
+
62
+ export function handleRequest(message, { env = process.env } = {}) {
63
+ const reply = (result) => ({ jsonrpc: '2.0', id: message.id, result });
64
+ const fail = (code, text) => ({ jsonrpc: '2.0', id: message.id, error: { code, message: text } });
65
+ const tools = toolsFor(env);
66
+ switch (message.method) {
67
+ case 'initialize':
68
+ return Promise.resolve(reply({ protocolVersion: message.params?.protocolVersion ?? '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: SERVER_NAME, version: SERVER_VERSION } }));
69
+ case 'notifications/initialized':
70
+ case 'initialized':
71
+ return Promise.resolve(null);
72
+ case 'ping':
73
+ return Promise.resolve(reply({}));
74
+ case 'tools/list':
75
+ return Promise.resolve(reply({ tools }));
76
+ case 'tools/call': {
77
+ const { name, arguments: args = {} } = message.params ?? {};
78
+ if (!tools.some((tool) => tool.name === name)) return Promise.resolve(fail(-32602, `Unknown tool: ${name}`));
79
+ return callTool(name, args, env)
80
+ .then((text) => reply({ content: [{ type: 'text', text }], isError: false }))
81
+ .catch((error) => reply({ content: [{ type: 'text', text: `Nothing was saved: ${error.message}` }], isError: true }));
82
+ }
83
+ default:
84
+ return Promise.resolve(message.id === undefined ? null : fail(-32601, `Method not found: ${message.method}`));
85
+ }
86
+ }
87
+
88
+ export function serve({ input = process.stdin, output = process.stdout, env = process.env } = {}) {
89
+ let buffer = '';
90
+ let pending = 0;
91
+ let ended = false;
92
+ const finish = () => { if (ended && pending === 0) process.exit(0); };
93
+ input.setEncoding('utf8');
94
+ input.on('data', (chunk) => {
95
+ buffer += chunk;
96
+ let index;
97
+ while ((index = buffer.indexOf('\n')) >= 0) {
98
+ const line = buffer.slice(0, index).trim();
99
+ buffer = buffer.slice(index + 1);
100
+ if (!line) continue;
101
+ let message;
102
+ try { message = JSON.parse(line); } catch { output.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } })}\n`); continue; }
103
+ pending += 1;
104
+ void handleRequest(message, { env })
105
+ .then((response) => { if (response) output.write(`${JSON.stringify(response)}\n`); })
106
+ .finally(() => { pending -= 1; finish(); });
107
+ }
108
+ });
109
+ input.on('end', () => { ended = true; finish(); });
110
+ }
111
+
112
+ // Both paths resolved before they are compared (WIN-004), as the other servers do.
113
+ const real = async (path) => (path ? realpath(path).catch(() => path) : null);
114
+ if (process.argv[1] && (await real(process.argv[1])) === (await real(SELF))) {
115
+ if (!process.env.PULSE_NOTES_DIR && !process.env.PULSE_REMINDERS_STATE) {
116
+ process.stderr.write('PULSE_NOTES_DIR or PULSE_REMINDERS_STATE is required.\n');
117
+ process.exit(2);
118
+ }
119
+ serve();
120
+ }
package/src/mcp/proxy.mjs CHANGED
@@ -114,18 +114,29 @@ async function viaHttp(server) {
114
114
  const reader = response.body.getReader();
115
115
  const decoder = new TextDecoder();
116
116
  let buffer = '';
117
- for (;;) {
117
+ // A server may keep the stream open after it answered (DeepWiki does, 2026-10-20): read until
118
+ // the answer to this request arrives, then let the stream go, or every message after it waits.
119
+ const asked = message.id !== undefined && message.id !== null;
120
+ let answered = false;
121
+ while (!answered) {
118
122
  const { value, done } = await reader.read();
119
123
  if (done) break;
120
- buffer += decoder.decode(value, { stream: true });
124
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n');
121
125
  for (let end = buffer.indexOf('\n\n'); end >= 0; end = buffer.indexOf('\n\n')) {
122
126
  const event = buffer.slice(0, end);
123
127
  buffer = buffer.slice(end + 2);
124
128
  const data = event.split('\n').filter((line) => line.startsWith('data:')).map((line) => line.slice(5).trimStart()).join('\n');
125
129
  if (!data) continue;
126
- try { const out = JSON.parse(data); for (const one of Array.isArray(out) ? out : [out]) deliver(one); } catch { /* not a message */ }
130
+ try {
131
+ const out = JSON.parse(data);
132
+ for (const one of Array.isArray(out) ? out : [out]) {
133
+ deliver(one);
134
+ if (asked && one?.id === message.id && ('result' in one || 'error' in one)) answered = true;
135
+ }
136
+ } catch { /* not a message */ }
127
137
  }
128
138
  }
139
+ if (answered) await reader.cancel().catch(() => {});
129
140
  return;
130
141
  }
131
142
  const out = await response.json().catch(() => null);