@jossuealcala/madre 1.1.2 → 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 (101) hide show
  1. package/CHANGELOG.en.md +21 -1
  2. package/CHANGELOG.md +21 -1
  3. package/README.en.md +3 -3
  4. package/README.md +3 -3
  5. package/SECURITY.md +11 -6
  6. package/bin/madre.mjs +74 -11
  7. package/docs/REFERENCE.md +13 -7
  8. package/docs/SDK.md +8 -8
  9. package/docs/en/REFERENCE.md +10 -6
  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 +988 -171
  19. package/public/attribution.js +9 -0
  20. package/public/brands.js +27 -13
  21. package/public/en.js +1 -2
  22. package/public/es.js +834 -257
  23. package/public/index.html +3 -0
  24. package/public/macroverso.js +24 -5
  25. package/public/manual-content.js +32 -2
  26. package/public/market-view.js +116 -9
  27. package/public/market.js +15 -0
  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 +229 -26
  33. package/public/salas-mac.html +3 -0
  34. package/public/salas-mac.js +454 -37
  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 +514 -273
  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 +18 -7
  53. package/src/event-store.mjs +10 -2
  54. package/src/ficha.mjs +142 -0
  55. package/src/files.mjs +36 -2
  56. package/src/lease.mjs +5 -0
  57. package/src/market-check.mjs +1 -1
  58. package/src/market-remote.mjs +135 -1
  59. package/src/mcp/image-server.mjs +1 -1
  60. package/src/mcp/memory-server.mjs +10 -0
  61. package/src/memory-tools.mjs +3 -0
  62. package/src/memory.mjs +29 -4
  63. package/src/models.mjs +21 -3
  64. package/src/modules/ahp.mjs +8 -3
  65. package/src/modules/bishop-exam.mjs +41 -12
  66. package/src/modules/bishop.mjs +2 -2
  67. package/src/modules/choices.mjs +12 -10
  68. package/src/modules/fetch-alone.mjs +7 -0
  69. package/src/modules/helpers.mjs +23 -5
  70. package/src/modules/image-studio.mjs +13 -27
  71. package/src/modules/index.mjs +54 -11
  72. package/src/modules/isolated.mjs +160 -0
  73. package/src/modules/ollama.mjs +35 -6
  74. package/src/modules/playwright.mjs +46 -17
  75. package/src/modules/run-alone.mjs +122 -0
  76. package/src/modules/runs.mjs +11 -8
  77. package/src/modules/sdk.mjs +4 -2
  78. package/src/notices-key.mjs +8 -0
  79. package/src/notices.mjs +185 -0
  80. package/src/ollama.mjs +57 -15
  81. package/src/outbound.mjs +45 -8
  82. package/src/room/archivist.mjs +30 -5
  83. package/src/room/busy.mjs +16 -0
  84. package/src/room/control.mjs +36 -6
  85. package/src/room/guard.mjs +32 -2
  86. package/src/room/prompt.mjs +32 -5
  87. package/src/room/vectors.mjs +7 -1
  88. package/src/room.mjs +94 -28
  89. package/src/router.mjs +1 -1
  90. package/src/runs.mjs +39 -0
  91. package/src/runtime-detection.mjs +46 -6
  92. package/src/salas.mjs +151 -15
  93. package/src/server.mjs +577 -80
  94. package/src/service.mjs +116 -0
  95. package/src/setup-trouble.mjs +20 -1
  96. package/src/skill-check.mjs +269 -0
  97. package/src/skills-import.mjs +128 -0
  98. package/src/skills.mjs +492 -0
  99. package/src/tour.mjs +14 -3
  100. package/src/whats-new.mjs +48 -0
  101. package/src/rumbo.mjs +0 -337
package/src/server.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  import http from 'node:http';
4
4
  import { readFile, realpath, writeFile, mkdir, mkdtemp, cp, rename, access, rm, stat } from 'node:fs/promises';
5
- import { existsSync, openSync, rmSync } from 'node:fs';
5
+ import { existsSync, rmSync } from 'node:fs';
6
6
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
7
7
  import { probePort, framable } from './ports.mjs';
8
8
  import { ControlDesk } from './room/control.mjs';
@@ -15,13 +15,14 @@ import { promisify } from 'node:util';
15
15
 
16
16
  const execFileAsync = promisify(execFile);
17
17
  import { detectAgents, toolsPrefix } from './runtime-detection.mjs';
18
+ import { codexRoute } from './codex-route.mjs';
18
19
  import { EventStore } from './event-store.mjs';
19
20
  import { RoomMemory, travels as memoryTravels } from './memory.mjs';
20
21
  import { createEmbedder } from './embeddings.mjs';
21
22
  import { memoryServerFor } from './memory-tools.mjs';
22
23
  import { MotherChannel, CODE000_STRIKES } from './mother.mjs';
23
24
  import { ErrorSentinel } from './sentinel-errors.mjs';
24
- import { probeOllama, ollamaEmbedder, ollamaGenerate, ollamaInvoker, pullModel, ollamaVersions, ownOllamaServers } from './ollama.mjs';
25
+ import { probeOllama, ollamaEmbedder, ollamaGenerate, ollamaInvoker, patientFetch, pullModel, ollamaVersions, ownOllamaServers } from './ollama.mjs';
25
26
  import { recallForTurn } from './modules/enlaces.mjs';
26
27
  import { hardwareOnce, MODEL_TIERS } from './modules/local-models.mjs';
27
28
  import { browserAdvice, environmentOnce, openBrowser as openInBrowser } from './environment.mjs';
@@ -48,6 +49,9 @@ const OWN_MODULE_IDS = new Set(MODULES.map((one) => one.id));
48
49
  // Where the author's token for the usage widget is kept: a vault name no module can take (module
49
50
  // ids are kebab-case, src/modules/sdk.mjs), so no module ever reads it.
50
51
  export const OWNER_VAULT = 'madre_owner';
52
+ // What a room that found its project already open writes in start.log, in either language MADRE
53
+ // speaks (Q-1): Home reads the address that follows to say where the project is open.
54
+ export const ALREADY_OPEN = /(?:already open for this project|ya está abierta para este proyecto)(?:\s+(?:at|en))?\s+(http:\/\/127\.0\.0\.1:\d+)/g;
51
55
  let crashHandlersInstalled = false;
52
56
 
53
57
  // RIPLEY's bridge, injected into every page it renders: reports the page's path
@@ -96,18 +100,21 @@ import { spawn } from 'node:child_process';
96
100
  import { cpus, freemem, loadavg, totalmem } from 'node:os';
97
101
  import { discoverModels, groupOpenCode, openCodeHidden, parseCursorModels, parseGeminiModels, parseOpenCodeVerbose, providerLabel, OPENCODE_OWN } from './models.mjs';
98
102
  import { cursorOnlyAuto } from './adapters/cursor.mjs';
103
+ import { parseGrokModels } from './adapters/grok.mjs';
99
104
  // Cursor's own list of models (`cursor-agent --list-models`), kept a few minutes: reading it asks
100
105
  // Cursor's servers.
101
106
  const cursorModels = { at: 0, ids: [] };
107
+ // Grok's (`grok models`, 2026-11-06), kept as long: it asks xAI for the account's list.
108
+ const grokModels = { at: 0, list: null };
102
109
  // And Gemini's, from Google with the person's key.
103
110
  const geminiModels = { at: 0, ids: [] };
104
111
  import { observable } from './modules/intents-observe.mjs';
105
112
  import { summarizeHistory } from './history.mjs';
106
113
  import { migrateOpenCodeHealth, noteOpenCodeTurn, openCodeHealth, suggestOpenCodeModel } from './opencode-health.mjs';
107
- import { normalizeMode, setImageModule } from './capabilities.mjs';
114
+ import { normalizeMode, setAgentsViaApi, setImageModule } from './capabilities.mjs';
108
115
  import { resolveGeminiKey } from './image-studio.mjs';
109
116
  import { commandByName, listCommands, parseCommand } from './commands.mjs';
110
- import { listDirectory, searchFiles, readServable, storeAttachment, resolveInside, createEmptyFile, writeEdited, MAX_ATTACHMENT_BYTES, MAX_EDIT_BYTES } from './files.mjs';
117
+ import { listDirectory, searchFiles, readServable, storeAttachment, keepAttachment, attachmentPlaceRefused, ATTACHMENT_REFUSED, resolveInside, createEmptyFile, writeEdited, MAX_ATTACHMENT_BYTES, MAX_EDIT_BYTES } from './files.mjs';
111
118
  import { planFileOp, freeCopyPath, needsDesignationOnDisk, CREATIONS } from './file-ops.mjs';
112
119
  import { ServerSentinel } from './server-sentinel.mjs';
113
120
  import { Eyecat } from './eyecat-watch.mjs';
@@ -127,21 +134,26 @@ import { readHandoff, writeHandoff } from './bridge/handoff.mjs';
127
134
  import { changeHome, changeLooks, readHome, readLooks, changeRoomLook, roomLooks, WALLPAPER_BYTES, dropWallpaper, frameWallpaper, readWallpaper, saveWallpaper, wallpaperBytes } from './looks.mjs';
128
135
  import { localAiConfig, localAiFor, localAiPatch } from './local-ai.mjs';
129
136
  import { moduleOnIn, scopeView, settingsIn } from './module-scope.mjs';
137
+ import { chooseSkills, declaredBy as skillDeclares, installSkill, isSkillFile, loadSkills, readSkillText, removeSkill, shareSkill, skillState, skillStateIn, skillIdOf, SKILL_FILES, SKILL_STATES } from './skills.mjs';
138
+ import { findSkills, importSkills } from './skills-import.mjs';
139
+ import { ASKS as SKILL_ASKS, SKILL_LICENSES, SKILL_SHELVES, submissionDraft as skillDraft, writeSubmission as writeSkillSubmission } from './skill-check.mjs';
130
140
  import { COMMUNITY_LICENSES, COMMUNITY_SHELVES, MARKET_REPO, checkSubmission, submissionDraft, writeSubmission } from './market-check.mjs';
131
- import { forgetFromMarket, installFromMarket, installedFromMarket, keptCatalog, marketAnnounced, marketAnnouncements, marketNews, marketNewsSeen, refreshCatalog, updateFromMarket } from './market-remote.mjs';
141
+ import { currentNotices, noticeSeen, noticesUrl, readFeed, readNotice, refreshNotices, signNotice, signRetire } from './notices.mjs';
142
+ import { forgetFromMarket, installFromMarket, installSkillFromMarket, installedFromMarket, installedSkills, keptCatalog, marketAnnounced, marketAnnouncements, marketNews, marketNewsSeen, refreshCatalog, updateFromMarket, updateSkillsFromMarket } from './market-remote.mjs';
132
143
  // Not moved project by project: the Coordinator is Home's, Git has no switch, and Local AI keeps
133
144
  // its own list of projects (local-ai.mjs).
134
145
  const NOT_BY_PROJECT = new Set(['bishop', 'git-pulse', 'ollama']);
135
146
  import { heartbeat, installId } from './heartbeat.mjs';
136
147
  import { PRESENCE_EVERY_MS, environmentGauges, noteLifecycle, sayPresent } from './install-metrics.mjs';
137
- import { keepHistory, readGithub, readHistory, readNpm, rumboModel } from './rumbo.mjs';
138
148
  import { TERMS_LINKS, acceptTerms, cameFromBefore, readTerms } from './terms.mjs';
139
149
  import { activateLicense, licensedIds, releaseLicense } from './market-license.mjs';
140
- import { askRoom, associateProject, createProject, createSampleProject, defaultProjectsFolder, ensureSalasProject, forgetProject, isSalasRoom, knownRooms, listFolders, markProject, projectRoomId, roomComesUp, salasRoomId, startRoom, suggestProjects, universeOf } from './salas.mjs';
150
+ import { askRoom, associateProject, createProject, createSampleProject, defaultProjectsFolder, ensureSalasProject, forgetProject, isSalasRoom, keepOpenProject, knownRooms, listFolders, markProject, projectRoomId, roomComesUp, salasRoomId, startRoom, suggestProjects, universeOf } from './salas.mjs';
151
+ import { disableService, enableService, launcherScript, refreshLauncher, serviceState } from './service.mjs';
141
152
  import { parseWork, recentWork, WORK_SYSTEM, workPrompt } from './lobby-work.mjs';
142
153
  import { CHANNEL_HEADER, CORPUS_MAX, CORPUS_PER_HOUR, DELIVER_MAX, MAX_LIMIT as ENLACE_MAX_LIMIT, NO_SUCH_LINK, NOTICES as ENLACE_NOTICES, activeContracts, allowContract, askCorpus, askEnlace, askState, channelKey, countRecent, decideDelivery, deliverable, deliverNotes, deliversTo, linkTraffic, mayServe, noteCrossing, noticeEnlace, readInbox, readsFrom, recallContract, receiveDelivery, revokeContract, sameKey, servingRooms, signContract, trainContract } from './enlaces.mjs';
143
154
  import { readContinuity } from './modules/ahp.mjs';
144
155
  import { readAt } from './checkpoint.mjs';
156
+ import { FICHA_HEADER, FICHA_NEEDED, FICHA_PARAM, carriesFicha, ensureFicha, fichaCookie, fichaHeaders, fichaReader, openPrivateLog, previewKey, sameFicha, withFicha } from './ficha.mjs';
145
157
 
146
158
  const sourceDirectory = dirname(fileURLToPath(import.meta.url));
147
159
  const publicDirectory = join(sourceDirectory, '..', 'public');
@@ -217,7 +229,7 @@ export async function openUrl(url) {
217
229
 
218
230
  // PULSE_AGENT_TIMEOUT_MS applies to every agent; PULSE_<AGENT>_TIMEOUT_MS
219
231
  // (e.g. PULSE_CLAUDE_TIMEOUT_MS) overrides it for one.
220
- export function agentTimeoutsFromEnv(env = process.env, agentIds = ['codex', 'claude', 'gemini', 'opencode', 'cursor']) {
232
+ export function agentTimeoutsFromEnv(env = process.env, agentIds = ['codex', 'claude', 'gemini', 'opencode', 'cursor', 'grok']) {
221
233
  const timeouts = {};
222
234
  const shared = Number(env.PULSE_AGENT_TIMEOUT_MS);
223
235
  if (Number.isFinite(shared) && shared > 0) timeouts.default = shared;
@@ -285,8 +297,15 @@ export async function createPulseServer({
285
297
  licenseApi = null,
286
298
  // Ollama detection; tests hand in a fake probe. PULSE_OLLAMA=0 leaves Ollama alone entirely.
287
299
  ollamaProbe = process.env.PULSE_OLLAMA === '0' ? async () => ({ running: false, host: null, models: [], embedModel: null, chatModel: null, disabled: true }) : probeOllama,
300
+ // Whether every request has to carry the ficha (src/ficha.mjs). Only the CLI entry point
301
+ // (startPulse) turns it on, as it does the quota sources; a test that checks it turns it on too.
302
+ // `renewFicha`: asked when the browser is opened by this start; only Home acts on it, and makes a
303
+ // new one for this run. A project Home opens keeps Home's.
304
+ ficha: fichaOn = false,
305
+ renewFicha = false,
288
306
  }) {
289
307
  const root = stateRoot ?? process.env.PULSE_HOME ?? join(homedir(), '.pulse');
308
+ const currentFicha = fichaOn ? fichaReader(root) : async () => null;
290
309
  // Whether this copy had its random identifier before this run: without one it is a new install
291
310
  // (src/install-metrics.mjs, noteLifecycle).
292
311
  const hadInstallId = existsSync(join(root, 'install-id'));
@@ -305,20 +324,36 @@ export async function createPulseServer({
305
324
  const ripleyOn = async () => moduleOnHere(await readConfig(root), 'ripley');
306
325
  agentTimeouts ??= agentTimeoutsFromEnv();
307
326
  const detector = detect ?? (providedAgents ? null : detectAgents);
308
- const agents = providedAgents ?? await detector();
327
+ const refreshCodexRoute = async (agent) => agent.id === 'codex' && agent.route
328
+ ? { ...agent, route: await codexRoute() }
329
+ : agent;
330
+ const agents = await Promise.all((providedAgents ?? await detector()).map(refreshCodexRoute));
331
+ setAgentsViaApi(agents);
309
332
  const canonicalProjectRoot = await realpath(projectRoot).catch(() => resolve(projectRoot));
310
333
  const roomDir = join(root, 'rooms', projectRoomId(canonicalProjectRoot));
311
334
  // Whether this is the room of Salas (docs/MACROVERSO.md, fase 3d): the room whose project is
312
335
  // the notebook of Salas, decided once from real paths; the page carries the MACROVERSO key there.
313
336
  const salasRoom = isSalasRoom(canonicalProjectRoot, root);
337
+ if (fichaOn) await ensureFicha(root, { renew: renewFicha && salasRoom });
314
338
  // What left this machine. Every fetch this process makes — MADRE's own and any a module makes,
315
339
  // because a module runs in here and cannot opt out — goes through one wrapper and lands in a
316
340
  // line beside the ledger. Bodies, headers and query values are never in it. One room per
317
341
  // process holds the watch; a second would only log what the first already logged.
318
342
  const outbound = await new OutboundLog({ file: join(roomDir, 'outbound.jsonl') }).load();
343
+ // The local AI's own channel: the same watch, without Node's 300 s wait for a first byte
344
+ // (patientFetch in src/ollama.mjs, L-7). A test's fake reportFetch is used as it is.
345
+ let localFetch = reportFetch === globalThis.fetch ? patientFetch : reportFetch;
346
+ // Whether git is on this computer (D-5): the restore point taken before an AI writes needs it,
347
+ // and without it every #2, #3 and #4 failed with a bare «spawn git ENOENT». Asked when the room
348
+ // opens and again, at most once a minute, when a page is served; the page marks those modes.
349
+ let gitHere = true;
350
+ let gitAsked = 0;
351
+ const askGit = () => { gitAsked = Date.now(); execFile('git', ['--version'], { timeout: 5000 }, (error) => { gitHere = error?.code !== 'ENOENT'; }); };
352
+ askGit();
319
353
  const unwatchOutbound = outbound.install();
320
354
  process.env.PULSE_OUTBOUND_LOG = join(roomDir, 'outbound.jsonl');
321
355
  reportFetch = outbound.watch(reportFetch);
356
+ localFetch = outbound.watch(localFetch);
322
357
  marketFetch = outbound.watch(marketFetch);
323
358
 
324
359
  // Attachments live beside the room log, never inside the project, and belong to the project
@@ -337,8 +372,9 @@ export async function createPulseServer({
337
372
  // is taken only if that room also answers on its port.
338
373
  const answers = async (port) => Number.isInteger(port) && await fetch(`http://127.0.0.1:${port}/api/version`, { signal: AbortSignal.timeout(1500) }).then((response) => response.ok, () => false);
339
374
  if (held && Number.isInteger(held.pid) && held.pid !== process.pid && alive(held.pid) && await answers(held.port)) {
340
- const error = new Error(`MADRE is already open for this project at http://127.0.0.1:${held.port} (process ${held.pid}). Close that room first, or open another conversation inside it.`);
375
+ const error = new Error(t('MADRE is already open for this project at {address} (process {pid}). Close that room first, or open another conversation inside it.', { address: `http://127.0.0.1:${held.port}`, pid: held.pid }));
341
376
  error.code = 'ROOM_IN_USE';
377
+ error.port = held.port;
342
378
  throw error;
343
379
  }
344
380
  // The room is this one's now. A room that died in the middle of a turn left the project's .env
@@ -348,7 +384,7 @@ export async function createPulseServer({
348
384
  // The mark also says which project and which MADRE, for the bridge's list of rooms on the phone.
349
385
  let openPort = null;
350
386
  // Where the project is, too (src/salas.mjs): a room that is closed can be opened again from Salas.
351
- const markOpen = async (port) => { openPort = port; await mkdir(roomDir, { recursive: true }).catch(() => {}); await writeFile(openMark, JSON.stringify({ pid: process.pid, port, at: new Date().toISOString(), project: basename(canonicalProjectRoot), version: PACKAGE.version ?? null })).catch(() => {}); await markProject(roomDir, canonicalProjectRoot).catch(() => {}); };
387
+ const markOpen = async (port) => { openPort = port; await mkdir(roomDir, { recursive: true }).catch(() => {}); await writeFile(openMark, JSON.stringify({ pid: process.pid, port, at: new Date().toISOString(), project: basename(canonicalProjectRoot), version: PACKAGE.version ?? null })).catch(() => {}); await markProject(roomDir, canonicalProjectRoot, { port, keepOpen: true }).catch(() => {}); };
352
388
  // The phone (docs/MOBILE.md) is not offered in MADRE 1.0 (2026-10-11, hidden 2026-10-12): Safari
353
389
  // in HTTPS-only mode refuses the bridge's http, and the relay that fixes it is not built. Only a
354
390
  // copy run from source (FROM_SOURCE, above) on a Mac that turned it on — `phone.preview` in
@@ -377,7 +413,7 @@ export async function createPulseServer({
377
413
  async function closeOtherRooms() {
378
414
  const here = basename(roomDir);
379
415
  const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
380
- await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/close', { method: 'POST', body: {}, timeoutMs: 3000 }).catch(() => null)));
416
+ await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/close', { stateRoot: root, method: 'POST', body: {}, timeoutMs: 3000 }).catch(() => null)));
381
417
  let left = others;
382
418
  for (let tries = 0; tries < 60 && left.length; tries += 1) {
383
419
  await new Promise((resolve) => setTimeout(resolve, 250));
@@ -398,7 +434,7 @@ export async function createPulseServer({
398
434
  setTimeout(() => {
399
435
  server.close(() => {
400
436
  let log = 'ignore';
401
- try { log = openSync(join(roomDir, 'restart.log'), 'a'); } catch { /* no witness, still restart */ }
437
+ try { log = openPrivateLog(join(roomDir, 'restart.log')); } catch { /* no witness, still restart */ }
402
438
  const env = { ...process.env, PULSE_RESTARTED: '1' };
403
439
  delete env.PULSE_UPDATE_RESTART;
404
440
  const child = spawn(process.execPath, [...process.execArgv, ...next], { cwd: process.cwd(), detached: process.platform !== 'win32', windowsHide: true, stdio: ['ignore', log, log], env });
@@ -466,6 +502,9 @@ export async function createPulseServer({
466
502
  const read = await refreshCatalog({ stateRoot: root, fetchImpl: marketFetch, force, ...marketKeyed });
467
503
  const names = Object.fromEntries(MODULES.map((one) => [one.id, one.name]));
468
504
  if (read.catalog) await updateFromMarket({ ...marketTools(), catalog: read.catalog, names, remove: (id) => removeExternalModule({ id, stateRoot: root, projectRoot: canonicalProjectRoot }) }).catch(() => []);
505
+ // The ways of working got from the Market (H-4): a newer version installs itself, one taken
506
+ // back is removed, and one that would bring a program nobody accepted waits for the person.
507
+ if (read.catalog) await updateSkillsFromMarket({ stateRoot: root, projectRoot: canonicalProjectRoot, catalog: read.catalog, madre: PACKAGE.version, fetchImpl: marketFetch }).catch(() => null);
469
508
  // MADRE's own modules, newer from the Market and signed with the factory key (src/builtin-updates.mjs):
470
509
  // what came or was taken back is run from now on, in this project and in Home.
471
510
  if (read.catalog) {
@@ -481,6 +520,20 @@ export async function createPulseServer({
481
520
  await adoptBuiltinUpdates({ stateRoot: root, enabled: marketOn(), ...factoryKeyed }).catch((error) => console.error(`MADRE modules: ${error.message}`));
482
521
  void syncMarket().catch(() => null);
483
522
  const install = detectInstall({ projectRoot: canonicalProjectRoot });
523
+ // Home as a service of this computer (src/service.mjs, L-3): the script it starts with says the
524
+ // version and the PATH of now, and when the service started it the projects that were open come
525
+ // back, each on the port it keeps (L-6). Not waited for by the start.
526
+ const homeLauncher = () => launcherScript({ install, name: PACKAGE.name, version: PACKAGE.version, port: openPort ?? 4317, env: process.env });
527
+ const afterOpen = async () => {
528
+ if (!salasRoom || testMode) return;
529
+ await refreshLauncher({ stateRoot: root, launcher: homeLauncher() }).catch(() => false);
530
+ if (process.env.MADRE_SERVICE !== '1') return;
531
+ const here = basename(roomDir);
532
+ for (const one of await knownRooms(root).catch(() => [])) {
533
+ if (one.id === here || one.open || !one.keepOpen || !one.root) continue;
534
+ try { startRoom({ projectRoot: one.root, roomDir: join(root, 'rooms', one.id) }); } catch (error) { console.error(`MADRE could not reopen ${one.name}: ${error.message}`); }
535
+ }
536
+ };
484
537
  async function versionView({ force = false } = {}) {
485
538
  const check = await checkForUpdate({ name: PACKAGE.name, current: PACKAGE.version, cacheFile: join(root, 'updates.json'), fetchImpl: reportFetch, enabled: updatesEnabled(), force });
486
539
  return { project: canonicalProjectRoot, ...check, notes: Boolean(notesFor(PACKAGE.version)), name: PACKAGE.name, install, command: updateCommand(install, PACKAGE.name, check.latest ?? 'latest'), release: check.latest ? releaseUrl(PACKAGE.repository, check.latest, roomLanguage()) : null, envWins: process.env.PULSE_UPDATE_CHECK !== undefined };
@@ -587,7 +640,68 @@ export async function createPulseServer({
587
640
  } catch { /* the plain count below */ }
588
641
  return { bytes: freemem(), source: 'freemem' };
589
642
  }
643
+ let logsSyncedAt = 0;
644
+ // The author's own reading of what fails in every copy (src/telemetry.mjs, madre.run's
645
+ // /api/telemetry): the same token as the usage, the same copy run from source. Read once every ten
646
+ // minutes for the two that use it, the errors widget and madre-logs' filing: behind it is a heavy
647
+ // query, and madre.run's reads of the day ran out once (2026-11-04).
648
+ async function errorsReading() {
649
+ const kept = widgetReadings.get('errors');
650
+ if (kept && Date.now() - kept.at < 600000) return kept.reading;
651
+ const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
652
+ if (!token) return null;
653
+ const answer = await reportFetch(process.env.PULSE_TELEMETRY_READ_URL ?? 'https://madre.run/api/telemetry', { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(8000) }).catch(() => null);
654
+ const body = answer?.ok ? await answer.json().catch(() => null) : null;
655
+ const reading = body?.ok ? { available: true, ...body } : { available: false, status: answer?.status ?? 0 };
656
+ widgetReadings.set('errors', { at: Date.now(), reading });
657
+ return reading;
658
+ }
659
+ // The sentinel's reports kept at madre.run (its /v1/reports, functions/v1 of the landing), read with
660
+ // the same token as the diagnostics, only by the author's copy run from source.
661
+ async function sentinelReading() {
662
+ const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
663
+ if (!token) return null;
664
+ const answer = await reportFetch(process.env.PULSE_SENTINEL_READ_URL ?? 'https://madre.run/v1/reports', { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(8000) }).catch(() => null);
665
+ const body = answer?.ok ? await answer.json().catch(() => null) : null;
666
+ return Array.isArray(body?.reports) ? body.reports : null;
667
+ }
668
+ // THE AUTHOR'S NOTICES (Q-11, src/notices.mjs). Every copy asks madre.run for them on its own,
669
+ // with or without the diagnostics, and shows the ones signed with the author's key that are for it.
670
+ const NOTICES_KEY_FILE = process.env.MADRE_NOTICES_KEY_DIR ? join(process.env.MADRE_NOTICES_KEY_DIR, 'ed25519.pem') : join(homedir(), '.madre', 'avisos', 'ed25519.pem');
671
+ const noticesEnabled = async () => ((await readConfig(root).catch(() => ({})))?.notices?.enabled !== false);
672
+ async function noticesForPage() {
673
+ void refreshNotices({ stateRoot: root }).catch(() => null);
674
+ const place = await environmentOnce().catch(() => null);
675
+ const enabled = await noticesEnabled();
676
+ return { enabled, notices: await currentNotices({ stateRoot: root, version: PACKAGE.version, wsl: Boolean(place?.wsl), enabled }).catch(() => []) };
677
+ }
678
+ void refreshNotices({ stateRoot: root }).catch(() => null);
679
+ // Only the author writes them: the copy run from source, with the author's token and the private key.
680
+ async function ownerCanNotify() {
681
+ if (!FROM_SOURCE) return false;
682
+ const token = await readSecret(root, OWNER_VAULT, 'usage').catch(() => null);
683
+ return Boolean(token) && existsSync(NOTICES_KEY_FILE);
684
+ }
590
685
  async function homeWidget(kind) {
686
+ // The author's error log (src/madre-logs.mjs): read from this disk every time, so Home shows it
687
+ // as agents add and close errors. Only in the copy run from source, and only Home serves it.
688
+ if (kind === 'madrelogs') {
689
+ if (!FROM_SOURCE || !salasRoom) return null;
690
+ const { keepSync, readLogs, syncDiagnostics, syncSentinel } = await import('./madre-logs.mjs');
691
+ // The diagnostics filed on their own (src/madre-logs.mjs, syncDiagnostics): every ten minutes
692
+ // while the widget is read, with the author's token, never waited for by the reading.
693
+ // And the sentinel's reports, the failures people's copies could not explain (2026-11-08).
694
+ if (Date.now() - logsSyncedAt > 600000) {
695
+ logsSyncedAt = Date.now();
696
+ void (async () => {
697
+ const reading = await errorsReading();
698
+ if (Array.isArray(reading?.errors)) await keepSync(await syncDiagnostics({ groups: reading.errors }));
699
+ const reports = await sentinelReading();
700
+ if (Array.isArray(reports)) await keepSync({ ...(await syncSentinel({ reports })), label: 'Centinela' });
701
+ })().catch((error) => console.error(`MADRE could not file the diagnostics in madre-logs: ${error.message}`));
702
+ }
703
+ return readLogs();
704
+ }
591
705
  const kept = widgetReadings.get(kind);
592
706
  // madre.run's count moves once a day: the author's reading is kept ten minutes, the Mac's thirty seconds.
593
707
  if (kept && Date.now() - kept.at < (kind === 'usage' || kind === 'errors' ? 600000 : 30000)) return kept.reading;
@@ -599,7 +713,7 @@ export async function createPulseServer({
599
713
  } else if (kind === 'servers') {
600
714
  const rooms = await openProjects();
601
715
  const projects = await Promise.all(rooms.map(async (one) => {
602
- const answer = await askRoom(one.open.port, '/api/ports', { timeoutMs: 4000 });
716
+ const answer = await askRoom(one.open.port, '/api/ports', { stateRoot: root, timeoutMs: 4000 });
603
717
  if (answer.unreachable && answer.status === 412) return { id: one.id, name: one.name, preview: false, ports: [] };
604
718
  if (answer.unreachable || answer.outdated) return { id: one.id, name: one.name, unreachable: true, ports: [] };
605
719
  return { id: one.id, name: one.name, preview: true, ports: (answer.ports ?? []).map((port) => ({ port: port.port, status: port.status ?? null, command: port.command ?? null })) };
@@ -607,7 +721,7 @@ export async function createPulseServer({
607
721
  reading = { available: projects.some((one) => one.preview), projects };
608
722
  } else if (kind === 'memory' || kind === 'models') {
609
723
  const rooms = await openProjects();
610
- const projects = await Promise.all(rooms.map(async (one) => ({ id: one.id, name: one.name, ...(readinessOf(await askRoom(one.open.port, '/api/dataset', { timeoutMs: 6000 })) ?? { unreachable: true }) })));
724
+ const projects = await Promise.all(rooms.map(async (one) => ({ id: one.id, name: one.name, ...(readinessOf(await askRoom(one.open.port, '/api/dataset', { stateRoot: root, timeoutMs: 6000 })) ?? { unreachable: true }) })));
611
725
  reading = kind === 'memory'
612
726
  ? { available: projects.some((one) => !one.unreachable), projects }
613
727
  : { available: true, ollama: { running: Boolean(ollama.running), models: (ollama.models ?? []).map((model) => model.name).filter(Boolean) }, projects: await withLocalAi(projects) };
@@ -627,13 +741,8 @@ export async function createPulseServer({
627
741
  const body = answer?.ok ? await answer.json().catch(() => null) : null;
628
742
  reading = body?.ok ? { available: true, ...body, mine } : { available: false, status: answer?.status ?? 0 };
629
743
  } else if (kind === 'errors') {
630
- // The author's own reading of what fails in every copy (src/telemetry.mjs, madre.run's
631
- // /api/telemetry): the same token as the usage, the same copy run from source.
632
- const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
633
- if (!token) return null;
634
- const answer = await reportFetch(process.env.PULSE_TELEMETRY_READ_URL ?? 'https://madre.run/api/telemetry', { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(8000) }).catch(() => null);
635
- const body = answer?.ok ? await answer.json().catch(() => null) : null;
636
- reading = body?.ok ? { available: true, ...body } : { available: false, status: answer?.status ?? 0 };
744
+ reading = await errorsReading();
745
+ if (!reading) return null;
637
746
  } else if (kind === 'live' || kind === 'installs' || kind === 'environments') {
638
747
  // The author's board (madre.run's /api/metrics, 2026-10-30): copies on now and off, installs,
639
748
  // updates and uninstalls by day, and where they run. One reading for the three widgets, kept a
@@ -654,6 +763,7 @@ export async function createPulseServer({
654
763
  // day) — and a source that fails keeps its last good reading, said as old.
655
764
  const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
656
765
  if (!token) return null;
766
+ const { keepHistory, readGithub, readHistory, readNpm, rumboModel } = await import('./rumbo.mjs');
657
767
  const source = async (name, ttl, read) => {
658
768
  const kept = rumboSources.get(name);
659
769
  if (kept && Date.now() - (kept.tried ?? kept.at) < ttl) return kept;
@@ -675,10 +785,25 @@ export async function createPulseServer({
675
785
  reading = funnel.value || github.value || npm.value
676
786
  ? { available: true, ...rumboModel({ madre: funnel.value, github: github.value, npm: npm.value, history }), sources: { madre: { ...said(funnel), status: rumboStatus }, github: said(github), npm: said(npm) } }
677
787
  : { available: false, status: rumboStatus };
788
+ } else if (kind === 'notices') {
789
+ // The author's notices (Q-11, src/notices.mjs): what madre.run serves now, checked as every copy
790
+ // checks it. Only in the copy run from source that holds the author's token and the notices' key.
791
+ if (!(await ownerCanNotify())) return null;
792
+ const answer = await globalThis.fetch(noticesUrl(), { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) }).catch(() => null);
793
+ const data = answer?.ok ? await answer.json().catch(() => null) : null;
794
+ const feed = data ? readFeed(data) : null;
795
+ const now = Date.now();
796
+ reading = {
797
+ available: true,
798
+ read: Boolean(feed),
799
+ notices: (feed?.entries ?? []).map((entry) => readNotice(entry.notice)).filter(Boolean)
800
+ .map((one) => ({ ...one, when: now < Date.parse(one.from) ? 'later' : now >= Date.parse(one.until) ? 'over' : 'now' })),
801
+ unverified: Math.max(0, (data?.notices?.length ?? 0) - (feed?.entries?.length ?? 0)),
802
+ };
678
803
  } else if (kind === 'coordinator' && !salasRoom) {
679
804
  // Home's page is served by every project too: the Coordinator's record is its own room's.
680
805
  const coordinator = (await knownRooms(root)).find((one) => one.id === salasRoomId(root));
681
- const answer = coordinator?.open ? await askRoom(coordinator.open.port, '/api/salas/widget?kind=coordinator', { timeoutMs: 6000 }) : null;
806
+ const answer = coordinator?.open ? await askRoom(coordinator.open.port, '/api/salas/widget?kind=coordinator', { stateRoot: root, timeoutMs: 6000 }) : null;
682
807
  reading = answer && !answer.unreachable && !answer.outdated ? answer : { available: false };
683
808
  } else if (kind === 'coordinator') {
684
809
  const notes = memory ? memory.memories({ limit: 5000 }) : [];
@@ -691,7 +816,7 @@ export async function createPulseServer({
691
816
  }
692
817
  async function lobbyGlance(one) {
693
818
  if (!one.open) { lobbyGlances.delete(one.id); return null; }
694
- const reading = await askRoom(one.open.port, '/api/glance?census=1', { timeoutMs: 1200 });
819
+ const reading = await askRoom(one.open.port, '/api/glance?census=1', { stateRoot: root, timeoutMs: 1200 });
695
820
  if (!reading.unreachable && !reading.outdated) {
696
821
  lobbyGlances.set(one.id, { port: one.open.port, reading, at: Date.now() });
697
822
  return reading;
@@ -735,7 +860,7 @@ export async function createPulseServer({
735
860
  function wireLocal(target) {
736
861
  if (!target) return;
737
862
  target.setInvoker('ollama', localWiring.archivist);
738
- target.setInvoker(MADRE_ADAPTER, localWiring.madre ? madreInvoker({ memory, ollama: () => ({ ...ollama, chatModel: ollama.madreModel ?? ollama.chatModel }), fetchImpl: reportFetch }) : null);
863
+ target.setInvoker(MADRE_ADAPTER, localWiring.madre ? madreInvoker({ memory, ollama: () => ({ ...ollama, chatModel: ollama.madreModel ?? ollama.chatModel }), fetchImpl: localFetch }) : null);
739
864
  }
740
865
  const ollamaSettings = async () => ({ enabled: true, embeddings: true, archivist: true, agent: true, ...((await readConfig(root)).modules?.ollama ?? {}) });
741
866
  // Whether this project uses the local AI at all, as Home decides it (src/local-ai.mjs).
@@ -879,7 +1004,7 @@ export async function createPulseServer({
879
1004
  const embedder = createEmbedder({ key, env: embedEnvFor(await memoryConfig()), ollama: useEmbeddings ? ollama : null, ollamaEmbedder });
880
1005
  if (room) room.setEmbedder(embedder); else memory.attachEmbedder(embedder);
881
1006
  }
882
- localWiring.archivist = useArchivist ? ollamaInvoker({ host: ollama.host, model: ollama.chatModel, fetchImpl: reportFetch }) : null;
1007
+ localWiring.archivist = useArchivist ? ollamaInvoker({ host: ollama.host, model: ollama.chatModel, fetchImpl: localFetch }) : null;
883
1008
  // @madre: the fifth agent, present whenever Ollama has a chat model and the human left it on.
884
1009
  const fifth = madreAgent({ ...ollama, chatModel: ollama.madreModel ?? ollama.chatModel }, { enabled: settings.enabled && settings.agent !== false });
885
1010
  const index = agents.findIndex((agent) => agent.id === MADRE_AGENT_ID);
@@ -964,6 +1089,19 @@ export async function createPulseServer({
964
1089
  return /^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) && (site === undefined || site === 'same-origin' || site === 'none') && request.headers.origin === `http://${host}`;
965
1090
  };
966
1091
  const onlyPressed = (mode) => !overrideSettings(overrideConfig).keys[mode].startsWith('phrase');
1092
+ // Installing a module by hand still asks for the #4 key (2026-11-02, external review #5):
1093
+ // before, any program on the computer
1094
+ // installed one with a single POST and it ran the next time the modules loaded. The answer is
1095
+ // the refusal to send, or null when the key holds.
1096
+ const moduleKeyRefused = (request, payload) => {
1097
+ const now = Date.now();
1098
+ while (keyMisses.length && keyMisses[0] < now - 60000) keyMisses.shift();
1099
+ if (keyMisses.length >= 8) return [429, { error: t('Too many wrong confirmations. Wait a minute and try again.') }];
1100
+ if (onlyPressed(4) && !pressedHere(request)) return [403, { error: t('This is confirmed from MADRE\'s own page, on this computer.') }];
1101
+ if (keyHolds(overrideConfig, { mode: 4, words: payload?.words })) return null;
1102
+ keyMisses.push(now);
1103
+ return [403, { error: t('That is not it. Try again, or cancel.'), denied: true }];
1104
+ };
967
1105
  const PASS_ONCE_MS = 30 * 60 * 1000;
968
1106
  // `asked` is a window the human chose on an agent's request for this mode (2026-10-14): one of
969
1107
  // the windows the project allows, never longer, and only for that agent and mode.
@@ -995,6 +1133,12 @@ export async function createPulseServer({
995
1133
  }
996
1134
  let listening = null;
997
1135
  const listeningPort = () => listening?.address?.()?.port ?? Number(process.env.PULSE_PORT ?? 4317);
1136
+ // Where the agents' headless browser opens RIPLEY's preview (src/modules/playwright.mjs): under the
1137
+ // preview's key when the ficha is on, since that browser has no cookie.
1138
+ const previewBase = async () => {
1139
+ const ficha = fichaOn ? await currentFicha() : null;
1140
+ return ficha ? `/preview/${previewKey(ficha)}` : '/preview';
1141
+ };
998
1142
  // One CONTROL desk for the whole project, shared by every conversation alive at once: a single
999
1143
  // holder of the working tree whichever chat asked, and an UNDO that works from any of them.
1000
1144
  const controlDesk = new ControlDesk({ projectRoot, guardRecord: join(roomDir, 'guard.json') });
@@ -1007,7 +1151,14 @@ export async function createPulseServer({
1007
1151
  controlDesk,
1008
1152
  privacy,
1009
1153
  // Modules may hand tools to a turn; the room asks once per turn, the server knows the port.
1010
- toolsForTurn: async (turn) => modulesToolsForTurn(await moduleContext(), { ...turn, port: listeningPort(), roomDir }),
1154
+ toolsForTurn: async (turn) => modulesToolsForTurn(await moduleContext(), { ...turn, port: listeningPort(), roomDir, preview: await previewBase() }),
1155
+ // Ways of working this project keeps (H-2): read from disk each turn, so a skill the person just
1156
+ // installed or switched is in the very next message, and chosen against what was asked.
1157
+ skillsForTurn: async (turn) => {
1158
+ const { loaded, failures } = await loadSkills({ stateRoot: root, projectRoot: canonicalProjectRoot });
1159
+ for (const one of failures) console.error(`MADRE skills: ${one.dir} was not read (${one.error})`);
1160
+ return chooseSkills({ skills: loaded, text: turn.text, config: await readConfig(root), roomId: scopeRoom }).chosen;
1161
+ },
1011
1162
  // What BISHOP reads for a turn is recorded in that turn's conversation, not the open one.
1012
1163
  bishopForTurn: salasRoom ? async (turn) => moduleById('bishop').promptForTurn({ ...(await moduleContext()), record: (type, payload) => ((turn.turn && liveRooms().find((one) => one.runningTurn?.(turn.turn))) || room).record(type, payload) }, turn) : null,
1013
1164
  // Fase 3e: notes a link with automatic recall brings to a turn. Never in the room of Salas
@@ -1321,15 +1472,19 @@ export async function createPulseServer({
1321
1472
  async function redetectAgents({ announce = true } = {}) {
1322
1473
  if (!detector) return { changed: false, agents };
1323
1474
  let changed = false;
1324
- for (const next of await detector()) {
1475
+ for (const found of await detector()) {
1476
+ const next = await refreshCodexRoute(found);
1325
1477
  const index = agents.findIndex((item) => item.id === next.id);
1326
1478
  if (index === -1) { agents.push(next); changed = true; continue; }
1327
1479
  const before = agents[index];
1328
- if (before.detected !== next.detected || before.ready !== next.ready || before.version !== next.version || before.path !== next.path || JSON.stringify(before.route ?? null) !== JSON.stringify(next.route ?? null)) {
1329
- agents[index] = { ...before, ...next };
1480
+ if (before.detected !== next.detected || before.ready !== next.ready || before.version !== next.version || before.path !== next.path || before.adapter !== next.adapter || JSON.stringify(before.route ?? null) !== JSON.stringify(next.route ?? null)) {
1481
+ // `viaApi` goes when the CLI arrives: a spread would keep the old one.
1482
+ agents[index] = { ...before, ...next, viaApi: next.viaApi };
1483
+ if (!next.viaApi) delete agents[index].viaApi;
1330
1484
  changed = true;
1331
1485
  }
1332
1486
  }
1487
+ setAgentsViaApi(agents);
1333
1488
  await refreshSessions();
1334
1489
  if (changed && announce) {
1335
1490
  await room.record('agents.updated', {
@@ -1346,7 +1501,8 @@ export async function createPulseServer({
1346
1501
  async function installAgent(id) {
1347
1502
  const agent = agents.find((item) => item.id === id);
1348
1503
  if (!agent) return { status: 404, body: { error: t('Unknown agent: {id}.', { id }) } };
1349
- if (agent.detected) return { status: 409, body: { error: t('{label} is already installed.', { label: agent.label }) } };
1504
+ // Gemini answering through its API with only a key is not its CLI: that one can still be installed.
1505
+ if (agent.detected && !agent.viaApi) return { status: 409, body: { error: t('{label} is already installed.', { label: agent.label }) } };
1350
1506
  const plan = installPlanFor(agent, { prefix: toolsPrefix() });
1351
1507
  if (!plan) return { status: 404, body: { error: t('MADRE does not know how to install {id}.', { id }) } };
1352
1508
  if (!plan.command) return { status: 409, body: { error: t('{label} installs with its own installer: copy the command into a terminal, then check again.', { label: agent.label }) } };
@@ -1653,7 +1809,15 @@ export async function createPulseServer({
1653
1809
  unsubscribe = room.subscribe(() => { void broadcastPending(); });
1654
1810
  unsubscribeModules = wireModules(room, chatId);
1655
1811
  unsubscribeAsks = trackAsks(room, historicalEvents);
1656
- unsubscribeSentinel = room.subscribe((event) => { void sentinel.observe(event).catch(() => null); countForDiagnostics(event); });
1812
+ unsubscribeSentinel = room.subscribe((event) => {
1813
+ void sentinel.observe(event).catch(() => null);
1814
+ countForDiagnostics(event);
1815
+ if (event?.type === 'extension.install.started') installLine = null;
1816
+ else if (event?.type === 'extension.install.output') {
1817
+ const said = (event.payload?.lines ?? []).map((line) => String(line).replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').trim()).filter((line) => line && !/^[\s{}\[\](),:;"'`]*$/.test(line)).at(-1);
1818
+ if (said) installLine = said.slice(0, 160);
1819
+ }
1820
+ });
1657
1821
  unsubscribeEyecat = room.subscribe((event) => { void eyecat.observe(event).catch(() => null); });
1658
1822
  unsubscribeGhost = room.subscribeGhost((event) => { for (const client of clients.keys()) writeEvent(client, event); });
1659
1823
  unsubscribeLive = room.subscribeLive((event) => { for (const client of clients.keys()) writeEvent(client, event); });
@@ -1717,7 +1881,7 @@ export async function createPulseServer({
1717
1881
  if (!one) continue;
1718
1882
  for (const item of one.activity()) now.push({ ...item, chat: id, chatTitle: titleOf(id) });
1719
1883
  }
1720
- if (installing) now.push({ kind: 'install', what: installing, model: pulling?.model ?? null, startedAt: installingSince || null });
1884
+ if (installing) now.push({ kind: 'install', what: installing, model: pulling?.model ?? null, startedAt: installingSince || null, line: installLine, stoppable: Boolean(pulling) });
1721
1885
  const done = await recentInProject(roomDir, { also: [chatId, ...parked.keys()] }).catch(() => []);
1722
1886
  return { room: thisRoomId, name: salasRoom ? null : basename(canonicalProjectRoot), home: salasRoom, version: PACKAGE.version ?? null, now, done };
1723
1887
  }
@@ -1919,10 +2083,11 @@ export async function createPulseServer({
1919
2083
  // The switches a room holds itself, as this project says them (module-scope.mjs). Read again
1920
2084
  // before every message, so a switch moved in Home reaches a project that is already open.
1921
2085
  function applyModuleSwitches(target, config) {
1922
- setImageModule(settingsIn(config.modules?.imageStudio ?? {}, scopeRoom));
2086
+ // Images, Options and Commands have no switch (2026-11-06): always on, whatever an old config says.
2087
+ setImageModule({ ...settingsIn(config.modules?.imageStudio ?? {}, scopeRoom), enabled: true });
1923
2088
  target.setAsh(moduleOnHere(config, 'ash'));
1924
- target.setChoices(moduleOnHere(config, 'choices'));
1925
- target.setRuns(moduleOnHere(config, 'runs'));
2089
+ target.setChoices(true);
2090
+ target.setRuns(true);
1926
2091
  }
1927
2092
 
1928
2093
  // Opening another conversation. The project keeps its memory, its crew, its modules, its
@@ -1990,6 +2155,10 @@ export async function createPulseServer({
1990
2155
  // When the install running now began, for «En marcha» (2026-10-30).
1991
2156
  let installingSince = 0;
1992
2157
  let pulling = null; // the model download running now, and how to stop it
2158
+ // What the install running now said last («pulling … 45%»), for «En marcha»: its row opened and
2159
+ // showed nothing (2026-11-06, the author). Ends with the install.
2160
+ let installLine = null;
2161
+ let lastPull = null; // what the last model download reported: { model, ok, detail, trouble }
1993
2162
 
1994
2163
  // Intenciones' reading of every conversation, kept per ledger file until that file changes.
1995
2164
  const observedLedgers = new Map();
@@ -2097,12 +2266,14 @@ export async function createPulseServer({
2097
2266
  }),
2098
2267
  ollama: {
2099
2268
  state: () => ollama,
2269
+ pulling: () => (pulling ? { model: pulling.model } : null),
2270
+ lastPull: () => lastPull,
2100
2271
  // One answer from the local model, for a module that reads something with it (SDK 2):
2101
2272
  // the model MADRE chose unless one is named. Nothing leaves this computer.
2102
2273
  generate: ({ model = null, system = null, prompt, json = false, timeoutMs = 60000, temperature = 0 } = {}) => {
2103
2274
  const chosen = model ?? ollama.madreModel ?? ollama.chatModel ?? null;
2104
2275
  if (!ollama.running || !chosen) return Promise.reject(new Error(t('The local AI is not running.')));
2105
- return ollamaGenerate({ host: ollama.host, model: chosen, system, prompt: String(prompt ?? ''), json, timeoutMs, temperature, fetchImpl: reportFetch });
2276
+ return ollamaGenerate({ host: ollama.host, model: chosen, system, prompt: String(prompt ?? ''), json, timeoutMs, temperature, fetchImpl: localFetch });
2106
2277
  },
2107
2278
  project: () => localAiHere(),
2108
2279
  setProject: (on) => setLocalAiHere(on),
@@ -2110,14 +2281,14 @@ export async function createPulseServer({
2110
2281
  // Getting Ollama onto this computer, with the command in plain sight, and waking it.
2111
2282
  install: async () => {
2112
2283
  if (installing) return { ok: false, error: t('Another install is running. Wait for it to finish and try again.') };
2113
- const { ollamaInstallPlan, adminHere } = await import('./modules/ollama.mjs');
2284
+ const { ollamaInstallPlan, adminHere, OLLAMA_INSTALL_MS } = await import('./modules/ollama.mjs');
2114
2285
  const plan = ollamaInstallPlan({ brew: await findOnPath('brew'), admin: await adminHere(), zstd: Boolean(await findOnPath('zstd')), apt: Boolean(await findOnPath('apt-get')) });
2115
2286
  if (!plan.command) return { ok: false, error: plan.note, download: plan.download, manual: plan.manual ? plan.display : null };
2116
2287
  installing = 'ollama'; installingSince = Date.now();
2117
2288
  await room.record('extension.install.started', { id: 'ollama', name: 'OLLAMA', command: plan.display, platforms: [], alreadyInstalled: false });
2118
2289
  void (async () => {
2119
2290
  const lines = [];
2120
- const result = await runInstaller({ command: plan.command, args: plan.args, projectRoot: canonicalProjectRoot, timeoutMs: 900000, onLine: (line) => { lines.push(line); void room.record('extension.install.output', { id: 'ollama', lines: [line.slice(0, 500)] }); } });
2291
+ const result = await runInstaller({ command: plan.command, args: plan.args, projectRoot: canonicalProjectRoot, timeoutMs: OLLAMA_INSTALL_MS, onLine: (line) => { lines.push(line); void room.record('extension.install.output', { id: 'ollama', lines: [line.slice(0, 500)] }); } });
2121
2292
  const status = await wireOllama();
2122
2293
  await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: result.code === 0, installed: Boolean(await findOnPath('ollama')), detail: result.code === 0 ? 'Ollama installed · START it to wake it' : (result.error ?? `exit ${result.code}`), trouble: result.code === 0 ? null : installTrouble(`${result.error ?? ''}\n${lines.slice(-20).join('\n')}`), ollama: status });
2123
2294
  installing = null;
@@ -2192,13 +2363,19 @@ export async function createPulseServer({
2192
2363
  await pullModel({ host: ollama.host, model, fetchImpl: reportFetch, signal: stopper.signal, onLine: (line) => { pending.push(line); if (!flushTimer) flushTimer = setTimeout(() => void flush(), 400); } });
2193
2364
  await flush();
2194
2365
  const status = await wireOllama();
2366
+ lastPull = { model, ok: true, detail: `pulled ${model}` };
2195
2367
  await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: true, installed: true, detail: `pulled ${model}`, model, ollama: status });
2196
2368
  } catch (error) {
2197
2369
  await flush();
2198
2370
  // Stopped on purpose: said as that, not as a failure.
2371
+ if (stopper.signal.aborted) lastPull = { model, ok: false, cancelled: true };
2199
2372
  if (stopper.signal.aborted) await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: false, installed: false, detail: 'cancelled', model, cancelled: true });
2200
- // Why it stopped, in one word the page says in plain words (src/setup-trouble.mjs).
2201
- else await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: false, installed: false, detail: error.message, model, trouble: installTrouble(error.message) });
2373
+ else {
2374
+ const trouble = error.trouble ?? installTrouble(error.message);
2375
+ lastPull = { model, ok: false, detail: error.message, trouble };
2376
+ // Why it stopped, in one word the page says in plain words (src/setup-trouble.mjs).
2377
+ await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: false, installed: false, detail: error.message, model, trouble });
2378
+ }
2202
2379
  } finally { installing = null; pulling = null; }
2203
2380
  })();
2204
2381
  return { ok: true };
@@ -2265,30 +2442,94 @@ export async function createPulseServer({
2265
2442
  clearTimeout(flushTimer);
2266
2443
  await flush();
2267
2444
  const after = await extension.detect(canonicalProjectRoot);
2445
+ const ok = result.code === 0 && after.installed;
2446
+ // Why it failed, for the diagnostics (D-10: two copies said only «install failed · ahp»): the
2447
+ // installer's own code when it prints one (AHP+ writes `"error": "GIT_REQUIRED"`), else the
2448
+ // kind of trouble its last lines show, else a command that ended well and installed nothing.
2449
+ // Words and codes only: the lines themselves carry paths and stay in the conversation.
2450
+ const said = lines.map((line) => line.match(/^\s*"error":\s*"([A-Z][A-Z0-9_]{2,40})"/)?.[1]).filter(Boolean).at(-1);
2268
2451
  await room.record('extension.install.finished', {
2269
2452
  id,
2270
2453
  name: extension.name,
2271
2454
  code: result.code,
2272
2455
  error: result.error ?? null,
2273
- ok: result.code === 0 && after.installed,
2456
+ ok,
2274
2457
  status: after,
2275
2458
  tail: lines.slice(-12),
2459
+ trouble: ok ? null : said ?? (result.code === 0 ? 'not-installed' : installTrouble(`${result.error ?? ''}\n${lines.slice(-20).join('\n')}`)),
2276
2460
  });
2277
2461
  installing = null;
2278
2462
  })();
2279
2463
  return { status: 202, body: { accepted: true, command: plan.display } };
2280
2464
  }
2281
2465
 
2466
+ // THE FICHA (src/ficha.mjs, 2026-11-02, external review #5). With it on, a request passes when it
2467
+ // carries the ficha (the page's cookie, or the header MADRE's own processes send) or is one of
2468
+ // the few that say nothing: the page's code, styles and pictures, and whether a MADRE answers here.
2469
+ // Everything else — every read, every change, the pages themselves — waits for it.
2470
+ const FICHA_PAGES = new Set(['/', '/salas']);
2471
+ const fichaFree = (method, pathname) => (method === 'GET' || method === 'HEAD') && !pathname.startsWith('/api/') && !pathname.startsWith('/preview/') && !FICHA_PAGES.has(pathname);
2472
+ const PREVIEW_ROUTE = /^\/preview\/(?:([0-9a-f]{32})\/)?(project|attachments)\/(.*)$/;
2473
+ // true when the request was answered here.
2474
+ async function fichaDoor(request, response, url) {
2475
+ const ficha = await currentFicha();
2476
+ // A page opened with the ficha in its address: the browser keeps it in a cookie, and the address
2477
+ // it shows (and remembers) is the same one without it.
2478
+ if (request.method === 'GET' && FICHA_PAGES.has(url.pathname) && url.searchParams.has(FICHA_PARAM) && ficha && sameFicha(url.searchParams.get(FICHA_PARAM), ficha)) {
2479
+ url.searchParams.delete(FICHA_PARAM);
2480
+ response.writeHead(303, { location: `${url.pathname}${url.search}`, 'set-cookie': fichaCookie(ficha), 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' });
2481
+ response.end();
2482
+ return true;
2483
+ }
2484
+ if (ficha && carriesFicha(request.headers, ficha)) return false;
2485
+ if (fichaFree(request.method, url.pathname)) return false;
2486
+ // RIPLEY's preview, under the key made from the ficha: a sealed frame sends no cookie.
2487
+ const preview = request.method === 'GET' ? url.pathname.match(PREVIEW_ROUTE) : null;
2488
+ if (preview?.[1] && ficha && sameFicha(preview[1], previewKey(ficha))) return false;
2489
+ // A link between projects, or the Coordinator's channel, carries the key of its own
2490
+ // (src/enlaces.mjs), kept in a file as private as the ficha; those routes check it again.
2491
+ if ((url.pathname.startsWith('/api/enlace/') || url.pathname.startsWith('/api/x/bishop/')) && typeof request.headers[CHANNEL_HEADER] === 'string') {
2492
+ const key = await channelKey(root).catch(() => null);
2493
+ if (key && sameKey(request.headers[CHANNEL_HEADER], key)) return false;
2494
+ }
2495
+ // Whether a MADRE answers on this port, and which: Home and the CLI ask it before anything
2496
+ // else. Nothing more without the ficha — not the project's folder, not the copy's identifier.
2497
+ if (request.method === 'GET' && url.pathname === '/api/version') {
2498
+ sendJson(response, 200, { name: PACKAGE.name, current: PACKAGE.version });
2499
+ return true;
2500
+ }
2501
+ if (request.method === 'GET' && FICHA_PAGES.has(url.pathname)) {
2502
+ response.writeHead(401, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', [FICHA_HEADER]: FICHA_NEEDED, ...PAGE_GUARDS });
2503
+ response.end(fichaPage());
2504
+ return true;
2505
+ }
2506
+ response.writeHead(401, { 'content-type': 'application/json; charset=utf-8', [FICHA_HEADER]: FICHA_NEEDED });
2507
+ response.end(JSON.stringify({ error: t('This request does not carry MADRE\'s ficha. Open MADRE from its shortcut or from the address it wrote in the terminal.'), ficha: FICHA_NEEDED }));
2508
+ return true;
2509
+ }
2510
+ // What a tab without the ficha shows: where to open MADRE from, nothing of the project.
2511
+ const fichaPage = () => {
2512
+ const escape = (text) => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2513
+ return `<!doctype html><html lang="${roomLanguage()}"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>MADRE</title>`
2514
+ + '<body style="font:16px/1.5 system-ui,sans-serif;background:#0b0c0b;color:#e8eae6;margin:0;display:grid;place-items:center;min-height:100vh"><main style="max-width:34rem;padding:32px">'
2515
+ + `<h1 style="font-size:22px;margin:0 0 12px">${escape(t('This tab needs to be opened from MADRE'))}</h1>`
2516
+ + `<p>${escape(t('MADRE only answers to the browser it opened itself, so that no other program on this computer can read your projects or act in them.'))}</p>`
2517
+ + `<p>${escape(t('Open it again from its shortcut, or with npx @jossuealcala/madre, or paste the full address MADRE wrote in the terminal (the one that ends in ?ficha=…).'))}</p>`
2518
+ + '</main></body></html>';
2519
+ };
2520
+
2282
2521
  const server = http.createServer(async (request, response) => {
2283
2522
  const foreign = refuseForeign(request);
2284
2523
  if (foreign) return sendJson(response, 403, { error: t(foreign), guarded: true });
2285
2524
  const url = new URL(request.url, 'http://127.0.0.1');
2525
+ if (fichaOn && await fichaDoor(request, response, url)) return;
2286
2526
  // The project's own folder name, typed by the human. Declared at the top of the handler and
2287
2527
  // not beside the first route that happened to need it: a const sits in its temporal dead zone
2288
2528
  // until its own line runs, so any route above it threw instead of refusing.
2289
2529
  // Which machine serves the page, written into it (public/i18n.js, hostWords): the browser that
2290
2530
  // reads it may be on another one, a Mac looking at a Linux box, and must not say «Mac» there.
2291
- const withHost = (html) => html.replace('<head>', `<head>\n <meta name="madre-host" content="${JSON.stringify(hostFacts()).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')}">`);
2531
+ if (Date.now() - gitAsked > 60_000) askGit();
2532
+ const withHost = (html) => html.replace('<head>', `<head>\n <meta name="madre-host" content="${JSON.stringify({ ...hostFacts(), ...(gitHere ? {} : { git: false }) }).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')}">`);
2292
2533
  // A page of MADRE's own. Its files can vanish under a running copy (npx replaced its folder
2293
2534
  // with a newer version): then the page says so, instead of a failure (1.1.0 diagnostics).
2294
2535
  const pageHtml = async (name) => {
@@ -2309,7 +2550,7 @@ export async function createPulseServer({
2309
2550
  response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...PAGE_GUARDS });
2310
2551
  return response.end(html);
2311
2552
  }
2312
- if (request.method === 'GET' && ['/app.js', '/nostromo-engine.js', '/brands.js', '/troubleshooting.js', '/inquiry.js', '/i18n.js', '/es.js', '/resay.js', '/syntax.js', '/editor.js', '/routing.js', '/abduction.js', '/review-ask.js', '/loader.js', '/tour.js', '/tour-chapters.js', '/touch.js', '/attribution.js', '/power.js', '/wallpaper.js', '/neural.js', '/hardware.js', '/code-tools.js', '/market.js', '/market-view.js', '/market-art.js', '/welcome.js', '/remedy.js', '/icons.js', '/page-errors.js', '/activity.js', '/terms.js', '/mcp-catalog.js', '/manual.js', '/manual-content.js', '/manual-shots.js', '/en.js'].includes(url.pathname)) {
2553
+ if (request.method === 'GET' && ['/app.js', '/nostromo-engine.js', '/brands.js', '/troubleshooting.js', '/inquiry.js', '/i18n.js', '/es.js', '/resay.js', '/syntax.js', '/editor.js', '/routing.js', '/abduction.js', '/review-ask.js', '/loader.js', '/tour.js', '/tour-chapters.js', '/touch.js', '/attribution.js', '/power.js', '/wallpaper.js', '/neural.js', '/hardware.js', '/code-tools.js', '/market.js', '/market-view.js', '/market-art.js', '/welcome.js', '/welcome-scene.js', '/news-scenes.js', '/remedy.js', '/icons.js', '/page-errors.js', '/activity.js', '/notices.js', '/tips.js', '/terms.js', '/mcp-catalog.js', '/manual.js', '/manual-content.js', '/manual-shots.js', '/en.js'].includes(url.pathname)) {
2313
2554
  return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'text/javascript; charset=utf-8');
2314
2555
  }
2315
2556
  if (request.method === 'GET' && url.pathname === '/styles.css') {
@@ -2585,7 +2826,7 @@ export async function createPulseServer({
2585
2826
  const later = [];
2586
2827
  if (request.method === 'POST') {
2587
2828
  await Promise.all(known.filter((one) => one.open && one.id !== thisRoomId).map(async (one) => {
2588
- const answer = await askRoom(one.open.port, '/api/local-ai/apply', { method: 'POST', timeoutMs: 6000 });
2829
+ const answer = await askRoom(one.open.port, '/api/local-ai/apply', { stateRoot: root, method: 'POST', timeoutMs: 6000 });
2589
2830
  if (answer.unreachable || answer.outdated) later.push(one.name);
2590
2831
  }));
2591
2832
  }
@@ -2632,7 +2873,7 @@ export async function createPulseServer({
2632
2873
  port: one.open.port,
2633
2874
  here: one.id === here,
2634
2875
  accent: owns[one.id]?.accent ?? homeAccent,
2635
- glance: one.id === here ? null : await askRoom(one.open.port, '/api/glance'),
2876
+ glance: one.id === here ? null : await askRoom(one.open.port, '/api/glance', { stateRoot: root }),
2636
2877
  })));
2637
2878
  return sendJson(response, 200, { here, salas: salasRoomId(root), rooms: seen });
2638
2879
  }
@@ -2645,7 +2886,7 @@ export async function createPulseServer({
2645
2886
  const room = (await knownRooms(root)).find((one) => one.id === id);
2646
2887
  if (!room) return sendJson(response, 404, { error: t('MADRE does not know that project on this Mac.') });
2647
2888
  if (!room.open) return sendJson(response, 200, { id, asleep: true });
2648
- const answer = await askRoom(room.open.port, `/api/memory?designation=${encodeURIComponent(room.name)}`, { timeoutMs: 4000 });
2889
+ const answer = await askRoom(room.open.port, `/api/memory?designation=${encodeURIComponent(room.name)}`, { stateRoot: root, timeoutMs: 4000 });
2649
2890
  if (answer.outdated) return sendJson(response, 200, { id, outdated: true });
2650
2891
  if (answer.unreachable) return sendJson(response, 200, { id, sealed: answer.status === 423, unreachable: answer.status !== 423 });
2651
2892
  return sendJson(response, 200, { id, ...universeOf(answer, { full: url.searchParams.get('full') === '1' }) });
@@ -2671,7 +2912,7 @@ export async function createPulseServer({
2671
2912
  // The commonest reason, said as itself: another MADRE (another Home, `madre start`) already
2672
2913
  // has this folder open, and one folder is one room. Where it is, so the person can go there.
2673
2914
  const said = (await readFile(join(root, 'rooms', room.id, 'start.log'), 'utf8').catch(() => '')).slice(logFrom);
2674
- const there = [...said.matchAll(/already open for this project\s+(http:\/\/127\.0\.0\.1:\d+)/g)].at(-1)?.[1];
2915
+ const there = [...said.matchAll(ALREADY_OPEN)].at(-1)?.[1];
2675
2916
  if (there) return sendJson(response, 409, { error: t('This project is already open in another MADRE, at {address}. Use that one, or close it there first.', { address: there }), address: there });
2676
2917
  return sendJson(response, 504, { error: t('The project did not open. What it said on the way up is in start.log, beside its record.') });
2677
2918
  }
@@ -2727,7 +2968,7 @@ export async function createPulseServer({
2727
2968
  if (!lobbyWork.running && (asked || due)) {
2728
2969
  lobbyWork.tried = Date.now();
2729
2970
  const language = roomLanguage() === 'en' ? 'en' : 'es';
2730
- lobbyWork.running = ollamaGenerate({ host: ollama.host, model, system: WORK_SYSTEM[language], prompt: workPrompt(items, language), fetchImpl: reportFetch, timeoutMs: 120000, temperature: 0.1 })
2971
+ lobbyWork.running = ollamaGenerate({ host: ollama.host, model, system: WORK_SYSTEM[language], prompt: workPrompt(items, language), fetchImpl: localFetch, timeoutMs: 120000, temperature: 0.1 })
2731
2972
  .then(async (answer) => {
2732
2973
  const bullets = parseWork(answer.text, items);
2733
2974
  if (!bullets.length) throw new Error('MADRE answered nothing the lobby could check against the conversations.');
@@ -2749,7 +2990,7 @@ export async function createPulseServer({
2749
2990
  lobbyDecisions.running = (async () => {
2750
2991
  const open = (await knownRooms(root)).filter((one) => one.open);
2751
2992
  const lists = await Promise.all(open.map(async (one) => {
2752
- const answer = await askRoom(one.open.port, `/api/memory?designation=${encodeURIComponent(one.name)}`, { timeoutMs: 6000 });
2993
+ const answer = await askRoom(one.open.port, `/api/memory?designation=${encodeURIComponent(one.name)}`, { stateRoot: root, timeoutMs: 6000 });
2753
2994
  if (!Array.isArray(answer?.memories)) return [];
2754
2995
  return answer.memories
2755
2996
  .filter((note) => note.kind === 'decision' && (note.zone === 'hold' || note.zone === 'bridge') && typeof note.text === 'string')
@@ -2803,20 +3044,22 @@ export async function createPulseServer({
2803
3044
  if (request.method === 'POST' && url.pathname === '/api/salas/close') {
2804
3045
  const payload = await body(request).catch(() => ({}));
2805
3046
  const room = (await knownRooms(root)).find((one) => one.id === payload.room);
3047
+ // Closed by the person: it does not come back when MADRE starts as a service (L-3).
3048
+ if (room) await keepOpenProject(root, room.id, false).catch(() => false);
2806
3049
  if (!room?.open) return sendJson(response, 200, { room: payload.room ?? null, closed: true });
2807
3050
  if (room.id === basename(roomDir)) {
2808
3051
  sendJson(response, 202, { room: room.id, closing: true, here: true });
2809
3052
  setTimeout(() => server.emit('madre:close'), 150);
2810
3053
  return undefined;
2811
3054
  }
2812
- const answer = await askRoom(room.open.port, '/api/room/close', { method: 'POST', body: {} });
3055
+ const answer = await askRoom(room.open.port, '/api/room/close', { stateRoot: root, method: 'POST', body: {} });
2813
3056
  if (answer.outdated) return sendJson(response, 409, { error: t('That project runs an older MADRE. Update it, or close it from its terminal.'), outdated: true });
2814
3057
  if (answer.unreachable) return sendJson(response, 502, { error: t('That project did not answer.') });
2815
3058
  return sendJson(response, 202, { room: room.id, closing: true });
2816
3059
  }
2817
3060
  if (request.method === 'POST' && url.pathname === '/api/salas/stop-all') {
2818
3061
  const rooms = (await knownRooms(root)).filter((one) => one.open);
2819
- const stopped = await Promise.all(rooms.map((one) => askRoom(one.open.port, '/api/stop-all', { method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer.unreachable && !answer.outdated)));
3062
+ const stopped = await Promise.all(rooms.map((one) => askRoom(one.open.port, '/api/stop-all', { stateRoot: root, method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer.unreachable && !answer.outdated)));
2820
3063
  return sendJson(response, 200, { rooms: rooms.length, stopped: stopped.filter(Boolean).length });
2821
3064
  }
2822
3065
  // Turning MADRE off (2026-10-16), from a page of this Mac only, after the person confirmed it.
@@ -2832,6 +3075,19 @@ export async function createPulseServer({
2832
3075
  setTimeout(() => server.emit('madre:close'), 150);
2833
3076
  return undefined;
2834
3077
  }
3078
+ // MADRE as a service of this Linux (src/service.mjs, L-3), from Home's Settings on this computer.
3079
+ if (url.pathname === '/api/madre/service' && (request.method === 'GET' || request.method === 'POST')) {
3080
+ const host = String(request.headers.host ?? '');
3081
+ if (!salasRoom || viaPhone || !/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) return sendJson(response, 403, { error: t('This is done from Home, on this computer.') });
3082
+ if (request.method === 'GET') return sendJson(response, 200, await serviceState());
3083
+ const site = request.headers['sec-fetch-site'];
3084
+ if ((site !== undefined && site !== 'same-origin' && site !== 'none') || request.headers.origin !== `http://${host}`) return sendJson(response, 403, { error: t('This is done from Home, on this computer.') });
3085
+ const payload = await body(request).catch(() => ({}));
3086
+ const state = payload?.on === true ? await enableService({ stateRoot: root, launcher: homeLauncher() }) : await disableService({ stateRoot: root });
3087
+ if (state.refused === 'install') return sendJson(response, 409, { ...state, error: t('This copy of MADRE was installed inside a project; install it with npx or npm -g to start it with the computer.') });
3088
+ if (state.refused) return sendJson(response, 500, { ...state, error: t('systemd did not turn the service on: {detail}', { detail: state.detail ?? '' }) });
3089
+ return sendJson(response, 200, state);
3090
+ }
2835
3091
  // Uninstalling MADRE (2026-10-29), from Home's Settings only (src/uninstall.mjs). GET says what
2836
3092
  // would go and what stays; POST, from a page of this computer, closes every open project the
2837
3093
  // way turning MADRE off does and — only once all of them closed — closes Home and takes away
@@ -2863,6 +3119,10 @@ export async function createPulseServer({
2863
3119
  // This room, asked to close by Salas: what is running stops and the room closes the way a
2864
3120
  // signal closes it (startPulse listens). Nothing here ends the process itself.
2865
3121
  if (request.method === 'POST' && url.pathname === '/api/room/close') {
3122
+ // From its own page, by the person: it stays closed when MADRE starts as a service (L-3).
3123
+ // Home turning everything off asks without it, and those come back.
3124
+ const payload = await body(request).catch(() => ({}));
3125
+ if (payload?.forget === true) await keepOpenProject(root, basename(roomDir), false).catch(() => false);
2866
3126
  sendJson(response, 202, { closing: true });
2867
3127
  setTimeout(() => server.emit('madre:close'), 150);
2868
3128
  return undefined;
@@ -2875,7 +3135,7 @@ export async function createPulseServer({
2875
3135
  if (viaPhone || !/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) || (site !== undefined && site !== 'same-origin' && site !== 'none') || request.headers.origin !== `http://${host}`) return sendJson(response, 403, { error: t('MADRE is restarted from its own page, on this computer.') });
2876
3136
  const here = basename(roomDir);
2877
3137
  const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
2878
- const asked = await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/restart', { method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer?.unreachable && !answer?.outdated).catch(() => false)));
3138
+ const asked = await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/restart', { stateRoot: root, method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer?.unreachable && !answer?.outdated).catch(() => false)));
2879
3139
  await room.record('room.restarting', { others: others.length });
2880
3140
  sendJson(response, 202, { restarting: true, others: others.length, stuck: others.filter((_, index) => !asked[index]).map((one) => one.name) });
2881
3141
  restartSelf(request.socket.localPort);
@@ -3256,7 +3516,7 @@ export async function createPulseServer({
3256
3516
  let one = await find();
3257
3517
  if (!one) return sendJson(response, 404, { error: t('MADRE does not know that project on this Mac.') });
3258
3518
  if (one.open) {
3259
- const answer = await askRoom(one.open.port, '/api/room/close', { method: 'POST', body: {} });
3519
+ const answer = await askRoom(one.open.port, '/api/room/close', { stateRoot: root, method: 'POST', body: {} });
3260
3520
  if (answer.outdated) return sendJson(response, 409, { error: t('That project runs an older MADRE. Update it, or close it from its terminal.'), outdated: true });
3261
3521
  if (answer.unreachable) return sendJson(response, 502, { error: t('That project did not answer.') });
3262
3522
  for (let tries = 0; tries < 40 && one?.open; tries += 1) { await new Promise((resolve) => setTimeout(resolve, 250)); one = await find(); }
@@ -3310,6 +3570,8 @@ export async function createPulseServer({
3310
3570
  phonePreview: viaPhone ? true : await phonePreview(),
3311
3571
  // The room of Salas knows it is: true only there, false in every other room.
3312
3572
  salas: salasRoom,
3573
+ // The longest message the room takes (D-15): a longer one goes as a text attachment.
3574
+ maxMessageChars,
3313
3575
  room: basename(roomDir),
3314
3576
  phones: viaPhone ? undefined : await phonePreview() ? (await readStore(root).catch(() => ({ devices: [] }))).devices.length : 0,
3315
3577
  // Which MADRE this is. The page prints it in the corner: the one fact a bug report
@@ -3513,11 +3775,19 @@ export async function createPulseServer({
3513
3775
  // (connect-src none), no forms, no top navigation, assets only from MADRE's
3514
3776
  // own host. Path-based, so a page's relative links to its CSS, JS and images
3515
3777
  // resolve to the same route.
3516
- const previewMatch = request.method === 'GET' && url.pathname.match(/^\/preview\/(project|attachments)\/(.*)$/);
3778
+ const previewMatch = request.method === 'GET' && url.pathname.match(PREVIEW_ROUTE);
3517
3779
  if (previewMatch) {
3518
3780
  if (!(await ripleyOn())) return sendJson(response, 412, { error: t('Preview is off. Enable it in MODULES to render files.') });
3519
- const which = previewMatch[1] === 'attachments' ? attachmentsRoot : canonicalProjectRoot;
3520
- const relative = decodeURIComponent(previewMatch[2]);
3781
+ // With the ficha on, the page's frame asks by the plain address (its cookie goes with it)
3782
+ // and is sent to the same one under the preview's key, where the sealed page's own CSS,
3783
+ // scripts and pictures — which carry no cookie — resolve by their relative links.
3784
+ const ficha = fichaOn ? await currentFicha() : null;
3785
+ if (ficha && !previewMatch[1]) {
3786
+ response.writeHead(307, { location: `/preview/${previewKey(ficha)}/${previewMatch[2]}/${previewMatch[3]}${url.search}`, 'cache-control': 'no-store' });
3787
+ return response.end();
3788
+ }
3789
+ const which = previewMatch[2] === 'attachments' ? attachmentsRoot : canonicalProjectRoot;
3790
+ const relative = decodeURIComponent(previewMatch[3]);
3521
3791
  const file = await readServable(which, relative);
3522
3792
  if (file.status !== 200) return sendJson(response, file.status, { error: file.error });
3523
3793
  const isPage = /\.(html?|xhtml)$/i.test(relative);
@@ -3552,10 +3822,42 @@ export async function createPulseServer({
3552
3822
  return sendJson(response, error.status ?? 400, { error: error.message });
3553
3823
  }
3554
3824
  const name = decodeURIComponent(request.headers['x-pulse-filename'] ?? url.searchParams.get('name') ?? 'attachment');
3825
+ // An empty file is the request's, not a broken route: refused in words, before it is stored,
3826
+ // and never counted as MADRE's failure in the diagnostics (D-8, one copy of 1.1.2).
3827
+ if (!bytes?.length) return sendJson(response, 400, { error: t('The file is empty: there is nothing to attach.') });
3555
3828
  const here = await scopeOf(url, response);
3556
3829
  if (here.error) return sendJson(response, 404, here);
3557
3830
  const record = await here.room.registerAttachment(await storeAttachment(attachmentsRoot, { name, bytes }));
3558
- return sendJson(response, 201, { attachment: { id: record.id, name: record.name, fileName: record.fileName, size: record.size, contentType: record.contentType, url: `/api/files?root=attachments&path=${encodeURIComponent(record.fileName)}` } });
3831
+ // A SKILL SOMEBODY SENT (C-1). The file a person drags in lands here, under the room, which
3832
+ // is one of the two places MADRE accepts a skill from; so what is left is recognising it.
3833
+ // Read from the bytes just stored: by its name (<id>.habilidad.md, as an agent writes one)
3834
+ // or because a .md turns out to read as a skill — which is what arrives by e-mail.
3835
+ let sent = null;
3836
+ if (/\.md$/i.test(record.name) && bytes.length <= 1024 * 1024) {
3837
+ try {
3838
+ const read = readSkillText(bytes.toString('utf8'), { id: skillIdOf(record.name) });
3839
+ sent = { id: read.id, name: read.name, when: read.when, version: read.version, body: read.body, unknown: read.unknown, declares: skillDeclares({ ...read, files: [], scripts: [] }), fileName: record.fileName };
3840
+ } catch { sent = isSkillFile(record.name) ? { error: t('That file is named like a skill, but MADRE cannot read it as one.') } : null; }
3841
+ }
3842
+ return sendJson(response, 201, { attachment: { id: record.id, name: record.name, fileName: record.fileName, size: record.size, contentType: record.contentType, url: `/api/files?root=attachments&path=${encodeURIComponent(record.fileName)}` }, ...(sent ? { skill: sent } : {}) });
3843
+ }
3844
+ // An attachment of the conversation, saved into the project where the person says (L-2,
3845
+ // src/files.mjs keepAttachment): a PDF into conocimiento/, a patient's photo into its folder.
3846
+ // The same steps as the attachment it comes from — the conversation it belongs to, MADRE's own
3847
+ // store — and the same guard as a new file from Archivos. Recorded in that conversation.
3848
+ if (request.method === 'POST' && url.pathname === '/api/attachments/keep') {
3849
+ const payload = await body(request).catch(() => ({}));
3850
+ const here = await scopeOf(url, response);
3851
+ if (here.error) return sendJson(response, 404, here);
3852
+ const to = String(payload.to ?? '').trim().replace(/^\/+/, '');
3853
+ if (attachmentPlaceRefused(to)) return sendJson(response, 403, { error: t(ATTACHMENT_REFUSED) });
3854
+ if (to && await needsDesignationOnDisk(canonicalProjectRoot, to) && !designationOk(payload.designation)) {
3855
+ return sendJson(response, 403, { error: t('This file is one the project guards. Type the project name to save it.'), guarded: true });
3856
+ }
3857
+ const kept = await keepAttachment({ attachmentsRoot, projectRoot: canonicalProjectRoot, fileName: String(payload.fileName ?? ''), to });
3858
+ if (kept.status !== 201) return sendJson(response, kept.status, { error: t(kept.error) });
3859
+ await here.room.record('project.file.created', { path: kept.path, from: 'attachment', bytes: kept.bytes });
3860
+ return sendJson(response, 201, { ok: true, path: kept.path, bytes: kept.bytes });
3559
3861
  }
3560
3862
  // The key for #3 and #4, checked here (src/override.mjs): what was typed, once or twice, and a
3561
3863
  // pass back for that agent and mode. Never from a phone: #3 and #4 are opened on the Mac.
@@ -3631,7 +3933,7 @@ export async function createPulseServer({
3631
3933
  await wireOllama();
3632
3934
  const later = [];
3633
3935
  await Promise.all((await knownRooms(root)).filter((one) => one.open && one.id !== thisRoomId).map(async (one) => {
3634
- const answer = await askRoom(one.open.port, '/api/local-ai/apply', { method: 'POST', timeoutMs: 6000 });
3936
+ const answer = await askRoom(one.open.port, '/api/local-ai/apply', { stateRoot: root, method: 'POST', timeoutMs: 6000 });
3635
3937
  if (answer.unreachable || answer.outdated) later.push(one.name);
3636
3938
  }));
3637
3939
  return sendJson(response, 200, { host, running: Boolean(ollama.running), models: (ollama.models ?? []).map((one) => one.name), later });
@@ -3906,6 +4208,8 @@ export async function createPulseServer({
3906
4208
  anthropic: agents.some((agent) => agent.id === 'claude' && agent.ready),
3907
4209
  ollama: Boolean(ollama.running),
3908
4210
  alive: true,
4211
+ // The same gate as sayHere: with the diagnostics, never from the author's own copies.
4212
+ presence: Boolean(await diagnosticsNow()) && !(await readSecret(root, OWNER_VAULT, 'usage').catch(() => null)),
3909
4213
  usage: FROM_SOURCE && Boolean(await readSecret(root, OWNER_VAULT, 'usage')),
3910
4214
  },
3911
4215
  }));
@@ -4131,11 +4435,14 @@ export async function createPulseServer({
4131
4435
  if (request.method === 'GET' && url.pathname === '/api/tour') {
4132
4436
  const state = await readTour(root);
4133
4437
  if (viaPhone || !fromHere) return sendJson(response, 200, { version: TOUR_VERSION, state, owed: false, returning: false, chapters: CHAPTERS, hints: HINTS, level: NEWS_LEVEL });
4134
- // Where this person comes from: the tour of 1.0 (path «since»), 0.7.2 (their words in a room's
4135
- // record, path «back»), or nowhere — a first install.
4136
- const from = state.path === 'since' || (!state.path && state.before === '1.0') ? '1.0' : (state.path ? state.path === 'back' : await cameBefore(root)) ? '0.7.2' : null;
4137
4438
  // `upgraded`: this copy was in use before 1.1.0 (src/terms.mjs): it meets the news, never the welcome of someone new.
4138
- return sendJson(response, 200, { version: TOUR_VERSION, state, owed: !state.bonjourAt, returning: Boolean(from), from, upgraded: await cameFromBefore(root), chapters: CHAPTERS, hints: HINTS, level: NEWS_LEVEL });
4439
+ const upgraded = await cameFromBefore(root);
4440
+ // Where this person comes from: the tour of 1.0 (path «since»), 0.7.2 (their words in a room's
4441
+ // record, path «back»), or nowhere — a first install. Words in a room are 0.7.2's only on a
4442
+ // copy from before 1.1.0 (Q-18, 2026-11-06): someone new who opened a project with `madre
4443
+ // start`, wrote, and reloaded before the bonjour was told «MADRE changed a lot since 0.7.2».
4444
+ const from = state.path === 'since' || (!state.path && state.before === '1.0') ? '1.0' : (state.path ? state.path === 'back' : upgraded && await cameBefore(root)) ? '0.7.2' : null;
4445
+ return sendJson(response, 200, { version: TOUR_VERSION, state, owed: !state.bonjourAt, returning: Boolean(from), from, upgraded, chapters: CHAPTERS, hints: HINTS, level: NEWS_LEVEL });
4139
4446
  }
4140
4447
  if (viaPhone || !fromHere || (request.method === 'POST' && request.headers.origin !== `http://${host}`)) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4141
4448
  if (request.method === 'POST' && url.pathname === '/api/tour') {
@@ -4209,7 +4516,7 @@ export async function createPulseServer({
4209
4516
  // What the new copy says on the way up lands beside the ledger: if it never comes back,
4210
4517
  // this file is the only witness.
4211
4518
  let log = 'ignore';
4212
- try { log = openSync(join(roomDir, 'update.log'), 'a'); } catch { /* no witness, still restart */ }
4519
+ try { log = openPrivateLog(join(roomDir, 'update.log')); } catch { /* no witness, still restart */ }
4213
4520
  const child = spawn(shell.file, shell.args, { cwd: canonicalProjectRoot, detached: process.platform !== 'win32', windowsHide: true, stdio: ['ignore', log, log], env: { ...process.env, PULSE_UPDATE_RESTART: '1' } });
4214
4521
  child.unref();
4215
4522
  setTimeout(() => process.exit(0), 200);
@@ -4218,6 +4525,44 @@ export async function createPulseServer({
4218
4525
  }, 300);
4219
4526
  return undefined;
4220
4527
  }
4528
+ // The author's notices (Q-11): the ones for this copy, «got it», and whether info and important
4529
+ // ones show (security ones always do).
4530
+ if (request.method === 'GET' && url.pathname === '/api/notices') {
4531
+ return sendJson(response, 200, await noticesForPage());
4532
+ }
4533
+ if (request.method === 'POST' && url.pathname === '/api/notices/seen') {
4534
+ const payload = await body(request).catch(() => ({}));
4535
+ if (!(await noticeSeen(root, payload.id))) return sendJson(response, 422, { error: t('No such notice.') });
4536
+ // Counted only where the anonymous diagnostics are on (src/telemetry.mjs decides): how many
4537
+ // copies saw a notice, never which.
4538
+ diagnostics.count(`notice.${payload.id}`);
4539
+ return sendJson(response, 200, { ok: true });
4540
+ }
4541
+ if (request.method === 'POST' && url.pathname === '/api/notices/settings') {
4542
+ const payload = await body(request).catch(() => ({}));
4543
+ if (typeof payload.enabled === 'boolean') await updateConfig(root, { notices: { enabled: payload.enabled } });
4544
+ return sendJson(response, 200, await noticesForPage());
4545
+ }
4546
+ // Writing one, or taking it back: only from this computer, only in the author's copy.
4547
+ if (request.method === 'POST' && (url.pathname === '/api/owner/notices' || url.pathname === '/api/owner/notices/retire')) {
4548
+ const address = request.socket.remoteAddress ?? '';
4549
+ if (viaPhone || !['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(address) || !(await ownerCanNotify())) return sendJson(response, 404, { error: t('Not found.') });
4550
+ const payload = await body(request).catch(() => ({}));
4551
+ const token = await readSecret(root, OWNER_VAULT, 'usage');
4552
+ const key = await readFile(NOTICES_KEY_FILE, 'utf8');
4553
+ let sent;
4554
+ try {
4555
+ sent = url.pathname.endsWith('/retire') ? { retire: signRetire(String(payload.id ?? ''), key) } : signNotice(payload.notice, key);
4556
+ } catch (error) {
4557
+ return sendJson(response, 422, { error: t(error.message) });
4558
+ }
4559
+ const answer = await globalThis.fetch(noticesUrl(), { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify(sent), signal: AbortSignal.timeout(10000) }).catch(() => null);
4560
+ const said = answer ? await answer.json().catch(() => ({})) : {};
4561
+ if (!answer?.ok) return sendJson(response, 502, { error: said.error ? t('madre.run said: {error}', { error: said.error }) : t('madre.run did not answer.') });
4562
+ widgetReadings.delete('notices');
4563
+ void refreshNotices({ stateRoot: root, force: true }).catch(() => null);
4564
+ return sendJson(response, 200, { ok: true, id: sent.notice?.id ?? sent.retire?.id });
4565
+ }
4221
4566
  if (request.method === 'POST' && url.pathname === '/api/updates/settings') {
4222
4567
  const patch = await body(request).catch(() => ({}));
4223
4568
  if (typeof patch.check === 'boolean') { updatesConfig = { ...updatesConfig, check: patch.check }; await updateConfig(root, { updates: updatesConfig }); await adoptBuiltinUpdates({ stateRoot: root, enabled: marketOn(), ...factoryKeyed }).catch(() => []); }
@@ -4344,11 +4689,12 @@ export async function createPulseServer({
4344
4689
  const result = await room.runExam(String(payload.which ?? ''), { findings: eyecat.findings() });
4345
4690
  return sendJson(response, result?.error ? 409 : 200, { ...result, exams: await room.exams() });
4346
4691
  }
4347
- // Somebody's own module, handed to MADRE from the panel. It runs inside MADRE with the
4348
- // human's permissions, so it goes through the same door as everything else: written to a
4349
- // scratch copy, imported there, checked against the house rules, and only then installed.
4692
+ // Somebody's own module, handed to MADRE from the panel. It goes through the same door as
4693
+ // everything else: checked in a fenced scratch copy, then installed for isolated calls.
4350
4694
  if (request.method === 'POST' && url.pathname === '/api/extensions/upload') {
4351
4695
  const payload = await body(request).catch(() => ({}));
4696
+ const refused = moduleKeyRefused(request, payload);
4697
+ if (refused) return sendJson(response, ...refused);
4352
4698
  const text = String(payload.text ?? '');
4353
4699
  const name = String(payload.name ?? 'module.mjs');
4354
4700
  if (!text.trim()) return sendJson(response, 400, { error: t('That file is empty.') });
@@ -4391,6 +4737,8 @@ export async function createPulseServer({
4391
4737
  return sendJson(response, 200, { origin, current: module.version ?? null, candidate: candidate.version ?? null, same: (candidate.version ?? null) === (module.version ?? null) });
4392
4738
  } catch (error) { return sendJson(response, 422, { error: error.message, origin }); }
4393
4739
  }
4740
+ const refused = moduleKeyRefused(request, payload);
4741
+ if (refused) return sendJson(response, ...refused);
4394
4742
  try {
4395
4743
  const installed = await installModuleText({ text, name: `${module.id}.mjs`, scope: module.origin === 'project' ? 'project' : 'user', stateRoot: root, projectRoot: canonicalProjectRoot, source: origin });
4396
4744
  await room.record('extension.installed', { id: installed.id, name: installed.name, origin: installed.origin, file: installed.file, version: installed.version, by: 'refresh' });
@@ -4415,7 +4763,7 @@ export async function createPulseServer({
4415
4763
  installing = module.id; installingSince = Date.now();
4416
4764
  await room.record('extension.install.started', { id: module.id, name: item.name, command: plan.display, platforms: [], alreadyInstalled: true });
4417
4765
  void (async () => {
4418
- const result = await runInstaller({ command: plan.command, args: plan.args, projectRoot: canonicalProjectRoot, timeoutMs: 900000, onLine: (line) => { void room.record('extension.install.output', { id: module.id, lines: [String(line).slice(0, 500)] }); } });
4766
+ const result = await runInstaller({ command: plan.command, args: plan.args, projectRoot: canonicalProjectRoot, timeoutMs: plan.timeoutMs ?? 900000, onLine: (line) => { void room.record('extension.install.output', { id: module.id, lines: [String(line).slice(0, 500)] }); } });
4419
4767
  // What the plan does once the command is done (Ollama: restart the old server). If it could
4420
4768
  // not, that is the outcome: «now runs <the old version>» would read as an update that worked.
4421
4769
  const settled = result.code === 0 ? await (async () => plan.after?.())().catch((error) => ({ ok: false, error: error.message })) : null;
@@ -4499,7 +4847,7 @@ export async function createPulseServer({
4499
4847
  return sendJson(response, 403, { error: t('A key is only accepted from this computer, never over the network.') });
4500
4848
  }
4501
4849
  const agent = agents.find((item) => item.id === id);
4502
- if (!agent?.detected) return sendJson(response, 412, { error: t('{label} is not installed on this computer.', { label: agent?.label ?? id }) });
4850
+ if (!agent?.detected && id !== 'gemini') return sendJson(response, 412, { error: t('{label} is not installed on this computer.', { label: agent?.label ?? id }) });
4503
4851
  if (!TAKES_KEY.has(id)) return sendJson(response, 400, { error: t('{agent} does not take a key here: it signs in with a click.', { agent: agent.label }) });
4504
4852
  const payload = await body(request).catch(() => ({}));
4505
4853
  const result = await applyKey({
@@ -4511,7 +4859,8 @@ export async function createPulseServer({
4511
4859
  probe: () => probeAgentAuth(agent),
4512
4860
  });
4513
4861
  if (!result.ok) return sendJson(response, 422, { error: result.error });
4514
- await refreshSessions();
4862
+ // A Gemini key with no CLI is how Gemini arrives (through its API): look again, not only at sessions.
4863
+ if (id === 'gemini' && !agent?.path) await redetectAgents(); else await refreshSessions();
4515
4864
  // What the room remembers: that a key was set, and for which provider. Never the key.
4516
4865
  await room.record('connection.key.set', { agent: id, label: agent.label, provider: payload.provider ?? null, detail: result.detail ?? null });
4517
4866
  return sendJson(response, 200, { ok: true, session: sessions[id] ?? null });
@@ -4571,7 +4920,14 @@ export async function createPulseServer({
4571
4920
  if (ids.length) Object.assign(cursorModels, { at: Date.now(), ids });
4572
4921
  return ids;
4573
4922
  };
4574
- return sendJson(response, 200, { models: await discoverModels({ agents, config: await readConfig(root), listOpenCode: url.searchParams.get('opencode') === '1' ? listOpenCode : async () => [], listCursor: url.searchParams.get('cursor') === '1' ? listCursor : async () => [], cursorOnlyAuto, listGemini: url.searchParams.get('gemini') === '1' ? listGemini : async () => [] }) });
4923
+ const listGrok = async (grok) => {
4924
+ if (grokModels.at && Date.now() - grokModels.at < 10 * 60 * 1000) return grokModels.list;
4925
+ const { stdout } = await execFileAsync(grok.path, ['models'], { timeout: 20000, env: { ...process.env, GROK_DISABLE_AUTOUPDATER: '1' } });
4926
+ const list = parseGrokModels(stdout);
4927
+ if (list.models.length) Object.assign(grokModels, { at: Date.now(), list });
4928
+ return list;
4929
+ };
4930
+ return sendJson(response, 200, { models: await discoverModels({ agents, config: await readConfig(root), listOpenCode: url.searchParams.get('opencode') === '1' ? listOpenCode : async () => [], listCursor: url.searchParams.get('cursor') === '1' ? listCursor : async () => [], cursorOnlyAuto, listGemini: url.searchParams.get('gemini') === '1' ? listGemini : async () => [], listGrok: url.searchParams.get('grok') === '1' ? listGrok : async () => ({ models: [], default: null }) }) });
4575
4931
  }
4576
4932
  // OpenCode's providers for AJUSTES: who has a key or an account, what each offers, which are
4577
4933
  // left out of the chooser. Never a key: only that one is there and of what kind.
@@ -4667,7 +5023,7 @@ export async function createPulseServer({
4667
5023
  if (url.searchParams.get('everywhere') !== '1') return sendJson(response, 200, mine);
4668
5024
  const others = (await knownRooms(root)).filter((one) => one.open && one.id !== thisRoomId);
4669
5025
  const answers = await Promise.all(others.map(async (one) => {
4670
- const answer = await askRoom(one.open.port, '/api/activity', { timeoutMs: 1500 });
5026
+ const answer = await askRoom(one.open.port, '/api/activity', { stateRoot: root, timeoutMs: 1500 });
4671
5027
  if (answer.unreachable) return null;
4672
5028
  if (answer.outdated) return { room: one.id, name: one.name, port: one.open.port, outdated: true, now: [], done: [] };
4673
5029
  return { ...answer, room: one.id, name: answer.name ?? one.name, port: one.open.port };
@@ -4688,7 +5044,7 @@ export async function createPulseServer({
4688
5044
  if (viaPhone) return sendJson(response, 403, { error: t('Other projects are stopped from this computer.') });
4689
5045
  const there = (await knownRooms(root)).find((one) => one.id === payload.room && one.open);
4690
5046
  if (!there) return sendJson(response, 404, { error: t('That project is not open any more.') });
4691
- const answer = await askRoom(there.open.port, '/api/activity/stop', { method: 'POST', body: { ...payload, room: null }, timeoutMs: 8000 });
5047
+ const answer = await askRoom(there.open.port, '/api/activity/stop', { stateRoot: root, method: 'POST', body: { ...payload, room: null }, timeoutMs: 8000 });
4692
5048
  if (answer.outdated) return sendJson(response, 409, { error: t('That project runs an older MADRE. Update it, or close it from its terminal.'), outdated: true });
4693
5049
  if (answer.unreachable) return sendJson(response, answer.status ?? 502, { error: answer.error ?? t('That project did not answer.') });
4694
5050
  return sendJson(response, 200, answer);
@@ -4703,6 +5059,11 @@ export async function createPulseServer({
4703
5059
  const id = String(payload.id ?? '');
4704
5060
  const cut = id.lastIndexOf(':');
4705
5061
  stopped = cut > 0 && where.stopRun({ responseMessageId: id.slice(0, cut), index: Number(id.slice(cut + 1)) });
5062
+ } else if (payload.kind === 'install' && pulling) {
5063
+ // A model downloading: the same stop as the welcome's and Local AI's. Other installs run to
5064
+ // the end; the row offers no stop for them.
5065
+ pulling.stopper.abort();
5066
+ stopped = true;
4706
5067
  }
4707
5068
  return sendJson(response, stopped ? 200 : 404, stopped ? { stopped: true } : { error: t('That is not running any more.') });
4708
5069
  }
@@ -4711,7 +5072,7 @@ export async function createPulseServer({
4711
5072
  let projects = 0;
4712
5073
  if (!viaPhone) {
4713
5074
  const others = (await knownRooms(root)).filter((one) => one.open && one.id !== thisRoomId);
4714
- const stopped = await Promise.all(others.map((one) => askRoom(one.open.port, '/api/stop-all', { method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer.unreachable && !answer.outdated)));
5075
+ const stopped = await Promise.all(others.map((one) => askRoom(one.open.port, '/api/stop-all', { stateRoot: root, method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer.unreachable && !answer.outdated)));
4715
5076
  projects = stopped.filter(Boolean).length;
4716
5077
  }
4717
5078
  return sendJson(response, 202, { stopped: true, ...result, projects });
@@ -4802,12 +5163,142 @@ export async function createPulseServer({
4802
5163
  void warmModuleUpdates(extensions);
4803
5164
  return sendJson(response, 200, { installing, extensions, failures: loadFailures, folders: moduleFolders({ stateRoot: root, projectRoot: canonicalProjectRoot }), sdk: SDK_PAGE[roomLanguage()] ?? SDK_PAGE.es });
4804
5165
  }
5166
+ // HABILIDADES (H-3): the ways of working this project keeps, each with what it tells the
5167
+ // agents, what it carries, and the word this project said about it. Read from disk every
5168
+ // time: a skill the person just dropped in is on the board without reloading anything.
5169
+ if (request.method === 'GET' && url.pathname === '/api/skills') {
5170
+ const config = await readConfig(root);
5171
+ const { loaded, failures, folders } = await loadSkills({ stateRoot: root, projectRoot: canonicalProjectRoot });
5172
+ const fromMarket = await installedSkills(root);
5173
+ const skills = loaded.map((skill) => ({
5174
+ id: skill.id, name: skill.name, when: skill.when, version: skill.version, minMadre: skill.minMadre,
5175
+ credit: skill.credit, license: skill.license, origin: skill.origin, dir: skill.dir, unknown: skill.unknown,
5176
+ // What it says, whole: it is a page, and a person can actually read it before turning it on.
5177
+ body: skill.body, declares: skillDeclares(skill),
5178
+ state: skillState(config, skill.id, scopeRoom),
5179
+ everywhere: skillState(config, skill.id, null),
5180
+ // One the Market signed is not the person's to send: it is already there.
5181
+ market: Boolean(fromMarket[skill.id]),
5182
+ }));
5183
+ return sendJson(response, 200, { skills, failures, folders, project: Boolean(scopeRoom) });
5184
+ }
5185
+ // GIVING ONE TO SOMEBODY (C-1): its files, without MADRE's own record of where it came from,
5186
+ // in a folder the person can find. Nothing is sent anywhere: MADRE prepares, the person sends.
5187
+ if (request.method === 'POST' && url.pathname === '/api/skills/share') {
5188
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5189
+ const payload = await body(request).catch(() => ({}));
5190
+ try {
5191
+ const ready = await shareSkill({ stateRoot: root, projectRoot: canonicalProjectRoot, id: String(payload.id ?? '') });
5192
+ const shown = await openInBrowser(ready.folder, await environmentOnce().catch(() => null)).catch(() => false);
5193
+ return sendJson(response, 200, { ...ready, shown });
5194
+ } catch (error) { return sendJson(response, 404, { error: error.message }); }
5195
+ }
5196
+ // SENDING ONE'S OWN SKILL TO THE MARKET (H-8). A skill is one file, so this is not a form full
5197
+ // of what MADRE already knows: only what nobody but the person can say, written into its own
5198
+ // header. Asked once for the draft, then again to write the folder they will send.
5199
+ if (request.method === 'POST' && url.pathname === '/api/skills/submission') {
5200
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5201
+ const payload = await body(request).catch(() => ({}));
5202
+ const { loaded } = await loadSkills({ stateRoot: root, projectRoot: canonicalProjectRoot });
5203
+ const mine = loaded.find((one) => one.id === String(payload.id ?? ''));
5204
+ if (!mine) return sendJson(response, 404, { error: t('No skill «{id}».', { id: payload.id }) });
5205
+ try {
5206
+ const draft = skillDraft(mine, { madre: PACKAGE.version });
5207
+ if (!payload.write) return sendJson(response, 200, { draft, asks: SKILL_ASKS, shelves: SKILL_SHELVES, licenses: SKILL_LICENSES });
5208
+ const written = await writeSkillSubmission({ stateRoot: root, dir: mine.dir, entry: payload.entry ?? {} });
5209
+ const shown = payload.reveal === true ? await openInBrowser(written.folder, await environmentOnce().catch(() => null)).catch(() => false) : false;
5210
+ return sendJson(response, 200, { draft, asks: SKILL_ASKS, shelves: SKILL_SHELVES, licenses: SKILL_LICENSES, ...written, shown });
5211
+ } catch (error) { return sendJson(response, 422, { error: error.message }); }
5212
+ }
5213
+ // THE SKILLS THIS COMPUTER ALREADY HAS (H-7): read where each CLI keeps them, with what would
5214
+ // happen to each one here. Nothing is brought over until the person says which.
5215
+ if (request.method === 'GET' && url.pathname === '/api/skills/import') {
5216
+ const found = await findSkills({ projectRoot: canonicalProjectRoot, stateRoot: root });
5217
+ return sendJson(response, 200, { found });
5218
+ }
5219
+ if (request.method === 'POST' && url.pathname === '/api/skills/import') {
5220
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5221
+ const payload = await body(request).catch(() => ({}));
5222
+ const ids = (Array.isArray(payload.ids) ? payload.ids : []).slice(0, 50).map((id) => String(id));
5223
+ if (!ids.length) return sendJson(response, 400, { error: t('Name which ones to bring over.') });
5224
+ const done = await importSkills({ ids, stateRoot: root, projectRoot: canonicalProjectRoot, scope: payload.scope === 'project' ? 'project' : 'user' });
5225
+ for (const one of done.brought) await room.record('skill.installed', { id: one.id, name: one.name, origin: payload.scope === 'project' ? 'project' : 'user', from: one.who, by: 'you' });
5226
+ return sendJson(response, 200, done);
5227
+ }
5228
+ // A skill an agent wrote in its draft folder (H-6): read it, say what it tells the agents, and
5229
+ // install it only when the person said so. The file is the agent's proposal; installing is
5230
+ // theirs. Two steps like every other door into the skills folder: `review` writes nothing.
5231
+ if (request.method === 'POST' && url.pathname === '/api/skills/install-file') {
5232
+ const payload = await body(request).catch(() => ({}));
5233
+ const relative = String(payload.path ?? '').replace(/^\/+/, '');
5234
+ // From the agent's draft inside the project, or from what the person dragged into the room
5235
+ // (C-1): those are the only two places, and they are the same two a module comes from.
5236
+ const sent = payload.root === 'attachments';
5237
+ if (!relative || relative.includes('..') || (!sent && !isSkillFile(relative))) return sendJson(response, 400, { error: t('Give the project-relative path of a <id>.habilidad.md file.') });
5238
+ const file = sent ? join(attachmentsRoot, relative) : join(canonicalProjectRoot, relative);
5239
+ try {
5240
+ const text = await readFile(file, 'utf8');
5241
+ const read = readSkillText(text, { id: skillIdOf(relative) });
5242
+ if (payload.review === true) {
5243
+ return sendJson(response, 200, { review: true, id: read.id, name: read.name, when: read.when, version: read.version, body: read.body, unknown: read.unknown, declares: skillDeclares({ ...read, files: [], scripts: [] }) });
5244
+ }
5245
+ const done = await installSkill({
5246
+ files: [{ path: SKILL_FILES[0], text }],
5247
+ scope: payload.scope === 'project' ? 'project' : 'user',
5248
+ stateRoot: root, projectRoot: canonicalProjectRoot,
5249
+ source: { kind: sent ? 'sent' : 'file', from: relative, id: read.id },
5250
+ });
5251
+ await room.record('skill.installed', { id: done.id, name: done.name, origin: done.origin, from: sent ? 'sent' : relative, by: 'you' });
5252
+ return sendJson(response, 200, { installed: done });
5253
+ } catch (error) { return sendJson(response, 422, { error: error.message }); }
5254
+ }
5255
+ // Off, matched or always on, for this project or for all of them. Nothing else changes.
5256
+ const skillState_ = request.method === 'POST' && url.pathname.match(/^\/api\/skills\/([a-z][a-z0-9-]{1,39})\/state$/);
5257
+ if (skillState_) {
5258
+ const payload = await body(request).catch(() => ({}));
5259
+ if (!SKILL_STATES.includes(payload.state)) return sendJson(response, 400, { error: t('A skill is off, matched or always on; nothing else.') });
5260
+ const id = skillState_[1];
5261
+ const config = await readConfig(root);
5262
+ const here = payload.scope === 'everywhere' ? null : scopeRoom;
5263
+ await updateConfig(root, { skills: { ...(config.skills ?? {}), [id]: skillStateIn(config.skills?.[id] ?? {}, here, payload.state) } });
5264
+ await room.record('skill.switched', { id, state: payload.state, scope: here ? 'project' : 'everywhere' });
5265
+ return sendJson(response, 200, { ok: true, id, state: payload.state });
5266
+ }
5267
+ // Removing one is the person's: the folder goes, and nothing a skill's scripts wrote is touched.
5268
+ const skillGone = request.method === 'POST' && url.pathname.match(/^\/api\/skills\/([a-z][a-z0-9-]{1,39})\/remove$/);
5269
+ if (skillGone) {
5270
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5271
+ try {
5272
+ const gone = await removeSkill({ id: skillGone[1], stateRoot: root, projectRoot: canonicalProjectRoot });
5273
+ await room.record('skill.removed', { id: gone.id, folders: gone.removed.length });
5274
+ return sendJson(response, 200, { ok: true, ...gone });
5275
+ } catch (error) { return sendJson(response, 404, { error: error.message }); }
5276
+ }
5277
+ // A skill from the Market onto this computer (H-4). Asked twice on purpose, as a module is:
5278
+ // first to read what it tells the agents, then to install the very files that were read.
5279
+ if (request.method === 'POST' && url.pathname === '/api/market/skills/install') {
5280
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5281
+ const payload = await body(request).catch(() => ({}));
5282
+ const read = await syncMarket().catch(() => ({ catalog: null }));
5283
+ const catalog = read.catalog ?? await keptCatalog({ stateRoot: root, ...marketKeyed });
5284
+ if (!catalog) return sendJson(response, 503, { error: t('MADRE could not read the Market.') });
5285
+ try {
5286
+ const done = await installSkillFromMarket({
5287
+ stateRoot: root, projectRoot: canonicalProjectRoot, madre: PACKAGE.version, fetchImpl: marketFetch,
5288
+ id: String(payload.id ?? ''), catalog, review: payload.review === true, accept: payload.accept ?? null,
5289
+ });
5290
+ if (!done.review) await room.record('skill.installed', { id: done.id, version: done.version ?? null, from: 'market' });
5291
+ return sendJson(response, 200, done);
5292
+ } catch (error) {
5293
+ return sendJson(response, error.code === 'REVIEW_FIRST' ? 409 : 400, { error: error.message, code: error.code ?? null });
5294
+ }
5295
+ }
4805
5296
  // THE MARKET's catalog for the page: the one kept here at once (and a fresh one asked for
4806
5297
  // behind it), what was got from it, and what it updated on its own that nobody was told yet.
4807
5298
  if (request.method === 'GET' && url.pathname === '/api/market') {
4808
5299
  const kept = await keptCatalog({ stateRoot: root, ...marketKeyed });
4809
5300
  const read = kept ? (void syncMarket().catch(() => null), { catalog: kept }) : await syncMarket().catch(() => ({ catalog: null }));
4810
- return sendJson(response, 200, { catalog: read.catalog ?? null, off: !marketOn(), installed: await installedFromMarket(root), licensed: await licensedIds(root), news: await marketNews(root), announce: await marketAnnouncements(root, read.catalog, MODULES.map((one) => one.id)), madre: PACKAGE.version });
5301
+ return sendJson(response, 200, { catalog: read.catalog ?? null, off: !marketOn(), installed: await installedFromMarket(root), skills: await installedSkills(root), licensed: await licensedIds(root), news: await marketNews(root), announce: await marketAnnouncements(root, read.catalog, MODULES.map((one) => one.id)), madre: PACKAGE.version });
4811
5302
  }
4812
5303
  if (request.method === 'POST' && url.pathname === '/api/market/seen') {
4813
5304
  await marketNewsSeen(root);
@@ -4836,7 +5327,7 @@ export async function createPulseServer({
4836
5327
  await room.record('extension.installed', { id: done.id, name: inRoomLanguage(listed?.name) || done.name, origin: 'market', version: done.version, by: 'you' });
4837
5328
  for (const one of await knownRooms(root)) {
4838
5329
  if (!one.open?.port || one.id === thisRoomId) continue;
4839
- await fetch(`http://127.0.0.1:${one.open.port}/api/extensions/reload`, { method: 'POST' }).catch(() => null);
5330
+ await fetch(`http://127.0.0.1:${one.open.port}/api/extensions/reload`, { method: 'POST', headers: await fichaHeaders(root) }).catch(() => null);
4840
5331
  }
4841
5332
  return sendJson(response, 200, { installed: done, extensions: await describeModules(await moduleContext()) });
4842
5333
  } catch (error) { return sendJson(response, error.code === 'REVIEW_FIRST' ? 409 : 422, { error: error.message, review: error.code === 'REVIEW_FIRST' }); }
@@ -4921,6 +5412,8 @@ export async function createPulseServer({
4921
5412
  // The human installs a module file an agent wrote (or they did): checked first, then copied into the chosen folder.
4922
5413
  if (request.method === 'POST' && url.pathname === '/api/extensions/install-file') {
4923
5414
  const payload = await body(request).catch(() => ({}));
5415
+ const refused = moduleKeyRefused(request, payload);
5416
+ if (refused) return sendJson(response, ...refused);
4924
5417
  const relative = String(payload.path ?? '').replace(/^\/+/, '');
4925
5418
  if (!relative || relative.includes('..')) return sendJson(response, 400, { error: t('Give the project-relative path of a <id>.module.mjs file.') });
4926
5419
  try {
@@ -5117,11 +5610,11 @@ export async function createPulseServer({
5117
5610
  server.on('close', () => { for (const timer of [...aliveTimers, ...hereTimers]) clearTimeout(timer); });
5118
5611
 
5119
5612
  server.on('close', () => { void phone.stop(); });
5120
- return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone, salasRoom, closeOtherRooms };
5613
+ return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone, salasRoom, closeOtherRooms, currentFicha, afterOpen };
5121
5614
  }
5122
5615
 
5123
5616
  export async function startPulse({ port, projectRoot, openBrowser, openPath = '' }) {
5124
- const { server, agents, markOpen, phone, salasRoom, closeOtherRooms } = await createPulseServer({ projectRoot, quotaSources: defaultQuotaSources() });
5617
+ const { server, agents, markOpen, phone, salasRoom, closeOtherRooms, currentFicha, afterOpen } = await createPulseServer({ projectRoot, quotaSources: defaultQuotaSources(), ficha: true, renewFicha: Boolean(openBrowser) });
5125
5618
  await new Promise((resolve, reject) => {
5126
5619
  server.once('error', reject);
5127
5620
  server.listen(port, '127.0.0.1', resolve);
@@ -5129,9 +5622,13 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
5129
5622
  const address = server.address();
5130
5623
  // The room is taken from here on, and says so on disk for anyone who tries to open it again.
5131
5624
  await markOpen(address.port);
5625
+ void afterOpen().catch(() => null);
5132
5626
  // From here this room offers to host the phone's bridge, when there is a phone to reach it.
5133
5627
  phone.start();
5134
5628
  const url = `http://127.0.0.1:${address.port}`;
5629
+ // The address with the ficha (src/ficha.mjs): the one the browser is opened at and the terminal
5630
+ // shows, so that pasting it into another browser works too.
5631
+ const opening = withFicha(`${url}${openPath}`, await currentFicha());
5135
5632
  // Installed is all this line knows: whether each one is signed in is asked in the room, and
5136
5633
  // «Ready: Codex, Claude…» before any sign-in told a newcomer the opposite (2026-10-19).
5137
5634
  const ready = agents.filter((agent) => agent.ready).map((agent) => agent.label).join(', ') || t('none');
@@ -5139,9 +5636,9 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
5139
5636
  // In the language MADRE speaks (QA 1.1.0, NUE-01): the terminal said «MADRE is ready» above
5140
5637
  // «Abre esta dirección…», and Home was called «Project: …/.pulse/salas», a folder of MADRE's own.
5141
5638
  const where = salasRoom ? t('Home: every project on this computer') : `${t('Project:')} ${projectRoot}`;
5142
- console.log(`\n${t('MADRE is ready')}\n\n ${url}${openPath}\n ${where}\n ${t('Agents installed: {list} (who is signed in: Settings › Agents)', { list: ready })}\n${broken ? ` ${t('Found but not answering: {list}', { list: broken })}\n` : ''}`);
5639
+ console.log(`\n${t('MADRE is ready')}\n\n ${opening}\n ${where}\n ${t('Agents installed: {list} (who is signed in: Settings › Agents)', { list: ready })}\n${broken ? ` ${t('Found but not answering: {list}', { list: broken })}\n` : ''}`);
5143
5640
  // Not waited for: the signals below are set up while the browser opens.
5144
- if (openBrowser) void openUrl(`${url}${openPath}`);
5641
+ if (openBrowser) void openUrl(opening);
5145
5642
  // SIGHUP too: closing the Terminal the room was started in is a way of closing it.
5146
5643
  // Home closed this way closes what Turn MADRE off closes (2026-10-21): every open project, also
5147
5644
  // one opened from another project, whose process outlives Home on its own. A second signal while