@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.
- package/CHANGELOG.en.md +40 -1
- package/CHANGELOG.md +40 -1
- package/README.en.md +3 -3
- package/README.md +3 -3
- package/SECURITY.md +11 -6
- package/TRADEMARKS.md +6 -2
- package/bin/madre.mjs +76 -11
- package/docs/REFERENCE.md +16 -10
- package/docs/SDK.md +36 -9
- package/docs/en/REFERENCE.md +12 -8
- package/docs/en/SDK.md +34 -8
- package/docs/en/training/README.md +1 -1
- package/docs/sdk/connector-module.mjs +1 -1
- package/docs/sdk/hello-module.mjs +39 -4
- package/docs/training/README.md +1 -1
- package/docs/training/train.sh +3 -0
- package/habilidades/explicamelo-facil/HABILIDAD.md +19 -0
- package/habilidades/hojas-de-calculo/HABILIDAD.md +18 -0
- package/habilidades/mensajes-a-clientes/HABILIDAD.md +19 -0
- package/habilidades/publicaciones-para-redes/HABILIDAD.md +19 -0
- package/habilidades/resumen-y-pendientes/HABILIDAD.md +18 -0
- package/habilidades/tu-pagina-paso-a-paso/HABILIDAD.md +19 -0
- package/package.json +7 -4
- package/public/activity.js +66 -22
- package/public/app.js +4947 -894
- package/public/assets/brand/OFL-SpaceGrotesk.txt +93 -0
- package/public/assets/brand/SpaceGrotesk-latin-ext.woff2 +0 -0
- package/public/assets/brand/SpaceGrotesk-latin.woff2 +0 -0
- package/public/assets/brand/madre-app-180.png +0 -0
- package/public/assets/brand/madre-app-192.png +0 -0
- package/public/assets/brand/madre-app-512.png +0 -0
- package/public/assets/brand/madre-app.svg +1 -1
- package/public/assets/brand/madre-favicon.svg +1 -1
- package/public/attribution.js +29 -19
- package/public/auto-open.js +102 -0
- package/public/brands.js +36 -19
- package/public/changes.js +63 -0
- package/public/en.js +1085 -102
- package/public/es.js +2940 -1656
- package/public/i18n.js +11 -0
- package/public/index.html +31 -27
- package/public/loader.js +322 -117
- package/public/macroverso.js +57 -355
- package/public/manual-content.js +69 -9
- package/public/manual.js +21 -6
- package/public/market-view.js +298 -84
- package/public/market.js +25 -2
- package/public/mcp-catalog.js +7 -2
- package/public/missions.js +169 -0
- package/public/news-scenes.js +292 -0
- package/public/nostromo-engine.js +935 -654
- package/public/notices.js +78 -0
- package/public/notifications.js +119 -0
- package/public/power.js +1 -1
- package/public/provider-marks.js +170 -0
- package/public/provider-pick.js +147 -0
- package/public/resay.js +4 -0
- package/public/review-ask.js +16 -13
- package/public/routing.js +29 -3
- package/public/salas-mac.css +467 -47
- package/public/salas-mac.html +8 -5
- package/public/salas-mac.js +805 -109
- package/public/salas.css +2 -2
- package/public/salas.html +2 -2
- package/public/salas.js +1 -1
- package/public/starters.js +128 -0
- package/public/styles.css +3036 -340
- package/public/subscription.js +303 -0
- package/public/terms-field.js +170 -0
- package/public/terms.js +117 -19
- package/public/tips.js +158 -0
- package/public/tour-chapters.js +88 -88
- package/public/tour.js +364 -46
- package/public/troubleshooting.js +313 -27
- package/public/welcome-scene.js +446 -0
- package/public/welcome.js +827 -282
- package/src/adapters/claude.mjs +2 -1
- package/src/adapters/codex.mjs +2 -1
- package/src/adapters/cursor.mjs +9 -6
- package/src/adapters/gemini-rest.mjs +236 -0
- package/src/adapters/gemini.mjs +13 -7
- package/src/adapters/grok.mjs +290 -0
- package/src/adapters/madre.mjs +71 -23
- package/src/adapters/opencode.mjs +15 -2
- package/src/adapters/process.mjs +14 -3
- package/src/adapters/steps.mjs +176 -0
- package/src/app-invite.mjs +90 -0
- package/src/auth-probe.mjs +32 -0
- package/src/billing-key.mjs +8 -0
- package/src/billing.mjs +317 -0
- package/src/bridge/policy.mjs +1 -1
- package/src/capabilities.mjs +46 -10
- package/src/chats.mjs +44 -2
- package/src/checkpoint.mjs +119 -1
- package/src/codex-route.mjs +113 -0
- package/src/commands.mjs +5 -2
- package/src/credentials.mjs +46 -8
- package/src/dataset.mjs +18 -7
- package/src/directives.mjs +1 -0
- package/src/event-store.mjs +25 -2
- package/src/extensions.mjs +5 -1
- package/src/ficha.mjs +158 -0
- package/src/files.mjs +36 -2
- package/src/image-studio.mjs +13 -3
- package/src/install-metrics.mjs +9 -3
- package/src/lease.mjs +6 -1
- package/src/looks.mjs +4 -1
- package/src/market-check.mjs +1 -1
- package/src/market-remote.mjs +135 -1
- package/src/mcp/image-server.mjs +59 -90
- 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 +10 -4
- 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/github.mjs +6 -2
- package/src/modules/helpers.mjs +23 -5
- package/src/modules/image-providers.mjs +281 -0
- package/src/modules/image-studio.mjs +106 -39
- package/src/modules/index.mjs +61 -12
- package/src/modules/intents-observe.mjs +3 -1
- package/src/modules/isolated.mjs +160 -0
- package/src/modules/ollama.mjs +35 -6
- package/src/modules/playwright.mjs +78 -20
- package/src/modules/reminders.mjs +42 -2
- package/src/modules/ripley.mjs +2 -1
- package/src/modules/run-alone.mjs +122 -0
- package/src/modules/runs.mjs +11 -8
- package/src/modules/sdk.mjs +10 -3
- package/src/notices-key.mjs +8 -0
- package/src/notices.mjs +185 -0
- package/src/ollama.mjs +57 -15
- package/src/opencode-health.mjs +1 -1
- package/src/outbound.mjs +124 -13
- package/src/quota-sources.mjs +148 -3
- package/src/review-ask.mjs +55 -31
- package/src/room/archivist.mjs +30 -5
- package/src/room/busy.mjs +16 -0
- package/src/room/changes.mjs +79 -0
- package/src/room/control.mjs +36 -6
- package/src/room/economy.mjs +1 -1
- package/src/room/guard.mjs +39 -2
- package/src/room/prompt.mjs +49 -6
- package/src/room/vectors.mjs +7 -1
- package/src/room.mjs +181 -49
- package/src/router.mjs +1 -1
- package/src/runs.mjs +39 -0
- package/src/runtime-detection.mjs +46 -6
- package/src/salas.mjs +181 -18
- package/src/server.mjs +1101 -118
- package/src/service.mjs +116 -0
- package/src/setup-trouble.mjs +20 -1
- package/src/setup.mjs +1 -1
- package/src/skill-check.mjs +269 -0
- package/src/skills-import.mjs +128 -0
- package/src/skills.mjs +502 -0
- package/src/terms.mjs +23 -5
- package/src/tour.mjs +31 -5
- package/src/updates.mjs +47 -4
- package/src/web-preview.mjs +181 -0
- package/src/whats-new.mjs +121 -1
- package/src/rumbo.mjs +0 -337
|
@@ -169,6 +169,42 @@ export function nextOccurrence(due, repeat, after = new Date()) {
|
|
|
169
169
|
return next;
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
+
// A date said whole (2026-11-14, the author): «16 de noviembre», «20 de diciembre de 2026», «November 20»,
|
|
173
|
+
// «Nov 20, 2026», «2026-11-20», «el sábado 16». Without a year it is the next one to come: «3 de enero»
|
|
174
|
+
// said in November is next January. Before this, «16 de noviembre a las 10:30» was read as today at
|
|
175
|
+
// 10:30 and «20 de diciembre» as nothing at all.
|
|
176
|
+
const MONTHS = [
|
|
177
|
+
['enero', 'january', 'jan', 'ene'], ['febrero', 'february', 'feb'], ['marzo', 'march', 'mar'], ['abril', 'april', 'apr', 'abr'],
|
|
178
|
+
['mayo', 'may'], ['junio', 'june', 'jun'], ['julio', 'july', 'jul'], ['agosto', 'august', 'aug', 'ago'],
|
|
179
|
+
['septiembre', 'setiembre', 'september', 'sep', 'sept'], ['octubre', 'october', 'oct'], ['noviembre', 'november', 'nov'], ['diciembre', 'december', 'dec', 'dic'],
|
|
180
|
+
];
|
|
181
|
+
const monthIndex = (word) => MONTHS.findIndex((names) => names.includes(String(word ?? '').replace(/\.$/, '')));
|
|
182
|
+
const MONTH_WORDS = MONTHS.flat().sort((a, b) => b.length - a.length).join('|');
|
|
183
|
+
function exactDay(text, base) {
|
|
184
|
+
let year = null; let month = -1; let date = null;
|
|
185
|
+
const iso = text.match(/\b(\d{4})-(\d{2})-(\d{2})\b/);
|
|
186
|
+
const es = text.match(new RegExp(`\\b(\\d{1,2})\\s+de\\s+(${MONTH_WORDS})\\.?(?:\\s+(?:de|del)\\s+(\\d{4}))?\\b`));
|
|
187
|
+
const en = text.match(new RegExp(`\\b(${MONTH_WORDS})\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?\\b(?:,?\\s+(\\d{4})\\b)?`));
|
|
188
|
+
const enAfter = text.match(new RegExp(`\\b(\\d{1,2})(?:st|nd|rd|th)?\\s+(?:of\\s+)?(${MONTH_WORDS})\\b(?:,?\\s+(\\d{4})\\b)?`));
|
|
189
|
+
const numbered = text.match(new RegExp(`\\b(?:${DAY_WORDS})\\s+(\\d{1,2})\\b(?!\\s*(?::|am|pm|hrs|h\\b))`));
|
|
190
|
+
if (iso) { year = Number(iso[1]); month = Number(iso[2]) - 1; date = Number(iso[3]); }
|
|
191
|
+
else if (es && monthIndex(es[2]) >= 0) { date = Number(es[1]); month = monthIndex(es[2]); year = es[3] ? Number(es[3]) : null; }
|
|
192
|
+
else if (en && monthIndex(en[1]) >= 0) { date = Number(en[2]); month = monthIndex(en[1]); year = en[3] ? Number(en[3]) : null; }
|
|
193
|
+
else if (enAfter && monthIndex(enAfter[2]) >= 0) { date = Number(enAfter[1]); month = monthIndex(enAfter[2]); year = enAfter[3] ? Number(enAfter[3]) : null; }
|
|
194
|
+
else if (numbered) {
|
|
195
|
+
// «el sábado 16»: the next 16th, this month or the next.
|
|
196
|
+
date = Number(numbered[1]);
|
|
197
|
+
month = base.getMonth();
|
|
198
|
+
if (date < base.getDate()) month += 1;
|
|
199
|
+
} else return null;
|
|
200
|
+
if (month < 0 || date < 1 || date > 31) return null;
|
|
201
|
+
const today = at(base, 0);
|
|
202
|
+
let day = new Date(year ?? base.getFullYear(), month, date);
|
|
203
|
+
if (day.getDate() !== date) return null;
|
|
204
|
+
if (year === null && day < today) day = new Date(base.getFullYear() + 1, month, date);
|
|
205
|
+
return day;
|
|
206
|
+
}
|
|
207
|
+
|
|
172
208
|
// { due, repeat, said } for the words, or null when they say no time at all.
|
|
173
209
|
export function parseWhen(words, now = new Date(), { hour: dayHour = DEFAULT_HOUR } = {}) {
|
|
174
210
|
const text = fold(words);
|
|
@@ -193,8 +229,9 @@ export function parseWhen(words, now = new Date(), { hour: dayHour = DEFAULT_HOU
|
|
|
193
229
|
return { due: new Date(base.getTime() + amount * unit), repeat: null, said: relative[0] };
|
|
194
230
|
}
|
|
195
231
|
|
|
196
|
-
let day =
|
|
197
|
-
if (
|
|
232
|
+
let day = exactDay(text, base);
|
|
233
|
+
if (day) said.push('fecha');
|
|
234
|
+
else if (/\bpasado manana\b|\bday after tomorrow\b/.test(text)) { day = plusDays(base, 2); said.push('pasado mañana'); }
|
|
198
235
|
// «mañana» is tomorrow unless it is the morning: «la mañana», «de la mañana», «por la mañana».
|
|
199
236
|
else if (/(^|[^a-z])(manana)(?![a-z])/.test(text.replace(/\b(la|las|en la|por la|de la|cada|todas las)\s+manana(s)?\b/g, ' ')) || /\btomorrow\b/.test(text)) { day = plusDays(base, 1); said.push('mañana'); }
|
|
200
237
|
else if (/\b(hoy|today|tonight|esta tarde|esta noche|this afternoon)\b/.test(text)) { day = new Date(base); said.push('hoy'); }
|
|
@@ -469,6 +506,9 @@ export default {
|
|
|
469
506
|
summary: 'Notices what you say you still have to do, or what you ask for every day, and offers to remind you with one press. Reminders show in Home and in the project they came from. Read on your computer, with the local AI when you have it; no agent is asked.',
|
|
470
507
|
creates: ['nothing in the project', 'a reminders.json file in ~/.pulse, one for the whole computer'],
|
|
471
508
|
settings: { enabled: false, offer: true, habits: true, local: true, hour: '9', snooze: '60' },
|
|
509
|
+
// Its permission to speak through MADRE's notifications (2026-11-10): what it says and when. MADRE's
|
|
510
|
+
// page hands it to the system, if the person lets it (Settings › Notifications); it never does.
|
|
511
|
+
notifies: { label: 'A reminder falls due', note: 'At its hour, with what you asked to remember.' },
|
|
472
512
|
controls: [
|
|
473
513
|
{ key: 'offer', type: 'switch', label: 'Offer a reminder when you write something pending', note: 'A card under your message, with the time already chosen. Nothing is set without your click.' },
|
|
474
514
|
{ key: 'habits', type: 'switch', label: 'Notice what you ask for often', note: 'The same request on three different days is offered as a daily reminder.' },
|
package/src/modules/ripley.mjs
CHANGED
|
@@ -17,7 +17,8 @@ export default defineModule({
|
|
|
17
17
|
// RIPLEY's own because it is a separate promise: rendering a file from this project and opening
|
|
18
18
|
// an address on the internet are not the same permission, and bundling them would hide the
|
|
19
19
|
// second one behind the first.
|
|
20
|
-
|
|
20
|
+
// On from the start (2026-11-14, the author): pages are shown as pages unless the person turns it off.
|
|
21
|
+
settings: { enabled: true, web: false },
|
|
21
22
|
// No switch for the web, because the browser has no address bar to use it with. What it opens
|
|
22
23
|
// is the list of servers answering on this computer, and nothing else.
|
|
23
24
|
//
|
|
@@ -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
|
@@ -91,7 +91,7 @@ export const MODULE_FIELDS = new Set([
|
|
|
91
91
|
'requires', 'models', 'commands', 'card', 'configKey', 'settings', 'controls', 'routes', 'reaches',
|
|
92
92
|
'conditions', 'slash', 'status', 'preflight', 'detect', 'confirm', 'installCommand', 'secrets',
|
|
93
93
|
'updatePlan', 'toolsForTurn', 'toggle', 'onToggle', 'onSettings', 'onEvent', 'toggledEvent',
|
|
94
|
-
'toggledBody', 'describe', 'ready', 'footer', 'credit', 'sdk', 'icon',
|
|
94
|
+
'toggledBody', 'describe', 'ready', 'footer', 'credit', 'sdk', 'icon', 'notifies',
|
|
95
95
|
]);
|
|
96
96
|
export const unknownFields = (spec) => Object.keys(spec ?? {}).filter((key) => !MODULE_FIELDS.has(key));
|
|
97
97
|
|
|
@@ -159,6 +159,11 @@ export function defineModule(spec) {
|
|
|
159
159
|
icon: moduleIconOf(spec),
|
|
160
160
|
// Whose idea it was (2026-10-20, Reminders): said on its card and in the Market.
|
|
161
161
|
credit: typeof spec.credit === 'string' && spec.credit.trim() ? spec.credit.trim().slice(0, 80) : null,
|
|
162
|
+
// Its permission to speak through MADRE's notifications of the system (2026-11-10): what it says,
|
|
163
|
+
// in a line, and when. Without it a module has no way to the system at all (public/notifications.js).
|
|
164
|
+
notifies: spec.notifies && typeof spec.notifies.label === 'string' && spec.notifies.label.trim()
|
|
165
|
+
? { label: spec.notifies.label.trim().slice(0, 120), note: typeof spec.notifies.note === 'string' ? spec.notifies.note.trim().slice(0, 200) : null }
|
|
166
|
+
: null,
|
|
162
167
|
summary: oneWord(spec.summary) ?? '', creates: spec.creates ?? [], requires: spec.requires ?? [], models: spec.models ?? [], commands: spec.commands ?? (spec.slash?.length ? spec.slash.map((command) => command.usage ?? `/${command.name}`) : undefined),
|
|
163
168
|
card: spec.card ?? (kind === 'builtin' ? 'switch' : 'installer'),
|
|
164
169
|
// The settings floor of the card, declared instead of drawn: MADRE renders these and saves
|
|
@@ -202,7 +207,9 @@ export function defineModule(spec) {
|
|
|
202
207
|
};
|
|
203
208
|
// A project reads its own word on `enabled` when it said one (module-scope.mjs).
|
|
204
209
|
const settingsFrom = (config, roomId = null) => ({ ...defaults, ...settingsIn(config?.modules?.[configKey] ?? {}, roomId) });
|
|
205
|
-
|
|
210
|
+
// A module running in a separate process receives a mediated vault. Never replace it with
|
|
211
|
+
// direct filesystem access: only the parent may open its credential file.
|
|
212
|
+
const mine = (ctx, settings) => ({ ...ctx, settings, vault: ctx.vault ?? vaultFor(spec.id, ctx.stateRoot) });
|
|
206
213
|
const scopeHere = (ctx) => {
|
|
207
214
|
const block = ctx.config?.modules?.[configKey] ?? {};
|
|
208
215
|
const own = ctx.roomId ? roomsOf(block)[ctx.roomId] : undefined;
|
|
@@ -260,7 +267,7 @@ export function defineModule(spec) {
|
|
|
260
267
|
canUpdate: Boolean(spec.updatePlan),
|
|
261
268
|
controls: base.controls.map((control) => ({ ...control, value: settings[control.key] ?? null })),
|
|
262
269
|
// 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(() => []) } : {}),
|
|
270
|
+
...(base.secrets.length ? { held: await (ctx.vault?.held?.() ?? vaultSummary(ctx.stateRoot, spec.id)).catch(() => []) } : {}),
|
|
264
271
|
ships: this.external ? null : await madreRelease(),
|
|
265
272
|
runs,
|
|
266
273
|
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
|
+
}
|
package/src/ollama.mjs
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
// so remembering costs no tokens elsewhere and nothing leaves. Nothing here is
|
|
6
6
|
// required: without Ollama every path falls back to what it did before.
|
|
7
7
|
|
|
8
|
+
import http from 'node:http';
|
|
9
|
+
import https from 'node:https';
|
|
8
10
|
import { t } from './i18n.mjs';
|
|
9
11
|
|
|
10
12
|
export const DEFAULT_OLLAMA_HOST = 'http://127.0.0.1:11434';
|
|
@@ -95,6 +97,30 @@ export function ollamaEmbedder({ host = ollamaHost(), model, fetchImpl = globalT
|
|
|
95
97
|
};
|
|
96
98
|
}
|
|
97
99
|
|
|
100
|
+
// Node's fetch gives up on an answer whose first byte has not come in 300 s (undici's own headers
|
|
101
|
+
// timeout), whatever the turn allowed, and Ollama sends nothing until the model has read the whole
|
|
102
|
+
// question — streaming or not. On a server without a graphics card that is minutes: the Coordinator
|
|
103
|
+
// on Carlos's server failed with a bare «fetch failed» at 303 s of the 10 000 its turn had (L-7,
|
|
104
|
+
// 2026-11-04). node:http has no such limit, so a local answer waits as long as the turn says.
|
|
105
|
+
// Shaped like fetch for what this file reads: ok, status, text(), json().
|
|
106
|
+
export function patientFetch(url, { method = 'GET', headers = {}, body = null, signal = null } = {}) {
|
|
107
|
+
return new Promise((resolve, reject) => {
|
|
108
|
+
const failed = (error) => reject(signal?.aborted ? signal.reason : error);
|
|
109
|
+
const target = new URL(url);
|
|
110
|
+
const request = (target.protocol === 'https:' ? https : http).request(target, { method, headers, ...(signal ? { signal } : {}) }, (response) => {
|
|
111
|
+
const chunks = [];
|
|
112
|
+
response.on('data', (chunk) => chunks.push(chunk));
|
|
113
|
+
response.on('error', failed);
|
|
114
|
+
response.on('end', () => {
|
|
115
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
116
|
+
resolve({ ok: response.statusCode >= 200 && response.statusCode < 300, status: response.statusCode, text: async () => text, json: async () => JSON.parse(text) });
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
request.on('error', failed);
|
|
120
|
+
request.end(body ?? undefined);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
98
124
|
// One answer from a local model. `json: true` asks Ollama for a JSON object.
|
|
99
125
|
export async function ollamaGenerate({ host = ollamaHost(), model, prompt, system = null, json = false, fetchImpl = globalThis.fetch, timeoutMs = 180000, temperature = 0.2, numCtx = DEFAULT_NUM_CTX, signal = null } = {}) {
|
|
100
126
|
const started = Date.now();
|
|
@@ -102,7 +128,14 @@ export async function ollamaGenerate({ host = ollamaHost(), model, prompt, syste
|
|
|
102
128
|
// A model that takes longer than the turn allows says so in the room's words, as any agent does:
|
|
103
129
|
// the bare «The operation was aborted due to timeout» reached the person, in English.
|
|
104
130
|
const response = await fetchImpl(`${host}/api/chat`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ model, messages, stream: false, options: { temperature, num_ctx: numCtx }, ...(json ? { format: 'json' } : {}) }), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs) })
|
|
105
|
-
.catch((error) => {
|
|
131
|
+
.catch((error) => {
|
|
132
|
+
if (error?.name === 'TimeoutError') throw Object.assign(new Error(t('{label} did not respond before the timeout ({seconds}s).', { label: `Ollama (${model})`, seconds: Math.round(timeoutMs / 1000) })), { code: 'ETIMEDOUT' });
|
|
133
|
+
if (error?.name === 'AbortError') throw error;
|
|
134
|
+
// Ollama stopped or closed the connection mid-answer: said in the room's words, with the code
|
|
135
|
+
// kept so the archivist still reads it as passing.
|
|
136
|
+
const code = error?.cause?.code ?? error?.code ?? error?.name ?? 'failed';
|
|
137
|
+
throw Object.assign(new Error(t('{label} closed the connection before answering ({code}). Check in Settings › Local AI that Ollama is still running.', { label: `Ollama (${model})`, code })), { code, cause: error });
|
|
138
|
+
});
|
|
106
139
|
if (!response.ok) throw new Error(`Ollama HTTP ${response.status}: ${(await response.text().catch(() => '')).slice(0, 200)}`);
|
|
107
140
|
const payload = await response.json();
|
|
108
141
|
const inputTokens = payload.prompt_eval_count ?? 0;
|
|
@@ -130,21 +163,30 @@ export async function pullModel({ host = ollamaHost(), model, fetchImpl = global
|
|
|
130
163
|
const decoder = new TextDecoder();
|
|
131
164
|
let buffer = '';
|
|
132
165
|
let lastStatus = '';
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
166
|
+
try {
|
|
167
|
+
for (;;) {
|
|
168
|
+
const { value, done } = await reader.read();
|
|
169
|
+
if (done) break;
|
|
170
|
+
buffer += decoder.decode(value, { stream: true });
|
|
171
|
+
let index;
|
|
172
|
+
while ((index = buffer.indexOf('\n')) >= 0) {
|
|
173
|
+
const line = buffer.slice(0, index).trim();
|
|
174
|
+
buffer = buffer.slice(index + 1);
|
|
175
|
+
if (!line) continue;
|
|
176
|
+
let event;
|
|
177
|
+
try { event = JSON.parse(line); } catch { continue; }
|
|
178
|
+
if (event.error) throw new Error(event.error);
|
|
179
|
+
const status = event.total ? `${event.status} · ${Math.round((event.completed ?? 0) / event.total * 100)}%` : event.status;
|
|
180
|
+
if (status && status !== lastStatus) { lastStatus = status; onLine(status); }
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (signal?.aborted) throw error;
|
|
185
|
+
// Ollama dropped or closed the connection mid-download (D-21, undici's TypeError: terminated / UND_ERR_SOCKET).
|
|
186
|
+
if (error?.message === 'terminated' || error?.cause?.code === 'UND_ERR_SOCKET' || /terminated|other side closed/i.test(error?.message ?? '')) {
|
|
187
|
+
throw Object.assign(new Error(t('Ollama closed the connection while downloading {model}. Check that Ollama is still running and try again; what already arrived stays.', { model })), { code: 'ECONNRESET', trouble: 'ollama-closed', cause: error });
|
|
147
188
|
}
|
|
189
|
+
throw error;
|
|
148
190
|
}
|
|
149
191
|
return { model };
|
|
150
192
|
}
|
package/src/opencode-health.mjs
CHANGED
|
@@ -45,7 +45,7 @@ const OPENCODE_PICK = 'opencode/big-pickle';
|
|
|
45
45
|
export const providerOf = (model) => (typeof model === 'string' && model.includes('/') ? model.split('/')[0] : null);
|
|
46
46
|
|
|
47
47
|
// Which of MADRE's known conditions this failure is, said as what the provider needs.
|
|
48
|
-
const KINDS = { 'provider-credit-exhausted': 'no-credit', 'opencode-default-provider': 'bad-key' };
|
|
48
|
+
const KINDS = { 'provider-credit-exhausted': 'no-credit', 'opencode-default-provider': 'bad-key', 'opencode-default-model-missing': 'no-model' };
|
|
49
49
|
export function problemOf(error) {
|
|
50
50
|
for (const condition of diagnose(error, 'opencode')) if (KINDS[condition.id]) return KINDS[condition.id];
|
|
51
51
|
return null;
|