@jossuealcala/madre 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. package/ADDITIONAL-TERMS.md +7 -2
  2. package/CHANGELOG.en.md +152 -1
  3. package/CHANGELOG.md +152 -1
  4. package/CONTRIBUTING.md +2 -2
  5. package/LICENSE +111 -661
  6. package/NOTICE +59 -24
  7. package/README.en.md +36 -204
  8. package/README.md +36 -210
  9. package/SECURITY.md +1 -0
  10. package/TRADEMARKS.en.md +13 -14
  11. package/TRADEMARKS.md +42 -26
  12. package/bin/madre.cjs +2 -2
  13. package/bin/madre.mjs +114 -42
  14. package/docs/REFERENCE.md +53 -6
  15. package/docs/SDK.md +44 -5
  16. package/docs/en/REFERENCE.md +53 -6
  17. package/docs/en/SDK.md +43 -4
  18. package/docs/madre-banner.png +0 -0
  19. package/docs/sdk/hello-module.mjs +3 -0
  20. package/package.json +3 -2
  21. package/public/abduction.js +6 -6
  22. package/public/activity.js +425 -0
  23. package/public/app.js +3519 -647
  24. package/public/assets/abduction-cat-blink.webp +0 -0
  25. package/public/assets/abduction-cat-control-left.webp +0 -0
  26. package/public/assets/abduction-cat-control-right.webp +0 -0
  27. package/public/assets/abduction-cat.webp +0 -0
  28. package/public/assets/manual/shots/en-agents.webp +0 -0
  29. package/public/assets/manual/shots/en-chats.webp +0 -0
  30. package/public/assets/manual/shots/en-code.webp +0 -0
  31. package/public/assets/manual/shots/en-composer.webp +0 -0
  32. package/public/assets/manual/shots/en-connectors.webp +0 -0
  33. package/public/assets/manual/shots/en-continuity.webp +0 -0
  34. package/public/assets/manual/shots/en-coordinator.webp +0 -0
  35. package/public/assets/manual/shots/en-copilot.webp +0 -0
  36. package/public/assets/manual/shots/en-diagnostics.webp +0 -0
  37. package/public/assets/manual/shots/en-home.webp +0 -0
  38. package/public/assets/manual/shots/en-local.webp +0 -0
  39. package/public/assets/manual/shots/en-market.webp +0 -0
  40. package/public/assets/manual/shots/en-memory.webp +0 -0
  41. package/public/assets/manual/shots/en-modes.webp +0 -0
  42. package/public/assets/manual/shots/en-notes.webp +0 -0
  43. package/public/assets/manual/shots/en-settings.webp +0 -0
  44. package/public/assets/manual/shots/en-welcome.webp +0 -0
  45. package/public/assets/manual/shots/en-windows.webp +0 -0
  46. package/public/assets/manual/shots/es-agents.webp +0 -0
  47. package/public/assets/manual/shots/es-chats.webp +0 -0
  48. package/public/assets/manual/shots/es-code.webp +0 -0
  49. package/public/assets/manual/shots/es-composer.webp +0 -0
  50. package/public/assets/manual/shots/es-connectors.webp +0 -0
  51. package/public/assets/manual/shots/es-continuity.webp +0 -0
  52. package/public/assets/manual/shots/es-coordinator.webp +0 -0
  53. package/public/assets/manual/shots/es-copilot.webp +0 -0
  54. package/public/assets/manual/shots/es-diagnostics.webp +0 -0
  55. package/public/assets/manual/shots/es-home.webp +0 -0
  56. package/public/assets/manual/shots/es-local.webp +0 -0
  57. package/public/assets/manual/shots/es-market.webp +0 -0
  58. package/public/assets/manual/shots/es-memory.webp +0 -0
  59. package/public/assets/manual/shots/es-modes.webp +0 -0
  60. package/public/assets/manual/shots/es-notes.webp +0 -0
  61. package/public/assets/manual/shots/es-settings.webp +0 -0
  62. package/public/assets/manual/shots/es-welcome.webp +0 -0
  63. package/public/assets/manual/shots/es-windows.webp +0 -0
  64. package/public/assets/news/1.1/en/chats.webp +0 -0
  65. package/public/assets/news/1.1/en/home.webp +0 -0
  66. package/public/assets/news/1.1/en/maps.webp +0 -0
  67. package/public/assets/news/1.1/en/market.webp +0 -0
  68. package/public/assets/news/1.1/en/permissions.webp +0 -0
  69. package/public/assets/news/1.1/en/privacy.webp +0 -0
  70. package/public/assets/news/1.1/en/welcome.webp +0 -0
  71. package/public/assets/news/1.1/es/chats.webp +0 -0
  72. package/public/assets/news/1.1/es/home.webp +0 -0
  73. package/public/assets/news/1.1/es/maps.webp +0 -0
  74. package/public/assets/news/1.1/es/market.webp +0 -0
  75. package/public/assets/news/1.1/es/permissions.webp +0 -0
  76. package/public/assets/news/1.1/es/privacy.webp +0 -0
  77. package/public/assets/news/1.1/es/welcome.webp +0 -0
  78. package/public/attribution.js +15 -16
  79. package/public/brands.js +2 -2
  80. package/public/code-tools.js +2 -2
  81. package/public/editor.js +13 -13
  82. package/public/en.js +483 -0
  83. package/public/es.js +1817 -598
  84. package/public/hardware.js +2 -2
  85. package/public/i18n.js +47 -9
  86. package/public/icons.js +158 -0
  87. package/public/index.html +68 -51
  88. package/public/inquiry.js +2 -2
  89. package/public/loader.js +271 -2
  90. package/public/macroverso.js +60 -21
  91. package/public/manual-content.js +900 -0
  92. package/public/manual-shots.js +47 -0
  93. package/public/manual.css +246 -0
  94. package/public/manual.html +15 -0
  95. package/public/manual.js +427 -0
  96. package/public/market-art.js +99 -41
  97. package/public/market-view.js +243 -47
  98. package/public/market.js +139 -26
  99. package/public/mcp-catalog.js +62 -0
  100. package/public/neural.js +64 -8
  101. package/public/nostromo-engine.js +709 -40
  102. package/public/page-errors.js +29 -0
  103. package/public/power.js +350 -11
  104. package/public/remedy.js +89 -0
  105. package/public/resay.js +4 -2
  106. package/public/review-ask.js +12 -7
  107. package/public/routing.js +3 -3
  108. package/public/salas-mac.css +875 -48
  109. package/public/salas-mac.html +27 -15
  110. package/public/salas-mac.js +1668 -338
  111. package/public/salas.css +2 -2
  112. package/public/salas.html +3 -3
  113. package/public/salas.js +3 -3
  114. package/public/styles.css +2694 -323
  115. package/public/syntax.js +2 -2
  116. package/public/terms.js +152 -0
  117. package/public/touch.js +2 -2
  118. package/public/tour-chapters.js +100 -92
  119. package/public/tour.js +118 -28
  120. package/public/troubleshooting.js +327 -21
  121. package/public/wallpaper.js +4 -3
  122. package/public/welcome.js +923 -0
  123. package/src/activity.mjs +85 -0
  124. package/src/adapters/claude.mjs +61 -35
  125. package/src/adapters/codex.mjs +18 -5
  126. package/src/adapters/cursor.mjs +60 -9
  127. package/src/adapters/gemini.mjs +17 -4
  128. package/src/adapters/madre.mjs +30 -9
  129. package/src/adapters/opencode.mjs +73 -10
  130. package/src/adapters/process.mjs +19 -15
  131. package/src/adapters/subagents.mjs +159 -0
  132. package/src/asking.mjs +8 -2
  133. package/src/auth-probe.mjs +47 -11
  134. package/src/bridge/devices.mjs +2 -2
  135. package/src/bridge/handoff.mjs +2 -2
  136. package/src/bridge/host.mjs +2 -2
  137. package/src/bridge/network.mjs +2 -2
  138. package/src/bridge/policy.mjs +3 -3
  139. package/src/bridge/qr.mjs +2 -2
  140. package/src/bridge/server.mjs +3 -3
  141. package/src/builtin-updates.mjs +87 -0
  142. package/src/capabilities.mjs +5 -5
  143. package/src/chats.mjs +51 -2
  144. package/src/checkpoint.mjs +67 -9
  145. package/src/choices.mjs +2 -2
  146. package/src/cli-args.mjs +2 -2
  147. package/src/cold.mjs +2 -2
  148. package/src/commands.mjs +2 -2
  149. package/src/config.mjs +2 -2
  150. package/src/conversation-context.mjs +2 -2
  151. package/src/credentials.mjs +80 -18
  152. package/src/dataset.mjs +2 -2
  153. package/src/directives.mjs +2 -2
  154. package/src/distiller.mjs +2 -2
  155. package/src/embeddings.mjs +2 -2
  156. package/src/enlaces.mjs +2 -2
  157. package/src/environment.mjs +147 -0
  158. package/src/event-store.mjs +2 -2
  159. package/src/exam.mjs +2 -2
  160. package/src/extensions.mjs +2 -2
  161. package/src/eyecat-watch.mjs +2 -2
  162. package/src/eyecat.mjs +2 -2
  163. package/src/file-ops.mjs +2 -2
  164. package/src/files.mjs +2 -2
  165. package/src/github.mjs +2 -2
  166. package/src/heartbeat.mjs +2 -2
  167. package/src/history.mjs +76 -0
  168. package/src/i18n.mjs +32 -3
  169. package/src/image-studio.mjs +2 -2
  170. package/src/install-metrics.mjs +109 -0
  171. package/src/json-file.mjs +2 -2
  172. package/src/launch.mjs +2 -2
  173. package/src/lease.mjs +15 -4
  174. package/src/lobby-work.mjs +11 -4
  175. package/src/local-ai.mjs +12 -4
  176. package/src/looks.mjs +19 -7
  177. package/src/market-check.mjs +165 -0
  178. package/src/market-key.mjs +10 -2
  179. package/src/market-license.mjs +104 -0
  180. package/src/market-remote.mjs +71 -13
  181. package/src/maturity.mjs +2 -2
  182. package/src/mcp/connect.mjs +2 -2
  183. package/src/mcp/github-server.mjs +2 -2
  184. package/src/mcp/image-server.mjs +2 -2
  185. package/src/mcp/memory-server.mjs +2 -2
  186. package/src/mcp/proxy.mjs +16 -5
  187. package/src/mcp/smtp-server.mjs +2 -2
  188. package/src/memory-dashboard.mjs +2 -2
  189. package/src/memory-tools.mjs +2 -2
  190. package/src/memory.mjs +2 -2
  191. package/src/models.mjs +115 -12
  192. package/src/module-scope.mjs +2 -2
  193. package/src/modules/ahp.mjs +2 -2
  194. package/src/modules/ash-policy.mjs +2 -2
  195. package/src/modules/ash.mjs +2 -2
  196. package/src/modules/bishop-exam.mjs +2 -2
  197. package/src/modules/bishop-plan.mjs +2 -2
  198. package/src/modules/bishop.mjs +9 -3
  199. package/src/modules/choices.mjs +2 -2
  200. package/src/modules/correo.mjs +2 -2
  201. package/src/modules/enlaces.mjs +2 -2
  202. package/src/modules/git-pulse.mjs +2 -2
  203. package/src/modules/github.mjs +2 -2
  204. package/src/modules/helpers.mjs +2 -2
  205. package/src/modules/image-studio.mjs +2 -2
  206. package/src/modules/index.mjs +92 -5
  207. package/src/modules/intents-calibration.mjs +2 -2
  208. package/src/modules/intents-desk.mjs +4 -3
  209. package/src/modules/intents-observe.mjs +2 -2
  210. package/src/modules/intents-policy.mjs +2 -2
  211. package/src/modules/intents-try.mjs +2 -2
  212. package/src/modules/intents.mjs +2 -2
  213. package/src/modules/local-models.mjs +41 -10
  214. package/src/modules/mcp-connect.mjs +2 -2
  215. package/src/modules/notes.mjs +281 -0
  216. package/src/modules/ollama.mjs +48 -13
  217. package/src/modules/playwright.mjs +16 -5
  218. package/src/modules/reminders.mjs +664 -0
  219. package/src/modules/ripley.mjs +3 -3
  220. package/src/modules/runs.mjs +2 -2
  221. package/src/modules/sdk.mjs +57 -9
  222. package/src/modules/updates.mjs +2 -2
  223. package/src/mother.mjs +13 -3
  224. package/src/npm-launch.mjs +2 -2
  225. package/src/ollama.mjs +8 -6
  226. package/src/opencode-health.mjs +83 -0
  227. package/src/outbound.mjs +35 -3
  228. package/src/override.mjs +27 -22
  229. package/src/ports.mjs +2 -2
  230. package/src/prices.mjs +2 -2
  231. package/src/privacy.mjs +2 -2
  232. package/src/quota-monitor.mjs +2 -2
  233. package/src/quota-sources.mjs +2 -2
  234. package/src/request-guard.mjs +2 -2
  235. package/src/review-ask.mjs +4 -3
  236. package/src/room/archivist.mjs +2 -2
  237. package/src/room/attachments.mjs +2 -2
  238. package/src/room/budget.mjs +2 -2
  239. package/src/room/context.mjs +2 -2
  240. package/src/room/control.mjs +2 -2
  241. package/src/room/copilot.mjs +2 -2
  242. package/src/room/economy.mjs +2 -2
  243. package/src/room/escalation.mjs +2 -2
  244. package/src/room/ghost.mjs +2 -2
  245. package/src/room/guard.mjs +6 -4
  246. package/src/room/prompt.mjs +3 -3
  247. package/src/room/returns.mjs +2 -2
  248. package/src/room/runs.mjs +6 -4
  249. package/src/room/vectors.mjs +2 -2
  250. package/src/room.mjs +144 -36
  251. package/src/router.mjs +2 -2
  252. package/src/runs.mjs +2 -2
  253. package/src/runtime-detection.mjs +36 -6
  254. package/src/salas.mjs +31 -6
  255. package/src/sentinel-errors.mjs +17 -7
  256. package/src/server-sentinel.mjs +2 -2
  257. package/src/server.mjs +980 -139
  258. package/src/setup-trouble.mjs +33 -0
  259. package/src/setup.mjs +4 -4
  260. package/src/smtp.mjs +2 -2
  261. package/src/telemetry.mjs +266 -0
  262. package/src/terms.mjs +43 -0
  263. package/src/tour.mjs +60 -7
  264. package/src/uninstall.mjs +225 -0
  265. package/src/updates.mjs +2 -2
  266. package/src/usage-sentinel.mjs +2 -2
  267. package/src/vault.mjs +2 -2
  268. package/src/verdict.mjs +13 -10
  269. package/src/whats-new.mjs +97 -3
  270. package/public/assets/abduction-cat-blink.png +0 -0
  271. package/public/assets/abduction-cat-control-left.png +0 -0
  272. package/public/assets/abduction-cat-control-right.png +0 -0
  273. package/public/assets/abduction-cat.png +0 -0
@@ -0,0 +1,664 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // Reminders (0.1, 2026-10-20). An idea by Daniel Castillo.
4
+ //
5
+ // What a person says they still have to do gets lost in a conversation: «mañana reviso el PR»,
6
+ // «recuérdame llamar a Daniel el lunes», the same request made every morning. This hears the
7
+ // person's own messages and, when one holds something pending or something they keep doing, puts
8
+ // a card under it — «¿Te lo recuerdo?» with the time already chosen — so a reminder takes one press.
9
+ // Nothing is set without that press.
10
+ //
11
+ // Two ways to notice, the cheap one first:
12
+ // · pending words that mean «later» or «remember» (WHEN, below, reads the when);
13
+ // · frequent the same request on three different days: offered as a daily reminder.
14
+ // When the project has the local AI, @madre's model reads a candidate before it is offered: it
15
+ // drops what is not a task and writes the task short, in the person's language. Without it the
16
+ // person's own words are offered as they are. No provider's agent is asked: a reminder costs
17
+ // no tokens.
18
+ //
19
+ // Reminders are kept for the whole computer, in ~/.pulse/reminders.json, each with the project and
20
+ // the conversation it came from: when it is due, Home shows it in «Needs you», and the project it
21
+ // came from shows it the moment it opens. A repeating one, marked done, comes back at its next time.
22
+ //
23
+ // ONE FILE (SDK 2, 2026-10-25). Everything Reminders is lives here: reading the when, its files,
24
+ // the cards, and the tool server an agent uses. It imports nothing from MADRE — the room's words
25
+ // come through ctx.t and the local AI through ctx.services.ollama — so a newer Reminders can come
26
+ // from the Market, signed, without waiting for a new MADRE (src/builtin-updates.mjs). When an
27
+ // agent runs it with node, the same file is the tool server (at the bottom).
28
+
29
+ import { mkdir, open, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
30
+ import { basename, dirname, join } from 'node:path';
31
+ import { randomUUID } from 'node:crypto';
32
+ import { fileURLToPath } from 'node:url';
33
+
34
+ const SELF = fileURLToPath(import.meta.url);
35
+
36
+ // FILES THAT MORE THAN ONE THING CHANGES (the same rules as MADRE's src/json-file.mjs): written
37
+ // whole, through a draft renamed over the file, and one change at a time — in this process by a
38
+ // queue, and between the rooms of this computer and the tool server by a lock file beside it.
39
+ async function writeWhole(file, text, { mode } = {}) {
40
+ await mkdir(dirname(file), { recursive: true });
41
+ const draft = `${file}.${process.pid}.${randomUUID()}.tmp`;
42
+ try {
43
+ await writeFile(draft, text, mode ? { mode } : undefined);
44
+ await rename(draft, file);
45
+ } catch (error) {
46
+ await rm(draft, { force: true }).catch(() => {});
47
+ throw error;
48
+ }
49
+ }
50
+
51
+ const STALE_MS = 5000;
52
+ async function lockBeside(file) {
53
+ const lock = `${file}.lock`;
54
+ await mkdir(dirname(lock), { recursive: true });
55
+ for (let attempt = 0; attempt < 250; attempt += 1) {
56
+ try {
57
+ await (await open(lock, 'wx')).close();
58
+ return () => rm(lock, { force: true });
59
+ } catch (error) {
60
+ if (error.code !== 'EEXIST') throw error;
61
+ const since = await stat(lock).catch(() => null);
62
+ if (since && Date.now() - since.mtimeMs > STALE_MS) { await rm(lock, { force: true }); continue; }
63
+ await new Promise((resolve) => setTimeout(resolve, 20));
64
+ }
65
+ }
66
+ throw new Error(`${file} is being changed by another room; try again.`);
67
+ }
68
+
69
+ const queues = new Map();
70
+ function oneAtATime(file, work) {
71
+ const run = async () => {
72
+ const release = await lockBeside(file);
73
+ try {
74
+ return await work();
75
+ } finally {
76
+ await release();
77
+ }
78
+ };
79
+ const before = queues.get(file) ?? Promise.resolve();
80
+ const turn = before.then(run, run);
81
+ const settled = turn.catch(() => {});
82
+ queues.set(file, settled);
83
+ void settled.then(() => { if (queues.get(file) === settled) queues.delete(file); });
84
+ return turn;
85
+ }
86
+
87
+ // WHEN, read from a person's own words.
88
+ // When a reminder is due, read from a person's own words (Reminders, 2026-10-20).
89
+ //
90
+ // «mañana a las 5», «el lunes», «en 2 horas», «cada día», «tomorrow at 9am», «every monday»: what
91
+ // people write when they say when, in Spanish or in English. Read here, without a model, so the
92
+ // same words always give the same hour and a reminder never depends on a model being awake. What
93
+ // is not said is filled the way a person would: a day without an hour is at 9:00, an hour without
94
+ // a day is the next time that hour comes, and «a las 5» with nothing else is in the afternoon.
95
+
96
+
97
+ const fold = (text) => String(text ?? '').normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
98
+ export const REPEATS = ['daily', 'weekdays', 'weekly'];
99
+ const DAYS = [
100
+ ['domingo', 'sunday'], ['lunes', 'monday'], ['martes', 'tuesday'], ['miercoles', 'wednesday'],
101
+ ['jueves', 'thursday'], ['viernes', 'friday'], ['sabado', 'saturday'],
102
+ ];
103
+ const dayIndex = (word) => DAYS.findIndex((names) => names.includes(word));
104
+ const DAY_WORDS = DAYS.flat().join('|');
105
+ const NUMBERS = { un: 1, una: 1, uno: 1, a: 1, an: 1, one: 1, dos: 2, two: 2, tres: 3, three: 3, cuatro: 4, four: 4, cinco: 5, five: 5, diez: 10, ten: 10, quince: 15, fifteen: 15, veinte: 20, twenty: 20, treinta: 30, thirty: 30 };
106
+ const UNIT_MS = { min: 60000, hor: 3600000, hou: 3600000, dia: 86400000, day: 86400000, sem: 7 * 86400000, wee: 7 * 86400000 };
107
+ export const DEFAULT_HOUR = 9;
108
+
109
+ const at = (base, hour, minute = 0) => { const next = new Date(base); next.setHours(hour, minute, 0, 0); return next; };
110
+ const plusDays = (base, days) => { const next = new Date(base); next.setDate(next.getDate() + days); return next; };
111
+
112
+ // The hour said, if any: «a las 5», «a las 17:30», «at 9am», «5 pm», «10:15». `tagged`: whether it
113
+ // said which half of the day (am, pm, «de la tarde»…), so the part of the day may still decide it.
114
+ // In English «at 3» is an hour only when nothing but the time follows it: «look at 3 files» is not.
115
+ const AT_FOLLOWS = /^\s*($|[,.;:!?)]|(?:tomorrow|today|tonight|to|on|in|every|and|then|sharp|o'?clock)\b)/;
116
+ function hourSaid(text) {
117
+ let match = null;
118
+ for (const one of text.matchAll(/\b(a las|a la|at)\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm|a\.m\.|p\.m\.|de la manana|de la tarde|de la noche|hrs|h)?\b/g)) {
119
+ if (one[1] === 'at' && !one[3] && !one[4] && !AT_FOLLOWS.test(text.slice(one.index + one[0].length))) continue;
120
+ match = one.slice(1);
121
+ break;
122
+ }
123
+ match ??= text.match(/\b()(\d{1,2}):(\d{2})\s*(am|pm|a\.m\.|p\.m\.)?/)?.slice(1)
124
+ ?? text.match(/\b()(\d{1,2})()\s*(am|pm|a\.m\.|p\.m\.)(?![a-z])/)?.slice(1);
125
+ if (!match) return null;
126
+ let hour = Number(match[1]);
127
+ const minute = Number(match[2] || 0);
128
+ const tag = match[3] ?? '';
129
+ if (hour > 23 || minute > 59) return null;
130
+ if (/pm|p\.m\.|tarde|noche/.test(tag) && hour < 12) hour += 12;
131
+ else if (/am|a\.m\.|manana/.test(tag) && hour === 12) hour = 0;
132
+ // «a las 5» with nothing else: a person at work means the afternoon, not dawn.
133
+ else if (!tag && hour >= 1 && hour <= 7) hour += 12;
134
+ // A 24-hour clock («a las 17», «9 hrs») or a half said (pm, «de la tarde») is not the part of the day's to change.
135
+ return { hour, minute, tagged: Number(match[1]) > 12 || Boolean(tag) };
136
+ }
137
+
138
+ // The part of the day said in words, when no hour was.
139
+ function partOfDay(text) {
140
+ if (/\b(esta noche|en la noche|por la noche|tonight|in the evening)\b/.test(text)) return { hour: 20, minute: 0 };
141
+ if (/\b(esta tarde|en la tarde|por la tarde|this afternoon|in the afternoon)\b/.test(text)) return { hour: 17, minute: 0 };
142
+ if (/\b(en la manana|por la manana|in the morning)\b/.test(text)) return { hour: 9, minute: 0 };
143
+ if (/\b(al mediodia|a mediodia|at noon|noon)\b/.test(text)) return { hour: 12, minute: 0 };
144
+ return null;
145
+ }
146
+
147
+ // What repeats, and on which day for a weekly one.
148
+ function repeatOf(text) {
149
+ const weekly = text.match(new RegExp(`\\b(?:cada|todos los|every)\\s+(${DAY_WORDS})s?\\b`));
150
+ if (weekly) return { repeat: 'weekly', day: dayIndex(weekly[1]) };
151
+ if (/\b(entre semana|de lunes a viernes|every weekday|weekdays)\b/.test(text)) return { repeat: 'weekdays' };
152
+ if (/\b(cada dia|todos los dias|diario|diariamente|cada manana|todas las mananas|every day|everyday|daily|each day|every morning)\b/.test(text)) return { repeat: 'daily' };
153
+ if (/\b(cada semana|semanal(mente)?|every week|weekly)\b/.test(text)) return { repeat: 'weekly' };
154
+ return null;
155
+ }
156
+
157
+ // The next time a repeating reminder comes after `after`.
158
+ export function nextOccurrence(due, repeat, after = new Date()) {
159
+ let next = new Date(due);
160
+ if (!REPEATS.includes(repeat)) return next;
161
+ const step = () => {
162
+ if (repeat === 'weekly') next = plusDays(next, 7);
163
+ else {
164
+ next = plusDays(next, 1);
165
+ if (repeat === 'weekdays') while (next.getDay() === 0 || next.getDay() === 6) next = plusDays(next, 1);
166
+ }
167
+ };
168
+ for (let guard = 0; next <= after && guard < 4000; guard += 1) step();
169
+ return next;
170
+ }
171
+
172
+ // { due, repeat, said } for the words, or null when they say no time at all.
173
+ export function parseWhen(words, now = new Date(), { hour: dayHour = DEFAULT_HOUR } = {}) {
174
+ const text = fold(words);
175
+ const base = new Date(now);
176
+ const repeated = repeatOf(text);
177
+ // The part of the day decides an hour that did not say its half: «esta noche a las 9» is 21:00,
178
+ // «en la mañana a las 5» is 5:00.
179
+ const clock = hourSaid(text);
180
+ const part = partOfDay(text);
181
+ let hour = clock ?? part;
182
+ if (clock && !clock.tagged && part) {
183
+ if (part.hour >= 17 && clock.hour < 12) hour = { ...clock, hour: clock.hour + 12 };
184
+ else if (part.hour === 9 && clock.hour > 12) hour = { ...clock, hour: clock.hour - 12 };
185
+ }
186
+ const said = [];
187
+
188
+ // «en 2 horas», «en media hora», «in 20 minutes»: a moment from now, the hour does not apply.
189
+ const relative = text.match(/\b(?:en|in|dentro de)\s+(\d+|media|half an?|un|una|uno|a|an|one|dos|two|tres|three|cuatro|four|cinco|five|diez|ten|quince|fifteen|veinte|twenty|treinta|thirty)\s+(min\w*|hor\w*|hou\w*|dia\w*|day\w*|sem\w*|wee\w*)/);
190
+ if (relative && !repeated) {
191
+ const amount = /^(media|half)/.test(relative[1]) ? 0.5 : Number(relative[1]) || NUMBERS[relative[1]] || 1;
192
+ const unit = UNIT_MS[relative[2].slice(0, 3)] ?? 3600000;
193
+ return { due: new Date(base.getTime() + amount * unit), repeat: null, said: relative[0] };
194
+ }
195
+
196
+ let day = null;
197
+ if (/\bpasado manana\b|\bday after tomorrow\b/.test(text)) { day = plusDays(base, 2); said.push('pasado mañana'); }
198
+ // «mañana» is tomorrow unless it is the morning: «la mañana», «de la mañana», «por la mañana».
199
+ else if (/(^|[^a-z])(manana)(?![a-z])/.test(text.replace(/\b(la|las|en la|por la|de la|cada|todas las)\s+manana(s)?\b/g, ' ')) || /\btomorrow\b/.test(text)) { day = plusDays(base, 1); said.push('mañana'); }
200
+ else if (/\b(hoy|today|tonight|esta tarde|esta noche|this afternoon)\b/.test(text)) { day = new Date(base); said.push('hoy'); }
201
+ else if (/\b(la proxima semana|la semana que viene|next week)\b/.test(text)) {
202
+ day = plusDays(base, ((8 - base.getDay()) % 7) || 7);
203
+ said.push('la próxima semana');
204
+ } else {
205
+ const named = text.match(new RegExp(`\\b(?:el|este|el proximo|on|next|this)?\\s*(${DAY_WORDS})\\b`));
206
+ if (named && !repeated) {
207
+ const target = dayIndex(named[1]);
208
+ const ahead = (target - base.getDay() + 7) % 7;
209
+ day = plusDays(base, ahead || 7);
210
+ said.push(named[1]);
211
+ }
212
+ }
213
+
214
+ if (repeated) {
215
+ let first = at(base, hour?.hour ?? dayHour, hour?.minute ?? 0);
216
+ if (repeated.repeat === 'weekly' && Number.isInteger(repeated.day)) first = plusDays(first, (repeated.day - base.getDay() + 7) % 7);
217
+ if (repeated.repeat === 'weekdays') while (first.getDay() === 0 || first.getDay() === 6) first = plusDays(first, 1);
218
+ const due = first > base ? first : nextOccurrence(first, repeated.repeat, base);
219
+ return { due, repeat: repeated.repeat, said: 'repeat' };
220
+ }
221
+ if (day) {
222
+ const due = at(day, hour?.hour ?? dayHour, hour?.minute ?? 0);
223
+ // «hoy a las 8» written at 23:00: never born overdue — the same hour, tomorrow.
224
+ return { due: due > base ? due : plusDays(due, 1), repeat: null, said: said.join(' ') };
225
+ }
226
+ if (hour) {
227
+ const today = at(base, hour.hour, hour.minute);
228
+ return { due: today > base ? today : plusDays(today, 1), repeat: null, said: 'hour' };
229
+ }
230
+ return null;
231
+ }
232
+
233
+ // When nothing was said: tomorrow, at the start of the day (the person's own start, from Reminders' settings).
234
+ export const tomorrowMorning = (now = new Date(), hour = DEFAULT_HOUR) => at(plusDays(now, 1), hour);
235
+
236
+ // A message that asks for a reminder (2026-10-20): «/recordatorios …», «/reminders …», «recuérdame».
237
+ export const ASKS_FOR_REMINDER = /(^|\s)\/(recordatorios?|reminders?|remind)\b|recu[eé]rd(ame|anos|ale)|\brecordatorios?\b|\bremind(er|ers)?\b/i;
238
+
239
+ export const REMINDERS_MAX = 500;
240
+ export const REMINDER_TEXT_MAX = 200;
241
+ const ID = /^[a-z0-9-]{6,64}$/i;
242
+ const remindersFile = (stateRoot) => join(stateRoot, 'reminders.json');
243
+ const habitsFile = (roomDir) => join(roomDir, 'reminder-habits.json');
244
+ const iso = (value) => (typeof value === 'string' && !Number.isNaN(Date.parse(value)) ? new Date(value).toISOString() : null);
245
+
246
+ function reminderOf(raw) {
247
+ if (!raw || typeof raw !== 'object' || !ID.test(String(raw.id ?? '')) || !iso(raw.due)) return null;
248
+ const text = String(raw.text ?? '').trim().slice(0, REMINDER_TEXT_MAX);
249
+ if (!text) return null;
250
+ return {
251
+ id: raw.id,
252
+ text,
253
+ due: iso(raw.due),
254
+ repeat: REPEATS.includes(raw.repeat) ? raw.repeat : null,
255
+ room: typeof raw.room === 'string' && raw.room.length <= 200 ? raw.room : null,
256
+ project: typeof raw.project === 'string' ? raw.project.slice(0, 120) : null,
257
+ chat: typeof raw.chat === 'string' && raw.chat.length <= 120 ? raw.chat : null,
258
+ why: ['pending', 'frequent', 'asked', 'manual'].includes(raw.why) ? raw.why : 'manual',
259
+ done: iso(raw.done),
260
+ // A repeating one put off: the time of its series, which «Done» goes on from.
261
+ series: REPEATS.includes(raw.repeat) ? iso(raw.series) : null,
262
+ at: iso(raw.at) ?? new Date(0).toISOString(),
263
+ };
264
+ }
265
+ export async function readReminders(stateRoot) {
266
+ if (!stateRoot) return [];
267
+ const raw = await readFile(remindersFile(stateRoot), 'utf8').then((text) => JSON.parse(text)).catch(() => null);
268
+ return (Array.isArray(raw?.reminders) ? raw.reminders : []).map(reminderOf).filter(Boolean).slice(0, REMINDERS_MAX);
269
+ }
270
+ const writeReminders = (stateRoot, reminders) => writeWhole(remindersFile(stateRoot), `${JSON.stringify({ reminders }, null, 2)}\n`);
271
+ const change = (stateRoot, work) => oneAtATime(remindersFile(stateRoot), async () => {
272
+ const reminders = await readReminders(stateRoot);
273
+ const answer = await work(reminders);
274
+ if (answer?.write !== false) await writeReminders(stateRoot, reminders.filter((one) => !one.drop).map(({ drop, ...one }) => one));
275
+ return answer;
276
+ });
277
+
278
+ export function addReminder(stateRoot, { text, due, repeat = null, room = null, project = null, chat = null, why = 'manual' }, now = new Date()) {
279
+ const made = reminderOf({ id: randomUUID(), text, due, repeat, room, project, chat, why, at: new Date(now).toISOString() });
280
+ if (!made) return Promise.resolve({ error: 'reminder' });
281
+ return change(stateRoot, (reminders) => {
282
+ // Done ones go first when the file is full: they are only history.
283
+ const open = reminders.filter((one) => !one.done);
284
+ if (open.length >= REMINDERS_MAX) return { error: 'full', write: false };
285
+ if (reminders.length >= REMINDERS_MAX) reminders.splice(reminders.findIndex((one) => one.done), 1);
286
+ reminders.push(made);
287
+ return { reminder: made };
288
+ });
289
+ }
290
+ // Done: a repeating one moves to its next time — also when it is marked before its hour today, which
291
+ // counts for today — from the hour of its series, not from where a snooze had moved it; any other is
292
+ // kept as done.
293
+ export function doneReminder(stateRoot, id, now = new Date()) {
294
+ return change(stateRoot, (reminders) => {
295
+ const one = reminders.find((item) => item.id === id);
296
+ if (!one) return { error: 'unknown', write: false };
297
+ if (one.repeat) {
298
+ const after = new Date(Math.max(new Date(now).getTime(), new Date(one.due).getTime()));
299
+ one.due = nextOccurrence(one.series ?? one.due, one.repeat, after).toISOString();
300
+ one.series = null;
301
+ } else one.done = new Date(now).toISOString();
302
+ return { reminder: one };
303
+ });
304
+ }
305
+ // Later: this time only. A repeating one keeps the hour of its series (`series`) to come back to.
306
+ export function snoozeReminder(stateRoot, id, until) {
307
+ return change(stateRoot, (reminders) => {
308
+ const one = reminders.find((item) => item.id === id);
309
+ if (!one || !iso(until)) return { error: 'unknown', write: false };
310
+ if (one.repeat) one.series ??= one.due;
311
+ one.due = iso(until);
312
+ one.done = null;
313
+ return { reminder: one };
314
+ });
315
+ }
316
+ export function clearDone(stateRoot, room = null) {
317
+ return change(stateRoot, (reminders) => {
318
+ let cleared = 0;
319
+ for (const one of reminders) if (one.done && (!room || one.room === room)) { one.drop = true; cleared += 1; }
320
+ return { cleared };
321
+ });
322
+ }
323
+ export function deleteReminder(stateRoot, id) {
324
+ return change(stateRoot, (reminders) => {
325
+ const one = reminders.find((item) => item.id === id);
326
+ if (!one) return { error: 'unknown', write: false };
327
+ one.drop = true;
328
+ return { deleted: id };
329
+ });
330
+ }
331
+
332
+ // PENDING: words that mean «later», «remember», «I still have to». Strong ones only: «luego» and
333
+ // «después» are how half the sentences of a conversation begin.
334
+ const PENDING = /\b(recuerd(a|ame|anos|ale)|recordarme|no (me )?(dejes|deje) olvidar|que no se me olvide|no olvides|no olvidar|pendiente|tengo que|tenemos que|manana|pasado manana|el (lunes|martes|miercoles|jueves|viernes|sabado|domingo)|la proxima semana|mas tarde|esta tarde|esta noche|cada (dia|semana|lunes|martes|miercoles|jueves|viernes|manana)|todos los (dias|lunes|martes|miercoles|jueves|viernes)|remind me|don'?t (let me )?forget|to-?do|tomorrow|next week|later today|this afternoon|tonight|every (day|week|morning|monday|tuesday|wednesday|thursday|friday)|follow up|dar seguimiento)\b/;
335
+ // When it is due is the card's to say: «mañana a las 5», «el lunes», «tomorrow at 9am» at the head
336
+ // of the sentence are taken off what the reminder says.
337
+ const LEADING_WHEN = /^(?:(?:pasado\s+)?ma[nñ]ana|hoy|esta\s+(?:tarde|noche)|(?:el|este|el\s+pr[oó]ximo)\s+(?:lunes|martes|mi[eé]rcoles|jueves|viernes|s[aá]bado|domingo)|la\s+pr[oó]xima\s+semana|en\s+\d+\s+(?:minutos?|horas?|d[ií]as?)|tomorrow|today|tonight|next\s+week|(?:on\s+)?(?:monday|tuesday|wednesday|thursday|friday|saturday|sunday)|in\s+\d+\s+(?:minutes?|hours?|days?))?\s*(?:(?:a\s+las?|at)\s+\d{1,2}(?::\d{2})?\s*(?:am|pm|de\s+la\s+(?:ma[nñ]ana|tarde|noche))?)?\s*(?:,\s*)?(?:que\s+|to\s+)?/i;
338
+ // What a reminder says, from the message: the cue words taken off its head, the rest as it was.
339
+ export function taskFromWords(text) {
340
+ const line = String(text ?? '').split('\n').map((one) => one.trim()).find(Boolean) ?? '';
341
+ const bare = line
342
+ .replace(/^(oye|hey|ok|vale|bueno|porfa|por favor|please)[,\s]+/i, '')
343
+ .replace(/^(recu[eé]rd(ame|anos|ale|a)|remind me|no (me )?(dejes|deje) olvidar|no olvides|don'?t (let me )?forget)\s*(?:(?:que|de|to|that)\b)?\s*/i, '')
344
+ .replace(LEADING_WHEN, '')
345
+ .replace(LEADING_WHEN, '')
346
+ .replace(/[.!?¿¡]+$/, '')
347
+ .trim();
348
+ return (bare.charAt(0).toUpperCase() + bare.slice(1)).slice(0, REMINDER_TEXT_MAX);
349
+ }
350
+ export function pendingIn(text) {
351
+ const words = fold(text);
352
+ if (words.length < 6 || words.length > 600 || !PENDING.test(words)) return null;
353
+ const asked = /\b(recuerd(a|ame|anos|ale)|recordarme|remind me|no olvides|don'?t (let me )?forget|que no se me olvide)\b/.test(words);
354
+ return { why: asked ? 'asked' : 'pending', text: taskFromWords(text) };
355
+ }
356
+
357
+ // FREQUENT: a request said again and again, read as its first content words.
358
+ const STOP = new Set('a al algo como con de del el en es esa ese eso esta este esto la las le lo los me mi mis no o para pero por que se si sin su sus te tu un una uno y ya yo the a an and to of in on for is it this that be with you me my please can could would por favor puedes podrias'.split(' '));
359
+ export function habitKey(text) {
360
+ const words = fold(text).replace(/[^a-z0-9ñ\s]/g, ' ').split(/\s+/).filter((word) => word.length >= 3 && !STOP.has(word));
361
+ if (words.length < 2 || words.length > 25) return null;
362
+ return words.slice(0, 5).join(' ');
363
+ }
364
+ // Seen once more; frequent the third time on a different day. Kept per project, small.
365
+ export function noteHabit(roomDir, text, now = new Date()) {
366
+ const key = habitKey(text);
367
+ if (!key) return Promise.resolve(null);
368
+ const file = habitsFile(roomDir);
369
+ return oneAtATime(file, async () => {
370
+ const raw = await readFile(file, 'utf8').then((body) => JSON.parse(body)).catch(() => ({}));
371
+ const habits = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
372
+ const day = new Date(now).toISOString().slice(0, 10);
373
+ const seen = habits[key] && Array.isArray(habits[key].days) ? habits[key] : { days: [], offered: false };
374
+ if (!seen.days.includes(day)) seen.days = [...seen.days, day].slice(-10);
375
+ seen.sample = String(text).slice(0, REMINDER_TEXT_MAX);
376
+ seen.hour = new Date(now).getHours();
377
+ habits[key] = seen;
378
+ // The newest two hundred, so the file stays small.
379
+ const kept = Object.fromEntries(Object.entries(habits).sort((a, b) => String(b[1].days?.at(-1)).localeCompare(String(a[1].days?.at(-1)))).slice(0, 200));
380
+ const frequent = seen.days.length >= 3 && !seen.offered;
381
+ if (frequent) kept[key].offered = true;
382
+ await writeWhole(file, `${JSON.stringify(kept)}\n`);
383
+ return frequent ? { why: 'frequent', text: taskFromWords(text), hour: seen.hour } : null;
384
+ });
385
+ }
386
+
387
+ // The local model's reading of a candidate: is it a task, and how would a reminder say it.
388
+ const LOCAL_SYSTEM = 'You read one message a person wrote to their AI agents about their project. Decide whether it holds something the PERSON must do or remember later: a pending task, a deadline, a follow-up, or something they asked to be reminded of. Questions, instructions for the agents to do now, and plans already done are not. Answer with JSON only: {"remind": true|false, "what": "the task as a short reminder, imperative, in the same language as the message, at most 80 characters", "when": "when it is due, in the words of the message, or empty"}.';
389
+ export async function readWithLocal({ generate, model = null, text, timeoutMs = 45000 }) {
390
+ try {
391
+ const answer = await generate({ model, system: LOCAL_SYSTEM, prompt: String(text).slice(0, 2000), json: true, timeoutMs, temperature: 0 });
392
+ const parsed = JSON.parse(answer.text);
393
+ if (typeof parsed?.remind !== 'boolean') return null;
394
+ return { remind: parsed.remind, what: typeof parsed.what === 'string' ? parsed.what.trim().replace(/[.!¡]+$/, '').slice(0, REMINDER_TEXT_MAX) : '', when: typeof parsed.when === 'string' ? parsed.when.slice(0, 120) : '' };
395
+ } catch { return null; }
396
+ }
397
+
398
+ // One offer per conversation every few minutes, unless the person asked for it in words.
399
+ const lastOffer = new Map();
400
+ const OFFER_GAP_MS = 10 * 60 * 1000;
401
+ export async function offerFor(ctx, event, { now = new Date() } = {}) {
402
+ const said = event?.payload ?? {};
403
+ if (event?.type !== 'message.created' || said.role !== 'user' || said.via || said.synthetic) return null;
404
+ const text = String(said.text ?? '');
405
+ if (!text.trim() || text.trim().startsWith('/')) return null;
406
+ const prefs = ctx.settings ?? {};
407
+ const dayHour = hourOf(prefs);
408
+ let found = prefs.offer === false ? null : pendingIn(text);
409
+ const habit = ctx.roomDir && prefs.habits !== false ? await noteHabit(ctx.roomDir, text, now).catch(() => null) : null;
410
+ if (!found && habit) found = habit;
411
+ if (!found) return null;
412
+ const chatKey = `${ctx.roomId ?? 'home'}|${ctx.chat ?? ''}`;
413
+ if (found.why !== 'asked' && Date.now() - (lastOffer.get(chatKey) ?? 0) < OFFER_GAP_MS) return null;
414
+ // The local AI, when this project has it, reads it first and says it shorter.
415
+ let what = found.text;
416
+ let whenWords = text;
417
+ let by = 'words';
418
+ const local = ctx.services?.ollama?.state?.() ?? null;
419
+ const project = await Promise.resolve(ctx.services?.ollama?.project?.()).catch(() => null);
420
+ const model = local?.madreModel ?? local?.chatModel ?? null;
421
+ const generate = ctx.services?.ollama?.generate;
422
+ if (prefs.local !== false && typeof generate === 'function' && local?.running && model && project?.on !== false && found.why !== 'frequent') {
423
+ const read = await readWithLocal({ generate, model, text });
424
+ if (read && !read.remind && found.why !== 'asked') return null;
425
+ if (read?.what) { what = read.what; by = 'local'; }
426
+ if (read?.when) whenWords = `${read.when} ${text}`;
427
+ }
428
+ if (!what) return null;
429
+ const when = found.why === 'frequent'
430
+ ? { due: nextOccurrence(new Date(new Date(now).setHours(found.hour ?? 9, 0, 0, 0)), 'daily', now), repeat: 'daily' }
431
+ : parseWhen(whenWords, now, { hour: dayHour }) ?? { due: tomorrowMorning(now, dayHour), repeat: null };
432
+ lastOffer.set(chatKey, Date.now());
433
+ return { offer: randomUUID(), what, due: when.due.toISOString(), repeat: when.repeat ?? null, why: found.why, by, messageId: said.messageId ?? null };
434
+ }
435
+
436
+ const reply = (status, body) => ({ status, body });
437
+ // What the person set in Reminders' settings: the hour a day starts at, and how long «later» is.
438
+ export const HOURS = ['7', '8', '9', '10', '11', '12'];
439
+ export const SNOOZES = ['15', '30', '60', '180'];
440
+ const hourOf = (prefs) => (HOURS.includes(String(prefs?.hour)) ? Number(prefs.hour) : 9);
441
+ const snoozeOf = (prefs) => (SNOOZES.includes(String(prefs?.snooze)) ? Number(prefs.snooze) : 60);
442
+ const prefsOf = (ctx) => ctx.settings ?? {};
443
+ // A due time said as a person reads it, in the room's language.
444
+ export const whenWords = (due, language = 'es') => new Intl.DateTimeFormat(language === 'en' ? 'en-US' : 'es-MX', { weekday: 'long', day: 'numeric', month: 'long', hour: 'numeric', minute: '2-digit' }).format(new Date(due));
445
+ const projectOf = (ctx) => (ctx.roomId ? basename(ctx.projectRoot ?? '') || null : null);
446
+ // The quick times a card offers beside the one it chose, said as data the page puts in words.
447
+ export function quickTimes(now = new Date()) {
448
+ const hour = new Date(now.getTime() + 3600000);
449
+ const evening = new Date(now); evening.setHours(18, 0, 0, 0);
450
+ const monday = parseWhen('el lunes', now).due;
451
+ return [
452
+ { id: 'hour', due: hour.toISOString(), repeat: null },
453
+ ...(evening > new Date(now.getTime() + 30 * 60000) ? [{ id: 'evening', due: evening.toISOString(), repeat: null }] : []),
454
+ { id: 'tomorrow', due: tomorrowMorning(now).toISOString(), repeat: null },
455
+ { id: 'monday', due: monday.toISOString(), repeat: null },
456
+ ];
457
+ }
458
+
459
+ // The room's words (ctx.t, SDK 2); outside a room — a test, the tool server — the English as written.
460
+ const say = (ctx, text, vars = null) => (typeof ctx?.t === 'function' ? ctx.t(text, vars) : String(text).replace(/\{(\w+)\}/g, (whole, name) => (vars && Object.hasOwn(vars, name) ? String(vars[name]) : whole)));
461
+
462
+ export default {
463
+ sdk: 2,
464
+ id: 'reminders',
465
+ name: 'Reminders',
466
+ vendor: 'MADRE',
467
+ version: '0.1.0',
468
+ credit: 'Daniel Castillo',
469
+ summary: 'Notices what you say you still have to do, or what you ask for every day, and offers to remind you with one press. Reminders show in Home and in the project they came from. Read on your computer, with the local AI when you have it; no agent is asked.',
470
+ creates: ['nothing in the project', 'a reminders.json file in ~/.pulse, one for the whole computer'],
471
+ settings: { enabled: false, offer: true, habits: true, local: true, hour: '9', snooze: '60' },
472
+ controls: [
473
+ { key: 'offer', type: 'switch', label: 'Offer a reminder when you write something pending', note: 'A card under your message, with the time already chosen. Nothing is set without your click.' },
474
+ { key: 'habits', type: 'switch', label: 'Notice what you ask for often', note: 'The same request on three different days is offered as a daily reminder.' },
475
+ { key: 'local', type: 'switch', label: 'Let the local AI read it first', note: 'When the project has it, it drops what is not a task and says it shorter. Without it, your own words are offered.' },
476
+ { key: 'hour', type: 'select', label: 'Hour when you do not say one', options: HOURS, choices: HOURS.map((hour) => ({ value: hour, label: `${hour}:00` })), note: '«Tomorrow» with no hour is tomorrow at this hour.' },
477
+ { key: 'snooze', type: 'select', label: 'Put off by', options: SNOOZES, choices: [{ value: '15', label: '15 minutes' }, { value: '30', label: '30 minutes' }, { value: '60', label: '1 hour' }, { value: '180', label: '3 hours' }], note: 'What the «later» key on a reminder that is due waits.' },
478
+ ],
479
+ async status(ctx) {
480
+ const enabled = Boolean(ctx.settings.enabled);
481
+ const list = (await readReminders(ctx.stateRoot)).filter((one) => !one.done && (!ctx.roomId || one.room === ctx.roomId));
482
+ // What is still to come, and what already fell due, said apart (QA 1.1.0, ACT-10).
483
+ const due = list.filter((one) => Date.parse(one.due) <= Date.now()).length;
484
+ const ahead = list.length - due;
485
+ const words = [ahead === 1 ? say(ctx, '1 reminder ahead') : say(ctx, '{n} reminders ahead', { n: ahead }), due ? (due === 1 ? say(ctx, '1 due') : say(ctx, '{n} due', { n: due })) : null].filter(Boolean).join(' · ');
486
+ return {
487
+ status: { installed: enabled, detail: enabled ? words : say(ctx, 'off') },
488
+ install: { display: enabled ? 'turn off Reminders' : 'turn on Reminders', platforms: [] },
489
+ };
490
+ },
491
+ async onEvent(ctx, event) {
492
+ const offer = await offerFor(ctx, event);
493
+ if (offer) await ctx.record('reminder.offered', offer);
494
+ },
495
+ // An agent sets a reminder when the person asks for one (this same file, run as its tool server):
496
+ // it can only add.
497
+ async toolsForTurn(ctx, turn) {
498
+ if (turn?.text !== undefined && !ASKS_FOR_REMINDER.test(turn.text)) return [];
499
+ return [{
500
+ name: 'madre-reminders',
501
+ command: process.execPath,
502
+ args: [SELF],
503
+ env: { PULSE_REMINDERS_STATE: ctx.stateRoot, PULSE_ROOM_ID: ctx.roomId ?? '', PULSE_PROJECT: projectOf(ctx) ?? '', PULSE_REMINDER_HOUR: String(hourOf(ctx.settings)) },
504
+ tools: ['create_reminder'],
505
+ brief: 'When the person asks to be reminded of something (they may write /recordatorios or /reminders), set it with the create_reminder tool of server madre-reminders: what to remember, short, in their language, and when, in their own words. Then tell them when it is due.',
506
+ }];
507
+ },
508
+ routes: [
509
+ // This project's reminders, or every one in Home; the due ones first.
510
+ { method: 'GET', path: '/api/reminders', handler: async (ctx, { url }) => {
511
+ const all = !ctx.roomId || url?.searchParams?.get('all') === '1';
512
+ const mine = (await readReminders(ctx.stateRoot)).filter((one) => all || one.room === ctx.roomId);
513
+ const list = mine.filter((one) => !one.done).sort((a, b) => a.due.localeCompare(b.due));
514
+ // The done ones, newest first, only when asked: the sheet's history.
515
+ const done = url?.searchParams?.get('done') === '1' ? mine.filter((one) => one.done).sort((a, b) => b.done.localeCompare(a.done)).slice(0, 20) : undefined;
516
+ const prefs = prefsOf(ctx);
517
+ return reply(200, { reminders: list, done, room: ctx.roomId ?? null, now: new Date().toISOString(), times: quickTimes(), prefs: { hour: hourOf(prefs), snooze: snoozeOf(prefs) } });
518
+ } },
519
+ { method: 'POST', path: '/api/reminders', handler: async (ctx, { payload }) => {
520
+ const text = String(payload?.text ?? '').trim();
521
+ if (!text) return reply(400, { error: say(ctx, 'Write what to remember.') });
522
+ const dayHour = hourOf(prefsOf(ctx));
523
+ const when = iso(payload?.due) ? { due: new Date(payload.due), repeat: REPEATS.includes(payload?.repeat) ? payload.repeat : null } : parseWhen(`${payload?.when ?? ''} ${text}`, new Date(), { hour: dayHour }) ?? { due: tomorrowMorning(new Date(), dayHour), repeat: null };
524
+ const made = await addReminder(ctx.stateRoot, { text: taskFromWords(text), due: when.due.toISOString(), repeat: when.repeat, room: ctx.roomId ?? null, project: projectOf(ctx), why: 'manual' });
525
+ return made.error ? reply(409, { error: say(ctx, 'The reminder was not set.') }) : reply(200, made);
526
+ } },
527
+ // The answer to a card: yes with the time it offered or one of the quick ones, or no.
528
+ { method: 'POST', path: '/api/reminders/answer', handler: async (ctx, { payload }) => {
529
+ const offer = String(payload?.offer ?? '');
530
+ if (!ID.test(offer)) return reply(400, { error: say(ctx, 'That offer is not known.') });
531
+ const chat = typeof payload?.chat === 'string' ? payload.chat : null;
532
+ let made = null;
533
+ if (payload?.accept === true) {
534
+ const due = iso(payload?.due);
535
+ if (!due) return reply(400, { error: say(ctx, 'Say when.') });
536
+ made = await addReminder(ctx.stateRoot, { text: String(payload?.text ?? ''), due, repeat: REPEATS.includes(payload?.repeat) ? payload.repeat : null, room: ctx.roomId ?? null, project: projectOf(ctx), chat, why: ['pending', 'frequent', 'asked'].includes(payload?.why) ? payload.why : 'pending' });
537
+ if (made.error) return reply(409, { error: say(ctx, 'The reminder was not set.') });
538
+ }
539
+ const settled = { offer, accepted: Boolean(made), id: made?.reminder.id ?? null, due: made?.reminder.due ?? null, repeat: made?.reminder.repeat ?? null };
540
+ await ctx.services.recordIn(chat, 'reminder.answered', settled).catch(() => null);
541
+ return reply(200, { ...settled, reminder: made?.reminder ?? null });
542
+ } },
543
+ { method: 'POST', path: '/api/reminders/done', handler: async (ctx, { payload }) => {
544
+ const done = await doneReminder(ctx.stateRoot, String(payload?.id ?? ''));
545
+ return done.error ? reply(404, { error: say(ctx, 'That reminder is no longer here.') }) : reply(200, done);
546
+ } },
547
+ { method: 'POST', path: '/api/reminders/snooze', handler: async (ctx, { payload }) => {
548
+ const minutes = Number(payload?.minutes);
549
+ const until = iso(payload?.until) ?? (Number.isFinite(minutes) && minutes > 0 && minutes <= 60 * 24 * 30 ? new Date(Date.now() + minutes * 60000).toISOString() : null);
550
+ if (!until) return reply(400, { error: say(ctx, 'Say when.') });
551
+ const moved = await snoozeReminder(ctx.stateRoot, String(payload?.id ?? ''), until);
552
+ return moved.error ? reply(404, { error: say(ctx, 'That reminder is no longer here.') }) : reply(200, moved);
553
+ } },
554
+ // The history emptied: the done ones of this project, or of every project in Home.
555
+ { method: 'POST', path: '/api/reminders/clear-done', handler: async (ctx) => {
556
+ const cleared = await clearDone(ctx.stateRoot, ctx.roomId ?? null);
557
+ return reply(200, cleared);
558
+ } },
559
+ { method: 'POST', path: '/api/reminders/delete', handler: async (ctx, { payload }) => {
560
+ const gone = await deleteReminder(ctx.stateRoot, String(payload?.id ?? ''));
561
+ return gone.error ? reply(404, { error: say(ctx, 'That reminder is no longer here.') }) : reply(200, gone);
562
+ } },
563
+ ],
564
+ };
565
+
566
+ // THE TOOL SERVER (MCP over stdio, JSON-RPC 2.0), when an agent's turn runs this file with node:
567
+ // one tool, create_reminder. It only adds — it cannot read, change or delete the person's
568
+ // reminders, which stay theirs — and it writes the same file the page reads.
569
+ //
570
+ // Environment:
571
+ // PULSE_REMINDERS_STATE ~/.pulse, where reminders.json is kept
572
+ // PULSE_ROOM_ID the project's room id, kept on each reminder
573
+ // PULSE_PROJECT the project's name, for Home
574
+ // PULSE_REMINDER_HOUR the hour a day starts at for a reminder with no hour (Reminders' setting)
575
+ const SERVER_NAME = 'madre-reminders';
576
+ const SERVER_VERSION = '2.0.0';
577
+ const REMINDER_TOOL = {
578
+ name: 'create_reminder',
579
+ 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.',
580
+ 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'] },
581
+ };
582
+
583
+ // This file imports nothing of MADRE: the hour is written in the language the computer runs in.
584
+ export function localWhen(iso, language = undefined) {
585
+ const when = new Date(iso);
586
+ if (Number.isNaN(when.getTime())) return String(iso);
587
+ const locale = language === 'en' ? 'en-US' : language === 'es' ? 'es-MX' : undefined;
588
+ try {
589
+ return when.toLocaleString(locale, { weekday: 'long', day: 'numeric', month: 'long', hour: 'numeric', minute: '2-digit' });
590
+ } catch { return when.toString(); }
591
+ }
592
+
593
+ async function createReminder(args, env) {
594
+ const what = taskFromWords(String(args.what ?? '').trim());
595
+ if (!what) throw new Error('The reminder needs what to remember.');
596
+ const hour = Number(env.PULSE_REMINDER_HOUR) || 9;
597
+ const when = parseWhen(String(args.when ?? ''), new Date(), { hour }) ?? { due: tomorrowMorning(new Date(), hour), repeat: null };
598
+ 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' });
599
+ if (made.error) throw new Error('The reminder was not set.');
600
+ // The hour as this computer reads it (QA 1.1.0, NUE-29): handed only the ISO time, an agent told
601
+ // a person in Mexico City «a las 03:09 UTC» for a reminder due at 21:09 where they are.
602
+ const local = localWhen(made.reminder.due);
603
+ return `Reminder set: «${made.reminder.text}», due ${local} (this computer's local time; ${made.reminder.due} in UTC)${made.reminder.repeat ? `, repeating ${made.reminder.repeat}` : ''}. Tell the person when, in their words and in that local time, never in UTC.`;
604
+ }
605
+
606
+ export function handleRequest(message, { env = process.env } = {}) {
607
+ const reply = (result) => ({ jsonrpc: '2.0', id: message.id, result });
608
+ const fail = (code, text) => ({ jsonrpc: '2.0', id: message.id, error: { code, message: text } });
609
+ const tools = env.PULSE_REMINDERS_STATE ? [REMINDER_TOOL] : [];
610
+ switch (message.method) {
611
+ case 'initialize':
612
+ return Promise.resolve(reply({ protocolVersion: message.params?.protocolVersion ?? '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: SERVER_NAME, version: SERVER_VERSION } }));
613
+ case 'notifications/initialized':
614
+ case 'initialized':
615
+ return Promise.resolve(null);
616
+ case 'ping':
617
+ return Promise.resolve(reply({}));
618
+ case 'tools/list':
619
+ return Promise.resolve(reply({ tools }));
620
+ case 'tools/call': {
621
+ const { name, arguments: args = {} } = message.params ?? {};
622
+ if (!tools.some((tool) => tool.name === name)) return Promise.resolve(fail(-32602, `Unknown tool: ${name}`));
623
+ return createReminder(args, env)
624
+ .then((text) => reply({ content: [{ type: 'text', text }], isError: false }))
625
+ .catch((error) => reply({ content: [{ type: 'text', text: `Nothing was saved: ${error.message}` }], isError: true }));
626
+ }
627
+ default:
628
+ return Promise.resolve(message.id === undefined ? null : fail(-32601, `Method not found: ${message.method}`));
629
+ }
630
+ }
631
+
632
+ export function serve({ input = process.stdin, output = process.stdout, env = process.env } = {}) {
633
+ let buffer = '';
634
+ let pending = 0;
635
+ let ended = false;
636
+ const finish = () => { if (ended && pending === 0) process.exit(0); };
637
+ input.setEncoding('utf8');
638
+ input.on('data', (chunk) => {
639
+ buffer += chunk;
640
+ let index;
641
+ while ((index = buffer.indexOf('\n')) >= 0) {
642
+ const line = buffer.slice(0, index).trim();
643
+ buffer = buffer.slice(index + 1);
644
+ if (!line) continue;
645
+ let message;
646
+ try { message = JSON.parse(line); } catch { output.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } })}\n`); continue; }
647
+ pending += 1;
648
+ void handleRequest(message, { env })
649
+ .then((response) => { if (response) output.write(`${JSON.stringify(response)}\n`); })
650
+ .finally(() => { pending -= 1; finish(); });
651
+ }
652
+ });
653
+ input.on('end', () => { ended = true; finish(); });
654
+ }
655
+
656
+ // Both paths resolved before they are compared (WIN-004), as the other servers do.
657
+ const real = async (path) => (path ? realpath(path).catch(() => path) : null);
658
+ if (process.argv[1] && (await real(process.argv[1])) === (await real(SELF))) {
659
+ if (!process.env.PULSE_REMINDERS_STATE) {
660
+ process.stderr.write('PULSE_REMINDERS_STATE is required.\n');
661
+ process.exit(2);
662
+ }
663
+ serve();
664
+ }