@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
@@ -0,0 +1,281 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // Who draws for Images (2026-11-14): the providers whose image models MADRE's image tool can use,
4
+ // where the person's own key for each is found, and how one image is asked of each.
5
+ //
6
+ // The models were read from each provider's own documentation on 2026-11-14:
7
+ // · Google aistudio.google.com/docs/models and /docs/image-generation (the Nano Banana family;
8
+ // gemini-2.5-flash-image is retired by Google on 2027-03-15). generateContent «remains
9
+ // fully supported» (ai.google.dev/gemini-api/docs/migrate-to-interactions), and it is
10
+ // what Images has always called.
11
+ // · OpenAI developers.openai.com/api/docs/models and /guides/image-generation: POST
12
+ // /v1/images/generations, the image in data[0].b64_json. gpt-image-1 was shut down on
13
+ // 2026-10-23, so none of the first ones is offered.
14
+ // · xAI docs.x.ai/docs/models and the images reference: POST /v1/images/generations with
15
+ // response_format b64_json, the image in data[0].b64_json and its type in mime_type.
16
+ // Ollama drew images for a while on the Mac only, and its own runner stopped (ollama/ollama#17893,
17
+ // still refused in 0.40.15, #19615): it is not offered until it draws again.
18
+ //
19
+ // A key is never handed to anyone here but the provider it belongs to. Where it was found is said
20
+ // (`from`), never what it is. Every place read is one a CLI of the person's own already keeps it
21
+ // in, or MADRE's vault, where a key pasted in MODULES › Images is kept (src/vault.mjs).
22
+
23
+ import { execFile } from 'node:child_process';
24
+ import { readFile } from 'node:fs/promises';
25
+ import { homedir } from 'node:os';
26
+ import { join } from 'node:path';
27
+ import { promisify } from 'node:util';
28
+ import { readSecret } from '../vault.mjs';
29
+
30
+ const execFileAsync = promisify(execFile);
31
+ export const IMAGE_MODULE_ID = 'image-studio';
32
+
33
+ // What each one is, for a person choosing. `hint` is a few words on when to pick that model.
34
+ export const IMAGE_PROVIDERS = [
35
+ {
36
+ id: 'gemini', name: 'Gemini', vendor: 'Google', variable: 'GEMINI_API_KEY',
37
+ keyUrl: 'https://aistudio.google.com/app/apikey',
38
+ // The first is the one that draws until the person chooses: the one Images has always called through
39
+ // generateContent. Google documents the newer ones only through its Interactions API (checked
40
+ // 2026-11-14), so they are offered but not made the default until one draws here with a real key.
41
+ models: [
42
+ { id: 'gemini-2.5-flash-image', label: 'Nano Banana', hint: 'the one MADRE has always used; Google retires it on March 15, 2027' },
43
+ { id: 'gemini-nano-banana-2.1', label: 'Nano Banana 2.1', hint: 'Google\'s newest everyday one' },
44
+ { id: 'gemini-3.1-flash-lite-image', label: 'Nano Banana 2 Lite', hint: 'the fastest and cheapest' },
45
+ { id: 'gemini-3-pro-image', label: 'Nano Banana Pro', hint: 'the most careful, and the most expensive' },
46
+ { id: 'gemini-3.1-flash-image', label: 'Nano Banana 2', hint: 'the one before 2.1' },
47
+ ],
48
+ },
49
+ {
50
+ id: 'openai', name: 'OpenAI', vendor: 'OpenAI', variable: 'OPENAI_API_KEY',
51
+ keyUrl: 'https://platform.openai.com/api-keys',
52
+ models: [
53
+ { id: 'gpt-image-2.6-flare', label: 'GPT Image 2.6 Flare', hint: 'fast, to try ideas' },
54
+ { id: 'gpt-image-2.6-sunburst', label: 'GPT Image 2.6 Sunburst', hint: 'the most detailed' },
55
+ { id: 'gpt-image-2.5-flare', label: 'GPT Image 2.5 Flare', hint: 'the one before, fast' },
56
+ { id: 'gpt-image-2.5-sunburst', label: 'GPT Image 2.5 Sunburst', hint: 'the one before, detailed' },
57
+ ],
58
+ },
59
+ {
60
+ id: 'xai', name: 'Grok', vendor: 'xAI', variable: 'XAI_API_KEY',
61
+ keyUrl: 'https://console.x.ai/team/default/api-keys',
62
+ models: [
63
+ { id: 'grok-imagine-image-2.0', label: 'Grok Imagine 2.0', hint: 'the newest' },
64
+ { id: 'grok-imagine-image', label: 'Grok Imagine', hint: 'the cheapest' },
65
+ ],
66
+ },
67
+ ];
68
+ export const IMAGE_MODELS = IMAGE_PROVIDERS.flatMap((provider) => provider.models.map((model) => model.id));
69
+ export const imageProvider = (id) => IMAGE_PROVIDERS.find((provider) => provider.id === id) ?? null;
70
+ // A model says whose it is by its name. A Gemini model this list no longer names (one saved in an
71
+ // older config) still goes to Google, which answers for it.
72
+ export function providerOf(model) {
73
+ const name = String(model ?? '');
74
+ if (/^gemini-/.test(name)) return 'gemini';
75
+ if (/^gpt-image-/.test(name)) return 'openai';
76
+ if (/^grok-/.test(name)) return 'xai';
77
+ return null;
78
+ }
79
+ export const defaultModel = (providerId) => imageProvider(providerId)?.models[0]?.id ?? null;
80
+
81
+ // ---- Where a key is found.
82
+ //
83
+ // `home` is the person's home (where each CLI keeps its files); `stateRoot` is MADRE's own folder,
84
+ // whose vault holds a key pasted for Images. Each answer is { key, from }: `from` is what a screen
85
+ // may say, the key is what only the request to its own provider may carry.
86
+
87
+ const readIfThere = (path) => readFile(path, 'utf8').catch(() => null);
88
+ const parsed = (text) => { try { const value = JSON.parse(text ?? ''); return value && typeof value === 'object' && !Array.isArray(value) ? value : null; } catch { return null; } };
89
+
90
+ // The file Gemini CLI reads on every run, which is also where MADRE writes a Gemini key pasted in
91
+ // Settings › Your AIs. Left out once, MADRE saved a key in a place Images then refused to look.
92
+ export async function keyFromGeminiEnvFile(env, home = homedir()) {
93
+ const text = await readIfThere(join(env.GEMINI_CLI_HOME ?? home, '.gemini', '.env'));
94
+ if (!text) return null;
95
+ for (const line of text.split('\n')) {
96
+ const match = line.match(/^\s*(?:export\s+)?(GEMINI_API_KEY|GOOGLE_API_KEY)\s*=\s*(.*)$/);
97
+ if (!match) continue;
98
+ const value = match[2].trim().replace(/^(['"])(.*)\1$/, '$2').trim();
99
+ if (value) return value;
100
+ }
101
+ return null;
102
+ }
103
+
104
+ // The macOS keychain entry Gemini CLI's own sign-in leaves. It occasionally answers empty under
105
+ // concurrent reads; one retry.
106
+ async function keyFromGeminiKeychain() {
107
+ if (process.platform !== 'darwin') return null;
108
+ for (let attempt = 0; attempt < 2; attempt += 1) {
109
+ try {
110
+ const { stdout } = await execFileAsync('/usr/bin/security', ['find-generic-password', '-s', 'gemini-cli-api-key', '-w'], { timeout: 4000 });
111
+ const raw = stdout.trim();
112
+ if (!raw) continue;
113
+ const json = parsed(raw);
114
+ return json ? (json.token?.accessToken ?? json.token?.apiKey ?? json.apiKey ?? null) : raw;
115
+ } catch {
116
+ if (attempt === 1) return null;
117
+ }
118
+ }
119
+ return null;
120
+ }
121
+
122
+ // A provider's key in OpenCode's own auth.json (src/credentials.mjs writes the same shape): only a
123
+ // key (`api`), never an account signed in with OpenCode's login.
124
+ async function keyFromOpenCode(provider, env, home) {
125
+ const auth = parsed(await readIfThere(join(env.XDG_DATA_HOME || join(home, '.local', 'share'), 'opencode', 'auth.json')));
126
+ const entry = auth?.[provider];
127
+ return entry?.type === 'api' && typeof entry.key === 'string' && entry.key.trim() ? entry.key.trim() : null;
128
+ }
129
+
130
+ // The key Codex signed in with, when it signed in with one ($CODEX_HOME/auth.json, OPENAI_API_KEY;
131
+ // the field is empty when Codex signed in with a ChatGPT account, whose sign-in draws nothing here).
132
+ async function keyFromCodex(env, home) {
133
+ const auth = parsed(await readIfThere(join(env.CODEX_HOME || join(home, '.codex'), 'auth.json')));
134
+ const key = auth?.OPENAI_API_KEY;
135
+ return typeof key === 'string' && key.trim() ? key.trim() : null;
136
+ }
137
+
138
+ const fromVault = async (stateRoot, provider) => (stateRoot ? readSecret(stateRoot, IMAGE_MODULE_ID, provider) : null);
139
+ const found = (key, from) => (key ? { key, from } : null);
140
+
141
+ // Where each provider's key is looked for, in the order it is trusted: what was pasted in MODULES ›
142
+ // Images first (it was pasted for this), then what this process was given, then the CLIs' own files.
143
+ // Gemini keeps the order it has always had, and adds OpenCode's Google key last.
144
+ async function geminiOwnKey(env, home) {
145
+ if (env.GEMINI_API_KEY) return found(env.GEMINI_API_KEY, 'env');
146
+ if (env.GOOGLE_API_KEY) return found(env.GOOGLE_API_KEY, 'env');
147
+ return found(await keyFromGeminiEnvFile(env, home), 'gemini-cli') ?? found(await keyFromGeminiKeychain(), 'keychain');
148
+ }
149
+ export async function resolveImageKey(providerId, { env = process.env, home = homedir(), stateRoot = null } = {}) {
150
+ if (providerId === 'gemini') return (await geminiOwnKey(env, home)) ?? found(await keyFromOpenCode('google', env, home), 'opencode');
151
+ if (providerId === 'openai') {
152
+ return found(await fromVault(stateRoot, 'openai'), 'madre')
153
+ ?? found(env.OPENAI_API_KEY, 'env')
154
+ ?? found(await keyFromOpenCode('openai', env, home), 'opencode')
155
+ ?? found(await keyFromCodex(env, home), 'codex');
156
+ }
157
+ if (providerId === 'xai') {
158
+ return found(await fromVault(stateRoot, 'xai'), 'madre')
159
+ ?? found(env.XAI_API_KEY, 'env')
160
+ ?? found(await keyFromOpenCode('xai', env, home), 'opencode');
161
+ }
162
+ return null;
163
+ }
164
+
165
+ // Gemini's own key alone, as MADRE has always asked for it. Embeddings and Gemini's model list use
166
+ // it too, so OpenCode's Google key stays out of it: that one only ever draws.
167
+ export async function resolveGeminiKey(env = process.env) {
168
+ return (await geminiOwnKey(env, homedir()))?.key ?? null;
169
+ }
170
+
171
+ // What a screen may know: for each provider, where its key was found, or null. Never a key.
172
+ export async function findImageSources(options = {}) {
173
+ const out = {};
174
+ for (const provider of IMAGE_PROVIDERS) {
175
+ const hit = await resolveImageKey(provider.id, options).catch(() => null);
176
+ out[provider.id] = hit ? { from: hit.from } : null;
177
+ }
178
+ return out;
179
+ }
180
+
181
+ // The model that draws: the one the person chose, or — until they choose — the first provider
182
+ // whose key MADRE finds, with that provider's first model. `auto` says which of the two it was.
183
+ export function pickImageModel(chosen, sources = {}) {
184
+ if (chosen && providerOf(chosen)) return { model: chosen, provider: providerOf(chosen), auto: false };
185
+ const first = IMAGE_PROVIDERS.find((provider) => sources[provider.id]);
186
+ return first ? { model: defaultModel(first.id), provider: first.id, auto: true } : null;
187
+ }
188
+
189
+ // ---- One image, asked of its provider.
190
+
191
+ const errorOf = (code, message, status) => Object.assign(new Error(message), { code, status });
192
+
193
+ // Google's error strings, turned into something a human can act on.
194
+ export function explainGoogleError(status, body) {
195
+ const message = body?.error?.message ?? '';
196
+ if (/prepayment credits are depleted|billing/i.test(message)) return { code: 'CREDITS_DEPLETED', message: 'Google reports the AI Studio project has no prepaid credits left. Top up at https://ai.studio/projects and try again.' };
197
+ if (status === 429) return { code: 'RATE_LIMITED', message: 'Google is rate-limiting this key (HTTP 429). Wait a minute and retry.' };
198
+ if (status === 401 || status === 403) return { code: 'AUTH', message: `Google rejected the Gemini key (HTTP ${status}). Check GEMINI_API_KEY or sign in again with the Gemini CLI.` };
199
+ if (status === 404) return { code: 'MODEL', message: `Image model not available to this key (HTTP 404): ${message}` };
200
+ return { code: 'ERROR', message: message || `Google returned HTTP ${status}.` };
201
+ }
202
+
203
+ // OpenAI's and xAI's, which answer in the same shape.
204
+ export function explainProviderError(providerId, status, body) {
205
+ if (providerId === 'gemini') return explainGoogleError(status, body);
206
+ const vendor = imageProvider(providerId)?.vendor ?? providerId;
207
+ const message = String(body?.error?.message ?? (typeof body?.error === 'string' ? body.error : '') ?? '');
208
+ const code = String(body?.error?.code ?? body?.code ?? '');
209
+ const topUp = providerId === 'openai' ? 'https://platform.openai.com/account/billing/overview' : 'https://console.x.ai';
210
+ if (/insufficient_quota|billing|credit|balance|spending limit/i.test(`${code} ${message}`)) return { code: 'CREDITS_DEPLETED', message: `${vendor} reports the account has no credit left for images. Add credit at ${topUp} and try again.` };
211
+ if (status === 429) return { code: 'RATE_LIMITED', message: `${vendor} is rate-limiting this key (HTTP 429). Wait a minute and retry.` };
212
+ if (status === 401) return { code: 'AUTH', message: `${vendor} rejected the key (HTTP 401). Paste a new one in MODULES › Images.` };
213
+ if (status === 403) return { code: 'AUTH', message: `${vendor} did not allow this image model for this key (HTTP 403)${message ? `: ${message}` : '.'}` };
214
+ if (status === 404) return { code: 'MODEL', message: `Image model not available to this key (HTTP 404)${message ? `: ${message}` : '.'}` };
215
+ return { code: 'ERROR', message: message || `${vendor} returned HTTP ${status}.` };
216
+ }
217
+
218
+ // Each provider's request and where its answer keeps the image.
219
+ const REQUESTS = {
220
+ gemini: ({ model, prompt, key }) => ({
221
+ url: `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent`,
222
+ init: { method: 'POST', headers: { 'content-type': 'application/json', 'x-goog-api-key': key }, body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }], generationConfig: { responseModalities: ['IMAGE'] } }) },
223
+ read: (body) => {
224
+ const part = body.candidates?.[0]?.content?.parts?.find((item) => item.inlineData?.data);
225
+ return part ? { data: part.inlineData.data, mimeType: part.inlineData.mimeType ?? 'image/png' } : { empty: body.candidates?.[0]?.finishReason ?? null };
226
+ },
227
+ }),
228
+ openai: ({ model, prompt, key }) => ({
229
+ url: 'https://api.openai.com/v1/images/generations',
230
+ init: { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` }, body: JSON.stringify({ model, prompt, n: 1 }) },
231
+ read: (body) => {
232
+ const data = body.data?.[0]?.b64_json;
233
+ const format = String(body.output_format ?? 'png').toLowerCase();
234
+ return data ? { data, mimeType: format === 'jpeg' || format === 'jpg' ? 'image/jpeg' : format === 'webp' ? 'image/webp' : 'image/png' } : { empty: null };
235
+ },
236
+ }),
237
+ xai: ({ model, prompt, key }) => ({
238
+ url: 'https://api.x.ai/v1/images/generations',
239
+ init: { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` }, body: JSON.stringify({ model, prompt, n: 1, response_format: 'b64_json' }) },
240
+ read: (body) => {
241
+ const one = body.data?.[0];
242
+ return one?.b64_json ? { data: one.b64_json, mimeType: one.mime_type ?? 'image/jpeg' } : { empty: null };
243
+ },
244
+ }),
245
+ };
246
+
247
+ // Draws one image with a model and a key, and hands back its bytes. Nothing is written here.
248
+ export async function drawImage({ model, prompt, key, fetchImpl = fetch, timeoutMs = 180000 }) {
249
+ const providerId = providerOf(model);
250
+ if (!providerId) throw errorOf('MODEL', `MADRE does not know which provider draws ${model}.`);
251
+ const { url, init, read } = REQUESTS[providerId]({ model, prompt, key });
252
+ const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
253
+ const body = await response.json().catch(() => ({}));
254
+ if (!response.ok) {
255
+ const explained = explainProviderError(providerId, response.status, body);
256
+ throw errorOf(explained.code, explained.message, response.status);
257
+ }
258
+ const image = read(body ?? {});
259
+ if (!image.data) throw Object.assign(errorOf('EMPTY', `${imageProvider(providerId).vendor} returned no image data.`), { detail: image.empty ?? null });
260
+ return { bytes: Buffer.from(image.data, 'base64'), mimeType: image.mimeType, provider: providerId };
261
+ }
262
+
263
+ // Whether OpenAI or xAI takes a key pasted in MODULES › Images: listing the models spends nothing.
264
+ // `ok: null` when the provider said nothing about the key (offline, its own trouble): that is not
265
+ // the key's fault, and the key is kept.
266
+ // The address can be moved (PULSE_OPENAI_API_URL, PULSE_XAI_API_URL) so the test suite never asks.
267
+ const MODEL_LISTS = {
268
+ openai: () => `${(process.env.PULSE_OPENAI_API_URL ?? 'https://api.openai.com').replace(/\/$/, '')}/v1/models`,
269
+ xai: () => `${(process.env.PULSE_XAI_API_URL ?? 'https://api.x.ai').replace(/\/$/, '')}/v1/models`,
270
+ };
271
+ export async function providerTakesKey(providerId, key, { fetchImpl = globalThis.fetch, timeoutMs = 8000 } = {}) {
272
+ const url = MODEL_LISTS[providerId]?.();
273
+ if (!url) return { ok: null, status: null };
274
+ try {
275
+ const answer = await fetchImpl(url, { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(timeoutMs) });
276
+ if (answer.ok) return { ok: true };
277
+ return { ok: answer.status === 401 || answer.status === 403 ? false : null, status: answer.status };
278
+ } catch {
279
+ return { ok: null, status: null };
280
+ }
281
+ }
@@ -1,42 +1,123 @@
1
1
  // SPDX-License-Identifier: BUSL-1.1
2
2
  // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
- // Image Studio: MADRE's own MCP image server on the Gemini image models, for
4
- // the CLIs that cannot draw natively. Always on, as Options and Commands are (2026-11-06, the author):
5
- // it attaches only inside a permission to create with images, granted turn by turn, so being on spends
6
- // nothing by itself. The model is in config.json.
3
+ // Image Studio: MADRE's own MCP image server, for the CLIs that cannot draw natively. Always on,
4
+ // as Options and Commands are (2026-11-06, the author): it attaches only inside a permission to
5
+ // create with images, granted turn by turn, so being on spends nothing by itself.
6
+ //
7
+ // Who draws (2026-11-14, the author: «facilitarle al usuario la creación de imágenes con sus
8
+ // agentes»): Google's Gemini, OpenAI's GPT Image or xAI's Grok Imagine, on the person's own key
9
+ // (src/modules/image-providers.mjs). What the person already has is found without asking — the key
10
+ // Gemini CLI keeps, the ones OpenCode and Codex signed in with — and what they do not have is
11
+ // offered with where to get it and a field to paste it. The model chosen is in config.json; until
12
+ // one is chosen, the first provider whose key is found draws.
7
13
 
8
14
  import { defineModule } from './sdk.mjs';
9
15
  import { t } from '../i18n.mjs';
16
+ import { normalizeKey } from '../credentials.mjs';
17
+ import { IMAGE_MODELS, IMAGE_PROVIDERS, defaultModel, imageProvider, pickImageModel, providerOf, providerTakesKey } from './image-providers.mjs';
10
18
 
11
- const MODELS = ['gemini-2.5-flash-image', 'gemini-3.1-flash-image', 'gemini-3-pro-image'];
19
+ // The IAs that draw with their own account and never use this module (src/capabilities.mjs).
20
+ const DRAW_ON_THEIR_OWN = ['codex', 'grok'];
21
+ const LOCAL = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);
22
+ const fromHere = (request, viaPhone) => !viaPhone && LOCAL.has(request?.socket?.remoteAddress ?? '');
23
+
24
+ // Where the keys are, as a screen may know it: by the room's own lookup, or — in a context that
25
+ // offers only Gemini's (a test, an older caller) — Gemini's alone.
26
+ async function sourcesOf(ctx) {
27
+ if (ctx.services?.imageSources) return ctx.services.imageSources();
28
+ const key = await ctx.services?.imageKey?.().catch(() => null);
29
+ return { gemini: key ? { from: 'gemini' } : null, openai: null, xai: null };
30
+ }
31
+ // The room's running copy has to hear about a new model at once, not only the file.
32
+ const tellRoom = (ctx, model) => ctx.services?.setImageModule?.({ enabled: true, model: model ?? null, stateRoot: ctx.stateRoot ?? null, home: ctx.services?.imageHome ?? null });
33
+ const keepModel = async (ctx, model) => {
34
+ await ctx.updateConfig({ modules: { imageStudio: { ...(ctx.config?.modules?.imageStudio ?? {}), model } } });
35
+ tellRoom(ctx, model);
36
+ };
12
37
 
13
38
  export default defineModule({
14
39
  id: 'image-studio',
15
40
  configKey: 'imageStudio',
16
41
  name: 'Images',
17
- vendor: 'MADRE · Gemini API',
18
- version: '1.0.0',
19
- summary: 'Gives Gemini CLI, Claude Code and OpenCode an image tool, through a MADRE-owned MCP server on the Gemini image models and your own key and credits.',
20
- creates: ['nothing in the project \u00b7 images land in the lease folder', 'the model in ~/.pulse/config.json', 'an MCP server per turn, started and stopped by the project'],
42
+ vendor: 'MADRE · Gemini, OpenAI, xAI',
43
+ version: '1.1.0',
44
+ summary: 'Gives Claude Code, Gemini CLI and OpenCode an image tool, through a MADRE-owned MCP server on the image model you choose (Gemini, OpenAI or Grok) and your own key and credits.',
45
+ creates: ['nothing in the project · images land in the lease folder', 'the model in ~/.pulse/config.json', 'an MCP server per turn, started and stopped by the project', 'a key you paste here, in MADRE\'s vault, readable only by you'],
21
46
  // Not something it writes: a condition for it to attach at all, which is what REQUIRES is for.
22
- requires: ['a Gemini API key with credits (the one the Gemini CLI stores, or GEMINI_API_KEY)', 'attached only inside a permission to create with images on'],
23
- models: MODELS,
24
- settings: { enabled: true, model: MODELS[0] },
47
+ requires: ['a key with credit for Gemini, OpenAI or Grok: one your AIs already use, or one you paste here', 'attached only inside a permission to create with images on'],
48
+ models: IMAGE_MODELS,
49
+ // No model until the person picks one: the first provider whose key is found draws.
50
+ settings: { enabled: true, model: null },
25
51
  card: 'fixed',
26
- controls: [{ key: 'model', label: 'MODEL', type: 'select', options: MODELS, note: 'The Gemini image model Image Studio draws with. It bills against your own key.' }],
52
+ controls: [{
53
+ key: 'model', label: 'MODEL', type: 'select', options: IMAGE_MODELS,
54
+ choices: IMAGE_PROVIDERS.flatMap((provider) => provider.models.map((model) => ({ value: model.id, label: `${provider.vendor} · ${model.label}` }))),
55
+ note: 'The image model Images draws with. It bills against your own key.',
56
+ }],
27
57
  // Changing the model has to reach the running room, not just the file.
28
- async onSettings(ctx, settings) { ctx.services.setImageModule({ enabled: true, model: settings.model }); },
58
+ async onSettings(ctx, settings) { tellRoom(ctx, settings.model); },
29
59
  async status(ctx) {
30
- const key = await ctx.services.imageKey();
31
- const model = ctx.settings.model ?? MODELS[0];
60
+ const sources = await sourcesOf(ctx);
61
+ const pick = pickImageModel(ctx.settings.model ?? null, sources);
62
+ const ready = Boolean(pick && sources[pick.provider]);
63
+ const vendor = imageProvider(pick?.provider)?.vendor ?? '';
32
64
  return {
33
- model,
65
+ model: pick?.model ?? null,
66
+ // «With what it draws», for the module's page: every provider, whether its key is here and
67
+ // where it was found — never the key — and its models.
68
+ drawing: {
69
+ chosen: ctx.settings.model ?? null,
70
+ model: pick?.model ?? null,
71
+ provider: pick?.provider ?? null,
72
+ auto: Boolean(pick?.auto),
73
+ native: DRAW_ON_THEIR_OWN,
74
+ providers: IMAGE_PROVIDERS.map((provider) => ({
75
+ id: provider.id, name: provider.name, vendor: provider.vendor, keyUrl: provider.keyUrl, variable: provider.variable,
76
+ ready: Boolean(sources[provider.id]),
77
+ from: sources[provider.id]?.from ?? null,
78
+ models: provider.models.map((model) => ({ id: model.id, label: model.label, hint: model.hint })),
79
+ })),
80
+ },
34
81
  // Without a key it is on all the same; it says so, since an image asked for would fail.
35
- status: { installed: true, detail: `${t('on')} · ${model}${key ? '' : t(' · no Gemini key found')}` },
36
- preflight: key ? { ok: true, problems: [] } : { ok: false, problems: ['No Gemini API key: sign in with the Gemini CLI (/auth → API key) or set GEMINI_API_KEY. Image models bill against that key.'] },
82
+ status: { installed: true, detail: !pick ? `${t('on')}${t(' · no image key found')}` : `${t('on')} · ${pick.model}${ready ? '' : t(' · no {vendor} key found', { vendor })}` },
83
+ preflight: ready ? { ok: true, problems: [] } : { ok: false, problems: ['No image key yet: connect Gemini, OpenAI or Grok in Modules › Images. Each image is billed to that key.'] },
37
84
  install: { display: 'always on', platforms: ['gemini', 'claude', 'opencode'] },
38
85
  fixed: true,
39
86
  };
40
87
  },
41
88
  async toggle() { return { status: 405, body: { error: 'Images has no switch: it is always on.' } }; },
89
+ routes: [
90
+ // An OpenAI or xAI key pasted in MODULES › Images. Taken only from this computer, as every key is;
91
+ // asked of its provider first (listing the models spends nothing), then kept in MADRE's vault under
92
+ // this module's name, `0600`. The ledger keeps that a key was kept and how long it is, never the key.
93
+ // A Gemini key is not kept here: it goes where Gemini CLI reads it (Settings › Your AIs, the same call).
94
+ { method: 'POST', path: '/api/image-studio/key', handler: async (ctx, { request, payload = {}, viaPhone } = {}) => {
95
+ if (!fromHere(request, viaPhone)) return { status: 403, body: { error: t('A key is only accepted from this computer, never over the network.') } };
96
+ const provider = imageProvider(payload.provider);
97
+ if (!provider || provider.id === 'gemini') return { status: 400, body: { error: t('Here a key is kept for OpenAI or Grok. A Gemini key is kept where Gemini CLI reads it.') } };
98
+ const checked = normalizeKey(payload.key);
99
+ if (!checked.ok) return { status: 400, body: { error: checked.error } };
100
+ const taken = await (ctx.services?.verifyImageKey ?? providerTakesKey)(provider.id, checked.key);
101
+ if (taken.ok === false) return { status: 422, body: { error: t('{vendor} did not accept this key (HTTP {status}): check you copied all of it, or make a new one. Nothing was kept.', { vendor: provider.vendor, status: taken.status }) } };
102
+ const kept = await ctx.vault.keep(provider.id, checked.key);
103
+ if (!kept.ok) return { status: 400, body: { error: kept.error } };
104
+ await ctx.record('module.secret.kept', { module: 'image-studio', name: provider.id, bytes: kept.bytes });
105
+ // What was just connected is what draws from now on; the page lets the person change it.
106
+ const model = defaultModel(provider.id);
107
+ await keepModel(ctx, model);
108
+ return { status: 200, body: { ok: true, model, checked: taken.ok === true } };
109
+ } },
110
+ // Forgets a key MADRE kept for Images. The ones a CLI keeps are that CLI's: they are signed out there.
111
+ { method: 'POST', path: '/api/image-studio/key/forget', handler: async (ctx, { request, payload = {}, viaPhone } = {}) => {
112
+ if (!fromHere(request, viaPhone)) return { status: 403, body: { error: t('A key is only accepted from this computer, never over the network.') } };
113
+ const provider = imageProvider(payload.provider);
114
+ if (!provider || provider.id === 'gemini') return { status: 400, body: { error: t('Here a key is kept for OpenAI or Grok. A Gemini key is kept where Gemini CLI reads it.') } };
115
+ const gone = await ctx.vault.forget(provider.id);
116
+ if (!gone.ok) return { status: 400, body: { error: gone.error } };
117
+ await ctx.record('module.secret.forgotten', { module: 'image-studio', name: gone.forgot });
118
+ // A model of the provider whose key went is no longer a choice that can draw: back to the first found.
119
+ if (providerOf(ctx.settings.model) === provider.id) await keepModel(ctx, null);
120
+ return { status: 200, body: { ok: true } };
121
+ } },
122
+ ],
42
123
  });
@@ -74,7 +74,9 @@ function checkExternal(module, { replace = false } = {}) {
74
74
  // replaced, because that is what installing a newer copy of it is.
75
75
  if (taken && (!replace || !taken.external)) throw new Error(`the id "${module.id}" is already taken`);
76
76
  for (const route of module.routes ?? []) {
77
- const path = typeof route.path === 'string' ? route.path : route.path?.source ?? '';
77
+ // A pattern may start with «^», as MADRE's own do: /^\/api\/x\/<id>\/…$/ was refused, and the
78
+ // person who wrote it was told to live where they already lived (2026-11-09, a report on Facebook).
79
+ const path = typeof route.path === 'string' ? route.path : String(route.path?.source ?? '').replace(/^\^/, '');
78
80
  if (!path.startsWith(`/api/x/${module.id}/`) && !path.startsWith(`\\/api\\/x\\/${module.id}\\/`)) throw new Error(`route ${path} must live under /api/x/${module.id}/`);
79
81
  }
80
82
  return module;
@@ -356,6 +358,10 @@ export async function describeModules(ctx) {
356
358
  // One flat list of every route a module serves, with the module attached.
357
359
  export function findModuleRoute(method, pathname) {
358
360
  for (const module of MODULES) {
361
+ // A module somebody installed answers only under its own /api/x/<id>/, whatever its pattern says:
362
+ // checking how a pattern starts let /\/api\/x\/<id>\/|\/api\/state/ through, and these routes are
363
+ // matched before MADRE's own (2026-11-09).
364
+ if (module.external && !String(pathname).startsWith(`/api/x/${module.id}/`)) continue;
359
365
  const hit = matchRoute(module.routes, method, pathname);
360
366
  if (hit) return { module, ...hit };
361
367
  }
@@ -40,7 +40,9 @@ const POSITIVE = new Set(['good', 'preference']);
40
40
  // A crash of the CLI is one of them too: it ended the turn before anything was answered.
41
41
  const NOT_THE_ANSWER = /rate.?limit|usage limit|quota|\b429\b|too many requests|overloaded|unavailable|HTTP 5\d\d|server error|not ready|not enabled|too long \(|does not know the model|is not found for|not supported|not logged in|\blog ?in\b|sign in|authenticat|unauthori[sz]ed|api.?key|ENOENT|ECONN|network|exited with code|shutting down|MADRE stopped while|waiting for the project/i;
42
42
  // Ledgers written before a STOP carried its own flag say so only in words.
43
- const STOPPED_WORDS = /stopped by the human|detenido por el humano|STOPALL/i;
43
+ // In either language the room wrote it: a turn the person stopped is not a turn that failed
44
+ // (2026-11-17: Spanish said «detenido por ti», now «lo detuviste tú», and neither was heard).
45
+ const STOPPED_WORDS = /stopped by the human|detenido por el humano|detenido por ti|detenida por ti|lo detuviste|STOPALL/i;
44
46
 
45
47
  /* ---------- what the reader keeps ---------- */
46
48
 
@@ -183,7 +183,10 @@ export function playwrightHealth({ browser = 'chromium', env = process.env, cwd
183
183
  if (env.PULSE_PLAYWRIGHT_CHECK === '0') return started.result;
184
184
  if (started.browser !== browser) started = { at: 0, result: null, asking: null, browser };
185
185
  if (!started.asking && now - started.at > 10 * 60 * 1000) {
186
- started.asking = check({ browser, env, cwd }).then((result) => { if (started.browser === browser) started = { at: Date.now(), result, asking: null, browser }; return result; }, () => { started.asking = null; return null; });
186
+ // Only this check writes its answer (Q-24): one forgotten, or asked before the person chose
187
+ // another browser and came back, arrives late and must not land over the newer one.
188
+ const asking = check({ browser, env, cwd }).then((result) => { if (started.asking === asking) started = { at: Date.now(), result, asking: null, browser }; return result; }, () => { if (started.asking === asking) started.asking = null; return null; });
189
+ started.asking = asking;
187
190
  }
188
191
  return started.result;
189
192
  }
@@ -213,6 +216,24 @@ export function playwrightServerFor({ port, outputDir, browser = 'chromium', hea
213
216
  };
214
217
  }
215
218
 
219
+ // The download a turn starts when the switch is on and nothing is installed yet (2026-11-14): one at a
220
+ // time per MADRE, never on Windows (there the person installs it), and said to the person when it
221
+ // starts and when it ends, since it takes a few minutes.
222
+ let fetching = null;
223
+ export function fetchWhenAsked(ctx, env, { prepare = preparePlaywright } = {}) {
224
+ if (fetching || process.platform === 'win32') return fetching;
225
+ const browser = ctx.settings.browser ?? 'chromium';
226
+ fetching = (async () => {
227
+ await ctx.record?.('extension.preparing', { id: 'playwright', name: 'PLAYWRIGHT', browser, first: true });
228
+ const check = await prepare({ browser, env, cwd: ctx.projectRoot, stateRoot: ctx.stateRoot });
229
+ forgetPlaywrightHealth(check, browser);
230
+ await playwrightVersion({ env, projectRoot: ctx.projectRoot, fresh: true });
231
+ await ctx.record?.('extension.prepared', { id: 'playwright', name: 'PLAYWRIGHT', browser, ok: Boolean(check.ok), problem: check.ok ? null : String(check.problem ?? '').slice(0, 200) });
232
+ return check;
233
+ })().catch(() => null).finally(() => { fetching = null; });
234
+ return fetching;
235
+ }
236
+
216
237
  async function playwrightReady(ctx) {
217
238
  const browser = ctx.settings.browser ?? 'chromium';
218
239
  let check = await playwrightStarts({ browser, env: await playwrightEnv(ctx), cwd: ctx.projectRoot });
@@ -239,7 +260,10 @@ export default defineModule({
239
260
  summary: 'Hands an agent a headless browser that reaches only this project and the servers you start from COMMANDS, on the turns that ask to look at a page, click through it, read its console or take screenshots.',
240
261
  creates: ['nothing in the project \u00b7 screenshots land in .pulse/out/<turn>/', 'a switch in ~/.pulse/config.json', 'a browser per turn, started and stopped by the CLI', 'no origin but this project is reachable through it'],
241
262
  requires: ['@playwright/mcp and the browser you choose for it (chromium by default) on this machine', 'PREVIEW on, to have pages to open'],
242
- settings: { enabled: false, browser: 'chromium', headless: true },
263
+ // On from the start (2026-11-14, the author: «vienen activas por defecto y el usuario las desactiva si
264
+ // quiere»). What it needs is fetched the first time a turn asks for a browser (toolsForTurn), not
265
+ // when MADRE is installed: someone who never tests a page never downloads one.
266
+ settings: { enabled: true, browser: 'chromium', headless: true },
243
267
  card: 'switch',
244
268
  controls: [
245
269
  { key: 'browser', label: 'BROWSER', type: 'select', options: PLAYWRIGHT_BROWSERS, note: 'Which browser engine the agents drive.' },
@@ -261,7 +285,7 @@ export default defineModule({
261
285
  return {
262
286
  runs: [{ name: PLAYWRIGHT_PACKAGE, version }],
263
287
  settings: { browser: ctx.settings.browser ?? 'chromium', headless: ctx.settings.headless !== false },
264
- status: { installed: Boolean(ctx.settings.enabled), detail: ctx.settings.enabled ? (!version ? t('on · the browser server is not installed') : health?.ok === false ? t('on · the browser does not start: {problem}. Turn it off and on again: MADRE downloads what is missing.', { problem: String(health.problem).replace(/[.\s]+$/, '').slice(0, 160) }) : `${t('on')} · ${ctx.settings.browser}`) : version ? t('off') : process.platform === 'win32' ? t('off · the browser server is not installed') : t('off · turn it on and MADRE installs its browser; it takes a few minutes') },
288
+ status: { installed: Boolean(ctx.settings.enabled), detail: ctx.settings.enabled ? (!version ? (process.platform === 'win32' ? t('on · the browser server is not installed') : t('on · it downloads the first time an AI opens your page')) : health?.ok === false ? t('on · the browser does not start: {problem}. Turn it off and on again: MADRE downloads what is missing.', { problem: String(health.problem).replace(/[.\s]+$/, '').slice(0, 160) }) : `${t('on')} · ${ctx.settings.browser}`) : version ? t('off') : process.platform === 'win32' ? t('off · the browser server is not installed') : t('off · turn it on and MADRE installs its browser; it takes a few minutes') },
265
289
  // Missing is not a reason to refuse the switch: turning it on installs what is missing
266
290
  // (playwrightReady) everywhere but Windows (2026-10-20). Only there does the person install it.
267
291
  preflight: version || process.platform !== 'win32' ? { ok: true, problems: [] } : { ok: false, problems: [t('Install the browser server first: {server}, then its browser: {browser}', { server: 'npm install -g @playwright/mcp', browser: installBrowserLine(ctx.settings.browser) })] },
@@ -285,8 +309,13 @@ export default defineModule({
285
309
  },
286
310
  async toolsForTurn(ctx, turn) {
287
311
  const env = await playwrightEnv(ctx);
288
- if (!(await playwrightVersion({ env, projectRoot: ctx.projectRoot }))) return [];
289
312
  if (turn.mode === 0) return []; // a ghost turn leaves no screenshots and opens no browser
313
+ if (!(await playwrightVersion({ env, projectRoot: ctx.projectRoot }))) {
314
+ // On but not yet on this computer: the first turn that wants a browser starts the download, and
315
+ // this turn goes on without one (the person is told it is on its way).
316
+ if (turn.text === undefined || wantsBrowser(turn.text)) fetchWhenAsked(ctx, env);
317
+ return [];
318
+ }
290
319
  // Only for a turn that asks for what a browser does. Its tool list goes into every call the CLI
291
320
  // makes inside the turn: a one-line change cost Codex 576 thousand tokens of reading, and the
292
321
  // browser it carried was never opened.
@@ -169,6 +169,42 @@ export function nextOccurrence(due, repeat, after = new Date()) {
169
169
  return next;
170
170
  }
171
171
 
172
+ // A date said whole (2026-11-14, the author): «16 de noviembre», «20 de diciembre de 2026», «November 20»,
173
+ // «Nov 20, 2026», «2026-11-20», «el sábado 16». Without a year it is the next one to come: «3 de enero»
174
+ // said in November is next January. Before this, «16 de noviembre a las 10:30» was read as today at
175
+ // 10:30 and «20 de diciembre» as nothing at all.
176
+ const MONTHS = [
177
+ ['enero', 'january', 'jan', 'ene'], ['febrero', 'february', 'feb'], ['marzo', 'march', 'mar'], ['abril', 'april', 'apr', 'abr'],
178
+ ['mayo', 'may'], ['junio', 'june', 'jun'], ['julio', 'july', 'jul'], ['agosto', 'august', 'aug', 'ago'],
179
+ ['septiembre', 'setiembre', 'september', 'sep', 'sept'], ['octubre', 'october', 'oct'], ['noviembre', 'november', 'nov'], ['diciembre', 'december', 'dec', 'dic'],
180
+ ];
181
+ const monthIndex = (word) => MONTHS.findIndex((names) => names.includes(String(word ?? '').replace(/\.$/, '')));
182
+ const MONTH_WORDS = MONTHS.flat().sort((a, b) => b.length - a.length).join('|');
183
+ function exactDay(text, base) {
184
+ let year = null; let month = -1; let date = null;
185
+ const iso = text.match(/\b(\d{4})-(\d{2})-(\d{2})\b/);
186
+ const es = text.match(new RegExp(`\\b(\\d{1,2})\\s+de\\s+(${MONTH_WORDS})\\.?(?:\\s+(?:de|del)\\s+(\\d{4}))?\\b`));
187
+ const en = text.match(new RegExp(`\\b(${MONTH_WORDS})\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?\\b(?:,?\\s+(\\d{4})\\b)?`));
188
+ const enAfter = text.match(new RegExp(`\\b(\\d{1,2})(?:st|nd|rd|th)?\\s+(?:of\\s+)?(${MONTH_WORDS})\\b(?:,?\\s+(\\d{4})\\b)?`));
189
+ const numbered = text.match(new RegExp(`\\b(?:${DAY_WORDS})\\s+(\\d{1,2})\\b(?!\\s*(?::|am|pm|hrs|h\\b))`));
190
+ if (iso) { year = Number(iso[1]); month = Number(iso[2]) - 1; date = Number(iso[3]); }
191
+ else if (es && monthIndex(es[2]) >= 0) { date = Number(es[1]); month = monthIndex(es[2]); year = es[3] ? Number(es[3]) : null; }
192
+ else if (en && monthIndex(en[1]) >= 0) { date = Number(en[2]); month = monthIndex(en[1]); year = en[3] ? Number(en[3]) : null; }
193
+ else if (enAfter && monthIndex(enAfter[2]) >= 0) { date = Number(enAfter[1]); month = monthIndex(enAfter[2]); year = enAfter[3] ? Number(enAfter[3]) : null; }
194
+ else if (numbered) {
195
+ // «el sábado 16»: the next 16th, this month or the next.
196
+ date = Number(numbered[1]);
197
+ month = base.getMonth();
198
+ if (date < base.getDate()) month += 1;
199
+ } else return null;
200
+ if (month < 0 || date < 1 || date > 31) return null;
201
+ const today = at(base, 0);
202
+ let day = new Date(year ?? base.getFullYear(), month, date);
203
+ if (day.getDate() !== date) return null;
204
+ if (year === null && day < today) day = new Date(base.getFullYear() + 1, month, date);
205
+ return day;
206
+ }
207
+
172
208
  // { due, repeat, said } for the words, or null when they say no time at all.
173
209
  export function parseWhen(words, now = new Date(), { hour: dayHour = DEFAULT_HOUR } = {}) {
174
210
  const text = fold(words);
@@ -193,8 +229,9 @@ export function parseWhen(words, now = new Date(), { hour: dayHour = DEFAULT_HOU
193
229
  return { due: new Date(base.getTime() + amount * unit), repeat: null, said: relative[0] };
194
230
  }
195
231
 
196
- let day = null;
197
- if (/\bpasado manana\b|\bday after tomorrow\b/.test(text)) { day = plusDays(base, 2); said.push('pasado mañana'); }
232
+ let day = exactDay(text, base);
233
+ if (day) said.push('fecha');
234
+ else if (/\bpasado manana\b|\bday after tomorrow\b/.test(text)) { day = plusDays(base, 2); said.push('pasado mañana'); }
198
235
  // «mañana» is tomorrow unless it is the morning: «la mañana», «de la mañana», «por la mañana».
199
236
  else if (/(^|[^a-z])(manana)(?![a-z])/.test(text.replace(/\b(la|las|en la|por la|de la|cada|todas las)\s+manana(s)?\b/g, ' ')) || /\btomorrow\b/.test(text)) { day = plusDays(base, 1); said.push('mañana'); }
200
237
  else if (/\b(hoy|today|tonight|esta tarde|esta noche|this afternoon)\b/.test(text)) { day = new Date(base); said.push('hoy'); }
@@ -469,6 +506,9 @@ export default {
469
506
  summary: 'Notices what you say you still have to do, or what you ask for every day, and offers to remind you with one press. Reminders show in Home and in the project they came from. Read on your computer, with the local AI when you have it; no agent is asked.',
470
507
  creates: ['nothing in the project', 'a reminders.json file in ~/.pulse, one for the whole computer'],
471
508
  settings: { enabled: false, offer: true, habits: true, local: true, hour: '9', snooze: '60' },
509
+ // Its permission to speak through MADRE's notifications (2026-11-10): what it says and when. MADRE's
510
+ // page hands it to the system, if the person lets it (Settings › Notifications); it never does.
511
+ notifies: { label: 'A reminder falls due', note: 'At its hour, with what you asked to remember.' },
472
512
  controls: [
473
513
  { key: 'offer', type: 'switch', label: 'Offer a reminder when you write something pending', note: 'A card under your message, with the time already chosen. Nothing is set without your click.' },
474
514
  { key: 'habits', type: 'switch', label: 'Notice what you ask for often', note: 'The same request on three different days is offered as a daily reminder.' },
@@ -17,7 +17,8 @@ export default defineModule({
17
17
  // RIPLEY's own because it is a separate promise: rendering a file from this project and opening
18
18
  // an address on the internet are not the same permission, and bundling them would hide the
19
19
  // second one behind the first.
20
- settings: { web: false },
20
+ // On from the start (2026-11-14, the author): pages are shown as pages unless the person turns it off.
21
+ settings: { enabled: true, web: false },
21
22
  // No switch for the web, because the browser has no address bar to use it with. What it opens
22
23
  // is the list of servers answering on this computer, and nothing else.
23
24
  //