synabun 2.2.2 → 2.3.0
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.md +26 -0
- package/README.md +1 -1
- package/docs/whatsapp.md +52 -20
- package/lib/mcp-build.js +519 -0
- package/lib/mcp-dist.js +10 -4
- package/lib/server-supervisor.js +7 -1
- package/lib/virustotal.mjs +4 -2
- package/mcp-server/dist/http.d.ts +38 -0
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +75 -7
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/services/browser-route-flow.d.ts +3 -2
- package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
- package/mcp-server/dist/services/browser-route-flow.js +4 -3
- package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
- package/mcp-server/dist/services/embedding-service.d.ts.map +1 -1
- package/mcp-server/dist/services/embedding-service.js +2 -1
- package/mcp-server/dist/services/embedding-service.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +21 -0
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +76 -4
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.js +2 -2
- package/mcp-server/dist/services/tool-catalog.js.map +1 -1
- package/mcp-server/dist/tools/agents.d.ts +3 -2
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +6 -4
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +3 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +30 -8
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-navigate.d.ts +3 -3
- package/mcp-server/dist/tools/browser-navigate.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-navigate.js +19 -16
- package/mcp-server/dist/tools/browser-navigate.js.map +1 -1
- package/mcp-server/dist/tools/browser-observe.d.ts +2 -1
- package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-observe.js +61 -20
- package/mcp-server/dist/tools/browser-observe.js.map +1 -1
- package/mcp-server/dist/tools/morelogin.d.ts +13 -3
- package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
- package/mcp-server/dist/tools/morelogin.js +81 -20
- package/mcp-server/dist/tools/morelogin.js.map +1 -1
- package/mcp-server/dist/tools/youtube/upload.d.ts.map +1 -1
- package/mcp-server/dist/tools/youtube/upload.js +225 -88
- package/mcp-server/dist/tools/youtube/upload.js.map +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +79 -7
- package/mcp-server/src/services/browser-route-flow.ts +4 -3
- package/mcp-server/src/services/embedding-service.ts +2 -1
- package/mcp-server/src/services/neural-interface.ts +77 -4
- package/mcp-server/src/services/tool-catalog.ts +2 -2
- package/mcp-server/src/tools/agents.ts +8 -4
- package/mcp-server/src/tools/browser-advanced.ts +29 -8
- package/mcp-server/src/tools/browser-navigate.ts +19 -16
- package/mcp-server/src/tools/browser-observe.ts +62 -20
- package/mcp-server/src/tools/morelogin.ts +81 -20
- package/mcp-server/src/tools/youtube/upload.ts +218 -99
- package/neural-interface/i18n/en.json +631 -123
- package/neural-interface/i18n/pt-BR.json +518 -10
- package/neural-interface/lib/assistant-api.js +26 -0
- package/neural-interface/lib/assistant-brains/claude.js +5 -0
- package/neural-interface/lib/assistant-catalog.js +114 -1
- package/neural-interface/lib/assistant-dispatch.js +71 -1
- package/neural-interface/lib/assistant-persona.js +14 -7
- package/neural-interface/lib/assistant-router.js +6 -4
- package/neural-interface/lib/assistant-runtime.js +3 -0
- package/neural-interface/lib/assistant-task-prompt.js +5 -0
- package/neural-interface/lib/automation-approval.js +249 -0
- package/neural-interface/lib/automation-browser-owner-access.js +82 -0
- package/neural-interface/lib/backup-service.js +16 -1
- package/neural-interface/lib/browser-background-tab.js +72 -3
- package/neural-interface/lib/browser-extraction.js +106 -45
- package/neural-interface/lib/browser-profile-choices.js +143 -0
- package/neural-interface/lib/browser-profiles.js +142 -0
- package/neural-interface/lib/browser-tab-recovery.js +153 -0
- package/neural-interface/lib/browser-tool-policy.js +2 -0
- package/neural-interface/lib/chromium-on-device-model.js +67 -0
- package/neural-interface/lib/claude-agent-bridge.js +7 -4
- package/neural-interface/lib/claude-model-catalog.js +12 -0
- package/neural-interface/lib/effort-levels.js +28 -2
- package/neural-interface/lib/local-profile-proxy.js +362 -0
- package/neural-interface/lib/local-profiles.js +929 -0
- package/neural-interface/lib/loop-logger.js +25 -4
- package/neural-interface/lib/maritaca/api.js +179 -0
- package/neural-interface/lib/maritaca/attachments.js +44 -0
- package/neural-interface/lib/maritaca/client.js +362 -0
- package/neural-interface/lib/maritaca/key-store.js +122 -0
- package/neural-interface/lib/maritaca/models.js +181 -0
- package/neural-interface/lib/maritaca/modes.js +39 -0
- package/neural-interface/lib/maritaca/opencode-proxy.js +236 -0
- package/neural-interface/lib/maritaca/opencode-stream.js +345 -0
- package/neural-interface/lib/maritaca/opencode.js +218 -0
- package/neural-interface/lib/maritaca/panel-bridge.js +273 -0
- package/neural-interface/lib/maritaca/sessions.js +198 -0
- package/neural-interface/lib/morelogin-agent-profiles.js +149 -0
- package/neural-interface/lib/morelogin.js +278 -14
- package/neural-interface/lib/native-loop-providers.js +3 -1
- package/neural-interface/lib/owner-authority.js +30 -12
- package/neural-interface/lib/page-session.js +43 -17
- package/neural-interface/lib/request-gate.js +2 -0
- package/neural-interface/lib/system-activity.js +1 -1
- package/neural-interface/lib/terminal-tokens.js +82 -5
- package/neural-interface/package-lock.json +3 -2
- package/neural-interface/package.json +2 -1
- package/neural-interface/public/assets/mascot/README.md +11 -0
- package/neural-interface/public/assets/mascot/ask.gif +0 -0
- package/neural-interface/public/assets/mascot/ask.png +0 -0
- package/neural-interface/public/assets/mascot/blocked.gif +0 -0
- package/neural-interface/public/assets/mascot/blocked.png +0 -0
- package/neural-interface/public/assets/mascot/budget.gif +0 -0
- package/neural-interface/public/assets/mascot/budget.png +0 -0
- package/neural-interface/public/assets/mascot/computer.gif +0 -0
- package/neural-interface/public/assets/mascot/computer.png +0 -0
- package/neural-interface/public/assets/mascot/edit.gif +0 -0
- package/neural-interface/public/assets/mascot/edit.png +0 -0
- package/neural-interface/public/assets/mascot/error.gif +0 -0
- package/neural-interface/public/assets/mascot/error.png +0 -0
- package/neural-interface/public/assets/mascot/hover-attention.gif +0 -0
- package/neural-interface/public/assets/mascot/hover-attention.png +0 -0
- package/neural-interface/public/assets/mascot/idle-hero.gif +0 -0
- package/neural-interface/public/assets/mascot/idle-hero.png +0 -0
- package/neural-interface/public/assets/mascot/idle.gif +0 -0
- package/neural-interface/public/assets/mascot/idle.png +0 -0
- package/neural-interface/public/assets/mascot/manifest.json +254 -0
- package/neural-interface/public/assets/mascot/mcp.gif +0 -0
- package/neural-interface/public/assets/mascot/mcp.png +0 -0
- package/neural-interface/public/assets/mascot/memory.gif +0 -0
- package/neural-interface/public/assets/mascot/memory.png +0 -0
- package/neural-interface/public/assets/mascot/offline.gif +0 -0
- package/neural-interface/public/assets/mascot/offline.png +0 -0
- package/neural-interface/public/assets/mascot/pick.gif +0 -0
- package/neural-interface/public/assets/mascot/pick.png +0 -0
- package/neural-interface/public/assets/mascot/plan.gif +0 -0
- package/neural-interface/public/assets/mascot/plan.png +0 -0
- package/neural-interface/public/assets/mascot/present.gif +0 -0
- package/neural-interface/public/assets/mascot/present.png +0 -0
- package/neural-interface/public/assets/mascot/project.gif +0 -0
- package/neural-interface/public/assets/mascot/project.png +0 -0
- package/neural-interface/public/assets/mascot/read.gif +0 -0
- package/neural-interface/public/assets/mascot/read.png +0 -0
- package/neural-interface/public/assets/mascot/runs.gif +0 -0
- package/neural-interface/public/assets/mascot/runs.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/automation.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/automation.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/browser.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/browser.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/code.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/code.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/complex.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/complex.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/computer.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/computer.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/design.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/design.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/edit.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/edit.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/generic.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/generic.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/image_gen.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/image_gen.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/manifest.json +173 -0
- package/neural-interface/public/assets/mascot/scenes/memory.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/memory.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/quick.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/quick.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/read.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/read.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/research.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/research.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/review.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/review.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/search.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/search.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/shell.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/shell.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/thinking.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/thinking.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/video_gen.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/video_gen.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/web.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/web.png +0 -0
- package/neural-interface/public/assets/mascot/search.gif +0 -0
- package/neural-interface/public/assets/mascot/search.png +0 -0
- package/neural-interface/public/assets/mascot/shell.gif +0 -0
- package/neural-interface/public/assets/mascot/shell.png +0 -0
- package/neural-interface/public/assets/mascot/skill.gif +0 -0
- package/neural-interface/public/assets/mascot/skill.png +0 -0
- package/neural-interface/public/assets/mascot/sleep.gif +0 -0
- package/neural-interface/public/assets/mascot/sleep.png +0 -0
- package/neural-interface/public/assets/mascot/subagent.gif +0 -0
- package/neural-interface/public/assets/mascot/subagent.png +0 -0
- package/neural-interface/public/assets/mascot/success.gif +0 -0
- package/neural-interface/public/assets/mascot/success.png +0 -0
- package/neural-interface/public/assets/mascot/think.gif +0 -0
- package/neural-interface/public/assets/mascot/think.png +0 -0
- package/neural-interface/public/assets/mascot/wait.gif +0 -0
- package/neural-interface/public/assets/mascot/wait.png +0 -0
- package/neural-interface/public/assets/mascot/watch.gif +0 -0
- package/neural-interface/public/assets/mascot/watch.png +0 -0
- package/neural-interface/public/assets/mascot/web.gif +0 -0
- package/neural-interface/public/assets/mascot/web.png +0 -0
- package/neural-interface/public/onboarding.html +14 -1
- package/neural-interface/public/shared/agent-runtime-options.js +49 -8
- package/neural-interface/public/shared/agy/agy-panel.js +2 -2
- package/neural-interface/public/shared/api.js +4 -4
- package/neural-interface/public/shared/assistant/asst-ask-styles.js +8 -8
- package/neural-interface/public/shared/assistant/asst-ask.js +1 -1
- package/neural-interface/public/shared/assistant/asst-brain-picker.js +99 -9
- package/neural-interface/public/shared/assistant/asst-control.js +1 -1
- package/neural-interface/public/shared/assistant/asst-limit-wait.js +4 -4
- package/neural-interface/public/shared/assistant/asst-panel.js +6 -2
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -4
- package/neural-interface/public/shared/assistant/asst-render.js +6 -6
- package/neural-interface/public/shared/assistant/asst-route-models.js +64 -4
- package/neural-interface/public/shared/assistant/asst-route.js +24 -7
- package/neural-interface/public/shared/assistant/asst-routes-editor.js +154 -39
- package/neural-interface/public/shared/assistant/asst-run-stage.js +3 -3
- package/neural-interface/public/shared/assistant/asst-scene-styles.js +8 -111
- package/neural-interface/public/shared/assistant/asst-scenes.js +46 -318
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +2 -2
- package/neural-interface/public/shared/assistant/asst-state.js +72 -2
- package/neural-interface/public/shared/assistant/asst-styles.js +58 -14
- package/neural-interface/public/shared/automation-approval-view.js +75 -0
- package/neural-interface/public/shared/cdx/cdx-panel.js +2 -2
- package/neural-interface/public/shared/context-menu-model.js +2 -0
- package/neural-interface/public/shared/editor/editor-panel-logic.js +10 -0
- package/neural-interface/public/shared/editor/editor-panel.js +10 -2
- package/neural-interface/public/shared/html-shell.js +30 -22
- package/neural-interface/public/shared/morelogin-profile-choices.js +107 -0
- package/neural-interface/public/shared/morelogin-profile-field.js +186 -0
- package/neural-interface/public/shared/mtc/mtc-client.js +181 -0
- package/neural-interface/public/shared/mtc/mtc-compose.js +40 -0
- package/neural-interface/public/shared/mtc/mtc-copy.js +253 -0
- package/neural-interface/public/shared/mtc/mtc-logic.js +478 -0
- package/neural-interface/public/shared/mtc/mtc-panel.js +1354 -0
- package/neural-interface/public/shared/mtc/mtc-render.js +172 -0
- package/neural-interface/public/shared/mtc/mtc-styles.js +437 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +6 -2
- package/neural-interface/public/shared/provider-icons.js +3 -0
- package/neural-interface/public/shared/schedules-view.js +7 -0
- package/neural-interface/public/shared/server-back.js +50 -0
- package/neural-interface/public/shared/settings/settings-browser-owner-access.js +72 -0
- package/neural-interface/public/shared/settings/settings-data.js +1 -0
- package/neural-interface/public/shared/settings/settings-ia.js +3 -1
- package/neural-interface/public/shared/settings/settings-local-profiles.js +153 -0
- package/neural-interface/public/shared/settings/settings-maritaca-opencode.js +105 -0
- package/neural-interface/public/shared/sidepanel-session-status.js +16 -2
- package/neural-interface/public/shared/state.js +1 -1
- package/neural-interface/public/shared/styles.css +356 -157
- package/neural-interface/public/shared/synabun-mascot-assets.js +67 -0
- package/neural-interface/public/shared/synabun-mascot.js +136 -12
- package/neural-interface/public/shared/synabun-ticker.js +3 -0
- package/neural-interface/public/shared/topright-overflow-logic.js +1 -0
- package/neural-interface/public/shared/ui-automation-approval.js +188 -0
- package/neural-interface/public/shared/ui-automation-studio.js +130 -90
- package/neural-interface/public/shared/ui-claude-panel.js +50 -2
- package/neural-interface/public/shared/ui-maritaca-panel.js +15 -0
- package/neural-interface/public/shared/ui-navbar.js +17 -0
- package/neural-interface/public/shared/ui-panels.js +3 -1
- package/neural-interface/public/shared/ui-schedules-studio.js +118 -17
- package/neural-interface/public/shared/ui-scroll-follow.js +3 -0
- package/neural-interface/public/shared/ui-settings.js +590 -27
- package/neural-interface/public/shared/ui-sidepanel-session-entry.js +8 -2
- package/neural-interface/public/shared/ui-sidepanel-sessions.js +3 -3
- package/neural-interface/public/shared/ui-sidepanel-tray.js +24 -0
- package/neural-interface/public/shared/ui-sidepanel-windows.js +1 -1
- package/neural-interface/scripts/build-mascot-assets.mjs +30 -0
- package/neural-interface/server.js +1784 -195
- package/npm-shrinkwrap.json +5 -17
- package/package.json +5 -6
- package/postinstall.js +38 -39
- package/setup.js +33 -31
- package/skills/synabun/modules/changelog.md +14 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun — Maritaca AI: the API key and the panel settings
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// The key lives in SynaBun's own file, DATA_HOME/data/maritaca/.synabun-api-key (0600, atomic
|
|
6
|
+
// replace, never followed as a link: the same discipline as lib/claude-profile-api-key.js), or
|
|
7
|
+
// comes from the environment (MARITACA_API_KEY, the name Maritaca's own library reads) when no
|
|
8
|
+
// file is saved. It is never returned to a page: GET answers whether a key is set and where it
|
|
9
|
+
// comes from, with a masked tail. The other settings (default model, reasoning effort, system
|
|
10
|
+
// prompt) are plain JSON next to it.
|
|
11
|
+
|
|
12
|
+
import { closeSync, constants, fstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import { randomUUID } from 'node:crypto';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import { MARITACA_DEFAULT_MODEL, findMaritacaModel, normalizeMaritacaEffort } from './models.js';
|
|
16
|
+
|
|
17
|
+
export const MARITACA_KEY_FILE = '.synabun-api-key';
|
|
18
|
+
export const MARITACA_SETTINGS_FILE = 'settings.json';
|
|
19
|
+
export const MARITACA_ENV_KEY = 'MARITACA_API_KEY';
|
|
20
|
+
const MAX_SYSTEM_PROMPT = 8000;
|
|
21
|
+
|
|
22
|
+
export function keyStoreError(code, message, status = 400) {
|
|
23
|
+
return Object.assign(new Error(message), { code, status });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The key as it is saved: trimmed, one line, 16–4096 printable ASCII characters. Throws INVALID_KEY. */
|
|
27
|
+
export function validateMaritacaKey(key) {
|
|
28
|
+
if (typeof key !== 'string' || key.length > 4096) throw keyStoreError('INVALID_KEY', "That doesn't look like a Maritaca API key.");
|
|
29
|
+
const value = key.trim();
|
|
30
|
+
if (value.length < 16 || !/^[\x21-\x7e]+$/.test(value)) throw keyStoreError('INVALID_KEY', "That doesn't look like a Maritaca API key.");
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** What a page may see of a key: its last four characters. */
|
|
35
|
+
export function maskKey(key) {
|
|
36
|
+
const s = String(key || '');
|
|
37
|
+
return s.length >= 8 ? `…${s.slice(-4)}` : '…';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const DEFAULTS = Object.freeze({ model: MARITACA_DEFAULT_MODEL, reasoningEffort: null, systemPrompt: '', temperature: null });
|
|
41
|
+
|
|
42
|
+
/** Settings as saved → settings as used: an unknown model falls back, an unknown effort is dropped. */
|
|
43
|
+
export function normalizeMaritacaSettings(raw = {}) {
|
|
44
|
+
const out = { ...DEFAULTS };
|
|
45
|
+
const src = raw && typeof raw === 'object' ? raw : {};
|
|
46
|
+
const model = findMaritacaModel(src.model);
|
|
47
|
+
out.model = model ? model.id : typeof src.model === 'string' && src.model.trim() ? src.model.trim().slice(0, 80) : MARITACA_DEFAULT_MODEL;
|
|
48
|
+
// An alias (xhigh / max / minimal, from a settings file written before 2026-11-08) is read as the level it names.
|
|
49
|
+
out.reasoningEffort = normalizeMaritacaEffort(src.reasoningEffort);
|
|
50
|
+
out.systemPrompt = typeof src.systemPrompt === 'string' ? src.systemPrompt.slice(0, MAX_SYSTEM_PROMPT) : '';
|
|
51
|
+
const temp = Number(src.temperature);
|
|
52
|
+
out.temperature = src.temperature === null || src.temperature === undefined || src.temperature === '' ? null : Number.isFinite(temp) ? Math.min(2, Math.max(0, temp)) : null;
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function createMaritacaKeyStore({ dir, env = process.env } = {}) {
|
|
57
|
+
if (!dir) throw new Error('createMaritacaKeyStore needs dir');
|
|
58
|
+
const keyPath = join(dir, MARITACA_KEY_FILE);
|
|
59
|
+
const settingsPath = join(dir, MARITACA_SETTINGS_FILE);
|
|
60
|
+
|
|
61
|
+
function readFileKey() {
|
|
62
|
+
let fd;
|
|
63
|
+
try {
|
|
64
|
+
fd = openSync(keyPath, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
65
|
+
const stat = fstatSync(fd);
|
|
66
|
+
if (!stat.isFile() || (process.platform !== 'win32' && (stat.mode & 0o077))) throw keyStoreError('UNSAFE_KEY_FILE', 'The saved key file has unsafe permissions. Save the key again.', 500);
|
|
67
|
+
return validateMaritacaKey(readFileSync(fd, 'utf8'));
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (error.code === 'ENOENT') return null;
|
|
70
|
+
if (error.code === 'INVALID_KEY') return null;
|
|
71
|
+
throw error;
|
|
72
|
+
} finally { if (fd !== undefined) closeSync(fd); }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The key to use: the saved file first, then the environment. null without either. */
|
|
76
|
+
function readKey() {
|
|
77
|
+
const file = readFileKey();
|
|
78
|
+
if (file) return file;
|
|
79
|
+
const fromEnv = typeof env[MARITACA_ENV_KEY] === 'string' ? env[MARITACA_ENV_KEY].trim() : '';
|
|
80
|
+
try { return fromEnv ? validateMaritacaKey(fromEnv) : null; } catch { return null; }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Where the key in use comes from: 'file' | 'env' | null. */
|
|
84
|
+
function keySource() {
|
|
85
|
+
if (readFileKey()) return 'file';
|
|
86
|
+
const fromEnv = typeof env[MARITACA_ENV_KEY] === 'string' ? env[MARITACA_ENV_KEY].trim() : '';
|
|
87
|
+
try { return fromEnv && validateMaritacaKey(fromEnv) ? 'env' : null; } catch { return null; }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function saveKey(key) {
|
|
91
|
+
const value = validateMaritacaKey(key);
|
|
92
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
93
|
+
const temp = `${keyPath}.${randomUUID()}.tmp`;
|
|
94
|
+
try { writeFileSync(temp, value, { mode: 0o600, flag: 'wx' }); renameSync(temp, keyPath); }
|
|
95
|
+
finally { rmSync(temp, { force: true }); }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function clearKey() { rmSync(keyPath, { force: true }); }
|
|
99
|
+
|
|
100
|
+
function readSettings() {
|
|
101
|
+
try { return normalizeMaritacaSettings(JSON.parse(readFileSync(settingsPath, 'utf8'))); }
|
|
102
|
+
catch { return normalizeMaritacaSettings({}); }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function saveSettings(patch = {}) {
|
|
106
|
+
const next = normalizeMaritacaSettings({ ...readSettings(), ...(patch && typeof patch === 'object' ? patch : {}) });
|
|
107
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
108
|
+
const temp = `${settingsPath}.${randomUUID()}.tmp`;
|
|
109
|
+
try { writeFileSync(temp, JSON.stringify(next, null, 2), { mode: 0o600, flag: 'wx' }); renameSync(temp, settingsPath); }
|
|
110
|
+
finally { rmSync(temp, { force: true }); }
|
|
111
|
+
return next;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** What a page is told: never the key. */
|
|
115
|
+
function status() {
|
|
116
|
+
const source = keySource();
|
|
117
|
+
const key = source ? readKey() : null;
|
|
118
|
+
return { configured: !!key, source, masked: key ? maskKey(key) : null, settings: readSettings() };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return { dir, readKey, keySource, saveKey, clearKey, readSettings, saveSettings, status };
|
|
122
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun — Maritaca AI: the Sabiá model table (pure)
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// What Maritaca's documentation says about each model, read 2026-11-06 and again 2026-11-08:
|
|
6
|
+
// https://docs.maritaca.ai/pt/modelos (ids, aliases, context, max output, capabilities)
|
|
7
|
+
// https://docs.maritaca.ai/pt/precos (BRL per million tokens: input, output, cached input)
|
|
8
|
+
// https://docs.maritaca.ai/pt/raciocinio (reasoning_effort: none · minimal = low · medium · high = xhigh = max; default xhigh)
|
|
9
|
+
// 2026-11-08: the S5 family's output went to 64K, S5 Nano (open weights, 256K context) joined the list, and the
|
|
10
|
+
// reasoning levels are offered as Off / Low / Medium / High (`high` is the API's `xhigh`, its default). The S5 rows'
|
|
11
|
+
// reasoning is encrypted (never streamed as text); only S5 Nano's arrives as text (`reasoningVisible`).
|
|
12
|
+
// Prices are in Brazilian reais (unit 'brl_per_mtok'), never converted: the Assistant's USD
|
|
13
|
+
// price table (lib/assistant-pricing.js) is for the dispatch providers and stays untouched.
|
|
14
|
+
// Maritaca is a chat API, not a coding agent: it is a sidepanel provider and a chat-only
|
|
15
|
+
// entry of the catalog, never a worker or a brain (docs/maritaca-sidepanel.md).
|
|
16
|
+
//
|
|
17
|
+
// Sampling (`fixedSampling`, read by client.js `maritacaFixedSampling`): the docs give one default for every model
|
|
18
|
+
// (https://docs.maritaca.ai/api/pt/completion: temperature 0.7, top_p 0.95) and no per-model rule, so it was probed
|
|
19
|
+
// live on 2026-11-06 with max_tokens 5: S5-free refused temperature 0.3 ("Only the default (1)"), top_p 0.5 ("Only the
|
|
20
|
+
// default (0.95)") and temperature with reasoning_effort none; sabia-4-thinking, sabia-4-thinking-br-sp and sabiazinho-4
|
|
21
|
+
// answered 200 to both. So the S5 family takes only its defaults and Sabiá 4 Thinking samples freely, though it reasons.
|
|
22
|
+
//
|
|
23
|
+
// The API's own model list (GET /models, when it answers) is merged over this table by
|
|
24
|
+
// client.js `listModels`: a model the API lists and this table does not know is offered with
|
|
25
|
+
// what the API said and `known: false`; a model here the API no longer lists is kept, marked
|
|
26
|
+
// `listed: false`, so a saved default still resolves.
|
|
27
|
+
|
|
28
|
+
export const MARITACA_PRICING_VERIFIED = '2026-11-08';
|
|
29
|
+
export const MARITACA_PRICING_SOURCE = 'https://docs.maritaca.ai/pt/precos';
|
|
30
|
+
export const MARITACA_MODELS_SOURCE = 'https://docs.maritaca.ai/pt/modelos';
|
|
31
|
+
export const MARITACA_DEFAULT_MODEL = 'sabiazinho-4';
|
|
32
|
+
/** The reasoning levels SynaBun offers, in order (docs → Raciocínio): `none` turns reasoning off; `high` is the API's default. */
|
|
33
|
+
export const MARITACA_REASONING_EFFORTS = Object.freeze(['none', 'low', 'medium', 'high']);
|
|
34
|
+
/** The other spellings the API takes for the same levels: `minimal` is `low`; `xhigh` and `max` are `high`. */
|
|
35
|
+
export const MARITACA_EFFORT_ALIASES = Object.freeze({ minimal: 'low', xhigh: 'high', max: 'high' });
|
|
36
|
+
|
|
37
|
+
/** A level as written (a saved setting, an older page, an alias) → the level SynaBun sends, or null for "the model's default". */
|
|
38
|
+
export function normalizeMaritacaEffort(value) {
|
|
39
|
+
const v = typeof value === 'string' ? value.trim().toLowerCase() : '';
|
|
40
|
+
if (!v) return null;
|
|
41
|
+
if (MARITACA_REASONING_EFFORTS.includes(v)) return v;
|
|
42
|
+
return MARITACA_EFFORT_ALIASES[v] || null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const price = (input, output, cacheRead) => Object.freeze({ input, output, cacheRead, unit: 'brl_per_mtok', basis: 'list' });
|
|
46
|
+
const FREE = Object.freeze({ input: 0, output: 0, cacheRead: 0, unit: 'brl_per_mtok', basis: 'free' });
|
|
47
|
+
const ONE_M = 1_000_000;
|
|
48
|
+
const K128 = 128_000;
|
|
49
|
+
const K256 = 256_000;
|
|
50
|
+
const K64 = 64_000;
|
|
51
|
+
|
|
52
|
+
/** Every model in the order the pickers show them. `aliases` are the other spellings the API accepts. */
|
|
53
|
+
export const MARITACA_MODELS = Object.freeze([
|
|
54
|
+
{
|
|
55
|
+
id: 'S5', label: 'Sabiá 5 (S5)', family: 's5', aliases: ['s5'],
|
|
56
|
+
tier: 'large', contextWindow: ONE_M, maxOutput: K64, reasoning: true, fixedSampling: true, efforts: MARITACA_REASONING_EFFORTS, defaultEffort: 'high',
|
|
57
|
+
toolcall: true, vision: false, price: price(0.5, 2.5, 0.05), region: 'global',
|
|
58
|
+
description: 'Native reasoning with adjustable intensity, 1M context, the cheapest of the family.',
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
id: 'S5-br-sp', label: 'Sabiá 5 BR-SP', family: 's5', aliases: ['s5-br-sp'],
|
|
62
|
+
tier: 'large', contextWindow: ONE_M, maxOutput: K64, reasoning: true, fixedSampling: true, efforts: MARITACA_REASONING_EFFORTS, defaultEffort: 'high',
|
|
63
|
+
toolcall: true, vision: false, price: price(0.65, 3.25, 0.065), region: 'br-sp',
|
|
64
|
+
description: 'S5 with inference 100% in Brazil (data residency), 30% over S5.',
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
id: 'S5-free', label: 'S5 (free)', family: 's5', aliases: ['s5-free'],
|
|
68
|
+
tier: 'large', contextWindow: ONE_M, maxOutput: K64, reasoning: true, fixedSampling: true, efforts: MARITACA_REASONING_EFFORTS, defaultEffort: 'high',
|
|
69
|
+
toolcall: false, vision: false, batch: false, flex: false, price: FREE, region: 'global', free: true,
|
|
70
|
+
// docs → Rate Limits: the free model has fixed limits whatever the plan (no batch / flex rates either).
|
|
71
|
+
rateLimit: Object.freeze({ requestsPerMinute: 60, tokensPerMinuteIn: 256_000, tokensPerMinuteOut: 256_000 }),
|
|
72
|
+
description: 'S5 free for a limited time (launch offer): text only, no tool calling, no batch or flex; fixed 60 requests and 256k tokens per minute in and out.',
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
id: 'S5-nano', label: 'Sabiá 5 Nano (S5 Nano)', family: 's5', aliases: ['s5-nano'],
|
|
76
|
+
tier: 'small', contextWindow: K256, maxOutput: 32_000, reasoning: true, fixedSampling: true, efforts: MARITACA_REASONING_EFFORTS, defaultEffort: 'high',
|
|
77
|
+
toolcall: true, vision: false, price: price(0.1, 0.6, 0.01), region: 'global',
|
|
78
|
+
// Open weights: its reasoning comes back as text (`reasoning_content`); the other S5 rows' is encrypted and never shown.
|
|
79
|
+
reasoningVisible: true,
|
|
80
|
+
description: 'Compact S5 with open weights: the same native reasoning (returned as text), 256K context, the cheapest of the family.',
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
id: 'sabia-4-thinking', label: 'Sabiá 4 Thinking', family: 'sabia-4', aliases: [],
|
|
84
|
+
tier: 'large', contextWindow: ONE_M, maxOutput: 32_000, reasoning: true, fixedSampling: false, efforts: [], defaultEffort: null,
|
|
85
|
+
toolcall: true, vision: false, price: price(5, 40, 1.25), region: 'global',
|
|
86
|
+
description: 'Reasoning model: explicit thinking before the answer, 1M context.',
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
id: 'sabia-4-thinking-br-sp', label: 'Sabiá 4 Thinking BR-SP', family: 'sabia-4', aliases: [],
|
|
90
|
+
tier: 'large', contextWindow: ONE_M, maxOutput: 32_000, reasoning: true, fixedSampling: false, efforts: [], defaultEffort: null,
|
|
91
|
+
toolcall: true, vision: false, price: price(6.5, 52, 1.63), region: 'br-sp',
|
|
92
|
+
description: 'Sabiá 4 Thinking with inference 100% in Brazil, 30% over the global model.',
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
id: 'sabia-4', label: 'Sabiá 4', family: 'sabia-4', aliases: ['sabia-4-2026-01-06'],
|
|
96
|
+
tier: 'medium', contextWindow: K128, maxOutput: 32_000, reasoning: false, efforts: [], defaultEffort: null,
|
|
97
|
+
toolcall: true, vision: false, price: price(5, 20, 1.25), region: 'global',
|
|
98
|
+
description: 'General model with agentic capability and Brazilian context.',
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: 'sabia-4-br-sp', label: 'Sabiá 4 BR-SP', family: 'sabia-4', aliases: [],
|
|
102
|
+
tier: 'medium', contextWindow: K128, maxOutput: 32_000, reasoning: false, efforts: [], defaultEffort: null,
|
|
103
|
+
toolcall: true, vision: false, price: price(6.5, 26, 1.63), region: 'br-sp',
|
|
104
|
+
description: 'Sabiá 4 with inference 100% in Brazil, 30% over the global model.',
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
id: 'sabiazinho-4', label: 'Sabiazinho 4', family: 'sabiazinho-4', aliases: ['sabiazinho-4-2026-01-06', 'sabia-4-small', 'sabiazim-4'],
|
|
108
|
+
tier: 'small', contextWindow: K128, maxOutput: 32_000, reasoning: false, efforts: [], defaultEffort: null,
|
|
109
|
+
toolcall: true, vision: false, price: price(1, 4, 0.25), region: 'global',
|
|
110
|
+
description: 'Fast and cheap, for large-scale applications and quick agentic flows.',
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
id: 'sabiazinho-4-br-sp', label: 'Sabiazinho 4 BR-SP', family: 'sabiazinho-4', aliases: [],
|
|
114
|
+
tier: 'small', contextWindow: K128, maxOutput: 32_000, reasoning: false, efforts: [], defaultEffort: null,
|
|
115
|
+
toolcall: true, vision: false, price: price(1.3, 5.2, 0.33), region: 'br-sp',
|
|
116
|
+
description: 'Sabiazinho 4 with inference 100% in Brazil, 30% over the global model.',
|
|
117
|
+
},
|
|
118
|
+
]);
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Models Maritaca retired (docs → Modelos descontinuados, 2026-11-06: sabia-3 and sabiazinho-3 are gone from the
|
|
122
|
+
* catalog). They are not in the table; a saved default or a stored conversation that still names one resolves to
|
|
123
|
+
* the nearest current model (sabia-3 → sabia-4, sabiazinho-3 → sabiazinho-4, Sabiá 2 → sabiazinho-4) and never fails.
|
|
124
|
+
*/
|
|
125
|
+
export const MARITACA_RETIRED = Object.freeze({
|
|
126
|
+
'sabia-2-medium': 'sabiazinho-4',
|
|
127
|
+
'sabia-2-small': 'sabiazinho-4',
|
|
128
|
+
'sabia-3': 'sabia-4',
|
|
129
|
+
'sabia-3-2024-07-15': 'sabia-4',
|
|
130
|
+
'sabia-3-2024-09-09': 'sabia-4',
|
|
131
|
+
'sabiazinho-3': 'sabiazinho-4',
|
|
132
|
+
'sabiazinho-3-2024-11-13': 'sabiazinho-4',
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
const byKey = new Map();
|
|
136
|
+
for (const model of MARITACA_MODELS) {
|
|
137
|
+
byKey.set(model.id.toLowerCase(), model);
|
|
138
|
+
for (const alias of model.aliases) byKey.set(alias.toLowerCase(), model);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The table row an id or alias names (case-insensitive), a retired id's replacement, else null. */
|
|
142
|
+
export function findMaritacaModel(id) {
|
|
143
|
+
const key = String(id || '').trim().toLowerCase();
|
|
144
|
+
if (!key) return null;
|
|
145
|
+
const direct = byKey.get(key);
|
|
146
|
+
if (direct) return direct;
|
|
147
|
+
const replacement = MARITACA_RETIRED[key];
|
|
148
|
+
return replacement ? byKey.get(replacement) || null : null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The canonical id of a model spelling (its table id), or the spelling itself trimmed when unknown. */
|
|
152
|
+
export function canonicalMaritacaModelId(id) {
|
|
153
|
+
const row = findMaritacaModel(id);
|
|
154
|
+
return row ? row.id : String(id || '').trim();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** BRL cost of a usage object ({ prompt_tokens, completion_tokens, prompt_tokens_details?.cached_tokens }) at list price; null without a price. */
|
|
158
|
+
export function maritacaUsageCostBrl(model, usage) {
|
|
159
|
+
const row = findMaritacaModel(model);
|
|
160
|
+
if (!row?.price || !usage || typeof usage !== 'object') return null;
|
|
161
|
+
const n = (v) => { const x = Number(v); return Number.isFinite(x) && x > 0 ? x : 0; };
|
|
162
|
+
const cached = n(usage.prompt_tokens_details?.cached_tokens ?? usage.cached_tokens);
|
|
163
|
+
const input = Math.max(0, n(usage.prompt_tokens) - cached);
|
|
164
|
+
const output = n(usage.completion_tokens);
|
|
165
|
+
const brl = (input * row.price.input + cached * (row.price.cacheRead ?? row.price.input) + output * row.price.output) / 1e6;
|
|
166
|
+
return Number(brl.toFixed(8));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The shape a picker or the catalog reads: a plain object per model (no frozen nested arrays leak). */
|
|
170
|
+
export function maritacaModelRows() {
|
|
171
|
+
return MARITACA_MODELS.map((m) => ({
|
|
172
|
+
id: m.id, label: m.label, family: m.family, aliases: [...m.aliases], tier: m.tier,
|
|
173
|
+
contextWindow: m.contextWindow, maxOutput: m.maxOutput, reasoning: m.reasoning, fixedSampling: m.fixedSampling === true,
|
|
174
|
+
efforts: [...m.efforts], defaultEffort: m.defaultEffort, toolcall: m.toolcall, vision: m.vision,
|
|
175
|
+
price: { ...m.price }, region: m.region, free: m.free === true, description: m.description,
|
|
176
|
+
// Whether the reasoning arrives as text: S5 Nano and Sabiá 4 Thinking yes; S5, S5 BR-SP and S5 Free keep it encrypted.
|
|
177
|
+
reasoningVisible: m.reasoningVisible === true || (m.reasoning === true && m.family !== 's5'),
|
|
178
|
+
batch: m.batch !== false, flex: m.flex !== false, rateLimit: m.rateLimit ? { ...m.rateLimit } : null,
|
|
179
|
+
isDefault: m.id === MARITACA_DEFAULT_MODEL, known: true, listed: true,
|
|
180
|
+
}));
|
|
181
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun — Maritaca AI: the panel's two modes (pure)
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// A Sabiá model is a chat API with no tools, so "plan mode" here is what it can be for a chat model: the turn is sent
|
|
6
|
+
// with an instruction (a system message after the user's own system prompt) that asks for a plan and not the work, and
|
|
7
|
+
// the reply is saved as a plan (`mode: 'plan'` on the user and the assistant message). The panel then offers the
|
|
8
|
+
// sibling panels' plan review: continue with the plan (the next turn goes in chat mode), suggest changes (another plan
|
|
9
|
+
// turn), copy it. Chat mode adds nothing. The server decides what a turn carries; the page only names the mode.
|
|
10
|
+
|
|
11
|
+
export const MARITACA_MODES = Object.freeze(['chat', 'plan']);
|
|
12
|
+
|
|
13
|
+
/** A mode as a page wrote it → 'plan' or 'chat' (anything else is chat). */
|
|
14
|
+
export function normalizeMaritacaMode(value) {
|
|
15
|
+
return value === 'plan' ? 'plan' : 'chat';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* What a plan turn asks of the model. English, like the rest of the request scaffolding; the model answers in the
|
|
20
|
+
* language the person writes in (the instruction says so), so a pt-BR conversation gets a pt-BR plan.
|
|
21
|
+
*/
|
|
22
|
+
export const MARITACA_PLAN_INSTRUCTION = [
|
|
23
|
+
'PLAN MODE is on for this reply.',
|
|
24
|
+
'Do not carry out the task yet: no finished code, no final text, no full deliverable.',
|
|
25
|
+
'Write a plan instead, in Markdown, with these parts:',
|
|
26
|
+
'1. Goal: the outcome in one or two sentences.',
|
|
27
|
+
'2. Assumptions and open questions: what you are taking as given, and what the user should confirm.',
|
|
28
|
+
'3. Steps: a numbered list; each step says what is done and what it produces.',
|
|
29
|
+
'4. Risks and checks: what could go wrong and how the result will be verified.',
|
|
30
|
+
'Keep it concise and concrete. End with one line asking whether to proceed or what to change.',
|
|
31
|
+
'Answer in the language the user writes in.',
|
|
32
|
+
].join('\n');
|
|
33
|
+
|
|
34
|
+
/** The system message a turn starts with: the user's own prompt, then the plan instruction when the mode asks for it. */
|
|
35
|
+
export function maritacaSystemPrompt({ systemPrompt = '', mode = 'chat' } = {}) {
|
|
36
|
+
const own = typeof systemPrompt === 'string' ? systemPrompt.trim() : '';
|
|
37
|
+
if (normalizeMaritacaMode(mode) !== 'plan') return own;
|
|
38
|
+
return own ? `${own}\n\n${MARITACA_PLAN_INSTRUCTION}` : MARITACA_PLAN_INSTRUCTION;
|
|
39
|
+
}
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun — Maritaca for OpenCode: the way OpenCode's requests reach Maritaca
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// POST /api/maritaca/opencode/v1/chat/completions
|
|
6
|
+
//
|
|
7
|
+
// The provider block SynaBun writes into opencode.json (lib/maritaca/opencode.js) points OpenCode's OpenAI-compatible
|
|
8
|
+
// package here instead of at https://chat.maritaca.ai/api: OpenCode 2 refuses Maritaca's stream on the first tool call
|
|
9
|
+
// ("OpenAI Chat received content after the finish reason", lib/maritaca/opencode-stream.js says why), and no option of
|
|
10
|
+
// OpenCode tolerates it. This route sends the request on to Maritaca and hands the answer back with the stream put in
|
|
11
|
+
// the order OpenCode reads (the finish reason last, each tool call whole), the reasoning OpenCode echoes on assistant
|
|
12
|
+
// messages left out of the request. Everything else goes through as it is: an error of Maritaca's with its status and
|
|
13
|
+
// body, an answer that is not a stream untouched.
|
|
14
|
+
//
|
|
15
|
+
// Who may call it: a request on the loopback interface (requireLocal), past the owner's route guard and SynaBun's
|
|
16
|
+
// gates, that presents the Maritaca key SynaBun has saved (`Authorization: Bearer <key>`, which OpenCode sends from
|
|
17
|
+
// the `{file:…}` / `{env:…}` reference the block holds). So the route gives nobody anything they did not have: a
|
|
18
|
+
// caller that can use it already holds the key. The key is compared by digest in constant time, sent to Maritaca in
|
|
19
|
+
// the header of the one request, never logged, never part of an answer. On macOS the peer gate knows OpenCode's serve
|
|
20
|
+
// as an agent's process tree, and this path is one of the few an agent's tree may call without a pin
|
|
21
|
+
// (lib/owner-authority.js AGENT_OPEN_PREFIXES); the automation browser and relays are still refused there.
|
|
22
|
+
//
|
|
23
|
+
// A request ends when OpenCode goes away (the request to Maritaca is aborted with it), or when Maritaca sends nothing
|
|
24
|
+
// for `idleMs` (a timeout per pause, not a deadline: a long answer that keeps streaming is never cut). A stream that
|
|
25
|
+
// breaks part-way ends with an `error` chunk, which OpenCode reports as the provider's error.
|
|
26
|
+
|
|
27
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
28
|
+
import { MARITACA_BASE_URL } from './client.js';
|
|
29
|
+
import { createChatStreamNormalizer, createSseLineReader, describeRepair, prepareUpstreamBody, readSseLine } from './opencode-stream.js';
|
|
30
|
+
|
|
31
|
+
export const MARITACA_OPENCODE_PROXY_PATH = '/api/maritaca/opencode/v1';
|
|
32
|
+
export const MARITACA_OPENCODE_PROXY_ROUTE = `${MARITACA_OPENCODE_PROXY_PATH}/chat/completions`;
|
|
33
|
+
/** A base URL that is SynaBun's own route (any loopback name, any port): the block points at a SynaBun server. */
|
|
34
|
+
export const MARITACA_OPENCODE_PROXY_URL_RE = /^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d{1,5}\/api\/maritaca\/opencode\/v1$/;
|
|
35
|
+
const IDLE_MS = 120_000;
|
|
36
|
+
const MAX_ERROR_BODY = 64 * 1024;
|
|
37
|
+
const MAX_LOGGED_SHAPES = 50;
|
|
38
|
+
|
|
39
|
+
/** The base URL OpenCode is given: this server, by its loopback address, on the port it listens on. */
|
|
40
|
+
export function maritacaOpencodeProxyBaseUrl(port) {
|
|
41
|
+
const n = Number(port);
|
|
42
|
+
if (!Number.isInteger(n) || n < 1 || n > 65535) throw new Error('maritacaOpencodeProxyBaseUrl needs the port SynaBun listens on');
|
|
43
|
+
return `http://127.0.0.1:${n}${MARITACA_OPENCODE_PROXY_PATH}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The key a request presents: `Authorization: Bearer <key>` (OpenCode) or `Key <key>` (Maritaca's own form). */
|
|
47
|
+
export function presentedKey(req) {
|
|
48
|
+
const header = req?.headers?.authorization;
|
|
49
|
+
if (typeof header !== 'string') return '';
|
|
50
|
+
const match = /^\s*(?:bearer|key)\s+(\S+)\s*$/i.exec(header);
|
|
51
|
+
return match ? match[1] : '';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Constant-time comparison of two keys (by their digests, so their lengths do not show either). */
|
|
55
|
+
export function sameKey(a, b) {
|
|
56
|
+
if (typeof a !== 'string' || typeof b !== 'string' || !a || !b) return false;
|
|
57
|
+
const digest = (s) => createHash('sha256').update(s, 'utf8').digest();
|
|
58
|
+
return timingSafeEqual(digest(a), digest(b));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** An error in the shape OpenCode reads from an OpenAI-compatible provider ({ error: { message, code } }). */
|
|
62
|
+
function sendError(res, status, code, message) {
|
|
63
|
+
if (res.headersSent) { try { res.end(); } catch { /* gone */ } return; }
|
|
64
|
+
res.status(status).json({ error: { message, type: 'synabun_maritaca_proxy', code } });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @param {object} o
|
|
71
|
+
* @param {{ readKey(): string|null }} o.keyStore lib/maritaca/key-store.js
|
|
72
|
+
* @param {string} [o.upstreamBaseUrl] Maritaca's API (the panel client's, so SYNABUN_MARITACA_BASE_URL applies to both)
|
|
73
|
+
* @param {typeof fetch} [o.fetchImpl]
|
|
74
|
+
* @param {number} [o.idleMs] how long Maritaca may stay silent (before its answer, and between chunks)
|
|
75
|
+
* @param {(line: string) => void} [o.log] one line per new kind of repair and per failure; never a key or a value
|
|
76
|
+
* @param {() => string} [o.newId] the id given to a tool call Maritaca sent without one (tests)
|
|
77
|
+
*/
|
|
78
|
+
export function createMaritacaOpencodeProxy({ keyStore, upstreamBaseUrl = MARITACA_BASE_URL, fetchImpl = globalThis.fetch, idleMs = IDLE_MS, log = () => {}, newId } = {}) {
|
|
79
|
+
if (!keyStore || typeof keyStore.readKey !== 'function') throw new Error('createMaritacaOpencodeProxy needs keyStore');
|
|
80
|
+
if (typeof fetchImpl !== 'function') throw new Error('createMaritacaOpencodeProxy needs fetch');
|
|
81
|
+
const base = String(upstreamBaseUrl || MARITACA_BASE_URL).replace(/\/+$/, '');
|
|
82
|
+
const stats = { requests: 0, streams: 0, repaired: 0, refused: 0, upstreamErrors: 0, active: 0, reasoningStripped: 0, lastRepair: null, lastError: null };
|
|
83
|
+
const loggedShapes = new Set();
|
|
84
|
+
|
|
85
|
+
function noteError(code, status = 0, model = '') {
|
|
86
|
+
stats.lastError = { at: new Date().toISOString(), code, ...(status ? { status } : {}), ...(model ? { model } : {}) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function noteRepair(report, model) {
|
|
90
|
+
if (!report.repaired) return;
|
|
91
|
+
stats.repaired += 1;
|
|
92
|
+
const line = describeRepair(report, { model });
|
|
93
|
+
stats.lastRepair = { at: new Date().toISOString(), model, finishReason: report.finishReason, afterFinish: { ...report.afterFinish }, shapes: [...report.shapes], line };
|
|
94
|
+
// One line per kind of repair, not one per turn: the shape without the model is the kind.
|
|
95
|
+
const kind = JSON.stringify([report.shapes, report.finishReasons, report.duplicateFragments > 0, report.snapshots > 0, report.conflicts > 0, report.idsAdded > 0, report.finishSynthesized]);
|
|
96
|
+
if (loggedShapes.has(kind) || loggedShapes.size >= MAX_LOGGED_SHAPES) return;
|
|
97
|
+
loggedShapes.add(kind);
|
|
98
|
+
log(line);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function handle(req, res) {
|
|
102
|
+
stats.requests += 1;
|
|
103
|
+
let key;
|
|
104
|
+
try { key = keyStore.readKey(); } catch (error) {
|
|
105
|
+
stats.refused += 1;
|
|
106
|
+
return sendError(res, 500, error?.code || 'KEY_UNREADABLE', 'SynaBun could not read its saved Maritaca key. Save it again in the Maritaca panel (the cog).');
|
|
107
|
+
}
|
|
108
|
+
if (!key) { stats.refused += 1; return sendError(res, 401, 'NO_KEY', 'No Maritaca API key is saved in SynaBun. Save one in the Maritaca panel (the cog).'); }
|
|
109
|
+
if (!sameKey(presentedKey(req), key)) {
|
|
110
|
+
stats.refused += 1;
|
|
111
|
+
return sendError(res, 401, 'KEY_MISMATCH', 'This address takes the Maritaca key SynaBun has saved. Re-sync Maritaca under Settings → OpenCode → Providers.');
|
|
112
|
+
}
|
|
113
|
+
const body = req.body;
|
|
114
|
+
if (!isObject(body) || typeof body.model !== 'string' || !body.model.trim() || !Array.isArray(body.messages)) {
|
|
115
|
+
return sendError(res, 400, 'BAD_REQUEST', 'A chat completion needs a model and messages.');
|
|
116
|
+
}
|
|
117
|
+
const model = body.model.trim().slice(0, 80);
|
|
118
|
+
const { body: upstreamBody, strippedReasoning } = prepareUpstreamBody(body);
|
|
119
|
+
stats.reasoningStripped += strippedReasoning;
|
|
120
|
+
|
|
121
|
+
const controller = new AbortController();
|
|
122
|
+
let clientGone = false;
|
|
123
|
+
let timedOut = false;
|
|
124
|
+
let timer = null;
|
|
125
|
+
const arm = () => { clearTimeout(timer); timer = setTimeout(() => { timedOut = true; controller.abort(new Error('idle')); }, idleMs); timer.unref?.(); };
|
|
126
|
+
const onClose = () => { if (!res.writableFinished) { clientGone = true; controller.abort(new Error('client gone')); } };
|
|
127
|
+
res.on('close', onClose);
|
|
128
|
+
stats.active += 1;
|
|
129
|
+
arm();
|
|
130
|
+
try {
|
|
131
|
+
let response;
|
|
132
|
+
try {
|
|
133
|
+
response = await fetchImpl(`${base}/chat/completions`, {
|
|
134
|
+
method: 'POST',
|
|
135
|
+
headers: { authorization: `Key ${key}`, 'content-type': 'application/json', accept: upstreamBody.stream === false ? 'application/json' : 'text/event-stream' },
|
|
136
|
+
body: JSON.stringify(upstreamBody),
|
|
137
|
+
signal: controller.signal,
|
|
138
|
+
redirect: 'error',
|
|
139
|
+
});
|
|
140
|
+
} catch {
|
|
141
|
+
if (clientGone) return;
|
|
142
|
+
stats.upstreamErrors += 1;
|
|
143
|
+
const code = timedOut ? 'TIMEOUT' : 'UNREACHABLE';
|
|
144
|
+
noteError(code, 0, model);
|
|
145
|
+
log(`[maritaca] OpenCode proxy: ${code === 'TIMEOUT' ? 'Maritaca did not answer in time' : 'could not reach Maritaca'} (${model})`);
|
|
146
|
+
return sendError(res, timedOut ? 504 : 502, code, timedOut ? 'Maritaca did not answer in time.' : 'Could not reach Maritaca.');
|
|
147
|
+
}
|
|
148
|
+
arm();
|
|
149
|
+
if (!response.ok) {
|
|
150
|
+
let text = '';
|
|
151
|
+
try { text = (await response.text()).slice(0, MAX_ERROR_BODY); } catch { text = ''; }
|
|
152
|
+
if (clientGone) return;
|
|
153
|
+
stats.upstreamErrors += 1;
|
|
154
|
+
noteError('UPSTREAM_STATUS', response.status, model);
|
|
155
|
+
log(`[maritaca] OpenCode proxy: Maritaca answered ${response.status} (${model})`);
|
|
156
|
+
res.status(response.status);
|
|
157
|
+
res.setHeader('content-type', response.headers.get('content-type') || 'application/json; charset=utf-8');
|
|
158
|
+
return res.send(text || JSON.stringify({ error: { message: `Maritaca answered ${response.status}.`, code: 'UPSTREAM_STATUS' } }));
|
|
159
|
+
}
|
|
160
|
+
const type = String(response.headers.get('content-type') || '');
|
|
161
|
+
if (!/event-stream/i.test(type)) {
|
|
162
|
+
// An answer that is not a stream (stream: false): one message, nothing out of order. Sent on as it is.
|
|
163
|
+
let text = '';
|
|
164
|
+
try { text = await response.text(); } catch {
|
|
165
|
+
if (clientGone) return;
|
|
166
|
+
noteError(timedOut ? 'TIMEOUT' : 'UPSTREAM_STREAM', 0, model);
|
|
167
|
+
return sendError(res, timedOut ? 504 : 502, timedOut ? 'TIMEOUT' : 'UPSTREAM_STREAM', 'The answer from Maritaca broke off.');
|
|
168
|
+
}
|
|
169
|
+
res.status(200).setHeader('content-type', type || 'application/json; charset=utf-8');
|
|
170
|
+
return res.send(text);
|
|
171
|
+
}
|
|
172
|
+
stats.streams += 1;
|
|
173
|
+
await relayStream(response, res, { model, arm, isGone: () => clientGone, timedOut: () => timedOut });
|
|
174
|
+
} finally {
|
|
175
|
+
clearTimeout(timer);
|
|
176
|
+
stats.active -= 1;
|
|
177
|
+
res.off?.('close', onClose);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function relayStream(response, res, { model, arm, isGone, timedOut }) {
|
|
182
|
+
res.status(200);
|
|
183
|
+
res.setHeader('content-type', 'text/event-stream; charset=utf-8');
|
|
184
|
+
res.setHeader('cache-control', 'no-cache, no-store, no-transform');
|
|
185
|
+
res.setHeader('x-accel-buffering', 'no');
|
|
186
|
+
res.flushHeaders?.();
|
|
187
|
+
const normalizer = createChatStreamNormalizer(newId ? { newId } : {});
|
|
188
|
+
const reader = createSseLineReader();
|
|
189
|
+
let done = false;
|
|
190
|
+
const send = async (text) => {
|
|
191
|
+
if (isGone() || res.writableEnded) return;
|
|
192
|
+
if (!res.write(text)) await new Promise((resolve) => { const go = () => { res.off('drain', go); res.off('close', go); resolve(); }; res.on('drain', go); res.on('close', go); });
|
|
193
|
+
};
|
|
194
|
+
const emit = async (payloads) => { for (const payload of payloads) await send(`data: ${JSON.stringify(payload)}\n\n`); };
|
|
195
|
+
const take = async (line) => {
|
|
196
|
+
const item = readSseLine(line);
|
|
197
|
+
if (!item) return;
|
|
198
|
+
if (item.kind === 'comment') return send(`${item.line}\n\n`); // a keep-alive, kept alive
|
|
199
|
+
if (item.kind === 'done') { done = true; return; }
|
|
200
|
+
if (item.kind === 'raw') return send(`data: ${item.data}\n\n`); // not JSON: OpenCode judges it, as it would have
|
|
201
|
+
return emit(normalizer.push(item.payload));
|
|
202
|
+
};
|
|
203
|
+
try {
|
|
204
|
+
for await (const chunk of response.body) {
|
|
205
|
+
arm();
|
|
206
|
+
for (const line of reader.push(chunk)) { await take(line); if (done) break; }
|
|
207
|
+
if (done) break;
|
|
208
|
+
}
|
|
209
|
+
if (!done) for (const line of reader.end()) { await take(line); if (done) break; }
|
|
210
|
+
} catch {
|
|
211
|
+
if (isGone()) return;
|
|
212
|
+
// The stream broke part-way (or went silent): say so as the provider's error, never as a finished answer.
|
|
213
|
+
stats.upstreamErrors += 1;
|
|
214
|
+
const code = timedOut() ? 'TIMEOUT' : 'UPSTREAM_STREAM';
|
|
215
|
+
noteError(code, 0, model);
|
|
216
|
+
log(`[maritaca] OpenCode proxy: the stream from Maritaca ${code === 'TIMEOUT' ? 'went silent' : 'broke off'} (${model})`);
|
|
217
|
+
await send(`data: ${JSON.stringify({ error: { message: code === 'TIMEOUT' ? 'Maritaca stopped sending before the answer ended.' : 'The connection to Maritaca broke before the answer ended.', type: 'synabun_maritaca_proxy', code } })}\n\n`);
|
|
218
|
+
res.end();
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (isGone()) return;
|
|
222
|
+
await emit(normalizer.end({ done }));
|
|
223
|
+
// [DONE] once the answer has its finish (said by Maritaca, or after its own [DONE]); a stream cut short without
|
|
224
|
+
// either ends without it, so OpenCode reports the stream as incomplete instead of taking it as an answer.
|
|
225
|
+
if (done || normalizer.finished) await send('data: [DONE]\n\n');
|
|
226
|
+
res.end();
|
|
227
|
+
noteRepair(normalizer.report(), model);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** What the Settings card and a diagnosis may read: counts and the last repair's shape, never a key or a value. */
|
|
231
|
+
function status() {
|
|
232
|
+
return { ...stats, lastRepair: stats.lastRepair ? { ...stats.lastRepair } : null, lastError: stats.lastError ? { ...stats.lastError } : null };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return { handle, status, route: MARITACA_OPENCODE_PROXY_ROUTE };
|
|
236
|
+
}
|