@jossuealcala/madre 1.1.1 → 1.1.3

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 (108) hide show
  1. package/CHANGELOG.en.md +42 -1
  2. package/CHANGELOG.md +42 -1
  3. package/README.en.md +4 -4
  4. package/README.md +4 -4
  5. package/SECURITY.md +11 -6
  6. package/bin/madre.mjs +74 -11
  7. package/docs/REFERENCE.md +15 -8
  8. package/docs/SDK.md +8 -8
  9. package/docs/en/REFERENCE.md +12 -7
  10. package/docs/en/SDK.md +8 -8
  11. package/docs/en/training/README.md +1 -1
  12. package/docs/sdk/connector-module.mjs +1 -1
  13. package/docs/sdk/hello-module.mjs +1 -1
  14. package/docs/training/README.md +1 -1
  15. package/docs/training/train.sh +3 -0
  16. package/package.json +4 -2
  17. package/public/activity.js +9 -0
  18. package/public/app.js +990 -173
  19. package/public/attribution.js +9 -0
  20. package/public/brands.js +27 -13
  21. package/public/en.js +2 -3
  22. package/public/es.js +968 -258
  23. package/public/index.html +3 -0
  24. package/public/macroverso.js +24 -5
  25. package/public/manual-content.js +38 -8
  26. package/public/market-view.js +116 -9
  27. package/public/market.js +28 -2
  28. package/public/news-scenes.js +185 -0
  29. package/public/notices.js +66 -0
  30. package/public/power.js +1 -1
  31. package/public/resay.js +3 -0
  32. package/public/salas-mac.css +294 -22
  33. package/public/salas-mac.html +3 -0
  34. package/public/salas-mac.js +760 -38
  35. package/public/styles.css +393 -17
  36. package/public/tips.js +124 -0
  37. package/public/tour-chapters.js +75 -75
  38. package/public/tour.js +36 -8
  39. package/public/troubleshooting.js +215 -22
  40. package/public/welcome-scene.js +358 -0
  41. package/public/welcome.js +523 -254
  42. package/src/adapters/gemini-rest.mjs +236 -0
  43. package/src/adapters/gemini.mjs +9 -7
  44. package/src/adapters/grok.mjs +288 -0
  45. package/src/adapters/process.mjs +14 -3
  46. package/src/auth-probe.mjs +32 -0
  47. package/src/bridge/policy.mjs +1 -1
  48. package/src/capabilities.mjs +30 -0
  49. package/src/checkpoint.mjs +115 -1
  50. package/src/codex-route.mjs +113 -0
  51. package/src/credentials.mjs +46 -8
  52. package/src/dataset.mjs +21 -8
  53. package/src/embeddings.mjs +2 -2
  54. package/src/event-store.mjs +10 -2
  55. package/src/ficha.mjs +142 -0
  56. package/src/file-ops.mjs +9 -3
  57. package/src/files.mjs +36 -2
  58. package/src/github.mjs +5 -3
  59. package/src/lease.mjs +5 -0
  60. package/src/market-check.mjs +1 -1
  61. package/src/market-remote.mjs +170 -3
  62. package/src/mcp/image-server.mjs +1 -1
  63. package/src/mcp/memory-server.mjs +22 -3
  64. package/src/mcp/proxy.mjs +31 -8
  65. package/src/memory-tools.mjs +12 -2
  66. package/src/memory.mjs +44 -3
  67. package/src/models.mjs +21 -3
  68. package/src/modules/ahp.mjs +8 -3
  69. package/src/modules/bishop-exam.mjs +41 -12
  70. package/src/modules/bishop.mjs +2 -2
  71. package/src/modules/check-alone.mjs +25 -0
  72. package/src/modules/choices.mjs +12 -10
  73. package/src/modules/fetch-alone.mjs +7 -0
  74. package/src/modules/helpers.mjs +23 -5
  75. package/src/modules/image-studio.mjs +13 -27
  76. package/src/modules/index.mjs +88 -11
  77. package/src/modules/isolated.mjs +160 -0
  78. package/src/modules/ollama.mjs +35 -6
  79. package/src/modules/playwright.mjs +46 -17
  80. package/src/modules/run-alone.mjs +122 -0
  81. package/src/modules/runs.mjs +11 -8
  82. package/src/modules/sdk.mjs +4 -2
  83. package/src/mother.mjs +6 -1
  84. package/src/notices-key.mjs +8 -0
  85. package/src/notices.mjs +185 -0
  86. package/src/ollama.mjs +57 -15
  87. package/src/outbound.mjs +56 -11
  88. package/src/room/archivist.mjs +36 -5
  89. package/src/room/busy.mjs +16 -0
  90. package/src/room/context.mjs +6 -3
  91. package/src/room/control.mjs +36 -6
  92. package/src/room/copilot.mjs +22 -28
  93. package/src/room/guard.mjs +32 -2
  94. package/src/room/prompt.mjs +32 -5
  95. package/src/room/vectors.mjs +7 -1
  96. package/src/room.mjs +98 -32
  97. package/src/router.mjs +1 -1
  98. package/src/runs.mjs +39 -0
  99. package/src/runtime-detection.mjs +46 -6
  100. package/src/salas.mjs +253 -15
  101. package/src/server.mjs +686 -87
  102. package/src/service.mjs +116 -0
  103. package/src/setup-trouble.mjs +20 -1
  104. package/src/skill-check.mjs +269 -0
  105. package/src/skills-import.mjs +128 -0
  106. package/src/skills.mjs +492 -0
  107. package/src/tour.mjs +15 -4
  108. package/src/whats-new.mjs +71 -0
@@ -0,0 +1,122 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // One call into a human module. The parent starts this file with Node's permission model:
4
+ // the module can read its own file and MADRE's SDK, but cannot read other files, write or spawn.
5
+ // The only way back into MADRE is a named ctx method answered by the parent.
6
+ import { createInterface } from 'node:readline';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { setLanguage, t } from '../i18n.mjs';
9
+ import { defineModule } from './sdk.mjs';
10
+
11
+ const wire = (value) => process.stdout.write(`\n${JSON.stringify({ madreModule: true, ...value })}\n`);
12
+ const pending = new Map();
13
+ let sequence = 0;
14
+ const ask = (method, args = []) => new Promise((resolve, reject) => {
15
+ const id = ++sequence;
16
+ pending.set(id, { resolve, reject });
17
+ wire({ type: 'ctx', id, method, args });
18
+ });
19
+
20
+ function context(input = {}) {
21
+ const ctx = {
22
+ projectRoot: input.projectRoot,
23
+ stateRoot: input.stateRoot,
24
+ roomId: input.roomId,
25
+ chat: input.chat,
26
+ config: input.config ?? {},
27
+ settings: input.settings ?? {},
28
+ env: {},
29
+ agents: input.agents ?? [],
30
+ language: input.language ?? 'en',
31
+ t,
32
+ readConfig: () => ask('readConfig'),
33
+ updateConfig: (patch) => ask('updateConfig', [patch]),
34
+ record: (type, payload) => ask('record', [type, payload]),
35
+ vault: {
36
+ get: (name) => ask('vault.get', [name]),
37
+ held: () => ask('vault.held'),
38
+ keep: (name, value) => ask('vault.keep', [name, value]),
39
+ forget: (name) => ask('vault.forget', [name]),
40
+ },
41
+ services: {
42
+ history: (range) => ask('services.history', [range]),
43
+ ollama: {
44
+ state: () => input.ollamaState ?? null,
45
+ generate: (request) => ask('services.ollama.generate', [request]),
46
+ },
47
+ },
48
+ room: input.hasRoom ? {
49
+ capabilities: () => input.capabilities ?? null,
50
+ runningTurn: (id) => id === input.turnId ? input.runningTurn ?? null : null,
51
+ record: (type, payload) => ask('room.record', [type, payload]),
52
+ } : null,
53
+ };
54
+ return ctx;
55
+ }
56
+
57
+ async function invoke(message) {
58
+ setLanguage(message.ctx?.language ?? 'en');
59
+ // The parent owns the log file. A hook may reach the network only when its module declared
60
+ // a destination; every fetch it makes is reported without a body, header or query value.
61
+ const fetchImpl = globalThis.fetch;
62
+ globalThis.fetch = async (resource, init = {}) => {
63
+ const url = typeof resource === 'string' ? resource : (resource?.url ?? String(resource));
64
+ const method = init?.method ?? resource?.method ?? 'GET';
65
+ const bytes = typeof init?.body === 'string' ? Buffer.byteLength(init.body) : null;
66
+ const started = Date.now();
67
+ try {
68
+ const response = await fetchImpl(resource, init);
69
+ await ask('outbound.record', [{ url, method, bytes, status: response?.status ?? null, ok: Boolean(response?.ok), ms: Date.now() - started }]).catch(() => null);
70
+ return response;
71
+ } catch (error) {
72
+ await ask('outbound.record', [{ url, method, bytes, ok: false, ms: Date.now() - started, error: error?.code ?? error?.name ?? 'failed' }]).catch(() => null);
73
+ throw error;
74
+ }
75
+ };
76
+ const file = process.argv[2];
77
+ const loaded = await import(pathToFileURL(file).href);
78
+ let spec = loaded.default ?? loaded.module ?? null;
79
+ if (typeof spec === 'function') spec = await spec({ defineModule });
80
+ if (!spec || typeof spec !== 'object') throw new Error('the default export must be a module spec object');
81
+ const module = typeof spec.describe === 'function' ? spec : defineModule(spec);
82
+ if (module.id !== message.expectedId) throw new Error('the module changed its id after it was checked');
83
+ const ctx = context(message.ctx);
84
+ const args = message.args ?? [];
85
+ if (message.operation === 'route') {
86
+ const route = module.routes?.[message.index];
87
+ if (typeof route?.handler !== 'function') throw new Error('the route has no handler');
88
+ const request = args[0] ?? {};
89
+ return route.handler(ctx, { ...request, request: { method: request.method, headers: request.headers }, url: request.url ? new URL(request.url) : null });
90
+ }
91
+ if (message.operation === 'slash' || message.operation === 'available') {
92
+ const command = module.slash?.[message.index];
93
+ const fn = command?.[message.operation === 'slash' ? 'execute' : 'available'];
94
+ if (typeof fn !== 'function') throw new Error('the command has no such hook');
95
+ return fn(ctx, ...args);
96
+ }
97
+ const fn = module[message.operation];
98
+ if (typeof fn !== 'function') throw new Error(`the module has no ${message.operation} hook`);
99
+ if (['detect', 'preflight', 'installCommand'].includes(message.operation)) return fn.call(module, ...args);
100
+ if (message.operation === 'describe') return fn.call({ ...module, external: true, file }, ctx);
101
+ return fn.call(module, ctx, ...args);
102
+ }
103
+
104
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
105
+ lines.on('line', (line) => {
106
+ let message;
107
+ try { message = JSON.parse(line); } catch { return; }
108
+ if (!message?.madreModule) return;
109
+ if (message.type === 'ctxResult') {
110
+ const waiting = pending.get(message.id);
111
+ if (!waiting) return;
112
+ pending.delete(message.id);
113
+ if (message.ok) waiting.resolve(message.value);
114
+ else waiting.reject(new Error(message.error ?? 'MADRE refused the call'));
115
+ return;
116
+ }
117
+ if (message.type !== 'invoke') return;
118
+ void invoke(message).then(
119
+ (value) => wire({ type: 'done', ok: true, value }),
120
+ (error) => wire({ type: 'done', ok: false, error: String(error?.message ?? error), code: error?.code ?? null }),
121
+ ).finally(() => { lines.close(); process.stdin.pause(); });
122
+ });
@@ -12,8 +12,9 @@
12
12
  // command sends off this machine does not come back with UNDO, and the button says what it runs
13
13
  // before it is pressed.
14
14
  //
15
- // It has a switch because it is not free: the instruction that teaches the block rides in every
16
- // prompt below AIRLOCK while this is on, measured in the economy as `runs`.
15
+ // Always on, as image generation is (2026-11-06, the author): asking for a command is part of how
16
+ // an agent works in MADRE. The instruction still rides in every prompt below AIRLOCK, measured in
17
+ // the economy as `runs`.
17
18
 
18
19
  import { defineModule } from './sdk.mjs';
19
20
  import { t } from '../i18n.mjs';
@@ -24,13 +25,15 @@ export default defineModule({
24
25
  name: 'Commands',
25
26
  vendor: 'MADRE',
26
27
  version: '1.0.0',
27
- summary: 'Lets an agent ask you to run a command it cannot run in its mode (tests, a build, a linter). Each command is a button: nothing runs until you press it, it runs from the project root with no shell, a restore point is taken first, and when it has run the output goes back to the agent that asked, which goes on. Costs about 300 tokens of instruction per turn below FULL ACCESS while it is on.',
28
- creates: ['nothing in the project', 'a switch in ~/.pulse/config.json'],
29
- async status(ctx) {
28
+ summary: 'Lets an agent ask you to run a command it cannot run in its mode (tests, a build, a linter). Each command is a button: nothing runs until you press it, it runs from the project root with no shell, a restore point is taken first, and when it has run the output goes back to the agent that asked, which goes on. Always on: about 300 tokens of instruction per turn below FULL ACCESS.',
29
+ creates: ['nothing in the project'],
30
+ card: 'fixed',
31
+ async status() {
30
32
  return {
31
- status: { installed: Boolean(ctx.settings.enabled), detail: ctx.settings.enabled ? t('on · agents may ask you to run commands') : t('off · agents describe the command in prose') },
32
- install: { display: ctx.settings.enabled ? 'stop offering commands' : 'let agents ask for commands', platforms: [] },
33
+ status: { installed: true, detail: t('on · agents may ask you to run commands') },
34
+ install: { display: 'always on', platforms: [] },
35
+ fixed: true,
33
36
  };
34
37
  },
35
- async onToggle(ctx, enabled) { ctx.room.setRuns(enabled); return null; },
38
+ async toggle() { return { status: 405, body: { error: 'Commands has no switch: it is always on.' } }; },
36
39
  });
@@ -202,7 +202,9 @@ export function defineModule(spec) {
202
202
  };
203
203
  // A project reads its own word on `enabled` when it said one (module-scope.mjs).
204
204
  const settingsFrom = (config, roomId = null) => ({ ...defaults, ...settingsIn(config?.modules?.[configKey] ?? {}, roomId) });
205
- const mine = (ctx, settings) => ({ ...ctx, settings, vault: vaultFor(spec.id, ctx.stateRoot) });
205
+ // A module running in a separate process receives a mediated vault. Never replace it with
206
+ // direct filesystem access: only the parent may open its credential file.
207
+ const mine = (ctx, settings) => ({ ...ctx, settings, vault: ctx.vault ?? vaultFor(spec.id, ctx.stateRoot) });
206
208
  const scopeHere = (ctx) => {
207
209
  const block = ctx.config?.modules?.[configKey] ?? {};
208
210
  const own = ctx.roomId ? roomsOf(block)[ctx.roomId] : undefined;
@@ -260,7 +262,7 @@ export function defineModule(spec) {
260
262
  canUpdate: Boolean(spec.updatePlan),
261
263
  controls: base.controls.map((control) => ({ ...control, value: settings[control.key] ?? null })),
262
264
  // What is in the vault for this module: names and lengths, never values.
263
- ...(base.secrets.length ? { held: await vaultSummary(ctx.stateRoot, spec.id).catch(() => []) } : {}),
265
+ ...(base.secrets.length ? { held: await (ctx.vault?.held?.() ?? vaultSummary(ctx.stateRoot, spec.id)).catch(() => []) } : {}),
264
266
  ships: this.external ? null : await madreRelease(),
265
267
  runs,
266
268
  status: own.status ?? { installed, detail: own.detail ?? (installed ? 'on' : 'off') },
package/src/mother.mjs CHANGED
@@ -158,12 +158,17 @@ export class MotherChannel {
158
158
 
159
159
  lockedFor() { return Math.max(0, this.#lockUntil - Date.now()); }
160
160
 
161
- // What the children read: the recent alerts, decoded, newest last.
161
+ // What the children read: the recent alerts, decoded, newest last. An intrusion alert travels
162
+ // only while the archive is sealed (2026-11-01, external review #21): it tells every agent to
163
+ // refuse any request to delete or rewrite a memory, and for a day after a ten-minute seal that
164
+ // turned down the human's own requests. A tampered seal is still said for the day.
162
165
  recent({ withinMs = 24 * 3600 * 1000, limit = 3 } = {}) {
163
166
  const since = Date.now() - withinMs;
167
+ const sealed = this.lockedFor() > 0;
164
168
  const out = [];
165
169
  for (const alert of this.#alerts) {
166
170
  if (new Date(alert.at).getTime() < since) continue;
171
+ if (alert.kind === 'intrusion' && !sealed) continue;
167
172
  try { out.push({ ...alert, text: decodeMessage(this.#seal, alert.code) }); } catch { /* sealed under an older key */ }
168
173
  }
169
174
  return out.slice(-limit);
@@ -0,0 +1,8 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // The public half of the key of the author's notices (scripts/notices-key.mjs, Q-11). Each notice
4
+ // madre.run serves is signed with the private half, which lives only on the author's computer; a
5
+ // notice this key does not verify is never shown (src/notices.mjs). Null: no notice is ever shown.
6
+ export const NOTICES_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
7
+ MCowBQYDK2VwAyEAPrOpPloPi1CDsCGRjnZNNMEH0AaD1c3sRsLjuXt9FVQ=
8
+ -----END PUBLIC KEY-----`;
@@ -0,0 +1,185 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // THE AUTHOR'S NOTICES (Q-11, 2026-11-06). What the author writes from the MADRE run from source
4
+ // («a version with a security fix is out», «if you use WSL, update») reaches every copy that is on,
5
+ // with or without the anonymous diagnostics, and without «Look for new versions».
6
+ //
7
+ // A notice is signed on the author's computer, with a key only the author holds (scripts/
8
+ // notices-key.mjs); madre.run keeps and serves it (functions/api/avisos.js of the landing) but cannot
9
+ // make one up or change a word of it: a notice whose signature the key in src/notices-key.mjs does
10
+ // not verify is never shown. The worst madre.run can do is not serve one.
11
+ //
12
+ // What a copy asks: GET madre.run/api/avisos, with nothing about the person, not even its version.
13
+ // It decides by itself which notices are for it (its version, its system), and remembers which ones
14
+ // it showed. At most every 15 minutes per computer, however many projects are open.
15
+ //
16
+ // Levels: «info» and «important» can be turned off (Settings › Version); «security» always shows.
17
+
18
+ import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
19
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
20
+ import { join } from 'node:path';
21
+ import { NOTICES_PUBLIC_KEY } from './notices-key.mjs';
22
+ import { compareVersions } from './updates.mjs';
23
+
24
+ export const NOTICES_URL = 'https://madre.run/api/avisos';
25
+ export const noticesUrl = (env = process.env) => env.PULSE_NOTICES_URL || NOTICES_URL;
26
+ export const noticesOn = (env = process.env) => env.PULSE_NOTICES !== '0';
27
+ export const LEVELS = ['info', 'important', 'security'];
28
+ export const SYSTEMS = ['darwin', 'linux', 'win32', 'wsl'];
29
+ const ID = /^[a-z0-9][a-z0-9-]{2,39}$/;
30
+ const VERSION = /^\d{1,3}\.\d{1,3}\.\d{1,4}$/;
31
+ const SIG = /^[A-Za-z0-9+/]{40,120}={0,2}$/;
32
+ export const TITLE_MAX = 80;
33
+ export const BODY_MAX = 400;
34
+ const LONGEST_MS = 90 * 86_400_000;
35
+ const FRESH_MS = 15 * 60_000;
36
+ const TIMEOUT_MS = 8000;
37
+ const MAX_FEED = 64 * 1024;
38
+
39
+ const folder = (stateRoot) => join(stateRoot, 'avisos');
40
+ const readJson = (file) => readFile(file, 'utf8').then((raw) => JSON.parse(raw)).catch(() => null);
41
+ async function writeAtomic(file, data) {
42
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
43
+ await writeFile(temp, data);
44
+ await rename(temp, file);
45
+ }
46
+
47
+ // Only text, short, in both languages; a link only to madre.run. Anything else is not a notice.
48
+ const words = (value, max) => (typeof value === 'string' ? value.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').trim() : '');
49
+ function pair(value, max) {
50
+ if (!value || typeof value !== 'object') return null;
51
+ const es = words(value.es, max);
52
+ const en = words(value.en, max);
53
+ if (!es || !en || es.length > max || en.length > max) return null;
54
+ return { es, en };
55
+ }
56
+ export function readNotice(raw) {
57
+ if (!raw || typeof raw !== 'object') return null;
58
+ const id = typeof raw.id === 'string' ? raw.id : '';
59
+ if (!ID.test(id) || !LEVELS.includes(raw.level)) return null;
60
+ const title = pair(raw.title, TITLE_MAX);
61
+ const body = pair(raw.body, BODY_MAX);
62
+ if (!title || !body) return null;
63
+ const from = Date.parse(raw.from);
64
+ const until = Date.parse(raw.until);
65
+ if (!Number.isFinite(from) || !Number.isFinite(until) || until <= from || until - from > LONGEST_MS) return null;
66
+ let link = null;
67
+ if (raw.link !== undefined && raw.link !== null && raw.link !== '') {
68
+ try {
69
+ const url = new URL(String(raw.link));
70
+ if (url.protocol !== 'https:' || url.hostname !== 'madre.run' || url.username || url.password) return null;
71
+ link = url.href;
72
+ } catch { return null; }
73
+ }
74
+ const to = raw.to && typeof raw.to === 'object' ? raw.to : {};
75
+ const min = to.min ? String(to.min) : null;
76
+ const max = to.max ? String(to.max) : null;
77
+ if ((min && !VERSION.test(min)) || (max && !VERSION.test(max))) return null;
78
+ const os = Array.isArray(to.os) ? to.os.filter((one) => SYSTEMS.includes(one)) : [];
79
+ if (Array.isArray(to.os) && os.length !== to.os.length) return null;
80
+ return { id, level: raw.level, title, body, link, to: { min, max, os }, from: new Date(from).toISOString(), until: new Date(until).toISOString() };
81
+ }
82
+
83
+ // The exact bytes signed: the notice read as above, its keys in this order, nothing else. A field
84
+ // added on the way (or one taken out) changes the bytes, and the signature no longer holds.
85
+ export const noticeBytes = (notice) => Buffer.from(JSON.stringify({
86
+ id: notice.id, level: notice.level, title: { es: notice.title.es, en: notice.title.en }, body: { es: notice.body.es, en: notice.body.en },
87
+ link: notice.link ?? null, to: { min: notice.to?.min ?? null, max: notice.to?.max ?? null, os: [...(notice.to?.os ?? [])] }, from: notice.from, until: notice.until,
88
+ }));
89
+ const retireBytes = (id) => Buffer.from(`madre-notice-retire:${id}`);
90
+
91
+ function checks(bytes, signature, publicKey) {
92
+ if (!publicKey || typeof signature !== 'string' || !SIG.test(signature)) return false;
93
+ try { return verify(null, bytes, createPublicKey(publicKey), Buffer.from(signature, 'base64')); } catch { return false; }
94
+ }
95
+ // One served entry, checked: `{ notice, sig }`, read and verified, or null.
96
+ export function verifiedNotice(entry, publicKey = NOTICES_PUBLIC_KEY) {
97
+ const notice = readNotice(entry?.notice);
98
+ if (!notice || !checks(noticeBytes(notice), entry.sig, publicKey)) return null;
99
+ return notice;
100
+ }
101
+ export const verifiedRetire = (entry, publicKey = NOTICES_PUBLIC_KEY) => (ID.test(entry?.id ?? '') && checks(retireBytes(entry.id), entry.sig, publicKey) ? entry.id : null);
102
+
103
+ // On the author's computer only: the signatures madre.run will keep.
104
+ export function signNotice(raw, privateKeyPem) {
105
+ const notice = readNotice(raw);
106
+ if (!notice) throw new Error('That is not a notice MADRE would show: check the words, the dates and the link.');
107
+ return { notice, sig: sign(null, noticeBytes(notice), createPrivateKey(privateKeyPem)).toString('base64') };
108
+ }
109
+ export const signRetire = (id, privateKeyPem) => {
110
+ if (!ID.test(String(id))) throw new Error('No such notice.');
111
+ return { id, sig: sign(null, retireBytes(id), createPrivateKey(privateKeyPem)).toString('base64') };
112
+ };
113
+
114
+ // Whether a notice is for this copy, now.
115
+ export function appliesTo(notice, { version, platform = process.platform, wsl = false, now = Date.now() }) {
116
+ if (now < Date.parse(notice.from) || now >= Date.parse(notice.until)) return false;
117
+ if (notice.to.min && compareVersions(version, notice.to.min) < 0) return false;
118
+ if (notice.to.max && compareVersions(version, notice.to.max) > 0) return false;
119
+ if (notice.to.os.length) {
120
+ const here = wsl ? 'wsl' : platform;
121
+ if (!notice.to.os.includes(here)) return false;
122
+ }
123
+ return true;
124
+ }
125
+
126
+ // The feed as madre.run serves it, checked one by one: the notices whose signatures hold, minus the
127
+ // ones the author retired with a signature of their own.
128
+ export function readFeed(data, publicKey = NOTICES_PUBLIC_KEY) {
129
+ const retired = new Set((Array.isArray(data?.retired) ? data.retired : []).map((entry) => verifiedRetire(entry, publicKey)).filter(Boolean));
130
+ const kept = [];
131
+ for (const entry of Array.isArray(data?.notices) ? data.notices.slice(0, 50) : []) {
132
+ const notice = verifiedNotice(entry, publicKey);
133
+ if (notice && !retired.has(notice.id) && !kept.some((one) => one.notice.id === notice.id)) kept.push({ notice: entry.notice, sig: entry.sig });
134
+ }
135
+ return { entries: kept, retired: [...retired] };
136
+ }
137
+
138
+ // Asked of madre.run at most every 15 minutes per computer; what was verified is kept, so a copy
139
+ // offline still shows what it knew, until it expires.
140
+ export async function refreshNotices({ stateRoot, env = process.env, fetchImpl = globalThis.fetch, publicKey = NOTICES_PUBLIC_KEY, force = false, now = Date.now } = {}) {
141
+ if (!noticesOn(env) || !publicKey) return { fresh: false, off: true };
142
+ const dir = folder(stateRoot);
143
+ const state = (await readJson(join(dir, 'state.json'))) ?? {};
144
+ if (!force && state.checkedAt && now() - Date.parse(state.checkedAt) < FRESH_MS) return { fresh: false };
145
+ await mkdir(dir, { recursive: true }).catch(() => {});
146
+ // Said as checked before asking: another process of this computer that asks meanwhile waits its turn.
147
+ await writeAtomic(join(dir, 'state.json'), JSON.stringify({ ...state, checkedAt: new Date(now()).toISOString() }, null, 2)).catch(() => {});
148
+ try {
149
+ const answer = await fetchImpl(noticesUrl(env), { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
150
+ if (!answer.ok) throw new Error(`HTTP ${answer.status}`);
151
+ const text = await answer.text();
152
+ if (text.length > MAX_FEED) throw new Error('too large');
153
+ const feed = readFeed(JSON.parse(text), publicKey);
154
+ await writeAtomic(join(dir, 'kept.json'), JSON.stringify(feed, null, 2));
155
+ await writeAtomic(join(dir, 'state.json'), JSON.stringify({ checkedAt: new Date(now()).toISOString(), count: feed.entries.length }, null, 2));
156
+ return { fresh: true, count: feed.entries.length };
157
+ } catch (error) {
158
+ await writeAtomic(join(dir, 'state.json'), JSON.stringify({ checkedAt: new Date(now()).toISOString(), failed: String(error?.name === 'TimeoutError' ? 'timeout' : error?.message ?? error).slice(0, 120) }, null, 2)).catch(() => {});
159
+ return { fresh: false, error: true };
160
+ }
161
+ }
162
+
163
+ // What this copy shows now: kept, checked again, for it, and on unless it is a security notice.
164
+ export async function currentNotices({ stateRoot, version, platform = process.platform, wsl = false, enabled = true, publicKey = NOTICES_PUBLIC_KEY, now = Date.now() } = {}) {
165
+ const kept = (await readJson(join(folder(stateRoot), 'kept.json'))) ?? {};
166
+ const seen = new Set((await readJson(join(folder(stateRoot), 'seen.json'))) ?? []);
167
+ const { entries } = readFeed({ notices: kept.entries, retired: [] }, publicKey);
168
+ const retired = new Set(Array.isArray(kept.retired) ? kept.retired : []);
169
+ return entries
170
+ .map((entry) => readNotice(entry.notice))
171
+ .filter((notice) => notice && !retired.has(notice.id) && appliesTo(notice, { version, platform, wsl, now }) && (enabled || notice.level === 'security'))
172
+ .sort((a, b) => LEVELS.indexOf(b.level) - LEVELS.indexOf(a.level) || b.from.localeCompare(a.from))
173
+ .map((notice) => ({ ...notice, seen: seen.has(notice.id) }));
174
+ }
175
+
176
+ // «Got it»: this computer does not show it again.
177
+ export async function noticeSeen(stateRoot, id) {
178
+ if (!ID.test(String(id))) return false;
179
+ const file = join(folder(stateRoot), 'seen.json');
180
+ const seen = new Set((await readJson(file)) ?? []);
181
+ seen.add(id);
182
+ await mkdir(folder(stateRoot), { recursive: true });
183
+ await writeAtomic(file, JSON.stringify([...seen].slice(-200)));
184
+ return true;
185
+ }
package/src/ollama.mjs CHANGED
@@ -5,6 +5,8 @@
5
5
  // so remembering costs no tokens elsewhere and nothing leaves. Nothing here is
6
6
  // required: without Ollama every path falls back to what it did before.
7
7
 
8
+ import http from 'node:http';
9
+ import https from 'node:https';
8
10
  import { t } from './i18n.mjs';
9
11
 
10
12
  export const DEFAULT_OLLAMA_HOST = 'http://127.0.0.1:11434';
@@ -95,6 +97,30 @@ export function ollamaEmbedder({ host = ollamaHost(), model, fetchImpl = globalT
95
97
  };
96
98
  }
97
99
 
100
+ // Node's fetch gives up on an answer whose first byte has not come in 300 s (undici's own headers
101
+ // timeout), whatever the turn allowed, and Ollama sends nothing until the model has read the whole
102
+ // question — streaming or not. On a server without a graphics card that is minutes: the Coordinator
103
+ // on Carlos's server failed with a bare «fetch failed» at 303 s of the 10 000 its turn had (L-7,
104
+ // 2026-11-04). node:http has no such limit, so a local answer waits as long as the turn says.
105
+ // Shaped like fetch for what this file reads: ok, status, text(), json().
106
+ export function patientFetch(url, { method = 'GET', headers = {}, body = null, signal = null } = {}) {
107
+ return new Promise((resolve, reject) => {
108
+ const failed = (error) => reject(signal?.aborted ? signal.reason : error);
109
+ const target = new URL(url);
110
+ const request = (target.protocol === 'https:' ? https : http).request(target, { method, headers, ...(signal ? { signal } : {}) }, (response) => {
111
+ const chunks = [];
112
+ response.on('data', (chunk) => chunks.push(chunk));
113
+ response.on('error', failed);
114
+ response.on('end', () => {
115
+ const text = Buffer.concat(chunks).toString('utf8');
116
+ resolve({ ok: response.statusCode >= 200 && response.statusCode < 300, status: response.statusCode, text: async () => text, json: async () => JSON.parse(text) });
117
+ });
118
+ });
119
+ request.on('error', failed);
120
+ request.end(body ?? undefined);
121
+ });
122
+ }
123
+
98
124
  // One answer from a local model. `json: true` asks Ollama for a JSON object.
99
125
  export async function ollamaGenerate({ host = ollamaHost(), model, prompt, system = null, json = false, fetchImpl = globalThis.fetch, timeoutMs = 180000, temperature = 0.2, numCtx = DEFAULT_NUM_CTX, signal = null } = {}) {
100
126
  const started = Date.now();
@@ -102,7 +128,14 @@ export async function ollamaGenerate({ host = ollamaHost(), model, prompt, syste
102
128
  // A model that takes longer than the turn allows says so in the room's words, as any agent does:
103
129
  // the bare «The operation was aborted due to timeout» reached the person, in English.
104
130
  const response = await fetchImpl(`${host}/api/chat`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ model, messages, stream: false, options: { temperature, num_ctx: numCtx }, ...(json ? { format: 'json' } : {}) }), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs) })
105
- .catch((error) => { throw error?.name === 'TimeoutError' ? new Error(t('{label} did not respond before the timeout ({seconds}s).', { label: `Ollama (${model})`, seconds: Math.round(timeoutMs / 1000) })) : error; });
131
+ .catch((error) => {
132
+ if (error?.name === 'TimeoutError') throw Object.assign(new Error(t('{label} did not respond before the timeout ({seconds}s).', { label: `Ollama (${model})`, seconds: Math.round(timeoutMs / 1000) })), { code: 'ETIMEDOUT' });
133
+ if (error?.name === 'AbortError') throw error;
134
+ // Ollama stopped or closed the connection mid-answer: said in the room's words, with the code
135
+ // kept so the archivist still reads it as passing.
136
+ const code = error?.cause?.code ?? error?.code ?? error?.name ?? 'failed';
137
+ throw Object.assign(new Error(t('{label} closed the connection before answering ({code}). Check in Settings › Local AI that Ollama is still running.', { label: `Ollama (${model})`, code })), { code, cause: error });
138
+ });
106
139
  if (!response.ok) throw new Error(`Ollama HTTP ${response.status}: ${(await response.text().catch(() => '')).slice(0, 200)}`);
107
140
  const payload = await response.json();
108
141
  const inputTokens = payload.prompt_eval_count ?? 0;
@@ -130,21 +163,30 @@ export async function pullModel({ host = ollamaHost(), model, fetchImpl = global
130
163
  const decoder = new TextDecoder();
131
164
  let buffer = '';
132
165
  let lastStatus = '';
133
- for (;;) {
134
- const { value, done } = await reader.read();
135
- if (done) break;
136
- buffer += decoder.decode(value, { stream: true });
137
- let index;
138
- while ((index = buffer.indexOf('\n')) >= 0) {
139
- const line = buffer.slice(0, index).trim();
140
- buffer = buffer.slice(index + 1);
141
- if (!line) continue;
142
- let event;
143
- try { event = JSON.parse(line); } catch { continue; }
144
- if (event.error) throw new Error(event.error);
145
- const status = event.total ? `${event.status} · ${Math.round((event.completed ?? 0) / event.total * 100)}%` : event.status;
146
- if (status && status !== lastStatus) { lastStatus = status; onLine(status); }
166
+ try {
167
+ for (;;) {
168
+ const { value, done } = await reader.read();
169
+ if (done) break;
170
+ buffer += decoder.decode(value, { stream: true });
171
+ let index;
172
+ while ((index = buffer.indexOf('\n')) >= 0) {
173
+ const line = buffer.slice(0, index).trim();
174
+ buffer = buffer.slice(index + 1);
175
+ if (!line) continue;
176
+ let event;
177
+ try { event = JSON.parse(line); } catch { continue; }
178
+ if (event.error) throw new Error(event.error);
179
+ const status = event.total ? `${event.status} · ${Math.round((event.completed ?? 0) / event.total * 100)}%` : event.status;
180
+ if (status && status !== lastStatus) { lastStatus = status; onLine(status); }
181
+ }
182
+ }
183
+ } catch (error) {
184
+ if (signal?.aborted) throw error;
185
+ // Ollama dropped or closed the connection mid-download (D-21, undici's TypeError: terminated / UND_ERR_SOCKET).
186
+ if (error?.message === 'terminated' || error?.cause?.code === 'UND_ERR_SOCKET' || /terminated|other side closed/i.test(error?.message ?? '')) {
187
+ throw Object.assign(new Error(t('Ollama closed the connection while downloading {model}. Check that Ollama is still running and try again; what already arrived stays.', { model })), { code: 'ECONNRESET', trouble: 'ollama-closed', cause: error });
147
188
  }
189
+ throw error;
148
190
  }
149
191
  return { model };
150
192
  }
package/src/outbound.mjs CHANGED
@@ -14,10 +14,10 @@
14
14
  // there, what puts it on and where you turn it off. It is written by hand because it says what a
15
15
  // request MEANS, and no wrapper can know that.
16
16
  //
17
- // The log is the check on the declaration. Every fetch the room's process makes goes through one
18
- // wrapper — MADRE's own calls and any a module makes, because a module installed tomorrow runs
19
- // inside this process and cannot opt out of it — and lands in a line saying where it went and
20
- // when. An address nobody declared shows up as one nobody declared, which is the whole point.
17
+ // The log is the check on the declaration. The room wraps its fetch calls; an installed module's
18
+ // separate process reports its fetch calls through the restricted bridge, and its one-file MCP
19
+ // server installs the same wrapper. Calls made through other protocols or an agent CLI do not
20
+ // pass through this wrapper. An address nobody declared shows up as one nobody declared.
21
21
  //
22
22
  // What is never recorded: bodies, headers, and the values of query parameters. The names stay.
23
23
  // The Gemini embedding endpoint takes the key in the URL, and a log of what left this machine
@@ -65,6 +65,15 @@ export const DESTINATIONS = [
65
65
  where: 'Settings › Agents › Gemini · without a key it is never asked',
66
66
  inside: true,
67
67
  },
68
+ {
69
+ // Gemini without its CLI (adapters/gemini-rest.mjs): MADRE's own process carries the turn, so it
70
+ // is declared here and not left to `crew`. The key travels in a header, never in the address.
71
+ id: 'gemini-answer', host: 'generativelanguage.googleapis.com', match: (url) => /:streamGenerateContent$/.test(url.pathname), to: 'Google · Gemini, through its API',
72
+ what: 'The briefing — the document above, your question, the memories it summoned and the transcript it carries — with your Gemini API key, to be answered by the model you chose.',
73
+ when: 'every turn you send to @gemini while Gemini answers through its API (a Gemini key and no Gemini CLI)',
74
+ where: 'you choose it every time you send a turn to @gemini; installing the Gemini CLI hands its turns back to the CLI',
75
+ inside: true,
76
+ },
68
77
  {
69
78
  id: 'image', host: 'generativelanguage.googleapis.com', match: (url) => /generateContent/.test(url.pathname), to: 'Google · Gemini image model',
70
79
  what: 'The prompt an agent wrote for an image.',
@@ -96,6 +105,16 @@ export const DESTINATIONS = [
96
105
  where: 'Always on: it is how the author knows how many people use MADRE',
97
106
  inside: true,
98
107
  },
108
+ {
109
+ // The author's notices (Q-11, src/notices.mjs): asked of madre.run with nothing about the person.
110
+ // Whatever the diagnostics say. In the author's own copy, the same address takes the notices the
111
+ // author writes, already signed on this computer.
112
+ id: 'notices', host: 'madre.run', match: (url) => url.pathname === '/api/avisos', to: 'madre.run · notices from MADRE\'s author',
113
+ what: 'Nothing about you: it asks for the notices MADRE\'s author wrote for every copy, not even with this copy\'s version. Each one is checked against the author\'s signature before it shows.',
114
+ when: 'when MADRE opens, and at most every 15 minutes while it is open',
115
+ where: 'Settings › Version › Notices from MADRE turns off the information and important ones; security notices always show · PULSE_NOTICES=0 for development',
116
+ inside: true,
117
+ },
99
118
  {
100
119
  // Anonymous diagnostics (src/telemetry.mjs, 2026-10-28): on unless turned off.
101
120
  id: 'diagnostics', host: 'madre.run', match: (url) => url.pathname === '/api/telemetry', to: 'madre.run · anonymous diagnostics',
@@ -104,6 +123,15 @@ export const DESTINATIONS = [
104
123
  where: 'Settings › Version and reports › Send anonymous diagnostics · or PULSE_TELEMETRY=0',
105
124
  inside: true,
106
125
  },
126
+ {
127
+ // On right now (src/install-metrics.mjs): part of the diagnostics and off with them. Without its
128
+ // own line it fell to the collector, and the log said it went to the error reports.
129
+ id: 'presence', host: 'madre.run', match: (url) => url.pathname === '/api/presence', to: 'madre.run · on right now',
130
+ what: 'This copy\'s random identifier, the MADRE version and the system, so the author knows how many copies are open now. Nothing from your projects.',
131
+ when: 'every five minutes while MADRE is open',
132
+ where: 'Off with the anonymous diagnostics: Settings › Version and reports › Send anonymous diagnostics · or PULSE_TELEMETRY=0',
133
+ inside: true,
134
+ },
107
135
  {
108
136
  // The Market (src/market-remote.mjs): a signed catalog, and the file of a module you get from it.
109
137
  id: 'market', host: 'madre.run', match: (url) => url.pathname.startsWith('/mercado/'), to: "madre.run · the Market",
@@ -121,9 +149,17 @@ export const DESTINATIONS = [
121
149
  inside: true,
122
150
  },
123
151
  {
124
- id: 'usage', host: 'madre.run', match: (url) => url.pathname === '/api/usage', to: "madre.run · the author's usage figures",
125
- what: "The author's token, to read how many copies are on. Only in the author's own copy, run from source.",
126
- when: 'while the «MADRE usage» widget is on Home',
152
+ id: 'usage', host: 'madre.run', match: (url) => url.pathname === '/api/usage' || url.pathname === '/api/rumbo', to: "madre.run · the author's usage figures",
153
+ what: "The author's token, to read how many copies are on and how far new ones get. Only in the author's own copy, run from source.",
154
+ when: 'while the «MADRE usage» or «MADRE\'s course» widget is on Home',
155
+ where: "Only in the author's copy",
156
+ inside: true,
157
+ },
158
+ {
159
+ // MADRE's course (src/rumbo.mjs, 2026-11-01): npm's public download counts of the package.
160
+ id: 'npm-stats', host: 'api.npmjs.org', to: "npm · the package's download counts",
161
+ what: 'Nothing but the name of MADRE\'s package, to read how many times it was downloaded. Only in the author\'s own copy, run from source.',
162
+ when: 'while the «MADRE\'s course» widget is on Home, every half hour at most',
127
163
  where: "Only in the author's copy",
128
164
  inside: true,
129
165
  },
@@ -134,6 +170,15 @@ export const DESTINATIONS = [
134
170
  where: 'Settings › Version and reports › Report automatically · or PULSE_REPORT_URL',
135
171
  inside: true,
136
172
  },
173
+ {
174
+ // Whether Anthropic takes the Claude key a person pastes (credentials.mjs, MR-R92AWX): Claude's
175
+ // own status says «logged in» for any key it finds, even a made-up one.
176
+ id: 'anthropic-key', host: 'api.anthropic.com', match: (url) => /^\/v1\/models\/?$/.test(url.pathname), to: 'Anthropic · whether it takes your Claude key',
177
+ what: 'The API key you paste for Claude, so Anthropic says whether it takes it. It lists models and spends no credit. Nothing about you or your project.',
178
+ when: 'once, when you save a Claude API key in Settings › Agents',
179
+ where: 'Settings › Agents › Claude · without a pasted key it is never asked',
180
+ inside: true,
181
+ },
137
182
  {
138
183
  id: 'anthropic', host: 'api.anthropic.com', to: 'Anthropic',
139
184
  what: 'Your Claude Code token, to read how much of your plan is left. It is read from where Claude keeps it and never stored by MADRE.',
@@ -336,7 +381,7 @@ export class OutboundLog {
336
381
  return watched;
337
382
  }
338
383
 
339
- // Everything in this process, including whatever a module calls. Returns the undo.
384
+ // Fetch in this process. An external module is logged through its own bridge. Returns the undo.
340
385
  install(target = globalThis) {
341
386
  if (this.#restore) return this.#restore;
342
387
  const original = target.fetch;
@@ -363,7 +408,7 @@ export class OutboundLog {
363
408
  export function outboundView({ log = null, state = {}, agents = [] } = {}) {
364
409
  const counts = log?.counts() ?? {};
365
410
  // Said in the room's language (2026-10-12): the list read in English inside a Spanish room.
366
- const vendors = { codex: 'OpenAI', claude: 'Anthropic', gemini: 'Google', opencode: t('the provider OpenCode is signed in to'), cursor: 'Cursor' };
411
+ const vendors = { codex: 'OpenAI', claude: 'Anthropic', gemini: 'Google', opencode: t('the provider OpenCode is signed in to'), cursor: 'Cursor', grok: 'xAI' };
367
412
  const crew = agents.filter((agent) => agent.detected && !agent.local).map((agent) => `@${agent.id} → ${agent.route?.destination ?? vendors[agent.id] ?? t('its own provider')}`);
368
413
  const destinations = DESTINATIONS.map((one) => ({
369
414
  id: one.id,
@@ -372,8 +417,8 @@ export function outboundView({ log = null, state = {}, agents = [] } = {}) {
372
417
  when: t(one.when),
373
418
  where: t(one.where),
374
419
  local: Boolean(one.local),
375
- // Whether the call lands in the log at all. Everything MADRE starts does, the image studio
376
- // from its own process included; the crew's own conversation with its provider does not.
420
+ // Whether MADRE's fetch call lands in the log. The image studio and one-file module servers
421
+ // install their own wrapper; other protocols and agent CLI traffic do not pass through it.
377
422
  inside: Boolean(one.inside),
378
423
  on: state[one.id] ?? null,
379
424
  calls: counts[one.id]?.calls ?? 0,