@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
@@ -23,6 +23,19 @@ export async function gitToplevel(projectRoot) {
23
23
  }
24
24
  }
25
25
 
26
+ // Why git will not read a repository that is there (D-10): «dubious ownership», a folder that belongs
27
+ // to another user of the computer, as a project under /mnt/c can in WSL. gitToplevel reads it as no
28
+ // repository at all. Asked in English so the words are the same in every language. `null` when git
29
+ // reads the folder, or when there is simply no repository in it.
30
+ export async function gitRefused(projectRoot) {
31
+ try {
32
+ await execFileAsync('git', ['-C', projectRoot, 'rev-parse', '--show-toplevel'], { timeout: 5000, env: { ...process.env, LC_ALL: 'C', LANGUAGE: 'C' } });
33
+ return null;
34
+ } catch (error) {
35
+ return /dubious ownership/i.test(String(error?.stderr ?? '')) ? 'dubious-ownership' : null;
36
+ }
37
+ }
38
+
26
39
  export async function findOnPath(name, envPath = process.env.PATH ?? '') {
27
40
  for (const directory of envPath.split(delimiter).filter(Boolean)) {
28
41
  const candidate = join(directory, name);
@@ -36,12 +49,17 @@ export async function findOnPath(name, envPath = process.env.PATH ?? '') {
36
49
  // Nothing is executed. Asking a package for its own --version through npx is not a test of
37
50
  // anything: when the package is not installed at all, npx answers with npm's version and exits
38
51
  // cleanly, which is how PLAYWRIGHT came to report a browser server that was never there.
39
- let globalRoot;
52
+ // Kept per npm prefix: a module that keeps its packages in a folder of its own (npm_config_prefix,
53
+ // the test browser on a Node whose global folder needs sudo) asks about that folder, not the other.
54
+ const globalRoots = new Map();
40
55
  async function npmGlobalRoot(env = process.env) {
41
- if (globalRoot !== undefined) return globalRoot;
42
- try { const { stdout } = await execFileAsync('npm', ['root', '-g'], { env, timeout: 10000 }); globalRoot = stdout.trim() || null; }
43
- catch { globalRoot = null; }
44
- return globalRoot;
56
+ const key = env.npm_config_prefix ?? '';
57
+ if (globalRoots.has(key)) return globalRoots.get(key);
58
+ let root = null;
59
+ try { const { stdout } = await execFileAsync('npm', ['root', '-g'], { env, timeout: 10000 }); root = stdout.trim() || null; }
60
+ catch { root = null; }
61
+ globalRoots.set(key, root);
62
+ return root;
45
63
  }
46
64
 
47
65
  export async function packageVersion(name, { projectRoot = process.cwd(), env = process.env } = {}) {
@@ -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,56 +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. A switch and a model 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.
5
13
 
6
14
  import { defineModule } from './sdk.mjs';
7
- import { switchIn } from '../module-scope.mjs';
8
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';
9
18
 
10
- 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
+ };
11
37
 
12
38
  export default defineModule({
13
39
  id: 'image-studio',
14
40
  configKey: 'imageStudio',
15
41
  name: 'Images',
16
- vendor: 'MADRE · Gemini API',
17
- version: '1.0.0',
18
- 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.',
19
- creates: ['nothing in the project \u00b7 images land in the lease folder', 'an entry 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'],
20
46
  // Not something it writes: a condition for it to attach at all, which is what REQUIRES is for.
21
- 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'],
22
- models: MODELS,
23
- settings: { enabled: false, model: MODELS[0] },
24
- card: 'image-studio',
25
- controls: [{ key: 'model', label: 'MODEL', type: 'select', options: MODELS, note: 'The Gemini image model Image Studio draws with. It bills against your own key.' }],
26
- // Changing the model while it is on has to reach the running room, not just the file.
27
- async onSettings(ctx, settings) { if (settings.enabled) ctx.services.setImageModule({ enabled: true, model: settings.model }); },
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 },
51
+ card: 'fixed',
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
+ }],
57
+ // Changing the model has to reach the running room, not just the file.
58
+ async onSettings(ctx, settings) { tellRoom(ctx, settings.model); },
28
59
  async status(ctx) {
29
- const key = await ctx.services.imageKey();
30
- 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 ?? '';
31
64
  return {
32
- model,
33
- status: { installed: Boolean(ctx.settings.enabled), detail: ctx.settings.enabled ? `${t('on')} · ${model}${key ? '' : t(' · no Gemini key found')}` : key ? t('key found') : t('no Gemini key found') },
34
- 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.'] },
35
- install: { display: ctx.settings.enabled ? 'disable Image Studio' : 'enable Image Studio (config.json)', platforms: ['gemini', 'claude', 'opencode'] },
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
+ },
81
+ // Without a key it is on all the same; it says so, since an image asked for would fail.
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.'] },
84
+ install: { display: 'always on', platforms: ['gemini', 'claude', 'opencode'] },
85
+ fixed: true,
36
86
  };
37
87
  },
38
- // Before it turns on, in one project or in all: a key to bill the images against.
39
- async ready(ctx) {
40
- if (await ctx.services.imageKey()) return null;
41
- return { status: 412, body: { error: 'No Gemini API key found. Sign in with the Gemini CLI (/auth → API key) or set GEMINI_API_KEY, then enable Image Studio.' } };
42
- },
43
- // The room's own image tools follow its switch, wherever the switch was moved from.
44
- async onToggle(ctx, enabled) { ctx.services.setImageModule({ enabled, model: ctx.settings.model ?? MODELS[0] }); return null; },
45
- async toggle(ctx, payload) {
46
- const enabled = !ctx.settings.enabled;
47
- const key = await ctx.services.imageKey();
48
- if (enabled && !key) return { status: 412, body: { error: 'No Gemini API key found. Sign in with the Gemini CLI (/auth → API key) or set GEMINI_API_KEY, then enable Image Studio.' } };
49
- const model = typeof payload?.model === 'string' && payload.model ? payload.model : (ctx.settings.model ?? MODELS[0]);
50
- // A project's switch is that project's (module-scope.mjs); the model is every project's.
51
- await ctx.updateConfig({ modules: { imageStudio: { ...switchIn(ctx.config.modules?.imageStudio ?? {}, ctx.roomId ?? null, enabled), model } } });
52
- ctx.services.setImageModule({ enabled, model });
53
- await ctx.record('extension.toggled', { id: 'image-studio', name: 'Image Studio', enabled, model });
54
- return { status: 200, body: { enabled, model, capabilities: ctx.room.capabilities() } };
55
- },
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
+ ],
56
123
  });