@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
@@ -6,9 +6,10 @@
6
6
  // (defineModule is applied here), a module already built with defineModule, or a function
7
7
  // receiving { defineModule } and returning either. Agents cannot write those folders: .madre/
8
8
  // is a forbidden zone, and ~/.pulse lives outside every project.
9
- import { readdir, readFile, writeFile, mkdir, unlink, mkdtemp, rm } from 'node:fs/promises';
9
+ import { readdir, readFile, writeFile, mkdir, unlink, mkdtemp, realpath, rm } from 'node:fs/promises';
10
+ import { execFile } from 'node:child_process';
10
11
  import { translate } from '../i18n.mjs';
11
- import { join, basename, resolve, sep } from 'node:path';
12
+ import { join, basename, dirname, resolve, sep } from 'node:path';
12
13
  import { tmpdir } from 'node:os';
13
14
  import { pathToFileURL, fileURLToPath } from 'node:url';
14
15
  import { clearDeclaredDestinations, declareDestinations } from '../outbound.mjs';
@@ -31,6 +32,8 @@ import bishop from './bishop.mjs';
31
32
  import mcpConnect from './mcp-connect.mjs';
32
33
  import { isSalasRoom } from '../salas.mjs';
33
34
  import { defineModule, matchRoute, understandsSdk } from './sdk.mjs';
35
+ import { settingsIn } from '../module-scope.mjs';
36
+ import { fencedTools, permissionArgs, runExternal } from './isolated.mjs';
34
37
  import { builtinFile, newer, readBuiltinRecord, trustedBytes } from '../builtin-updates.mjs';
35
38
 
36
39
  // The lab: modules that are built and tested but not offered yet, because they are not finished
@@ -86,6 +89,78 @@ async function importModuleFile(file) {
86
89
  return typeof spec.describe === 'function' ? spec : defineModule(spec);
87
90
  }
88
91
 
92
+ // The same file, described in words that cross a process: what the check and the person need,
93
+ // never the module itself. src/modules/check-alone.mjs answers with it.
94
+ export async function inspectModuleFile(file) {
95
+ const module = await importModuleFile(file);
96
+ const snapshot = JSON.parse(JSON.stringify(module, (_, value) => value instanceof RegExp ? { madreRegExp: value.source, flags: value.flags } : value));
97
+ return {
98
+ id: module.id, name: module.name, vendor: module.vendor, version: module.version ?? null, summary: module.summary ?? '', words: module.words ?? null, credit: module.credit ?? null, updates: module.updates ?? null, unknown: module.unknown ?? [], declares: declaredBy(module),
99
+ routes: (module.routes ?? []).map((route) => ({ path: typeof route.path === 'string' ? route.path : { source: route.path?.source ?? '' } })),
100
+ snapshot,
101
+ hooks: Object.fromEntries(['describe', 'onEvent', 'toolsForTurn', 'updatePlan', 'detect', 'preflight', 'installCommand', 'setControl', 'toggle', 'scope'].map((key) => [key, typeof module[key] === 'function'])),
102
+ routeHooks: (module.routes ?? []).map((route) => typeof route.handler === 'function'),
103
+ slashHooks: (module.slash ?? []).map((command) => ({ execute: typeof command.execute === 'function', available: typeof command.available === 'function' })),
104
+ };
105
+ }
106
+
107
+ // Loads a candidate in a node of its own, fenced by Node's permission model (check-alone.mjs says
108
+ // what it may and may not do), so that asking what a file is never runs it inside MADRE.
109
+ const CHECK_ALONE = fileURLToPath(new URL('./check-alone.mjs', import.meta.url));
110
+ export const CHECK_MS = 15000;
111
+ async function inspectAlone(probe) {
112
+ const [folder, canonical] = await Promise.all([realpath(dirname(probe)), realpath(probe)]);
113
+ const fence = permissionArgs(canonical);
114
+ return new Promise((done, fail) => {
115
+ execFile(process.execPath, [...fence, CHECK_ALONE, canonical], { env: {}, cwd: folder, timeout: CHECK_MS, maxBuffer: 1 << 20, windowsHide: true }, (error, stdout, stderr) => {
116
+ if (error?.killed) return fail(new Error(`it did not finish loading in ${CHECK_MS / 1000} s, so MADRE stopped it: a module only declares what it is, and loading it must not wait on anything`));
117
+ const said = String(stdout ?? '').split('\n').reverse().map((line) => { try { return JSON.parse(line); } catch { return null; } }).find((one) => one && typeof one.ok === 'boolean');
118
+ if (!said) return fail(new Error(String(stderr ?? '').trim().split('\n').at(-1) || error?.message || 'it ended before saying what it is'));
119
+ if (!said.ok) return fail(Object.assign(new Error(said.error), { code: said.code ?? undefined }));
120
+ if (!said.module || typeof said.module.id !== 'string' || !/^[a-z][a-z0-9-]*$/.test(said.module.id)) return fail(new Error('it did not say a module id MADRE can use'));
121
+ return done(said.module);
122
+ });
123
+ });
124
+ }
125
+
126
+ const revive = (value) => {
127
+ if (Array.isArray(value)) return value.map(revive);
128
+ if (!value || typeof value !== 'object') return value;
129
+ if (typeof value.madreRegExp === 'string') return new RegExp(value.madreRegExp, value.flags ?? '');
130
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, revive(item)]));
131
+ };
132
+
133
+ function externalProxy(checked, file, origin) {
134
+ const snapshot = revive(checked.snapshot);
135
+ const invoke = (operation, ctx, args = [], index = null) => runExternal({
136
+ file, id: checked.id, configKey: snapshot.configKey, reaches: snapshot.reaches ?? [], operation, index, ctx, args,
137
+ });
138
+ const module = {
139
+ ...snapshot,
140
+ external: true, origin, file,
141
+ settingsFrom: (config, roomId = null) => ({ ...snapshot.defaults, ...settingsIn(config?.modules?.[snapshot.configKey] ?? {}, roomId) }),
142
+ describe: async (ctx) => ({ ...(await invoke('describe', ctx)), external: true, origin, file }),
143
+ routes: (snapshot.routes ?? []).map((route, index) => ({ ...route, handler: checked.routeHooks[index]
144
+ ? (ctx, request) => invoke('route', ctx, [{ method: request.request?.method, url: request.url?.href ?? null, headers: request.request?.headers ?? {}, payload: request.payload, params: request.params, viaPhone: request.viaPhone }], index)
145
+ : null })),
146
+ slash: (snapshot.slash ?? []).map((command, index) => ({ ...command,
147
+ ...(checked.slashHooks[index]?.execute ? { execute: (ctx, args) => invoke('slash', ctx, [args], index) } : {}),
148
+ ...(checked.slashHooks[index]?.available ? { available: (ctx) => invoke('available', ctx, [], index) } : {}),
149
+ })),
150
+ };
151
+ for (const hook of ['onEvent', 'updatePlan', 'setControl', 'toggle', 'scope']) {
152
+ if (checked.hooks[hook]) module[hook] = (ctx, ...args) => invoke(hook, ctx, args);
153
+ }
154
+ for (const hook of ['detect', 'preflight', 'installCommand']) {
155
+ if (checked.hooks[hook]) module[hook] = (...args) => invoke(hook, {}, args);
156
+ }
157
+ module.toolsForTurn = checked.hooks.toolsForTurn ? async (ctx, turn) => {
158
+ try { return await fencedTools(await invoke('toolsForTurn', ctx, [turn]), { file, id: checked.id, reaches: snapshot.reaches ?? [], turn, outboundLog: ctx.env?.PULSE_OUTBOUND_LOG ?? null }); }
159
+ catch (error) { console.error(`MADRE module ${checked.id}: toolsForTurn failed: ${error.message}`); return []; }
160
+ } : null;
161
+ return Object.freeze(module);
162
+ }
163
+
89
164
  export async function loadExternalModules({ stateRoot, projectRoot }) {
90
165
  for (let index = MODULES.length - 1; index >= 0; index -= 1) if (MODULES[index].external) MODULES.splice(index, 1);
91
166
  loadFailures.length = 0;
@@ -100,8 +175,8 @@ export async function loadExternalModules({ stateRoot, projectRoot }) {
100
175
  for (const name of files) {
101
176
  const file = join(dir, name);
102
177
  try {
103
- const module = checkExternal(await importModuleFile(file));
104
- MODULES.push(Object.freeze({ ...module, external: true, origin, file }));
178
+ const module = checkExternal(externalProxy(await inspectAlone(file), file, origin));
179
+ MODULES.push(module);
105
180
  if (module.reaches) declareDestinations(module.id, module.reaches);
106
181
  } catch (error) {
107
182
  loadFailures.push({ file, origin, error: error.message });
@@ -153,9 +228,11 @@ export async function adoptBuiltinUpdates({ stateRoot, enabled = true, factoryKe
153
228
  }
154
229
 
155
230
  // The one door every module comes through, whoever wrote it and wherever the text came from: it
156
- // is written to a scratch copy, imported there and checked against the house rules. A module runs
157
- // inside MADRE with the human's own permissions, so the check is the point. Checking installs
158
- // nothing and touches no registry — asking what a file is must never change what is loaded.
231
+ // is written to a scratch copy, loaded there in a fenced node of its own (inspectAlone) and checked
232
+ // against the house rules. Each later call also runs in a fenced process (RX-2); checking and
233
+ // running a human module never execute its JavaScript in MADRE's server process.
234
+ // Checking installs nothing and touches no registry — asking what a file is must never change
235
+ // what is loaded.
159
236
  export async function verifyModuleText({ text, name = null, replace = true }) {
160
237
  const scratch = await mkdtemp(join(tmpdir(), 'madre-module-check-'));
161
238
  try {
@@ -163,7 +240,7 @@ export async function verifyModuleText({ text, name = null, replace = true }) {
163
240
  await writeFile(probe, text);
164
241
  let module;
165
242
  try {
166
- module = checkExternal(await importModuleFile(probe), { replace });
243
+ module = checkExternal(await inspectAlone(probe), { replace });
167
244
  } catch (error) {
168
245
  // The one mistake that looks right and never works: MADRE's own modules import the SDK by
169
246
  // relative path because they live inside the package, and anyone — an agent most of all —
@@ -174,7 +251,7 @@ export async function verifyModuleText({ text, name = null, replace = true }) {
174
251
  }
175
252
  throw error;
176
253
  }
177
- return { id: module.id, name: module.name, vendor: module.vendor, version: module.version ?? null, summary: module.summary ?? '', words: module.words ?? null, credit: module.credit ?? null, updates: module.updates ?? null, unknown: module.unknown ?? [], declares: declaredBy(module) };
254
+ return { id: module.id, name: module.name, vendor: module.vendor, version: module.version ?? null, summary: module.summary ?? '', words: module.words ?? null, credit: module.credit ?? null, updates: module.updates ?? null, unknown: module.unknown ?? [], declares: module.declares };
178
255
  } finally { await rm(scratch, { recursive: true, force: true, maxRetries: 6, retryDelay: 60 }); }
179
256
  }
180
257
 
@@ -182,7 +259,7 @@ export async function verifyModuleText({ text, name = null, replace = true }) {
182
259
  // installed (2026-10-25). Only what the file itself declares: where it reaches, the keys it asks
183
260
  // for, whether it hands tools to the agents or reads the conversations, the pages and commands it
184
261
  // adds, and whether it writes in the project. What the code does beyond that nobody can promise —
185
- // which is why the page also says, every time, that a module runs with the person's permissions.
262
+ // its declared destinations still need the person's review before installation.
186
263
  export function declaredBy(module) {
187
264
  return {
188
265
  reaches: (module.reaches ?? []).map(({ host, to, what, when }) => ({ host: host ?? null, to: to ?? null, what: what ?? null, when: when ?? null })),
@@ -206,7 +283,7 @@ export async function verifyBuiltinText({ text, id }) {
206
283
  try {
207
284
  const probe = join(scratch, `${id}.mjs`);
208
285
  await writeFile(probe, text);
209
- const module = await importModuleFile(probe);
286
+ const module = (await inspectAlone(probe)).snapshot;
210
287
  if (module.id !== id) throw new Error(`The file says it is "${module.id}", not "${id}".`);
211
288
  if (!understandsSdk(module.sdk)) throw new Error(`${id} needs contract ${module.sdk} of the SDK.`);
212
289
  if (!module.version || !newer(module.version, packaged.version ?? '0.0.0')) throw new Error(`${id} ${module.version ?? '(no version)'} is not newer than the ${packaged.version} MADRE comes with.`);
@@ -0,0 +1,160 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // The only bridge from a human module to MADRE. The module's JavaScript runs in a fresh Node
4
+ // process with no inherited environment, no filesystem writes and no child processes.
5
+ import { spawn } from 'node:child_process';
6
+ import { realpath } from 'node:fs/promises';
7
+ import { basename, dirname, join, resolve } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { forgetSecret, readSecret, summary as vaultSummary, writeSecret } from '../vault.mjs';
10
+ import { OutboundLog } from '../outbound.mjs';
11
+
12
+ const RUN_ALONE = fileURLToPath(new URL('./run-alone.mjs', import.meta.url));
13
+ const FETCH_ALONE = fileURLToPath(new URL('./fetch-alone.mjs', import.meta.url));
14
+ const PACKAGE_ROOT = fileURLToPath(new URL('../..', import.meta.url));
15
+ const SOURCE_ROOT = join(PACKAGE_ROOT, 'src');
16
+ const PUBLIC_ROOT = join(PACKAGE_ROOT, 'public');
17
+ const PACKAGE_JSON = join(PACKAGE_ROOT, 'package.json');
18
+ export const FENCE = ['--permission', '--experimental-permission'].find((flag) => process.allowedNodeEnvironmentFlags.has(flag)) ?? null;
19
+ const NETWORK = process.allowedNodeEnvironmentFlags.has('--allow-net') ? '--allow-net' : null;
20
+ // The module's own time for one call. What it waits on MADRE for (a local model on a computer with no
21
+ // graphics card takes minutes, L-7) does not count against it; the ceiling holds both.
22
+ const LIMIT_MS = 30000;
23
+ const CEILING_MS = 15 * 60 * 1000;
24
+ const MAX_BYTES = 1 << 20;
25
+ const MAX_CONTEXT_CALLS = 256;
26
+
27
+ export const permissionArgs = (file, reaches = [], { sdk = true } = {}) => {
28
+ if (!FENCE) throw new Error('This Node cannot isolate a module; update Node before loading it.');
29
+ const readable = sdk ? [SOURCE_ROOT, PUBLIC_ROOT, PACKAGE_JSON, file] : [file];
30
+ return [FENCE, ...readable.map((path) => `--allow-fs-read=${path}`), ...(NETWORK && reaches.length ? [NETWORK] : [])];
31
+ };
32
+ const send = (child, message) => {
33
+ if (child.stdin.destroyed) return;
34
+ try { child.stdin.write(`${JSON.stringify({ madreModule: true, ...message })}\n`); }
35
+ catch { /* A finished child cannot receive another context answer. */ }
36
+ };
37
+
38
+ async function answerContext(id, ctx, method, args) {
39
+ const services = ctx.services ?? {};
40
+ switch (method) {
41
+ case 'readConfig': return ctx.readConfig?.();
42
+ case 'updateConfig': {
43
+ const patch = args[0];
44
+ const key = ctx.moduleConfigKey;
45
+ if (!key || !patch || Object.keys(patch).join() !== 'modules' || Object.keys(patch.modules ?? {}).join() !== key) throw new Error('A module may change only its own settings.');
46
+ return ctx.updateConfig?.(patch);
47
+ }
48
+ case 'record': return ctx.record?.(args[0], args[1]);
49
+ case 'room.record': return ctx.record?.(args[0], args[1]);
50
+ case 'vault.get': return readSecret(ctx.stateRoot, id, args[0]);
51
+ case 'vault.held': return vaultSummary(ctx.stateRoot, id);
52
+ case 'vault.keep': return writeSecret(ctx.stateRoot, id, args[0], args[1]);
53
+ case 'vault.forget': return forgetSecret(ctx.stateRoot, id, args[0]);
54
+ case 'services.history': return services.history?.(args[0]);
55
+ case 'services.ollama.generate': return services.ollama?.generate?.(args[0]);
56
+ case 'outbound.record': {
57
+ const file = ctx.env?.PULSE_OUTBOUND_LOG;
58
+ if (!file) return null;
59
+ const log = new OutboundLog({ file });
60
+ log.record(args[0] ?? {});
61
+ await log.drain();
62
+ return null;
63
+ }
64
+ default: throw new Error('This context method is not available to a human module.');
65
+ }
66
+ }
67
+
68
+ export async function runExternal({ file, id, configKey, reaches = [], operation, index = null, ctx = {}, args = [], limitMs = LIMIT_MS, ceilingMs = CEILING_MS }) {
69
+ const canonical = await realpath(file);
70
+ const flags = permissionArgs(canonical, reaches);
71
+ const room = ctx.room;
72
+ const turnId = operation === 'toolsForTurn' ? args[0]?.turn : null;
73
+ const input = {
74
+ projectRoot: ctx.projectRoot, stateRoot: ctx.stateRoot, roomId: ctx.roomId, chat: ctx.chat,
75
+ config: ctx.config ?? {}, settings: ctx.settings ?? {}, agents: ctx.agents ?? [], language: ctx.language ?? 'en',
76
+ hasRoom: Boolean(room), capabilities: room?.capabilities?.() ?? null, turnId,
77
+ runningTurn: turnId ? room?.runningTurn?.(turnId) ?? null : null,
78
+ ollamaState: ctx.services?.ollama?.state?.() ?? null,
79
+ };
80
+ return new Promise((resolveDone, rejectDone) => {
81
+ const child = spawn(process.execPath, [...flags, RUN_ALONE, canonical], { cwd: dirname(canonical), env: {}, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
82
+ const context = { ...ctx, moduleConfigKey: configKey };
83
+ let settled = false;
84
+ let stdout = '';
85
+ let bytes = 0;
86
+ let contextCalls = 0;
87
+ let timer = null;
88
+ let spent = 0;
89
+ let since = Date.now();
90
+ let waiting = 0;
91
+ const finish = (error, value) => {
92
+ if (settled) return;
93
+ settled = true;
94
+ clearTimeout(timer);
95
+ clearTimeout(ceiling);
96
+ child.kill();
97
+ if (error) rejectDone(error); else resolveDone(value);
98
+ };
99
+ const tooLong = () => finish(new Error(`Module ${id} did not answer in ${limitMs / 1000} s.`));
100
+ const ceiling = setTimeout(() => finish(new Error(`Module ${id} did not answer in ${Math.round(ceilingMs / 60000)} min.`)), ceilingMs);
101
+ timer = setTimeout(tooLong, limitMs);
102
+ // While MADRE answers one of its calls, the module's clock stops.
103
+ const pause = () => { if (waiting++ === 0) { spent += Date.now() - since; clearTimeout(timer); } };
104
+ const resume = () => { if (--waiting === 0 && !settled) { since = Date.now(); timer = setTimeout(tooLong, Math.max(0, limitMs - spent)); } };
105
+ child.on('error', (error) => finish(error));
106
+ child.stdin.on('error', (error) => { if (!settled) finish(error); });
107
+ child.on('close', (code) => {
108
+ if (!settled) finish(new Error(`Module ${id} ended before answering (exit ${code}).`));
109
+ });
110
+ child.stderr.resume();
111
+ child.stdout.on('data', (chunk) => {
112
+ bytes += chunk.length;
113
+ if (bytes > MAX_BYTES) return finish(new Error(`Module ${id} answered with too much data.`));
114
+ stdout += chunk;
115
+ let end;
116
+ while ((end = stdout.indexOf('\n')) >= 0) {
117
+ const line = stdout.slice(0, end).trim();
118
+ stdout = stdout.slice(end + 1);
119
+ let message;
120
+ try { message = JSON.parse(line); } catch { continue; }
121
+ if (!message?.madreModule) continue;
122
+ if (message.type === 'done') return finish(message.ok ? null : Object.assign(new Error(message.error ?? 'Module failed.'), { code: message.code ?? undefined }), message.value);
123
+ if (message.type !== 'ctx') continue;
124
+ if (++contextCalls > MAX_CONTEXT_CALLS) return finish(new Error(`Module ${id} requested too many context calls.`));
125
+ pause();
126
+ void Promise.resolve().then(() => answerContext(id, context, message.method, message.args ?? []))
127
+ .then((value) => send(child, { type: 'ctxResult', id: message.id, ok: true, value }),
128
+ (error) => send(child, { type: 'ctxResult', id: message.id, ok: false, error: String(error?.message ?? error) }))
129
+ .finally(resume);
130
+ }
131
+ });
132
+ send(child, { type: 'invoke', expectedId: id, operation, index, ctx: input, args });
133
+ });
134
+ }
135
+
136
+ // A module may hand a server to a turn, but it may not use that to regain the rights that its
137
+ // own process lacks. Only the same one-file Node server is accepted, under the same fence.
138
+ export async function fencedTools(servers, { file, id = '?', reaches = [], turn, outboundLog = null } = {}) {
139
+ const canonical = await realpath(file);
140
+ const flags = permissionArgs(canonical, reaches);
141
+ const offered = [];
142
+ for (const server of servers ?? []) {
143
+ const script = server?.args?.[0];
144
+ const same = script && await realpath(resolve(dirname(canonical), script)).then((path) => path === canonical).catch(() => false);
145
+ if (!same || ![process.execPath, 'node'].includes(server.command)) {
146
+ console.error(`MADRE module ${id}: an MCP server was withheld because it is not this module's own Node file.`);
147
+ continue;
148
+ }
149
+ const scratchDir = Number(turn?.mode) >= 2 && turn?.scratchDir ? await realpath(turn.scratchDir) : null;
150
+ const tracePath = outboundLog ? join(await realpath(dirname(outboundLog)), basename(outboundLog)) : null;
151
+ const scratch = scratchDir ? [`--allow-fs-write=${scratchDir}`] : [];
152
+ const trace = tracePath ? [`--allow-fs-write=${tracePath}`, '--import', FETCH_ALONE] : [];
153
+ const env = { ...(server.env ?? {}) };
154
+ // A tool may receive its own declared credentials, but it cannot smuggle extra Node flags
155
+ // (including permission grants) through the environment of the process MADRE starts.
156
+ delete env.NODE_OPTIONS;
157
+ offered.push({ ...server, command: process.execPath, args: [...flags, ...scratch, ...trace, canonical, ...server.args.slice(1)], env: { ...env, ...(tracePath ? { PULSE_OUTBOUND_LOG: tracePath } : {}) } });
158
+ }
159
+ return offered;
160
+ }
@@ -4,6 +4,8 @@
4
4
  // Ollama runs. The server offers the wiring through ctx.services.ollama.
5
5
 
6
6
  import { execFile } from 'node:child_process';
7
+ import { access, constants, readdir, realpath } from 'node:fs/promises';
8
+ import { dirname, join } from 'node:path';
7
9
  import { defineModule } from './sdk.mjs';
8
10
  import { t } from '../i18n.mjs';
9
11
  import { findOnPath } from './helpers.mjs';
@@ -73,22 +75,49 @@ export function ollamaUpdatePlan({ platform = process.platform, brew = null, adm
73
75
  }
74
76
  if (platform === 'linux') {
75
77
  if (!admin) return { command: null, manual: true, display: script.replace('sudo -n ', 'sudo '), note: `${t(NEEDS_PASSWORD)} ${t('Your models stay where they are.')}` };
76
- return { command: 'sh', args: ['-c', script], display: script, note: "Ollama's own install script upgrades in place. Your models stay where they are." };
78
+ return { command: 'sh', args: ['-c', script], display: script, timeoutMs: OLLAMA_INSTALL_MS, note: "Ollama's own install script upgrades in place. Your models stay where they are." };
77
79
  }
78
80
  return { command: null, download: 'https://ollama.com/download', display: null, note: 'Download the newer Ollama from ollama.com and run it. Your models stay where they are.' };
79
81
  }
80
82
 
83
+ // How long Ollama's script may take (D-2, 2026-11-03): it streams a bundle of more than a GB, and on
84
+ // a slow line inside WSL fifteen minutes ran out halfway (diagnostics of 1.1.2: «timeout»).
85
+ export const OLLAMA_INSTALL_MS = 60 * 60 * 1000;
86
+
87
+ // An install that stopped halfway (D-2, 2026-11-03). Ollama's script first deletes lib/ollama and
88
+ // then unpacks the whole bundle in one stream; cut by the time limit or the network, it leaves
89
+ // bin/ollama with no llama-server beside it («llama-server binary not found», 1.1.2) or a binary
90
+ // this user cannot run (EACCES). Either reads as installed, and every answer of @madre failed. Seen
91
+ // as halfway, the card offers the install again, which finishes it. Only Linux, and only where the
92
+ // script installs (`scriptRoot`): Homebrew, the Mac app or a distribution's package lay it out
93
+ // otherwise.
94
+ export async function ollamaHalfway(binary, { platform = process.platform, scriptRoot = '/usr/local' } = {}) {
95
+ if (!binary || platform !== 'linux') return false;
96
+ try { await access(binary, constants.X_OK); } catch { return true; }
97
+ const real = await realpath(binary).catch(() => binary);
98
+ const root = dirname(dirname(real));
99
+ if (root !== scriptRoot) return false;
100
+ const lib = await readdir(join(root, 'lib', 'ollama')).catch(() => null);
101
+ return !lib?.length;
102
+ }
103
+
81
104
  // Waking it: the same command on every system, and the app on macOS does it too.
82
105
  export const ollamaStartPlan = () => ({ command: 'ollama', args: ['serve'], display: 'ollama serve' });
83
106
 
84
107
  // What the room needs to know about the local brain: its own state, whether it is even on this
85
108
  // computer, and the one step that moves it forward. The card and the routes share this.
86
109
  export async function ollamaView(probe, settings) {
87
- const binary = await findOnPath('ollama');
110
+ const found = await findOnPath('ollama');
111
+ // Halfway is not installed: no binary for the card, which offers the install again, and the path
112
+ // kept apart so it can say what it found.
113
+ const halfway = await ollamaHalfway(found) ? found : null;
114
+ const binary = halfway ? null : found;
88
115
  // The sudo question is only worth asking while there is something to install.
89
116
  const admin = binary ? true : await adminHere();
90
- return { ...probe, settings, binary, install: ollamaInstallPlan({ brew: await findOnPath('brew'), admin, zstd: Boolean(await findOnPath('zstd')), apt: Boolean(await findOnPath('apt-get')) }), start: ollamaStartPlan() };
117
+ const install = ollamaInstallPlan({ brew: await findOnPath('brew'), admin, zstd: Boolean(await findOnPath('zstd')), apt: Boolean(await findOnPath('apt-get')) });
118
+ return { ...probe, settings, binary, ...(halfway ? { halfway } : {}), install: halfway && install.command ? { ...install, note: t(HALFWAY_NOTE) } : install, start: ollamaStartPlan() };
91
119
  }
120
+ const HALFWAY_NOTE = 'Ollama was left installed halfway (the download stopped). Installing it again finishes it; your models stay where they are.';
92
121
 
93
122
  export default defineModule({
94
123
  id: 'ollama',
@@ -108,7 +137,7 @@ export default defineModule({
108
137
  const roles = [settings.embeddings && probe.embedModel ? `${t('smart search')} · ${probe.embedModel}` : null, settings.archivist && probe.chatModel ? `${t('archivist')} · ${probe.chatModel}` : null, settings.agent !== false && probe.chatModel ? t('@madre in the project') : null].filter(Boolean);
109
138
  // Home can leave this one project without the local AI while the module stays on (src/local-ai.mjs).
110
139
  const project = await ctx.services.ollama?.project?.() ?? { on: true };
111
- const detail = !probe.running ? (binary ? t('installed, not running · START it here') : t('not installed · INSTALL it here'))
140
+ const detail = !probe.running ? (binary ? t('installed, not running · START it here') : view.halfway ? t('installed halfway · INSTALL it again here') : t('not installed · INSTALL it here'))
112
141
  : !settings.enabled ? t('off · {n} models available', { n: probe.models.length })
113
142
  : !project.on ? t('off in this project · Home › Settings › Local AI')
114
143
  : roles.length ? `${t('on')} · ${roles.join(' · ')}` : t('on · no usable model yet · PULL one');
@@ -147,8 +176,8 @@ export default defineModule({
147
176
  return { status: 200, body: { enabled, ollama: status } };
148
177
  },
149
178
  routes: [
150
- { method: 'GET', path: '/api/ollama', handler: async (ctx) => ({ status: 200, body: { ollama: await ollamaView(await ctx.services.ollama.wire({ probe: false }), ctx.settings), recommended: await recommendedHere() } }) },
151
- { method: 'POST', path: '/api/ollama/probe', handler: async (ctx) => ({ status: 200, body: { ollama: await ollamaView(await ctx.services.ollama.wire(), ctx.settings), recommended: await recommendedHere() } }) },
179
+ { method: 'GET', path: '/api/ollama', handler: async (ctx) => ({ status: 200, body: { ollama: await ollamaView(await ctx.services.ollama.wire({ probe: false }), ctx.settings), recommended: await recommendedHere(), pulling: ctx.services.ollama.pulling?.() ?? null, lastPull: ctx.services.ollama.lastPull?.() ?? null } }) },
180
+ { method: 'POST', path: '/api/ollama/probe', handler: async (ctx) => ({ status: 200, body: { ollama: await ollamaView(await ctx.services.ollama.wire(), ctx.settings), recommended: await recommendedHere(), pulling: ctx.services.ollama.pulling?.() ?? null, lastPull: ctx.services.ollama.lastPull?.() ?? null } }) },
152
181
  { method: 'POST', path: '/api/ollama/settings', handler: async (ctx, { payload }) => {
153
182
  const next = { ...(ctx.config.modules?.ollama ?? {}) };
154
183
  for (const key of ['embeddings', 'archivist', 'agent', 'enabled']) if (typeof payload[key] === 'boolean') next[key] = payload[key];
@@ -6,7 +6,7 @@
6
6
  // room's own address: nothing else on the network is reachable through it.
7
7
 
8
8
  import { spawn } from 'node:child_process';
9
- import { mkdtemp, rm } from 'node:fs/promises';
9
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
10
10
  import { tmpdir } from 'node:os';
11
11
  import { join } from 'node:path';
12
12
  import { t } from '../i18n.mjs';
@@ -61,18 +61,41 @@ function runToEnd(command, args, { cwd, env, timeoutMs = 900000 } = {}) {
61
61
  });
62
62
  }
63
63
 
64
+ // Where npm installs for every project is often not this person's to write: Node from apt or the
65
+ // distribution keeps it in /usr/lib/node_modules, and `npm install -g` ends in EACCES, exit 243
66
+ // (report MR-5NY24Y and the diagnostics of 1.1.2). MADRE never asks for sudo; it keeps the server in
67
+ // a folder of its own instead, and tells npm and npx where with npm_config_prefix (2026-11-03).
68
+ export const ownNpmPrefix = (stateRoot) => join(stateRoot, 'npm-global');
69
+ const refusedWrite = (said, code) => code === 243 || /EACCES|EPERM|permission denied/i.test(String(said ?? ''));
70
+ // The environment the server is looked for and started with: MADRE's own folder once the server
71
+ // lives there, the person's own otherwise.
72
+ export async function playwrightEnv({ env = process.env, stateRoot = null } = {}) {
73
+ if (!stateRoot) return env;
74
+ const prefix = ownNpmPrefix(stateRoot);
75
+ const there = await readFile(join(prefix, 'lib', 'node_modules', ...PLAYWRIGHT_PACKAGE.split('/'), 'package.json'), 'utf8').then(() => true, () => false);
76
+ return there ? { ...env, npm_config_prefix: prefix } : env;
77
+ }
78
+
64
79
  // What the switch puts in place by itself before it gives up (2026-10-18): the person turned it
65
80
  // on, and a browser to download is MADRE's to fetch, not a line to copy into a terminal. The
66
81
  // server, globally (where `npx --no` finds it at turn time), when it is missing; then the browser
67
82
  // the server itself downloads for the engine chosen. Asked again after.
68
- export async function preparePlaywright({ browser = 'chromium', env = process.env, cwd = process.cwd(), run = runToEnd, starts = playwrightStarts, version = playwrightVersion } = {}) {
83
+ export async function preparePlaywright({ browser = 'chromium', env = process.env, cwd = process.cwd(), stateRoot = null, run = runToEnd, starts = playwrightStarts, version = playwrightVersion } = {}) {
69
84
  const engine = PLAYWRIGHT_BROWSERS.includes(browser) ? browser : 'chromium';
70
85
  let installed = await version({ env, projectRoot: cwd, fresh: true });
71
86
  const steps = [];
72
87
  if (!installed) {
73
- const server = await run('npm', ['install', '-g', PLAYWRIGHT_PACKAGE], { cwd, env });
88
+ let server = await run('npm', ['install', '-g', PLAYWRIGHT_PACKAGE], { cwd, env });
74
89
  steps.push({ display: `npm install -g ${PLAYWRIGHT_PACKAGE}`, code: server.code });
75
90
  installed = await version({ env, projectRoot: cwd, fresh: true });
91
+ // The global folder is not this person's to write: the same install, into MADRE's own.
92
+ if (!installed && stateRoot && refusedWrite(server.said, server.code)) {
93
+ const prefix = ownNpmPrefix(stateRoot);
94
+ env = { ...env, npm_config_prefix: prefix };
95
+ server = await run('npm', ['install', '-g', PLAYWRIGHT_PACKAGE], { cwd, env });
96
+ steps.push({ display: `npm install -g --prefix ${prefix} ${PLAYWRIGHT_PACKAGE}`, code: server.code });
97
+ installed = await version({ env, projectRoot: cwd, fresh: true });
98
+ }
76
99
  if (!installed) return { ok: false, steps, problem: server.said ?? t('the browser server could not be installed') };
77
100
  }
78
101
  const fetched = await run('npx', ['--no', PLAYWRIGHT_PACKAGE, 'install-browser', engine], { cwd, env });
@@ -169,7 +192,7 @@ export function forgetPlaywrightHealth(result = null, browser = null) { started
169
192
  // What the browser may open: this room, and the servers the human started from RUNS in this project
170
193
  // while they listen on 127.0.0.1. RIPLEY's sealed frame keeps no data, so an app that stores its
171
194
  // data could only be tried through it half-blind. Nothing else on the network.
172
- export function playwrightServerFor({ port, outputDir, browser = 'chromium', headless = true, servers = [] }) {
195
+ export function playwrightServerFor({ port, outputDir, browser = 'chromium', headless = true, servers = [], preview = '/preview', prefix = null }) {
173
196
  const origins = [port, ...servers.filter((one) => Number.isInteger(one) && one !== port)].flatMap((one) => [`http://127.0.0.1:${one}`, `http://localhost:${one}`]);
174
197
  const served = servers.filter((one) => Number.isInteger(one) && one !== port);
175
198
  return {
@@ -183,25 +206,26 @@ export function playwrightServerFor({ port, outputDir, browser = 'chromium', hea
183
206
  // recently added route first — so a blocked `*`, registered after both, wins over the
184
207
  // allowlist and aborts even this room with ERR_BLOCKED_BY_CLIENT.
185
208
  args: ['--no', '@playwright/mcp', '--', ...(headless ? ['--headless'] : []), '--isolated', '--browser', browser, '--allowed-origins', origins.join(';'), '--output-dir', outputDir, '--no-sandbox'],
186
- env: {},
209
+ // npx finds a server kept in MADRE's own folder only when told where it is.
210
+ env: prefix ? { npm_config_prefix: prefix } : {},
187
211
  tools: PLAYWRIGHT_TOOLS,
188
- brief: `a headless browser that reaches only this MADRE at http://127.0.0.1:${port}${served.length ? ` and the project's servers the human started (${served.map((one) => `http://127.0.0.1:${one}`).join(', ')})` : ''}. Open a project file rendered by RIPLEY at http://127.0.0.1:${port}/preview/project/<path>, click, read the console and network, take screenshots (they land in ${outputDir}). RIPLEY's preview keeps no data (no localStorage, no cookies)${served.length ? '; to try an app with its data, open it on its server' : ''}. Nothing else on the network is reachable through it.`,
212
+ brief: `a headless browser that reaches only this MADRE at http://127.0.0.1:${port}${served.length ? ` and the project's servers the human started (${served.map((one) => `http://127.0.0.1:${one}`).join(', ')})` : ''}. Open a project file rendered by RIPLEY at http://127.0.0.1:${port}${preview}/project/<path>, click, read the console and network, take screenshots (they land in ${outputDir}). RIPLEY's preview keeps no data (no localStorage, no cookies)${served.length ? '; to try an app with its data, open it on its server' : ''}. Nothing else on the network is reachable through it.`,
189
213
  };
190
214
  }
191
215
 
192
216
  async function playwrightReady(ctx) {
193
217
  const browser = ctx.settings.browser ?? 'chromium';
194
- let check = await playwrightStarts({ browser, env: ctx.env, cwd: ctx.projectRoot });
218
+ let check = await playwrightStarts({ browser, env: await playwrightEnv(ctx), cwd: ctx.projectRoot });
195
219
  // Something missing: MADRE fetches it, then asks again, before saying anything to the person.
196
220
  if (!check.ok && process.platform !== 'win32') {
197
221
  await ctx.record('extension.preparing', { id: 'playwright', name: 'PLAYWRIGHT', browser });
198
- check = await preparePlaywright({ browser, env: ctx.env, cwd: ctx.projectRoot });
222
+ check = await preparePlaywright({ browser, env: await playwrightEnv(ctx), cwd: ctx.projectRoot, stateRoot: ctx.stateRoot });
199
223
  }
200
224
  forgetPlaywrightHealth(check, browser);
201
225
  if (check.ok) return null;
202
226
  // The server is there and only the browser is missing: say which one, and the one line that
203
227
  // installs it. Without the server, both lines.
204
- const version = await playwrightVersion({ env: ctx.env, projectRoot: ctx.projectRoot });
228
+ const version = await playwrightVersion({ env: await playwrightEnv(ctx), projectRoot: ctx.projectRoot });
205
229
  return { status: 412, body: { error: version
206
230
  ? t('TEST BROWSER stays off: MADRE downloaded the {browser} browser and it still does not start ({problem}). Check your internet connection and turn it on again, or choose another browser in its settings.', { problem: String(check.problem).replace(/[.\s]+$/, ''), browser })
207
231
  : t('TEST BROWSER stays off: MADRE could not install its browser server ({problem}). Check your internet connection and turn it on again.', { problem: String(check.problem).replace(/[.\s]+$/, '') }), code: 'MU-054' } };
@@ -231,8 +255,9 @@ export default defineModule({
231
255
  },
232
256
  ],
233
257
  async status(ctx) {
234
- const version = await playwrightVersion({ env: ctx.env, projectRoot: ctx.projectRoot });
235
- const health = ctx.settings.enabled && version ? playwrightHealth({ browser: ctx.settings.browser ?? 'chromium', env: ctx.env, cwd: ctx.projectRoot }) : null;
258
+ const env = await playwrightEnv(ctx);
259
+ const version = await playwrightVersion({ env, projectRoot: ctx.projectRoot });
260
+ const health = ctx.settings.enabled && version ? playwrightHealth({ browser: ctx.settings.browser ?? 'chromium', env, cwd: ctx.projectRoot }) : null;
236
261
  return {
237
262
  runs: [{ name: PLAYWRIGHT_PACKAGE, version }],
238
263
  settings: { browser: ctx.settings.browser ?? 'chromium', headless: ctx.settings.headless !== false },
@@ -247,25 +272,29 @@ export default defineModule({
247
272
  // where `npx --no` looks for it at turn time without downloading anything.
248
273
  async updatePlan(ctx, { latest = null } = {}) {
249
274
  const target = latest ? `${PLAYWRIGHT_PACKAGE}@${latest}` : PLAYWRIGHT_PACKAGE;
275
+ // Kept in MADRE's own folder, it is updated there.
276
+ const prefix = (await playwrightEnv(ctx)).npm_config_prefix;
277
+ const where = prefix ? ['--prefix', prefix] : [];
250
278
  return {
251
279
  command: 'npm',
252
- args: ['install', '-g', target],
253
- display: `npm install -g ${target}`,
280
+ args: ['install', '-g', ...where, target],
281
+ display: `npm install -g ${[...where, target].join(' ')}`,
254
282
  note: 'Installs the browser server for every project on this computer. A browser itself may still be missing; the card says so if it is.',
255
- after: async () => { await playwrightVersion({ env: ctx.env, projectRoot: ctx.projectRoot, fresh: true }); },
283
+ after: async () => { await playwrightVersion({ env: await playwrightEnv(ctx), projectRoot: ctx.projectRoot, fresh: true }); },
256
284
  };
257
285
  },
258
286
  async toolsForTurn(ctx, turn) {
259
- if (!(await playwrightVersion({ env: ctx.env, projectRoot: ctx.projectRoot }))) return [];
287
+ const env = await playwrightEnv(ctx);
288
+ if (!(await playwrightVersion({ env, projectRoot: ctx.projectRoot }))) return [];
260
289
  if (turn.mode === 0) return []; // a ghost turn leaves no screenshots and opens no browser
261
290
  // Only for a turn that asks for what a browser does. Its tool list goes into every call the CLI
262
291
  // makes inside the turn: a one-line change cost Codex 576 thousand tokens of reading, and the
263
292
  // browser it carried was never opened.
264
293
  if (turn.text !== undefined && !wantsBrowser(turn.text)) return [];
265
294
  // A browser known not to start is not handed to anyone: every call to it would fail.
266
- if (playwrightHealth({ browser: ctx.settings.browser ?? 'chromium', env: ctx.env, cwd: ctx.projectRoot })?.ok === false) return [];
295
+ if (playwrightHealth({ browser: ctx.settings.browser ?? 'chromium', env, cwd: ctx.projectRoot })?.ok === false) return [];
267
296
  const outputDir = turn.scratchDir ?? join(turn.roomDir ?? ctx.stateRoot, 'playwright');
268
- return [playwrightServerFor({ port: turn.port, outputDir, browser: ctx.settings.browser ?? 'chromium', headless: ctx.settings.headless !== false, servers: turn.servers ?? [] })];
297
+ return [playwrightServerFor({ port: turn.port, outputDir, browser: ctx.settings.browser ?? 'chromium', headless: ctx.settings.headless !== false, servers: turn.servers ?? [], preview: turn.preview ?? '/preview', prefix: env.npm_config_prefix ?? null })];
269
298
  },
270
299
  // Before it turns on, in one project or in all: the server starts and has its browser, or MADRE
271
300
  // fetches what is missing and asks again. `null` is ready; anything else is the refusal.