@jossuealcala/madre 1.0.3 → 1.0.5

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 (106) hide show
  1. package/CHANGELOG.en.md +113 -1
  2. package/CHANGELOG.md +113 -1
  3. package/NOTICE +30 -0
  4. package/README.en.md +59 -156
  5. package/README.md +60 -161
  6. package/TRADEMARKS.md +18 -0
  7. package/bin/madre.mjs +2 -2
  8. package/docs/REFERENCE.md +1 -1
  9. package/docs/SDK.md +25 -4
  10. package/docs/en/REFERENCE.md +1 -1
  11. package/docs/en/SDK.md +22 -2
  12. package/docs/madre-banner.png +0 -0
  13. package/package.json +1 -1
  14. package/public/app.js +1087 -247
  15. package/public/assets/manual/madre-manual-en.pdf +0 -0
  16. package/public/assets/manual/madre-manual-es.pdf +0 -0
  17. package/public/assets/manual/shots/en-agents.webp +0 -0
  18. package/public/assets/manual/shots/en-code.webp +0 -0
  19. package/public/assets/manual/shots/en-composer.webp +0 -0
  20. package/public/assets/manual/shots/en-connectors.webp +0 -0
  21. package/public/assets/manual/shots/en-continuity.webp +0 -0
  22. package/public/assets/manual/shots/en-coordinator.webp +0 -0
  23. package/public/assets/manual/shots/en-copilot.webp +0 -0
  24. package/public/assets/manual/shots/en-diagnostics.webp +0 -0
  25. package/public/assets/manual/shots/en-home.webp +0 -0
  26. package/public/assets/manual/shots/en-local.webp +0 -0
  27. package/public/assets/manual/shots/en-memory.webp +0 -0
  28. package/public/assets/manual/shots/en-modes.webp +0 -0
  29. package/public/assets/manual/shots/en-modules.webp +0 -0
  30. package/public/assets/manual/shots/en-notes.webp +0 -0
  31. package/public/assets/manual/shots/en-settings.webp +0 -0
  32. package/public/assets/manual/shots/en-windows.webp +0 -0
  33. package/public/assets/manual/shots/es-agents.webp +0 -0
  34. package/public/assets/manual/shots/es-code.webp +0 -0
  35. package/public/assets/manual/shots/es-composer.webp +0 -0
  36. package/public/assets/manual/shots/es-connectors.webp +0 -0
  37. package/public/assets/manual/shots/es-continuity.webp +0 -0
  38. package/public/assets/manual/shots/es-coordinator.webp +0 -0
  39. package/public/assets/manual/shots/es-copilot.webp +0 -0
  40. package/public/assets/manual/shots/es-diagnostics.webp +0 -0
  41. package/public/assets/manual/shots/es-home.webp +0 -0
  42. package/public/assets/manual/shots/es-local.webp +0 -0
  43. package/public/assets/manual/shots/es-memory.webp +0 -0
  44. package/public/assets/manual/shots/es-modes.webp +0 -0
  45. package/public/assets/manual/shots/es-modules.webp +0 -0
  46. package/public/assets/manual/shots/es-notes.webp +0 -0
  47. package/public/assets/manual/shots/es-settings.webp +0 -0
  48. package/public/assets/manual/shots/es-windows.webp +0 -0
  49. package/public/en.js +74 -0
  50. package/public/es.js +495 -137
  51. package/public/i18n.js +45 -7
  52. package/public/index.html +2 -3
  53. package/public/manual-content.js +657 -0
  54. package/public/manual-shots.js +43 -0
  55. package/public/manual.css +228 -0
  56. package/public/manual.html +15 -0
  57. package/public/manual.js +398 -0
  58. package/public/market-art.js +56 -0
  59. package/public/market-view.js +140 -22
  60. package/public/market.js +25 -14
  61. package/public/mcp-catalog.js +62 -0
  62. package/public/resay.js +1 -0
  63. package/public/salas-mac.css +185 -30
  64. package/public/salas-mac.html +5 -5
  65. package/public/salas-mac.js +475 -68
  66. package/public/styles.css +306 -42
  67. package/public/tour-chapters.js +98 -90
  68. package/public/tour.js +63 -21
  69. package/public/troubleshooting.js +145 -10
  70. package/src/adapters/cursor.mjs +56 -7
  71. package/src/adapters/gemini.mjs +12 -1
  72. package/src/adapters/madre.mjs +27 -6
  73. package/src/adapters/process.mjs +5 -2
  74. package/src/auth-probe.mjs +22 -3
  75. package/src/bridge/policy.mjs +1 -1
  76. package/src/bridge/server.mjs +1 -1
  77. package/src/capabilities.mjs +3 -3
  78. package/src/credentials.mjs +24 -2
  79. package/src/history.mjs +76 -0
  80. package/src/i18n.mjs +23 -1
  81. package/src/local-ai.mjs +10 -2
  82. package/src/looks.mjs +17 -5
  83. package/src/market-license.mjs +104 -0
  84. package/src/market-remote.mjs +17 -1
  85. package/src/mcp/notes-server.mjs +120 -0
  86. package/src/mcp/proxy.mjs +14 -3
  87. package/src/models.mjs +82 -9
  88. package/src/modules/index.mjs +3 -1
  89. package/src/modules/local-models.mjs +28 -0
  90. package/src/modules/notes.mjs +142 -0
  91. package/src/modules/ollama.mjs +39 -10
  92. package/src/modules/playwright.mjs +14 -3
  93. package/src/modules/reminders.mjs +345 -0
  94. package/src/modules/sdk.mjs +21 -5
  95. package/src/mother.mjs +11 -1
  96. package/src/ollama.mjs +2 -2
  97. package/src/opencode-health.mjs +63 -0
  98. package/src/outbound.mjs +25 -1
  99. package/src/ports.mjs +4 -6
  100. package/src/reminder-time.mjs +127 -0
  101. package/src/room.mjs +19 -7
  102. package/src/runtime-detection.mjs +6 -2
  103. package/src/sentinel-errors.mjs +4 -3
  104. package/src/server-sentinel.mjs +7 -3
  105. package/src/server.mjs +302 -70
  106. package/src/tour.mjs +24 -5
package/src/server.mjs CHANGED
@@ -28,7 +28,7 @@ import { MODULES, moduleById, describeModules, findModuleRoute, toolsForTurn as
28
28
  import { madreAgent, madreInvoker, MADRE_AGENT_ID, MADRE_ADAPTER } from './adapters/madre.mjs';
29
29
  import { exportDataset, forgetCorpus, keepCorpus, keptCorpus, pruneCorpora, readiness as datasetReadiness } from './dataset.mjs';
30
30
  import { OutboundLog, outboundView, DEFAULT_REPORT_URL } from './outbound.mjs';
31
- import { language as roomLanguage, setLanguage as setRoomLanguage, t } from './i18n.mjs';
31
+ import { hostFacts, inRoomLanguage, language as roomLanguage, setLanguage as setRoomLanguage, t } from './i18n.mjs';
32
32
 
33
33
  // One per start of this process: a restart is a new one, a reload of the page is not.
34
34
  const BOOT_ID = `${process.pid}-${Date.now().toString(36)}`;
@@ -75,7 +75,7 @@ import { Privacy, normalizeTerms, privacySettings } from './privacy.mjs';
75
75
  import { checkForUpdate, detectInstall, updateCommand, releaseUrl, applyCommand, fetchCommand } from './updates.mjs';
76
76
  import { bootWhatsNew, markSeen, newestNotes, notesFor, whatsNew } from './whats-new.mjs';
77
77
  import { answerAsk, tickAsk } from './review-ask.mjs';
78
- import { CHAPTERS, HINTS, TOUR_VERSION, cameBefore, changeTour, readTour, recoverProject, roomsWithoutProject } from './tour.mjs';
78
+ import { CHAPTERS, HINTS, NEWS_LEVEL, TOUR_VERSION, cameBefore, changeTour, readTour, recoverProject, roomsWithoutProject } from './tour.mjs';
79
79
 
80
80
  // Where a person reads the module contract, in the language the room is speaking.
81
81
  const SDK_PAGE = { es: 'https://madre.run/sdk/', en: 'https://madre.run/en/sdk/' };
@@ -83,8 +83,16 @@ import { moduleUpdate } from './modules/updates.mjs';
83
83
  import { adoptStrays, chatIndex, chatLedger, createChat, deleteChat, isChatId, listChats, openChat as openChatIndex, projectFloor, renameChat, touchChat } from './chats.mjs';
84
84
  import { spawn } from 'node:child_process';
85
85
  import { cpus, freemem, loadavg, totalmem } from 'node:os';
86
- import { discoverModels, groupOpenCode, openCodeHidden, parseOpenCodeVerbose, providerLabel, OPENCODE_OWN } from './models.mjs';
86
+ import { discoverModels, groupOpenCode, openCodeHidden, parseCursorModels, parseGeminiModels, parseOpenCodeVerbose, providerLabel, OPENCODE_OWN } from './models.mjs';
87
+ import { cursorOnlyAuto } from './adapters/cursor.mjs';
88
+ // Cursor's own list of models (`cursor-agent --list-models`), kept a few minutes: reading it asks
89
+ // Cursor's servers.
90
+ const cursorModels = { at: 0, ids: [] };
91
+ // And Gemini's, from Google with the person's key.
92
+ const geminiModels = { at: 0, ids: [] };
87
93
  import { observable } from './modules/intents-observe.mjs';
94
+ import { summarizeHistory } from './history.mjs';
95
+ import { noteOpenCodeTurn, openCodeHealth, suggestOpenCodeModel } from './opencode-health.mjs';
88
96
  import { normalizeMode, setImageModule } from './capabilities.mjs';
89
97
  import { resolveGeminiKey } from './image-studio.mjs';
90
98
  import { commandByName, listCommands, parseCommand } from './commands.mjs';
@@ -112,7 +120,8 @@ import { forgetFromMarket, installFromMarket, installedFromMarket, keptCatalog,
112
120
  // Not moved project by project: the Coordinator is Home's, Git has no switch, and Local AI keeps
113
121
  // its own list of projects (local-ai.mjs).
114
122
  const NOT_BY_PROJECT = new Set(['bishop', 'git-pulse', 'ollama']);
115
- import { heartbeat } from './heartbeat.mjs';
123
+ import { heartbeat, installId } from './heartbeat.mjs';
124
+ import { activateLicense, licensedIds, releaseLicense } from './market-license.mjs';
116
125
  import { askRoom, associateProject, createProject, ensureSalasProject, forgetProject, isSalasRoom, knownRooms, listFolders, markProject, projectRoomId, roomComesUp, salasRoomId, startRoom, suggestProjects, universeOf } from './salas.mjs';
117
126
  import { parseWork, recentWork, WORK_SYSTEM, workPrompt } from './lobby-work.mjs';
118
127
  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';
@@ -246,6 +255,8 @@ export async function createPulseServer({
246
255
  // fake, and the key their catalog is signed with.
247
256
  marketFetch = globalThis.fetch,
248
257
  marketKey = null,
258
+ // Where a paid module's license is checked (src/market-license.mjs); tests hand in their own.
259
+ licenseApi = null,
249
260
  // Ollama detection; tests hand in a fake probe. PULSE_OLLAMA=0 leaves Ollama alone entirely.
250
261
  ollamaProbe = process.env.PULSE_OLLAMA === '0' ? async () => ({ running: false, host: null, models: [], embedModel: null, chatModel: null, disabled: true }) : probeOllama,
251
262
  }) {
@@ -330,6 +341,22 @@ export async function createPulseServer({
330
341
  };
331
342
  }
332
343
  const releaseOpen = () => { try { rmSync(openMark, { force: true }); } catch { /* it was already gone */ } };
344
+ // Every other open project of this Mac, asked to close the way Home closes one, and waited for.
345
+ // Found by its mark (knownRooms), not by who started its process: a project opened from another
346
+ // project hangs from that one, not from Home, and closes all the same (2026-10-21). Only rooms
347
+ // are asked, over their own port; no process is signalled from here.
348
+ async function closeOtherRooms() {
349
+ const here = basename(roomDir);
350
+ const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
351
+ await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/close', { method: 'POST', body: {}, timeoutMs: 3000 }).catch(() => null)));
352
+ let left = others;
353
+ for (let tries = 0; tries < 60 && left.length; tries += 1) {
354
+ await new Promise((resolve) => setTimeout(resolve, 250));
355
+ const now = await knownRooms(root);
356
+ left = left.filter((one) => now.find((room) => room.id === one.id)?.open);
357
+ }
358
+ return { closed: others.length - left.length, stuck: left.map((one) => one.name) };
359
+ }
333
360
  // How many memories of each kind, and how many travel into turns. Counted, never read out.
334
361
  function memoryCensus() {
335
362
  const all = memory ? memory.memories({ limit: 20000 }) : [];
@@ -376,6 +403,9 @@ export async function createPulseServer({
376
403
  // says so once, the next time a page asks (market/updates.json).
377
404
  const marketOn = () => process.env.PULSE_MARKET !== '0' && updatesEnabled();
378
405
  const marketKeyed = marketKey ? { publicKey: marketKey } : {};
406
+ const licenseKeyed = licenseApi ? { api: licenseApi } : {};
407
+ // OpenCode's own free models, as its CLI lists them, read again at most every ten minutes.
408
+ const openCodeOwn = { names: null, at: 0 };
379
409
  const marketTools = () => ({ stateRoot: root, projectRoot: canonicalProjectRoot, madre: PACKAGE.version, fetchImpl: marketFetch, verifyText: verifyModuleText, installText: installModuleText });
380
410
  let marketSync = null;
381
411
  const syncMarket = ({ force = false } = {}) => {
@@ -443,6 +473,8 @@ export async function createPulseServer({
443
473
  // Coordinator, and Ollama as this room probed it. A reading is kept 30 s, so a page that asks
444
474
  // every few seconds never makes the projects work for it.
445
475
  const widgetReadings = new Map();
476
+ // This copy's identifier once left out of the author's usage figures (the usage widget, below).
477
+ const usageExcluded = new Set();
446
478
  let cpuSeen = null;
447
479
  const cpuTimes = () => cpus().reduce((sum, one) => {
448
480
  const times = one.times;
@@ -520,9 +552,15 @@ export async function createPulseServer({
520
552
  // (scripts/owner-usage.mjs); anywhere else there is no such widget.
521
553
  const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
522
554
  if (!token) return null;
555
+ // This copy is the author's: left out of the figures the first time the widget reads them.
556
+ const mine = await installId(root).catch(() => null);
557
+ if (mine && !usageExcluded.has(mine)) {
558
+ const marked = await reportFetch(process.env.PULSE_USAGE_URL ?? 'https://madre.run/api/usage', { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify({ exclude: mine }), signal: AbortSignal.timeout(8000) }).catch(() => null);
559
+ if (marked?.ok) usageExcluded.add(mine);
560
+ }
523
561
  const answer = await reportFetch(process.env.PULSE_USAGE_URL ?? 'https://madre.run/api/usage', { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(8000) }).catch(() => null);
524
562
  const body = answer?.ok ? await answer.json().catch(() => null) : null;
525
- reading = body?.ok ? { available: true, ...body } : { available: false, status: answer?.status ?? 0 };
563
+ reading = body?.ok ? { available: true, ...body, mine } : { available: false, status: answer?.status ?? 0 };
526
564
  } else if (kind === 'coordinator' && !salasRoom) {
527
565
  // Home's page is served by every project too: the Coordinator's record is its own room's.
528
566
  const coordinator = (await knownRooms(root)).find((one) => one.id === salasRoomId(root));
@@ -706,11 +744,17 @@ export async function createPulseServer({
706
744
  return { roomDir, recipeDir: fileURLToPath(new URL('../docs/training/', import.meta.url)), modelName: `madre-${slug}`, baseModel: base.base, memoryGb: fit.hardware?.memoryGb ?? Math.round(totalmem() / 1024 ** 3), fit };
707
745
  }
708
746
  async function wireOllama({ probe: doProbe = true } = {}) {
709
- if (doProbe) ollama = await ollamaProbe();
747
+ if (doProbe) { ollama = await ollamaProbe(); ollama.autoModel = ollama.chatModel; }
710
748
  // A model trained on this room (docs/training) is named madre-<project>: @madre uses it when it exists.
711
749
  const slug = basename(canonicalProjectRoot).toLowerCase().replace(/[^a-z0-9]+/g, '-');
712
750
  const trained = (ollama.models ?? []).map((model) => model.name).find((name) => name.startsWith(`madre-${slug}`)) ?? null;
713
- ollama = { ...ollama, madreModel: trained };
751
+ // The model the person chose in Home, one for the whole computer (src/local-ai.mjs), while it
752
+ // is installed; otherwise the one MADRE picked. PULSE_OLLAMA_MODEL still wins over both.
753
+ const chosen = process.env.PULSE_OLLAMA_MODEL ? null : localAiConfig(await readConfig(root)).model;
754
+ const bare = (name) => String(name ?? '').replace(/:latest$/, '');
755
+ const installed = chosen ? (ollama.models ?? []).find((model) => bare(model.name) === bare(chosen))?.name ?? null : null;
756
+ const auto = ollama.autoModel !== undefined ? ollama.autoModel : ollama.chatModel;
757
+ ollama = { ...ollama, autoModel: auto, chosenModel: chosen, chatModel: installed ?? auto, madreModel: trained };
714
758
  const project = await localAiHere();
715
759
  // Off for this project reads exactly as the module switched off, and only here.
716
760
  const settings = { ...(await ollamaSettings()), enabled: project.on };
@@ -1137,6 +1181,7 @@ export async function createPulseServer({
1137
1181
  if (agent.detected) return { status: 409, body: { error: `${agent.label} is already installed.` } };
1138
1182
  const plan = installPlanFor(agent, { prefix: toolsPrefix() });
1139
1183
  if (!plan) return { status: 404, body: { error: `MADRE does not know how to install ${id}.` } };
1184
+ 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 }) } };
1140
1185
  if (installing) return { status: 409, body: { error: `Another install is running (${installing}).` } };
1141
1186
  installing = `agent:${id}`;
1142
1187
  await room.record('connection.install.started', { agent: id, label: agent.label, command: plan.display });
@@ -1259,7 +1304,7 @@ export async function createPulseServer({
1259
1304
  agents,
1260
1305
  settings: { autoReport: process.env.PULSE_AUTO_REPORT === '1' || Boolean(telemetry.autoReport), reportUrl: process.env.PULSE_REPORT_URL ?? telemetry.reportUrl ?? DEFAULT_REPORT_URL },
1261
1306
  fetchImpl: reportFetch,
1262
- emit: (type, payload) => room.record(type, payload),
1307
+ emit: (type, payload) => writeFromOutside(room, type, payload),
1263
1308
  save: async (settings) => { const current = await readConfig(root); await updateConfig(root, { telemetry: { ...(current.telemetry ?? {}), ...settings } }); },
1264
1309
  });
1265
1310
  outbound.watchReportUrl(sentinel.settings().reportUrl);
@@ -1281,7 +1326,7 @@ export async function createPulseServer({
1281
1326
  research: () => room.memoryResearch(),
1282
1327
  entriesFor: (notes) => (memory ? memory.entriesAt(notes.flatMap((note) => note.sources ?? [])) : []),
1283
1328
  bench: () => room.bench(),
1284
- emit: (type, payload) => room.record(type, payload),
1329
+ emit: (type, payload) => writeFromOutside(room, type, payload),
1285
1330
  });
1286
1331
  let unsubscribeEyecat = () => {};
1287
1332
 
@@ -1292,6 +1337,22 @@ export async function createPulseServer({
1292
1337
  // when the room closes: a file that reappears while its folder is being removed is a test that
1293
1338
  // fails for a reason that has nothing to do with it.
1294
1339
  let chatWrites = Promise.resolve();
1340
+ // What the watchers outside the room (the error sentinel, EYECAT, the modules' onEvent) write
1341
+ // to a record. They hear an event and answer when they are done, which can be after the room
1342
+ // was told to close: a report written once the server said it was closed landed in a folder
1343
+ // being removed, and in a memory file already shut (2026-10-21). From the close on they write
1344
+ // nothing; what they had started writing is waited for. Their work itself is not: EYECAT may
1345
+ // be asking an agent, and closing does not wait for an answer.
1346
+ let serverClosing = false;
1347
+ const lateWrites = new Set();
1348
+ const writeFromOutside = (target, type, payload) => {
1349
+ if (serverClosing) return Promise.resolve(null);
1350
+ const write = Promise.resolve(target.record(type, payload));
1351
+ lateWrites.add(write);
1352
+ write.finally(() => lateWrites.delete(write)).catch(() => {});
1353
+ return write;
1354
+ };
1355
+ const lateWritesDone = async () => { while (lateWrites.size) await Promise.allSettled([...lateWrites]); };
1295
1356
 
1296
1357
  // Everything that listens to the open conversation, attached in one place so that opening
1297
1358
  // another attaches exactly the same things to it. Live readings go straight to whoever is
@@ -1341,14 +1402,19 @@ export async function createPulseServer({
1341
1402
  // event is its own business and never holds up the room: a failure is logged and dropped.
1342
1403
  function wireModules(target, id) {
1343
1404
  return target.subscribe((event) => {
1405
+ // What OpenCode answered with, and what failed for which provider (src/opencode-health.mjs):
1406
+ // the next failure offers a model that works instead of a sentence in English.
1407
+ if (event.type === 'agent.completed' && event.payload?.agent === 'opencode') void noteOpenCodeTurn(root, { ok: true, model: event.payload.ranOn ?? null }).catch(() => null);
1408
+ if (event.type === 'message.failed' && event.payload?.target === 'opencode') void noteOpenCodeTurn(root, { ok: false, model: event.payload.ranOn ?? null, error: event.payload.error }).catch(() => null);
1344
1409
  const listening = MODULES.filter((module) => typeof module.onEvent === 'function');
1345
1410
  if (!listening.length) return;
1346
1411
  void (async () => {
1347
1412
  const ctx = await moduleContext();
1348
1413
  for (const module of listening) {
1349
- const settings = module.settingsFrom(ctx.config);
1414
+ // This project's word on the module, not only the one for every project (module-scope.mjs).
1415
+ const settings = module.settingsFrom(ctx.config, ctx.roomId);
1350
1416
  if (module.kind === 'builtin' && !settings.enabled) continue;
1351
- await Promise.resolve(module.onEvent({ ...ctx, settings, room: target, chat: id, record: (type, payload) => target.record(type, payload) }, event))
1417
+ await Promise.resolve(module.onEvent({ ...ctx, settings, room: target, chat: id, record: (type, payload) => writeFromOutside(target, type, payload) }, event))
1352
1418
  .catch((error) => console.error(`MADRE module ${module.id}: onEvent failed: ${error.message}`));
1353
1419
  }
1354
1420
  })().catch((error) => console.error(`MADRE: a module could not hear an event: ${error.message}`));
@@ -1426,7 +1492,9 @@ export async function createPulseServer({
1426
1492
  if (!testMode) serverSentinel.start();
1427
1493
  // «Still in use», once a day per copy (src/heartbeat.mjs): a little after start, then looked at
1428
1494
  // every few hours; the day it was already said, nothing goes.
1429
- const sayAlive = () => { void heartbeat({ root, version: PACKAGE.version, fetchImpl: reportFetch }); };
1495
+ // The author's own copies say nothing (2026-10-20): a copy that holds the author's usage key is
1496
+ // one of his, and it would only count him in his own figures.
1497
+ const sayAlive = () => { void readSecret(root, OWNER_VAULT, 'usage').catch(() => null).then((owner) => (owner ? null : heartbeat({ root, version: PACKAGE.version, fetchImpl: reportFetch }))); };
1430
1498
  const aliveTimers = testMode ? [] : [setTimeout(sayAlive, 20_000), setInterval(sayAlive, 6 * 60 * 60 * 1000)];
1431
1499
  for (const timer of aliveTimers) timer.unref?.();
1432
1500
  const endClients = (feed) => { for (const client of [...feed.clients.keys()]) { feed.clients.delete(client); try { client.end(); } catch { /* already gone */ } } };
@@ -1442,7 +1510,7 @@ export async function createPulseServer({
1442
1510
  async function releaseIfIdle(id, target = null) {
1443
1511
  const held = parked.get(id);
1444
1512
  if (!held || (target && held.room !== target)) return;
1445
- if (held.room.busy() || held.room.hasLiveRuns?.() || held.feed?.clients.size) return;
1513
+ if (held.room.busy() || held.room.hasLiveRuns?.() || held.feed?.clients.size || held.claims) return;
1446
1514
  await closeHeld(id);
1447
1515
  }
1448
1516
  // A conversation's turns starting and ending, said to every page whichever conversation it shows.
@@ -1497,7 +1565,24 @@ export async function createPulseServer({
1497
1565
  // mountChat builds one.
1498
1566
  // The room on screen, for the places where a route names its own conversation `room`.
1499
1567
  const openRoom = () => room;
1500
- async function scopeOf(url) {
1568
+ // A request about a conversation beside claims it until its response is over: a held room is not
1569
+ // let go while a request is still at work in it. The grace ran out between the room being found
1570
+ // and the request reaching it — a message read and checked before it was handed over, a page's
1571
+ // feed being built — and the room closed under it: the message was accepted and never answered,
1572
+ // the page heard nothing (2026-10-21). The last request to end gives it its grace again.
1573
+ function claimFor(entry, id, response) {
1574
+ if (!response) return;
1575
+ entry.claims = (entry.claims ?? 0) + 1;
1576
+ let done = false;
1577
+ const release = () => {
1578
+ if (done) return;
1579
+ done = true;
1580
+ entry.claims -= 1;
1581
+ if (!entry.claims) setTimeout(() => { void releaseIfIdle(id, entry.room); }, heldGraceMs).unref?.();
1582
+ };
1583
+ if (response.closed) release(); else response.once('close', release);
1584
+ }
1585
+ async function scopeOf(url, response = null) {
1501
1586
  const asked = url.searchParams.get('chat');
1502
1587
  if (!asked || asked === chatId) return { id: chatId, room, store, feed: mainFeed, main: true };
1503
1588
  if (!isChatId(asked)) return { error: `No conversation "${asked}".` };
@@ -1529,6 +1614,7 @@ export async function createPulseServer({
1529
1614
  }
1530
1615
  // It may have become the open one while it was being built.
1531
1616
  if (asked === chatId) return { id: chatId, room, store, feed: mainFeed, main: true };
1617
+ claimFor(entry, asked, response);
1532
1618
  return { id: asked, room: entry.room, store: entry.store, entry, main: false };
1533
1619
  }
1534
1620
  let unsubscribeActivity = () => {};
@@ -1624,6 +1710,11 @@ export async function createPulseServer({
1624
1710
  const config = await readConfig(root);
1625
1711
  return {
1626
1712
  projectRoot: canonicalProjectRoot, stateRoot: root, config, env: process.env, agents, room,
1713
+ // The language the room speaks, 'es' or 'en': a module answers in it (SDK, 2026-10-20).
1714
+ language: roomLanguage(),
1715
+ // Where this project's conversations are kept (~/.pulse/rooms/<id>): a module's own small
1716
+ // files about the project live beside them, never in the project's folder.
1717
+ roomDir,
1627
1718
  // Which project's word a module's switch reads and writes; none in Home (module-scope.mjs).
1628
1719
  roomId: scopeRoom,
1629
1720
  readConfig: () => readConfig(root),
@@ -1694,6 +1785,22 @@ export async function createPulseServer({
1694
1785
  },
1695
1786
  // What a card knows about being up to date. Reading is free: it answers from the day's
1696
1787
  // cache. The button on a card is what forces a look outside.
1788
+ // The project's history over a period, in the shape docs/SDK.md promises (src/history.mjs):
1789
+ // every conversation's ledger and the memory's decisions, read on demand and never written.
1790
+ history: async ({ since = null, until = null } = {}) => {
1791
+ const chats = [];
1792
+ for (const chat of (await listChats(roomDir)).chats) {
1793
+ const text = await readFile(chatLedger(roomDir, chat.id), 'utf8').catch(() => '');
1794
+ const events = [];
1795
+ for (const line of text.split('\n')) {
1796
+ if (!line) continue;
1797
+ try { events.push(JSON.parse(line)); } catch { /* a torn last line */ }
1798
+ }
1799
+ chats.push({ id: chat.id, title: chat.title ?? null, events });
1800
+ }
1801
+ const memories = memory?.memories?.({ kind: 'decision', limit: 1000 }) ?? [];
1802
+ return { project: basename(canonicalProjectRoot), ...summarizeHistory({ chats, memories, since, until }) };
1803
+ },
1697
1804
  moduleUpdate: (item, { force = false, cacheOnly = !force } = {}) => moduleUpdate(item, {
1698
1805
  stateRoot: root, madre: { name: PACKAGE.name, version: PACKAGE.version },
1699
1806
  fetchImpl: reportFetch, enabled: updatesEnabled(), force, cacheOnly,
@@ -1706,9 +1813,9 @@ export async function createPulseServer({
1706
1813
  // Getting Ollama onto this computer, with the command in plain sight, and waking it.
1707
1814
  install: async () => {
1708
1815
  if (installing) return { ok: false, error: `Another install is running (${installing}).` };
1709
- const { ollamaInstallPlan } = await import('./modules/ollama.mjs');
1710
- const plan = ollamaInstallPlan({ brew: await findOnPath('brew') });
1711
- if (!plan.command) return { ok: false, error: plan.note, download: plan.download };
1816
+ const { ollamaInstallPlan, adminHere } = await import('./modules/ollama.mjs');
1817
+ const plan = ollamaInstallPlan({ brew: await findOnPath('brew'), admin: await adminHere() });
1818
+ if (!plan.command) return { ok: false, error: plan.note, download: plan.download, manual: plan.manual ? plan.display : null };
1712
1819
  installing = 'ollama';
1713
1820
  await room.record('extension.install.started', { id: 'ollama', name: 'OLLAMA', command: plan.display, platforms: [], alreadyInstalled: false });
1714
1821
  void (async () => {
@@ -1858,6 +1965,9 @@ export async function createPulseServer({
1858
1965
  // The project's own folder name, typed by the human. Declared at the top of the handler and
1859
1966
  // not beside the first route that happened to need it: a const sits in its temporal dead zone
1860
1967
  // until its own line runs, so any route above it threw instead of refusing.
1968
+ // Which machine serves the page, written into it (public/i18n.js, hostWords): the browser that
1969
+ // reads it may be on another one, a Mac looking at a Linux box, and must not say «Mac» there.
1970
+ 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;')}">`);
1861
1971
  const designationOk = (given) => typeof given === 'string' && given.trim().toLowerCase() === basename(canonicalProjectRoot).toLowerCase();
1862
1972
  // A request the bridge passed on from a paired phone. It reaches the room from 127.0.0.1 like
1863
1973
  // anything on this Mac, so «only from this computer» has to ask this too.
@@ -1865,16 +1975,34 @@ export async function createPulseServer({
1865
1975
  const phoneKind = viaPhone ? String(request.headers['x-madre-device-kind'] ?? 'other').slice(0, 20) : null;
1866
1976
  try {
1867
1977
  if (request.method === 'GET' && url.pathname === '/') {
1868
- const html = await readFile(join(publicDirectory, 'index.html'));
1978
+ const html = withHost(await readFile(join(publicDirectory, 'index.html'), 'utf8'));
1869
1979
  response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...PAGE_GUARDS });
1870
1980
  return response.end(html);
1871
1981
  }
1872
- 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'].includes(url.pathname)) {
1982
+ 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', '/mcp-catalog.js', '/manual.js', '/manual-content.js', '/manual-shots.js', '/en.js'].includes(url.pathname)) {
1873
1983
  return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'text/javascript; charset=utf-8');
1874
1984
  }
1875
1985
  if (request.method === 'GET' && url.pathname === '/styles.css') {
1876
1986
  return sendAsset(request, response, join(publicDirectory, 'styles.css'), 'text/css; charset=utf-8');
1877
1987
  }
1988
+ // The user manual (public/manual.html, 1.0.5): read here, without a network, in the room's
1989
+ // language; and the same manual printed, in both languages (scripts/manual-pdf.mjs).
1990
+ if (request.method === 'GET' && url.pathname === '/manual') {
1991
+ const html = withHost(await readFile(join(publicDirectory, 'manual.html'), 'utf8'));
1992
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache', ...PAGE_GUARDS });
1993
+ return response.end(html);
1994
+ }
1995
+ if (request.method === 'GET' && url.pathname === '/manual.css') {
1996
+ return sendAsset(request, response, join(publicDirectory, 'manual.css'), 'text/css; charset=utf-8');
1997
+ }
1998
+ if (request.method === 'GET' && (url.pathname === '/assets/manual/madre-manual-es.pdf' || url.pathname === '/assets/manual/madre-manual-en.pdf')) {
1999
+ return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'application/pdf');
2000
+ }
2001
+ // Its pictures: MADRE itself, photographed in each language (scripts/manual-shots.mjs). Only
2002
+ // a name of letters and dashes, so no path leaves the folder.
2003
+ if (request.method === 'GET' && /^\/assets\/manual\/shots\/(es|en)-[a-z]+\.webp$/.test(url.pathname)) {
2004
+ return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'image/webp');
2005
+ }
1878
2006
  const abductionAssets = new Map([
1879
2007
  ['/assets/abduction-cat.png', 'abduction-cat.png'],
1880
2008
  ['/assets/abduction-cat-blink.png', 'abduction-cat-blink.png'],
@@ -1898,6 +2026,8 @@ export async function createPulseServer({
1898
2026
  ['/assets/brand/OFL-Sora.txt', 'text/plain; charset=utf-8'],
1899
2027
  ['/assets/brand/OFL-JetBrainsMono.txt', 'text/plain; charset=utf-8'],
1900
2028
  ['/assets/brand/madre-favicon.svg', 'image/svg+xml'],
2029
+ // The app's mark, on the user manual's cover (public/manual.js).
2030
+ ['/assets/brand/madre-app.svg', 'image/svg+xml'],
1901
2031
  // The conversation's wallpapers (Appearance): twelve pictures, encoded by hand from their
1902
2032
  // masters (cwebp), whose light and dark, layer or mesh and intensity are layers in the CSS.
1903
2033
  ['/assets/wallpapers/jarrito.webp', 'image/webp'],
@@ -2022,7 +2152,7 @@ export async function createPulseServer({
2022
2152
  return sendJson(response, 403, { error: t('This is done on the Mac.') });
2023
2153
  }
2024
2154
  if (request.method === 'GET' && url.pathname === '/salas') {
2025
- const html = await readFile(join(publicDirectory, 'salas-mac.html'));
2155
+ const html = withHost(await readFile(join(publicDirectory, 'salas-mac.html'), 'utf8'));
2026
2156
  response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache', ...PAGE_GUARDS });
2027
2157
  return response.end(html);
2028
2158
  }
@@ -2030,6 +2160,20 @@ export async function createPulseServer({
2030
2160
  return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), url.pathname.endsWith('.js') ? 'text/javascript; charset=utf-8' : 'text/css; charset=utf-8');
2031
2161
  }
2032
2162
  // A widget of Home, read here (homeWidget above): only from this Mac's own pages.
2163
+ // Another copy of the author's, left out of the usage figures by its identifier (Settings ›
2164
+ // Version on that copy). Only from this computer's page, and only with the author's key.
2165
+ if (request.method === 'POST' && url.pathname === '/api/salas/usage/exclude') {
2166
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
2167
+ const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
2168
+ if (!token) return sendJson(response, 404, { error: t('Home has no widget by that name.') });
2169
+ const { id } = await body(request);
2170
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(String(id ?? '').trim())) return sendJson(response, 400, { error: t('That is not a copy\'s identifier. Copy it from Settings › Version on that copy.') });
2171
+ const answer = await reportFetch(process.env.PULSE_USAGE_URL ?? 'https://madre.run/api/usage', { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify({ exclude: String(id).trim().toLowerCase() }), signal: AbortSignal.timeout(8000) }).catch(() => null);
2172
+ const result = answer?.ok ? await answer.json().catch(() => null) : null;
2173
+ if (!result?.ok) return sendJson(response, 502, { error: t('madre.run did not answer. Try again in a moment.') });
2174
+ widgetReadings.delete('usage');
2175
+ return sendJson(response, 200, { ok: true });
2176
+ }
2033
2177
  if (request.method === 'GET' && url.pathname === '/api/salas/widget') {
2034
2178
  const reading = await homeWidget(String(url.searchParams.get('kind') ?? ''));
2035
2179
  if (!reading) return sendJson(response, 404, { error: t('Home has no widget by that name.') });
@@ -2049,7 +2193,14 @@ export async function createPulseServer({
2049
2193
  if (!salasRoom) ids.push(thisRoomId);
2050
2194
  for (const id of ids) if (id !== salasId && !(id in rooms)) rooms[id] = localAiFor(before, id).chosen;
2051
2195
  }
2052
- await updateConfig(root, localAiPatch(before, { mode: patch?.mode, rooms }));
2196
+ // The model for the whole computer: one Ollama has installed, or null to let MADRE pick.
2197
+ let model;
2198
+ if (patch?.model === null) model = null;
2199
+ else if (typeof patch?.model === 'string') {
2200
+ if (!(ollama.models ?? []).some((one) => one.name === patch.model)) return sendJson(response, 400, { error: t('That model is not installed. Download it first.') });
2201
+ model = patch.model;
2202
+ }
2203
+ await updateConfig(root, localAiPatch(before, { mode: patch?.mode, rooms, model }));
2053
2204
  await wireOllama({ probe: false });
2054
2205
  widgetReadings.delete('models');
2055
2206
  }
@@ -2066,19 +2217,22 @@ export async function createPulseServer({
2066
2217
  }));
2067
2218
  }
2068
2219
  const projects = known.map((one) => ({ id: one.id, name: one.name, open: Boolean(one.open), ...localAiFor(config, one.id) }));
2069
- return sendJson(response, 200, { ...localAiConfig(config), master: localAiFor(config).master, ollama: { running: Boolean(ollama.running), models: (ollama.models ?? []).length }, projects, later });
2220
+ return sendJson(response, 200, { ...localAiConfig(config), master: localAiFor(config).master, ollama: { running: Boolean(ollama.running), models: (ollama.models ?? []).length, using: ollama.chatModel ?? null, auto: ollama.autoModel ?? null }, projects, later });
2070
2221
  }
2071
2222
  if (request.method === 'GET' && url.pathname === '/api/salas') {
2072
2223
  const rooms = await knownRooms(root);
2073
2224
  const here = basename(roomDir);
2074
2225
  const own = await roomLooks(root);
2075
2226
  // A project that never chose its own wears the wallpaper every page shared before.
2076
- const before = (await readLooks(root)).looks['pulse.wallpaper'] ?? null;
2227
+ const shared = (await readLooks(root)).looks;
2228
+ const before = shared['pulse.wallpaper'] ?? null;
2077
2229
  const seen = await Promise.all(rooms.map(async (one) => ({
2078
2230
  ...one,
2079
2231
  here: one.id === here,
2080
2232
  glance: await lobbyGlance(one),
2081
2233
  wallpaper: own[one.id]?.wallpaper ?? before,
2234
+ // Its accent: its own, or Home's while it has none (1.0.5).
2235
+ accent: own[one.id]?.accent ?? shared['pulse.accent'] ?? 'madre',
2082
2236
  })));
2083
2237
  // The links in force (docs/MACROVERSO.md, fase 3c), each with what crossed: counted from the
2084
2238
  // lines the serving room keeps beside its record, never from a ledger. `salas` is the id of
@@ -2096,11 +2250,15 @@ export async function createPulseServer({
2096
2250
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) || (site !== undefined && site !== 'same-origin' && site !== 'none')) return sendJson(response, 403, { error: t('This is done from Home, on this Mac.') });
2097
2251
  const here = basename(roomDir);
2098
2252
  const rooms = (await knownRooms(root)).filter((one) => one.open);
2253
+ // Each project's accent (src/looks.mjs): its own, or Home's while it has none.
2254
+ const owns = await roomLooks(root);
2255
+ const homeAccent = (await readLooks(root)).looks['pulse.accent'] ?? 'madre';
2099
2256
  const seen = await Promise.all(rooms.map(async (one) => ({
2100
2257
  id: one.id,
2101
2258
  name: one.name,
2102
2259
  port: one.open.port,
2103
2260
  here: one.id === here,
2261
+ accent: owns[one.id]?.accent ?? homeAccent,
2104
2262
  glance: one.id === here ? null : await askRoom(one.open.port, '/api/glance'),
2105
2263
  })));
2106
2264
  return sendJson(response, 200, { here, salas: salasRoomId(root), rooms: seen });
@@ -2283,16 +2441,8 @@ export async function createPulseServer({
2283
2441
  const host = String(request.headers.host ?? '');
2284
2442
  const site = request.headers['sec-fetch-site'];
2285
2443
  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 turned off from its own page, on this computer.') });
2286
- const here = basename(roomDir);
2287
- const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
2288
- await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/close', { method: 'POST', body: {}, timeoutMs: 3000 }).catch(() => null)));
2289
- let left = others;
2290
- for (let tries = 0; tries < 60 && left.length; tries += 1) {
2291
- await new Promise((resolve) => setTimeout(resolve, 250));
2292
- const now = await knownRooms(root);
2293
- left = left.filter((one) => now.find((room) => room.id === one.id)?.open);
2294
- }
2295
- sendJson(response, 202, { closing: true, closed: others.length - left.length, stuck: left.map((one) => one.name) });
2444
+ const { closed, stuck } = await closeOtherRooms();
2445
+ sendJson(response, 202, { closing: true, closed, stuck });
2296
2446
  setTimeout(() => server.emit('madre:close'), 150);
2297
2447
  return undefined;
2298
2448
  }
@@ -2705,7 +2855,7 @@ export async function createPulseServer({
2705
2855
  if (request.method === 'GET' && url.pathname === '/api/state') {
2706
2856
  // `?chat=` reads another conversation, held open beside the one on screen; the room-wide
2707
2857
  // parts are the same, the record and what is running in it are that conversation's.
2708
- const here = await scopeOf(url);
2858
+ const here = await scopeOf(url, response);
2709
2859
  if (here.error) return sendJson(response, 404, here);
2710
2860
  const room = here.room;
2711
2861
  const store = here.store;
@@ -2770,7 +2920,7 @@ export async function createPulseServer({
2770
2920
  const sinceValue = request.headers['last-event-id'] ?? url.searchParams.get('since');
2771
2921
  const since = sinceValue === undefined || sinceValue === null || sinceValue === '' ? null : Number(sinceValue);
2772
2922
  // `?chat=` watches a conversation held open beside the one on screen, on a feed of its own.
2773
- const here = await scopeOf(url);
2923
+ const here = await scopeOf(url, response);
2774
2924
  if (here.error) return sendJson(response, 404, here);
2775
2925
  const feed = here.main ? mainFeed : await watchHeld(here.entry);
2776
2926
  response.writeHead(200, {
@@ -2965,7 +3115,7 @@ export async function createPulseServer({
2965
3115
  return sendJson(response, error.status ?? 400, { error: error.message });
2966
3116
  }
2967
3117
  const name = decodeURIComponent(request.headers['x-pulse-filename'] ?? url.searchParams.get('name') ?? 'attachment');
2968
- const here = await scopeOf(url);
3118
+ const here = await scopeOf(url, response);
2969
3119
  if (here.error) return sendJson(response, 404, here);
2970
3120
  const record = await here.room.registerAttachment(await storeAttachment(attachmentsRoot, { name, bytes }));
2971
3121
  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)}` } });
@@ -3016,7 +3166,8 @@ export async function createPulseServer({
3016
3166
  // switch does not move; /apply is how Home tells an open project the choice changed.
3017
3167
  if (request.method === 'GET' && url.pathname === '/api/local-ai') return sendJson(response, 200, { project: await localAiHere(), running: Boolean(ollama.running) });
3018
3168
  if (request.method === 'POST' && url.pathname === '/api/local-ai/apply') {
3019
- const status = await wireOllama({ probe: false });
3169
+ // Probed again: the model chosen in Home may have been downloaded after this project last looked.
3170
+ const status = await wireOllama();
3020
3171
  return sendJson(response, 200, { project: status.project });
3021
3172
  }
3022
3173
  if (request.method === 'POST' && url.pathname === '/api/local-ai') {
@@ -3130,13 +3281,13 @@ export async function createPulseServer({
3130
3281
  }
3131
3282
  if (request.method === 'GET' && url.pathname === '/api/questions') {
3132
3283
  const limit = Math.min(5, Math.max(1, Number(url.searchParams.get('limit') ?? 3) || 3));
3133
- const here = await scopeOf(url);
3284
+ const here = await scopeOf(url, response);
3134
3285
  if (here.error) return sendJson(response, 404, here);
3135
3286
  return sendJson(response, 200, { questions: here.room.questions({ limit }) });
3136
3287
  }
3137
3288
  if (request.method === 'GET' && url.pathname === '/api/decisions') {
3138
3289
  const limit = Math.min(5, Math.max(1, Number(url.searchParams.get('limit') ?? 3) || 3));
3139
- const here = await scopeOf(url);
3290
+ const here = await scopeOf(url, response);
3140
3291
  if (here.error) return sendJson(response, 404, here);
3141
3292
  return sendJson(response, 200, { decisions: here.room.decisions({ limit }) });
3142
3293
  }
@@ -3266,7 +3417,10 @@ export async function createPulseServer({
3266
3417
  // This project's own wallpaper («only in this project»), or back to the shared one with null.
3267
3418
  if (request.method === 'POST' && url.pathname === '/api/looks/room') {
3268
3419
  const payload = await body(request).catch(() => ({}));
3269
- const answer = await changeRoomLook(root, basename(roomDir), payload?.wallpaper ?? null);
3420
+ const change = {};
3421
+ if (payload && 'wallpaper' in payload) change.wallpaper = payload.wallpaper ?? null;
3422
+ if (payload && 'accent' in payload) change.accent = payload.accent ?? null;
3423
+ const answer = await changeRoomLook(root, basename(roomDir), Object.keys(change).length ? change : { wallpaper: null });
3270
3424
  return sendJson(response, answer.error ? 400 : 200, answer);
3271
3425
  }
3272
3426
  // How Home is arranged (src/looks.mjs, home.json): the same on every port Home is shown from.
@@ -3330,7 +3484,7 @@ export async function createPulseServer({
3330
3484
  if (request.method === 'POST' && url.pathname === '/api/messages/rate') {
3331
3485
  const payload = await body(request).catch(() => ({}));
3332
3486
  try {
3333
- const here = await scopeOf(url);
3487
+ const here = await scopeOf(url, response);
3334
3488
  if (here.error) return sendJson(response, 404, here);
3335
3489
  const event = await here.room.rateMessage(String(payload.messageId ?? ''), String(payload.rating ?? ''));
3336
3490
  return sendJson(response, 200, { rated: event.payload });
@@ -3375,11 +3529,11 @@ export async function createPulseServer({
3375
3529
  const fromHere = /^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) && (site === undefined || site === 'same-origin' || site === 'none');
3376
3530
  if (request.method === 'GET' && url.pathname === '/api/tour') {
3377
3531
  const state = await readTour(root);
3378
- if (viaPhone || !fromHere) return sendJson(response, 200, { version: TOUR_VERSION, state, owed: false, returning: false, chapters: CHAPTERS, hints: HINTS });
3532
+ if (viaPhone || !fromHere) return sendJson(response, 200, { version: TOUR_VERSION, state, owed: false, returning: false, chapters: CHAPTERS, hints: HINTS, level: NEWS_LEVEL });
3379
3533
  // Where this person comes from: the tour of 1.0 (path «since»), 0.7.2 (their words in a room's
3380
3534
  // record, path «back»), or nowhere — a first install.
3381
3535
  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;
3382
- return sendJson(response, 200, { version: TOUR_VERSION, state, owed: !state.bonjourAt, returning: Boolean(from), from, chapters: CHAPTERS, hints: HINTS });
3536
+ return sendJson(response, 200, { version: TOUR_VERSION, state, owed: !state.bonjourAt, returning: Boolean(from), from, chapters: CHAPTERS, hints: HINTS, level: NEWS_LEVEL });
3383
3537
  }
3384
3538
  if (viaPhone || !fromHere || (request.method === 'POST' && request.headers.origin !== `http://${host}`)) return sendJson(response, 403, { error: t('This is done on the Mac.') });
3385
3539
  if (request.method === 'POST' && url.pathname === '/api/tour') {
@@ -3399,7 +3553,9 @@ export async function createPulseServer({
3399
3553
  return sendJson(response, 404, { error: 'Not found' });
3400
3554
  }
3401
3555
  if (request.method === 'GET' && url.pathname === '/api/version') {
3402
- return sendJson(response, 200, await versionView({ force: url.searchParams.get('force') === '1' }));
3556
+ // With the one thing the daily notice says about this copy: its random identifier, shown so the
3557
+ // person can see it, and so the author can leave out a copy of his own (the usage widget).
3558
+ return sendJson(response, 200, { ...(await versionView({ force: url.searchParams.get('force') === '1' })), install: await installId(root).catch(() => null) });
3403
3559
  }
3404
3560
  // One click: install the newer version and come back on the same port. The room records it,
3405
3561
  // closes its listener so the port is free, hands the command to a detached shell and exits.
@@ -3497,7 +3653,7 @@ export async function createPulseServer({
3497
3653
  const mode = Math.min(4, Math.max(0, Number(url.searchParams.get('mode') ?? 1) || 0));
3498
3654
  const text = String(url.searchParams.get('text') ?? '').slice(0, 2000);
3499
3655
  const ash = url.searchParams.get('ash') === 'true';
3500
- const here = await scopeOf(url);
3656
+ const here = await scopeOf(url, response);
3501
3657
  if (here.error) return sendJson(response, 404, here);
3502
3658
  const room = here.room;
3503
3659
  const briefing = await room.briefing({ agent: asked, mode, text, ash });
@@ -3768,7 +3924,27 @@ export async function createPulseServer({
3768
3924
  await runInstaller({ command: opencode.path, args: ['models', '--verbose'], projectRoot: canonicalProjectRoot, timeoutMs: 30000, onLine: (line) => { lines.push(line); } });
3769
3925
  return parseOpenCodeVerbose(lines);
3770
3926
  };
3771
- return sendJson(response, 200, { models: await discoverModels({ agents, config: await readConfig(root), listOpenCode: url.searchParams.get('opencode') === '1' ? listOpenCode : async () => [] }) });
3927
+ // Gemini's, from Google with the person's own key, read once in a while (src/outbound.mjs,
3928
+ // gemini-models). Signed in with a Google account and no key, there is nothing to ask.
3929
+ const listGemini = async () => {
3930
+ if (geminiModels.at && Date.now() - geminiModels.at < 10 * 60 * 1000) return geminiModels.ids;
3931
+ const key = await imageKey().catch(() => null);
3932
+ if (!key) return [];
3933
+ const answer = await fetch('https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000', { headers: { 'x-goog-api-key': key }, signal: AbortSignal.timeout(8000) });
3934
+ if (!answer.ok) return [];
3935
+ const ids = parseGeminiModels(await answer.json());
3936
+ if (ids.length) Object.assign(geminiModels, { at: Date.now(), ids });
3937
+ return ids;
3938
+ };
3939
+ // Cursor's own list, read once in a while: it asks Cursor's servers, so not on every call.
3940
+ const listCursor = async (cursor) => {
3941
+ if (cursorModels.at && Date.now() - cursorModels.at < 10 * 60 * 1000) return cursorModels.ids;
3942
+ const { stdout } = await execFileAsync(cursor.path, ['--list-models'], { timeout: 20000, env: { ...process.env, NO_OPEN_BROWSER: '1' } });
3943
+ const ids = parseCursorModels(stdout);
3944
+ if (ids.length) Object.assign(cursorModels, { at: Date.now(), ids });
3945
+ return ids;
3946
+ };
3947
+ 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 () => [] }) });
3772
3948
  }
3773
3949
  // OpenCode's providers for AJUSTES: who has a key or an account, what each offers, which are
3774
3950
  // left out of the chooser. Never a key: only that one is there and of what kind.
@@ -3791,8 +3967,27 @@ export async function createPulseServer({
3791
3967
  const via = own ? 'own' : signed.get(id) ?? null;
3792
3968
  return { id, label: known?.label ?? providerLabel(id), keyUrl: known?.keyUrl ?? null, takesKey: Boolean(known), featured: Boolean(known?.featured), via, models: groups.get(id)?.models ?? [], hidden: hidden.has(id) };
3793
3969
  }).sort((a, b) => Number(Boolean(b.via)) - Number(Boolean(a.via)) || Number(a.via === 'own') - Number(b.via === 'own') || a.label.localeCompare(b.label));
3970
+ // A provider whose last turn was refused (no credit, a dead key) says so beside its name.
3971
+ const { problems } = await openCodeHealth(root);
3972
+ for (const provider of providers) provider.problem = problems[provider.id]?.kind ?? null;
3794
3973
  return sendJson(response, 200, { providers, default: process.env.PULSE_OPENCODE_MODEL ?? null });
3795
3974
  }
3975
+ // What to offer when an OpenCode turn failed on its provider: the model that answered last, or
3976
+ // one of OpenCode's own free models (src/opencode-health.mjs). Its own models are asked of the
3977
+ // CLI at most every ten minutes.
3978
+ if (request.method === 'GET' && url.pathname === '/api/agents/opencode/suggest') {
3979
+ const opencode = agents.find((agent) => agent.id === 'opencode');
3980
+ if (!opencode?.detected) return sendJson(response, 404, { error: t('OpenCode is not installed.') });
3981
+ if (!openCodeOwn.names || Date.now() - openCodeOwn.at > 600000) {
3982
+ const names = [];
3983
+ await runInstaller({ command: opencode.path, args: ['models', OPENCODE_OWN], projectRoot: canonicalProjectRoot, timeoutMs: 20000, onLine: (line) => { if (/^opencode\/[\w.:-]+$/.test(line.trim())) names.push(line.trim()); } }).catch(() => null);
3984
+ openCodeOwn.names = names;
3985
+ openCodeOwn.at = Date.now();
3986
+ }
3987
+ const health = await openCodeHealth(root);
3988
+ const failed = url.searchParams.get('failed') || process.env.PULSE_OPENCODE_MODEL || null;
3989
+ return sendJson(response, 200, { suggestion: suggestOpenCodeModel(health, { failed, own: openCodeOwn.names }), default: process.env.PULSE_OPENCODE_MODEL ?? null, problems: health.problems });
3990
+ }
3796
3991
  // A provider's key out of OpenCode, from this computer only, the same rule as putting one in.
3797
3992
  if (request.method === 'POST' && url.pathname === '/api/agents/opencode/providers/remove') {
3798
3993
  const address = request.socket.remoteAddress ?? '';
@@ -3816,7 +4011,7 @@ export async function createPulseServer({
3816
4011
  // One answer, not the room. The master brake lives next door and means something else.
3817
4012
  if (request.method === 'POST' && url.pathname === '/api/stop-turn') {
3818
4013
  const payload = await body(request).catch(() => ({}));
3819
- const here = await scopeOf(url);
4014
+ const here = await scopeOf(url, response);
3820
4015
  if (here.error) return sendJson(response, 404, here);
3821
4016
  const stopped = await here.room.stopTurn(String(payload.messageId ?? ''));
3822
4017
  return sendJson(response, stopped ? 200 : 404, stopped ? { stopped: true } : { error: t('That turn is not running any more.') });
@@ -3849,7 +4044,7 @@ export async function createPulseServer({
3849
4044
  }
3850
4045
  const stopMatch = request.method === 'POST' && url.pathname.match(/^\/api\/plans\/([0-9a-f-]+)\/stop$/);
3851
4046
  if (stopMatch) {
3852
- const here = await scopeOf(url);
4047
+ const here = await scopeOf(url, response);
3853
4048
  if (here.error) return sendJson(response, 404, here);
3854
4049
  const stopped = await here.room.stopPlan(stopMatch[1]);
3855
4050
  return sendJson(response, stopped ? 202 : 404, stopped ? { stopped: true } : { error: t('No running plan with that id.') });
@@ -3861,7 +4056,7 @@ export async function createPulseServer({
3861
4056
  const payload = await body(request).catch(() => ({}));
3862
4057
  const index = Number(payload.index);
3863
4058
  if (typeof payload.responseMessageId !== 'string' || !Number.isInteger(index) || index < 0) return sendJson(response, 400, { error: t('Name the request and the line to run.') });
3864
- const here = await scopeOf(url);
4059
+ const here = await scopeOf(url, response);
3865
4060
  if (here.error) return sendJson(response, 404, here);
3866
4061
  return here.room.stopRun({ responseMessageId: payload.responseMessageId, index }) ? sendJson(response, 202, { stopped: true }) : sendJson(response, 404, { error: t('That command is not running.') });
3867
4062
  }
@@ -3869,7 +4064,7 @@ export async function createPulseServer({
3869
4064
  const payload = await body(request).catch(() => ({}));
3870
4065
  const index = Number(payload.index);
3871
4066
  if (typeof payload.responseMessageId !== 'string' || !Number.isInteger(index) || index < 0) return sendJson(response, 400, { error: t('Name the request and the line to run.') });
3872
- const here = await scopeOf(url);
4067
+ const here = await scopeOf(url, response);
3873
4068
  if (here.error) return sendJson(response, 404, here);
3874
4069
  const outcome = await here.room.runRequested({ responseMessageId: payload.responseMessageId, index, returnCap: viaPhone ? PHONE_MAX_MODE : 3 });
3875
4070
  return sendJson(response, outcome.status, outcome.ok ? outcome.result : { error: outcome.error });
@@ -3878,7 +4073,7 @@ export async function createPulseServer({
3878
4073
  if (request.method === 'POST' && url.pathname === '/api/runs/return') {
3879
4074
  const payload = await body(request).catch(() => ({}));
3880
4075
  if (typeof payload.responseMessageId !== 'string') return sendJson(response, 400, { error: t('Say which request to hand back.') });
3881
- const here = await scopeOf(url);
4076
+ const here = await scopeOf(url, response);
3882
4077
  if (here.error) return sendJson(response, 404, here);
3883
4078
  const outcome = await here.room.returnRun({ responseMessageId: payload.responseMessageId, returnCap: viaPhone ? PHONE_MAX_MODE : 3 });
3884
4079
  return sendJson(response, outcome.status, outcome.ok ? outcome : { error: outcome.error });
@@ -3886,11 +4081,11 @@ export async function createPulseServer({
3886
4081
  if (request.method === 'GET' && url.pathname === '/api/commands') {
3887
4082
  const ctx = await moduleContext();
3888
4083
  const fromModules = await Promise.all(moduleCommands().map(async (command) => {
3889
- const settings = command.module.settingsFrom(ctx.config);
4084
+ const settings = command.module.settingsFrom(ctx.config, ctx.roomId);
3890
4085
  const on = command.module.kind !== 'builtin' || Boolean(settings.enabled);
3891
4086
  let available = on;
3892
4087
  if (on && command.available) { try { available = Boolean(await command.available({ ...ctx, settings })); } catch { available = false; } }
3893
- return { name: command.name, module: command.module.id, title: command.title, usage: command.usage, summary: command.summary, available };
4088
+ return { name: command.name, module: command.module.id, title: inRoomLanguage(command.title), usage: inRoomLanguage(command.usage), summary: inRoomLanguage(command.summary), available };
3894
4089
  }));
3895
4090
  return sendJson(response, 200, { commands: [...(await listCommands({ projectRoot: canonicalProjectRoot })), ...fromModules] });
3896
4091
  }
@@ -3908,16 +4103,22 @@ export async function createPulseServer({
3908
4103
  const own = moduleCommands().find((item) => item.name === parsed.name);
3909
4104
  if (!own) return sendJson(response, 404, { error: `Unknown command /${parsed.name}.` });
3910
4105
  const ctx = await moduleContext();
3911
- const settings = own.module.settingsFrom(ctx.config);
4106
+ // Turned on only in this project is on here (2026-10-19): read without the project, a
4107
+ // module switched on from its project's Market never had its command.
4108
+ const settings = own.module.settingsFrom(ctx.config, ctx.roomId);
3912
4109
  if (own.module.kind === 'builtin' && !settings.enabled) return sendJson(response, 412, { error: `/${parsed.name} belongs to ${own.module.name}, which is off. Enable it in MODULES.` });
3913
- if (own.available && !(await own.available({ ...ctx, settings }).catch(() => false))) return sendJson(response, 412, { error: `/${parsed.name} is not available here (${own.title}).` });
4110
+ if (own.available && !(await own.available({ ...ctx, settings }).catch(() => false))) return sendJson(response, 412, { error: `/${parsed.name} is not available here (${inRoomLanguage(own.title)}).` });
3914
4111
  try {
3915
4112
  const answer = await own.execute({ ...ctx, settings }, parsed.args);
3916
- result = { ok: answer?.ok !== false, title: answer?.title ?? own.title, text: String(answer?.text ?? '') };
3917
- } catch (error) { result = { ok: false, title: own.title, text: `/${parsed.name} failed: ${error.message}` }; }
4113
+ result = { ok: answer?.ok !== false, title: inRoomLanguage(answer?.title ?? own.title), text: String(answer?.text ?? '') };
4114
+ // A page of the module's own (a report to print, say): the card offers it as a key. Only
4115
+ // its own routes, /api/x/<id>/, on this room; never an address elsewhere.
4116
+ const href = typeof answer?.link?.href === 'string' ? answer.link.href : '';
4117
+ if (href.startsWith(`/api/x/${own.module.id}/`) && !/[\s"'<>\\]/.test(href) && href.length <= 400) result.link = { href, label: String(inRoomLanguage(answer.link.label) ?? '').slice(0, 80) || inRoomLanguage(own.title) };
4118
+ } catch (error) { result = { ok: false, title: inRoomLanguage(own.title), text: `/${parsed.name} failed: ${error.message}` }; }
3918
4119
  command = own;
3919
4120
  }
3920
- const here = await scopeOf(url);
4121
+ const here = await scopeOf(url, response);
3921
4122
  if (here.error) return sendJson(response, 404, here);
3922
4123
  const event = await here.room.recordCommand({ name: parsed.name, args: parsed.args, ...result });
3923
4124
  return sendJson(response, result.ok ? 200 : 422, { command: parsed.name, title: result.title, ok: result.ok, sequence: event.sequence });
@@ -3932,7 +4133,7 @@ export async function createPulseServer({
3932
4133
  if (request.method === 'GET' && url.pathname === '/api/market') {
3933
4134
  const kept = await keptCatalog({ stateRoot: root, ...marketKeyed });
3934
4135
  const read = kept ? (void syncMarket().catch(() => null), { catalog: kept }) : await syncMarket().catch(() => ({ catalog: null }));
3935
- return sendJson(response, 200, { catalog: read.catalog ?? null, off: !marketOn(), installed: await installedFromMarket(root), news: await marketNews(root), announce: await marketAnnouncements(root, read.catalog, MODULES.map((one) => one.id)), madre: PACKAGE.version });
4136
+ 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 });
3936
4137
  }
3937
4138
  if (request.method === 'POST' && url.pathname === '/api/market/seen') {
3938
4139
  await marketNewsSeen(root);
@@ -3961,6 +4162,26 @@ export async function createPulseServer({
3961
4162
  return sendJson(response, 200, { installed: done, extensions: await describeModules(await moduleContext()) });
3962
4163
  } catch (error) { return sendJson(response, 422, { error: error.message }); }
3963
4164
  }
4165
+ // A paid module's license (src/market-license.mjs): checked once with Lemon Squeezy when the
4166
+ // person activates it, kept here, and given back when they release it. Only from this Mac.
4167
+ if (request.method === 'POST' && (url.pathname === '/api/market/license' || url.pathname === '/api/market/license/release')) {
4168
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4169
+ const payload = await body(request).catch(() => ({}));
4170
+ const id = String(payload.id ?? '');
4171
+ try {
4172
+ if (url.pathname === '/api/market/license/release') {
4173
+ await releaseLicense({ stateRoot: root, id, fetchImpl: marketFetch, ...licenseKeyed });
4174
+ await room.record('market.license.released', { id });
4175
+ return sendJson(response, 200, { released: id, licensed: await licensedIds(root) });
4176
+ }
4177
+ const catalog = (await keptCatalog({ stateRoot: root, ...marketKeyed })) ?? (await syncMarket({ force: true }).catch(() => ({}))).catalog;
4178
+ const entry = catalog?.modules.find((one) => one.id === id);
4179
+ if (!entry) return sendJson(response, 404, { error: t('The Market has no module «{id}» to install.', { id }) });
4180
+ const done = await activateLicense({ stateRoot: root, entry, key: payload.key, installId: await installId(root), fetchImpl: marketFetch, ...licenseKeyed });
4181
+ await room.record('market.license.activated', { id });
4182
+ return sendJson(response, 200, { activated: done.id, licensed: await licensedIds(root) });
4183
+ } catch (error) { return sendJson(response, 422, { error: error.message }); }
4184
+ }
3964
4185
  // Home's view of which projects each module is on in (module-scope.mjs), and where the
3965
4186
  // modules that install into a project's folder are installed.
3966
4187
  if (request.method === 'GET' && url.pathname === '/api/modules/scope') {
@@ -4063,7 +4284,7 @@ export async function createPulseServer({
4063
4284
  return sendJson(response, result.status, result.body);
4064
4285
  }
4065
4286
  if (request.method === 'POST' && /^\/api\/control\/[\w-]+\/undo$/.test(url.pathname)) {
4066
- const here = await scopeOf(url);
4287
+ const here = await scopeOf(url, response);
4067
4288
  if (here.error) return sendJson(response, 404, here);
4068
4289
  const result = await here.room.undoControl(url.pathname.split('/')[3]);
4069
4290
  return sendJson(response, result.ok ? 200 : result.status ?? 400, result);
@@ -4071,7 +4292,7 @@ export async function createPulseServer({
4071
4292
  if (request.method === 'POST' && /^\/api\/modes\/[\w-]+\/decide$/.test(url.pathname)) {
4072
4293
  const requestId = url.pathname.split('/')[3];
4073
4294
  const { decision, key } = await body(request);
4074
- const here = await scopeOf(url);
4295
+ const here = await scopeOf(url, response);
4075
4296
  if (here.error) return sendJson(response, 404, here);
4076
4297
  if (!['once', 'plan', 'deny'].includes(decision)) return sendJson(response, 400, { error: t('Decision must be once, plan or deny.') });
4077
4298
  const asked = here.room.modeRequest(requestId);
@@ -4095,7 +4316,7 @@ export async function createPulseServer({
4095
4316
  } else delete payload.via;
4096
4317
  // `?chat=` sends into a conversation held open beside the one on screen. TURNS counts it
4097
4318
  // like any other: the conversation on screen is one of the "others" when it is working.
4098
- const here = await scopeOf(url);
4319
+ const here = await scopeOf(url, response);
4099
4320
  if (here.error) return sendJson(response, 404, here);
4100
4321
  // A switch moved in Home since this project opened reaches it here (module-scope.mjs).
4101
4322
  applyModuleSwitches(here.room, await readConfig(root));
@@ -4149,6 +4370,7 @@ export async function createPulseServer({
4149
4370
  // long-lived SSE responses must be ended before the native close runs.
4150
4371
  const nativeClose = server.close.bind(server);
4151
4372
  server.close = (callback) => {
4373
+ serverClosing = true;
4152
4374
  clearInterval(poller);
4153
4375
  serverSentinel.stop();
4154
4376
  clearTimeout(embedKick);
@@ -4159,8 +4381,10 @@ export async function createPulseServer({
4159
4381
  // off() also ends the streams of pages watching a conversation held open beside.
4160
4382
  for (const held of parked.values()) held.off();
4161
4383
  parked.clear();
4162
- shutdown.then(() => {
4163
- void broadcastPending().then(() => chatWrites).then(() => {
4384
+ // The catalog asked of madre.run at start may still be on its way: when the ask fails, a note
4385
+ // of it is written to the state folder, and the outbound log says the request went out.
4386
+ shutdown.then(lateWritesDone).then(() => marketSync?.catch(() => null)).then(() => {
4387
+ void broadcastPending().then(() => chatWrites).then(async () => {
4164
4388
  unsubscribe();
4165
4389
  unsubscribeSentinel();
4166
4390
  unsubscribeEyecat();
@@ -4170,7 +4394,7 @@ export async function createPulseServer({
4170
4394
  clients.clear();
4171
4395
  // The memory file closes last, once nothing else writes to it; WAL and shm go with it.
4172
4396
  try { memory?.close(); } catch { /* already closed */ }
4173
- void outbound.drain();
4397
+ await outbound.close().catch(() => null);
4174
4398
  releaseOpen();
4175
4399
  nativeClose(callback);
4176
4400
  server.closeIdleConnections?.();
@@ -4182,11 +4406,11 @@ export async function createPulseServer({
4182
4406
  server.on('close', () => { for (const timer of aliveTimers) clearTimeout(timer); });
4183
4407
 
4184
4408
  server.on('close', () => { void phone.stop(); });
4185
- return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone };
4409
+ return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone, salasRoom, closeOtherRooms };
4186
4410
  }
4187
4411
 
4188
4412
  export async function startPulse({ port, projectRoot, openBrowser, openPath = '' }) {
4189
- const { server, agents, markOpen, phone } = await createPulseServer({ projectRoot, quotaSources: defaultQuotaSources() });
4413
+ const { server, agents, markOpen, phone, salasRoom, closeOtherRooms } = await createPulseServer({ projectRoot, quotaSources: defaultQuotaSources() });
4190
4414
  await new Promise((resolve, reject) => {
4191
4415
  server.once('error', reject);
4192
4416
  server.listen(port, '127.0.0.1', resolve);
@@ -4197,13 +4421,21 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
4197
4421
  // From here this room offers to host the phone's bridge, when there is a phone to reach it.
4198
4422
  phone.start();
4199
4423
  const url = `http://127.0.0.1:${address.port}`;
4424
+ // Installed is all this line knows: whether each one is signed in is asked in the room, and
4425
+ // «Ready: Codex, Claude…» before any sign-in told a newcomer the opposite (2026-10-19).
4200
4426
  const ready = agents.filter((agent) => agent.ready).map((agent) => agent.label).join(', ') || 'none';
4201
- const detected = agents.filter((agent) => agent.detected).map((agent) => agent.label).join(', ') || 'none';
4202
- console.log(`\nMADRE is ready\n\n ${url}${openPath}\n Project: ${projectRoot}\n Ready: ${ready}\n Detected: ${detected}\n`);
4427
+ const broken = agents.filter((agent) => agent.detected && !agent.ready).map((agent) => agent.label).join(', ');
4428
+ console.log(`\nMADRE is ready\n\n ${url}${openPath}\n Project: ${projectRoot}\n Agents installed: ${ready} (who is signed in: Settings › Agents)\n${broken ? ` Found but not answering: ${broken}\n` : ''}`);
4203
4429
  if (openBrowser) openUrl(`${url}${openPath}`);
4204
4430
  // SIGHUP too: closing the Terminal the room was started in is a way of closing it.
4431
+ // Home closed this way closes what Turn MADRE off closes (2026-10-21): every open project, also
4432
+ // one opened from another project, whose process outlives Home on its own. A second signal while
4433
+ // they close is not caught again and ends Home at once.
4205
4434
  for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
4206
- process.once(signal, () => server.close(() => process.exit(0)));
4435
+ process.once(signal, async () => {
4436
+ if (salasRoom) await closeOtherRooms().catch(() => null);
4437
+ server.close(() => process.exit(0));
4438
+ });
4207
4439
  }
4208
4440
  // Salas asked this room to close: the same as a signal.
4209
4441
  server.once('madre:close', () => server.close(() => process.exit(0)));