@jossuealcala/madre 1.1.3 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.en.md +20 -1
  2. package/CHANGELOG.md +20 -1
  3. package/TRADEMARKS.md +6 -2
  4. package/bin/madre.mjs +4 -2
  5. package/docs/REFERENCE.md +3 -3
  6. package/docs/SDK.md +28 -1
  7. package/docs/en/REFERENCE.md +2 -2
  8. package/docs/en/SDK.md +26 -0
  9. package/docs/sdk/hello-module.mjs +38 -3
  10. package/habilidades/explicamelo-facil/HABILIDAD.md +19 -0
  11. package/habilidades/hojas-de-calculo/HABILIDAD.md +18 -0
  12. package/habilidades/mensajes-a-clientes/HABILIDAD.md +19 -0
  13. package/habilidades/publicaciones-para-redes/HABILIDAD.md +19 -0
  14. package/habilidades/resumen-y-pendientes/HABILIDAD.md +18 -0
  15. package/habilidades/tu-pagina-paso-a-paso/HABILIDAD.md +19 -0
  16. package/package.json +4 -3
  17. package/public/activity.js +57 -22
  18. package/public/app.js +3998 -762
  19. package/public/assets/brand/OFL-SpaceGrotesk.txt +93 -0
  20. package/public/assets/brand/SpaceGrotesk-latin-ext.woff2 +0 -0
  21. package/public/assets/brand/SpaceGrotesk-latin.woff2 +0 -0
  22. package/public/assets/brand/madre-app-180.png +0 -0
  23. package/public/assets/brand/madre-app-192.png +0 -0
  24. package/public/assets/brand/madre-app-512.png +0 -0
  25. package/public/assets/brand/madre-app.svg +1 -1
  26. package/public/assets/brand/madre-favicon.svg +1 -1
  27. package/public/attribution.js +28 -27
  28. package/public/auto-open.js +102 -0
  29. package/public/brands.js +9 -6
  30. package/public/changes.js +63 -0
  31. package/public/en.js +1085 -101
  32. package/public/es.js +2395 -1688
  33. package/public/i18n.js +11 -0
  34. package/public/index.html +28 -27
  35. package/public/loader.js +322 -117
  36. package/public/macroverso.js +33 -350
  37. package/public/manual-content.js +37 -7
  38. package/public/manual.js +21 -6
  39. package/public/market-view.js +212 -105
  40. package/public/market.js +10 -2
  41. package/public/mcp-catalog.js +7 -2
  42. package/public/missions.js +169 -0
  43. package/public/news-scenes.js +110 -3
  44. package/public/nostromo-engine.js +935 -654
  45. package/public/notices.js +14 -2
  46. package/public/notifications.js +119 -0
  47. package/public/provider-marks.js +170 -0
  48. package/public/provider-pick.js +147 -0
  49. package/public/resay.js +1 -0
  50. package/public/review-ask.js +16 -13
  51. package/public/routing.js +29 -3
  52. package/public/salas-mac.css +257 -40
  53. package/public/salas-mac.html +5 -5
  54. package/public/salas-mac.js +376 -97
  55. package/public/salas.css +2 -2
  56. package/public/salas.html +2 -2
  57. package/public/salas.js +1 -1
  58. package/public/starters.js +128 -0
  59. package/public/styles.css +2656 -336
  60. package/public/subscription.js +303 -0
  61. package/public/terms-field.js +170 -0
  62. package/public/terms.js +117 -19
  63. package/public/tips.js +41 -7
  64. package/public/tour-chapters.js +35 -35
  65. package/public/tour.js +333 -43
  66. package/public/troubleshooting.js +100 -7
  67. package/public/welcome-scene.js +117 -29
  68. package/public/welcome.js +364 -60
  69. package/src/adapters/claude.mjs +2 -1
  70. package/src/adapters/codex.mjs +2 -1
  71. package/src/adapters/cursor.mjs +9 -6
  72. package/src/adapters/gemini.mjs +4 -0
  73. package/src/adapters/grok.mjs +6 -4
  74. package/src/adapters/madre.mjs +71 -23
  75. package/src/adapters/opencode.mjs +15 -2
  76. package/src/adapters/steps.mjs +176 -0
  77. package/src/app-invite.mjs +90 -0
  78. package/src/billing-key.mjs +8 -0
  79. package/src/billing.mjs +317 -0
  80. package/src/bridge/policy.mjs +1 -1
  81. package/src/capabilities.mjs +17 -11
  82. package/src/chats.mjs +44 -2
  83. package/src/checkpoint.mjs +5 -1
  84. package/src/commands.mjs +5 -2
  85. package/src/directives.mjs +1 -0
  86. package/src/event-store.mjs +15 -0
  87. package/src/extensions.mjs +5 -1
  88. package/src/ficha.mjs +16 -0
  89. package/src/image-studio.mjs +13 -3
  90. package/src/install-metrics.mjs +9 -3
  91. package/src/lease.mjs +1 -1
  92. package/src/looks.mjs +4 -1
  93. package/src/mcp/image-server.mjs +59 -90
  94. package/src/modules/ahp.mjs +2 -1
  95. package/src/modules/github.mjs +6 -2
  96. package/src/modules/image-providers.mjs +281 -0
  97. package/src/modules/image-studio.mjs +100 -19
  98. package/src/modules/index.mjs +7 -1
  99. package/src/modules/intents-observe.mjs +3 -1
  100. package/src/modules/playwright.mjs +33 -4
  101. package/src/modules/reminders.mjs +42 -2
  102. package/src/modules/ripley.mjs +2 -1
  103. package/src/modules/sdk.mjs +6 -1
  104. package/src/opencode-health.mjs +1 -1
  105. package/src/outbound.mjs +80 -6
  106. package/src/quota-sources.mjs +148 -3
  107. package/src/review-ask.mjs +55 -31
  108. package/src/room/changes.mjs +79 -0
  109. package/src/room/economy.mjs +1 -1
  110. package/src/room/guard.mjs +8 -1
  111. package/src/room/prompt.mjs +20 -4
  112. package/src/room.mjs +87 -21
  113. package/src/salas.mjs +30 -3
  114. package/src/server.mjs +545 -59
  115. package/src/setup.mjs +1 -1
  116. package/src/skills.mjs +10 -0
  117. package/src/terms.mjs +23 -5
  118. package/src/tour.mjs +18 -3
  119. package/src/updates.mjs +47 -4
  120. package/src/web-preview.mjs +181 -0
  121. package/src/whats-new.mjs +76 -4
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, rmSync } from 'node:fs';
5
+ import { closeSync, 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';
@@ -25,7 +25,7 @@ import { ErrorSentinel } from './sentinel-errors.mjs';
25
25
  import { probeOllama, ollamaEmbedder, ollamaGenerate, ollamaInvoker, patientFetch, pullModel, ollamaVersions, ownOllamaServers } from './ollama.mjs';
26
26
  import { recallForTurn } from './modules/enlaces.mjs';
27
27
  import { hardwareOnce, MODEL_TIERS } from './modules/local-models.mjs';
28
- import { browserAdvice, environmentOnce, openBrowser as openInBrowser } from './environment.mjs';
28
+ import { browserAdvice, browserWays, environmentOnce, openBrowser as openInBrowser } from './environment.mjs';
29
29
  import { installTrouble, loginTrouble } from './setup-trouble.mjs';
30
30
  import { MODULES, moduleById, describeModules, findModuleRoute, toolsForTurn as modulesToolsForTurn, loadExternalModules, loadFailures, moduleFolders, moduleCommands, installModuleFile, installModuleText, verifyModuleText, moduleOrigin, removeExternalModule, adoptBuiltinUpdates, packagedVersions } from './modules/index.mjs';
31
31
  import { understandsSdk } from './modules/sdk.mjs';
@@ -33,8 +33,11 @@ import { updateBuiltins } from './builtin-updates.mjs';
33
33
  import { madreAgent, madreInvoker, MADRE_AGENT_ID, MADRE_ADAPTER } from './adapters/madre.mjs';
34
34
  import { exportDataset, forgetCorpus, keepCorpus, keptCorpus, pruneCorpora, readiness as datasetReadiness } from './dataset.mjs';
35
35
  import { OutboundLog, outboundView, DEFAULT_REPORT_URL } from './outbound.mjs';
36
+ import { webPreview } from './web-preview.mjs';
36
37
  import { Telemetry, telemetryOn } from './telemetry.mjs';
37
38
  import { hostFacts, inRoomLanguage, language as roomLanguage, say, setLanguage as setRoomLanguage, t } from './i18n.mjs';
39
+ import { BILLING_PUBLIC_KEY } from './billing-key.mjs';
40
+ import { ORDER_EVERY_MS, ORDER_FAST_MS, PRICE_MXN, RECOVERY_KEEP_MS, SWITCH_EVERY_MS, TRIAL_DAYS, askOrder, askRecovery, askSwitch, billingInApp, billingSite, chooseProject, claimProject, dueMoment, loadBilling, markSeen as markBillingSeen, newOrder, portalUrl, renewKey, signSwitch, startRecovery, stopRecovery, verifiedSwitch } from './billing.mjs';
38
41
 
39
42
  // One per start of this process: a restart is a new one, a reload of the page is not.
40
43
  const BOOT_ID = `${process.pid}-${Date.now().toString(36)}`;
@@ -85,17 +88,26 @@ import { forgetSecret, readSecret, summary as vaultSummary, writeSecret } from '
85
88
  import { applyConfigToEnv, loadConfig as readConfig, updateConfig } from './config.mjs';
86
89
  import { Privacy, normalizeTerms, privacySettings } from './privacy.mjs';
87
90
  import { planView, removeMadre, uninstallPlan } from './uninstall.mjs';
88
- import { checkForUpdate, detectInstall, updateCommand, releaseUrl, applyCommand, fetchCommand } from './updates.mjs';
91
+ import { canReplace, checkForUpdate, detectInstall, updateCommand, releaseUrl, applyCommand, fetchCommand, nextProcess, opensBrowser, roomsBehind, takesItsPlace } from './updates.mjs';
89
92
  import { INVITE_ANSWERS, bootWhatsNew, cameFromOlder, invitedFor, markInvited, markSeen, newestNotes, notesFor, whatsNew } from './whats-new.mjs';
90
- import { answerAsk, tickAsk } from './review-ask.mjs';
91
- import { CHAPTERS, HINTS, NEWS_LEVEL, TOUR_VERSION, WELCOME_STEPS, cameBefore, changeTour, readTour, recoverProject, roomsWithoutProject } from './tour.mjs';
93
+ import { answerAppInvite, appInvite } from './app-invite.mjs';
94
+ import { answerAsk, askVia, tickAsk } from './review-ask.mjs';
95
+ import { CHAPTERS, HINTS, MISSIONS, NEWS_LEVEL, TOUR_VERSION, WELCOME_STEPS, cameBefore, changeTour, readTour, recoverProject, roomsWithoutProject } from './tour.mjs';
92
96
 
93
97
  // Where a person reads the module contract, in the language the room is speaking.
94
98
  const SDK_PAGE = { es: 'https://madre.run/sdk/', en: 'https://madre.run/en/sdk/' };
99
+ // The kinds of notification of the system a person turns on or off (/api/notifications), and `enabled`,
100
+ // MADRE's own switch for all of them (2026-11-14). A new version and the author's notices are not among
101
+ // them: they always go out (public/notifications.js).
102
+ const NOTIFICATION_KINDS = ['enabled', 'conversations'];
103
+ // @madre is offered a test once agents answered this many real questions in a conversation, and
104
+ // offered again after these days while it has not been measured (offerLocalTry).
105
+ const LOCAL_TRY_MIN = 6;
106
+ const LOCAL_TRY_AGAIN_MS = 3 * 24 * 60 * 60 * 1000;
95
107
  import { moduleUpdate } from './modules/updates.mjs';
96
108
  import { ACTIVITY_SOON_MS, recentInProject } from './activity.mjs';
97
109
  import { readReminders } from './modules/reminders.mjs';
98
- import { adoptStrays, chatIndex, chatLedger, createChat, deleteChat, isChatId, listChats, openChat as openChatIndex, searchChats, projectFloor, renameChat, touchChat } from './chats.mjs';
110
+ import { adoptStrays, chatIndex, chatLedger, createChat, deleteChat, isChatId, listChats, openChat as openChatIndex, archiveChat, carryChat, pinChat, searchChats, projectFloor, renameChat, touchChat } from './chats.mjs';
99
111
  import { spawn } from 'node:child_process';
100
112
  import { cpus, freemem, loadavg, totalmem } from 'node:os';
101
113
  import { discoverModels, groupOpenCode, openCodeHidden, parseCursorModels, parseGeminiModels, parseOpenCodeVerbose, providerLabel, OPENCODE_OWN } from './models.mjs';
@@ -113,6 +125,7 @@ import { summarizeHistory } from './history.mjs';
113
125
  import { migrateOpenCodeHealth, noteOpenCodeTurn, openCodeHealth, suggestOpenCodeModel } from './opencode-health.mjs';
114
126
  import { normalizeMode, setAgentsViaApi, setImageModule } from './capabilities.mjs';
115
127
  import { resolveGeminiKey } from './image-studio.mjs';
128
+ import { findImageSources } from './modules/image-providers.mjs';
116
129
  import { commandByName, listCommands, parseCommand } from './commands.mjs';
117
130
  import { listDirectory, searchFiles, readServable, storeAttachment, keepAttachment, attachmentPlaceRefused, ATTACHMENT_REFUSED, resolveInside, createEmptyFile, writeEdited, MAX_ATTACHMENT_BYTES, MAX_EDIT_BYTES } from './files.mjs';
118
131
  import { planFileOp, freeCopyPath, needsDesignationOnDisk, CREATIONS } from './file-ops.mjs';
@@ -133,7 +146,7 @@ import { qrSvg } from './bridge/qr.mjs';
133
146
  import { readHandoff, writeHandoff } from './bridge/handoff.mjs';
134
147
  import { changeHome, changeLooks, readHome, readLooks, changeRoomLook, roomLooks, WALLPAPER_BYTES, dropWallpaper, frameWallpaper, readWallpaper, saveWallpaper, wallpaperBytes } from './looks.mjs';
135
148
  import { localAiConfig, localAiFor, localAiPatch } from './local-ai.mjs';
136
- import { moduleOnIn, scopeView, settingsIn } from './module-scope.mjs';
149
+ import { moduleOnIn, scopeView, settingsIn, switchIn } from './module-scope.mjs';
137
150
  import { chooseSkills, declaredBy as skillDeclares, installSkill, isSkillFile, loadSkills, readSkillText, removeSkill, shareSkill, skillState, skillStateIn, skillIdOf, SKILL_FILES, SKILL_STATES } from './skills.mjs';
138
151
  import { findSkills, importSkills } from './skills-import.mjs';
139
152
  import { ASKS as SKILL_ASKS, SKILL_LICENSES, SKILL_SHELVES, submissionDraft as skillDraft, writeSubmission as writeSkillSubmission } from './skill-check.mjs';
@@ -145,15 +158,15 @@ import { forgetFromMarket, installFromMarket, installSkillFromMarket, installedF
145
158
  const NOT_BY_PROJECT = new Set(['bishop', 'git-pulse', 'ollama']);
146
159
  import { heartbeat, installId } from './heartbeat.mjs';
147
160
  import { PRESENCE_EVERY_MS, environmentGauges, noteLifecycle, sayPresent } from './install-metrics.mjs';
148
- import { TERMS_LINKS, acceptTerms, cameFromBefore, readTerms } from './terms.mjs';
161
+ import { acceptTerms, cameFromBefore, readTerms, termsKind, termsLinks } from './terms.mjs';
149
162
  import { activateLicense, licensedIds, releaseLicense } from './market-license.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';
163
+ import { askRoom, associateProject, createProject, createSampleProject, defaultProjectsFolder, ensureSalasProject, forgetProject, isSalasRoom, keepOpenProject, knownRooms, listFolders, markProject, projectRoomId, projectTitle, renameProject, roomComesUp, salasRoomId, startRoom, suggestProjects, universeOf } from './salas.mjs';
164
+ import { UNIT_NAME, disableService, enableService, launcherScript, refreshLauncher, serviceState } from './service.mjs';
152
165
  import { parseWork, recentWork, WORK_SYSTEM, workPrompt } from './lobby-work.mjs';
153
166
  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';
154
167
  import { readContinuity } from './modules/ahp.mjs';
155
168
  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';
169
+ import { FICHA_HEADER, FICHA_NEEDED, FICHA_PARAM, carriesFicha, defaultStateRoot, ensureFicha, fichaCookie, fichaHeaders, fichaReader, fichaShown, openPrivateLog, previewKey, withoutFicha, readFicha, sameFicha, withFicha } from './ficha.mjs';
157
170
 
158
171
  const sourceDirectory = dirname(fileURLToPath(import.meta.url));
159
172
  const publicDirectory = join(sourceDirectory, '..', 'public');
@@ -205,14 +218,20 @@ function sendJson(response, status, value) {
205
218
  // A request's JSON, read whole before it is decoded (2026-10-12, SRV-08): a «ñ» split between two
206
219
  // packets came out as «��». The limit is in bytes; a route that takes more says so (the editor).
207
220
  const BODY_LIMIT = 100_000;
208
- async function body(request, { limit = BODY_LIMIT } = {}) {
221
+ // A message takes a long paste — a log, a file pasted whole (D-40, 2026-11-10: refused at 100 KB).
222
+ const MESSAGE_LIMIT = 1_000_000;
223
+ async function body(request, { limit = BODY_LIMIT, tooLarge = null } = {}) {
209
224
  const chunks = [];
210
225
  let size = 0;
211
226
  for await (const chunk of request) {
212
227
  size += chunk.length;
213
- if (size > limit) throw Object.assign(new Error('Request too large.'), { status: 413 });
214
- chunks.push(chunk);
228
+ if (size <= limit) { chunks.push(chunk); continue; }
229
+ // Past the limit the rest is read and dropped, so the answer that says why reaches the page: cut
230
+ // in the middle of the upload, Node 22 lost it and the page waited forever (CI of 1.1.4,
231
+ // D-40). Only something many times the limit is cut.
232
+ if (size > limit * 8) break;
215
233
  }
234
+ if (size > limit) throw Object.assign(new Error(tooLarge ?? t('That is too much to send at once.')), { status: 413 });
216
235
  return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
217
236
  }
218
237
 
@@ -285,6 +304,8 @@ export async function createPulseServer({
285
304
  credentialHome = homedir(),
286
305
  probe = probeAll,
287
306
  imageKey = resolveGeminiKey,
307
+ // Where Images finds each provider's key (src/modules/image-providers.mjs); null reads this computer.
308
+ imageSources = null,
288
309
  // The sentinel's outbound channel; tests hand in a fake.
289
310
  reportFetch = globalThis.fetch,
290
311
  // The Market's catalog and module files from madre.run (src/market-remote.mjs); tests hand in a
@@ -297,12 +318,18 @@ export async function createPulseServer({
297
318
  licenseApi = null,
298
319
  // Ollama detection; tests hand in a fake probe. PULSE_OLLAMA=0 leaves Ollama alone entirely.
299
320
  ollamaProbe = process.env.PULSE_OLLAMA === '0' ? async () => ({ running: false, host: null, models: [], embedModel: null, chatModel: null, disabled: true }) : probeOllama,
321
+ // When Ollama did not answer the first look, how long until it is asked again; the last wait
322
+ // repeats (L-14). Tests hand in short ones.
323
+ ollamaRetryMs = [10_000, 30_000, 90_000, 300_000],
300
324
  // Whether every request has to carry the ficha (src/ficha.mjs). Only the CLI entry point
301
325
  // (startPulse) turns it on, as it does the quota sources; a test that checks it turns it on too.
302
326
  // `renewFicha`: asked when the browser is opened by this start; only Home acts on it, and makes a
303
327
  // new one for this run. A project Home opens keeps Home's.
304
328
  ficha: fichaOn = false,
305
329
  renewFicha = false,
330
+ // The keys MADRE App's subscription checks against (src/billing.mjs). Only a test passes its own;
331
+ // no environment variable changes them.
332
+ billingKeys = {},
306
333
  }) {
307
334
  const root = stateRoot ?? process.env.PULSE_HOME ?? join(homedir(), '.pulse');
308
335
  const currentFicha = fichaOn ? fichaReader(root) : async () => null;
@@ -321,7 +348,8 @@ export async function createPulseServer({
321
348
  // opens it (public/i18n.js, browserLanguage), once, and keeps it as if it had been chosen.
322
349
  let languageChosen = Boolean(process.env.PULSE_LANGUAGE || (await readConfig(root)).language);
323
350
  // RIPLEY renders HTML in the viewer only while the human has it switched on; read live, the switch is the module's.
324
- const ripleyOn = async () => moduleOnHere(await readConfig(root), 'ripley');
351
+ // On unless the person turned it off (2026-11-14): the module's own default (src/modules/ripley.mjs).
352
+ const ripleyOn = async () => moduleOnHere(await readConfig(root), 'ripley', true);
325
353
  agentTimeouts ??= agentTimeoutsFromEnv();
326
354
  const detector = detect ?? (providedAgents ? null : detectAgents);
327
355
  const refreshCodexRoute = async (agent) => agent.id === 'codex' && agent.route
@@ -422,6 +450,51 @@ export async function createPulseServer({
422
450
  }
423
451
  return { closed: others.length - left.length, stuck: left.map((one) => one.name) };
424
452
  }
453
+ // UPDATING ALL OF MADRE (L-13, Carlos's server, 2026-11-10). An update restarted only the room it
454
+ // was pressed in: Carlos updated a project, Home and the other projects stayed on the older MADRE,
455
+ // and with the ficha of the new one in between he was left outside. The start that comes from an
456
+ // update now brings every other open room on an older MADRE to this one: asked to close the way
457
+ // Home closes one, and opened again by this copy's own script on the port it had. The older one is
458
+ // only asked to close, so this works from any version before it. A room with something running is
459
+ // left for the next round (every minute, for an hour). Home as a service of this Linux comes back
460
+ // through systemd, its launcher saying the new version first. A copy installed inside a project
461
+ // is not the MADRE of the others, and is left alone.
462
+ async function bringOthersAlong({ rounds = 60, everyMs = 60000 } = {}) {
463
+ if (install !== 'npx' && install !== 'global') return;
464
+ const here = basename(roomDir);
465
+ for (let round = 0; round < rounds; round += 1) {
466
+ const behind = roomsBehind(await knownRooms(root), { here, version: PACKAGE.version });
467
+ if (!behind.length) return;
468
+ for (const one of behind) await bringAlong(one).catch(() => false);
469
+ if (round < rounds - 1) await new Promise((resolve) => setTimeout(resolve, everyMs));
470
+ }
471
+ }
472
+ async function bringAlong(one) {
473
+ const home = one.id === salasRoomId(root);
474
+ if (!one.root) return false;
475
+ const running = await askRoom(one.open.port, '/api/activity', { stateRoot: root, timeoutMs: 3000 });
476
+ if (running.unreachable || running.now?.length) return false;
477
+ const service = home && process.platform === 'linux' ? await serviceState().catch(() => null) : null;
478
+ if (service?.active) await refreshLauncher({ stateRoot: root, launcher: launcherScript({ install, name: PACKAGE.name, version: PACKAGE.version, port: one.open.port, env: process.env }) }).catch(() => false);
479
+ await askRoom(one.open.port, '/api/room/close', { stateRoot: root, method: 'POST', body: {}, timeoutMs: 3000 }).catch(() => null);
480
+ let gone = false;
481
+ for (let tries = 0; tries < 60 && !gone; tries += 1) {
482
+ await new Promise((resolve) => setTimeout(resolve, 250));
483
+ gone = !(await knownRooms(root)).find((room) => room.id === one.id)?.open;
484
+ }
485
+ if (!gone) return false;
486
+ if (service?.active) await execFileAsync('systemctl', ['--user', 'start', UNIT_NAME], { timeout: 15000 }).catch(() => null);
487
+ else startRoom({ projectRoot: one.root, roomDir: join(root, 'rooms', one.id), port: one.open.port, home });
488
+ await room.record('room.update.along', { name: one.name, from: one.open.version, to: PACKAGE.version }).catch(() => null);
489
+ return Boolean(await roomComesUp(root, one.id));
490
+ }
491
+ // What is running in the other open rooms, by name: an update now restarts all of MADRE (L-13).
492
+ async function busyElsewhere() {
493
+ const here = basename(roomDir);
494
+ const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
495
+ const answers = await Promise.all(others.map((one) => askRoom(one.open.port, '/api/activity', { stateRoot: root, timeoutMs: 3000 })));
496
+ return others.filter((_, index) => answers[index].now?.length).map((one) => one.name);
497
+ }
425
498
  // RESTARTING MADRE (2026-10-28): this process goes and a new one takes its place — the same
426
499
  // command, the same project, on the same port so every page open on it finds it again, and
427
500
  // without opening the browser a second time. Its listener is closed first, so the port is free
@@ -433,17 +506,38 @@ export async function createPulseServer({
433
506
  if (!args.includes('--no-open')) next.push('--no-open');
434
507
  setTimeout(() => {
435
508
  server.close(() => {
436
- let log = 'ignore';
437
- try { log = openPrivateLog(join(roomDir, 'restart.log')); } catch { /* no witness, still restart */ }
438
509
  const env = { ...process.env, PULSE_RESTARTED: '1' };
439
510
  delete env.PULSE_UPDATE_RESTART;
440
- const child = spawn(process.execPath, [...process.execArgv, ...next], { cwd: process.cwd(), detached: process.platform !== 'win32', windowsHide: true, stdio: ['ignore', log, log], env });
511
+ // On Linux the new one takes this process's place (Q-23, src/updates.mjs takesItsPlace): it
512
+ // comes back here only when it could not.
513
+ becomeNext({ file: process.execPath, args: [...process.execArgv, ...next], env, cwd: process.cwd(), log: join(roomDir, 'restart.log') });
514
+ let log = 'ignore';
515
+ try { log = openPrivateLog(join(roomDir, 'restart.log')); } catch { /* no witness, still restart */ }
516
+ // Inside the app the new process keeps the app's pipe (the watch below): given none, it read
517
+ // the app as gone the moment it started and closed, and MADRE did not come back (2026-11-10).
518
+ const watched = process.env.MADRE_APP === '1' && salasRoom;
519
+ const child = spawn(process.execPath, [...process.execArgv, ...next], { cwd: process.cwd(), detached: process.platform !== 'win32', windowsHide: true, stdio: [watched ? 'inherit' : 'ignore', log, log], env });
441
520
  child.unref();
442
521
  setTimeout(() => process.exit(0), 200);
443
522
  });
444
523
  for (const client of clients.keys()) { try { client.end(); } catch { /* gone */ } }
445
524
  }, 300);
446
525
  }
526
+ // This process becomes the next MADRE, same PID (Q-23): on Linux with a Node that can. When it
527
+ // cannot, it returns and the caller starts a new one as before. Its log is made private first; the
528
+ // shell only adds to it.
529
+ function becomeNext({ file, args, env, cwd, log }) {
530
+ if (!takesItsPlace()) return;
531
+ const terminal = Boolean(process.stdout.isTTY);
532
+ if (!terminal) { try { closeSync(openPrivateLog(log)); } catch { /* the shell makes it */ } }
533
+ const [program, argv] = nextProcess({ file, args, log, terminal });
534
+ try {
535
+ process.chdir(cwd);
536
+ process.execve(program, argv, Object.fromEntries(Object.entries(env).filter(([, value]) => typeof value === 'string')));
537
+ } catch (error) {
538
+ console.error(`MADRE: could not take its own place (${error.message}); starting a new process instead.`);
539
+ }
540
+ }
447
541
  // How many memories of each kind, and how many travel into turns. Counted, never read out.
448
542
  function memoryCensus() {
449
543
  const all = memory ? memory.memories({ limit: 20000 }) : [];
@@ -483,7 +577,9 @@ export async function createPulseServer({
483
577
  // and never a reason for the room not to open.
484
578
  // Release channel: one registry read a day, cached for every room on this machine. On by
485
579
  // default; PULSE_UPDATE_CHECK=0 or the switch in MU/TH/UR turns it off. Never self-updates.
486
- const updatesEnabled = () => (process.env.PULSE_UPDATE_CHECK !== undefined ? process.env.PULSE_UPDATE_CHECK !== '0' : updatesConfig.check !== false);
580
+ // Always (2026-11-17, the author: every person hears of a new version and decides whether to install
581
+ // it). Only PULSE_UPDATE_CHECK=0 turns it off, for tests and QA houses; a switch saved before is not read.
582
+ const updatesEnabled = () => process.env.PULSE_UPDATE_CHECK !== '0';
487
583
  let updatesConfig = { ...((await readConfig(root)).updates ?? {}) };
488
584
  // THE MARKET from madre.run (src/market-remote.mjs): read when MADRE opens, while Look for new
489
585
  // versions is on (PULSE_MARKET=0 says no to it alone). A module got from it updates itself and
@@ -668,7 +764,8 @@ export async function createPulseServer({
668
764
  // THE AUTHOR'S NOTICES (Q-11, src/notices.mjs). Every copy asks madre.run for them on its own,
669
765
  // with or without the diagnostics, and shows the ones signed with the author's key that are for it.
670
766
  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);
767
+ // The author's notices always arrive (2026-11-17): a new version, a fix or a service stop is for everyone.
768
+ const noticesEnabled = async () => true;
672
769
  async function noticesForPage() {
673
770
  void refreshNotices({ stateRoot: root }).catch(() => null);
674
771
  const place = await environmentOnce().catch(() => null);
@@ -682,11 +779,63 @@ export async function createPulseServer({
682
779
  const token = await readSecret(root, OWNER_VAULT, 'usage').catch(() => null);
683
780
  return Boolean(token) && existsSync(NOTICES_KEY_FILE);
684
781
  }
782
+ // MADRE App's subscription (src/billing.mjs, docs/private/SUSCRIPCION.md): only inside the app and
783
+ // only once the author's signed switch says so. Every server of the house reads the same files;
784
+ // Home alone asks madre.run, so a copy asks once however many projects are open.
785
+ let billing = { view: { state: 'off' }, saved: {}, at: 0 };
786
+ const switchKey = billingKeys.switchKey ?? undefined;
787
+ const billingKey = billingKeys.billingKey ?? BILLING_PUBLIC_KEY;
788
+ const billingView = () => billing.view;
789
+ // The days with everything the author's switch gives, or null while it is off (Q-26): the gate
790
+ // and the manual name them only when they exist.
791
+ const trialDaysNow = async () => {
792
+ const now = await billingNow().catch(() => billing);
793
+ return now.view.state === 'off' ? null : now.view.trialDays ?? null;
794
+ };
795
+ async function billingNow({ ask = false } = {}) {
796
+ if (!billingInApp()) return billing;
797
+ if (ask && salasRoom) {
798
+ const due = Date.now() - billingAsked > SWITCH_EVERY_MS;
799
+ if (due) { billingAsked = Date.now(); await askSwitch(root, { switchKey }).catch(() => null); }
800
+ if (billing.saved?.order && Date.now() - orderAsked > ORDER_EVERY_MS) { orderAsked = Date.now(); await askOrder(root, { billingKey }).catch(() => null); }
801
+ // Turning it on with the email of the payment (2026-11-18): the key arrives once the button is confirmed.
802
+ if (billing.saved?.recovery && Date.now() - recoveryAsked > ORDER_EVERY_MS) { recoveryAsked = Date.now(); await askRecovery(root, { billingKey }).catch(() => null); }
803
+ }
804
+ billing = { ...(await loadBilling(root, { switchKey, billingKey }).catch(() => ({ view: { state: 'off' }, saved: {} }))), at: Date.now() };
805
+ return billing;
806
+ }
807
+ let billingAsked = 0;
808
+ let orderAsked = 0;
809
+ let recoveryAsked = 0;
810
+ // Home keeps the copy current: the switch every half hour, a key it waits for every few seconds,
811
+ // and a fresh key every twelve hours.
812
+ if (billingInApp() && salasRoom && !testMode) {
813
+ const tick = async () => {
814
+ await billingNow({ ask: true }).catch(() => null);
815
+ if (billing.key) { await renewKey(root, { billingKey }).catch(() => null); await billingNow().catch(() => null); }
816
+ };
817
+ void tick();
818
+ const billingTimer = setInterval(() => void tick(), 60000);
819
+ billingTimer.unref?.();
820
+ const orderTimer = setInterval(() => {
821
+ const paying = billing.saved?.order && Date.now() - Date.parse(billing.saved.order.at) < ORDER_FAST_MS;
822
+ const recovering = billing.saved?.recovery && Date.now() - Date.parse(billing.saved.recovery.at) < RECOVERY_KEEP_MS;
823
+ if (paying || recovering) void billingNow({ ask: true }).catch(() => null);
824
+ }, ORDER_EVERY_MS);
825
+ orderTimer.unref?.();
826
+ } else void billingNow().catch(() => null);
827
+ // What the page reads: where this copy stands and the one thing to tell the person now, if any.
828
+ async function billingForPage({ ask = true } = {}) {
829
+ const now = await billingNow({ ask });
830
+ return { ...now.view, moment: dueMoment(now.view, now.saved), project: salasRoom ? null : { room: projectRoomId(canonicalProjectRoot), name: basename(canonicalProjectRoot) }, site: billingSite() };
831
+ }
685
832
  async function homeWidget(kind) {
686
833
  // 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.
834
+ // as agents add and close errors. Only in the author's copy run from source, and only Home serves it.
688
835
  if (kind === 'madrelogs') {
689
- if (!FROM_SOURCE || !salasRoom) return null;
836
+ // And only in the author's own copy, with the author's token (2026-11-10): a clean copy run from
837
+ // this same source (a test house, the Mac app pointed at it) showed it too.
838
+ if (!FROM_SOURCE || !salasRoom || !(await readSecret(root, OWNER_VAULT, 'usage').catch(() => null))) return null;
690
839
  const { keepSync, readLogs, syncDiagnostics, syncSentinel } = await import('./madre-logs.mjs');
691
840
  // The diagnostics filed on their own (src/madre-logs.mjs, syncDiagnostics): every ten minutes
692
841
  // while the widget is read, with the author's token, never waited for by the reading.
@@ -800,6 +949,14 @@ export async function createPulseServer({
800
949
  .map((one) => ({ ...one, when: now < Date.parse(one.from) ? 'later' : now >= Date.parse(one.until) ? 'over' : 'now' })),
801
950
  unverified: Math.max(0, (data?.notices?.length ?? 0) - (feed?.entries?.length ?? 0)),
802
951
  };
952
+ } else if (kind === 'billing') {
953
+ // The author's switch for MADRE App's subscription (src/billing.mjs): what madre.run serves now,
954
+ // checked as every app checks it, and whether the key of the subscription keys exists yet.
955
+ if (!(await ownerCanNotify())) return null;
956
+ const answer = await globalThis.fetch(`${billingSite()}/api/cobro`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) }).catch(() => null);
957
+ const data = answer?.ok ? await answer.json().catch(() => null) : null;
958
+ const served = data?.switch ? verifiedSwitch(data, switchKey) : null;
959
+ reading = { available: true, read: Boolean(data), switch: served, unverified: Boolean(data?.switch && !served), keyReady: Boolean(billingKey) };
803
960
  } else if (kind === 'coordinator' && !salasRoom) {
804
961
  // Home's page is served by every project too: the Coordinator's record is its own room's.
805
962
  const coordinator = (await knownRooms(root)).find((one) => one.id === salasRoomId(root));
@@ -982,6 +1139,28 @@ export async function createPulseServer({
982
1139
  const base = fit.recommended.train ?? MODEL_TIERS[1];
983
1140
  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 };
984
1141
  }
1142
+ // TRYING @madre ON THIS PROJECT (2026-11-10, asked by the author). It used to be announced on a
1143
+ // project's first page, with its one key greyed out: there was nothing to compare it with yet. Now
1144
+ // it is offered in the conversation once agents have answered enough real questions here
1145
+ // (LOCAL_TRY_MIN), with «Try it» and «Remind me later»; unanswered or put off, it comes back after
1146
+ // a few days (LOCAL_TRY_AGAIN_MS), until the project has been measured.
1147
+ async function offerLocalTry(target, { now = Date.now() } = {}) {
1148
+ if (!target || !memory || !localWiring.madre) return;
1149
+ let exams = {};
1150
+ try { exams = JSON.parse(memory.metaGet('exams') ?? '{}'); } catch { exams = {}; }
1151
+ if (exams.match?.ran) return;
1152
+ const offered = Date.parse(memory.metaGet('local.offered') ?? '');
1153
+ if (Number.isFinite(offered) && now - offered < LOCAL_TRY_AGAIN_MS) return;
1154
+ if ((await target.answeredByAgents().catch(() => 0)) < LOCAL_TRY_MIN) return;
1155
+ memory.metaSet('local.offered', new Date(now).toISOString());
1156
+ const model = agents.find((agent) => agent.id === MADRE_AGENT_ID)?.version ?? null;
1157
+ await target.record('local.present', {
1158
+ model,
1159
+ offer: true,
1160
+ // Ollama on another computer of the network (NUE-07): the card does not say «on this Mac».
1161
+ ...(ollama.host && !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?\/?$/i.test(String(ollama.host)) ? { remote: true } : {}),
1162
+ });
1163
+ }
985
1164
  async function wireOllama({ probe: doProbe = true } = {}) {
986
1165
  if (doProbe) { ollama = await ollamaProbe(); ollama.autoModel = ollama.chatModel; }
987
1166
  // A model trained on this room (docs/training) is named madre-<project>: @madre uses it when it exists.
@@ -1021,17 +1200,7 @@ export async function createPulseServer({
1021
1200
  // the second thing is the one a person needs told. Said once per model, in the room, with
1022
1201
  // the one button that settles it — the crew line above fires only when the crew CHANGES,
1023
1202
  // and a room whose Ollama was already up when it opened would never have heard it.
1024
- if (fifth.ready && memory && memory.metaGet('local.announced') !== fifth.version) {
1025
- let checked = null;
1026
- try { checked = JSON.parse(memory.metaGet('exams') ?? '{}').match ?? null; } catch { checked = null; }
1027
- memory.metaSet('local.announced', fifth.version);
1028
- await room.record('local.present', {
1029
- model: fifth.version,
1030
- // Ollama on another computer of the network (NUE-07): the card does not say «on this Mac».
1031
- ...(ollama.host && !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?\/?$/i.test(String(ollama.host)) ? { remote: true } : {}),
1032
- checked: checked?.ran ? { passed: Boolean(checked.passed), matched: checked.matched ?? 0, n: checked.n ?? 0, at: checked.at ?? null } : null,
1033
- });
1034
- }
1203
+ await offerLocalTry(room);
1035
1204
  }
1036
1205
  return { ...ollama, settings, project, embeddings: Boolean(useEmbeddings), archivist: Boolean(useArchivist), agent: fifth.ready };
1037
1206
  }
@@ -1063,6 +1232,30 @@ export async function createPulseServer({
1063
1232
  };
1064
1233
  adoptOllamaHost(await readConfig(root));
1065
1234
  await wireOllama();
1235
+ // The first look gives Ollama 1.5 s. On a busy machine (a 14B loading, a knowledge load running)
1236
+ // that is not enough, and before this the local AI stayed off for the whole run: no @madre, the
1237
+ // archive written by a paid agent, until a restart (L-14, Carlos's server, 2026-11-12). Now it is
1238
+ // asked again on its own, with more time, until it answers.
1239
+ let ollamaRetry = null;
1240
+ let ollamaRetries = 0;
1241
+ const askOllamaAgain = () => {
1242
+ clearTimeout(ollamaRetry);
1243
+ ollamaRetry = null;
1244
+ if (ollama.running || ollama.disabled || !ollamaRetryMs.length) return;
1245
+ const wait = ollamaRetryMs[Math.min(ollamaRetries, ollamaRetryMs.length - 1)];
1246
+ ollamaRetries += 1;
1247
+ ollamaRetry = setTimeout(async () => {
1248
+ ollamaRetry = null;
1249
+ const seen = await ollamaProbe({ timeoutMs: 10_000 }).catch(() => null);
1250
+ if (seen?.running && !ollama.running) {
1251
+ ollama = { ...seen, autoModel: seen.chatModel };
1252
+ await wireOllama({ probe: false }).catch((error) => console.error(`MADRE could not wire Ollama: ${error.message}`));
1253
+ }
1254
+ askOllamaAgain();
1255
+ }, wait);
1256
+ ollamaRetry.unref?.();
1257
+ };
1258
+ askOllamaAgain();
1066
1259
  const memoryServer = memory ? memoryServerFor({ dbFile: memory.file, projectRoot: canonicalProjectRoot }) : null;
1067
1260
  // MOTHER's channel to the crew: her seal's fingerprint lives in the memory
1068
1261
  // file, so a deleted or edited .pulse/mother.env is noticed.
@@ -1157,7 +1350,12 @@ export async function createPulseServer({
1157
1350
  skillsForTurn: async (turn) => {
1158
1351
  const { loaded, failures } = await loadSkills({ stateRoot: root, projectRoot: canonicalProjectRoot });
1159
1352
  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;
1353
+ // Called by its name (2026-11-10, the author): «/habilidad explicamelo-facil …» brings that one
1354
+ // into this turn whatever its switch says; the rest are still chosen by what was asked.
1355
+ const called = /^\s*\/(?:habilidad|skill)\s+([a-z][a-z0-9-]{1,39})\b/i.exec(String(turn.text ?? ''))?.[1]?.toLowerCase();
1356
+ const named = called ? loaded.find((one) => one.id === called) : null;
1357
+ const rest = chooseSkills({ skills: named ? loaded.filter((one) => one !== named) : loaded, text: turn.text, config: await readConfig(root), roomId: scopeRoom }).chosen;
1358
+ return named ? [{ ...named, state: 'always', why: [`/habilidad ${named.id}`] }, ...rest].slice(0, 3) : rest;
1161
1359
  },
1162
1360
  // What BISHOP reads for a turn is recorded in that turn's conversation, not the open one.
1163
1361
  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,
@@ -1187,6 +1385,8 @@ export async function createPulseServer({
1187
1385
  // S-032: in the room of Salas nobody delegates. BISHOP speaks there, and what it sets in
1188
1386
  // motion goes through its own plans, never through a ```pulse plan of that room.
1189
1387
  delegation: salasRoom ? false : delegation,
1388
+ // In the limited mode of MADRE App (src/billing.mjs), no plan among several AIs.
1389
+ plansAllowed: () => billingView().state !== 'limited',
1190
1390
  maxPlanSteps,
1191
1391
  ...own,
1192
1392
  });
@@ -1268,6 +1468,18 @@ export async function createPulseServer({
1268
1468
  if (!Array.isArray(patch.opencode.hidden) || patch.opencode.hidden.some((id) => typeof id !== 'string' || !/^[\w.-]{1,60}$/.test(id))) throw new Error(t('Hidden providers must be a list of provider names.'));
1269
1469
  config.opencode = { ...(config.opencode ?? {}), hidden: [...new Set(patch.opencode.hidden)] };
1270
1470
  }
1471
+ // Up to three of OpenCode's models kept at the top of its chooser (2026-11-10), for every project.
1472
+ if (patch.opencode && 'favorites' in patch.opencode) {
1473
+ if (!Array.isArray(patch.opencode.favorites) || patch.opencode.favorites.some((name) => typeof name !== 'string' || !/^[\w.:@/+-]{1,200}$/.test(name))) throw new Error(t('Favourite models must be a list of model names.'));
1474
+ config.opencode = { ...(config.opencode ?? {}), favorites: [...new Set(patch.opencode.favorites)].slice(0, 3) };
1475
+ }
1476
+ // Every other agent's, the same way (2026-11-11): { agent, models }.
1477
+ if (patch.favorites) {
1478
+ const { agent, models } = patch.favorites;
1479
+ if (typeof agent !== 'string' || !/^[a-z][\w-]{0,30}$/.test(agent) || agent === 'opencode') throw new Error(t('Favourite models must be a list of model names.'));
1480
+ if (!Array.isArray(models) || models.some((name) => typeof name !== 'string' || !/^[\w.:@/+-]{1,200}$/.test(name))) throw new Error(t('Favourite models must be a list of model names.'));
1481
+ config.favorites = { ...(config.favorites ?? {}), [agent]: [...new Set(models)].slice(0, 3) };
1482
+ }
1271
1483
  if (patch.timeouts) {
1272
1484
  const timeouts = { ...room.settings().agentTimeouts };
1273
1485
  for (const [key, value] of Object.entries(patch.timeouts)) {
@@ -1756,6 +1968,8 @@ export async function createPulseServer({
1756
1968
  // What OpenCode answered with, and what failed for which provider (src/opencode-health.mjs):
1757
1969
  // the next failure offers a model that works instead of a sentence in English.
1758
1970
  if (event.type === 'agent.completed' && event.payload?.agent === 'opencode') void noteOpenCodeTurn(root, { ok: true, model: event.payload.ranOn ?? null }).catch(() => null);
1971
+ // A turn answered by an agent may be the one that makes @madre worth trying here.
1972
+ if (event.type === 'agent.completed' && event.payload?.agent !== MADRE_AGENT_ID) void offerLocalTry(target).catch(() => null);
1759
1973
  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);
1760
1974
  const listening = MODULES.filter((module) => typeof module.onEvent === 'function');
1761
1975
  if (!listening.length) return;
@@ -2084,7 +2298,9 @@ export async function createPulseServer({
2084
2298
  // before every message, so a switch moved in Home reaches a project that is already open.
2085
2299
  function applyModuleSwitches(target, config) {
2086
2300
  // 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 });
2301
+ // Where its server looks for the key: MADRE's own folder (a key pasted in Images) and the home
2302
+ // where each CLI keeps its own.
2303
+ setImageModule({ ...settingsIn(config.modules?.imageStudio ?? {}, scopeRoom), enabled: true, stateRoot: root, home: credentialHome });
2088
2304
  target.setAsh(moduleOnHere(config, 'ash'));
2089
2305
  target.setChoices(true);
2090
2306
  target.setRuns(true);
@@ -2094,6 +2310,8 @@ export async function createPulseServer({
2094
2310
  // privacy list and its numbering; what changes is the record being shown. With TURNS on, a
2095
2311
  // conversation still at work is parked, not stopped; with it off, a turn in flight is a reason to
2096
2312
  // refuse, as it always was.
2313
+ // Conversations left while their memory work was still running, until it is done.
2314
+ const closing = new Set();
2097
2315
  async function mountChat(id) {
2098
2316
  if (!isChatId(id)) return { error: `No conversation "${id}".` };
2099
2317
  const policy = await turnsPolicy();
@@ -2112,8 +2330,13 @@ export async function createPulseServer({
2112
2330
  // Still writing its record and touching the list; only the page stops watching it.
2113
2331
  hold(chatId, leaving, store);
2114
2332
  } else if (leaving) {
2115
- await leaving.shutdown().catch(() => null);
2116
- retireLedger(store);
2333
+ // Q-29 (2026-11-18): the room left may still be distilling with the local model, half a
2334
+ // minute with qwen2.5:7b, and the new conversation waited for it. It finishes on its own;
2335
+ // closing MADRE still waits for it (`closing`, in server.close).
2336
+ const leavingStore = store;
2337
+ const closed = leaving.shutdown().catch(() => null).then(() => retireLedger(leavingStore));
2338
+ closing.add(closed);
2339
+ void closed.finally(() => closing.delete(closed));
2117
2340
  }
2118
2341
  chatId = id;
2119
2342
  const held = parked.get(id);
@@ -2188,6 +2411,10 @@ export async function createPulseServer({
2188
2411
  },
2189
2412
  imageKey,
2190
2413
  setImageModule,
2414
+ // Images (2026-11-14): where each provider's key was found — never the key — and the home
2415
+ // a CLI keeps its own in. Tests hand in their own sources.
2416
+ imageSources: imageSources ?? (() => findImageSources({ env: process.env, home: credentialHome, stateRoot: root })),
2417
+ imageHome: credentialHome,
2191
2418
  // Intenciones keeps its measurements beside the project's room, reads the open
2192
2419
  // conversation, and asks agents through the same bench EYECAT and the archivist draw on.
2193
2420
  intents: {
@@ -2390,6 +2617,15 @@ export async function createPulseServer({
2390
2617
  };
2391
2618
  }
2392
2619
 
2620
+ // One of the first steps (public/missions.js): something got from the Market. Seen here, where
2621
+ // every way of getting one ends (the Market, MODULES, Settings), and counted the first time only.
2622
+ // The local AI has its own step, so turning it on is not this one.
2623
+ async function marketUsed() {
2624
+ const before = await readTour(root).catch(() => null);
2625
+ if (!before || before.missions?.market) return;
2626
+ await changeTour(root, { mission: 'market' }).catch(() => null);
2627
+ diagnostics.count('mission.market');
2628
+ }
2393
2629
  async function installExtension(id, payload = {}) {
2394
2630
  const { confirm } = payload;
2395
2631
  const extension = extensionById(id);
@@ -2500,21 +2736,27 @@ export async function createPulseServer({
2500
2736
  }
2501
2737
  if (request.method === 'GET' && FICHA_PAGES.has(url.pathname)) {
2502
2738
  response.writeHead(401, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', [FICHA_HEADER]: FICHA_NEEDED, ...PAGE_GUARDS });
2503
- response.end(fichaPage());
2739
+ response.end(fichaPage(request));
2504
2740
  return true;
2505
2741
  }
2506
2742
  response.writeHead(401, { 'content-type': 'application/json; charset=utf-8', [FICHA_HEADER]: FICHA_NEEDED });
2507
2743
  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
2744
  return true;
2509
2745
  }
2510
- // What a tab without the ficha shows: where to open MADRE from, nothing of the project.
2511
- const fichaPage = () => {
2746
+ // What a tab without the ficha shows: where to open MADRE from, nothing of the project. Through an
2747
+ // SSH tunnel (L-13) MADRE cannot open that browser, so the page says how to get the address; and
2748
+ // when the tunnel uses another number on the person's side, which one to change.
2749
+ const fichaPage = (request) => {
2750
+ const seen = Number(String(request?.headers?.host ?? '').match(/:(\d+)$/)?.[1]) || null;
2751
+ const mine = request?.socket?.localPort ?? null;
2512
2752
  const escape = (text) => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2513
2753
  return `<!doctype html><html lang="${roomLanguage()}"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>MADRE</title>`
2514
2754
  + '<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
2755
  + `<h1 style="font-size:22px;margin:0 0 12px">${escape(t('This tab needs to be opened from MADRE'))}</h1>`
2516
2756
  + `<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
2757
  + `<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>`
2758
+ + `<p>${escape(t('Reaching this computer through an SSH tunnel? On that computer, run npx @jossuealcala/madre and open here the address it writes (the one that ends in ?ficha=…).'))}</p>`
2759
+ + (seen && mine && seen !== mine ? `<p>${escape(t('Your tunnel brings port {theirs} to {yours} on your side: in that address, change {theirs} to {yours}.', { theirs: mine, yours: seen }))}</p>` : '')
2518
2760
  + '</main></body></html>';
2519
2761
  };
2520
2762
 
@@ -2550,7 +2792,7 @@ export async function createPulseServer({
2550
2792
  response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...PAGE_GUARDS });
2551
2793
  return response.end(html);
2552
2794
  }
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)) {
2795
+ 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', '/missions.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', '/auto-open.js', '/changes.js', '/activity.js', '/notices.js', '/subscription.js', '/tips.js', '/starters.js', '/provider-pick.js', '/notifications.js', '/provider-marks.js', '/terms.js', '/terms-field.js', '/mcp-catalog.js', '/manual.js', '/manual-content.js', '/manual-shots.js', '/en.js'].includes(url.pathname)) {
2554
2796
  return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'text/javascript; charset=utf-8');
2555
2797
  }
2556
2798
  if (request.method === 'GET' && url.pathname === '/styles.css') {
@@ -2598,6 +2840,9 @@ export async function createPulseServer({
2598
2840
  ['/assets/brand/Geist-latin-ext.woff2', 'font/woff2'],
2599
2841
  ['/assets/brand/GeistMono-latin.woff2', 'font/woff2'],
2600
2842
  ['/assets/brand/GeistMono-latin-ext.woff2', 'font/woff2'],
2843
+ ['/assets/brand/SpaceGrotesk-latin.woff2', 'font/woff2'],
2844
+ ['/assets/brand/SpaceGrotesk-latin-ext.woff2', 'font/woff2'],
2845
+ ['/assets/brand/OFL-SpaceGrotesk.txt', 'text/plain; charset=utf-8'],
2601
2846
  ['/assets/brand/OFL-Geist.txt', 'text/plain; charset=utf-8'],
2602
2847
  ['/assets/brand/OFL-GeistMono.txt', 'text/plain; charset=utf-8'],
2603
2848
  ['/assets/brand/OFL-Sora.txt', 'text/plain; charset=utf-8'],
@@ -2923,7 +3168,7 @@ export async function createPulseServer({
2923
3168
  // folders (Sec-Fetch-Site) or to add one (Origin), and so is any host name but this Mac's
2924
3169
  // own, so a name pointed at it from outside reaches nothing. Folders are listed inside the
2925
3170
  // home folder only; what is listed is names, never what a file says.
2926
- if (url.pathname === '/api/salas/folders' || url.pathname === '/api/salas/suggestions' || url.pathname === '/api/salas/projects' || url.pathname === '/api/salas/new' || url.pathname === '/api/salas/work' || url.pathname === '/api/salas/decisions') {
3171
+ if (url.pathname === '/api/salas/folders' || url.pathname === '/api/salas/suggestions' || url.pathname === '/api/salas/peek' || url.pathname === '/api/salas/projects' || url.pathname === '/api/salas/new' || url.pathname === '/api/salas/work' || url.pathname === '/api/salas/decisions') {
2927
3172
  const host = String(request.headers.host ?? '');
2928
3173
  const localHost = /^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host);
2929
3174
  const site = request.headers['sec-fetch-site'];
@@ -2939,6 +3184,16 @@ export async function createPulseServer({
2939
3184
  if (request.method === 'GET' && url.pathname === '/api/salas/suggestions') {
2940
3185
  return sendJson(response, 200, { suggestions: await suggestProjects({ home, stateRoot: root }) });
2941
3186
  }
3187
+ // What the first level of a project Home knows holds, by name only (2026-11-10): the end of
3188
+ // the welcome writes its first ideas for what is in that folder (public/starters.js).
3189
+ if (request.method === 'GET' && url.pathname === '/api/salas/peek') {
3190
+ const asked = url.searchParams.get('room');
3191
+ const room = (await knownRooms(root)).find((one) => one.id === asked && one.root);
3192
+ if (!room) return sendJson(response, 404, { error: t('That folder is not there.') });
3193
+ const listing = await listDirectory(room.root, '.');
3194
+ if (listing.status !== 200) return sendJson(response, listing.status, { error: listing.error });
3195
+ return sendJson(response, 200, { entries: listing.entries.map(({ name, kind }) => ({ name, kind })) });
3196
+ }
2942
3197
  // WHAT WAS WORKED ON LAST: the newest conversations of every room the lobby knows (read from
2943
3198
  // their folders, open or asleep), and MADRE's summary of them with its local model. The
2944
3199
  // summary is written in the background and kept until what it summarises changes; it is
@@ -3010,6 +3265,13 @@ export async function createPulseServer({
3010
3265
  if (payload.sample === true) {
3011
3266
  const sample = await createSampleProject({ home, stateRoot: root, language: payload.language === 'en' ? 'en' : 'es' });
3012
3267
  if (sample.error) return sendJson(response, 422, { error: t('The project to try MADRE could not be made.'), code: sample.error });
3268
+ // Its page is the point (2026-11-11): the first change opens beside the conversation as
3269
+ // the page it is, so Preview is on in this project — unless the person already said
3270
+ // otherwise, for every project or for this one.
3271
+ const ripleyBlock = (await readConfig(root)).modules?.ripley ?? {};
3272
+ if (sample.id && typeof ripleyBlock.enabled !== 'boolean' && typeof ripleyBlock.rooms?.[sample.id] !== 'boolean') {
3273
+ await updateConfig(root, { modules: { ripley: switchIn(ripleyBlock, sample.id, true) } }).catch(() => {});
3274
+ }
3013
3275
  diagnostics.count('project.sample');
3014
3276
  return sendJson(response, 200, { added: [sample] });
3015
3277
  }
@@ -3504,6 +3766,19 @@ export async function createPulseServer({
3504
3766
  // adding one is. Never the Coordinator's own, never the room that is asked. Open, it is closed
3505
3767
  // first; its connections end with it, so none is left pointing at a project MADRE no longer
3506
3768
  // knows; then its record goes aside (forgetProject). Its folder on the Mac is not touched.
3769
+ // A name of the person's own for a project, from Home (2026-11-13). Its folder keeps its name.
3770
+ if (request.method === 'POST' && url.pathname === '/api/salas/rename') {
3771
+ const host = String(request.headers.host ?? '');
3772
+ const site = request.headers['sec-fetch-site'];
3773
+ if (!/^(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('This is done from Home, on this Mac.') });
3774
+ const payload = await body(request).catch(() => ({}));
3775
+ const id = String(payload.room ?? '');
3776
+ if (id === salasRoomId(root)) return sendJson(response, 422, { error: t('The Coordinator keeps its name.') });
3777
+ if (!(await knownRooms(root)).some((one) => one.id === id)) return sendJson(response, 404, { error: t('MADRE does not know that project on this Mac.') });
3778
+ const renamed = await renameProject({ stateRoot: root, id, title: payload.name });
3779
+ if (renamed.error) return sendJson(response, 404, { error: t('MADRE does not know that project on this Mac.') });
3780
+ return sendJson(response, 200, renamed);
3781
+ }
3507
3782
  if (request.method === 'POST' && url.pathname === '/api/salas/forget') {
3508
3783
  const host = String(request.headers.host ?? '');
3509
3784
  const site = request.headers['sec-fetch-site'];
@@ -3560,6 +3835,8 @@ export async function createPulseServer({
3560
3835
  // The project's name as this system writes paths (WEB-11): the page cut it at «/», and on
3561
3836
  // Windows the name was the whole path, so the key for #3 never matched.
3562
3837
  projectName: basename(canonicalProjectRoot),
3838
+ // The name the person gave it in Home, if any (2026-11-13): shown in place of the folder's.
3839
+ projectTitle: await projectTitle(roomDir).catch(() => null),
3563
3840
  // The column Diagnostics reads its commands from (public/troubleshooting.js): WSL is Linux
3564
3841
  // inside Windows, and says so (2026-10-28).
3565
3842
  platform: await environmentOnce().then((one) => (one?.wsl ? 'wsl' : process.platform), () => process.platform),
@@ -4031,7 +4308,7 @@ export async function createPulseServer({
4031
4308
  if (url.pathname === '/api/terms' && request.method === 'GET') {
4032
4309
  const terms = viaPhone ? { accepted: true, version: null } : await readTerms(root);
4033
4310
  const before = !terms.accepted && ((await cameFromBefore(root)) || (hadInstallId && !existsSync(join(root, 'lifecycle.json'))));
4034
- return sendJson(response, 200, { ...terms, before, language: roomLanguage(), languageChosen, diagnostics: await diagnosticsNow(), diagnosticsFixed: process.env.PULSE_TELEMETRY === '0', links: TERMS_LINKS });
4311
+ return sendJson(response, 200, { ...terms, before, language: roomLanguage(), languageChosen, diagnostics: await diagnosticsNow(), diagnosticsFixed: process.env.PULSE_TELEMETRY === '0', links: termsLinks(), trialDays: termsKind() === 'app' ? await trialDaysNow() : null });
4035
4312
  }
4036
4313
  if (url.pathname === '/api/terms' && request.method === 'POST') {
4037
4314
  const site = request.headers['sec-fetch-site'];
@@ -4156,6 +4433,15 @@ export async function createPulseServer({
4156
4433
  return sendJson(response, 200, { framable: true, status: null, unreachable: true });
4157
4434
  }
4158
4435
  }
4436
+ // The photo and title of a link an agent gave, only when the person pressed «Show photos»
4437
+ // (web-preview.mjs): a page on the internet, never one on this computer or its network.
4438
+ if (request.method === 'POST' && url.pathname === '/api/web/preview') {
4439
+ const asked = await body(request);
4440
+ const links = (Array.isArray(asked?.urls) ? asked.urls : [asked?.url]).filter((one) => typeof one === 'string' && /^https?:\/\//i.test(one)).slice(0, 12);
4441
+ if (!links.length) return sendJson(response, 400, { error: t('No link to show.') });
4442
+ const previews = await Promise.all(links.map((one) => webPreview(one)));
4443
+ return sendJson(response, 200, { previews: Object.fromEntries(links.map((one, index) => [one, previews[index]])) });
4444
+ }
4159
4445
  if (request.method === 'GET' && url.pathname === '/api/ports') {
4160
4446
  if (!(await ripleyOn())) return sendJson(response, 412, { error: t('Preview is off. Enable it in MODULES to render files.') });
4161
4447
  // Only this project's servers, read by the servers sentinel: the same reading its watch
@@ -4385,7 +4671,8 @@ export async function createPulseServer({
4385
4671
  const asked = url.searchParams.get('version');
4386
4672
  const version = any && asked && notesFor(asked) ? asked : PACKAGE.version;
4387
4673
  const news = await whatsNew({ root, version, returning: novelty.returning, any });
4388
- return sendJson(response, 200, { ...news, preview: version !== PACKAGE.version, newest: newestNotes(), changes: { es: releaseUrl(PACKAGE.repository, version, 'es'), en: releaseUrl(PACKAGE.repository, version, 'en') } });
4674
+ // `app`: read inside the desktop app, where the notes say what the app gives instead of asking for it.
4675
+ return sendJson(response, 200, { ...news, app: process.env.MADRE_APP === '1', preview: version !== PACKAGE.version, newest: newestNotes(), changes: { es: releaseUrl(PACKAGE.repository, version, 'es'), en: releaseUrl(PACKAGE.repository, version, 'en') } });
4389
4676
  }
4390
4677
  if (request.method === 'POST' && url.pathname === '/api/whats-new/seen') {
4391
4678
  await markSeen(root, PACKAGE.version);
@@ -4394,6 +4681,28 @@ export async function createPulseServer({
4394
4681
  // The invitation to a first project (src/whats-new.mjs): due on Home to a copy that came from an
4395
4682
  // older MADRE and has no project, once per version. Never on a phone. Its answers are counted
4396
4683
  // with the anonymous diagnostics, and «shown» is what spends it.
4684
+ // The choice of the app (src/app-invite.mjs): a window on Home for whoever updated MADRE and uses
4685
+ // it in the browser, once per version, once the app can be downloaded for their desktop. Never on a
4686
+ // phone. Its answers are counted with the anonymous diagnostics.
4687
+ if (url.pathname === '/api/invite/app') {
4688
+ if (viaPhone || !salasRoom) return sendJson(response, 200, { show: false });
4689
+ if (request.method === 'GET') {
4690
+ const place = await environmentOnce().catch(() => null);
4691
+ const said = await appInvite({ root, novelty, version: PACKAGE.version, wsl: Boolean(place?.wsl) });
4692
+ // The person's own projects, the ones opened last, so the window can speak of them by name.
4693
+ const projects = (await knownRooms(root)).filter((one) => one.id !== salasRoomId(root))
4694
+ .sort((a, b) => String(b.lastOpened ?? '').localeCompare(String(a.lastOpened ?? ''))).map((one) => one.name);
4695
+ return sendJson(response, 200, { ...said, projects: projects.slice(0, 3), count: projects.length });
4696
+ }
4697
+ if (request.method === 'POST') {
4698
+ const payload = await body(request).catch(() => ({}));
4699
+ const said = await answerAppInvite(root, { answer: payload.answer, version: PACKAGE.version });
4700
+ if (said.error) return sendJson(response, 422, { error: 'answer' });
4701
+ diagnostics.count(`invite.app.${payload.answer}`);
4702
+ return sendJson(response, 200, said);
4703
+ }
4704
+ return sendJson(response, 405, { error: 'method' });
4705
+ }
4397
4706
  if (url.pathname === '/api/invite/project') {
4398
4707
  if (viaPhone) return sendJson(response, 200, { show: false });
4399
4708
  if (request.method === 'GET') {
@@ -4415,8 +4724,11 @@ export async function createPulseServer({
4415
4724
  // is never asked.
4416
4725
  if (request.method === 'POST' && url.pathname === '/api/review-ask/tick') {
4417
4726
  if (viaPhone) return sendJson(response, 200, { due: null });
4418
- // Never on the day of the bonjour: one welcome is enough for a day.
4419
- return sendJson(response, 200, await tickAsk(root, Date.now(), { quietSince: (await readTour(root)).bonjourAt }));
4727
+ // Never on the day of the bonjour: one welcome is enough for a day. Only the minutes the page
4728
+ // says an AI is at work count (`using`); `via` says where the question sends the person.
4729
+ const payload = await body(request).catch(() => ({}));
4730
+ const ticked = await tickAsk(root, Date.now(), { quietSince: (await readTour(root)).bonjourAt, using: payload?.using === true });
4731
+ return sendJson(response, 200, { ...ticked, via: askVia() });
4420
4732
  }
4421
4733
  if (request.method === 'POST' && url.pathname === '/api/review-ask/answer') {
4422
4734
  if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
@@ -4447,6 +4759,7 @@ export async function createPulseServer({
4447
4759
  if (viaPhone || !fromHere || (request.method === 'POST' && request.headers.origin !== `http://${host}`)) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4448
4760
  if (request.method === 'POST' && url.pathname === '/api/tour') {
4449
4761
  const change = await body(request).catch(() => null);
4762
+ const already = MISSIONS.includes(change?.mission) && Boolean((await readTour(root)).missions?.[change.mission]);
4450
4763
  const changed = await changeTour(root, change);
4451
4764
  if (changed.error) return sendJson(response, 422, { error: t('That is not a change to the tour.') });
4452
4765
  // How far people get in the welcome, and what they leave for later (2026-11-01): 90 of 147
@@ -4458,6 +4771,8 @@ export async function createPulseServer({
4458
4771
  if (WELCOME_STEPS.includes(step.skipped)) diagnostics.count(`welcome.skip.${step.skipped}`);
4459
4772
  if (step.finished === true) diagnostics.count('welcome.finished');
4460
4773
  }
4774
+ // Which of the first steps people do (2026-11-11): the mission's id, nothing else.
4775
+ if (MISSIONS.includes(change?.mission) && !already) diagnostics.count(`mission.${change.mission}`);
4461
4776
  return sendJson(response, 200, { state: changed });
4462
4777
  }
4463
4778
  if (request.method === 'GET' && url.pathname === '/api/tour/projects') {
@@ -4498,7 +4813,14 @@ export async function createPulseServer({
4498
4813
  // Only a version semver would write reaches a shell, and the restart never runs without the
4499
4814
  // download first (src/updates.mjs): an unchecked one used to skip the download and run.
4500
4815
  if (!command || !fetching) return sendJson(response, 412, { error: t('The version the registry gave ({version}) is not one MADRE installs.', { version: String(info.latest).slice(0, 40) }) });
4816
+ // Installed with sudo (Q-22): npm -g cannot replace it from here, so the room says how and stays open.
4817
+ if (install === 'global' && !(await canReplace(await realpath(join(sourceDirectory, '..')).catch(() => join(sourceDirectory, '..'))))) {
4818
+ return sendJson(response, 412, { error: t('MADRE was installed with administrator permission, so it cannot update itself. In a terminal, run: {command}', { command: `sudo npm install -g ${PACKAGE.name}@${info.latest}` }) });
4819
+ }
4501
4820
  if (room.activeTurns().length || room.activePlans().length) return sendJson(response, 409, { error: t('Agents are still working. STOPALL or wait, then update.') });
4821
+ // The update brings every open project and Home along (L-13): none of them may be cut off.
4822
+ const busy = await busyElsewhere().catch(() => []);
4823
+ if (busy.length) return sendJson(response, 409, { error: t('Something is still running in {list}. Updating restarts all of MADRE: wait for it to finish or stop it, then update.', { list: busy.join(', ') }), busy });
4502
4824
  {
4503
4825
  // npm is a .cmd on Windows and needs a shell there; every argument here is fixed or checked above.
4504
4826
  const fetched = await new Promise((resolve) => execFile(fetching.command, fetching.args, { cwd: root, timeout: 180000, shell: process.platform === 'win32', windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => resolve(error ? (String(stderr || error.message).split('\n').map((line) => line.trim()).find((line) => line && !/complete log|^npm (error|ERR!)(\s+code\b.*)?\s*$/i.test(line)) ?? error.message) : null)));
@@ -4511,6 +4833,9 @@ export async function createPulseServer({
4511
4833
  sendJson(response, 202, { restarting: true, from: info.current, to: info.latest, command });
4512
4834
  setTimeout(() => {
4513
4835
  server.close(() => {
4836
+ // On Linux the new version takes this process's place (Q-23, src/updates.mjs takesItsPlace):
4837
+ // it comes back here only when it could not.
4838
+ becomeNext({ file: '/bin/sh', args: ['-c', command], env: { ...process.env, PULSE_UPDATE_RESTART: '1' }, cwd: canonicalProjectRoot, log: join(roomDir, 'update.log') });
4514
4839
  // Each system has its own shell: the command is one line either way.
4515
4840
  const shell = process.platform === 'win32' ? { file: process.env.COMSPEC ?? 'cmd.exe', args: ['/d', '/s', '/c', command] } : { file: '/bin/sh', args: ['-c', command] };
4516
4841
  // What the new copy says on the way up lands beside the ledger: if it never comes back,
@@ -4538,11 +4863,97 @@ export async function createPulseServer({
4538
4863
  diagnostics.count(`notice.${payload.id}`);
4539
4864
  return sendJson(response, 200, { ok: true });
4540
4865
  }
4866
+ // NOTIFICATIONS OF THE SYSTEM (2026-11-10, asked by the author): which kinds this computer hands
4867
+ // to macOS (or the browser). A new version and the author's notices always do; the rest are the person's.
4868
+ // A module never reaches the system: it declares `notifies` (its permission) and MADRE's page
4869
+ // decides, with this, whether what it has to say goes out (public/notifications.js).
4870
+ if (url.pathname === '/api/notifications' && (request.method === 'GET' || request.method === 'POST')) {
4871
+ if (request.method === 'POST') {
4872
+ const payload = await body(request).catch(() => ({}));
4873
+ const patch = {};
4874
+ for (const key of NOTIFICATION_KINDS) if (typeof payload[key] === 'boolean') patch[key] = payload[key];
4875
+ if (payload.modules && typeof payload.modules === 'object' && !Array.isArray(payload.modules)) {
4876
+ const declared = new Set(MODULES.filter((one) => one.notifies).map((one) => one.id));
4877
+ const current = (await readConfig(root)).notifications?.modules ?? {};
4878
+ const modules = { ...current };
4879
+ for (const [id, on] of Object.entries(payload.modules)) if (declared.has(id) && typeof on === 'boolean') modules[id] = on;
4880
+ patch.modules = modules;
4881
+ }
4882
+ await updateConfig(root, { notifications: patch });
4883
+ }
4884
+ const kept = (await readConfig(root)).notifications ?? {};
4885
+ const prefs = Object.fromEntries(NOTIFICATION_KINDS.map((key) => [key, kept[key] !== false]));
4886
+ const modules = MODULES.filter((one) => one.notifies).map((one) => ({ id: one.id, name: say(one.name), about: say(one.notifies.label), note: one.notifies.note ? say(one.notifies.note) : null, on: kept.modules?.[one.id] !== false }));
4887
+ return sendJson(response, 200, { prefs, modules });
4888
+ }
4541
4889
  if (request.method === 'POST' && url.pathname === '/api/notices/settings') {
4542
4890
  const payload = await body(request).catch(() => ({}));
4543
4891
  if (typeof payload.enabled === 'boolean') await updateConfig(root, { notices: { enabled: payload.enabled } });
4544
4892
  return sendJson(response, 200, await noticesForPage());
4545
4893
  }
4894
+ // MADRE App's subscription (src/billing.mjs): read and changed from the pages of this computer only.
4895
+ if (url.pathname === '/api/subscription' || url.pathname.startsWith('/api/subscription/')) {
4896
+ if (viaPhone) return sendJson(response, 404, { error: t('Not found.') });
4897
+ if (request.method === 'GET' && url.pathname === '/api/subscription') return sendJson(response, 200, await billingForPage());
4898
+ if (request.method !== 'POST' || request.headers.origin !== `http://${request.headers.host}`) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4899
+ const payload = await body(request).catch(() => ({}));
4900
+ const now = await billingNow();
4901
+ if (now.view.state === 'off') return sendJson(response, 409, { error: t('There is no subscription in this copy of MADRE.') });
4902
+ if (url.pathname === '/api/subscription/subscribe') {
4903
+ if (!billingKey) return sendJson(response, 503, { error: t('Subscriptions are not open yet. Try again in a few days.') });
4904
+ const order = await newOrder(root, { language: roomLanguage() });
4905
+ orderAsked = 0;
4906
+ await billingNow();
4907
+ return sendJson(response, 200, { url: order.url });
4908
+ }
4909
+ // Already subscribed, on another computer or before (2026-11-18): the email of the payment gets a
4910
+ // button, and this copy's key arrives on its own once it is confirmed. Nothing to paste.
4911
+ if (url.pathname === '/api/subscription/recover') {
4912
+ if (!billingKey) return sendJson(response, 503, { error: t('Subscriptions are not open yet. Try again in a few days.') });
4913
+ const started = await startRecovery(root, { email: payload.email, language: roomLanguage() });
4914
+ if (started.error === 'email') return sendJson(response, 422, { error: t('Write the email you paid with.') });
4915
+ if (started.error === 'too_many') return sendJson(response, 429, { error: t('You asked several times already. Wait an hour and try again.') });
4916
+ if (started.error) return sendJson(response, 502, { error: t('madre.run did not answer. Try again in a moment.') });
4917
+ recoveryAsked = 0;
4918
+ return sendJson(response, 200, await billingForPage({ ask: false }));
4919
+ }
4920
+ if (url.pathname === '/api/subscription/recover/stop') {
4921
+ await stopRecovery(root);
4922
+ return sendJson(response, 200, await billingForPage({ ask: false }));
4923
+ }
4924
+ if (url.pathname === '/api/subscription/manage') {
4925
+ const where = await portalUrl(root, { language: roomLanguage() });
4926
+ return where ? sendJson(response, 200, { url: where }) : sendJson(response, 502, { error: t('madre.run did not answer. Try again in a moment.') });
4927
+ }
4928
+ if (url.pathname === '/api/subscription/seen') {
4929
+ await markBillingSeen(root, String(payload.moment ?? ''));
4930
+ return sendJson(response, 200, await billingForPage({ ask: false }));
4931
+ }
4932
+ if (url.pathname === '/api/subscription/project' && !salasRoom) {
4933
+ const chosen = await chooseProject(root, { room: projectRoomId(canonicalProjectRoot), name: basename(canonicalProjectRoot) });
4934
+ if (!chosen.ok) return sendJson(response, 409, { error: t('You can change the project that takes messages once a day. Next time: {when}.', { when: new Date(chosen.next).toLocaleString(roomLanguage() === 'en' ? 'en-US' : 'es-MX', { weekday: 'long', hour: 'numeric', minute: '2-digit' }) }), active: chosen.active });
4935
+ return sendJson(response, 200, await billingForPage({ ask: false }));
4936
+ }
4937
+ return sendJson(response, 404, { error: t('Not found.') });
4938
+ }
4939
+ // The author's switch for the subscription: signed here with the notices' key, sent to madre.run,
4940
+ // read by every app. Only in the author's copy run from source, from this computer.
4941
+ if (request.method === 'POST' && url.pathname === '/api/owner/billing') {
4942
+ const address = request.socket.remoteAddress ?? '';
4943
+ if (viaPhone || !['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(address) || !(await ownerCanNotify())) return sendJson(response, 404, { error: t('Not found.') });
4944
+ if (request.headers.origin !== `http://${request.headers.host}`) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4945
+ const payload = await body(request).catch(() => ({}));
4946
+ if (typeof payload.on !== 'boolean') return sendJson(response, 422, { error: t('Say whether it is on or off.') });
4947
+ if (payload.on && !billingKey) return sendJson(response, 409, { error: t('First make the key of the subscription keys: node scripts/billing-key.mjs. Without it nobody could pay.') });
4948
+ const at = new Date().toISOString();
4949
+ const sent = signSwitch({ on: payload.on, from: at, trialDays: TRIAL_DAYS, price: { mxn: PRICE_MXN }, at }, await readFile(NOTICES_KEY_FILE, 'utf8'));
4950
+ const token = await readSecret(root, OWNER_VAULT, 'usage');
4951
+ const answer = await globalThis.fetch(`${billingSite()}/api/cobro`, { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify(sent), signal: AbortSignal.timeout(10000) }).catch(() => null);
4952
+ const said = answer ? await answer.json().catch(() => ({})) : {};
4953
+ if (!answer?.ok) return sendJson(response, 502, { error: said.error ? t('madre.run said: {error}', { error: said.error }) : t('madre.run did not answer.') });
4954
+ widgetReadings.delete('billing');
4955
+ return sendJson(response, 200, { ok: true, switch: sent.switch });
4956
+ }
4546
4957
  // Writing one, or taking it back: only from this computer, only in the author's copy.
4547
4958
  if (request.method === 'POST' && (url.pathname === '/api/owner/notices' || url.pathname === '/api/owner/notices/retire')) {
4548
4959
  const address = request.socket.remoteAddress ?? '';
@@ -4654,6 +5065,25 @@ export async function createPulseServer({
4654
5065
  if (mounted.error) return sendJson(response, 409, mounted);
4655
5066
  return sendJson(response, 200, { ...(await chatsView()), opened: made.id });
4656
5067
  }
5068
+ // Summarize and continue (2026-11-11): the summary its agent wrote opens a new conversation.
5069
+ const carryMatch = url.pathname.match(/^\/api\/chats\/([a-z0-9]+)\/carry$/);
5070
+ if (carryMatch && request.method === 'POST') {
5071
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5072
+ const payload = await body(request).catch(() => ({}));
5073
+ const index = await chatIndex(roomDir);
5074
+ const before = index.chats[carryMatch[1]];
5075
+ // Its name as the page saw it before the summary was asked for: an unnamed conversation took
5076
+ // the request itself as its name, and gets it back empty.
5077
+ const named = typeof payload.title === 'string' ? payload.title.trim().slice(0, 80) || null : (before?.title ?? null);
5078
+ if (before && typeof payload.title !== 'undefined' && !named) await renameChat(roomDir, carryMatch[1], '');
5079
+ // One that already continued another keeps one «· continued», not a chain of them.
5080
+ const title = named ? t('{title} · continued', { title: named.replace(/ · (?:continued|sigue)$/, '').slice(0, 60) }) : null;
5081
+ const made = await carryChat(roomDir, carryMatch[1], { title, summary: payload.summary, from: named });
5082
+ if (!made) return sendJson(response, 400, { error: t('There was no summary to carry.') });
5083
+ const mounted = await mountChat(made.id);
5084
+ if (mounted.error) return sendJson(response, 409, mounted);
5085
+ return sendJson(response, 200, { ...(await chatsView()), opened: made.id });
5086
+ }
4657
5087
  const chatMatch = url.pathname.match(/^\/api\/chats\/([a-z0-9]+)$/);
4658
5088
  if (chatMatch && request.method === 'POST') {
4659
5089
  if (viaPhone) return sendJson(response, 200, { ...(await chatsView()), opened: chatMatch[1] });
@@ -4663,7 +5093,11 @@ export async function createPulseServer({
4663
5093
  }
4664
5094
  if (chatMatch && request.method === 'PATCH') {
4665
5095
  const payload = await body(request).catch(() => ({}));
4666
- const named = await renameChat(roomDir, chatMatch[1], payload.title);
5096
+ // Its name, or whether it is pinned (2026-11-11), or both.
5097
+ let named = true;
5098
+ if ('title' in payload) named = await renameChat(roomDir, chatMatch[1], payload.title);
5099
+ if (named && 'pinned' in payload) named = await pinChat(roomDir, chatMatch[1], Boolean(payload.pinned));
5100
+ if (named && 'archived' in payload) named = await archiveChat(roomDir, chatMatch[1], Boolean(payload.archived));
4667
5101
  return named ? sendJson(response, 200, { ...(await chatsView()) }) : sendJson(response, 404, { error: t('No such conversation.') });
4668
5102
  }
4669
5103
  if (chatMatch && request.method === 'DELETE') {
@@ -4689,6 +5123,11 @@ export async function createPulseServer({
4689
5123
  const result = await room.runExam(String(payload.which ?? ''), { findings: eyecat.findings() });
4690
5124
  return sendJson(response, result?.error ? 409 : 200, { ...result, exams: await room.exams() });
4691
5125
  }
5126
+ // «Remind me later» on @madre's test: asked again in a few days (offerLocalTry).
5127
+ if (request.method === 'POST' && url.pathname === '/api/local/later') {
5128
+ if (memory) memory.metaSet('local.offered', new Date().toISOString());
5129
+ return sendJson(response, 200, { ok: true, again: LOCAL_TRY_AGAIN_MS });
5130
+ }
4692
5131
  // Somebody's own module, handed to MADRE from the panel. It goes through the same door as
4693
5132
  // everything else: checked in a fenced scratch copy, then installed for isolated calls.
4694
5133
  if (request.method === 'POST' && url.pathname === '/api/extensions/upload') {
@@ -4927,7 +5366,13 @@ export async function createPulseServer({
4927
5366
  if (list.models.length) Object.assign(grokModels, { at: Date.now(), list });
4928
5367
  return list;
4929
5368
  };
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 }) }) });
5369
+ const config = await readConfig(root);
5370
+ const found = await discoverModels({ agents, config, 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 }) });
5371
+ for (const [agent, list] of Object.entries(found)) {
5372
+ const kept = agent === 'opencode' ? config.opencode?.favorites : config.favorites?.[agent];
5373
+ if (list && typeof list === 'object') list.favorites = Array.isArray(kept) ? kept.slice(0, 3) : [];
5374
+ }
5375
+ return sendJson(response, 200, { models: found });
4931
5376
  }
4932
5377
  // OpenCode's providers for AJUSTES: who has a key or an account, what each offers, which are
4933
5378
  // left out of the chooser. Never a key: only that one is there and of what kind.
@@ -5171,7 +5616,7 @@ export async function createPulseServer({
5171
5616
  const { loaded, failures, folders } = await loadSkills({ stateRoot: root, projectRoot: canonicalProjectRoot });
5172
5617
  const fromMarket = await installedSkills(root);
5173
5618
  const skills = loaded.map((skill) => ({
5174
- id: skill.id, name: skill.name, when: skill.when, version: skill.version, minMadre: skill.minMadre,
5619
+ id: skill.id, name: skill.name, when: skill.when, line: skill.line, icon: skill.icon, version: skill.version, minMadre: skill.minMadre,
5175
5620
  credit: skill.credit, license: skill.license, origin: skill.origin, dir: skill.dir, unknown: skill.unknown,
5176
5621
  // What it says, whole: it is a page, and a person can actually read it before turning it on.
5177
5622
  body: skill.body, declares: skillDeclares(skill),
@@ -5287,7 +5732,7 @@ export async function createPulseServer({
5287
5732
  stateRoot: root, projectRoot: canonicalProjectRoot, madre: PACKAGE.version, fetchImpl: marketFetch,
5288
5733
  id: String(payload.id ?? ''), catalog, review: payload.review === true, accept: payload.accept ?? null,
5289
5734
  });
5290
- if (!done.review) await room.record('skill.installed', { id: done.id, version: done.version ?? null, from: 'market' });
5735
+ if (!done.review) { await room.record('skill.installed', { id: done.id, version: done.version ?? null, from: 'market' }); await marketUsed(); }
5291
5736
  return sendJson(response, 200, done);
5292
5737
  } catch (error) {
5293
5738
  return sendJson(response, error.code === 'REVIEW_FIRST' ? 409 : 400, { error: error.message, code: error.code ?? null });
@@ -5298,7 +5743,14 @@ export async function createPulseServer({
5298
5743
  if (request.method === 'GET' && url.pathname === '/api/market') {
5299
5744
  const kept = await keptCatalog({ stateRoot: root, ...marketKeyed });
5300
5745
  const read = kept ? (void syncMarket().catch(() => null), { catalog: kept }) : await syncMarket().catch(() => ({ catalog: null }));
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 });
5746
+ // The skills that come with MADRE (1.1.4), shown on the Market's shelf of skills as already here.
5747
+ const speak = (value) => (value && typeof value === 'object' ? value[roomLanguage()] ?? value.es ?? value.en ?? '' : String(value ?? ''));
5748
+ // And the ones this person already keeps (theirs, brought over, or got from the Market).
5749
+ const local = (await loadSkills({ stateRoot: root, projectRoot: canonicalProjectRoot }).catch(() => ({ loaded: [] }))).loaded;
5750
+ const shown = (one) => ({ id: one.id, name: speak(one.name), line: speak(one.line) || speak(one.when), version: one.version, icon: one.icon ?? null, origin: one.origin });
5751
+ const included = local.filter((one) => one.origin === 'madre').map(shown);
5752
+ const yours = local.filter((one) => one.origin !== 'madre').map(shown);
5753
+ return sendJson(response, 200, { catalog: read.catalog ?? null, off: !marketOn(), installed: await installedFromMarket(root), skills: await installedSkills(root), included, yours, licensed: await licensedIds(root), news: await marketNews(root), announce: await marketAnnouncements(root, read.catalog, MODULES.map((one) => one.id)), madre: PACKAGE.version });
5302
5754
  }
5303
5755
  if (request.method === 'POST' && url.pathname === '/api/market/seen') {
5304
5756
  await marketNewsSeen(root);
@@ -5407,6 +5859,7 @@ export async function createPulseServer({
5407
5859
  const payload = await body(request).catch(() => ({}));
5408
5860
  const result = await module.scope(await moduleContext(), { all: payload.all, rooms: payload.rooms, confirm: payload.confirm });
5409
5861
  for (const held of parked.values()) await applyRoomSettings(held.room, null);
5862
+ if (result.status < 300 && (payload.all === true || Object.values(payload.rooms ?? {}).includes(true))) await marketUsed();
5410
5863
  return sendJson(response, result.status, result.body);
5411
5864
  }
5412
5865
  // The human installs a module file an agent wrote (or they did): checked first, then copied into the chosen folder.
@@ -5474,6 +5927,7 @@ export async function createPulseServer({
5474
5927
  // A phone switches MADRE's own modules; installing one runs commands in the project.
5475
5928
  if (viaPhone && !extensionById(installMatch[1])?.toggle) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5476
5929
  const result = await installExtension(installMatch[1], await body(request));
5930
+ if (result.status < 300 && result.body?.enabled !== false && installMatch[1] !== 'ollama') await marketUsed();
5477
5931
  return sendJson(response, result.status, result.body);
5478
5932
  }
5479
5933
  if (request.method === 'POST' && /^\/api\/control\/[\w-]+\/undo$/.test(url.pathname)) {
@@ -5501,7 +5955,17 @@ export async function createPulseServer({
5501
5955
  // No turn before MADRE's license is accepted on this computer (src/terms.mjs): a page left open
5502
5956
  // from before, or a script, is told where to accept it.
5503
5957
  if (!viaPhone && !(await readTerms(root)).accepted) return sendJson(response, 403, { error: t('Accept MADRE\'s license in Home to start.'), terms: true });
5504
- const payload = await body(request);
5958
+ // The limited mode of MADRE App (src/billing.mjs): the Coordinator comes with the subscription,
5959
+ // and one project takes messages; the others are read, never locked or emptied.
5960
+ if (billingInApp()) {
5961
+ const plan = await billingNow();
5962
+ if (plan.view.state === 'limited') {
5963
+ if (salasRoom) return sendJson(response, 402, { error: t('The Coordinator comes with the subscription. Your projects still work: write in the one you are using.'), subscription: { limit: 'coordinator' } });
5964
+ const claim = await claimProject(root, { room: projectRoomId(canonicalProjectRoot), name: basename(canonicalProjectRoot), view: plan.view });
5965
+ if (!claim.ok) return sendJson(response, 402, { error: t('Without the subscription, one project takes messages: {name}. This one stays as it is, to read.', { name: claim.active?.name ?? '' }), subscription: { limit: 'project', active: claim.active } });
5966
+ }
5967
+ }
5968
+ const payload = await body(request, { limit: MESSAGE_LIMIT, tooLarge: t('Your message is too long to send as text. Attach it as a file instead.') });
5505
5969
  // A phone asks up to #2. The bridge already said so; the room says it again, and records
5506
5970
  // where the message came from. Only the bridge's word counts for that, never the body's.
5507
5971
  if (viaPhone) {
@@ -5561,11 +6025,12 @@ export async function createPulseServer({
5561
6025
  // A route that broke is a failure of MADRE's, not of the request: told, with the route's shape
5562
6026
  // (its ids taken out) and MADRE's own lines it went through. A body that was not JSON is the
5563
6027
  // request's.
5564
- if (!(error instanceof SyntaxError)) {
6028
+ // Nor is one that was too big to take (D-40): said as it is, with its own status.
6029
+ if (!(error instanceof SyntaxError) && error?.status !== 413) {
5565
6030
  const shape = url.pathname.replace(/\/[0-9a-f]{6,}(?=\/|$)/gi, '/:id').replace(/\/\d+(?=\/|$)/g, '/:n');
5566
6031
  diagnostics.error({ kind: 'route', where: `${request.method} ${shape}`, message: error?.message ?? String(error), stack: error?.stack ?? null });
5567
6032
  }
5568
- sendJson(response, 400, { error: error.message });
6033
+ sendJson(response, error?.status === 413 ? 413 : 400, { error: error.message });
5569
6034
  }
5570
6035
  });
5571
6036
  listening = server;
@@ -5580,7 +6045,7 @@ export async function createPulseServer({
5580
6045
  unwatchOutbound();
5581
6046
  // In-flight agent processes are killed and their turns recorded as failed
5582
6047
  // before the SSE clients go away, so open pages see the outcome.
5583
- const shutdown = Promise.all([room, ...[...parked.values()].map((held) => held.room)].map((each) => each.shutdown().catch((error) => console.error(`MADRE shutdown error: ${error.message}`))));
6048
+ const shutdown = Promise.all([...[room, ...[...parked.values()].map((held) => held.room)].map((each) => each.shutdown().catch((error) => console.error(`MADRE shutdown error: ${error.message}`))), ...closing]);
5584
6049
  // off() also ends the streams of pages watching a conversation held open beside.
5585
6050
  for (const held of parked.values()) held.off();
5586
6051
  parked.clear();
@@ -5607,14 +6072,20 @@ export async function createPulseServer({
5607
6072
  };
5608
6073
  server.on('close', () => quotaMonitor.stop());
5609
6074
  server.on('close', () => clearTimeout(reprobe));
6075
+ server.on('close', () => clearTimeout(ollamaRetry));
5610
6076
  server.on('close', () => { for (const timer of [...aliveTimers, ...hereTimers]) clearTimeout(timer); });
5611
6077
 
5612
6078
  server.on('close', () => { void phone.stop(); });
5613
- return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone, salasRoom, closeOtherRooms, currentFicha, afterOpen };
6079
+ return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone, salasRoom, closeOtherRooms, currentFicha, afterOpen, bringOthersAlong };
5614
6080
  }
5615
6081
 
5616
- export async function startPulse({ port, projectRoot, openBrowser, openPath = '' }) {
5617
- const { server, agents, markOpen, phone, salasRoom, closeOtherRooms, currentFicha, afterOpen } = await createPulseServer({ projectRoot, quotaSources: defaultQuotaSources(), ficha: true, renewFicha: Boolean(openBrowser) });
6082
+ export async function startPulse({ port, projectRoot, openBrowser: asked, openPath = '' }) {
6083
+ // A start from an update to the first MADRE with a ficha opens the browser with it (Q-21).
6084
+ const openBrowser = opensBrowser({ asked, hadFicha: Boolean(await readFicha(defaultStateRoot())) });
6085
+ // A new ficha only where a browser can be opened to take it (L-13): over SSH, or on a Linux with no
6086
+ // screen, Home made one nobody received, and the tabs open through a tunnel lost theirs.
6087
+ const canOpen = Boolean(openBrowser) && browserWays(await environmentOnce().catch(() => null)).length > 0;
6088
+ const { server, agents, markOpen, phone, salasRoom, closeOtherRooms, currentFicha, afterOpen, bringOthersAlong } = await createPulseServer({ projectRoot, quotaSources: defaultQuotaSources(), ficha: true, renewFicha: canOpen });
5618
6089
  await new Promise((resolve, reject) => {
5619
6090
  server.once('error', reject);
5620
6091
  server.listen(port, '127.0.0.1', resolve);
@@ -5623,6 +6094,8 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
5623
6094
  // The room is taken from here on, and says so on disk for anyone who tries to open it again.
5624
6095
  await markOpen(address.port);
5625
6096
  void afterOpen().catch(() => null);
6097
+ // Back from an update: the rest of MADRE comes to this version too (L-13). Not waited for.
6098
+ if (process.env.PULSE_UPDATE_RESTART === '1') void bringOthersAlong().catch(() => null);
5626
6099
  // From here this room offers to host the phone's bridge, when there is a phone to reach it.
5627
6100
  phone.start();
5628
6101
  const url = `http://127.0.0.1:${address.port}`;
@@ -5636,7 +6109,10 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
5636
6109
  // In the language MADRE speaks (QA 1.1.0, NUE-01): the terminal said «MADRE is ready» above
5637
6110
  // «Abre esta dirección…», and Home was called «Project: …/.pulse/salas», a folder of MADRE's own.
5638
6111
  const where = salasRoom ? t('Home: every project on this computer') : `${t('Project:')} ${projectRoot}`;
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` : ''}`);
6112
+ // The key only where a person or the app reads it (L-15): a log gets the address without it.
6113
+ const shown = fichaShown() ? opening : withoutFicha(opening);
6114
+ const keyNote = shown === opening ? '' : ` ${t('The access key is not written here. To open MADRE, run npx @jossuealcala/madre in a terminal on this computer.')}\n`;
6115
+ console.log(`\n${t('MADRE is ready')}\n\n ${shown}\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` : ''}${keyNote}`);
5640
6116
  // Not waited for: the signals below are set up while the browser opens.
5641
6117
  if (openBrowser) void openUrl(opening);
5642
6118
  // SIGHUP too: closing the Terminal the room was started in is a way of closing it.
@@ -5649,6 +6125,16 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
5649
6125
  server.close(() => process.exit(0));
5650
6126
  });
5651
6127
  }
6128
+ // Inside the app (MADRE.app, Tauri), the app holds this process's stdin open and never writes to it:
6129
+ // when the app dies — Force Quit, a crash — the pipe closes, and Home closes as it does for a signal,
6130
+ // projects first, instead of staying behind with nobody to see it (2026-11-09).
6131
+ if (process.env.MADRE_APP === '1' && salasRoom) {
6132
+ process.stdin.once('end', async () => {
6133
+ await closeOtherRooms().catch(() => null);
6134
+ server.close(() => process.exit(0));
6135
+ });
6136
+ process.stdin.resume();
6137
+ }
5652
6138
  // Salas asked this room to close: the same as a signal.
5653
6139
  server.once('madre:close', () => server.close(() => process.exit(0)));
5654
6140
  // Uninstalling (src/uninstall.mjs): the room closes as it does for a signal — every write done,