@jossuealcala/madre 1.1.3 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.en.md +20 -1
  2. package/CHANGELOG.md +20 -1
  3. package/TRADEMARKS.md +6 -2
  4. package/bin/madre.mjs +4 -2
  5. package/docs/REFERENCE.md +3 -3
  6. package/docs/SDK.md +28 -1
  7. package/docs/en/REFERENCE.md +2 -2
  8. package/docs/en/SDK.md +26 -0
  9. package/docs/sdk/hello-module.mjs +38 -3
  10. package/habilidades/explicamelo-facil/HABILIDAD.md +19 -0
  11. package/habilidades/hojas-de-calculo/HABILIDAD.md +18 -0
  12. package/habilidades/mensajes-a-clientes/HABILIDAD.md +19 -0
  13. package/habilidades/publicaciones-para-redes/HABILIDAD.md +19 -0
  14. package/habilidades/resumen-y-pendientes/HABILIDAD.md +18 -0
  15. package/habilidades/tu-pagina-paso-a-paso/HABILIDAD.md +19 -0
  16. package/package.json +4 -3
  17. package/public/activity.js +57 -22
  18. package/public/app.js +3998 -762
  19. package/public/assets/brand/OFL-SpaceGrotesk.txt +93 -0
  20. package/public/assets/brand/SpaceGrotesk-latin-ext.woff2 +0 -0
  21. package/public/assets/brand/SpaceGrotesk-latin.woff2 +0 -0
  22. package/public/assets/brand/madre-app-180.png +0 -0
  23. package/public/assets/brand/madre-app-192.png +0 -0
  24. package/public/assets/brand/madre-app-512.png +0 -0
  25. package/public/assets/brand/madre-app.svg +1 -1
  26. package/public/assets/brand/madre-favicon.svg +1 -1
  27. package/public/attribution.js +28 -27
  28. package/public/auto-open.js +102 -0
  29. package/public/brands.js +9 -6
  30. package/public/changes.js +63 -0
  31. package/public/en.js +1085 -101
  32. package/public/es.js +2395 -1688
  33. package/public/i18n.js +11 -0
  34. package/public/index.html +28 -27
  35. package/public/loader.js +322 -117
  36. package/public/macroverso.js +33 -350
  37. package/public/manual-content.js +37 -7
  38. package/public/manual.js +21 -6
  39. package/public/market-view.js +212 -105
  40. package/public/market.js +10 -2
  41. package/public/mcp-catalog.js +7 -2
  42. package/public/missions.js +169 -0
  43. package/public/news-scenes.js +110 -3
  44. package/public/nostromo-engine.js +935 -654
  45. package/public/notices.js +14 -2
  46. package/public/notifications.js +119 -0
  47. package/public/provider-marks.js +170 -0
  48. package/public/provider-pick.js +147 -0
  49. package/public/resay.js +1 -0
  50. package/public/review-ask.js +16 -13
  51. package/public/routing.js +29 -3
  52. package/public/salas-mac.css +257 -40
  53. package/public/salas-mac.html +5 -5
  54. package/public/salas-mac.js +376 -97
  55. package/public/salas.css +2 -2
  56. package/public/salas.html +2 -2
  57. package/public/salas.js +1 -1
  58. package/public/starters.js +128 -0
  59. package/public/styles.css +2656 -336
  60. package/public/subscription.js +303 -0
  61. package/public/terms-field.js +170 -0
  62. package/public/terms.js +117 -19
  63. package/public/tips.js +41 -7
  64. package/public/tour-chapters.js +35 -35
  65. package/public/tour.js +333 -43
  66. package/public/troubleshooting.js +100 -7
  67. package/public/welcome-scene.js +117 -29
  68. package/public/welcome.js +364 -60
  69. package/src/adapters/claude.mjs +2 -1
  70. package/src/adapters/codex.mjs +2 -1
  71. package/src/adapters/cursor.mjs +9 -6
  72. package/src/adapters/gemini.mjs +4 -0
  73. package/src/adapters/grok.mjs +6 -4
  74. package/src/adapters/madre.mjs +71 -23
  75. package/src/adapters/opencode.mjs +15 -2
  76. package/src/adapters/steps.mjs +176 -0
  77. package/src/app-invite.mjs +90 -0
  78. package/src/billing-key.mjs +8 -0
  79. package/src/billing.mjs +317 -0
  80. package/src/bridge/policy.mjs +1 -1
  81. package/src/capabilities.mjs +17 -11
  82. package/src/chats.mjs +44 -2
  83. package/src/checkpoint.mjs +5 -1
  84. package/src/commands.mjs +5 -2
  85. package/src/directives.mjs +1 -0
  86. package/src/event-store.mjs +15 -0
  87. package/src/extensions.mjs +5 -1
  88. package/src/ficha.mjs +16 -0
  89. package/src/image-studio.mjs +13 -3
  90. package/src/install-metrics.mjs +9 -3
  91. package/src/lease.mjs +1 -1
  92. package/src/looks.mjs +4 -1
  93. package/src/mcp/image-server.mjs +59 -90
  94. package/src/modules/ahp.mjs +2 -1
  95. package/src/modules/github.mjs +6 -2
  96. package/src/modules/image-providers.mjs +281 -0
  97. package/src/modules/image-studio.mjs +100 -19
  98. package/src/modules/index.mjs +7 -1
  99. package/src/modules/intents-observe.mjs +3 -1
  100. package/src/modules/playwright.mjs +33 -4
  101. package/src/modules/reminders.mjs +42 -2
  102. package/src/modules/ripley.mjs +2 -1
  103. package/src/modules/sdk.mjs +6 -1
  104. package/src/opencode-health.mjs +1 -1
  105. package/src/outbound.mjs +80 -6
  106. package/src/quota-sources.mjs +148 -3
  107. package/src/review-ask.mjs +55 -31
  108. package/src/room/changes.mjs +79 -0
  109. package/src/room/economy.mjs +1 -1
  110. package/src/room/guard.mjs +8 -1
  111. package/src/room/prompt.mjs +20 -4
  112. package/src/room.mjs +87 -21
  113. package/src/salas.mjs +30 -3
  114. package/src/server.mjs +545 -59
  115. package/src/setup.mjs +1 -1
  116. package/src/skills.mjs +10 -0
  117. package/src/terms.mjs +23 -5
  118. package/src/tour.mjs +18 -3
  119. package/src/updates.mjs +47 -4
  120. package/src/web-preview.mjs +181 -0
  121. package/src/whats-new.mjs +76 -4
package/src/commands.mjs CHANGED
@@ -33,7 +33,8 @@ export const COMMANDS = [
33
33
  return exists(join(projectRoot, '.git'));
34
34
  },
35
35
  async execute({ projectRoot, args }) {
36
- const what = (args[0] ?? 'status').toLowerCase();
36
+ // Said in Spanish too (2026-11-11): «/git estado», «/git guardar "…"», «/git subir confirmar».
37
+ const what = GIT_WORDS[(args[0] ?? 'status').toLowerCase()] ?? (args[0] ?? 'status').toLowerCase();
37
38
  const sections = [];
38
39
  const add = async (title, gitArgs) => {
39
40
  const result = await run('git', gitArgs, projectRoot);
@@ -73,7 +74,7 @@ export const COMMANDS = [
73
74
  const ahead = await run('git', ['-c', 'color.ui=never', 'log', '--oneline', '@{u}..HEAD'], projectRoot);
74
75
  const commits = ahead.text ? ahead.text.split('\n').filter(Boolean) : [];
75
76
  if (!commits.length) return { ok: true, title: 'Git · push', text: `Nothing to push: ${upstream.text} already has everything.` };
76
- if ((args[1] ?? '').toLowerCase() !== 'confirm') {
77
+ if (!['confirm', 'confirmar'].includes((args[1] ?? '').toLowerCase())) {
77
78
  return { ok: true, title: 'Git · push · preview', text: `## would leave for ${upstream.text}\n${commits.join('\n')}\n\nThis leaves the machine and cannot be undone by MADRE. Send it with: /git push confirm` };
78
79
  }
79
80
  const pushed = await run('git', ['-c', 'color.ui=never', 'push'], projectRoot, 120000);
@@ -107,6 +108,8 @@ export const COMMANDS = [
107
108
  },
108
109
  ];
109
110
 
111
+ export const GIT_WORDS = { estado: 'status', historial: 'log', cambios: 'diff', ramas: 'branches', guardar: 'commit', subir: 'push' };
112
+
110
113
  export const commandByName = (name) => COMMANDS.find((command) => command.name === String(name ?? '').toLowerCase()) ?? null;
111
114
 
112
115
  export async function listCommands({ projectRoot }) {
@@ -24,6 +24,7 @@ export const DELEGATION_HELP = (self, others, maxSteps) => [
24
24
  `@${self}: <what you will do with their answers, optional closing turn for you>`,
25
25
  '```',
26
26
  'A step may name the mode it needs, "@codex #2: create the page" or "@claude #3: fix the router"; MADRE uses the human permission for this turn as the ceiling. A higher mode pauses for the human to unlock it for that agent, and #4 always does. Without a number a step only reads, or creates files when the plan may create; ask for #3 by name.',
27
+ 'Only one agent at a time can hold #3 or #4 in the project: a step that needs one waits until the agent holding it finishes, so give #3 or #4 to as few steps as you can. A step at #1 or #2 cannot run commands: when one must run, give that one step #4, or leave it out of the plan and ask the human for the command in a ```pulse-run block in a later reply.',
27
28
  `MADRE runs the steps in order (at most ${maxSteps}), shows every answer in the room, then hands you a closing turn to review progress. If work remains within the human permission, you may end that turn with another pulse plan; at most three waves run from one request.`,
28
29
  'The plan block must be the very last thing in your reply: nothing after it, not even a closing sentence. Say everything else before it.',
29
30
  'Address each agent once. Do not delegate what you can answer yourself.',
@@ -32,6 +32,11 @@ function parseLines(text) {
32
32
  // write that fsyncs took longer, and the page's reader gave up with «Timed out waiting for event
33
33
  // store lock». Thirty seconds of clock, however slow each try is.
34
34
  export const LOCK_WAIT_MS = 30_000;
35
+ // A lock older than any write ever takes was left behind (D-48, 1.1.3, WSL, 2026-11-16): a MADRE
36
+ // that ended abruptly left its lock naming a process number the system later gave to another
37
+ // program, which looked alive forever. A write holds the lock for milliseconds, seconds on a server
38
+ // with every core taken; two minutes is none of them.
39
+ export const STALE_LOCK_MS = 120_000;
35
40
 
36
41
  export class EventStore {
37
42
  #file;
@@ -148,6 +153,9 @@ export class EventStore {
148
153
  await rm(this.#lockDirectory, { recursive: true, force: true, maxRetries: 6, retryDelay: 60 });
149
154
  throw error;
150
155
  }
156
+ // The room's own folder was gone (D-34, 1.1.3: «mkdir '….lock'» ENOENT, two copies): the
157
+ // record comes back in a folder made again, instead of every later write failing.
158
+ if (error.code === 'ENOENT') { await mkdir(dirname(this.#lockDirectory), { recursive: true }); continue; }
151
159
  if (error.code !== 'EEXIST') throw error;
152
160
  try {
153
161
  const owner = JSON.parse(await readFile(ownerFile, 'utf8'));
@@ -159,6 +167,13 @@ export class EventStore {
159
167
  continue;
160
168
  }
161
169
  }
170
+ // Its number answers, but it has held the ledger longer than any write does: the number
171
+ // belongs to someone else now (STALE_LOCK_MS).
172
+ const lock = await stat(this.#lockDirectory).catch(() => null);
173
+ if (lock && Date.now() - lock.mtimeMs > STALE_LOCK_MS) {
174
+ await rm(this.#lockDirectory, { recursive: true, force: true, maxRetries: 6, retryDelay: 60 });
175
+ continue;
176
+ }
162
177
  } catch (ownerError) {
163
178
  if (ownerError.code !== 'ENOENT' && !(ownerError instanceof SyntaxError)) throw ownerError;
164
179
  const lock = await stat(this.#lockDirectory).catch(() => null);
@@ -42,7 +42,11 @@ const redrawn = (text) => { const at = text.lastIndexOf(REDRAW); return at < 0 ?
42
42
 
43
43
  export function runInstaller({ command, args, projectRoot, onLine, timeoutMs = 600000, heartbeatMs = 8000, env = process.env, stdin = 'ignore', onChild = null, flushIdleMs = 0, ci = true, quietNote = 'installer is quiet (npm install or git status can take a while)' }) {
44
44
  return new Promise((resolve) => {
45
- const child = spawn(command, args, { cwd: projectRoot, env: { ...env, NO_COLOR: '1', ...(ci ? { CI: '1' } : {}) }, stdio: [stdin, 'pipe', 'pipe'], shell: process.platform === 'win32', windowsHide: true });
45
+ // A program that cannot be run at all (ENOEXEC, a file with no interpreter) makes spawn throw at
46
+ // once, inside this promise: it was an unhandledRejection and the install never answered (S-7).
47
+ let child;
48
+ try { child = spawn(command, args, { cwd: projectRoot, env: { ...env, NO_COLOR: '1', ...(ci ? { CI: '1' } : {}) }, stdio: [stdin, 'pipe', 'pipe'], shell: process.platform === 'win32', windowsHide: true }); }
49
+ catch (error) { resolve({ code: 1, error: error.code === 'ENOEXEC' ? `${command} cannot be run on this computer (${error.code}): it is not a program for this system, or it has no interpreter line` : error.message }); return; }
46
50
  const started = Date.now();
47
51
  let lastOutput = started;
48
52
  let buffer = '';
package/src/ficha.mjs CHANGED
@@ -114,6 +114,22 @@ export function withFicha(url, ficha) {
114
114
  return address.toString();
115
115
  }
116
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
+
117
133
  // Constant time, and never a throw on something that is not a string.
118
134
  export function sameFicha(given, ficha) {
119
135
  if (typeof given !== 'string' || typeof ficha !== 'string' || !given || given.length !== ficha.length) return false;
@@ -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
@@ -127,7 +127,7 @@ export function leaseInstructions({ outDir, agentId, scopes = { write: true, ima
127
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.'
128
128
  : 'Write every file you produce there (images, code, documents); paths elsewhere are denied.',
129
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.',
130
- 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
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 })}/.`
132
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.`
133
133
  : couldImage ? 'Image generation is switched off for this request; if asked for an image, say so and do not attempt 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
 
@@ -2,94 +2,47 @@
2
2
  // SPDX-License-Identifier: BUSL-1.1
3
3
  // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
4
4
  // MADRE Image Studio: a tiny MCP server (stdio, JSON-RPC 2.0) that exposes one
5
- // tool, generate_image, backed by the Gemini API image models and the user's
6
- // own Gemini key. MADRE attaches it to the isolated homes of the CLIs that
7
- // cannot generate images natively (Gemini CLI, Claude Code, OpenCode), only
8
- // during a creation lease whose image scope is on. Files are written inside
9
- // the lease directory given in PULSE_IMAGE_OUT_DIR, never anywhere else.
5
+ // tool, generate_image, backed by the image model chosen in MODULES › Images —
6
+ // Google's Gemini, OpenAI's GPT Image or xAI's Grok Imagine — and the person's
7
+ // own key for it (src/modules/image-providers.mjs). MADRE attaches it to the
8
+ // isolated homes of the CLIs that cannot generate images natively (Gemini CLI,
9
+ // Claude Code, OpenCode), only during a creation lease whose image scope is on.
10
+ // Files are written inside the lease directory given in PULSE_IMAGE_OUT_DIR,
11
+ // never anywhere else.
10
12
  //
11
13
  // Environment:
12
14
  // PULSE_IMAGE_OUT_DIR required, absolute lease directory
13
- // PULSE_IMAGE_MODEL default gemini-2.5-flash-image
15
+ // PULSE_IMAGE_MODEL the model chosen; without one, the first provider whose key is found
16
+ // PULSE_IMAGE_HOME the person's home, where each CLI keeps its key (default: this HOME)
17
+ // PULSE_IMAGE_STATE MADRE's own folder, whose vault keeps a key pasted in MODULES › Images
14
18
  // GEMINI_API_KEY optional; otherwise ~/.gemini/.env, then the macOS keychain entry the
15
19
  // Gemini CLI stores (service gemini-cli-api-key)
16
- // PULSE_IMAGE_FAKE=1 write a 1×1 PNG without calling Google (tests)
20
+ // PULSE_IMAGE_FAKE=1 write a 1×1 PNG without calling any provider (tests)
21
+ //
22
+ // No key travels in this server's environment but the Gemini one it always took: Claude Code is
23
+ // handed its MCP servers in its arguments, where `ps` shows them. The server reads the key itself,
24
+ // from the same places MODULES › Images says it found it, at the moment it draws.
17
25
 
18
- import { execFile } from 'node:child_process';
19
- import { mkdir, readFile, writeFile, realpath } from 'node:fs/promises';
26
+ import { mkdir, writeFile, realpath } from 'node:fs/promises';
20
27
  import { homedir } from 'node:os';
21
- import { basename, extname, join, resolve, sep } from 'node:path';
22
- import { promisify } from 'node:util';
28
+ import { basename, extname, resolve, sep } from 'node:path';
23
29
  import { OutboundLog } from '../outbound.mjs';
30
+ import { IMAGE_PROVIDERS, defaultModel, drawImage, imageProvider, providerOf, resolveImageKey } from '../modules/image-providers.mjs';
31
+
32
+ export { explainGoogleError, keyFromGeminiEnvFile, resolveGeminiKey } from '../modules/image-providers.mjs';
24
33
 
25
- const execFileAsync = promisify(execFile);
26
34
  const SERVER_NAME = 'pulse-image';
27
- const SERVER_VERSION = '0.1.0';
28
- const DEFAULT_MODEL = 'gemini-2.5-flash-image';
35
+ const SERVER_VERSION = '0.2.0';
29
36
  const FAKE_PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64');
30
37
 
31
- // Where a Gemini key can be, in the order the room should trust them: what this process was
32
- // given, then the file the CLI reads on every run — which is also the file MADRE itself writes
33
- // when a key is pasted into Settings › Agents — and last the macOS keychain, which only exists when
34
- // the CLI's own sign-in put it there. Leaving the file out meant MADRE saved a key in a place it
35
- // then refused to look, and on Linux, where there is no keychain, that was the only place it
36
- // could have been: Image Studio could never find a key there at all.
37
- export async function keyFromGeminiEnvFile(env) {
38
- const home = env.GEMINI_CLI_HOME ?? homedir();
39
- let text;
40
- try { text = await readFile(join(home, '.gemini', '.env'), 'utf8'); } catch { return null; }
41
- for (const line of text.split('\n')) {
42
- const match = line.match(/^\s*(?:export\s+)?(GEMINI_API_KEY|GOOGLE_API_KEY)\s*=\s*(.*)$/);
43
- if (!match) continue;
44
- const value = match[2].trim().replace(/^(['"])(.*)\1$/, '$2').trim();
45
- if (value) return value;
46
- }
47
- return null;
48
- }
49
-
50
- export async function resolveGeminiKey(env = process.env) {
51
- if (env.GEMINI_API_KEY) return env.GEMINI_API_KEY;
52
- if (env.GOOGLE_API_KEY) return env.GOOGLE_API_KEY;
53
- const fromFile = await keyFromGeminiEnvFile(env);
54
- if (fromFile) return fromFile;
55
- if (process.platform !== 'darwin') return null;
56
- // The keychain occasionally answers empty under concurrent reads; one retry.
57
- for (let attempt = 0; attempt < 2; attempt += 1) {
58
- try {
59
- const { stdout } = await execFileAsync('/usr/bin/security', ['find-generic-password', '-s', 'gemini-cli-api-key', '-w'], { timeout: 4000 });
60
- const raw = stdout.trim();
61
- if (!raw) continue;
62
- try {
63
- const parsed = JSON.parse(raw);
64
- return parsed?.token?.accessToken ?? parsed?.token?.apiKey ?? parsed?.apiKey ?? null;
65
- } catch {
66
- return raw;
67
- }
68
- } catch {
69
- if (attempt === 1) return null;
70
- }
71
- }
72
- return null;
73
- }
74
-
75
38
  export function safeImageName(name, fallback = 'image.png') {
76
39
  const cleaned = basename(String(name ?? fallback)).replace(/[^\w.\- ]+/g, '_').replace(/^\.+/, '') || fallback;
77
40
  return extname(cleaned) ? cleaned : `${cleaned}.png`;
78
41
  }
79
42
 
80
- // Google's error strings, turned into something a human can act on.
81
- export function explainGoogleError(status, body) {
82
- const message = body?.error?.message ?? '';
83
- 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.' };
84
- if (status === 429) return { code: 'RATE_LIMITED', message: 'Google is rate-limiting this key (HTTP 429). Wait a minute and retry.' };
85
- 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.` };
86
- if (status === 404) return { code: 'MODEL', message: `Image model not available to this key (HTTP 404): ${message}` };
87
- return { code: 'ERROR', message: message || `Google returned HTTP ${status}.` };
88
- }
89
-
90
43
  // The image studio runs in a process of its own, so it writes its own line into the room's
91
- // outbound log. Without this, the one request MADRE makes that carries somebody's words to
92
- // Google would be the one request the log could not see.
44
+ // outbound log. Without this, the one request MADRE makes that carries somebody's words to an
45
+ // image provider would be the one request the log could not see.
93
46
  let outboundLog = null;
94
47
  function outboundFetch(fetchImpl, file) {
95
48
  if (!file) return fetchImpl;
@@ -97,7 +50,29 @@ function outboundFetch(fetchImpl, file) {
97
50
  return outboundLog.watch(fetchImpl);
98
51
  }
99
52
 
100
- export async function generateImage({ prompt, fileName, outDir, model = process.env.PULSE_IMAGE_MODEL || DEFAULT_MODEL, env = process.env, fetchImpl = fetch }) {
53
+ // Which model draws and with which key: the one chosen, or — until one is chosen — the first
54
+ // provider whose key is found, with its first model (the same choice MODULES › Images shows).
55
+ async function keyedModel(model, lookup) {
56
+ if (model) {
57
+ const providerId = providerOf(model);
58
+ if (!providerId) throw Object.assign(new Error(`MADRE does not know which provider draws ${model}. Choose another model in MODULES › Images.`), { code: 'MODEL' });
59
+ return { model, providerId, key: (await resolveImageKey(providerId, lookup))?.key ?? null };
60
+ }
61
+ for (const provider of IMAGE_PROVIDERS) {
62
+ const hit = await resolveImageKey(provider.id, lookup).catch(() => null);
63
+ if (hit) return { model: defaultModel(provider.id), providerId: provider.id, key: hit.key };
64
+ }
65
+ return { model: null, providerId: null, key: null };
66
+ }
67
+
68
+ // The name the file keeps follows what came back: a JPEG is not saved as .png.
69
+ function namedFor(target, mimeType) {
70
+ if (/jpe?g/.test(mimeType) && !/\.jpe?g$/i.test(target)) return target.replace(/\.(png|webp)$/i, '.jpg');
71
+ if (/webp/.test(mimeType) && !/\.webp$/i.test(target)) return target.replace(/\.png$/i, '.webp');
72
+ return target;
73
+ }
74
+
75
+ export async function generateImage({ prompt, fileName, outDir, model = null, env = process.env, fetchImpl = fetch }) {
101
76
  if (!prompt || typeof prompt !== 'string') throw Object.assign(new Error('A text prompt is required.'), { code: 'INVALID' });
102
77
  const root = await realpath(outDir).catch(() => null);
103
78
  if (!root) throw Object.assign(new Error('The lease directory does not exist.'), { code: 'NO_LEASE' });
@@ -109,35 +84,29 @@ export async function generateImage({ prompt, fileName, outDir, model = process.
109
84
  await writeFile(target, FAKE_PNG);
110
85
  return { path: target, bytes: FAKE_PNG.length, mimeType: 'image/png', model: 'fake' };
111
86
  }
112
- const key = await resolveGeminiKey(env);
113
- if (!key) throw Object.assign(new Error('No Gemini API key: set GEMINI_API_KEY or sign in with the Gemini CLI (/auth → API key).'), { code: 'NO_KEY' });
114
- const response = await outboundFetch(fetchImpl, env.PULSE_OUTBOUND_LOG)(`https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent`, {
115
- method: 'POST',
116
- headers: { 'content-type': 'application/json', 'x-goog-api-key': key },
117
- body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }], generationConfig: { responseModalities: ['IMAGE'] } }),
118
- });
119
- const body = await response.json().catch(() => ({}));
120
- if (!response.ok) {
121
- const explained = explainGoogleError(response.status, body);
122
- throw Object.assign(new Error(explained.message), { code: explained.code, status: response.status });
87
+ const lookup = { env, home: env.PULSE_IMAGE_HOME || homedir(), stateRoot: env.PULSE_IMAGE_STATE || null };
88
+ const chosen = await keyedModel(model ?? env.PULSE_IMAGE_MODEL ?? null, lookup);
89
+ if (!chosen.key) {
90
+ const provider = imageProvider(chosen.providerId);
91
+ const message = provider
92
+ ? `No ${provider.vendor} key for ${chosen.model}: the human connects one in MODULES › Images (or sets ${provider.variable}).`
93
+ : 'No image key yet: the human connects Gemini, OpenAI or Grok in MODULES › Images. Each image is billed to that key.';
94
+ throw Object.assign(new Error(message), { code: 'NO_KEY' });
123
95
  }
124
- const part = body.candidates?.[0]?.content?.parts?.find((item) => item.inlineData?.data);
125
- if (!part) throw Object.assign(new Error('Google returned no image data.'), { code: 'EMPTY', detail: body.candidates?.[0]?.finishReason ?? null });
126
- const bytes = Buffer.from(part.inlineData.data, 'base64');
127
- const mimeType = part.inlineData.mimeType ?? 'image/png';
128
- const finalPath = /jpe?g/.test(mimeType) && !/\.jpe?g$/i.test(target) ? target.replace(/\.png$/i, '.jpg') : target;
96
+ const { bytes, mimeType } = await drawImage({ model: chosen.model, prompt, key: chosen.key, fetchImpl: outboundFetch(fetchImpl, env.PULSE_OUTBOUND_LOG) });
97
+ const finalPath = namedFor(target, mimeType);
129
98
  await writeFile(finalPath, bytes);
130
- return { path: finalPath, bytes: bytes.length, mimeType, model };
99
+ return { path: finalPath, bytes: bytes.length, mimeType, model: chosen.model };
131
100
  }
132
101
 
133
102
  export const TOOL = {
134
103
  name: 'generate_image',
135
- description: 'Generate an image from a text prompt with a Gemini image model and save it as a PNG inside the current creation lease directory. Returns the saved path.',
104
+ description: 'Generate an image from a text prompt with the image model the human chose in MADRE (Gemini, OpenAI or Grok, on their own key) and save it inside the current creation lease directory. Returns the saved path.',
136
105
  inputSchema: {
137
106
  type: 'object',
138
107
  properties: {
139
108
  prompt: { type: 'string', description: 'What the image should show; be specific about style, colors and composition.' },
140
- file_name: { type: 'string', description: 'File name for the PNG, e.g. poster.png. Saved inside the lease directory.' },
109
+ file_name: { type: 'string', description: 'File name for the image, e.g. poster.png. Saved inside the lease directory; a JPEG answer is saved as .jpg.' },
141
110
  },
142
111
  required: ['prompt', 'file_name'],
143
112
  },
@@ -27,7 +27,8 @@ async function detect(projectRoot) {
27
27
  version: pinned ?? null,
28
28
  protocolVersion: manifest.protocol_version ?? null,
29
29
  projectId: manifest.project_id ?? null,
30
- detail: [pinned ? `cli ${pinned}` : null, manifest.protocol_version ? `protocol ${manifest.protocol_version}` : null].filter(Boolean).join(' · '),
30
+ // In the room's language (2026-11-17): Modules › Continuity read «Cli 1.4.2 · protocol 1.4.0».
31
+ detail: [pinned ? t('cli {version}', { version: pinned }) : null, manifest.protocol_version ? t('protocol {version}', { version: manifest.protocol_version }) : null].filter(Boolean).join(' · '),
31
32
  };
32
33
  }
33
34
 
@@ -63,10 +63,12 @@ export function tokenize(args) {
63
63
  pieces.push(match[3] !== undefined ? { text: match[3], quoted: false } : { text: match[1] ?? match[2] ?? '', quoted: true });
64
64
  }
65
65
  const last = pieces[pieces.length - 1];
66
- const confirm = Boolean(last && !last.quoted && last.text.toLowerCase() === 'confirm');
66
+ const confirm = Boolean(last && !last.quoted && ['confirm', 'confirmar'].includes(last.text.toLowerCase()));
67
67
  return { pieces: confirm ? pieces.slice(0, -1) : pieces, confirm };
68
68
  }
69
69
 
70
+ const GH_WORDS = { solicitudes: ['pr'], solicitud: ['pr'], proponer: ['pr', 'create'], pruebas: ['ci'], pendientes: ['issues'], pendiente: ['issue'], comentar: ['comment'] };
71
+
70
72
  // A title and an optional body: quoted pieces when there are any, the bare words otherwise.
71
73
  function titleAndBody(pieces) {
72
74
  const quoted = pieces.filter((one) => one.quoted);
@@ -202,7 +204,9 @@ async function openIssue(ctx, { project, auth, env, log }, pieces, confirm) {
202
204
  }
203
205
 
204
206
  export async function runGh(ctx, args = []) {
205
- const { pieces, confirm } = tokenize(args);
207
+ const { pieces: said, confirm } = tokenize(args);
208
+ // Said in Spanish too (2026-11-11): «/gh pruebas», «/gh proponer "…"», «/gh pendiente "…" confirmar».
209
+ const pieces = said[0] && !said[0].quoted && GH_WORDS[said[0].text.toLowerCase()] ? [...GH_WORDS[said[0].text.toLowerCase()].map((text) => ({ text, quoted: false })), ...said.slice(1)] : said;
206
210
  const what = (pieces[0]?.quoted ? '' : pieces[0]?.text ?? '').toLowerCase();
207
211
  const facts = await where(ctx);
208
212
  const problems = problemsOf(facts);