@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
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
2
|
+
// MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
|
|
3
|
+
// Gemini without its CLI: Google AI Studio's API, called by MADRE with the person's own key.
|
|
4
|
+
//
|
|
5
|
+
// What it is and what it is not (review of 2026-11-06). The CLI reads the project, sees what is
|
|
6
|
+
// attached and writes where a permission lets it; this is a request with the briefing in it and an
|
|
7
|
+
// answer back. So the room gives it what it can do (capabilities.mjs, `gemini-rest`): it answers,
|
|
8
|
+
// at #1 at most, and it is told it cannot open a file. The key travels in a header, never in the
|
|
9
|
+
// address, and the request goes through the same watch as every other one this process makes
|
|
10
|
+
// (outbound.mjs, `gemini-answer`).
|
|
11
|
+
|
|
12
|
+
import { resolveGeminiKey } from '../mcp/image-server.mjs';
|
|
13
|
+
import { withListPrice } from '../prices.mjs';
|
|
14
|
+
import { t } from '../i18n.mjs';
|
|
15
|
+
|
|
16
|
+
// The ones Google still gives a new key (models.mjs): 2.5 Flash is not among them any more.
|
|
17
|
+
export const DEFAULT_GEMINI_REST_MODEL = 'gemini-3-flash-preview';
|
|
18
|
+
export const DEFAULT_GEMINI_FALLBACK_MODEL = 'gemini-3-flash-preview';
|
|
19
|
+
export const geminiApiBase = (env = process.env) => env.PULSE_GEMINI_API_URL ?? 'https://generativelanguage.googleapis.com';
|
|
20
|
+
|
|
21
|
+
// Said to the model before the briefing: the briefing speaks of a project it was not given.
|
|
22
|
+
export const REST_INSTRUCTION = 'You are answering through Google\'s Gemini API, called by MADRE. You have no tools here: you cannot open, read, list, create or change any file of the project, run a command or search the web. Answer only from what this message contains. When asked about a file or folder you were not shown, say you cannot read it from here and that the Gemini CLI, once installed, can.';
|
|
23
|
+
|
|
24
|
+
// Google's own words, turned into something a person can act on.
|
|
25
|
+
export function diagnoseGeminiRestError(status, errorBody = {}) {
|
|
26
|
+
const message = String(errorBody?.message ?? errorBody?.error?.message ?? '');
|
|
27
|
+
const errorStatus = String(errorBody?.status ?? errorBody?.error?.status ?? '');
|
|
28
|
+
|
|
29
|
+
if (/prepayment credits are depleted/i.test(message)) {
|
|
30
|
+
return {
|
|
31
|
+
code: 'CREDITS_DEPLETED',
|
|
32
|
+
message: t('Google says the AI Studio project behind this Gemini key has no prepaid credits left; every request is refused (HTTP 429) until it is topped up.'),
|
|
33
|
+
hint: t('Add credits at https://ai.studio/projects, or paste another Gemini key in Settings › Agents › Gemini.'),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
if (status === 429 || errorStatus === 'RESOURCE_EXHAUSTED' || /quota exceeded|rate limit/i.test(message)) {
|
|
37
|
+
return {
|
|
38
|
+
code: 'RATE_LIMITED',
|
|
39
|
+
message: t('Google is rate-limiting this Gemini key (HTTP 429).'),
|
|
40
|
+
hint: t('Wait a minute, or pick another model; check the key\'s quota at aistudio.google.com.'),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
// A bad key is a 400 at Google (API_KEY_INVALID), not a 401.
|
|
44
|
+
if (status === 401 || status === 403 || errorStatus === 'PERMISSION_DENIED' || /API key not valid|API_KEY_INVALID|unauthorized/i.test(message)) {
|
|
45
|
+
return {
|
|
46
|
+
code: 'AUTH',
|
|
47
|
+
message: t('Google rejected the Gemini credentials.'),
|
|
48
|
+
hint: t('Paste the key again in Settings › Agents › Gemini, or check GEMINI_API_KEY in your environment or ~/.gemini/.env.'),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
if (/input token count|exceeds the maximum number of tokens|too many tokens/i.test(message)) {
|
|
52
|
+
return {
|
|
53
|
+
code: 'TOO_LONG',
|
|
54
|
+
message: t('The message is longer than this Gemini model takes in one go.'),
|
|
55
|
+
hint: t('Start a new conversation, or attach less text.'),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
if (status === 404 || errorStatus === 'NOT_FOUND' || /model .*not found|is not found for API version|is not supported for generateContent/i.test(message)) {
|
|
59
|
+
return {
|
|
60
|
+
code: 'MODEL_NOT_FOUND',
|
|
61
|
+
message: t('Google reported that the requested Gemini model does not exist or is not available for this key.'),
|
|
62
|
+
hint: t('Pick another model under the box.'),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
if (status >= 500 || errorStatus === 'UNAVAILABLE') {
|
|
66
|
+
return {
|
|
67
|
+
code: 'UNAVAILABLE',
|
|
68
|
+
message: t('Google reported the model as unavailable (HTTP {status}).', { status }),
|
|
69
|
+
hint: t('Try again shortly or choose another model.'),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
code: 'API_ERROR',
|
|
74
|
+
message: message || t('Google Gemini API request failed with HTTP {status}.', { status }),
|
|
75
|
+
hint: '',
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const failure = (diagnosis, also = '') => {
|
|
80
|
+
const error = new Error(`${diagnosis.message} ${diagnosis.hint}${also}`.trim());
|
|
81
|
+
error.code = diagnosis.code;
|
|
82
|
+
error.diagnosis = diagnosis;
|
|
83
|
+
return error;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
// What the stream says, piece by piece: text, the bill, and why it stopped.
|
|
87
|
+
function readEvent(data, into) {
|
|
88
|
+
const candidate = data.candidates?.[0];
|
|
89
|
+
for (const part of candidate?.content?.parts ?? []) {
|
|
90
|
+
// A thought is the model's reasoning, not its answer; it is billed (usageMetadata), not shown.
|
|
91
|
+
if (typeof part.text === 'string' && !part.thought) into.text += part.text;
|
|
92
|
+
}
|
|
93
|
+
if (candidate?.finishReason) into.finish = candidate.finishReason;
|
|
94
|
+
if (data.promptFeedback?.blockReason) into.blocked = data.promptFeedback.blockReason;
|
|
95
|
+
const usage = data.usageMetadata;
|
|
96
|
+
if (usage) {
|
|
97
|
+
into.inputTokens = usage.promptTokenCount ?? into.inputTokens;
|
|
98
|
+
into.outputTokens = usage.candidatesTokenCount ?? into.outputTokens;
|
|
99
|
+
into.reasoningTokens = usage.thoughtsTokenCount ?? into.reasoningTokens;
|
|
100
|
+
into.cachedInputTokens = usage.cachedContentTokenCount ?? into.cachedInputTokens;
|
|
101
|
+
into.totalTokens = usage.totalTokenCount ?? into.totalTokens;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function oneCall({ base, model, apiKey, prompt, json, signal, timeoutMs, fetchImpl, onProgress }) {
|
|
106
|
+
const url = `${base}/v1beta/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`;
|
|
107
|
+
const body = {
|
|
108
|
+
systemInstruction: { parts: [{ text: REST_INSTRUCTION }] },
|
|
109
|
+
contents: [{ role: 'user', parts: [{ text: String(prompt ?? '') }] }],
|
|
110
|
+
generationConfig: { temperature: 0.2, ...(json ? { responseMimeType: 'application/json' } : {}) },
|
|
111
|
+
};
|
|
112
|
+
const clock = AbortSignal.timeout(timeoutMs);
|
|
113
|
+
const callSignal = signal ? AbortSignal.any([signal, clock]) : clock;
|
|
114
|
+
const late = () => {
|
|
115
|
+
const error = new Error(t('Gemini did not respond before the timeout ({seconds}s).', { seconds: Math.round(timeoutMs / 1000) }));
|
|
116
|
+
error.code = 'TIMEOUT';
|
|
117
|
+
return error;
|
|
118
|
+
};
|
|
119
|
+
// Every way the wire can fail, said as what happened: stopped by the person, out of time, offline.
|
|
120
|
+
const wire = (error) => {
|
|
121
|
+
if (signal?.aborted) return error;
|
|
122
|
+
if (clock.aborted) return late();
|
|
123
|
+
const offline = new Error(t('MADRE could not reach Google\'s Gemini API: {reason}. Check this computer\'s internet connection.', { reason: error?.cause?.code ?? error?.message ?? 'no answer' }));
|
|
124
|
+
offline.code = 'NETWORK';
|
|
125
|
+
return offline;
|
|
126
|
+
};
|
|
127
|
+
let response;
|
|
128
|
+
try {
|
|
129
|
+
response = await fetchImpl(url, {
|
|
130
|
+
method: 'POST',
|
|
131
|
+
headers: { 'content-type': 'application/json', 'x-goog-api-key': apiKey },
|
|
132
|
+
body: JSON.stringify(body),
|
|
133
|
+
signal: callSignal,
|
|
134
|
+
});
|
|
135
|
+
} catch (error) {
|
|
136
|
+
throw wire(error);
|
|
137
|
+
}
|
|
138
|
+
if (!response.ok) {
|
|
139
|
+
let errorBody = {};
|
|
140
|
+
try { errorBody = await response.json(); } catch {
|
|
141
|
+
try { errorBody = { message: await response.text() }; } catch { /* nothing said */ }
|
|
142
|
+
}
|
|
143
|
+
return { trouble: diagnoseGeminiRestError(response.status, errorBody) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const got = { text: '', finish: null, blocked: null, inputTokens: 0, outputTokens: 0, reasoningTokens: 0, cachedInputTokens: 0, totalTokens: 0 };
|
|
147
|
+
const decoder = new TextDecoder();
|
|
148
|
+
let buffer = '';
|
|
149
|
+
let told = 0;
|
|
150
|
+
const take = (line) => {
|
|
151
|
+
const trimmed = line.trim();
|
|
152
|
+
if (!trimmed.startsWith('data:')) return;
|
|
153
|
+
const jsonText = trimmed.slice(5).trim();
|
|
154
|
+
if (!jsonText || jsonText === '[DONE]') return;
|
|
155
|
+
try { readEvent(JSON.parse(jsonText), got); } catch { /* a partial line */ }
|
|
156
|
+
if (got.text.length > told) { told = got.text.length; onProgress?.({ chars: told }); }
|
|
157
|
+
};
|
|
158
|
+
try {
|
|
159
|
+
if (response.body) {
|
|
160
|
+
for await (const chunk of response.body) {
|
|
161
|
+
buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
|
|
162
|
+
const lines = buffer.split('\n');
|
|
163
|
+
buffer = lines.pop() ?? '';
|
|
164
|
+
lines.forEach(take);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
} catch (error) {
|
|
168
|
+
throw wire(error);
|
|
169
|
+
}
|
|
170
|
+
take(buffer);
|
|
171
|
+
return { got };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export async function invokeGeminiRest({
|
|
175
|
+
prompt,
|
|
176
|
+
model = null,
|
|
177
|
+
signal = null,
|
|
178
|
+
timeoutMs = 120000,
|
|
179
|
+
key = undefined,
|
|
180
|
+
env = process.env,
|
|
181
|
+
keyResolver = resolveGeminiKey,
|
|
182
|
+
fetchImpl = globalThis.fetch,
|
|
183
|
+
onProgress = null,
|
|
184
|
+
fallbackModel = env.PULSE_GEMINI_FALLBACK_MODEL ?? DEFAULT_GEMINI_FALLBACK_MODEL,
|
|
185
|
+
json = false,
|
|
186
|
+
} = {}) {
|
|
187
|
+
// `null` and `undefined` both mean «find it»: the room never hands a key in.
|
|
188
|
+
const apiKey = key ?? await keyResolver(env);
|
|
189
|
+
if (!apiKey) {
|
|
190
|
+
const error = new Error(t('Gemini requires an API key. Set GEMINI_API_KEY or save it in Settings.'));
|
|
191
|
+
error.code = 'AUTH';
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
const base = geminiApiBase(env).replace(/\/$/, '');
|
|
195
|
+
// «auto» is the CLI's router; the API has no such model, so it means the default here.
|
|
196
|
+
const asked = String(model || env.PULSE_GEMINI_MODEL || DEFAULT_GEMINI_REST_MODEL).replace(/^models\//, '');
|
|
197
|
+
const first = asked === 'auto' ? DEFAULT_GEMINI_REST_MODEL : asked;
|
|
198
|
+
const spare = fallbackModel && fallbackModel !== first ? fallbackModel : null;
|
|
199
|
+
|
|
200
|
+
let current = first;
|
|
201
|
+
let firstTrouble = null;
|
|
202
|
+
for (;;) {
|
|
203
|
+
let outcome;
|
|
204
|
+
try {
|
|
205
|
+
outcome = await oneCall({ base, model: current, apiKey, prompt, json, signal, timeoutMs, fetchImpl, onProgress });
|
|
206
|
+
} catch (error) {
|
|
207
|
+
// The spare hung or the wire broke after the first model's refusal: that refusal is still why.
|
|
208
|
+
if (firstTrouble && !signal?.aborted) throw failure(firstTrouble, t(' (also tried {model})', { model: current }));
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
if (outcome.trouble) {
|
|
212
|
+
if (firstTrouble) throw failure(firstTrouble, t(' (also tried {model})', { model: current }));
|
|
213
|
+
if (spare && current !== spare && ['UNAVAILABLE', 'RATE_LIMITED', 'CREDITS_DEPLETED', 'MODEL_NOT_FOUND'].includes(outcome.trouble.code)) {
|
|
214
|
+
firstTrouble = outcome.trouble;
|
|
215
|
+
current = spare;
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
throw failure(outcome.trouble);
|
|
219
|
+
}
|
|
220
|
+
const { got } = outcome;
|
|
221
|
+
if (!got.text.trim() && (got.blocked || ['SAFETY', 'PROHIBITED_CONTENT', 'BLOCKLIST', 'SPII', 'RECITATION'].includes(got.finish))) {
|
|
222
|
+
throw failure({ code: 'BLOCKED', message: t('Google\'s Gemini API refused to answer this message ({reason}).', { reason: got.blocked ?? got.finish }), hint: t('Rephrase it, or ask another agent.') });
|
|
223
|
+
}
|
|
224
|
+
const usage = withListPrice({
|
|
225
|
+
inputTokens: got.inputTokens,
|
|
226
|
+
outputTokens: got.outputTokens,
|
|
227
|
+
cachedInputTokens: got.cachedInputTokens,
|
|
228
|
+
// Gemini bills its thinking apart from the answer (prices.mjs, gemini-json: reasoningIn false).
|
|
229
|
+
reasoningTokens: got.reasoningTokens,
|
|
230
|
+
totalTokens: got.totalTokens || (got.inputTokens + got.outputTokens + got.reasoningTokens),
|
|
231
|
+
source: 'gemini-json',
|
|
232
|
+
model: current,
|
|
233
|
+
}, current);
|
|
234
|
+
return { text: got.text.trim(), usage, toolCalls: 0, model: current, ...(current !== first ? { fallbackFrom: first } : {}) };
|
|
235
|
+
}
|
|
236
|
+
}
|
package/src/adapters/gemini.mjs
CHANGED
|
@@ -372,25 +372,27 @@ export async function invokeGemini({
|
|
|
372
372
|
// The spare failed too, for whatever reason (a model this account is not given, say): what
|
|
373
373
|
// the person needs to read is why the model they chose failed, not why the spare did.
|
|
374
374
|
if (switched && firstTrouble && !produced && !signal?.aborted) {
|
|
375
|
-
|
|
375
|
+
// In the room's words, like the sentence before it (L-8: «… (also tried …)» closed a Spanish notice).
|
|
376
|
+
error.message = `${firstTrouble.message} ${firstTrouble.hint}${t(' (also tried {model})', { model: fallbackModel })}`;
|
|
376
377
|
error.code = firstTrouble.code;
|
|
377
378
|
throw error;
|
|
378
379
|
}
|
|
379
|
-
if (diagnosis?.code === 'AUTH' || diagnosis?.code === 'INELIGIBLE'
|
|
380
|
+
if (diagnosis?.code === 'AUTH' || diagnosis?.code === 'INELIGIBLE') {
|
|
380
381
|
error.message = `${diagnosis.message} ${diagnosis.hint}`;
|
|
381
382
|
error.code = diagnosis.code;
|
|
382
383
|
throw error;
|
|
383
384
|
}
|
|
384
|
-
// Capacity trouble (503) or
|
|
385
|
-
// try on a lighter, explicit model before giving up
|
|
386
|
-
|
|
385
|
+
// Capacity trouble (503), rate limit (429), or depleted credits on the chosen model: one more
|
|
386
|
+
// try on a lighter, explicit model before giving up (L-12: a free-tier Flash model may answer
|
|
387
|
+
// when the default preview/pro router refuses for lack of prepayment credits).
|
|
388
|
+
if ((diagnosis?.code === 'UNAVAILABLE' || diagnosis?.code === 'RATE_LIMITED' || diagnosis?.code === 'CREDITS_DEPLETED') && !produced && !signal?.aborted && fallbackModel && !switched && currentModel !== fallbackModel) {
|
|
387
389
|
switched = true;
|
|
388
390
|
firstTrouble = diagnosis;
|
|
389
391
|
currentModel = fallbackModel;
|
|
390
392
|
continue;
|
|
391
393
|
}
|
|
392
|
-
if (diagnosis?.code === 'UNAVAILABLE' || diagnosis?.code === 'RATE_LIMITED') {
|
|
393
|
-
error.message = `${diagnosis.message} ${diagnosis.hint}${switched ?
|
|
394
|
+
if (diagnosis?.code === 'UNAVAILABLE' || diagnosis?.code === 'RATE_LIMITED' || diagnosis?.code === 'CREDITS_DEPLETED') {
|
|
395
|
+
error.message = `${diagnosis.message} ${diagnosis.hint}${switched ? t(' (also tried {model})', { model: fallbackModel }) : ''}`;
|
|
394
396
|
error.code = diagnosis.code;
|
|
395
397
|
throw error;
|
|
396
398
|
}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
2
|
+
// MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
|
|
3
|
+
// Grok Build (`grok`, xAI's own CLI, npm @xai-official/grok), added 2026-11-06. It read only at
|
|
4
|
+
// first; the same day it was opened to every mode, after its own tests (below, «Writing»).
|
|
5
|
+
//
|
|
6
|
+
// Tried against the real CLI (1.0.77, a Grok Plus account) on 2026-11-06, before a line was written
|
|
7
|
+
// here (docs/private/INVESTIGACION-GROK.md §8b):
|
|
8
|
+
//
|
|
9
|
+
// · `--output-format streaming-messages-json` is Claude Code's stream-json, line for line: a
|
|
10
|
+
// `system/init`, the `assistant` and `user` messages, and one closing `result` with the answer,
|
|
11
|
+
// the turn's tokens summed over every model call, and the cost (also for an account session).
|
|
12
|
+
// · Grok reads the person's Claude permissions: ~/.claude/settings.json always, and the project's
|
|
13
|
+
// .claude/settings*.json once the folder is trusted. An `allow: Bash(cp *)` there let a headless
|
|
14
|
+
// turn copy a file without asking. Its compatibility switches (GROK_CLAUDE_*_ENABLED) turn off
|
|
15
|
+
// skills, hooks and the rest, never those permissions — so a reading turn is given only the
|
|
16
|
+
// tools that read (`--tools`): a terminal it does not have cannot be allowed by anyone's rule.
|
|
17
|
+
// With that, and the same Claude rule in place, it wrote nothing and said why.
|
|
18
|
+
// · A call that needs an approval cancels the WHOLE turn (`errors: ["cancelled"]`, exit code 0)
|
|
19
|
+
// instead of being refused and going on; an explicit `--deny` is refused and the turn goes on.
|
|
20
|
+
// Hence the denials below, one rule per flag (two in one value were read as one tool name).
|
|
21
|
+
// · `--sandbox read-only` (Seatbelt on macOS) refused a write outside /tmp with «Operation not
|
|
22
|
+
// permitted» even under always-approve. It is the second wall, not the first. Not yet tried on
|
|
23
|
+
// Linux or WSL2 (Landlock); PULSE_GROK_SANDBOX=off leaves it out where it cannot start.
|
|
24
|
+
//
|
|
25
|
+
// The folder is not trusted for the turn (no `--trust`): a headless read needs no trust, and trust
|
|
26
|
+
// is kept by Grok for good and would bring the project's Claude rules and .grok/ along with it.
|
|
27
|
+
//
|
|
28
|
+
// Writing (2026-11-06, the real CLI in a test repository). #2 and #3: the reading tools plus its edit
|
|
29
|
+
// and write tools, `--permission-mode dontAsk`, writing allowed everywhere and every place nobody
|
|
30
|
+
// writes denied one rule at a time. It created a file, changed another, was refused .env and
|
|
31
|
+
// .git/hooks and went on, and had no terminal to run `touch` with. #4: the terminal too, with
|
|
32
|
+
// `--always-approve` (a command that waited for an approval would cancel the turn): it ran `touch`
|
|
33
|
+
// and `git status`, was refused .env and went on. The room is the wall behind Grok's own: it locks
|
|
34
|
+
// .env, .git and its folders read-only for the turn and puts back whatever reaches them, and at #2
|
|
35
|
+
// everything that existed (room/control.mjs) — a terminal can write where a rule cannot see.
|
|
36
|
+
import { chmod, copyFile, mkdir, mkdtemp, realpath, rm, stat, writeFile } from 'node:fs/promises';
|
|
37
|
+
import { homedir, tmpdir } from 'node:os';
|
|
38
|
+
import { basename, extname, join, sep } from 'node:path';
|
|
39
|
+
import { ENV_SECRETS } from '../checkpoint.mjs';
|
|
40
|
+
import { grokImagesDir } from '../lease.mjs';
|
|
41
|
+
import { t } from '../i18n.mjs';
|
|
42
|
+
import { runReadonlyProcess } from './process.mjs';
|
|
43
|
+
import { jsonLines } from './subagents.mjs';
|
|
44
|
+
|
|
45
|
+
// What a reading turn may use: the three tools that read. Everything else Grok offers by default
|
|
46
|
+
// (terminal, edits, `write`, subagents, schedulers, workflows, web, image and video) is absent.
|
|
47
|
+
export const READ_TOOLS = ['read_file', 'list_dir', 'grep'];
|
|
48
|
+
// Taken away even though --tools already leaves them out: a denial is refused and the turn goes on.
|
|
49
|
+
export const READ_DENY = ['Bash', 'Edit', 'Write'];
|
|
50
|
+
// Grok keeps its MCP meta-tools beside any --tools list; no server of the person's reaches a turn.
|
|
51
|
+
export const MCP_META_TOOLS = ['search_tool', 'use_tool'];
|
|
52
|
+
// What Grok would bring in from the other agents' folders. Off for a turn, so the person's Claude
|
|
53
|
+
// hooks never fire inside a Grok turn. Grok reads `false`, not `0` (tried with `grok inspect`).
|
|
54
|
+
const COMPAT_OFF = Object.fromEntries(['CLAUDE', 'CURSOR'].flatMap((vendor) => ['AGENTS', 'HOOKS', 'MCPS', 'RULES', 'SKILLS'].map((surface) => [`GROK_${vendor}_${surface}_ENABLED`, 'false'])));
|
|
55
|
+
|
|
56
|
+
// What a writing turn adds: its edit tool (search_replace) and its write tool; #4, the terminal.
|
|
57
|
+
export const WRITE_TOOLS = ['search_replace', 'write'];
|
|
58
|
+
export const SHELL_TOOL = 'run_terminal_cmd';
|
|
59
|
+
// The places no turn writes, whatever its mode (as Cursor's and OpenCode's). `.pulse` is left to the
|
|
60
|
+
// room when the turn has a draft folder there, because a denial wins over an allowance and would
|
|
61
|
+
// shut that folder too; the room locks every other `.pulse` path itself. `.grok/` is the project's
|
|
62
|
+
// own Grok configuration (hooks, MCP servers, permission rules): a turn that wrote it would arm the
|
|
63
|
+
// next one.
|
|
64
|
+
const NEVER_WRITTEN = ['.git/**', '.madre/**', '.grok/**', ...ENV_SECRETS.flatMap((name) => [name, `**/${name}`]), '.claude/settings.local.json'];
|
|
65
|
+
|
|
66
|
+
// The sandbox for a turn: read-only to read, the project (and Grok's own folder, and the temporary
|
|
67
|
+
// ones) to write. #4 runs none: its commands install, push and deploy with what is outside the project.
|
|
68
|
+
export function grokSandbox(environment = process.env, lease = null) {
|
|
69
|
+
const chosen = String(environment.PULSE_GROK_SANDBOX ?? '').trim().toLowerCase();
|
|
70
|
+
if (chosen === 'off' || chosen === '0' || chosen === 'false') return null;
|
|
71
|
+
if (lease?.airlock) return null;
|
|
72
|
+
return lease ? 'workspace' : 'read-only';
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// What the turn may do, from the lease the room gave it: none, read; #2 and #3, write; #4, also run.
|
|
76
|
+
export function grokPermissionsFor(lease = null) {
|
|
77
|
+
if (!lease) return { tools: READ_TOOLS, mode: null, allow: [], deny: READ_DENY };
|
|
78
|
+
const everywhere = Boolean(lease.create || lease.control || lease.airlock);
|
|
79
|
+
const dir = String(lease.relativeDir ?? '.').replace(/^\.\/+/, '').replace(/\/+$/, '');
|
|
80
|
+
const roots = everywhere || !dir || dir === '.' ? ['**'] : [`${dir}/**`];
|
|
81
|
+
const never = [...NEVER_WRITTEN, ...(lease.scratchDir ? [] : ['.pulse/**'])].flatMap((glob) => [`Write(${glob})`, `Edit(${glob})`]);
|
|
82
|
+
if (lease.airlock) return { tools: [...READ_TOOLS, ...WRITE_TOOLS, SHELL_TOOL], mode: 'always-approve', allow: [], deny: never };
|
|
83
|
+
return { tools: [...READ_TOOLS, ...WRITE_TOOLS], mode: 'dontAsk', allow: roots.flatMap((root) => [`Write(${root})`, `Edit(${root})`]), deny: ['Bash', ...never] };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// The web (2026-11-07): Grok's own search and page reader, both run by xAI's servers, neither asking
|
|
87
|
+
// for an approval (tried in a reading turn: it searched and opened nodejs.org and example.com). Off
|
|
88
|
+
// until the person turns on Web access for Grok, as for every agent.
|
|
89
|
+
export const WEB_TOOLS = ['web_search', 'web_fetch'];
|
|
90
|
+
// Images (2026-11-08): Grok's own image tool, run by xAI, allowed by name (without the rule it waits for
|
|
91
|
+
// an approval and the turn is cancelled; with it, it generated). Only in a writing turn with images on.
|
|
92
|
+
export const IMAGE_TOOL = 'image_gen';
|
|
93
|
+
|
|
94
|
+
export function buildGrokArgs({ projectRoot, promptFile, model = process.env.PULSE_GROK_MODEL || null, effort = null, lease = null, scopes = null, environment = process.env }) {
|
|
95
|
+
const sandbox = grokSandbox(environment, lease);
|
|
96
|
+
const allowed = grokPermissionsFor(lease);
|
|
97
|
+
const web = Boolean(scopes?.web);
|
|
98
|
+
const images = Boolean(lease && scopes?.imageGen);
|
|
99
|
+
return [
|
|
100
|
+
// From a file, word for word: a message that starts with «/» or «-» is not a command or a flag.
|
|
101
|
+
'--prompt-file', promptFile,
|
|
102
|
+
'--verbatim',
|
|
103
|
+
'--output-format', 'streaming-messages-json',
|
|
104
|
+
'--cwd', projectRoot,
|
|
105
|
+
'--tools', [...allowed.tools, ...(web ? WEB_TOOLS : []), ...(images ? [IMAGE_TOOL] : [])].join(','),
|
|
106
|
+
'--disallowed-tools', MCP_META_TOOLS.join(','),
|
|
107
|
+
// #4 approves every call of its own (a command waiting for an approval would cancel the turn);
|
|
108
|
+
// #2 and #3 approve only what is allowed below and refuse the rest without asking.
|
|
109
|
+
...(allowed.mode === 'always-approve' ? ['--always-approve'] : allowed.mode ? ['--permission-mode', allowed.mode] : []),
|
|
110
|
+
...allowed.allow.flatMap((rule) => ['--allow', rule]),
|
|
111
|
+
...(images ? ['--allow', IMAGE_TOOL] : []),
|
|
112
|
+
...allowed.deny.flatMap((rule) => ['--deny', rule]),
|
|
113
|
+
...(sandbox ? ['--sandbox', sandbox] : []),
|
|
114
|
+
'--no-subagents',
|
|
115
|
+
...(web ? [] : ['--disable-web-search']),
|
|
116
|
+
'--no-memory',
|
|
117
|
+
'--no-wait-for-background',
|
|
118
|
+
'--no-auto-update',
|
|
119
|
+
...(model && model !== 'default' ? ['--model', model] : []),
|
|
120
|
+
...(effort ? ['--effort', effort] : []),
|
|
121
|
+
];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function grokEnvironment(environment = process.env) {
|
|
125
|
+
return { ...environment, ...COMPAT_OFF, GROK_DISABLE_AUTOUPDATER: '1', GROK_MEMORY: '0' };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// xAI's refusals, in words a person can act on. The 403 is the one seen on 2026-11-06: an account
|
|
129
|
+
// whose plan was paid after its sign-in; signing in again fixed it.
|
|
130
|
+
export function grokFailure(raw) {
|
|
131
|
+
const said = String(raw ?? '');
|
|
132
|
+
if (/permission-denied|chat endpoint is denied|\b403\b/i.test(said)) {
|
|
133
|
+
return t('xAI refused this Grok account (403). Sign in again (grok logout, then grok login); if it keeps happening, check at grok.com that your plan is active.');
|
|
134
|
+
}
|
|
135
|
+
if (/not signed in|not logged in|token expired|not authenticated/i.test(said)) {
|
|
136
|
+
return t('Grok is not signed in. Sign in from Settings › Agents › Grok, or run grok login in a terminal.');
|
|
137
|
+
}
|
|
138
|
+
if (/\b429\b|rate.?limit|usage limit|quota/i.test(said)) {
|
|
139
|
+
return t('Grok says this account has reached its usage limit for now.');
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// The closing `result` carries the answer, the tokens of every model call of the run, and the
|
|
145
|
+
// cost; a cost of 0 means unknown, never free (Grok's own manual). An error carries `errors[]`.
|
|
146
|
+
// The images its tool saved, as the tool reported them: `{"type":"ImageGen","path":"…"}` in a result.
|
|
147
|
+
export function grokImagesIn(events) {
|
|
148
|
+
const paths = [];
|
|
149
|
+
for (const event of events) {
|
|
150
|
+
if (event?.type !== 'user') continue;
|
|
151
|
+
for (const part of event.message?.content ?? []) {
|
|
152
|
+
if (part?.type !== 'tool_result' || typeof part.content !== 'string') continue;
|
|
153
|
+
try { const said = JSON.parse(part.content); if (said?.type === 'ImageGen' && typeof said.path === 'string') paths.push(said.path); } catch { /* not an image */ }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return [...new Set(paths)];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function parseGrokOutput(output) {
|
|
160
|
+
const events = jsonLines(output);
|
|
161
|
+
const images = grokImagesIn(events);
|
|
162
|
+
const last = events.filter((event) => event?.type === 'result').at(-1);
|
|
163
|
+
if (!last) {
|
|
164
|
+
// Cut short before its close: what it had written so far is all there is.
|
|
165
|
+
const pieces = events.filter((event) => event?.type === 'assistant' && !event.parent_tool_use_id)
|
|
166
|
+
.flatMap((event) => event.message?.content ?? []).filter((part) => part?.type === 'text').map((part) => part.text);
|
|
167
|
+
return { text: pieces.join('').trim(), usage: null };
|
|
168
|
+
}
|
|
169
|
+
if (last.is_error) {
|
|
170
|
+
const errors = Array.isArray(last.errors) ? last.errors.map(String) : [];
|
|
171
|
+
const said = errors.join(' ');
|
|
172
|
+
const error = grokFailure(said)
|
|
173
|
+
?? (errors.length === 1 && errors[0] === 'cancelled'
|
|
174
|
+
? t('Grok stopped the turn: a step needed an approval that a turn cannot give.')
|
|
175
|
+
: (said.trim() ? t('Grok returned an error: {error}', { error: said.trim().slice(0, 300) }) : t('Grok returned an error.')));
|
|
176
|
+
return { text: '', usage: null, error };
|
|
177
|
+
}
|
|
178
|
+
const tokens = last.usage && typeof last.usage === 'object' ? last.usage : null;
|
|
179
|
+
const count = (key) => Number(tokens?.[key] ?? 0) || 0;
|
|
180
|
+
const cost = Number(last.total_cost_usd);
|
|
181
|
+
const usage = tokens
|
|
182
|
+
? {
|
|
183
|
+
inputTokens: count('input_tokens'),
|
|
184
|
+
cacheCreationInputTokens: count('cache_creation_input_tokens'),
|
|
185
|
+
cachedInputTokens: count('cache_read_input_tokens'),
|
|
186
|
+
outputTokens: count('output_tokens'),
|
|
187
|
+
reasoningTokens: 0,
|
|
188
|
+
totalTokens: count('input_tokens') + count('cache_creation_input_tokens') + count('cache_read_input_tokens') + count('output_tokens'),
|
|
189
|
+
costUsd: Number.isFinite(cost) && cost > 0 ? cost : null,
|
|
190
|
+
source: 'grok-json',
|
|
191
|
+
}
|
|
192
|
+
: null;
|
|
193
|
+
return { text: typeof last.result === 'string' ? last.result.trim() : '', usage, ...(images.length ? { images } : {}) };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// While it runs: what it has written so far.
|
|
197
|
+
export function grokProgress(output) {
|
|
198
|
+
let chars = 0;
|
|
199
|
+
for (const event of jsonLines(output)) {
|
|
200
|
+
if (event?.type !== 'assistant' || event.parent_tool_use_id) continue;
|
|
201
|
+
for (const part of event.message?.content ?? []) if (part?.type === 'text') chars += String(part.text ?? '').length;
|
|
202
|
+
}
|
|
203
|
+
return { chars };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// `grok models` says whether there is a session, and lists the account's models (2026-11-06):
|
|
207
|
+
// «You are logged in with grok.com.» / «You are not authenticated.»
|
|
208
|
+
// «Default model: grok-4.7» then « * grok-4.7 (default)», « - grok-4.6»…
|
|
209
|
+
// It exits 0 either way: the words decide.
|
|
210
|
+
export function parseGrokModels(output) {
|
|
211
|
+
const text = String(output ?? '');
|
|
212
|
+
const models = [];
|
|
213
|
+
let fallback = null;
|
|
214
|
+
for (const line of text.split('\n')) {
|
|
215
|
+
const listed = line.match(/^\s*[*-]\s+([\w.:-]+)(\s+\(default\))?\s*$/);
|
|
216
|
+
if (listed) {
|
|
217
|
+
models.push(listed[1]);
|
|
218
|
+
if (listed[2]) fallback = listed[1];
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const named = text.match(/Default model:\s*([\w.:-]+)/);
|
|
222
|
+
return { models, default: named?.[1] ?? fallback };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function parseGrokStatus(output, env = process.env, { saved = false } = {}) {
|
|
226
|
+
const said = String(output ?? '');
|
|
227
|
+
if (/you are logged in|signed in as/i.test(said)) return { state: 'signed-in', detail: said.match(/logged in with ([^\s.]+(?:\.[^\s.]+)*)/i)?.[1] ?? 'grok.com' };
|
|
228
|
+
if (/not authenticated|not signed in|not logged in/i.test(said)) {
|
|
229
|
+
// A key is Grok's fallback when there is no session (its manual; not yet tried here).
|
|
230
|
+
if (env.XAI_API_KEY) return { state: 'signed-in', detail: 'via XAI_API_KEY' };
|
|
231
|
+
// `grok models` does not renew an expired session; a turn does (2026-11-08: a copy started while the
|
|
232
|
+
// session was due was told «not authenticated», and Grok renewed it minutes later). While its saved
|
|
233
|
+
// session is there (~/.grok/auth.json, gone after `grok logout`), Grok is not signed out.
|
|
234
|
+
return saved ? { state: 'signed-in', detail: 'grok.com · session saved' } : { state: 'signed-out', detail: 'grok login' };
|
|
235
|
+
}
|
|
236
|
+
return { state: 'unknown', detail: said.trim().split('\n')[0]?.slice(0, 120) || 'no answer from grok models' };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// The images go into the project only from Grok's own folder, and only as images: a path the tool
|
|
240
|
+
// reported that leads anywhere else is left where it is. A name already taken gets a number.
|
|
241
|
+
const IMAGE_KINDS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif']);
|
|
242
|
+
export async function copyGrokImages(paths, { projectRoot, lease, environment = process.env }) {
|
|
243
|
+
const home = await realpath(environment.GROK_HOME || join(homedir(), '.grok')).catch(() => null);
|
|
244
|
+
if (!home) return [];
|
|
245
|
+
const dir = grokImagesDir(lease);
|
|
246
|
+
const target = join(projectRoot, dir);
|
|
247
|
+
const saved = [];
|
|
248
|
+
for (const path of paths) {
|
|
249
|
+
const real = await realpath(path).catch(() => null);
|
|
250
|
+
if (!real || !real.startsWith(home + sep) || !IMAGE_KINDS.has(extname(real).toLowerCase())) continue;
|
|
251
|
+
if (!(await stat(real).catch(() => null))?.isFile()) continue;
|
|
252
|
+
await mkdir(target, { recursive: true });
|
|
253
|
+
const ext = extname(real).toLowerCase();
|
|
254
|
+
const stem = basename(real, extname(real)).replace(/[^\w.-]+/g, '-').slice(0, 60) || 'imagen';
|
|
255
|
+
let name = `grok-${stem}${ext}`;
|
|
256
|
+
for (let n = 2; await stat(join(target, name)).catch(() => null); n += 1) name = `grok-${stem}-${n}${ext}`;
|
|
257
|
+
await copyFile(real, join(target, name));
|
|
258
|
+
saved.push(`${dir}/${name}`);
|
|
259
|
+
}
|
|
260
|
+
return saved;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export async function invokeGrok({ executable, projectRoot, prompt, timeoutMs = 120000, signal, model = null, effort = null, lease = null, scopes = null, onProgress = null }) {
|
|
264
|
+
// The message goes in a file only this person can read, made for the turn and removed after it.
|
|
265
|
+
const dir = await mkdtemp(join(tmpdir(), 'madre-grok-'));
|
|
266
|
+
try {
|
|
267
|
+
const promptFile = join(dir, 'prompt.md');
|
|
268
|
+
await writeFile(promptFile, String(prompt ?? ''), { mode: 0o600 });
|
|
269
|
+
await chmod(promptFile, 0o600).catch(() => {});
|
|
270
|
+
const result = await runReadonlyProcess({
|
|
271
|
+
onProgress: onProgress ? (out) => onProgress(grokProgress(out)) : null,
|
|
272
|
+
executable,
|
|
273
|
+
args: buildGrokArgs({ projectRoot, promptFile, ...(model ? { model } : {}), effort, lease, scopes }),
|
|
274
|
+
cwd: projectRoot,
|
|
275
|
+
env: grokEnvironment(process.env),
|
|
276
|
+
timeoutMs,
|
|
277
|
+
signal,
|
|
278
|
+
label: 'Grok',
|
|
279
|
+
parse: parseGrokOutput,
|
|
280
|
+
});
|
|
281
|
+
if (!lease || !result.images?.length) return result;
|
|
282
|
+
const saved = await copyGrokImages(result.images, { projectRoot, lease, environment: process.env });
|
|
283
|
+
if (!saved.length) return result;
|
|
284
|
+
return { ...result, text: `${result.text}\n\n${t('Images MADRE saved in the project: {list}', { list: saved.join(', ') })}` };
|
|
285
|
+
} finally {
|
|
286
|
+
await rm(dir, { recursive: true, force: true, maxRetries: 6, retryDelay: 60 }).catch(() => {});
|
|
287
|
+
}
|
|
288
|
+
}
|
package/src/adapters/process.mjs
CHANGED
|
@@ -34,7 +34,7 @@ export function terminateProcessTree(child, { graceMs = 2000 } = {}) {
|
|
|
34
34
|
// agent and looking for whoever pulled the plug.
|
|
35
35
|
// In the room's language (QA 1.1.0, ACT-11): «OpenCode exited with code 1. Última salida: …» mixed two.
|
|
36
36
|
const SIGNAL_MEANING = {
|
|
37
|
-
SIGTERM: '{label} was stopped (SIGTERM)
|
|
37
|
+
SIGTERM: '{label} was stopped (SIGTERM): something outside the turn asked it to quit, such as the system, another program or MADRE closing.',
|
|
38
38
|
SIGKILL: '{label} was killed outright (SIGKILL) — usually this machine running out of memory.',
|
|
39
39
|
SIGINT: '{label} was interrupted (SIGINT) — a Ctrl+C reached it.',
|
|
40
40
|
SIGHUP: '{label} lost its terminal (SIGHUP).',
|
|
@@ -94,6 +94,17 @@ function eventWords(event) {
|
|
|
94
94
|
return null;
|
|
95
95
|
}
|
|
96
96
|
|
|
97
|
+
function failureLine(stderr) {
|
|
98
|
+
const lines = stderr.split('\n').map((line) => line.trim()).filter(Boolean);
|
|
99
|
+
const last = lines.at(-1);
|
|
100
|
+
// Node prints its version after an uncaught exception. That footer displaced the actual
|
|
101
|
+
// exception from the one-line room error, making a crash look like a Node version problem.
|
|
102
|
+
if (!/^Node\.js v\d+\.\d+\.\d+/.test(last ?? '')) return last;
|
|
103
|
+
return lines.find((line) => /^(?:[A-Za-z_$][\w$]*(?:Error|Exception)|Error)(?: \[[^\]]+\])?:\s*\S/.test(line))
|
|
104
|
+
?? lines.at(-2)
|
|
105
|
+
?? last;
|
|
106
|
+
}
|
|
107
|
+
|
|
97
108
|
export function runReadonlyProcess({
|
|
98
109
|
executable,
|
|
99
110
|
args,
|
|
@@ -225,9 +236,9 @@ export function runReadonlyProcess({
|
|
|
225
236
|
// facts that actually diagnose the turn — the exit code, or a clean exit with nothing to
|
|
226
237
|
// show — were discarded by the `||` and never reached the human. A warning is not a cause.
|
|
227
238
|
const printed = stderr.trim();
|
|
228
|
-
// The room keeps one line of a failure, so
|
|
239
|
+
// The room keeps one line of a failure, so a useful diagnostic from stderr rides on it —
|
|
229
240
|
// labelled as output, the way a timeout carries it, and never as the cause.
|
|
230
|
-
const lastLine = printed
|
|
241
|
+
const lastLine = failureLine(printed);
|
|
231
242
|
const why = response.error ?? ((code === 0
|
|
232
243
|
? t('{label} exited cleanly without an answer.', { label })
|
|
233
244
|
: endedBy(code, closedBy, label)) + (lastLine ? t(' Last output: {output}', { output: lastLine.slice(0, 200) }) : ''));
|