@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
package/src/adapters/claude.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { ENV_SECRETS } from '../checkpoint.mjs';
|
|
4
4
|
import { runReadonlyProcess } from './process.mjs';
|
|
5
5
|
import { claudeSubagents, jsonLines } from './subagents.mjs';
|
|
6
|
+
import { claudeSteps } from './steps.mjs';
|
|
6
7
|
|
|
7
8
|
// dontAsk denies any tool use that is not pre-approved, so under a lease the
|
|
8
9
|
// Write/Edit tools exist but only paths inside the lease directory are
|
|
@@ -131,7 +132,7 @@ export function claudeProgress(output, { root = null } = {}) {
|
|
|
131
132
|
if (event?.type !== 'assistant' || event.parent_tool_use_id) continue;
|
|
132
133
|
for (const part of event.message?.content ?? []) if (part?.type === 'text') chars += String(part.text ?? '').length;
|
|
133
134
|
}
|
|
134
|
-
return { chars, subagents: claudeSubagents(events, { root }) };
|
|
135
|
+
return { chars, subagents: claudeSubagents(events, { root }), steps: claudeSteps(events, { root }) };
|
|
135
136
|
}
|
|
136
137
|
|
|
137
138
|
export function invokeClaude({ executable, projectRoot, prompt, timeoutMs = 120000, signal, model = null, effort = null, attachments = [], lease = null, scopes = null, imageStudio = null, memoryServer = null, mcpServers = [], onProgress = null }) {
|
package/src/adapters/codex.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// SPDX-License-Identifier: BUSL-1.1
|
|
2
2
|
// MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
|
|
3
|
+
import { codexSteps } from './steps.mjs';
|
|
3
4
|
import { readdir } from 'node:fs/promises';
|
|
4
5
|
import { homedir } from 'node:os';
|
|
5
6
|
import { join } from 'node:path';
|
|
@@ -134,7 +135,7 @@ export async function codexGeneratedImages(threadId, { home = process.env.CODEX_
|
|
|
134
135
|
export const CODEX_SUBAGENT_NOTE = 'If you start a subagent: this run keeps no conversation history, so never ask the subagent to inherit or fork this conversation. Give it the whole task in its own message.';
|
|
135
136
|
export async function invokeCodex({ executable, projectRoot, prompt, timeoutMs = 120000, signal, model = null, effort = null, attachments = [], lease = null, scopes = null, memoryServer = null, mcpServers = [], onProgress = null }) {
|
|
136
137
|
const result = await runReadonlyProcess({
|
|
137
|
-
onProgress: onProgress ? (out) => { const said = parseCodexOutput(out); onProgress({ chars: said.text.length, subagents: said.subagents ?? [] }); } : null,
|
|
138
|
+
onProgress: onProgress ? (out) => { const said = parseCodexOutput(out); onProgress({ chars: said.text.length, subagents: said.subagents ?? [], steps: codexSteps(out, { root: projectRoot }) }); } : null,
|
|
138
139
|
executable,
|
|
139
140
|
args: buildCodexArgs({ projectRoot, prompt: lease?.airlock ? prompt : `${prompt}\n\n${CODEX_SUBAGENT_NOTE}`, model, effort, attachments, lease, scopes, memoryServer, mcpServers }),
|
|
140
141
|
cwd: lease ? lease.outDir : projectRoot,
|
package/src/adapters/cursor.mjs
CHANGED
|
@@ -26,6 +26,7 @@ import { tmpdir } from 'node:os';
|
|
|
26
26
|
import { join } from 'node:path';
|
|
27
27
|
import { ENV_SECRETS } from '../checkpoint.mjs';
|
|
28
28
|
import { runReadonlyProcess } from './process.mjs';
|
|
29
|
+
import { cursorSteps } from './steps.mjs';
|
|
29
30
|
|
|
30
31
|
// What the turn's own configuration allows: reading, and nothing else.
|
|
31
32
|
export const READONLY_CONFIG = {
|
|
@@ -58,13 +59,15 @@ export function cursorConfigFor(lease = null) {
|
|
|
58
59
|
};
|
|
59
60
|
}
|
|
60
61
|
|
|
61
|
-
export function buildCursorArgs({ projectRoot, prompt, model = process.env.PULSE_CURSOR_MODEL || null, lease = null }) {
|
|
62
|
+
export function buildCursorArgs({ projectRoot, prompt, model = process.env.PULSE_CURSOR_MODEL || null, lease = null, scopes = null }) {
|
|
62
63
|
return [
|
|
63
64
|
'--print',
|
|
64
65
|
'--output-format', 'stream-json',
|
|
65
66
|
// Reading: Cursor's own ask mode. Writing: its agent mode, with the changes applied (`--force`)
|
|
66
|
-
// under the turn's configuration above.
|
|
67
|
-
|
|
67
|
+
// under the turn's configuration above. Reading with Web access on: ask mode with `--force`, so its
|
|
68
|
+
// search and page reader run without an approval nobody could give; the configuration still denies
|
|
69
|
+
// every command and every write (tried 2026-11-10: it searched, wrote nothing, ran nothing).
|
|
70
|
+
...(lease ? ['--force'] : ['--mode', 'ask', ...(scopes?.web ? ['--force'] : [])]),
|
|
68
71
|
// A headless run cannot answer the «trust this folder?» question; the project is the human's.
|
|
69
72
|
'--trust',
|
|
70
73
|
'--workspace', projectRoot,
|
|
@@ -117,14 +120,14 @@ export const ONLY_AUTO = /Free plans can only use Auto|Named models unavailable/
|
|
|
117
120
|
let onlyAuto = false;
|
|
118
121
|
export const cursorOnlyAuto = () => onlyAuto;
|
|
119
122
|
|
|
120
|
-
export async function invokeCursor({ executable, projectRoot, prompt, timeoutMs = 120000, signal, model = null, lease = null, onProgress = null }) {
|
|
123
|
+
export async function invokeCursor({ executable, projectRoot, prompt, timeoutMs = 120000, signal, model = null, lease = null, scopes = null, onProgress = null }) {
|
|
121
124
|
const configDir = await mkdtemp(join(tmpdir(), 'madre-cursor-'));
|
|
122
125
|
try {
|
|
123
126
|
await writeFile(join(configDir, 'cli-config.json'), `${JSON.stringify(cursorConfigFor(lease), null, 2)}\n`);
|
|
124
127
|
const run = (named) => runReadonlyProcess({
|
|
125
|
-
onProgress: onProgress ? (out) => onProgress({ chars: out.length }) : null,
|
|
128
|
+
onProgress: onProgress ? (out) => onProgress({ chars: out.length, steps: cursorSteps(out, { root: projectRoot }) }) : null,
|
|
126
129
|
executable,
|
|
127
|
-
args: buildCursorArgs({ projectRoot, prompt, lease, ...(named ? { model: named } : {}) }),
|
|
130
|
+
args: buildCursorArgs({ projectRoot, prompt, lease, scopes, ...(named ? { model: named } : {}) }),
|
|
128
131
|
cwd: projectRoot,
|
|
129
132
|
env: cursorEnvironment(process.env, { configDir }),
|
|
130
133
|
timeoutMs,
|
|
@@ -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
|
@@ -6,6 +6,7 @@ import { t } from '../i18n.mjs';
|
|
|
6
6
|
import { homedir, tmpdir } from 'node:os';
|
|
7
7
|
import { join } from 'node:path';
|
|
8
8
|
import { runReadonlyProcess } from './process.mjs';
|
|
9
|
+
import { geminiSteps } from './steps.mjs';
|
|
9
10
|
|
|
10
11
|
// Where each rule stands. The higher one wins, and Gemini CLI refuses a policy whose priorities
|
|
11
12
|
// go past 999 ("priority must be <= 999 to prevent tier overflow"): a refused policy loads no rule
|
|
@@ -329,6 +330,7 @@ export async function invokeGemini({
|
|
|
329
330
|
fallbackModel = process.env.PULSE_GEMINI_FALLBACK_MODEL ?? 'gemini-3-flash-preview',
|
|
330
331
|
failFastMs = 15000,
|
|
331
332
|
run = runReadonlyProcess,
|
|
333
|
+
onProgress = null,
|
|
332
334
|
}) {
|
|
333
335
|
const runtimeRoot = await mkdtemp(join(tmpdir(), 'pulse-gemini-'));
|
|
334
336
|
const policyPath = join(runtimeRoot, 'readonly.toml');
|
|
@@ -365,6 +367,8 @@ export async function invokeGemini({
|
|
|
365
367
|
signal,
|
|
366
368
|
label: 'Gemini',
|
|
367
369
|
parse: parseGeminiOutput,
|
|
370
|
+
// What it has written so far, and each tool it calls (src/adapters/steps.mjs).
|
|
371
|
+
onProgress: onProgress ? (out) => onProgress({ chars: parseGeminiOutput(out).text.length, steps: geminiSteps(out, { root: projectRoot }) }) : null,
|
|
368
372
|
});
|
|
369
373
|
} catch (error) {
|
|
370
374
|
const produced = parseGeminiOutput(error.partialOutput ?? '').text;
|
|
@@ -372,25 +376,27 @@ export async function invokeGemini({
|
|
|
372
376
|
// The spare failed too, for whatever reason (a model this account is not given, say): what
|
|
373
377
|
// the person needs to read is why the model they chose failed, not why the spare did.
|
|
374
378
|
if (switched && firstTrouble && !produced && !signal?.aborted) {
|
|
375
|
-
|
|
379
|
+
// In the room's words, like the sentence before it (L-8: «… (also tried …)» closed a Spanish notice).
|
|
380
|
+
error.message = `${firstTrouble.message} ${firstTrouble.hint}${t(' (also tried {model})', { model: fallbackModel })}`;
|
|
376
381
|
error.code = firstTrouble.code;
|
|
377
382
|
throw error;
|
|
378
383
|
}
|
|
379
|
-
if (diagnosis?.code === 'AUTH' || diagnosis?.code === 'INELIGIBLE'
|
|
384
|
+
if (diagnosis?.code === 'AUTH' || diagnosis?.code === 'INELIGIBLE') {
|
|
380
385
|
error.message = `${diagnosis.message} ${diagnosis.hint}`;
|
|
381
386
|
error.code = diagnosis.code;
|
|
382
387
|
throw error;
|
|
383
388
|
}
|
|
384
|
-
// Capacity trouble (503) or
|
|
385
|
-
// try on a lighter, explicit model before giving up
|
|
386
|
-
|
|
389
|
+
// Capacity trouble (503), rate limit (429), or depleted credits on the chosen model: one more
|
|
390
|
+
// try on a lighter, explicit model before giving up (L-12: a free-tier Flash model may answer
|
|
391
|
+
// when the default preview/pro router refuses for lack of prepayment credits).
|
|
392
|
+
if ((diagnosis?.code === 'UNAVAILABLE' || diagnosis?.code === 'RATE_LIMITED' || diagnosis?.code === 'CREDITS_DEPLETED') && !produced && !signal?.aborted && fallbackModel && !switched && currentModel !== fallbackModel) {
|
|
387
393
|
switched = true;
|
|
388
394
|
firstTrouble = diagnosis;
|
|
389
395
|
currentModel = fallbackModel;
|
|
390
396
|
continue;
|
|
391
397
|
}
|
|
392
|
-
if (diagnosis?.code === 'UNAVAILABLE' || diagnosis?.code === 'RATE_LIMITED') {
|
|
393
|
-
error.message = `${diagnosis.message} ${diagnosis.hint}${switched ?
|
|
398
|
+
if (diagnosis?.code === 'UNAVAILABLE' || diagnosis?.code === 'RATE_LIMITED' || diagnosis?.code === 'CREDITS_DEPLETED') {
|
|
399
|
+
error.message = `${diagnosis.message} ${diagnosis.hint}${switched ? t(' (also tried {model})', { model: fallbackModel }) : ''}`;
|
|
394
400
|
error.code = diagnosis.code;
|
|
395
401
|
throw error;
|
|
396
402
|
}
|