@jossuealcala/madre 1.1.2 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/CHANGELOG.en.md +40 -1
  2. package/CHANGELOG.md +40 -1
  3. package/README.en.md +3 -3
  4. package/README.md +3 -3
  5. package/SECURITY.md +11 -6
  6. package/TRADEMARKS.md +6 -2
  7. package/bin/madre.mjs +76 -11
  8. package/docs/REFERENCE.md +16 -10
  9. package/docs/SDK.md +36 -9
  10. package/docs/en/REFERENCE.md +12 -8
  11. package/docs/en/SDK.md +34 -8
  12. package/docs/en/training/README.md +1 -1
  13. package/docs/sdk/connector-module.mjs +1 -1
  14. package/docs/sdk/hello-module.mjs +39 -4
  15. package/docs/training/README.md +1 -1
  16. package/docs/training/train.sh +3 -0
  17. package/habilidades/explicamelo-facil/HABILIDAD.md +19 -0
  18. package/habilidades/hojas-de-calculo/HABILIDAD.md +18 -0
  19. package/habilidades/mensajes-a-clientes/HABILIDAD.md +19 -0
  20. package/habilidades/publicaciones-para-redes/HABILIDAD.md +19 -0
  21. package/habilidades/resumen-y-pendientes/HABILIDAD.md +18 -0
  22. package/habilidades/tu-pagina-paso-a-paso/HABILIDAD.md +19 -0
  23. package/package.json +7 -4
  24. package/public/activity.js +66 -22
  25. package/public/app.js +4947 -894
  26. package/public/assets/brand/OFL-SpaceGrotesk.txt +93 -0
  27. package/public/assets/brand/SpaceGrotesk-latin-ext.woff2 +0 -0
  28. package/public/assets/brand/SpaceGrotesk-latin.woff2 +0 -0
  29. package/public/assets/brand/madre-app-180.png +0 -0
  30. package/public/assets/brand/madre-app-192.png +0 -0
  31. package/public/assets/brand/madre-app-512.png +0 -0
  32. package/public/assets/brand/madre-app.svg +1 -1
  33. package/public/assets/brand/madre-favicon.svg +1 -1
  34. package/public/attribution.js +29 -19
  35. package/public/auto-open.js +102 -0
  36. package/public/brands.js +36 -19
  37. package/public/changes.js +63 -0
  38. package/public/en.js +1085 -102
  39. package/public/es.js +2940 -1656
  40. package/public/i18n.js +11 -0
  41. package/public/index.html +31 -27
  42. package/public/loader.js +322 -117
  43. package/public/macroverso.js +57 -355
  44. package/public/manual-content.js +69 -9
  45. package/public/manual.js +21 -6
  46. package/public/market-view.js +298 -84
  47. package/public/market.js +25 -2
  48. package/public/mcp-catalog.js +7 -2
  49. package/public/missions.js +169 -0
  50. package/public/news-scenes.js +292 -0
  51. package/public/nostromo-engine.js +935 -654
  52. package/public/notices.js +78 -0
  53. package/public/notifications.js +119 -0
  54. package/public/power.js +1 -1
  55. package/public/provider-marks.js +170 -0
  56. package/public/provider-pick.js +147 -0
  57. package/public/resay.js +4 -0
  58. package/public/review-ask.js +16 -13
  59. package/public/routing.js +29 -3
  60. package/public/salas-mac.css +467 -47
  61. package/public/salas-mac.html +8 -5
  62. package/public/salas-mac.js +805 -109
  63. package/public/salas.css +2 -2
  64. package/public/salas.html +2 -2
  65. package/public/salas.js +1 -1
  66. package/public/starters.js +128 -0
  67. package/public/styles.css +3036 -340
  68. package/public/subscription.js +303 -0
  69. package/public/terms-field.js +170 -0
  70. package/public/terms.js +117 -19
  71. package/public/tips.js +158 -0
  72. package/public/tour-chapters.js +88 -88
  73. package/public/tour.js +364 -46
  74. package/public/troubleshooting.js +313 -27
  75. package/public/welcome-scene.js +446 -0
  76. package/public/welcome.js +827 -282
  77. package/src/adapters/claude.mjs +2 -1
  78. package/src/adapters/codex.mjs +2 -1
  79. package/src/adapters/cursor.mjs +9 -6
  80. package/src/adapters/gemini-rest.mjs +236 -0
  81. package/src/adapters/gemini.mjs +13 -7
  82. package/src/adapters/grok.mjs +290 -0
  83. package/src/adapters/madre.mjs +71 -23
  84. package/src/adapters/opencode.mjs +15 -2
  85. package/src/adapters/process.mjs +14 -3
  86. package/src/adapters/steps.mjs +176 -0
  87. package/src/app-invite.mjs +90 -0
  88. package/src/auth-probe.mjs +32 -0
  89. package/src/billing-key.mjs +8 -0
  90. package/src/billing.mjs +317 -0
  91. package/src/bridge/policy.mjs +1 -1
  92. package/src/capabilities.mjs +46 -10
  93. package/src/chats.mjs +44 -2
  94. package/src/checkpoint.mjs +119 -1
  95. package/src/codex-route.mjs +113 -0
  96. package/src/commands.mjs +5 -2
  97. package/src/credentials.mjs +46 -8
  98. package/src/dataset.mjs +18 -7
  99. package/src/directives.mjs +1 -0
  100. package/src/event-store.mjs +25 -2
  101. package/src/extensions.mjs +5 -1
  102. package/src/ficha.mjs +158 -0
  103. package/src/files.mjs +36 -2
  104. package/src/image-studio.mjs +13 -3
  105. package/src/install-metrics.mjs +9 -3
  106. package/src/lease.mjs +6 -1
  107. package/src/looks.mjs +4 -1
  108. package/src/market-check.mjs +1 -1
  109. package/src/market-remote.mjs +135 -1
  110. package/src/mcp/image-server.mjs +59 -90
  111. package/src/mcp/memory-server.mjs +10 -0
  112. package/src/memory-tools.mjs +3 -0
  113. package/src/memory.mjs +29 -4
  114. package/src/models.mjs +21 -3
  115. package/src/modules/ahp.mjs +10 -4
  116. package/src/modules/bishop-exam.mjs +41 -12
  117. package/src/modules/bishop.mjs +2 -2
  118. package/src/modules/choices.mjs +12 -10
  119. package/src/modules/fetch-alone.mjs +7 -0
  120. package/src/modules/github.mjs +6 -2
  121. package/src/modules/helpers.mjs +23 -5
  122. package/src/modules/image-providers.mjs +281 -0
  123. package/src/modules/image-studio.mjs +106 -39
  124. package/src/modules/index.mjs +61 -12
  125. package/src/modules/intents-observe.mjs +3 -1
  126. package/src/modules/isolated.mjs +160 -0
  127. package/src/modules/ollama.mjs +35 -6
  128. package/src/modules/playwright.mjs +78 -20
  129. package/src/modules/reminders.mjs +42 -2
  130. package/src/modules/ripley.mjs +2 -1
  131. package/src/modules/run-alone.mjs +122 -0
  132. package/src/modules/runs.mjs +11 -8
  133. package/src/modules/sdk.mjs +10 -3
  134. package/src/notices-key.mjs +8 -0
  135. package/src/notices.mjs +185 -0
  136. package/src/ollama.mjs +57 -15
  137. package/src/opencode-health.mjs +1 -1
  138. package/src/outbound.mjs +124 -13
  139. package/src/quota-sources.mjs +148 -3
  140. package/src/review-ask.mjs +55 -31
  141. package/src/room/archivist.mjs +30 -5
  142. package/src/room/busy.mjs +16 -0
  143. package/src/room/changes.mjs +79 -0
  144. package/src/room/control.mjs +36 -6
  145. package/src/room/economy.mjs +1 -1
  146. package/src/room/guard.mjs +39 -2
  147. package/src/room/prompt.mjs +49 -6
  148. package/src/room/vectors.mjs +7 -1
  149. package/src/room.mjs +181 -49
  150. package/src/router.mjs +1 -1
  151. package/src/runs.mjs +39 -0
  152. package/src/runtime-detection.mjs +46 -6
  153. package/src/salas.mjs +181 -18
  154. package/src/server.mjs +1101 -118
  155. package/src/service.mjs +116 -0
  156. package/src/setup-trouble.mjs +20 -1
  157. package/src/setup.mjs +1 -1
  158. package/src/skill-check.mjs +269 -0
  159. package/src/skills-import.mjs +128 -0
  160. package/src/skills.mjs +502 -0
  161. package/src/terms.mjs +23 -5
  162. package/src/tour.mjs +31 -5
  163. package/src/updates.mjs +47 -4
  164. package/src/web-preview.mjs +181 -0
  165. package/src/whats-new.mjs +121 -1
  166. package/src/rumbo.mjs +0 -337
package/src/ficha.mjs ADDED
@@ -0,0 +1,158 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // The ficha: what a request to MADRE carries to show it comes from the person (2026-11-02,
4
+ // external review #5).
5
+ //
6
+ // MADRE listens on 127.0.0.1, and request-guard.mjs keeps other web pages out. It did not keep out
7
+ // other programs: any process of this computer — of any user, and in WSL2 any program of Windows —
8
+ // could read a project's conversations, install a module that runs with the person's permissions,
9
+ // or open #4 by writing an Origin header by hand. Now every request that reads or changes something
10
+ // carries the ficha: a random secret in `~/.pulse/credentials/ficha.json`, readable only by the
11
+ // person's own user (0600 inside 0700), as Jupyter does with its token.
12
+ //
13
+ // · The browser gets it once, in the address MADRE opens (`?ficha=…`): the page answers with a
14
+ // cookie (HttpOnly, SameSite=Strict) and the same address without it. Cookies do not tell ports
15
+ // apart, so the one cookie serves Home and every project of this computer.
16
+ // · MADRE's own processes (the CLI, Home asking a project, a project asking another) read the file
17
+ // and send it in the `x-madre-ficha` header.
18
+ // · Home makes a new one each time it starts and opens the browser itself, so a ficha lives as
19
+ // long as that run. A restart with no browser (an update, a project Home opens) keeps it, and
20
+ // so do the tabs already open.
21
+ //
22
+ // What it does not stop, and is said in SECURITY.md: a program running as the person can read the
23
+ // file, as it can read everything else of theirs; and the cookie travels to any other port of
24
+ // 127.0.0.1 this browser visits.
25
+ import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
26
+ import { fchmodSync, openSync } from 'node:fs';
27
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
28
+ import { homedir } from 'node:os';
29
+ import { join } from 'node:path';
30
+
31
+ export const FICHA_HEADER = 'x-madre-ficha';
32
+ export const FICHA_COOKIE = 'madre_ficha';
33
+ export const FICHA_PARAM = 'ficha';
34
+ // What a 401 says in its headers, so the page knows to reload into the page that explains it.
35
+ export const FICHA_NEEDED = 'needed';
36
+ const OWNER_ONLY = 0o600;
37
+ const OWNER_DIR = 0o700;
38
+ const FICHA_HEX = /^[0-9a-f]{64}$/;
39
+
40
+ export const defaultStateRoot = (env = process.env) => env.PULSE_HOME ?? join(homedir(), '.pulse');
41
+ export const fichaFile = (stateRoot) => join(stateRoot, 'credentials', 'ficha.json');
42
+
43
+ // The ficha on file, or null when there is none (or it is not one).
44
+ export async function readFicha(stateRoot) {
45
+ try {
46
+ const parsed = JSON.parse(await readFile(fichaFile(stateRoot), 'utf8'));
47
+ return typeof parsed?.ficha === 'string' && FICHA_HEX.test(parsed.ficha) ? parsed.ficha : null;
48
+ } catch { return null; }
49
+ }
50
+
51
+ // The ficha this run uses: the one on file, or a new one when there is none or `renew` asks for it.
52
+ // Written whole beside the name and renamed over it, so nobody reads half a ficha.
53
+ export async function ensureFicha(stateRoot, { renew = false } = {}) {
54
+ if (!renew) {
55
+ const kept = await readFicha(stateRoot);
56
+ if (kept) return kept;
57
+ }
58
+ const dir = join(stateRoot, 'credentials');
59
+ await mkdir(dir, { recursive: true, mode: OWNER_DIR });
60
+ // An older credentials directory may predate this mode (src/vault.mjs does the same).
61
+ await chmod(dir, OWNER_DIR).catch(() => {});
62
+ const file = fichaFile(stateRoot);
63
+ const draft = `${file}.${process.pid}.${randomUUID()}.tmp`;
64
+ const ficha = randomBytes(32).toString('hex');
65
+ try {
66
+ await writeFile(draft, `${JSON.stringify({ ficha, at: new Date().toISOString() })}\n`, { mode: OWNER_ONLY });
67
+ await rename(draft, file);
68
+ } finally {
69
+ await rm(draft, { force: true });
70
+ }
71
+ await chmod(file, OWNER_ONLY).catch(() => {});
72
+ return ficha;
73
+ }
74
+
75
+ // The ficha as the server checks it: read again when the file changes (Home renewed it while this
76
+ // project was open), never more than once a second.
77
+ export function fichaReader(stateRoot, { everyMs = 1000 } = {}) {
78
+ let value = null;
79
+ let seen = null;
80
+ let checked = 0;
81
+ return async () => {
82
+ const now = Date.now();
83
+ if (value && now - checked < everyMs) return value;
84
+ checked = now;
85
+ const info = await stat(fichaFile(stateRoot)).catch(() => null);
86
+ const stamp = info ? `${info.mtimeMs}:${info.size}` : null;
87
+ if (stamp !== seen || !value) { value = await readFicha(stateRoot); seen = stamp; }
88
+ return value;
89
+ };
90
+ }
91
+
92
+ // A log a MADRE process writes on its way up (start.log, restart.log, update.log) holds the address
93
+ // with the ficha that process prints: kept for the person alone, as the ficha is. One written
94
+ // before this rule, open to every user of the computer, is closed the next time it is opened
95
+ // (2026-11-03, the ficha's test).
96
+ export function openPrivateLog(file) {
97
+ const fd = openSync(file, 'a', OWNER_ONLY);
98
+ try { fchmodSync(fd, OWNER_ONLY); } catch { /* a filesystem without modes */ }
99
+ return fd;
100
+ }
101
+
102
+ // The header a MADRE process sends to another, or nothing when this computer has no ficha yet (a
103
+ // MADRE that does not ask for one does not need it).
104
+ export async function fichaHeaders(stateRoot = defaultStateRoot()) {
105
+ const ficha = await readFicha(stateRoot);
106
+ return ficha ? { [FICHA_HEADER]: ficha } : {};
107
+ }
108
+
109
+ // The address MADRE opens and prints: the page's own, with the ficha for the browser to keep.
110
+ export function withFicha(url, ficha) {
111
+ if (!ficha) return url;
112
+ const address = new URL(url);
113
+ address.searchParams.set(FICHA_PARAM, ficha);
114
+ return address.toString();
115
+ }
116
+
117
+ // Where the address may carry the ficha when MADRE writes it out (L-15, 2026-11-14): a terminal a
118
+ // person reads at once, or the desktop app, which reads it to open MADRE (MADRE_APP=1). Anywhere
119
+ // else — a log a start script or a service writes, which others on the computer may read — the
120
+ // address goes without it. PULSE_PRINT_FICHA=1 asks for it anyway (QA scripts that read their log).
121
+ export function fichaShown({ stream = process.stdout, env = process.env } = {}) {
122
+ return Boolean(stream?.isTTY) || env.MADRE_APP === '1' || env.PULSE_PRINT_FICHA === '1';
123
+ }
124
+ export function withoutFicha(url) {
125
+ try {
126
+ const address = new URL(url);
127
+ if (!address.searchParams.has(FICHA_PARAM)) return url;
128
+ address.searchParams.delete(FICHA_PARAM);
129
+ return address.toString();
130
+ } catch { return url; }
131
+ }
132
+
133
+ // Constant time, and never a throw on something that is not a string.
134
+ export function sameFicha(given, ficha) {
135
+ if (typeof given !== 'string' || typeof ficha !== 'string' || !given || given.length !== ficha.length) return false;
136
+ return timingSafeEqual(Buffer.from(given), Buffer.from(ficha));
137
+ }
138
+
139
+ export function cookieFicha(cookieHeader) {
140
+ for (const part of String(cookieHeader ?? '').split(';')) {
141
+ const [name, ...rest] = part.trim().split('=');
142
+ if (name === FICHA_COOKIE) return rest.join('=');
143
+ }
144
+ return null;
145
+ }
146
+
147
+ // Whether a request carries this ficha, in its header or in the page's cookie.
148
+ export function carriesFicha(headers = {}, ficha) {
149
+ return sameFicha(headers[FICHA_HEADER], ficha) || sameFicha(cookieFicha(headers.cookie), ficha);
150
+ }
151
+
152
+ export const fichaCookie = (ficha) => `${FICHA_COOKIE}=${ficha}; Path=/; HttpOnly; SameSite=Strict; Max-Age=2592000`;
153
+
154
+ // RIPLEY's preview runs in a sealed frame, whose requests carry no cookie, and the agents' headless
155
+ // browser (src/modules/playwright.mjs) has none either. Its pages are served under a key of their own,
156
+ // made from the ficha: it opens the preview of this project's files and nothing else, and it says
157
+ // nothing of the ficha it comes from.
158
+ export const previewKey = (ficha) => createHmac('sha256', ficha).update('madre preview').digest('hex').slice(0, 32);
package/src/files.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // SPDX-License-Identifier: BUSL-1.1
2
2
  // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  import { createHash, randomUUID } from 'node:crypto';
4
- import { mkdir, readdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';
4
+ import { copyFile, mkdir, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
5
5
  import { dirname, extname, join, resolve, sep } from 'node:path';
6
6
 
7
7
  // Read-only file access for the room UI, and human attachments.
@@ -237,7 +237,41 @@ export async function createEmptyFile(root, relative) {
237
237
  return { status: 201, path: parts.join('/') };
238
238
  }
239
239
 
240
+ // Where an attachment never goes, whatever is typed after: judged part by part, as createEmptyFile
241
+ // splits them («datos\.env» is datos/.env too). Asked before the project's name, so nobody types it
242
+ // to be refused anyway.
243
+ export const ATTACHMENT_REFUSED = 'That place is MADRE\'s own or a secret\'s: choose another folder.';
244
+ export function attachmentPlaceRefused(to) {
245
+ return String(to ?? '').split(/[/\\]+/).some((part) => /^\.(pulse|madre|git)$/i.test(part) || /^\.env(\.|$)/i.test(part));
246
+ }
247
+
248
+ // An attachment of the conversation, saved into the project where the person says (L-2, Carlos's
249
+ // server, 2026-11-04): a patient's photo into pacientes/…/fotos/, a guide into conocimiento/. Until
250
+ // now a PDF or a photo stayed in MADRE's store; copying it in took a `cp`, which is #4. The person
251
+ // chooses the place, so no mode is asked. The same fence as a new file (createEmptyFile), never
252
+ // into MADRE's own folders, a repository's or a .env, and an existing file is never replaced.
253
+ export async function keepAttachment({ attachmentsRoot, projectRoot, fileName, to }) {
254
+ const from = await resolveInside(attachmentsRoot, String(fileName ?? ''));
255
+ if (!from || !(await stat(from).catch(() => null))?.isFile()) return { status: 404, error: 'That attachment is no longer here.' };
256
+ const clean = String(to ?? '').trim().replace(/^[/\\]+/, '');
257
+ if (attachmentPlaceRefused(clean)) return { status: 403, error: ATTACHMENT_REFUSED };
258
+ // Fenced and checked the way a new, empty file is; then the attachment is copied over it.
259
+ const made = await createEmptyFile(projectRoot, clean);
260
+ if (made.status !== 201) return made;
261
+ const canonicalRoot = await realpath(projectRoot);
262
+ const target = join(canonicalRoot, ...made.path.split('/'));
263
+ // A copy that fails takes back the empty file it was going into: the next try is not refused as
264
+ // «already there».
265
+ try { await copyFile(from, target); } catch (error) { await rm(target, { force: true }).catch(() => {}); return { status: 400, error: error.message }; }
266
+ const info = await stat(target);
267
+ return { status: 201, path: made.path, bytes: info.size };
268
+ }
269
+
240
270
  const safeName = (name) => String(name ?? 'file').replace(/[^\w.\- ]+/g, '_').replace(/^\.+/, '').slice(0, 120) || 'file';
271
+ // The name a person reads and is offered to save with (Q-5): «guía de curación.pdf» stays as it was
272
+ // written, accents and eñes included. Only what could break a line or a path is taken out; the file
273
+ // on disk keeps the plain name above.
274
+ const shownName = (name) => String(name ?? 'file').normalize('NFC').replace(/[\u0000-\u001f\u007f/\\]+/g, '_').replace(/^\.+/, '').trim().slice(0, 120) || 'file';
241
275
 
242
276
  export async function storeAttachment(attachmentsRoot, { name, bytes }) {
243
277
  if (!Buffer.isBuffer(bytes) || bytes.length === 0) throw new Error('Attachment is empty.');
@@ -249,7 +283,7 @@ export async function storeAttachment(attachmentsRoot, { name, bytes }) {
249
283
  await writeFile(path, bytes, { mode: 0o600 });
250
284
  return {
251
285
  id,
252
- name: safeName(name),
286
+ name: shownName(name),
253
287
  fileName,
254
288
  path,
255
289
  size: bytes.length,
@@ -2,25 +2,35 @@
2
2
  // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { resolveGeminiKey } from './mcp/image-server.mjs';
5
+ import { imageProvider, providerOf } from './modules/image-providers.mjs';
5
6
 
6
7
  // How MADRE attaches its image MCP server to a CLI during a lease.
7
8
  export const IMAGE_SERVER_PATH = fileURLToPath(new URL('./mcp/image-server.mjs', import.meta.url));
8
9
  export const IMAGE_SERVER_NAME = 'pulse-image';
9
10
  export const IMAGE_TOOL = 'generate_image';
10
11
 
11
- export function imageStudioFor({ enabled, model, outDir, env = process.env }) {
12
+ // `model` is the one chosen in MODULES › Images, or none: then the server draws with the first
13
+ // provider whose key it finds. `stateRoot` and `home` say where to look for the key — paths, never
14
+ // a key: Claude Code receives this whole object in its arguments (see src/mcp/image-server.mjs).
15
+ export function imageStudioFor({ enabled, model = null, outDir, stateRoot = null, home = null, env = process.env }) {
12
16
  if (!enabled || !outDir) return null;
17
+ const provider = model ? imageProvider(providerOf(model)) : null;
13
18
  return {
14
19
  name: IMAGE_SERVER_NAME,
15
20
  tool: IMAGE_TOOL,
16
21
  command: process.execPath,
17
22
  args: [IMAGE_SERVER_PATH],
23
+ // What the prompt may say about who draws (src/lease.mjs).
24
+ model: model ?? null,
25
+ vendor: provider?.vendor ?? null,
18
26
  env: {
19
27
  PULSE_IMAGE_OUT_DIR: outDir,
20
- PULSE_IMAGE_MODEL: model ?? 'gemini-2.5-flash-image',
28
+ ...(model ? { PULSE_IMAGE_MODEL: model } : {}),
29
+ ...(stateRoot ? { PULSE_IMAGE_STATE: stateRoot } : {}),
30
+ ...(home ? { PULSE_IMAGE_HOME: home } : {}),
21
31
  ...(env.GEMINI_API_KEY ? { GEMINI_API_KEY: env.GEMINI_API_KEY } : {}),
22
32
  ...(env.PULSE_IMAGE_FAKE ? { PULSE_IMAGE_FAKE: env.PULSE_IMAGE_FAKE } : {}),
23
- // So the one request that carries a prompt to Google lands in the same log as the rest.
33
+ // So the one request that carries a prompt to the image provider lands in the same log as the rest.
24
34
  ...(env.PULSE_OUTBOUND_LOG ? { PULSE_OUTBOUND_LOG: env.PULSE_OUTBOUND_LOG } : {}),
25
35
  },
26
36
  };
@@ -19,7 +19,7 @@
19
19
  // copy says it; the others see it was said.
20
20
  //
21
21
  // docs/REFERENCE.md › «Lo que sale de la máquina» says all of it; madre.run's privacy page too.
22
- import { readFile, writeFile } from 'node:fs/promises';
22
+ import { readFile, rename, rm, writeFile } from 'node:fs/promises';
23
23
  import { basename, join } from 'node:path';
24
24
  import { installId } from './heartbeat.mjs';
25
25
  import { compareVersions } from './updates.mjs';
@@ -27,7 +27,8 @@ import { compareVersions } from './updates.mjs';
27
27
  export const PRESENCE_URL = 'https://madre.run/api/presence';
28
28
  export const PRESENCE_EVERY_MS = 5 * 60 * 1000;
29
29
  const KEY_PART = /^[a-z0-9][a-z0-9-]{0,30}$/;
30
- const CHANNELS = new Set(['npx', 'global', 'project', 'source']);
30
+ // «app»: the desktop app (MADRE_APP=1, src/updates.mjs), counted apart since 2026-11-13.
31
+ const CHANNELS = new Set(['npx', 'global', 'project', 'source', 'app']);
31
32
  const SHELLS = new Set(['zsh', 'bash', 'fish', 'sh', 'pwsh', 'powershell', 'nu', 'dash', 'ksh', 'tcsh']);
32
33
  const GB = 1024 ** 3;
33
34
 
@@ -76,7 +77,12 @@ export async function noteLifecycle({ root, version, hadId, now = new Date() })
76
77
  if (!kept?.version || kept.version !== version) {
77
78
  // `before`: this copy was in use before 1.1.0 (src/terms.mjs tells it what changed).
78
79
  const before = kept ? kept.before === true : Boolean(hadId);
79
- await writeFile(file, `${JSON.stringify({ first: kept?.first ?? now.toISOString(), version, at: now.toISOString(), ...(before ? { before: true } : {}) })}\n`).catch(() => null);
80
+ // Written beside it and swapped in one step (Q-19): Home and a project read this file while
81
+ // another start rewrites it, and a file emptied before being filled read as «this copy is new».
82
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
83
+ await writeFile(temp, `${JSON.stringify({ first: kept?.first ?? now.toISOString(), version, at: now.toISOString(), ...(before ? { before: true } : {}) })}\n`)
84
+ .then(() => rename(temp, file))
85
+ .catch(() => rm(temp, { force: true }).catch(() => null));
80
86
  }
81
87
  return { event, first: kept?.first ?? now.toISOString() };
82
88
  }
package/src/lease.mjs CHANGED
@@ -103,6 +103,10 @@ export function diffSnapshots(before, after, { relativeDir }) {
103
103
  // the ones whose adapter hands a subagent exactly the turn's permissions (src/adapters/claude.mjs,
104
104
  // opencode.mjs; Codex's subagents inherit its sandbox). Never in #4.
105
105
  export const SUBAGENT_AGENTS = new Set(['claude', 'opencode', 'codex']);
106
+ // Where MADRE puts the images Grok generates (2026-11-08, the author's choice): its image tool saves
107
+ // them in Grok's own folder, outside the project, and with no terminal below #4 it cannot copy them.
108
+ // At #2 the turn's draft folder; at #3 and #4 `imagenes/` at the project's root.
109
+ export const grokImagesDir = (lease = {}) => lease?.scratchDir || 'imagenes';
106
110
  export const subagentsAllowed = (agentId, { airlock = false } = {}) => !airlock && SUBAGENT_AGENTS.has(agentId);
107
111
 
108
112
  export function leaseInstructions({ outDir, agentId, scopes = { write: true, imageGen: agentId === 'codex' }, capable = null, imageStudio = null, control = false, create = false, airlock = false, scratchDir = null }) {
@@ -123,7 +127,8 @@ export function leaseInstructions({ outDir, agentId, scopes = { write: true, ima
123
127
  ? 'Do not modify, overwrite, rename or delete files that already exist: MADRE restores them after your turn and tells the human. If a change to an existing file is truly needed, say so and stop; the human can grant #3 CONTROL. Never touch .git, .pulse, .madre, .env files or credentials.'
124
128
  : 'Write every file you produce there (images, code, documents); paths elsewhere are denied.',
125
129
  airlock ? 'End with the commands you ran, what left the machine, and the files you changed.' : control ? 'End with a short list of the files you changed and why.' : create ? 'End with a short list of the files you created, with their paths, and why there.' : 'Reading the project stays allowed. Do not modify project files.',
126
- imageStudio ? `You can generate images with the MCP tool ${imageStudio.tool} (server ${imageStudio.name}): pass a detailed prompt and a file_name; it saves the PNG${scratch ? ` into ${scratch}` : ' into the lease directory'} and returns the path.`
130
+ imageStudio ? `You can generate images with the MCP tool ${imageStudio.tool} (server ${imageStudio.name}), which draws ${imageStudio.model ? `with ${imageStudio.vendor ? `${imageStudio.vendor} ` : ''}${imageStudio.model}` : 'with the first image key MADRE finds'}, billed to the human's own key: pass a detailed prompt and a file_name; it saves the image${scratch ? ` into ${scratch}` : ' into the lease directory'} and returns the path. If it answers that there is no key, say in one sentence that one is connected in MODULES › Images, and do not try another way.`
131
+ : canImage && agentId === 'grok' ? `You can generate images with your image_gen tool. It saves each image in your own folder, outside this project; when your turn ends MADRE copies every image you generated into ${outDir}/${grokImagesDir({ scratchDir })}. Do not try to copy, convert or move it yourself, and do not write a file in its place: say what you generated and that it will be in ${grokImagesDir({ scratchDir })}/.`
127
132
  : canImage ? `You can generate images; save them${create ? ' where images live in this project, or in the scratch folder,' : ' into the lease directory'} with a descriptive file name.`
128
133
  : couldImage ? 'Image generation is switched off for this request; if asked for an image, say so and do not attempt it.'
129
134
  : 'You cannot generate images from this CLI; if asked for one, say so plainly instead of attempting it.',
package/src/looks.mjs CHANGED
@@ -8,7 +8,7 @@
8
8
  // so a page paints in the last known look before it hears from here.
9
9
  //
10
10
  // Only what the pages share: the theme, the accent, the wallpaper and its dials, the bubbles and
11
- // the text of the conversation. How Home is arranged lives beside it, in home.json (below).
11
+ // the text of the conversation, and how code reads (the terminal and the editor). How Home is arranged lives beside it, in home.json (below).
12
12
 
13
13
  import { createHash } from 'node:crypto';
14
14
  import { readFile, rm } from 'node:fs/promises';
@@ -28,6 +28,9 @@ export const LOOK_KEYS = {
28
28
  'pulse.text': CHOICE,
29
29
  // The maps drawn as neurons (public/neural.js): 'on', or nothing.
30
30
  'pulse.neural': CHOICE,
31
+ // How code reads in the editor, the viewer and the app's terminal (2026-11-14): 'coldbrew',
32
+ // 'oldcode', or nothing for Simple.
33
+ 'pulse.code.theme': CHOICE,
31
34
  };
32
35
  const looksFile = (stateRoot) => join(stateRoot, 'looks.json');
33
36
 
@@ -122,7 +122,7 @@ export function submissionMarkdown(result, entry = {}) {
122
122
  lines.push(result.reaches.length ? result.reaches.map((one) => `- ${one.words}`).join('\n') : `- ${t('Nothing beyond what MADRE hands every module.')}`);
123
123
  for (const one of result.undeclared) lines.push(`- ⚠️ ${one}`);
124
124
  if (result.module?.unknown?.length) lines.push(`- ⚠️ ${t('Fields MADRE does not know: {list}', { list: result.module.unknown.join(', ') })}`);
125
- lines.push('', `_${t('Checked by MADRE (src/market-check.mjs). A person still reads the code before it is signed: a module runs with the permissions of whoever opens MADRE.')}_`);
125
+ lines.push('', `_${t('Checked by MADRE (src/market-check.mjs). A person still reads the code before it is signed: an installed module runs in a separate process, but Node cannot guarantee containment of malicious code.')}_`);
126
126
  return lines.join('\n');
127
127
  }
128
128
 
@@ -26,6 +26,7 @@ import { join } from 'node:path';
26
26
  import { t } from './i18n.mjs';
27
27
  import { MARKET_PUBLIC_KEY } from './market-key.mjs';
28
28
  import { mayInstall } from './market-license.mjs';
29
+ import { MARKET_MAX_FILES as MAX_SKILL_FILES, SKILL_FILES, installSkill, declaredBy as skillDeclares, readSkillText, removeSkill, runnable, safePath } from './skills.mjs';
29
30
 
30
31
  export const MARKET_URL = 'https://madre.run/mercado/catalogo.json';
31
32
  const MAX_CATALOG = 1024 * 1024;
@@ -147,10 +148,42 @@ export function readCatalog(text, { url = MARKET_URL } = {}) {
147
148
  if (!href || !SHA.test(raw.file?.sha256 ?? '') || typeof raw.file?.factory !== 'string' || raw.file.factory.length > MAX_SIGNATURE) continue;
148
149
  builtins.push({ id: raw.id, version: raw.version, sdk: raw.sdk, changes: words(raw.changes, 400), file: { url: href, sha256: raw.file.sha256, size: Number(raw.file.size) || null, factory: raw.file.factory.trim() } });
149
150
  }
151
+ // SKILLS (2026-11-08, H-4): ways of working, not code. A list of their own, like `builtins`, so a
152
+ // MADRE that does not know them (1.1.2 and before) never sees one as a module to install. Each
153
+ // file is pinned by its own sha256 — there is no archive to unpack, so there is no path to climb
154
+ // out of and no bomb to unzip — and every path is checked as the installer checks it.
155
+ const skills = [];
156
+ for (const raw of (Array.isArray(data.skills) ? data.skills : []).slice(0, 200)) {
157
+ if (!ID.test(raw?.id ?? '') || typeof raw.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(raw.version)) continue;
158
+ const files = [];
159
+ let weight = 0;
160
+ for (const file of (Array.isArray(raw.files) ? raw.files : []).slice(0, MAX_SKILL_FILES)) {
161
+ const href = fileUrl(file?.url, url);
162
+ if (!href || !safePath(file?.path) || !SHA.test(file?.sha256 ?? '')) { files.length = 0; break; }
163
+ weight += Number(file.size) || 0;
164
+ files.push({ path: String(file.path), url: href, sha256: file.sha256, size: Number(file.size) || null });
165
+ }
166
+ // Its own page is what makes it a skill; without it there is nothing to read and nothing to run.
167
+ if (!files.length || !files.some((file) => SKILL_FILES.includes(file.path)) || weight > MAX_MODULE) continue;
168
+ skills.push({
169
+ id: raw.id, version: raw.version, files,
170
+ shelf: ID.test(raw.shelf ?? '') ? raw.shelf : null,
171
+ name: words(raw.name, 60), line: words(raw.line, 140), summary: words(raw.summary, 1200),
172
+ changes: words(raw.changes, 400), credit: words(raw.credit, 60),
173
+ minMadre: typeof raw.minMadre === 'string' && /^\d+\.\d+\.\d+$/.test(raw.minMadre) ? raw.minMadre : null,
174
+ hue: Array.isArray(raw.hue) && raw.hue.length === 2 && raw.hue.every((one) => COLOR.test(one)) ? raw.hue : null,
175
+ icon: typeof raw.icon === 'string' && raw.icon.length <= 8000 ? raw.icon : null,
176
+ community: raw.community === true,
177
+ author: raw.author && typeof raw.author === 'object' && typeof raw.author.name === 'string' && raw.author.name.trim()
178
+ ? { name: raw.author.name.trim().slice(0, 60), github: /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(raw.author.github ?? '') ? raw.author.github : null }
179
+ : null,
180
+ spdx: typeof raw.spdx === 'string' && /^[A-Za-z0-9.+-]{2,40}$/.test(raw.spdx) ? raw.spdx : null,
181
+ });
182
+ }
150
183
  // TAKEN BACK: a module, or one version of it, that must not run anywhere any more. A module got
151
184
  // from the Market is removed; a newer file of one of MADRE's own goes back to the one MADRE came with.
152
185
  const revoked = (Array.isArray(data.revoked) ? data.revoked : []).filter((one) => ID.test(one?.id ?? '')).map((one) => ({ id: one.id, version: typeof one.version === 'string' && /^\d+\.\d+\.\d+$/.test(one.version) ? one.version : null, why: words(one.why, 240) })).slice(0, 100);
153
- return { schema: 1, issued: new Date(issued).toISOString(), shelves, featured, modules, news, builtins, revoked };
186
+ return { schema: 1, issued: new Date(issued).toISOString(), shelves, featured, modules, news, builtins, skills, revoked };
154
187
  }
155
188
 
156
189
  export async function bytesFrom(url, { fetchImpl, max }) {
@@ -328,3 +361,104 @@ export async function updateFromMarket({ stateRoot, projectRoot, catalog, madre,
328
361
  }
329
362
  return updated;
330
363
  }
364
+
365
+ // ---- SKILLS FROM THE MARKET (2026-11-08, H-4). The same chain of trust a module travels on: the
366
+ // catalog is signed with the author's key, each file is pinned by its own sha256, and a version the
367
+ // person never accepted is not installed on its own. What is different is what arrives — words, not
368
+ // code — and that it arrives as several files instead of one, so what the person accepts is a seal
369
+ // over all of them together.
370
+ const SKILL_SEAL = (files) => sha256(Buffer.from([...files].map((file) => `${file.path}\0${file.sha256}`).sort().join('\n')));
371
+ export const installedSkills = async (stateRoot) => (await readJson(join(folder(stateRoot), 'skills.json'))) ?? {};
372
+
373
+ // One skill from the catalog onto this computer, for every project (each one says when it comes in).
374
+ // Two steps, as a module's are: asked with `review`, every file is fetched and checked and what it
375
+ // says comes back with its seal, and nothing is written; installed only when the person accepted
376
+ // that very seal, so what is installed is what was read.
377
+ export async function installSkillFromMarket({ stateRoot, projectRoot, id, catalog, madre, fetchImpl = globalThis.fetch, review = false, accept = null, accepted = false }) {
378
+ const entry = catalog?.skills?.find((one) => one.id === id);
379
+ if (!entry) throw new Error(t('The Market has no skill «{id}» to install.', { id }));
380
+ if (!fitsVersion(madre, entry.minMadre)) throw new Error(t('This skill needs MADRE {version} or newer.', { version: entry.minMadre }));
381
+ const files = [];
382
+ for (const file of entry.files) {
383
+ const bytes = await bytesFrom(file.url, { fetchImpl, max: MAX_MODULE });
384
+ if (sha256(bytes) !== file.sha256) throw new Error(t('A file of this skill is not the one the Market signed, so MADRE did not install it.'));
385
+ files.push({ path: file.path, text: bytes });
386
+ }
387
+ const main = files.find((file) => SKILL_FILES.includes(file.path));
388
+ const read = readSkillText(main.text.toString('utf8'), { id });
389
+ if (read.id !== id) throw new Error(t('The file says it is «{found}», not «{id}», so MADRE did not install it.', { found: read.id, id }));
390
+ if (read.version !== entry.version) throw new Error(t('The skill says {found} and the Market said {said}, so MADRE did not install it.', { found: read.version ?? '—', said: entry.version }));
391
+ const shape = files.map((file) => ({ path: file.path, bytes: file.text.length, runs: runnable(file.path) }));
392
+ const declares = skillDeclares({ ...read, files: shape, scripts: shape.filter((file) => file.runs).map((file) => file.path) });
393
+ const seal = SKILL_SEAL(entry.files);
394
+ if (review) return { review: true, id, name: read.name, version: entry.version, seal, declares, body: read.body, files: shape };
395
+ if (!accepted && accept !== seal) throw Object.assign(new Error(t('Read what {name} tells your agents before installing it.', { name: read.name ?? id })), { code: 'REVIEW_FIRST' });
396
+ const done = await installSkill({ files, scope: 'user', stateRoot, projectRoot, source: { kind: 'market', from: entry.files.find((file) => SKILL_FILES.includes(file.path))?.url ?? null, id } });
397
+ const kept = await installedSkills(stateRoot);
398
+ // The programs by name, not by how many: what the person accepted is these files, and a version
399
+ // that swaps one for another is asking for something new even when the count has not moved.
400
+ kept[id] = { version: entry.version, seal, scripts: declares.scripts, at: new Date().toISOString() };
401
+ await writeAtomic(join(folder(stateRoot), 'skills.json'), JSON.stringify(kept, null, 2));
402
+ return { ...done, version: entry.version, declares };
403
+ }
404
+
405
+ // A skill removed by hand is no longer the Market's to update.
406
+ export async function forgetSkillFromMarket(stateRoot, id) {
407
+ const kept = await installedSkills(stateRoot);
408
+ if (!kept[id]) return false;
409
+ delete kept[id];
410
+ await writeAtomic(join(folder(stateRoot), 'skills.json'), JSON.stringify(kept, null, 2));
411
+ return true;
412
+ }
413
+
414
+ // What a newer version asks for that the one the person accepted did not. For a skill there is one
415
+ // thing that matters: PROGRAMS. Its words can be read and changed freely between versions, and the
416
+ // mode of the turn still rules them; a file an agent could run at #4 is the one thing accepting
417
+ // version 1.0.0 never agreed to. One that brings a program, or more of them, waits for the person.
418
+ export function widensSkill(before = {}, after = {}) {
419
+ const had = new Set(before?.scripts ?? []);
420
+ return (after?.scripts ?? []).filter((path) => !had.has(path)).map((path) => ({ what: 'script', name: path }));
421
+ }
422
+
423
+ // Every skill got from the Market whose signed files changed: the new one, installed, and a line for
424
+ // the person. Taken back first. One that would bring a program the person never accepted is not
425
+ // installed on its own: it waits, and they are told once what it wants.
426
+ export async function updateSkillsFromMarket({ stateRoot, projectRoot, catalog, madre, fetchImpl = globalThis.fetch }) {
427
+ const kept = await installedSkills(stateRoot);
428
+ const updated = [];
429
+ const removed = [];
430
+ const held = [];
431
+ for (const [id, have] of Object.entries({ ...kept })) {
432
+ const taken = (catalog?.revoked ?? []).find((one) => one.id === id && (!one.version || one.version === have.version));
433
+ if (!taken) continue;
434
+ await removeSkill({ id, stateRoot, projectRoot }).catch(() => null);
435
+ await forgetSkillFromMarket(stateRoot, id);
436
+ delete kept[id];
437
+ removed.push({ id, name: catalog?.skills?.find((one) => one.id === id)?.name ?? id, kind: 'removed', version: have.version ?? null, why: taken.why ?? null, at: new Date().toISOString() });
438
+ }
439
+ for (const [id, have] of Object.entries(kept)) {
440
+ const entry = catalog?.skills?.find((one) => one.id === id);
441
+ if (!entry || SKILL_SEAL(entry.files) === have.seal || !fitsVersion(madre, entry.minMadre)) continue;
442
+ try {
443
+ const seal = SKILL_SEAL(entry.files);
444
+ if (have.held === seal) continue;
445
+ const fresh = await installSkillFromMarket({ stateRoot, projectRoot, id, catalog, madre, fetchImpl, review: true });
446
+ const more = widensSkill({ scripts: Array.isArray(have.scripts) ? have.scripts : [] }, fresh.declares);
447
+ if (more.length) {
448
+ const now = await installedSkills(stateRoot);
449
+ now[id] = { ...(now[id] ?? have), held: seal };
450
+ await writeAtomic(join(folder(stateRoot), 'skills.json'), JSON.stringify(now, null, 2));
451
+ held.push({ id, name: fresh.name ?? id, kind: 'held', from: have.version ?? null, to: entry.version, more, at: new Date().toISOString() });
452
+ continue;
453
+ }
454
+ await installSkillFromMarket({ stateRoot, projectRoot, id, catalog, madre, fetchImpl, accepted: true });
455
+ updated.push({ id, name: fresh.name ?? id, from: have.version ?? null, to: entry.version, changes: entry.changes ?? null, at: new Date().toISOString() });
456
+ } catch { /* tried again the next time MADRE opens */ }
457
+ }
458
+ const told = [...updated, ...removed, ...held];
459
+ if (told.length) {
460
+ const news = [...(await marketNews(stateRoot)).filter((one) => !told.some((fresh) => fresh.id === one.id)), ...told];
461
+ await writeAtomic(join(folder(stateRoot), 'updates.json'), JSON.stringify(news, null, 2));
462
+ }
463
+ return { updated, removed, held };
464
+ }