@jossuealcala/madre 1.1.2 → 1.1.4

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 (166) hide show
  1. package/CHANGELOG.en.md +40 -1
  2. package/CHANGELOG.md +40 -1
  3. package/README.en.md +3 -3
  4. package/README.md +3 -3
  5. package/SECURITY.md +11 -6
  6. package/TRADEMARKS.md +6 -2
  7. package/bin/madre.mjs +76 -11
  8. package/docs/REFERENCE.md +16 -10
  9. package/docs/SDK.md +36 -9
  10. package/docs/en/REFERENCE.md +12 -8
  11. package/docs/en/SDK.md +34 -8
  12. package/docs/en/training/README.md +1 -1
  13. package/docs/sdk/connector-module.mjs +1 -1
  14. package/docs/sdk/hello-module.mjs +39 -4
  15. package/docs/training/README.md +1 -1
  16. package/docs/training/train.sh +3 -0
  17. package/habilidades/explicamelo-facil/HABILIDAD.md +19 -0
  18. package/habilidades/hojas-de-calculo/HABILIDAD.md +18 -0
  19. package/habilidades/mensajes-a-clientes/HABILIDAD.md +19 -0
  20. package/habilidades/publicaciones-para-redes/HABILIDAD.md +19 -0
  21. package/habilidades/resumen-y-pendientes/HABILIDAD.md +18 -0
  22. package/habilidades/tu-pagina-paso-a-paso/HABILIDAD.md +19 -0
  23. package/package.json +7 -4
  24. package/public/activity.js +66 -22
  25. package/public/app.js +4947 -894
  26. package/public/assets/brand/OFL-SpaceGrotesk.txt +93 -0
  27. package/public/assets/brand/SpaceGrotesk-latin-ext.woff2 +0 -0
  28. package/public/assets/brand/SpaceGrotesk-latin.woff2 +0 -0
  29. package/public/assets/brand/madre-app-180.png +0 -0
  30. package/public/assets/brand/madre-app-192.png +0 -0
  31. package/public/assets/brand/madre-app-512.png +0 -0
  32. package/public/assets/brand/madre-app.svg +1 -1
  33. package/public/assets/brand/madre-favicon.svg +1 -1
  34. package/public/attribution.js +29 -19
  35. package/public/auto-open.js +102 -0
  36. package/public/brands.js +36 -19
  37. package/public/changes.js +63 -0
  38. package/public/en.js +1085 -102
  39. package/public/es.js +2940 -1656
  40. package/public/i18n.js +11 -0
  41. package/public/index.html +31 -27
  42. package/public/loader.js +322 -117
  43. package/public/macroverso.js +57 -355
  44. package/public/manual-content.js +69 -9
  45. package/public/manual.js +21 -6
  46. package/public/market-view.js +298 -84
  47. package/public/market.js +25 -2
  48. package/public/mcp-catalog.js +7 -2
  49. package/public/missions.js +169 -0
  50. package/public/news-scenes.js +292 -0
  51. package/public/nostromo-engine.js +935 -654
  52. package/public/notices.js +78 -0
  53. package/public/notifications.js +119 -0
  54. package/public/power.js +1 -1
  55. package/public/provider-marks.js +170 -0
  56. package/public/provider-pick.js +147 -0
  57. package/public/resay.js +4 -0
  58. package/public/review-ask.js +16 -13
  59. package/public/routing.js +29 -3
  60. package/public/salas-mac.css +467 -47
  61. package/public/salas-mac.html +8 -5
  62. package/public/salas-mac.js +805 -109
  63. package/public/salas.css +2 -2
  64. package/public/salas.html +2 -2
  65. package/public/salas.js +1 -1
  66. package/public/starters.js +128 -0
  67. package/public/styles.css +3036 -340
  68. package/public/subscription.js +303 -0
  69. package/public/terms-field.js +170 -0
  70. package/public/terms.js +117 -19
  71. package/public/tips.js +158 -0
  72. package/public/tour-chapters.js +88 -88
  73. package/public/tour.js +364 -46
  74. package/public/troubleshooting.js +313 -27
  75. package/public/welcome-scene.js +446 -0
  76. package/public/welcome.js +827 -282
  77. package/src/adapters/claude.mjs +2 -1
  78. package/src/adapters/codex.mjs +2 -1
  79. package/src/adapters/cursor.mjs +9 -6
  80. package/src/adapters/gemini-rest.mjs +236 -0
  81. package/src/adapters/gemini.mjs +13 -7
  82. package/src/adapters/grok.mjs +290 -0
  83. package/src/adapters/madre.mjs +71 -23
  84. package/src/adapters/opencode.mjs +15 -2
  85. package/src/adapters/process.mjs +14 -3
  86. package/src/adapters/steps.mjs +176 -0
  87. package/src/app-invite.mjs +90 -0
  88. package/src/auth-probe.mjs +32 -0
  89. package/src/billing-key.mjs +8 -0
  90. package/src/billing.mjs +317 -0
  91. package/src/bridge/policy.mjs +1 -1
  92. package/src/capabilities.mjs +46 -10
  93. package/src/chats.mjs +44 -2
  94. package/src/checkpoint.mjs +119 -1
  95. package/src/codex-route.mjs +113 -0
  96. package/src/commands.mjs +5 -2
  97. package/src/credentials.mjs +46 -8
  98. package/src/dataset.mjs +18 -7
  99. package/src/directives.mjs +1 -0
  100. package/src/event-store.mjs +25 -2
  101. package/src/extensions.mjs +5 -1
  102. package/src/ficha.mjs +158 -0
  103. package/src/files.mjs +36 -2
  104. package/src/image-studio.mjs +13 -3
  105. package/src/install-metrics.mjs +9 -3
  106. package/src/lease.mjs +6 -1
  107. package/src/looks.mjs +4 -1
  108. package/src/market-check.mjs +1 -1
  109. package/src/market-remote.mjs +135 -1
  110. package/src/mcp/image-server.mjs +59 -90
  111. package/src/mcp/memory-server.mjs +10 -0
  112. package/src/memory-tools.mjs +3 -0
  113. package/src/memory.mjs +29 -4
  114. package/src/models.mjs +21 -3
  115. package/src/modules/ahp.mjs +10 -4
  116. package/src/modules/bishop-exam.mjs +41 -12
  117. package/src/modules/bishop.mjs +2 -2
  118. package/src/modules/choices.mjs +12 -10
  119. package/src/modules/fetch-alone.mjs +7 -0
  120. package/src/modules/github.mjs +6 -2
  121. package/src/modules/helpers.mjs +23 -5
  122. package/src/modules/image-providers.mjs +281 -0
  123. package/src/modules/image-studio.mjs +106 -39
  124. package/src/modules/index.mjs +61 -12
  125. package/src/modules/intents-observe.mjs +3 -1
  126. package/src/modules/isolated.mjs +160 -0
  127. package/src/modules/ollama.mjs +35 -6
  128. package/src/modules/playwright.mjs +78 -20
  129. package/src/modules/reminders.mjs +42 -2
  130. package/src/modules/ripley.mjs +2 -1
  131. package/src/modules/run-alone.mjs +122 -0
  132. package/src/modules/runs.mjs +11 -8
  133. package/src/modules/sdk.mjs +10 -3
  134. package/src/notices-key.mjs +8 -0
  135. package/src/notices.mjs +185 -0
  136. package/src/ollama.mjs +57 -15
  137. package/src/opencode-health.mjs +1 -1
  138. package/src/outbound.mjs +124 -13
  139. package/src/quota-sources.mjs +148 -3
  140. package/src/review-ask.mjs +55 -31
  141. package/src/room/archivist.mjs +30 -5
  142. package/src/room/busy.mjs +16 -0
  143. package/src/room/changes.mjs +79 -0
  144. package/src/room/control.mjs +36 -6
  145. package/src/room/economy.mjs +1 -1
  146. package/src/room/guard.mjs +39 -2
  147. package/src/room/prompt.mjs +49 -6
  148. package/src/room/vectors.mjs +7 -1
  149. package/src/room.mjs +181 -49
  150. package/src/router.mjs +1 -1
  151. package/src/runs.mjs +39 -0
  152. package/src/runtime-detection.mjs +46 -6
  153. package/src/salas.mjs +181 -18
  154. package/src/server.mjs +1101 -118
  155. package/src/service.mjs +116 -0
  156. package/src/setup-trouble.mjs +20 -1
  157. package/src/setup.mjs +1 -1
  158. package/src/skill-check.mjs +269 -0
  159. package/src/skills-import.mjs +128 -0
  160. package/src/skills.mjs +502 -0
  161. package/src/terms.mjs +23 -5
  162. package/src/tour.mjs +31 -5
  163. package/src/updates.mjs +47 -4
  164. package/src/web-preview.mjs +181 -0
  165. package/src/whats-new.mjs +121 -1
  166. package/src/rumbo.mjs +0 -337
@@ -32,6 +32,8 @@ import bishop from './bishop.mjs';
32
32
  import mcpConnect from './mcp-connect.mjs';
33
33
  import { isSalasRoom } from '../salas.mjs';
34
34
  import { defineModule, matchRoute, understandsSdk } from './sdk.mjs';
35
+ import { settingsIn } from '../module-scope.mjs';
36
+ import { fencedTools, permissionArgs, runExternal } from './isolated.mjs';
35
37
  import { builtinFile, newer, readBuiltinRecord, trustedBytes } from '../builtin-updates.mjs';
36
38
 
37
39
  // The lab: modules that are built and tested but not offered yet, because they are not finished
@@ -72,7 +74,9 @@ function checkExternal(module, { replace = false } = {}) {
72
74
  // replaced, because that is what installing a newer copy of it is.
73
75
  if (taken && (!replace || !taken.external)) throw new Error(`the id "${module.id}" is already taken`);
74
76
  for (const route of module.routes ?? []) {
75
- const path = typeof route.path === 'string' ? route.path : route.path?.source ?? '';
77
+ // A pattern may start with «^», as MADRE's own do: /^\/api\/x\/<id>\/…$/ was refused, and the
78
+ // person who wrote it was told to live where they already lived (2026-11-09, a report on Facebook).
79
+ const path = typeof route.path === 'string' ? route.path : String(route.path?.source ?? '').replace(/^\^/, '');
76
80
  if (!path.startsWith(`/api/x/${module.id}/`) && !path.startsWith(`\\/api\\/x\\/${module.id}\\/`)) throw new Error(`route ${path} must live under /api/x/${module.id}/`);
77
81
  }
78
82
  return module;
@@ -91,23 +95,26 @@ async function importModuleFile(file) {
91
95
  // never the module itself. src/modules/check-alone.mjs answers with it.
92
96
  export async function inspectModuleFile(file) {
93
97
  const module = await importModuleFile(file);
98
+ const snapshot = JSON.parse(JSON.stringify(module, (_, value) => value instanceof RegExp ? { madreRegExp: value.source, flags: value.flags } : value));
94
99
  return {
95
100
  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),
96
101
  routes: (module.routes ?? []).map((route) => ({ path: typeof route.path === 'string' ? route.path : { source: route.path?.source ?? '' } })),
102
+ snapshot,
103
+ hooks: Object.fromEntries(['describe', 'onEvent', 'toolsForTurn', 'updatePlan', 'detect', 'preflight', 'installCommand', 'setControl', 'toggle', 'scope'].map((key) => [key, typeof module[key] === 'function'])),
104
+ routeHooks: (module.routes ?? []).map((route) => typeof route.handler === 'function'),
105
+ slashHooks: (module.slash ?? []).map((command) => ({ execute: typeof command.execute === 'function', available: typeof command.available === 'function' })),
97
106
  };
98
107
  }
99
108
 
100
109
  // Loads a candidate in a node of its own, fenced by Node's permission model (check-alone.mjs says
101
110
  // what it may and may not do), so that asking what a file is never runs it inside MADRE.
102
111
  const CHECK_ALONE = fileURLToPath(new URL('./check-alone.mjs', import.meta.url));
103
- const PACKAGE_ROOT = fileURLToPath(new URL('../..', import.meta.url));
104
112
  export const CHECK_MS = 15000;
105
- const FENCE = ['--permission', '--experimental-permission'].find((flag) => process.allowedNodeEnvironmentFlags.has(flag)) ?? null;
106
113
  async function inspectAlone(probe) {
107
- const [folder, root] = await Promise.all([realpath(dirname(probe)), realpath(PACKAGE_ROOT)]);
108
- const fence = FENCE ? [FENCE, `--allow-fs-read=${folder}`, `--allow-fs-read=${root}`] : [];
114
+ const [folder, canonical] = await Promise.all([realpath(dirname(probe)), realpath(probe)]);
115
+ const fence = permissionArgs(canonical);
109
116
  return new Promise((done, fail) => {
110
- execFile(process.execPath, [...fence, CHECK_ALONE, join(folder, basename(probe))], { env: {}, cwd: folder, timeout: CHECK_MS, maxBuffer: 1 << 20, windowsHide: true }, (error, stdout, stderr) => {
117
+ execFile(process.execPath, [...fence, CHECK_ALONE, canonical], { env: {}, cwd: folder, timeout: CHECK_MS, maxBuffer: 1 << 20, windowsHide: true }, (error, stdout, stderr) => {
111
118
  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`));
112
119
  const said = String(stdout ?? '').split('\n').reverse().map((line) => { try { return JSON.parse(line); } catch { return null; } }).find((one) => one && typeof one.ok === 'boolean');
113
120
  if (!said) return fail(new Error(String(stderr ?? '').trim().split('\n').at(-1) || error?.message || 'it ended before saying what it is'));
@@ -118,6 +125,44 @@ async function inspectAlone(probe) {
118
125
  });
119
126
  }
120
127
 
128
+ const revive = (value) => {
129
+ if (Array.isArray(value)) return value.map(revive);
130
+ if (!value || typeof value !== 'object') return value;
131
+ if (typeof value.madreRegExp === 'string') return new RegExp(value.madreRegExp, value.flags ?? '');
132
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, revive(item)]));
133
+ };
134
+
135
+ function externalProxy(checked, file, origin) {
136
+ const snapshot = revive(checked.snapshot);
137
+ const invoke = (operation, ctx, args = [], index = null) => runExternal({
138
+ file, id: checked.id, configKey: snapshot.configKey, reaches: snapshot.reaches ?? [], operation, index, ctx, args,
139
+ });
140
+ const module = {
141
+ ...snapshot,
142
+ external: true, origin, file,
143
+ settingsFrom: (config, roomId = null) => ({ ...snapshot.defaults, ...settingsIn(config?.modules?.[snapshot.configKey] ?? {}, roomId) }),
144
+ describe: async (ctx) => ({ ...(await invoke('describe', ctx)), external: true, origin, file }),
145
+ routes: (snapshot.routes ?? []).map((route, index) => ({ ...route, handler: checked.routeHooks[index]
146
+ ? (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)
147
+ : null })),
148
+ slash: (snapshot.slash ?? []).map((command, index) => ({ ...command,
149
+ ...(checked.slashHooks[index]?.execute ? { execute: (ctx, args) => invoke('slash', ctx, [args], index) } : {}),
150
+ ...(checked.slashHooks[index]?.available ? { available: (ctx) => invoke('available', ctx, [], index) } : {}),
151
+ })),
152
+ };
153
+ for (const hook of ['onEvent', 'updatePlan', 'setControl', 'toggle', 'scope']) {
154
+ if (checked.hooks[hook]) module[hook] = (ctx, ...args) => invoke(hook, ctx, args);
155
+ }
156
+ for (const hook of ['detect', 'preflight', 'installCommand']) {
157
+ if (checked.hooks[hook]) module[hook] = (...args) => invoke(hook, {}, args);
158
+ }
159
+ module.toolsForTurn = checked.hooks.toolsForTurn ? async (ctx, turn) => {
160
+ try { return await fencedTools(await invoke('toolsForTurn', ctx, [turn]), { file, id: checked.id, reaches: snapshot.reaches ?? [], turn, outboundLog: ctx.env?.PULSE_OUTBOUND_LOG ?? null }); }
161
+ catch (error) { console.error(`MADRE module ${checked.id}: toolsForTurn failed: ${error.message}`); return []; }
162
+ } : null;
163
+ return Object.freeze(module);
164
+ }
165
+
121
166
  export async function loadExternalModules({ stateRoot, projectRoot }) {
122
167
  for (let index = MODULES.length - 1; index >= 0; index -= 1) if (MODULES[index].external) MODULES.splice(index, 1);
123
168
  loadFailures.length = 0;
@@ -132,8 +177,8 @@ export async function loadExternalModules({ stateRoot, projectRoot }) {
132
177
  for (const name of files) {
133
178
  const file = join(dir, name);
134
179
  try {
135
- const module = checkExternal(await importModuleFile(file));
136
- MODULES.push(Object.freeze({ ...module, external: true, origin, file }));
180
+ const module = checkExternal(externalProxy(await inspectAlone(file), file, origin));
181
+ MODULES.push(module);
137
182
  if (module.reaches) declareDestinations(module.id, module.reaches);
138
183
  } catch (error) {
139
184
  loadFailures.push({ file, origin, error: error.message });
@@ -186,8 +231,8 @@ export async function adoptBuiltinUpdates({ stateRoot, enabled = true, factoryKe
186
231
 
187
232
  // The one door every module comes through, whoever wrote it and wherever the text came from: it
188
233
  // is written to a scratch copy, loaded there in a fenced node of its own (inspectAlone) and checked
189
- // against the house rules. An installed module runs inside MADRE with the human's own permissions,
190
- // so the check is the point — and checking runs nothing in MADRE (2026-11-01, external review #1).
234
+ // against the house rules. Each later call also runs in a fenced process (RX-2); checking and
235
+ // running a human module never execute its JavaScript in MADRE's server process.
191
236
  // Checking installs nothing and touches no registry — asking what a file is must never change
192
237
  // what is loaded.
193
238
  export async function verifyModuleText({ text, name = null, replace = true }) {
@@ -216,7 +261,7 @@ export async function verifyModuleText({ text, name = null, replace = true }) {
216
261
  // installed (2026-10-25). Only what the file itself declares: where it reaches, the keys it asks
217
262
  // for, whether it hands tools to the agents or reads the conversations, the pages and commands it
218
263
  // adds, and whether it writes in the project. What the code does beyond that nobody can promise —
219
- // which is why the page also says, every time, that a module runs with the person's permissions.
264
+ // its declared destinations still need the person's review before installation.
220
265
  export function declaredBy(module) {
221
266
  return {
222
267
  reaches: (module.reaches ?? []).map(({ host, to, what, when }) => ({ host: host ?? null, to: to ?? null, what: what ?? null, when: when ?? null })),
@@ -240,7 +285,7 @@ export async function verifyBuiltinText({ text, id }) {
240
285
  try {
241
286
  const probe = join(scratch, `${id}.mjs`);
242
287
  await writeFile(probe, text);
243
- const module = await importModuleFile(probe);
288
+ const module = (await inspectAlone(probe)).snapshot;
244
289
  if (module.id !== id) throw new Error(`The file says it is "${module.id}", not "${id}".`);
245
290
  if (!understandsSdk(module.sdk)) throw new Error(`${id} needs contract ${module.sdk} of the SDK.`);
246
291
  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.`);
@@ -313,6 +358,10 @@ export async function describeModules(ctx) {
313
358
  // One flat list of every route a module serves, with the module attached.
314
359
  export function findModuleRoute(method, pathname) {
315
360
  for (const module of MODULES) {
361
+ // A module somebody installed answers only under its own /api/x/<id>/, whatever its pattern says:
362
+ // checking how a pattern starts let /\/api\/x\/<id>\/|\/api\/state/ through, and these routes are
363
+ // matched before MADRE's own (2026-11-09).
364
+ if (module.external && !String(pathname).startsWith(`/api/x/${module.id}/`)) continue;
316
365
  const hit = matchRoute(module.routes, method, pathname);
317
366
  if (hit) return { module, ...hit };
318
367
  }
@@ -40,7 +40,9 @@ const POSITIVE = new Set(['good', 'preference']);
40
40
  // A crash of the CLI is one of them too: it ended the turn before anything was answered.
41
41
  const NOT_THE_ANSWER = /rate.?limit|usage limit|quota|\b429\b|too many requests|overloaded|unavailable|HTTP 5\d\d|server error|not ready|not enabled|too long \(|does not know the model|is not found for|not supported|not logged in|\blog ?in\b|sign in|authenticat|unauthori[sz]ed|api.?key|ENOENT|ECONN|network|exited with code|shutting down|MADRE stopped while|waiting for the project/i;
42
42
  // Ledgers written before a STOP carried its own flag say so only in words.
43
- const STOPPED_WORDS = /stopped by the human|detenido por el humano|STOPALL/i;
43
+ // In either language the room wrote it: a turn the person stopped is not a turn that failed
44
+ // (2026-11-17: Spanish said «detenido por ti», now «lo detuviste tú», and neither was heard).
45
+ const STOPPED_WORDS = /stopped by the human|detenido por el humano|detenido por ti|detenida por ti|lo detuviste|STOPALL/i;
44
46
 
45
47
  /* ---------- what the reader keeps ---------- */
46
48
 
@@ -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 });
@@ -160,7 +183,10 @@ export function playwrightHealth({ browser = 'chromium', env = process.env, cwd
160
183
  if (env.PULSE_PLAYWRIGHT_CHECK === '0') return started.result;
161
184
  if (started.browser !== browser) started = { at: 0, result: null, asking: null, browser };
162
185
  if (!started.asking && now - started.at > 10 * 60 * 1000) {
163
- started.asking = check({ browser, env, cwd }).then((result) => { if (started.browser === browser) started = { at: Date.now(), result, asking: null, browser }; return result; }, () => { started.asking = null; return null; });
186
+ // Only this check writes its answer (Q-24): one forgotten, or asked before the person chose
187
+ // another browser and came back, arrives late and must not land over the newer one.
188
+ const asking = check({ browser, env, cwd }).then((result) => { if (started.asking === asking) started = { at: Date.now(), result, asking: null, browser }; return result; }, () => { if (started.asking === asking) started.asking = null; return null; });
189
+ started.asking = asking;
164
190
  }
165
191
  return started.result;
166
192
  }
@@ -169,7 +195,7 @@ export function forgetPlaywrightHealth(result = null, browser = null) { started
169
195
  // What the browser may open: this room, and the servers the human started from RUNS in this project
170
196
  // while they listen on 127.0.0.1. RIPLEY's sealed frame keeps no data, so an app that stores its
171
197
  // 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 = [] }) {
198
+ export function playwrightServerFor({ port, outputDir, browser = 'chromium', headless = true, servers = [], preview = '/preview', prefix = null }) {
173
199
  const origins = [port, ...servers.filter((one) => Number.isInteger(one) && one !== port)].flatMap((one) => [`http://127.0.0.1:${one}`, `http://localhost:${one}`]);
174
200
  const served = servers.filter((one) => Number.isInteger(one) && one !== port);
175
201
  return {
@@ -183,25 +209,44 @@ export function playwrightServerFor({ port, outputDir, browser = 'chromium', hea
183
209
  // recently added route first — so a blocked `*`, registered after both, wins over the
184
210
  // allowlist and aborts even this room with ERR_BLOCKED_BY_CLIENT.
185
211
  args: ['--no', '@playwright/mcp', '--', ...(headless ? ['--headless'] : []), '--isolated', '--browser', browser, '--allowed-origins', origins.join(';'), '--output-dir', outputDir, '--no-sandbox'],
186
- env: {},
212
+ // npx finds a server kept in MADRE's own folder only when told where it is.
213
+ env: prefix ? { npm_config_prefix: prefix } : {},
187
214
  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.`,
215
+ 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
216
  };
190
217
  }
191
218
 
219
+ // The download a turn starts when the switch is on and nothing is installed yet (2026-11-14): one at a
220
+ // time per MADRE, never on Windows (there the person installs it), and said to the person when it
221
+ // starts and when it ends, since it takes a few minutes.
222
+ let fetching = null;
223
+ export function fetchWhenAsked(ctx, env, { prepare = preparePlaywright } = {}) {
224
+ if (fetching || process.platform === 'win32') return fetching;
225
+ const browser = ctx.settings.browser ?? 'chromium';
226
+ fetching = (async () => {
227
+ await ctx.record?.('extension.preparing', { id: 'playwright', name: 'PLAYWRIGHT', browser, first: true });
228
+ const check = await prepare({ browser, env, cwd: ctx.projectRoot, stateRoot: ctx.stateRoot });
229
+ forgetPlaywrightHealth(check, browser);
230
+ await playwrightVersion({ env, projectRoot: ctx.projectRoot, fresh: true });
231
+ await ctx.record?.('extension.prepared', { id: 'playwright', name: 'PLAYWRIGHT', browser, ok: Boolean(check.ok), problem: check.ok ? null : String(check.problem ?? '').slice(0, 200) });
232
+ return check;
233
+ })().catch(() => null).finally(() => { fetching = null; });
234
+ return fetching;
235
+ }
236
+
192
237
  async function playwrightReady(ctx) {
193
238
  const browser = ctx.settings.browser ?? 'chromium';
194
- let check = await playwrightStarts({ browser, env: ctx.env, cwd: ctx.projectRoot });
239
+ let check = await playwrightStarts({ browser, env: await playwrightEnv(ctx), cwd: ctx.projectRoot });
195
240
  // Something missing: MADRE fetches it, then asks again, before saying anything to the person.
196
241
  if (!check.ok && process.platform !== 'win32') {
197
242
  await ctx.record('extension.preparing', { id: 'playwright', name: 'PLAYWRIGHT', browser });
198
- check = await preparePlaywright({ browser, env: ctx.env, cwd: ctx.projectRoot });
243
+ check = await preparePlaywright({ browser, env: await playwrightEnv(ctx), cwd: ctx.projectRoot, stateRoot: ctx.stateRoot });
199
244
  }
200
245
  forgetPlaywrightHealth(check, browser);
201
246
  if (check.ok) return null;
202
247
  // The server is there and only the browser is missing: say which one, and the one line that
203
248
  // installs it. Without the server, both lines.
204
- const version = await playwrightVersion({ env: ctx.env, projectRoot: ctx.projectRoot });
249
+ const version = await playwrightVersion({ env: await playwrightEnv(ctx), projectRoot: ctx.projectRoot });
205
250
  return { status: 412, body: { error: version
206
251
  ? 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
252
  : 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' } };
@@ -215,7 +260,10 @@ export default defineModule({
215
260
  summary: 'Hands an agent a headless browser that reaches only this project and the servers you start from COMMANDS, on the turns that ask to look at a page, click through it, read its console or take screenshots.',
216
261
  creates: ['nothing in the project \u00b7 screenshots land in .pulse/out/<turn>/', 'a switch in ~/.pulse/config.json', 'a browser per turn, started and stopped by the CLI', 'no origin but this project is reachable through it'],
217
262
  requires: ['@playwright/mcp and the browser you choose for it (chromium by default) on this machine', 'PREVIEW on, to have pages to open'],
218
- settings: { enabled: false, browser: 'chromium', headless: true },
263
+ // On from the start (2026-11-14, the author: «vienen activas por defecto y el usuario las desactiva si
264
+ // quiere»). What it needs is fetched the first time a turn asks for a browser (toolsForTurn), not
265
+ // when MADRE is installed: someone who never tests a page never downloads one.
266
+ settings: { enabled: true, browser: 'chromium', headless: true },
219
267
  card: 'switch',
220
268
  controls: [
221
269
  { key: 'browser', label: 'BROWSER', type: 'select', options: PLAYWRIGHT_BROWSERS, note: 'Which browser engine the agents drive.' },
@@ -231,12 +279,13 @@ export default defineModule({
231
279
  },
232
280
  ],
233
281
  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;
282
+ const env = await playwrightEnv(ctx);
283
+ const version = await playwrightVersion({ env, projectRoot: ctx.projectRoot });
284
+ const health = ctx.settings.enabled && version ? playwrightHealth({ browser: ctx.settings.browser ?? 'chromium', env, cwd: ctx.projectRoot }) : null;
236
285
  return {
237
286
  runs: [{ name: PLAYWRIGHT_PACKAGE, version }],
238
287
  settings: { browser: ctx.settings.browser ?? 'chromium', headless: ctx.settings.headless !== false },
239
- status: { installed: Boolean(ctx.settings.enabled), detail: ctx.settings.enabled ? (!version ? t('on · the browser server is not installed') : health?.ok === false ? t('on · the browser does not start: {problem}. Turn it off and on again: MADRE downloads what is missing.', { problem: String(health.problem).replace(/[.\s]+$/, '').slice(0, 160) }) : `${t('on')} · ${ctx.settings.browser}`) : version ? t('off') : process.platform === 'win32' ? t('off · the browser server is not installed') : t('off · turn it on and MADRE installs its browser; it takes a few minutes') },
288
+ status: { installed: Boolean(ctx.settings.enabled), detail: ctx.settings.enabled ? (!version ? (process.platform === 'win32' ? t('on · the browser server is not installed') : t('on · it downloads the first time an AI opens your page')) : health?.ok === false ? t('on · the browser does not start: {problem}. Turn it off and on again: MADRE downloads what is missing.', { problem: String(health.problem).replace(/[.\s]+$/, '').slice(0, 160) }) : `${t('on')} · ${ctx.settings.browser}`) : version ? t('off') : process.platform === 'win32' ? t('off · the browser server is not installed') : t('off · turn it on and MADRE installs its browser; it takes a few minutes') },
240
289
  // Missing is not a reason to refuse the switch: turning it on installs what is missing
241
290
  // (playwrightReady) everywhere but Windows (2026-10-20). Only there does the person install it.
242
291
  preflight: version || process.platform !== 'win32' ? { ok: true, problems: [] } : { ok: false, problems: [t('Install the browser server first: {server}, then its browser: {browser}', { server: 'npm install -g @playwright/mcp', browser: installBrowserLine(ctx.settings.browser) })] },
@@ -247,25 +296,34 @@ export default defineModule({
247
296
  // where `npx --no` looks for it at turn time without downloading anything.
248
297
  async updatePlan(ctx, { latest = null } = {}) {
249
298
  const target = latest ? `${PLAYWRIGHT_PACKAGE}@${latest}` : PLAYWRIGHT_PACKAGE;
299
+ // Kept in MADRE's own folder, it is updated there.
300
+ const prefix = (await playwrightEnv(ctx)).npm_config_prefix;
301
+ const where = prefix ? ['--prefix', prefix] : [];
250
302
  return {
251
303
  command: 'npm',
252
- args: ['install', '-g', target],
253
- display: `npm install -g ${target}`,
304
+ args: ['install', '-g', ...where, target],
305
+ display: `npm install -g ${[...where, target].join(' ')}`,
254
306
  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 }); },
307
+ after: async () => { await playwrightVersion({ env: await playwrightEnv(ctx), projectRoot: ctx.projectRoot, fresh: true }); },
256
308
  };
257
309
  },
258
310
  async toolsForTurn(ctx, turn) {
259
- if (!(await playwrightVersion({ env: ctx.env, projectRoot: ctx.projectRoot }))) return [];
311
+ const env = await playwrightEnv(ctx);
260
312
  if (turn.mode === 0) return []; // a ghost turn leaves no screenshots and opens no browser
313
+ if (!(await playwrightVersion({ env, projectRoot: ctx.projectRoot }))) {
314
+ // On but not yet on this computer: the first turn that wants a browser starts the download, and
315
+ // this turn goes on without one (the person is told it is on its way).
316
+ if (turn.text === undefined || wantsBrowser(turn.text)) fetchWhenAsked(ctx, env);
317
+ return [];
318
+ }
261
319
  // Only for a turn that asks for what a browser does. Its tool list goes into every call the CLI
262
320
  // makes inside the turn: a one-line change cost Codex 576 thousand tokens of reading, and the
263
321
  // browser it carried was never opened.
264
322
  if (turn.text !== undefined && !wantsBrowser(turn.text)) return [];
265
323
  // 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 [];
324
+ if (playwrightHealth({ browser: ctx.settings.browser ?? 'chromium', env, cwd: ctx.projectRoot })?.ok === false) return [];
267
325
  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 ?? [] })];
326
+ 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
327
  },
270
328
  // Before it turns on, in one project or in all: the server starts and has its browser, or MADRE
271
329
  // fetches what is missing and asks again. `null` is ready; anything else is the refusal.