@jossuealcala/madre 1.1.2 → 1.1.3
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.
- package/CHANGELOG.en.md +21 -1
- package/CHANGELOG.md +21 -1
- package/README.en.md +3 -3
- package/README.md +3 -3
- package/SECURITY.md +11 -6
- package/bin/madre.mjs +74 -11
- package/docs/REFERENCE.md +13 -7
- package/docs/SDK.md +8 -8
- package/docs/en/REFERENCE.md +10 -6
- package/docs/en/SDK.md +8 -8
- package/docs/en/training/README.md +1 -1
- package/docs/sdk/connector-module.mjs +1 -1
- package/docs/sdk/hello-module.mjs +1 -1
- package/docs/training/README.md +1 -1
- package/docs/training/train.sh +3 -0
- package/package.json +4 -2
- package/public/activity.js +9 -0
- package/public/app.js +988 -171
- package/public/attribution.js +9 -0
- package/public/brands.js +27 -13
- package/public/en.js +1 -2
- package/public/es.js +834 -257
- package/public/index.html +3 -0
- package/public/macroverso.js +24 -5
- package/public/manual-content.js +32 -2
- package/public/market-view.js +116 -9
- package/public/market.js +15 -0
- package/public/news-scenes.js +185 -0
- package/public/notices.js +66 -0
- package/public/power.js +1 -1
- package/public/resay.js +3 -0
- package/public/salas-mac.css +229 -26
- package/public/salas-mac.html +3 -0
- package/public/salas-mac.js +454 -37
- package/public/styles.css +393 -17
- package/public/tips.js +124 -0
- package/public/tour-chapters.js +75 -75
- package/public/tour.js +36 -8
- package/public/troubleshooting.js +215 -22
- package/public/welcome-scene.js +358 -0
- package/public/welcome.js +514 -273
- package/src/adapters/gemini-rest.mjs +236 -0
- package/src/adapters/gemini.mjs +9 -7
- package/src/adapters/grok.mjs +288 -0
- package/src/adapters/process.mjs +14 -3
- package/src/auth-probe.mjs +32 -0
- package/src/bridge/policy.mjs +1 -1
- package/src/capabilities.mjs +30 -0
- package/src/checkpoint.mjs +115 -1
- package/src/codex-route.mjs +113 -0
- package/src/credentials.mjs +46 -8
- package/src/dataset.mjs +18 -7
- package/src/event-store.mjs +10 -2
- package/src/ficha.mjs +142 -0
- package/src/files.mjs +36 -2
- package/src/lease.mjs +5 -0
- package/src/market-check.mjs +1 -1
- package/src/market-remote.mjs +135 -1
- package/src/mcp/image-server.mjs +1 -1
- package/src/mcp/memory-server.mjs +10 -0
- package/src/memory-tools.mjs +3 -0
- package/src/memory.mjs +29 -4
- package/src/models.mjs +21 -3
- package/src/modules/ahp.mjs +8 -3
- package/src/modules/bishop-exam.mjs +41 -12
- package/src/modules/bishop.mjs +2 -2
- package/src/modules/choices.mjs +12 -10
- package/src/modules/fetch-alone.mjs +7 -0
- package/src/modules/helpers.mjs +23 -5
- package/src/modules/image-studio.mjs +13 -27
- package/src/modules/index.mjs +54 -11
- package/src/modules/isolated.mjs +160 -0
- package/src/modules/ollama.mjs +35 -6
- package/src/modules/playwright.mjs +46 -17
- package/src/modules/run-alone.mjs +122 -0
- package/src/modules/runs.mjs +11 -8
- package/src/modules/sdk.mjs +4 -2
- package/src/notices-key.mjs +8 -0
- package/src/notices.mjs +185 -0
- package/src/ollama.mjs +57 -15
- package/src/outbound.mjs +45 -8
- package/src/room/archivist.mjs +30 -5
- package/src/room/busy.mjs +16 -0
- package/src/room/control.mjs +36 -6
- package/src/room/guard.mjs +32 -2
- package/src/room/prompt.mjs +32 -5
- package/src/room/vectors.mjs +7 -1
- package/src/room.mjs +94 -28
- package/src/router.mjs +1 -1
- package/src/runs.mjs +39 -0
- package/src/runtime-detection.mjs +46 -6
- package/src/salas.mjs +151 -15
- package/src/server.mjs +577 -80
- package/src/service.mjs +116 -0
- package/src/setup-trouble.mjs +20 -1
- package/src/skill-check.mjs +269 -0
- package/src/skills-import.mjs +128 -0
- package/src/skills.mjs +492 -0
- package/src/tour.mjs +14 -3
- package/src/whats-new.mjs +48 -0
- package/src/rumbo.mjs +0 -337
package/src/modules/ollama.mjs
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
// Ollama runs. The server offers the wiring through ctx.services.ollama.
|
|
5
5
|
|
|
6
6
|
import { execFile } from 'node:child_process';
|
|
7
|
+
import { access, constants, readdir, realpath } from 'node:fs/promises';
|
|
8
|
+
import { dirname, join } from 'node:path';
|
|
7
9
|
import { defineModule } from './sdk.mjs';
|
|
8
10
|
import { t } from '../i18n.mjs';
|
|
9
11
|
import { findOnPath } from './helpers.mjs';
|
|
@@ -73,22 +75,49 @@ export function ollamaUpdatePlan({ platform = process.platform, brew = null, adm
|
|
|
73
75
|
}
|
|
74
76
|
if (platform === 'linux') {
|
|
75
77
|
if (!admin) return { command: null, manual: true, display: script.replace('sudo -n ', 'sudo '), note: `${t(NEEDS_PASSWORD)} ${t('Your models stay where they are.')}` };
|
|
76
|
-
return { command: 'sh', args: ['-c', script], display: script, note: "Ollama's own install script upgrades in place. Your models stay where they are." };
|
|
78
|
+
return { command: 'sh', args: ['-c', script], display: script, timeoutMs: OLLAMA_INSTALL_MS, note: "Ollama's own install script upgrades in place. Your models stay where they are." };
|
|
77
79
|
}
|
|
78
80
|
return { command: null, download: 'https://ollama.com/download', display: null, note: 'Download the newer Ollama from ollama.com and run it. Your models stay where they are.' };
|
|
79
81
|
}
|
|
80
82
|
|
|
83
|
+
// How long Ollama's script may take (D-2, 2026-11-03): it streams a bundle of more than a GB, and on
|
|
84
|
+
// a slow line inside WSL fifteen minutes ran out halfway (diagnostics of 1.1.2: «timeout»).
|
|
85
|
+
export const OLLAMA_INSTALL_MS = 60 * 60 * 1000;
|
|
86
|
+
|
|
87
|
+
// An install that stopped halfway (D-2, 2026-11-03). Ollama's script first deletes lib/ollama and
|
|
88
|
+
// then unpacks the whole bundle in one stream; cut by the time limit or the network, it leaves
|
|
89
|
+
// bin/ollama with no llama-server beside it («llama-server binary not found», 1.1.2) or a binary
|
|
90
|
+
// this user cannot run (EACCES). Either reads as installed, and every answer of @madre failed. Seen
|
|
91
|
+
// as halfway, the card offers the install again, which finishes it. Only Linux, and only where the
|
|
92
|
+
// script installs (`scriptRoot`): Homebrew, the Mac app or a distribution's package lay it out
|
|
93
|
+
// otherwise.
|
|
94
|
+
export async function ollamaHalfway(binary, { platform = process.platform, scriptRoot = '/usr/local' } = {}) {
|
|
95
|
+
if (!binary || platform !== 'linux') return false;
|
|
96
|
+
try { await access(binary, constants.X_OK); } catch { return true; }
|
|
97
|
+
const real = await realpath(binary).catch(() => binary);
|
|
98
|
+
const root = dirname(dirname(real));
|
|
99
|
+
if (root !== scriptRoot) return false;
|
|
100
|
+
const lib = await readdir(join(root, 'lib', 'ollama')).catch(() => null);
|
|
101
|
+
return !lib?.length;
|
|
102
|
+
}
|
|
103
|
+
|
|
81
104
|
// Waking it: the same command on every system, and the app on macOS does it too.
|
|
82
105
|
export const ollamaStartPlan = () => ({ command: 'ollama', args: ['serve'], display: 'ollama serve' });
|
|
83
106
|
|
|
84
107
|
// What the room needs to know about the local brain: its own state, whether it is even on this
|
|
85
108
|
// computer, and the one step that moves it forward. The card and the routes share this.
|
|
86
109
|
export async function ollamaView(probe, settings) {
|
|
87
|
-
const
|
|
110
|
+
const found = await findOnPath('ollama');
|
|
111
|
+
// Halfway is not installed: no binary for the card, which offers the install again, and the path
|
|
112
|
+
// kept apart so it can say what it found.
|
|
113
|
+
const halfway = await ollamaHalfway(found) ? found : null;
|
|
114
|
+
const binary = halfway ? null : found;
|
|
88
115
|
// The sudo question is only worth asking while there is something to install.
|
|
89
116
|
const admin = binary ? true : await adminHere();
|
|
90
|
-
|
|
117
|
+
const install = ollamaInstallPlan({ brew: await findOnPath('brew'), admin, zstd: Boolean(await findOnPath('zstd')), apt: Boolean(await findOnPath('apt-get')) });
|
|
118
|
+
return { ...probe, settings, binary, ...(halfway ? { halfway } : {}), install: halfway && install.command ? { ...install, note: t(HALFWAY_NOTE) } : install, start: ollamaStartPlan() };
|
|
91
119
|
}
|
|
120
|
+
const HALFWAY_NOTE = 'Ollama was left installed halfway (the download stopped). Installing it again finishes it; your models stay where they are.';
|
|
92
121
|
|
|
93
122
|
export default defineModule({
|
|
94
123
|
id: 'ollama',
|
|
@@ -108,7 +137,7 @@ export default defineModule({
|
|
|
108
137
|
const roles = [settings.embeddings && probe.embedModel ? `${t('smart search')} · ${probe.embedModel}` : null, settings.archivist && probe.chatModel ? `${t('archivist')} · ${probe.chatModel}` : null, settings.agent !== false && probe.chatModel ? t('@madre in the project') : null].filter(Boolean);
|
|
109
138
|
// Home can leave this one project without the local AI while the module stays on (src/local-ai.mjs).
|
|
110
139
|
const project = await ctx.services.ollama?.project?.() ?? { on: true };
|
|
111
|
-
const detail = !probe.running ? (binary ? t('installed, not running · START it here') : t('not installed · INSTALL it here'))
|
|
140
|
+
const detail = !probe.running ? (binary ? t('installed, not running · START it here') : view.halfway ? t('installed halfway · INSTALL it again here') : t('not installed · INSTALL it here'))
|
|
112
141
|
: !settings.enabled ? t('off · {n} models available', { n: probe.models.length })
|
|
113
142
|
: !project.on ? t('off in this project · Home › Settings › Local AI')
|
|
114
143
|
: roles.length ? `${t('on')} · ${roles.join(' · ')}` : t('on · no usable model yet · PULL one');
|
|
@@ -147,8 +176,8 @@ export default defineModule({
|
|
|
147
176
|
return { status: 200, body: { enabled, ollama: status } };
|
|
148
177
|
},
|
|
149
178
|
routes: [
|
|
150
|
-
{ method: 'GET', path: '/api/ollama', handler: async (ctx) => ({ status: 200, body: { ollama: await ollamaView(await ctx.services.ollama.wire({ probe: false }), ctx.settings), recommended: await recommendedHere() } }) },
|
|
151
|
-
{ method: 'POST', path: '/api/ollama/probe', handler: async (ctx) => ({ status: 200, body: { ollama: await ollamaView(await ctx.services.ollama.wire(), ctx.settings), recommended: await recommendedHere() } }) },
|
|
179
|
+
{ method: 'GET', path: '/api/ollama', handler: async (ctx) => ({ status: 200, body: { ollama: await ollamaView(await ctx.services.ollama.wire({ probe: false }), ctx.settings), recommended: await recommendedHere(), pulling: ctx.services.ollama.pulling?.() ?? null, lastPull: ctx.services.ollama.lastPull?.() ?? null } }) },
|
|
180
|
+
{ method: 'POST', path: '/api/ollama/probe', handler: async (ctx) => ({ status: 200, body: { ollama: await ollamaView(await ctx.services.ollama.wire(), ctx.settings), recommended: await recommendedHere(), pulling: ctx.services.ollama.pulling?.() ?? null, lastPull: ctx.services.ollama.lastPull?.() ?? null } }) },
|
|
152
181
|
{ method: 'POST', path: '/api/ollama/settings', handler: async (ctx, { payload }) => {
|
|
153
182
|
const next = { ...(ctx.config.modules?.ollama ?? {}) };
|
|
154
183
|
for (const key of ['embeddings', 'archivist', 'agent', 'enabled']) if (typeof payload[key] === 'boolean') next[key] = payload[key];
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// room's own address: nothing else on the network is reachable through it.
|
|
7
7
|
|
|
8
8
|
import { spawn } from 'node:child_process';
|
|
9
|
-
import { mkdtemp, rm } from 'node:fs/promises';
|
|
9
|
+
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
|
10
10
|
import { tmpdir } from 'node:os';
|
|
11
11
|
import { join } from 'node:path';
|
|
12
12
|
import { t } from '../i18n.mjs';
|
|
@@ -61,18 +61,41 @@ function runToEnd(command, args, { cwd, env, timeoutMs = 900000 } = {}) {
|
|
|
61
61
|
});
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
// Where npm installs for every project is often not this person's to write: Node from apt or the
|
|
65
|
+
// distribution keeps it in /usr/lib/node_modules, and `npm install -g` ends in EACCES, exit 243
|
|
66
|
+
// (report MR-5NY24Y and the diagnostics of 1.1.2). MADRE never asks for sudo; it keeps the server in
|
|
67
|
+
// a folder of its own instead, and tells npm and npx where with npm_config_prefix (2026-11-03).
|
|
68
|
+
export const ownNpmPrefix = (stateRoot) => join(stateRoot, 'npm-global');
|
|
69
|
+
const refusedWrite = (said, code) => code === 243 || /EACCES|EPERM|permission denied/i.test(String(said ?? ''));
|
|
70
|
+
// The environment the server is looked for and started with: MADRE's own folder once the server
|
|
71
|
+
// lives there, the person's own otherwise.
|
|
72
|
+
export async function playwrightEnv({ env = process.env, stateRoot = null } = {}) {
|
|
73
|
+
if (!stateRoot) return env;
|
|
74
|
+
const prefix = ownNpmPrefix(stateRoot);
|
|
75
|
+
const there = await readFile(join(prefix, 'lib', 'node_modules', ...PLAYWRIGHT_PACKAGE.split('/'), 'package.json'), 'utf8').then(() => true, () => false);
|
|
76
|
+
return there ? { ...env, npm_config_prefix: prefix } : env;
|
|
77
|
+
}
|
|
78
|
+
|
|
64
79
|
// What the switch puts in place by itself before it gives up (2026-10-18): the person turned it
|
|
65
80
|
// on, and a browser to download is MADRE's to fetch, not a line to copy into a terminal. The
|
|
66
81
|
// server, globally (where `npx --no` finds it at turn time), when it is missing; then the browser
|
|
67
82
|
// the server itself downloads for the engine chosen. Asked again after.
|
|
68
|
-
export async function preparePlaywright({ browser = 'chromium', env = process.env, cwd = process.cwd(), run = runToEnd, starts = playwrightStarts, version = playwrightVersion } = {}) {
|
|
83
|
+
export async function preparePlaywright({ browser = 'chromium', env = process.env, cwd = process.cwd(), stateRoot = null, run = runToEnd, starts = playwrightStarts, version = playwrightVersion } = {}) {
|
|
69
84
|
const engine = PLAYWRIGHT_BROWSERS.includes(browser) ? browser : 'chromium';
|
|
70
85
|
let installed = await version({ env, projectRoot: cwd, fresh: true });
|
|
71
86
|
const steps = [];
|
|
72
87
|
if (!installed) {
|
|
73
|
-
|
|
88
|
+
let server = await run('npm', ['install', '-g', PLAYWRIGHT_PACKAGE], { cwd, env });
|
|
74
89
|
steps.push({ display: `npm install -g ${PLAYWRIGHT_PACKAGE}`, code: server.code });
|
|
75
90
|
installed = await version({ env, projectRoot: cwd, fresh: true });
|
|
91
|
+
// The global folder is not this person's to write: the same install, into MADRE's own.
|
|
92
|
+
if (!installed && stateRoot && refusedWrite(server.said, server.code)) {
|
|
93
|
+
const prefix = ownNpmPrefix(stateRoot);
|
|
94
|
+
env = { ...env, npm_config_prefix: prefix };
|
|
95
|
+
server = await run('npm', ['install', '-g', PLAYWRIGHT_PACKAGE], { cwd, env });
|
|
96
|
+
steps.push({ display: `npm install -g --prefix ${prefix} ${PLAYWRIGHT_PACKAGE}`, code: server.code });
|
|
97
|
+
installed = await version({ env, projectRoot: cwd, fresh: true });
|
|
98
|
+
}
|
|
76
99
|
if (!installed) return { ok: false, steps, problem: server.said ?? t('the browser server could not be installed') };
|
|
77
100
|
}
|
|
78
101
|
const fetched = await run('npx', ['--no', PLAYWRIGHT_PACKAGE, 'install-browser', engine], { cwd, env });
|
|
@@ -169,7 +192,7 @@ export function forgetPlaywrightHealth(result = null, browser = null) { started
|
|
|
169
192
|
// What the browser may open: this room, and the servers the human started from RUNS in this project
|
|
170
193
|
// while they listen on 127.0.0.1. RIPLEY's sealed frame keeps no data, so an app that stores its
|
|
171
194
|
// data could only be tried through it half-blind. Nothing else on the network.
|
|
172
|
-
export function playwrightServerFor({ port, outputDir, browser = 'chromium', headless = true, servers = [] }) {
|
|
195
|
+
export function playwrightServerFor({ port, outputDir, browser = 'chromium', headless = true, servers = [], preview = '/preview', prefix = null }) {
|
|
173
196
|
const origins = [port, ...servers.filter((one) => Number.isInteger(one) && one !== port)].flatMap((one) => [`http://127.0.0.1:${one}`, `http://localhost:${one}`]);
|
|
174
197
|
const served = servers.filter((one) => Number.isInteger(one) && one !== port);
|
|
175
198
|
return {
|
|
@@ -183,25 +206,26 @@ export function playwrightServerFor({ port, outputDir, browser = 'chromium', hea
|
|
|
183
206
|
// recently added route first — so a blocked `*`, registered after both, wins over the
|
|
184
207
|
// allowlist and aborts even this room with ERR_BLOCKED_BY_CLIENT.
|
|
185
208
|
args: ['--no', '@playwright/mcp', '--', ...(headless ? ['--headless'] : []), '--isolated', '--browser', browser, '--allowed-origins', origins.join(';'), '--output-dir', outputDir, '--no-sandbox'],
|
|
186
|
-
|
|
209
|
+
// npx finds a server kept in MADRE's own folder only when told where it is.
|
|
210
|
+
env: prefix ? { npm_config_prefix: prefix } : {},
|
|
187
211
|
tools: PLAYWRIGHT_TOOLS,
|
|
188
|
-
brief: `a headless browser that reaches only this MADRE at http://127.0.0.1:${port}${served.length ? ` and the project's servers the human started (${served.map((one) => `http://127.0.0.1:${one}`).join(', ')})` : ''}. Open a project file rendered by RIPLEY at http://127.0.0.1:${port}
|
|
212
|
+
brief: `a headless browser that reaches only this MADRE at http://127.0.0.1:${port}${served.length ? ` and the project's servers the human started (${served.map((one) => `http://127.0.0.1:${one}`).join(', ')})` : ''}. Open a project file rendered by RIPLEY at http://127.0.0.1:${port}${preview}/project/<path>, click, read the console and network, take screenshots (they land in ${outputDir}). RIPLEY's preview keeps no data (no localStorage, no cookies)${served.length ? '; to try an app with its data, open it on its server' : ''}. Nothing else on the network is reachable through it.`,
|
|
189
213
|
};
|
|
190
214
|
}
|
|
191
215
|
|
|
192
216
|
async function playwrightReady(ctx) {
|
|
193
217
|
const browser = ctx.settings.browser ?? 'chromium';
|
|
194
|
-
let check = await playwrightStarts({ browser, env: ctx
|
|
218
|
+
let check = await playwrightStarts({ browser, env: await playwrightEnv(ctx), cwd: ctx.projectRoot });
|
|
195
219
|
// Something missing: MADRE fetches it, then asks again, before saying anything to the person.
|
|
196
220
|
if (!check.ok && process.platform !== 'win32') {
|
|
197
221
|
await ctx.record('extension.preparing', { id: 'playwright', name: 'PLAYWRIGHT', browser });
|
|
198
|
-
check = await preparePlaywright({ browser, env: ctx
|
|
222
|
+
check = await preparePlaywright({ browser, env: await playwrightEnv(ctx), cwd: ctx.projectRoot, stateRoot: ctx.stateRoot });
|
|
199
223
|
}
|
|
200
224
|
forgetPlaywrightHealth(check, browser);
|
|
201
225
|
if (check.ok) return null;
|
|
202
226
|
// The server is there and only the browser is missing: say which one, and the one line that
|
|
203
227
|
// installs it. Without the server, both lines.
|
|
204
|
-
const version = await playwrightVersion({ env: ctx
|
|
228
|
+
const version = await playwrightVersion({ env: await playwrightEnv(ctx), projectRoot: ctx.projectRoot });
|
|
205
229
|
return { status: 412, body: { error: version
|
|
206
230
|
? t('TEST BROWSER stays off: MADRE downloaded the {browser} browser and it still does not start ({problem}). Check your internet connection and turn it on again, or choose another browser in its settings.', { problem: String(check.problem).replace(/[.\s]+$/, ''), browser })
|
|
207
231
|
: t('TEST BROWSER stays off: MADRE could not install its browser server ({problem}). Check your internet connection and turn it on again.', { problem: String(check.problem).replace(/[.\s]+$/, '') }), code: 'MU-054' } };
|
|
@@ -231,8 +255,9 @@ export default defineModule({
|
|
|
231
255
|
},
|
|
232
256
|
],
|
|
233
257
|
async status(ctx) {
|
|
234
|
-
const
|
|
235
|
-
const
|
|
258
|
+
const env = await playwrightEnv(ctx);
|
|
259
|
+
const version = await playwrightVersion({ env, projectRoot: ctx.projectRoot });
|
|
260
|
+
const health = ctx.settings.enabled && version ? playwrightHealth({ browser: ctx.settings.browser ?? 'chromium', env, cwd: ctx.projectRoot }) : null;
|
|
236
261
|
return {
|
|
237
262
|
runs: [{ name: PLAYWRIGHT_PACKAGE, version }],
|
|
238
263
|
settings: { browser: ctx.settings.browser ?? 'chromium', headless: ctx.settings.headless !== false },
|
|
@@ -247,25 +272,29 @@ export default defineModule({
|
|
|
247
272
|
// where `npx --no` looks for it at turn time without downloading anything.
|
|
248
273
|
async updatePlan(ctx, { latest = null } = {}) {
|
|
249
274
|
const target = latest ? `${PLAYWRIGHT_PACKAGE}@${latest}` : PLAYWRIGHT_PACKAGE;
|
|
275
|
+
// Kept in MADRE's own folder, it is updated there.
|
|
276
|
+
const prefix = (await playwrightEnv(ctx)).npm_config_prefix;
|
|
277
|
+
const where = prefix ? ['--prefix', prefix] : [];
|
|
250
278
|
return {
|
|
251
279
|
command: 'npm',
|
|
252
|
-
args: ['install', '-g', target],
|
|
253
|
-
display: `npm install -g ${target}`,
|
|
280
|
+
args: ['install', '-g', ...where, target],
|
|
281
|
+
display: `npm install -g ${[...where, target].join(' ')}`,
|
|
254
282
|
note: 'Installs the browser server for every project on this computer. A browser itself may still be missing; the card says so if it is.',
|
|
255
|
-
after: async () => { await playwrightVersion({ env: ctx
|
|
283
|
+
after: async () => { await playwrightVersion({ env: await playwrightEnv(ctx), projectRoot: ctx.projectRoot, fresh: true }); },
|
|
256
284
|
};
|
|
257
285
|
},
|
|
258
286
|
async toolsForTurn(ctx, turn) {
|
|
259
|
-
|
|
287
|
+
const env = await playwrightEnv(ctx);
|
|
288
|
+
if (!(await playwrightVersion({ env, projectRoot: ctx.projectRoot }))) return [];
|
|
260
289
|
if (turn.mode === 0) return []; // a ghost turn leaves no screenshots and opens no browser
|
|
261
290
|
// Only for a turn that asks for what a browser does. Its tool list goes into every call the CLI
|
|
262
291
|
// makes inside the turn: a one-line change cost Codex 576 thousand tokens of reading, and the
|
|
263
292
|
// browser it carried was never opened.
|
|
264
293
|
if (turn.text !== undefined && !wantsBrowser(turn.text)) return [];
|
|
265
294
|
// A browser known not to start is not handed to anyone: every call to it would fail.
|
|
266
|
-
if (playwrightHealth({ browser: ctx.settings.browser ?? 'chromium', env
|
|
295
|
+
if (playwrightHealth({ browser: ctx.settings.browser ?? 'chromium', env, cwd: ctx.projectRoot })?.ok === false) return [];
|
|
267
296
|
const outputDir = turn.scratchDir ?? join(turn.roomDir ?? ctx.stateRoot, 'playwright');
|
|
268
|
-
return [playwrightServerFor({ port: turn.port, outputDir, browser: ctx.settings.browser ?? 'chromium', headless: ctx.settings.headless !== false, servers: turn.servers ?? [] })];
|
|
297
|
+
return [playwrightServerFor({ port: turn.port, outputDir, browser: ctx.settings.browser ?? 'chromium', headless: ctx.settings.headless !== false, servers: turn.servers ?? [], preview: turn.preview ?? '/preview', prefix: env.npm_config_prefix ?? null })];
|
|
269
298
|
},
|
|
270
299
|
// Before it turns on, in one project or in all: the server starts and has its browser, or MADRE
|
|
271
300
|
// fetches what is missing and asks again. `null` is ready; anything else is the refusal.
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
2
|
+
// MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
|
|
3
|
+
// One call into a human module. The parent starts this file with Node's permission model:
|
|
4
|
+
// the module can read its own file and MADRE's SDK, but cannot read other files, write or spawn.
|
|
5
|
+
// The only way back into MADRE is a named ctx method answered by the parent.
|
|
6
|
+
import { createInterface } from 'node:readline';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
import { setLanguage, t } from '../i18n.mjs';
|
|
9
|
+
import { defineModule } from './sdk.mjs';
|
|
10
|
+
|
|
11
|
+
const wire = (value) => process.stdout.write(`\n${JSON.stringify({ madreModule: true, ...value })}\n`);
|
|
12
|
+
const pending = new Map();
|
|
13
|
+
let sequence = 0;
|
|
14
|
+
const ask = (method, args = []) => new Promise((resolve, reject) => {
|
|
15
|
+
const id = ++sequence;
|
|
16
|
+
pending.set(id, { resolve, reject });
|
|
17
|
+
wire({ type: 'ctx', id, method, args });
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
function context(input = {}) {
|
|
21
|
+
const ctx = {
|
|
22
|
+
projectRoot: input.projectRoot,
|
|
23
|
+
stateRoot: input.stateRoot,
|
|
24
|
+
roomId: input.roomId,
|
|
25
|
+
chat: input.chat,
|
|
26
|
+
config: input.config ?? {},
|
|
27
|
+
settings: input.settings ?? {},
|
|
28
|
+
env: {},
|
|
29
|
+
agents: input.agents ?? [],
|
|
30
|
+
language: input.language ?? 'en',
|
|
31
|
+
t,
|
|
32
|
+
readConfig: () => ask('readConfig'),
|
|
33
|
+
updateConfig: (patch) => ask('updateConfig', [patch]),
|
|
34
|
+
record: (type, payload) => ask('record', [type, payload]),
|
|
35
|
+
vault: {
|
|
36
|
+
get: (name) => ask('vault.get', [name]),
|
|
37
|
+
held: () => ask('vault.held'),
|
|
38
|
+
keep: (name, value) => ask('vault.keep', [name, value]),
|
|
39
|
+
forget: (name) => ask('vault.forget', [name]),
|
|
40
|
+
},
|
|
41
|
+
services: {
|
|
42
|
+
history: (range) => ask('services.history', [range]),
|
|
43
|
+
ollama: {
|
|
44
|
+
state: () => input.ollamaState ?? null,
|
|
45
|
+
generate: (request) => ask('services.ollama.generate', [request]),
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
room: input.hasRoom ? {
|
|
49
|
+
capabilities: () => input.capabilities ?? null,
|
|
50
|
+
runningTurn: (id) => id === input.turnId ? input.runningTurn ?? null : null,
|
|
51
|
+
record: (type, payload) => ask('room.record', [type, payload]),
|
|
52
|
+
} : null,
|
|
53
|
+
};
|
|
54
|
+
return ctx;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function invoke(message) {
|
|
58
|
+
setLanguage(message.ctx?.language ?? 'en');
|
|
59
|
+
// The parent owns the log file. A hook may reach the network only when its module declared
|
|
60
|
+
// a destination; every fetch it makes is reported without a body, header or query value.
|
|
61
|
+
const fetchImpl = globalThis.fetch;
|
|
62
|
+
globalThis.fetch = async (resource, init = {}) => {
|
|
63
|
+
const url = typeof resource === 'string' ? resource : (resource?.url ?? String(resource));
|
|
64
|
+
const method = init?.method ?? resource?.method ?? 'GET';
|
|
65
|
+
const bytes = typeof init?.body === 'string' ? Buffer.byteLength(init.body) : null;
|
|
66
|
+
const started = Date.now();
|
|
67
|
+
try {
|
|
68
|
+
const response = await fetchImpl(resource, init);
|
|
69
|
+
await ask('outbound.record', [{ url, method, bytes, status: response?.status ?? null, ok: Boolean(response?.ok), ms: Date.now() - started }]).catch(() => null);
|
|
70
|
+
return response;
|
|
71
|
+
} catch (error) {
|
|
72
|
+
await ask('outbound.record', [{ url, method, bytes, ok: false, ms: Date.now() - started, error: error?.code ?? error?.name ?? 'failed' }]).catch(() => null);
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const file = process.argv[2];
|
|
77
|
+
const loaded = await import(pathToFileURL(file).href);
|
|
78
|
+
let spec = loaded.default ?? loaded.module ?? null;
|
|
79
|
+
if (typeof spec === 'function') spec = await spec({ defineModule });
|
|
80
|
+
if (!spec || typeof spec !== 'object') throw new Error('the default export must be a module spec object');
|
|
81
|
+
const module = typeof spec.describe === 'function' ? spec : defineModule(spec);
|
|
82
|
+
if (module.id !== message.expectedId) throw new Error('the module changed its id after it was checked');
|
|
83
|
+
const ctx = context(message.ctx);
|
|
84
|
+
const args = message.args ?? [];
|
|
85
|
+
if (message.operation === 'route') {
|
|
86
|
+
const route = module.routes?.[message.index];
|
|
87
|
+
if (typeof route?.handler !== 'function') throw new Error('the route has no handler');
|
|
88
|
+
const request = args[0] ?? {};
|
|
89
|
+
return route.handler(ctx, { ...request, request: { method: request.method, headers: request.headers }, url: request.url ? new URL(request.url) : null });
|
|
90
|
+
}
|
|
91
|
+
if (message.operation === 'slash' || message.operation === 'available') {
|
|
92
|
+
const command = module.slash?.[message.index];
|
|
93
|
+
const fn = command?.[message.operation === 'slash' ? 'execute' : 'available'];
|
|
94
|
+
if (typeof fn !== 'function') throw new Error('the command has no such hook');
|
|
95
|
+
return fn(ctx, ...args);
|
|
96
|
+
}
|
|
97
|
+
const fn = module[message.operation];
|
|
98
|
+
if (typeof fn !== 'function') throw new Error(`the module has no ${message.operation} hook`);
|
|
99
|
+
if (['detect', 'preflight', 'installCommand'].includes(message.operation)) return fn.call(module, ...args);
|
|
100
|
+
if (message.operation === 'describe') return fn.call({ ...module, external: true, file }, ctx);
|
|
101
|
+
return fn.call(module, ctx, ...args);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
105
|
+
lines.on('line', (line) => {
|
|
106
|
+
let message;
|
|
107
|
+
try { message = JSON.parse(line); } catch { return; }
|
|
108
|
+
if (!message?.madreModule) return;
|
|
109
|
+
if (message.type === 'ctxResult') {
|
|
110
|
+
const waiting = pending.get(message.id);
|
|
111
|
+
if (!waiting) return;
|
|
112
|
+
pending.delete(message.id);
|
|
113
|
+
if (message.ok) waiting.resolve(message.value);
|
|
114
|
+
else waiting.reject(new Error(message.error ?? 'MADRE refused the call'));
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (message.type !== 'invoke') return;
|
|
118
|
+
void invoke(message).then(
|
|
119
|
+
(value) => wire({ type: 'done', ok: true, value }),
|
|
120
|
+
(error) => wire({ type: 'done', ok: false, error: String(error?.message ?? error), code: error?.code ?? null }),
|
|
121
|
+
).finally(() => { lines.close(); process.stdin.pause(); });
|
|
122
|
+
});
|
package/src/modules/runs.mjs
CHANGED
|
@@ -12,8 +12,9 @@
|
|
|
12
12
|
// command sends off this machine does not come back with UNDO, and the button says what it runs
|
|
13
13
|
// before it is pressed.
|
|
14
14
|
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
15
|
+
// Always on, as image generation is (2026-11-06, the author): asking for a command is part of how
|
|
16
|
+
// an agent works in MADRE. The instruction still rides in every prompt below AIRLOCK, measured in
|
|
17
|
+
// the economy as `runs`.
|
|
17
18
|
|
|
18
19
|
import { defineModule } from './sdk.mjs';
|
|
19
20
|
import { t } from '../i18n.mjs';
|
|
@@ -24,13 +25,15 @@ export default defineModule({
|
|
|
24
25
|
name: 'Commands',
|
|
25
26
|
vendor: 'MADRE',
|
|
26
27
|
version: '1.0.0',
|
|
27
|
-
summary: 'Lets an agent ask you to run a command it cannot run in its mode (tests, a build, a linter). Each command is a button: nothing runs until you press it, it runs from the project root with no shell, a restore point is taken first, and when it has run the output goes back to the agent that asked, which goes on.
|
|
28
|
-
creates: ['nothing in the project'
|
|
29
|
-
|
|
28
|
+
summary: 'Lets an agent ask you to run a command it cannot run in its mode (tests, a build, a linter). Each command is a button: nothing runs until you press it, it runs from the project root with no shell, a restore point is taken first, and when it has run the output goes back to the agent that asked, which goes on. Always on: about 300 tokens of instruction per turn below FULL ACCESS.',
|
|
29
|
+
creates: ['nothing in the project'],
|
|
30
|
+
card: 'fixed',
|
|
31
|
+
async status() {
|
|
30
32
|
return {
|
|
31
|
-
status: { installed:
|
|
32
|
-
install: { display:
|
|
33
|
+
status: { installed: true, detail: t('on · agents may ask you to run commands') },
|
|
34
|
+
install: { display: 'always on', platforms: [] },
|
|
35
|
+
fixed: true,
|
|
33
36
|
};
|
|
34
37
|
},
|
|
35
|
-
async
|
|
38
|
+
async toggle() { return { status: 405, body: { error: 'Commands has no switch: it is always on.' } }; },
|
|
36
39
|
});
|
package/src/modules/sdk.mjs
CHANGED
|
@@ -202,7 +202,9 @@ export function defineModule(spec) {
|
|
|
202
202
|
};
|
|
203
203
|
// A project reads its own word on `enabled` when it said one (module-scope.mjs).
|
|
204
204
|
const settingsFrom = (config, roomId = null) => ({ ...defaults, ...settingsIn(config?.modules?.[configKey] ?? {}, roomId) });
|
|
205
|
-
|
|
205
|
+
// A module running in a separate process receives a mediated vault. Never replace it with
|
|
206
|
+
// direct filesystem access: only the parent may open its credential file.
|
|
207
|
+
const mine = (ctx, settings) => ({ ...ctx, settings, vault: ctx.vault ?? vaultFor(spec.id, ctx.stateRoot) });
|
|
206
208
|
const scopeHere = (ctx) => {
|
|
207
209
|
const block = ctx.config?.modules?.[configKey] ?? {};
|
|
208
210
|
const own = ctx.roomId ? roomsOf(block)[ctx.roomId] : undefined;
|
|
@@ -260,7 +262,7 @@ export function defineModule(spec) {
|
|
|
260
262
|
canUpdate: Boolean(spec.updatePlan),
|
|
261
263
|
controls: base.controls.map((control) => ({ ...control, value: settings[control.key] ?? null })),
|
|
262
264
|
// What is in the vault for this module: names and lengths, never values.
|
|
263
|
-
...(base.secrets.length ? { held: await vaultSummary(ctx.stateRoot, spec.id).catch(() => []) } : {}),
|
|
265
|
+
...(base.secrets.length ? { held: await (ctx.vault?.held?.() ?? vaultSummary(ctx.stateRoot, spec.id)).catch(() => []) } : {}),
|
|
264
266
|
ships: this.external ? null : await madreRelease(),
|
|
265
267
|
runs,
|
|
266
268
|
status: own.status ?? { installed, detail: own.detail ?? (installed ? 'on' : 'off') },
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
2
|
+
// MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
|
|
3
|
+
// The public half of the key of the author's notices (scripts/notices-key.mjs, Q-11). Each notice
|
|
4
|
+
// madre.run serves is signed with the private half, which lives only on the author's computer; a
|
|
5
|
+
// notice this key does not verify is never shown (src/notices.mjs). Null: no notice is ever shown.
|
|
6
|
+
export const NOTICES_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
|
7
|
+
MCowBQYDK2VwAyEAPrOpPloPi1CDsCGRjnZNNMEH0AaD1c3sRsLjuXt9FVQ=
|
|
8
|
+
-----END PUBLIC KEY-----`;
|
package/src/notices.mjs
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
2
|
+
// MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
|
|
3
|
+
// THE AUTHOR'S NOTICES (Q-11, 2026-11-06). What the author writes from the MADRE run from source
|
|
4
|
+
// («a version with a security fix is out», «if you use WSL, update») reaches every copy that is on,
|
|
5
|
+
// with or without the anonymous diagnostics, and without «Look for new versions».
|
|
6
|
+
//
|
|
7
|
+
// A notice is signed on the author's computer, with a key only the author holds (scripts/
|
|
8
|
+
// notices-key.mjs); madre.run keeps and serves it (functions/api/avisos.js of the landing) but cannot
|
|
9
|
+
// make one up or change a word of it: a notice whose signature the key in src/notices-key.mjs does
|
|
10
|
+
// not verify is never shown. The worst madre.run can do is not serve one.
|
|
11
|
+
//
|
|
12
|
+
// What a copy asks: GET madre.run/api/avisos, with nothing about the person, not even its version.
|
|
13
|
+
// It decides by itself which notices are for it (its version, its system), and remembers which ones
|
|
14
|
+
// it showed. At most every 15 minutes per computer, however many projects are open.
|
|
15
|
+
//
|
|
16
|
+
// Levels: «info» and «important» can be turned off (Settings › Version); «security» always shows.
|
|
17
|
+
|
|
18
|
+
import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
|
|
19
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
import { NOTICES_PUBLIC_KEY } from './notices-key.mjs';
|
|
22
|
+
import { compareVersions } from './updates.mjs';
|
|
23
|
+
|
|
24
|
+
export const NOTICES_URL = 'https://madre.run/api/avisos';
|
|
25
|
+
export const noticesUrl = (env = process.env) => env.PULSE_NOTICES_URL || NOTICES_URL;
|
|
26
|
+
export const noticesOn = (env = process.env) => env.PULSE_NOTICES !== '0';
|
|
27
|
+
export const LEVELS = ['info', 'important', 'security'];
|
|
28
|
+
export const SYSTEMS = ['darwin', 'linux', 'win32', 'wsl'];
|
|
29
|
+
const ID = /^[a-z0-9][a-z0-9-]{2,39}$/;
|
|
30
|
+
const VERSION = /^\d{1,3}\.\d{1,3}\.\d{1,4}$/;
|
|
31
|
+
const SIG = /^[A-Za-z0-9+/]{40,120}={0,2}$/;
|
|
32
|
+
export const TITLE_MAX = 80;
|
|
33
|
+
export const BODY_MAX = 400;
|
|
34
|
+
const LONGEST_MS = 90 * 86_400_000;
|
|
35
|
+
const FRESH_MS = 15 * 60_000;
|
|
36
|
+
const TIMEOUT_MS = 8000;
|
|
37
|
+
const MAX_FEED = 64 * 1024;
|
|
38
|
+
|
|
39
|
+
const folder = (stateRoot) => join(stateRoot, 'avisos');
|
|
40
|
+
const readJson = (file) => readFile(file, 'utf8').then((raw) => JSON.parse(raw)).catch(() => null);
|
|
41
|
+
async function writeAtomic(file, data) {
|
|
42
|
+
const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
43
|
+
await writeFile(temp, data);
|
|
44
|
+
await rename(temp, file);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Only text, short, in both languages; a link only to madre.run. Anything else is not a notice.
|
|
48
|
+
const words = (value, max) => (typeof value === 'string' ? value.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').trim() : '');
|
|
49
|
+
function pair(value, max) {
|
|
50
|
+
if (!value || typeof value !== 'object') return null;
|
|
51
|
+
const es = words(value.es, max);
|
|
52
|
+
const en = words(value.en, max);
|
|
53
|
+
if (!es || !en || es.length > max || en.length > max) return null;
|
|
54
|
+
return { es, en };
|
|
55
|
+
}
|
|
56
|
+
export function readNotice(raw) {
|
|
57
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
58
|
+
const id = typeof raw.id === 'string' ? raw.id : '';
|
|
59
|
+
if (!ID.test(id) || !LEVELS.includes(raw.level)) return null;
|
|
60
|
+
const title = pair(raw.title, TITLE_MAX);
|
|
61
|
+
const body = pair(raw.body, BODY_MAX);
|
|
62
|
+
if (!title || !body) return null;
|
|
63
|
+
const from = Date.parse(raw.from);
|
|
64
|
+
const until = Date.parse(raw.until);
|
|
65
|
+
if (!Number.isFinite(from) || !Number.isFinite(until) || until <= from || until - from > LONGEST_MS) return null;
|
|
66
|
+
let link = null;
|
|
67
|
+
if (raw.link !== undefined && raw.link !== null && raw.link !== '') {
|
|
68
|
+
try {
|
|
69
|
+
const url = new URL(String(raw.link));
|
|
70
|
+
if (url.protocol !== 'https:' || url.hostname !== 'madre.run' || url.username || url.password) return null;
|
|
71
|
+
link = url.href;
|
|
72
|
+
} catch { return null; }
|
|
73
|
+
}
|
|
74
|
+
const to = raw.to && typeof raw.to === 'object' ? raw.to : {};
|
|
75
|
+
const min = to.min ? String(to.min) : null;
|
|
76
|
+
const max = to.max ? String(to.max) : null;
|
|
77
|
+
if ((min && !VERSION.test(min)) || (max && !VERSION.test(max))) return null;
|
|
78
|
+
const os = Array.isArray(to.os) ? to.os.filter((one) => SYSTEMS.includes(one)) : [];
|
|
79
|
+
if (Array.isArray(to.os) && os.length !== to.os.length) return null;
|
|
80
|
+
return { id, level: raw.level, title, body, link, to: { min, max, os }, from: new Date(from).toISOString(), until: new Date(until).toISOString() };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// The exact bytes signed: the notice read as above, its keys in this order, nothing else. A field
|
|
84
|
+
// added on the way (or one taken out) changes the bytes, and the signature no longer holds.
|
|
85
|
+
export const noticeBytes = (notice) => Buffer.from(JSON.stringify({
|
|
86
|
+
id: notice.id, level: notice.level, title: { es: notice.title.es, en: notice.title.en }, body: { es: notice.body.es, en: notice.body.en },
|
|
87
|
+
link: notice.link ?? null, to: { min: notice.to?.min ?? null, max: notice.to?.max ?? null, os: [...(notice.to?.os ?? [])] }, from: notice.from, until: notice.until,
|
|
88
|
+
}));
|
|
89
|
+
const retireBytes = (id) => Buffer.from(`madre-notice-retire:${id}`);
|
|
90
|
+
|
|
91
|
+
function checks(bytes, signature, publicKey) {
|
|
92
|
+
if (!publicKey || typeof signature !== 'string' || !SIG.test(signature)) return false;
|
|
93
|
+
try { return verify(null, bytes, createPublicKey(publicKey), Buffer.from(signature, 'base64')); } catch { return false; }
|
|
94
|
+
}
|
|
95
|
+
// One served entry, checked: `{ notice, sig }`, read and verified, or null.
|
|
96
|
+
export function verifiedNotice(entry, publicKey = NOTICES_PUBLIC_KEY) {
|
|
97
|
+
const notice = readNotice(entry?.notice);
|
|
98
|
+
if (!notice || !checks(noticeBytes(notice), entry.sig, publicKey)) return null;
|
|
99
|
+
return notice;
|
|
100
|
+
}
|
|
101
|
+
export const verifiedRetire = (entry, publicKey = NOTICES_PUBLIC_KEY) => (ID.test(entry?.id ?? '') && checks(retireBytes(entry.id), entry.sig, publicKey) ? entry.id : null);
|
|
102
|
+
|
|
103
|
+
// On the author's computer only: the signatures madre.run will keep.
|
|
104
|
+
export function signNotice(raw, privateKeyPem) {
|
|
105
|
+
const notice = readNotice(raw);
|
|
106
|
+
if (!notice) throw new Error('That is not a notice MADRE would show: check the words, the dates and the link.');
|
|
107
|
+
return { notice, sig: sign(null, noticeBytes(notice), createPrivateKey(privateKeyPem)).toString('base64') };
|
|
108
|
+
}
|
|
109
|
+
export const signRetire = (id, privateKeyPem) => {
|
|
110
|
+
if (!ID.test(String(id))) throw new Error('No such notice.');
|
|
111
|
+
return { id, sig: sign(null, retireBytes(id), createPrivateKey(privateKeyPem)).toString('base64') };
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
// Whether a notice is for this copy, now.
|
|
115
|
+
export function appliesTo(notice, { version, platform = process.platform, wsl = false, now = Date.now() }) {
|
|
116
|
+
if (now < Date.parse(notice.from) || now >= Date.parse(notice.until)) return false;
|
|
117
|
+
if (notice.to.min && compareVersions(version, notice.to.min) < 0) return false;
|
|
118
|
+
if (notice.to.max && compareVersions(version, notice.to.max) > 0) return false;
|
|
119
|
+
if (notice.to.os.length) {
|
|
120
|
+
const here = wsl ? 'wsl' : platform;
|
|
121
|
+
if (!notice.to.os.includes(here)) return false;
|
|
122
|
+
}
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// The feed as madre.run serves it, checked one by one: the notices whose signatures hold, minus the
|
|
127
|
+
// ones the author retired with a signature of their own.
|
|
128
|
+
export function readFeed(data, publicKey = NOTICES_PUBLIC_KEY) {
|
|
129
|
+
const retired = new Set((Array.isArray(data?.retired) ? data.retired : []).map((entry) => verifiedRetire(entry, publicKey)).filter(Boolean));
|
|
130
|
+
const kept = [];
|
|
131
|
+
for (const entry of Array.isArray(data?.notices) ? data.notices.slice(0, 50) : []) {
|
|
132
|
+
const notice = verifiedNotice(entry, publicKey);
|
|
133
|
+
if (notice && !retired.has(notice.id) && !kept.some((one) => one.notice.id === notice.id)) kept.push({ notice: entry.notice, sig: entry.sig });
|
|
134
|
+
}
|
|
135
|
+
return { entries: kept, retired: [...retired] };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Asked of madre.run at most every 15 minutes per computer; what was verified is kept, so a copy
|
|
139
|
+
// offline still shows what it knew, until it expires.
|
|
140
|
+
export async function refreshNotices({ stateRoot, env = process.env, fetchImpl = globalThis.fetch, publicKey = NOTICES_PUBLIC_KEY, force = false, now = Date.now } = {}) {
|
|
141
|
+
if (!noticesOn(env) || !publicKey) return { fresh: false, off: true };
|
|
142
|
+
const dir = folder(stateRoot);
|
|
143
|
+
const state = (await readJson(join(dir, 'state.json'))) ?? {};
|
|
144
|
+
if (!force && state.checkedAt && now() - Date.parse(state.checkedAt) < FRESH_MS) return { fresh: false };
|
|
145
|
+
await mkdir(dir, { recursive: true }).catch(() => {});
|
|
146
|
+
// Said as checked before asking: another process of this computer that asks meanwhile waits its turn.
|
|
147
|
+
await writeAtomic(join(dir, 'state.json'), JSON.stringify({ ...state, checkedAt: new Date(now()).toISOString() }, null, 2)).catch(() => {});
|
|
148
|
+
try {
|
|
149
|
+
const answer = await fetchImpl(noticesUrl(env), { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
150
|
+
if (!answer.ok) throw new Error(`HTTP ${answer.status}`);
|
|
151
|
+
const text = await answer.text();
|
|
152
|
+
if (text.length > MAX_FEED) throw new Error('too large');
|
|
153
|
+
const feed = readFeed(JSON.parse(text), publicKey);
|
|
154
|
+
await writeAtomic(join(dir, 'kept.json'), JSON.stringify(feed, null, 2));
|
|
155
|
+
await writeAtomic(join(dir, 'state.json'), JSON.stringify({ checkedAt: new Date(now()).toISOString(), count: feed.entries.length }, null, 2));
|
|
156
|
+
return { fresh: true, count: feed.entries.length };
|
|
157
|
+
} catch (error) {
|
|
158
|
+
await writeAtomic(join(dir, 'state.json'), JSON.stringify({ checkedAt: new Date(now()).toISOString(), failed: String(error?.name === 'TimeoutError' ? 'timeout' : error?.message ?? error).slice(0, 120) }, null, 2)).catch(() => {});
|
|
159
|
+
return { fresh: false, error: true };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// What this copy shows now: kept, checked again, for it, and on unless it is a security notice.
|
|
164
|
+
export async function currentNotices({ stateRoot, version, platform = process.platform, wsl = false, enabled = true, publicKey = NOTICES_PUBLIC_KEY, now = Date.now() } = {}) {
|
|
165
|
+
const kept = (await readJson(join(folder(stateRoot), 'kept.json'))) ?? {};
|
|
166
|
+
const seen = new Set((await readJson(join(folder(stateRoot), 'seen.json'))) ?? []);
|
|
167
|
+
const { entries } = readFeed({ notices: kept.entries, retired: [] }, publicKey);
|
|
168
|
+
const retired = new Set(Array.isArray(kept.retired) ? kept.retired : []);
|
|
169
|
+
return entries
|
|
170
|
+
.map((entry) => readNotice(entry.notice))
|
|
171
|
+
.filter((notice) => notice && !retired.has(notice.id) && appliesTo(notice, { version, platform, wsl, now }) && (enabled || notice.level === 'security'))
|
|
172
|
+
.sort((a, b) => LEVELS.indexOf(b.level) - LEVELS.indexOf(a.level) || b.from.localeCompare(a.from))
|
|
173
|
+
.map((notice) => ({ ...notice, seen: seen.has(notice.id) }));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// «Got it»: this computer does not show it again.
|
|
177
|
+
export async function noticeSeen(stateRoot, id) {
|
|
178
|
+
if (!ID.test(String(id))) return false;
|
|
179
|
+
const file = join(folder(stateRoot), 'seen.json');
|
|
180
|
+
const seen = new Set((await readJson(file)) ?? []);
|
|
181
|
+
seen.add(id);
|
|
182
|
+
await mkdir(folder(stateRoot), { recursive: true });
|
|
183
|
+
await writeAtomic(file, JSON.stringify([...seen].slice(-200)));
|
|
184
|
+
return true;
|
|
185
|
+
}
|