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
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync } from 'node:fs';
|
|
12
12
|
import { appendFile } from 'node:fs/promises';
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
13
14
|
import { resolve, join } from 'node:path';
|
|
14
15
|
import { getDataHome } from '../../lib/paths.js';
|
|
15
16
|
import { redactTerminalSecrets, scrubTokenText } from './terminal-token-redaction.js';
|
|
@@ -54,9 +55,28 @@ function rotateOnce() {
|
|
|
54
55
|
}
|
|
55
56
|
}
|
|
56
57
|
|
|
57
|
-
|
|
58
|
+
/** The shape of an id the MCP transport mints for a session (a random UUID): a bearer for that MCP session. */
|
|
59
|
+
const MCP_SESSION_ID_SHAPE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The part of the log file's name that stands for `id` (finding 5 of the re-review of 2026-11-11). A run's id names
|
|
63
|
+
* its file as it is (it is nothing without its token, and the log is searched by it). An MCP session's id
|
|
64
|
+
* (`mcpSession`, or an id of its shape) is a bearer, so its file is `mcp-<first 8 characters>-<24 hex of a SHA-256 of
|
|
65
|
+
* the whole id>`: the 8 characters are what the log lines show (sessionLogId / logOwnerId), the digest keeps two
|
|
66
|
+
* sessions whose ids share those 8 characters in two files with two append queues, and cannot be turned back into
|
|
67
|
+
* the id. Before, the file was `loop-mcp-<8 characters>.log`, so two such sessions wrote one file.
|
|
68
|
+
*/
|
|
69
|
+
export function loopLogFileKey(id, { mcpSession = false } = {}) {
|
|
70
|
+
const text = String(id ?? '');
|
|
71
|
+
if (!text) return '';
|
|
72
|
+
if (!(mcpSession === true || MCP_SESSION_ID_SHAPE_RE.test(text))) return text;
|
|
73
|
+
const digest = createHash('sha256').update(`synabun-loop-log\0${text}`).digest('hex').slice(0, 24);
|
|
74
|
+
return `mcp-${text.slice(0, 8)}-${digest}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function loopLogPath(terminalSessionId, options = {}) {
|
|
58
78
|
if (!terminalSessionId) return null;
|
|
59
|
-
return resolve(LOG_DIR, `loop-${terminalSessionId}.log`);
|
|
79
|
+
return resolve(LOG_DIR, `loop-${loopLogFileKey(terminalSessionId, options)}.log`);
|
|
60
80
|
}
|
|
61
81
|
|
|
62
82
|
/**
|
|
@@ -85,7 +105,7 @@ function _appendOrdered(path, line, terminalSessionId) {
|
|
|
85
105
|
});
|
|
86
106
|
}
|
|
87
107
|
|
|
88
|
-
export function loopLog(terminalSessionId, tag, msg, meta = undefined) {
|
|
108
|
+
export function loopLog(terminalSessionId, tag, msg, meta = undefined, { mcpSession = false } = {}) {
|
|
89
109
|
const ts = new Date().toISOString();
|
|
90
110
|
// A run's secrets never reach a log line, the file under data/logs or the console (lib/terminal-token-redaction.js):
|
|
91
111
|
// a message or its data may quote what an agent printed or a provider threw, a token included (review 972afb74,
|
|
@@ -101,7 +121,8 @@ export function loopLog(terminalSessionId, tag, msg, meta = undefined) {
|
|
|
101
121
|
|
|
102
122
|
ensureDir();
|
|
103
123
|
rotateOnce();
|
|
104
|
-
|
|
124
|
+
const fileKey = loopLogFileKey(terminalSessionId, { mcpSession });
|
|
125
|
+
_appendOrdered(loopLogPath(fileKey), line, fileKey);
|
|
105
126
|
}
|
|
106
127
|
|
|
107
128
|
/**
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun — Maritaca AI: the REST routes (/api/maritaca)
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// GET /api/maritaca/panel what the side panel's socket offers on this server ({ socket, capabilities, live })
|
|
6
|
+
// GET /api/maritaca/models the Sabiá models: the API's list merged over the table, else the table ({ models, source })
|
|
7
|
+
// GET /api/maritaca/settings { configured, source: 'file' | 'env' | null, masked, settings } — never the key
|
|
8
|
+
// PUT /api/maritaca/settings { key?, model?, reasoningEffort?, systemPrompt?, temperature? }; `key` is saved to the key file
|
|
9
|
+
// DELETE /api/maritaca/settings/key forgets the saved key (an environment key stays in force)
|
|
10
|
+
// POST /api/maritaca/test asks Maritaca whether the key is accepted ({ key? } tests a key before saving it)
|
|
11
|
+
// GET /api/maritaca/sessions the conversations ({ sessions }), `?project=` narrows
|
|
12
|
+
// GET /api/maritaca/sessions/:id one conversation with its messages
|
|
13
|
+
// DELETE /api/maritaca/sessions/:id
|
|
14
|
+
// GET /api/maritaca/opencode/status Maritaca as an OpenCode provider (lib/maritaca/opencode.js): registered, modelCount, inSync, key source; never the key
|
|
15
|
+
// POST /api/maritaca/opencode/configure writes the provider block into the global opencode.json (412 NO_KEY, 409 OPENCODE1_PROVIDERS)
|
|
16
|
+
// DELETE /api/maritaca/opencode/configure takes it out
|
|
17
|
+
// (the three answer 503 OPENCODE_SYNC_UNAVAILABLE on a server built without the sync; status also carries `proxy`,
|
|
18
|
+
// the counts of the route below and the shape of its last repair, never a key or a value)
|
|
19
|
+
// POST /api/maritaca/opencode/v1/chat/completions OpenCode's requests for a Sabiá model, sent on to Maritaca with the
|
|
20
|
+
// stream put in the order OpenCode reads (lib/maritaca/opencode-proxy.js): loopback only, and only for a caller
|
|
21
|
+
// that presents the saved key; errors in OpenAI's shape; 503 OPENCODE_PROXY_UNAVAILABLE on a server without it
|
|
22
|
+
//
|
|
23
|
+
// Registered on the app one by one (`registerMaritacaRoutes(app, deps)`, the form tests/request-gate.test.mjs asks
|
|
24
|
+
// every helper for), each behind `guard` (server.js's ownerRouteGuard: this server's Hosts, own Origin on a write, no
|
|
25
|
+
// guests); the prefix is admin-only in lib/request-gate.js too. A request body never outlives its handler
|
|
26
|
+
// with a key in it, an error from Maritaca is answered by its code, never its text verbatim when it could echo
|
|
27
|
+
// input, and nothing here logs a key.
|
|
28
|
+
|
|
29
|
+
import express from 'express';
|
|
30
|
+
import { MARITACA_PANEL_CAPABILITIES, MARITACA_WS_PATH } from './panel-bridge.js';
|
|
31
|
+
import { isSessionId } from './sessions.js';
|
|
32
|
+
import { requireLocal } from '../http-guards.js';
|
|
33
|
+
|
|
34
|
+
const STATUS_FOR = { KEY_REJECTED: 401, RATE_LIMITED: 429, MODEL_UNKNOWN: 404, BAD_REQUEST: 400, UPSTREAM: 502, UNREACHABLE: 503, TIMEOUT: 504, NO_KEY: 412, INVALID_KEY: 400, ABORTED: 499 };
|
|
35
|
+
|
|
36
|
+
export function registerMaritacaRoutes(app, { client, keyStore, sessions, bridge = null, opencode = null, proxy = null, guard = (req, res, next) => next(), localOnly = requireLocal, log = () => {} } = {}) {
|
|
37
|
+
if (!client || !keyStore || !sessions) throw new Error('registerMaritacaRoutes needs client, keyStore and sessions');
|
|
38
|
+
const noStore = (req, res, next) => { res.setHeader('Cache-Control', 'no-store'); next(); };
|
|
39
|
+
const body = express.json({ limit: '256kb' });
|
|
40
|
+
// Every route: the guard, then no-store. `router` below is a tiny shim so each handler reads as a route line.
|
|
41
|
+
const router = {
|
|
42
|
+
get: (path, ...rest) => app.get(`/api/maritaca${path}`, guard, noStore, ...rest),
|
|
43
|
+
put: (path, ...rest) => app.put(`/api/maritaca${path}`, guard, noStore, ...rest),
|
|
44
|
+
post: (path, ...rest) => app.post(`/api/maritaca${path}`, guard, noStore, ...rest),
|
|
45
|
+
delete: (path, ...rest) => app.delete(`/api/maritaca${path}`, guard, noStore, ...rest),
|
|
46
|
+
};
|
|
47
|
+
const fail = (res, error) => {
|
|
48
|
+
const code = error?.code || 'ERROR';
|
|
49
|
+
const status = Number(error?.status) >= 400 && Number(error?.status) < 600 ? Number(error.status) : STATUS_FOR[code] || 500;
|
|
50
|
+
res.status(status).json({ ok: false, code, error: error?.message || 'Something went wrong.' });
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
router.get('/panel', (req, res) => {
|
|
54
|
+
res.json({ ok: true, socket: MARITACA_WS_PATH, capabilities: [...MARITACA_PANEL_CAPABILITIES], live: bridge?.liveCount?.() || 0, turns: bridge?.turnsRunning?.() || 0 });
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
router.get('/models', async (req, res) => {
|
|
58
|
+
try {
|
|
59
|
+
const listed = await client.listModels({ key: keyStore.readKey() });
|
|
60
|
+
res.json({ ok: true, models: listed.models, source: listed.source, configured: !!keyStore.readKey(), ...(listed.error ? { error: listed.error } : {}) });
|
|
61
|
+
} catch (error) { fail(res, error); }
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
router.get('/settings', (req, res) => {
|
|
65
|
+
try { res.json({ ok: true, ...keyStore.status() }); } catch (error) { fail(res, error); }
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
router.put('/settings', body, async (req, res) => {
|
|
69
|
+
let key = req.body?.key;
|
|
70
|
+
if (req.body) delete req.body.key;
|
|
71
|
+
try {
|
|
72
|
+
let keySaved = false;
|
|
73
|
+
if (typeof key === 'string' && key.trim()) { keyStore.saveKey(key); keySaved = true; }
|
|
74
|
+
const { model, reasoningEffort, systemPrompt, temperature } = req.body || {};
|
|
75
|
+
const patch = {};
|
|
76
|
+
if (model !== undefined) patch.model = model;
|
|
77
|
+
if (reasoningEffort !== undefined) patch.reasoningEffort = reasoningEffort;
|
|
78
|
+
if (systemPrompt !== undefined) patch.systemPrompt = systemPrompt;
|
|
79
|
+
if (temperature !== undefined) patch.temperature = temperature;
|
|
80
|
+
if (Object.keys(patch).length) keyStore.saveSettings(patch);
|
|
81
|
+
const status = keyStore.status();
|
|
82
|
+
try { bridge?.notifySettingsChanged?.(); } catch { /* no panel open */ }
|
|
83
|
+
// A registered OpenCode provider block follows the key (never throws).
|
|
84
|
+
const opencodeSync = keySaved && opencode ? await opencode.onKeyChanged() : null;
|
|
85
|
+
res.json({ ok: true, ...status, ...(opencodeSync ? { opencode: opencodeSync } : {}) });
|
|
86
|
+
} catch (error) { fail(res, error); }
|
|
87
|
+
finally { key = null; }
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
router.delete('/settings/key', async (req, res) => {
|
|
91
|
+
try {
|
|
92
|
+
keyStore.clearKey();
|
|
93
|
+
try { bridge?.notifySettingsChanged?.(); } catch { /* no panel open */ }
|
|
94
|
+
const opencodeSync = opencode ? await opencode.onKeyChanged() : null;
|
|
95
|
+
res.json({ ok: true, ...keyStore.status(), ...(opencodeSync ? { opencode: opencodeSync } : {}) });
|
|
96
|
+
} catch (error) { fail(res, error); }
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
router.post('/test', body, async (req, res) => {
|
|
100
|
+
let key = req.body?.key;
|
|
101
|
+
if (req.body) delete req.body.key;
|
|
102
|
+
try {
|
|
103
|
+
const candidate = typeof key === 'string' && key.trim() ? key.trim() : keyStore.readKey();
|
|
104
|
+
if (!candidate) return fail(res, Object.assign(new Error('Save a Maritaca API key first.'), { code: 'NO_KEY', status: 412 }));
|
|
105
|
+
const verdict = await client.verifyKey({ key: candidate });
|
|
106
|
+
res.json({ ok: true, via: verdict.via });
|
|
107
|
+
} catch (error) {
|
|
108
|
+
log(`[maritaca] key test: ${error?.code || 'ERROR'}`);
|
|
109
|
+
fail(res, error);
|
|
110
|
+
} finally { key = null; }
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
// ── Maritaca as an OpenCode provider ──
|
|
114
|
+
const noSync = (res) => res.status(503).json({ ok: false, code: 'OPENCODE_SYNC_UNAVAILABLE', error: 'This server cannot register Maritaca in OpenCode yet. Restart SynaBun.' });
|
|
115
|
+
|
|
116
|
+
router.get('/opencode/status', (req, res) => {
|
|
117
|
+
if (!opencode) return noSync(res);
|
|
118
|
+
try { res.json({ ok: true, ...opencode.status(), ...(proxy ? { proxy: proxy.status() } : {}) }); } catch (error) { fail(res, error); }
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
router.post('/opencode/configure', async (req, res) => {
|
|
122
|
+
if (!opencode) return noSync(res);
|
|
123
|
+
try {
|
|
124
|
+
const result = await opencode.configure();
|
|
125
|
+
res.json({ ok: true, ...result, ...opencode.status() });
|
|
126
|
+
} catch (error) {
|
|
127
|
+
log(`[maritaca] OpenCode provider configure: ${error?.code || 'ERROR'}`);
|
|
128
|
+
fail(res, error);
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
router.delete('/opencode/configure', async (req, res) => {
|
|
133
|
+
if (!opencode) return noSync(res);
|
|
134
|
+
try {
|
|
135
|
+
const result = await opencode.remove();
|
|
136
|
+
res.json({ ok: true, ...result, ...opencode.status() });
|
|
137
|
+
} catch (error) { fail(res, error); }
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// OpenCode's requests for a Sabiá model (the provider block's baseURL). Its answers are in OpenAI's error shape, which
|
|
141
|
+
// is what OpenCode shows, never this module's { ok, code, error }.
|
|
142
|
+
router.post('/opencode/v1/chat/completions', localOnly, (req, res) => {
|
|
143
|
+
if (!proxy) return res.status(503).json({ error: { message: 'This SynaBun server cannot carry OpenCode\'s Maritaca requests yet. Restart SynaBun.', type: 'synabun_maritaca_proxy', code: 'OPENCODE_PROXY_UNAVAILABLE' } });
|
|
144
|
+
Promise.resolve().then(() => proxy.handle(req, res)).catch((error) => {
|
|
145
|
+
log(`[maritaca] OpenCode proxy: ${error?.code || 'ERROR'}`);
|
|
146
|
+
if (!res.headersSent) res.status(500).json({ error: { message: 'SynaBun could not send this request on to Maritaca.', type: 'synabun_maritaca_proxy', code: 'PROXY_ERROR' } });
|
|
147
|
+
else { try { res.end(); } catch { /* gone */ } }
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
router.get('/sessions', (req, res) => {
|
|
152
|
+
try { res.json({ ok: true, sessions: sessions.list({ project: typeof req.query.project === 'string' ? req.query.project : null, limit: req.query.limit }) }); }
|
|
153
|
+
catch (error) { fail(res, error); }
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
router.get('/sessions/:id', (req, res) => {
|
|
157
|
+
if (!isSessionId(req.params.id)) return res.status(400).json({ ok: false, code: 'SESSION_INVALID', error: 'Unknown conversation.' });
|
|
158
|
+
const session = sessions.get(req.params.id);
|
|
159
|
+
if (!session) return res.status(404).json({ ok: false, code: 'SESSION_UNKNOWN', error: 'That conversation no longer exists.' });
|
|
160
|
+
res.json({ ok: true, session });
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
router.delete('/sessions/:id', (req, res) => {
|
|
164
|
+
if (!isSessionId(req.params.id)) return res.status(400).json({ ok: false, code: 'SESSION_INVALID', error: 'Unknown conversation.' });
|
|
165
|
+
res.json({ ok: true, ...(bridge?.removeSession ? bridge.removeSession(req.params.id) : { deleted: sessions.remove(req.params.id) }) });
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
router.put('/sessions/:id', body, (req, res) => {
|
|
169
|
+
if (!isSessionId(req.params.id)) return res.status(400).json({ ok: false, code: 'SESSION_INVALID', error: 'Unknown conversation.' });
|
|
170
|
+
if (typeof req.body?.title !== 'string') return res.status(400).json({ ok: false, code: 'TITLE_INVALID', error: 'A title is required.' });
|
|
171
|
+
try {
|
|
172
|
+
const result = bridge?.renameSession ? bridge.renameSession(req.params.id, req.body.title) : { session: sessions.update(req.params.id, { title: req.body.title }) };
|
|
173
|
+
if (!result.session) return res.status(404).json({ ok: false, code: 'SESSION_UNKNOWN', error: 'That conversation no longer exists.' });
|
|
174
|
+
res.json({ ok: true, ...result });
|
|
175
|
+
} catch (error) { fail(res, error); }
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
return app;
|
|
179
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Small attachments use the same base64 prompt envelope as the Antigravity panel.
|
|
2
|
+
// Nothing is opened by path or executed. Validation happens before history is changed.
|
|
3
|
+
import { sanitizeAttachmentName, normalizeAttachmentMime } from '../assistant-attachments.js';
|
|
4
|
+
|
|
5
|
+
export const MARITACA_ATTACHMENT_LIMITS = Object.freeze({ maxAttachments: 5, maxBytes: 100_000, maxPromptChars: 200_000 });
|
|
6
|
+
const TEXT_EXT = /(?:^|\.)(?:txt|md|mdx|js|ts|jsx|tsx|mjs|cjs|mts|cts|json|jsonl|html|css|scss|less|xml|py|rb|go|rs|java|c|cpp|h|hpp|cs|php|sh|bash|zsh|yml|yaml|toml|ini|cfg|conf|env|gitignore|dockerignore|sql|graphql|proto|csv|tsv|log|diff|patch|vue|svelte|astro|rst|tex|lua|r|swift|kt|dockerfile|makefile|cmake|gradle|bat|ps1|fish)$/i;
|
|
7
|
+
const IMAGE_EXT = /\.(?:png|jpe?g|gif|webp|svg|avif|heic|bmp|ico|tiff?)$/i;
|
|
8
|
+
const fail = (code, message) => { throw Object.assign(new Error(message), { code, status: 400 }); };
|
|
9
|
+
|
|
10
|
+
export function inlineMaritacaAttachments(text, files = [], { vision = false, limits = MARITACA_ATTACHMENT_LIMITS } = {}) {
|
|
11
|
+
if (!Array.isArray(files)) fail('ATTACHMENT_DATA', 'Attachments must be a list.');
|
|
12
|
+
if (files.length > limits.maxAttachments) fail('ATTACHMENT_COUNT', `At most ${limits.maxAttachments} attachments per message.`);
|
|
13
|
+
const blocks = [], attachments = [], images = [];
|
|
14
|
+
for (const file of files) {
|
|
15
|
+
const name = sanitizeAttachmentName(file?.name);
|
|
16
|
+
const mimeType = normalizeAttachmentMime(file?.mimeType);
|
|
17
|
+
const image = mimeType.startsWith('image/') || IMAGE_EXT.test(name);
|
|
18
|
+
if (image && !vision) fail('IMAGE_UNSUPPORTED', 'This model does not read images. Attach a text or code file instead.');
|
|
19
|
+
const data = file?.data;
|
|
20
|
+
if (typeof data !== 'string' || data.length > Math.ceil(limits.maxBytes / 3) * 4) fail('ATTACHMENT_SIZE', `Each file must be at most ${limits.maxBytes} bytes.`);
|
|
21
|
+
if (data && (data.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data))) fail('ATTACHMENT_DATA', 'An attachment arrived damaged.');
|
|
22
|
+
const bytes = Buffer.from(data, 'base64');
|
|
23
|
+
if (bytes.length > limits.maxBytes) fail('ATTACHMENT_SIZE', `Each file must be at most ${limits.maxBytes} bytes.`);
|
|
24
|
+
if (bytes.toString('base64') !== data) fail('ATTACHMENT_DATA', 'An attachment arrived damaged.');
|
|
25
|
+
if (image) {
|
|
26
|
+
if (!/^image\/(png|jpeg|gif|webp)$/.test(mimeType)) fail('ATTACHMENT_TYPE', 'This image type is not supported.');
|
|
27
|
+
images.push({ type: 'image_url', image_url: { url: `data:${mimeType};base64,${data}` } });
|
|
28
|
+
} else {
|
|
29
|
+
if (!(TEXT_EXT.test(name) || !name.includes('.') || mimeType.startsWith('text/') || /application\/(json|xml|javascript|x-yaml)/.test(mimeType))) fail('ATTACHMENT_TYPE', 'Attach a text or code file.');
|
|
30
|
+
let content;
|
|
31
|
+
try { content = new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { fail('ATTACHMENT_BINARY', 'Attachments must contain UTF-8 text.'); }
|
|
32
|
+
if (/[\u0000-\u0008\u000e-\u001f]/.test(content)) fail('ATTACHMENT_BINARY', 'Binary files cannot be included as text.');
|
|
33
|
+
// A fence longer than any run in the file keeps nested markdown/code literal.
|
|
34
|
+
const fence = '`'.repeat([...content.matchAll(/`+/g)].reduce((max, m) => Math.max(max, m[0].length + 1), 3));
|
|
35
|
+
blocks.push(`File: ${name}\n${fence}\n${content}\n${fence}`);
|
|
36
|
+
}
|
|
37
|
+
attachments.push({ name, mimeType, size: bytes.length });
|
|
38
|
+
}
|
|
39
|
+
const attachmentText = blocks.join('\n\n');
|
|
40
|
+
const content = [text, attachmentText].filter(Boolean).join('\n\n');
|
|
41
|
+
if (!content.trim() && !images.length) fail('PROMPT_EMPTY', 'Type something or attach a file first.');
|
|
42
|
+
if (content.length > limits.maxPromptChars) fail('PROMPT_TOO_LONG', `The message including files is longer than ${limits.maxPromptChars} characters.`);
|
|
43
|
+
return { content, displayText: text, attachmentText, attachments, images };
|
|
44
|
+
}
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun — Maritaca AI: the HTTP client (no dependency)
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// Maritaca exposes an OpenAI-compatible API at https://chat.maritaca.ai/api (docs.maritaca.ai →
|
|
6
|
+
// API reference → Chat): POST /chat/completions with `messages`, `stream`, `stream_options`,
|
|
7
|
+
// `tools`, `tool_choice`, `max_tokens`, `temperature`, `reasoning_effort` (S5), and the key in the
|
|
8
|
+
// Authorization header. There is no official Node SDK (the `maritalk` package is Python), so this is
|
|
9
|
+
// a thin `fetch` client: no new dependency, every request bounded by a timeout and an AbortSignal,
|
|
10
|
+
// the key held only for the call, never logged, never part of an error.
|
|
11
|
+
//
|
|
12
|
+
// `chatStream` reads the server-sent events of a streaming completion and calls `onEvent` with:
|
|
13
|
+
// { type: 'delta', text } answer text
|
|
14
|
+
// { type: 'reasoning', text } reasoning text (S5, Sabiá 4 Thinking), when the API streams it
|
|
15
|
+
// { type: 'tool_call', index, id, name, arguments } a tool call, assembled when its deltas end
|
|
16
|
+
// { type: 'usage', usage } the final usage chunk (stream_options.include_usage)
|
|
17
|
+
// { type: 'done', finishReason } the stream ended
|
|
18
|
+
// and resolves with { text, reasoning, toolCalls, usage, finishReason }. An HTTP error rejects with
|
|
19
|
+
// an Error carrying `status` and `code` ('KEY_REJECTED' 401/403, 'RATE_LIMITED' 429, 'MODEL_UNKNOWN'
|
|
20
|
+
// 404, 'BAD_REQUEST' 400, 'UPSTREAM' 5xx, 'UNREACHABLE' a network failure, 'ABORTED'); the body of a
|
|
21
|
+
// failure is read for its `error.message` only, bounded, and the key is never in it.
|
|
22
|
+
|
|
23
|
+
import { MARITACA_MODELS, findMaritacaModel, maritacaModelRows, normalizeMaritacaEffort } from './models.js';
|
|
24
|
+
|
|
25
|
+
export const MARITACA_BASE_URL = 'https://chat.maritaca.ai/api';
|
|
26
|
+
export const MARITACA_DOCS_URL = 'https://docs.maritaca.ai';
|
|
27
|
+
export const MARITACA_KEYS_URL = 'https://plataforma.maritaca.ai/chaves-de-api';
|
|
28
|
+
const MAX_ERROR_BODY = 2000;
|
|
29
|
+
const DEFAULT_TIMEOUT_MS = 20_000;
|
|
30
|
+
const STREAM_IDLE_MS = 120_000; // a stream ends when no bytes arrive for this long (reset by every chunk), not a total
|
|
31
|
+
|
|
32
|
+
export function maritacaError(code, message, status = 0) {
|
|
33
|
+
return Object.assign(new Error(message), { code, status });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The error code an HTTP status means. */
|
|
37
|
+
export function codeForStatus(status) {
|
|
38
|
+
if (status === 401 || status === 403) return 'KEY_REJECTED';
|
|
39
|
+
if (status === 429) return 'RATE_LIMITED';
|
|
40
|
+
if (status === 404) return 'MODEL_UNKNOWN';
|
|
41
|
+
if (status === 400 || status === 422) return 'BAD_REQUEST';
|
|
42
|
+
if (status >= 500) return 'UPSTREAM';
|
|
43
|
+
return 'HTTP_ERROR';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The message of a failed answer, from its JSON `error.message` / `detail` / `message`, else the status line. Never the key. */
|
|
47
|
+
export async function readErrorMessage(response) {
|
|
48
|
+
let text = '';
|
|
49
|
+
try { text = (await response.text()).slice(0, MAX_ERROR_BODY); } catch { text = ''; }
|
|
50
|
+
try {
|
|
51
|
+
const body = JSON.parse(text);
|
|
52
|
+
const msg = body?.error?.message || body?.detail || body?.message || body?.error;
|
|
53
|
+
if (typeof msg === 'string' && msg.trim()) return msg.trim().slice(0, 400);
|
|
54
|
+
} catch { /* not JSON */ }
|
|
55
|
+
return `Maritaca answered ${response.status}${response.statusText ? ` ${response.statusText}` : ''}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The request key is kept only in the header of the one call. */
|
|
59
|
+
function headers(key, extra = {}) {
|
|
60
|
+
// The documentation's direct HTTP example sends `Authorization: Key <key>`; the OpenAI SDK sends `Bearer`.
|
|
61
|
+
// Both are accepted; the documented one is used.
|
|
62
|
+
return { authorization: `Key ${key}`, 'content-type': 'application/json', accept: 'application/json', ...extra };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function abortIn(ms, outer) {
|
|
66
|
+
const controller = new AbortController();
|
|
67
|
+
let timer = null;
|
|
68
|
+
const arm = () => { clearTimeout(timer); timer = setTimeout(() => controller.abort(new Error('timeout')), ms); timer.unref?.(); };
|
|
69
|
+
arm();
|
|
70
|
+
const onOuter = () => controller.abort(outer?.reason || new Error('aborted'));
|
|
71
|
+
if (outer) {
|
|
72
|
+
if (outer.aborted) onOuter();
|
|
73
|
+
else outer.addEventListener('abort', onOuter, { once: true });
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
signal: controller.signal,
|
|
77
|
+
/** Something arrived: the clock starts over (an idle timeout, not a deadline). */
|
|
78
|
+
touch: () => { if (!controller.signal.aborted) arm(); },
|
|
79
|
+
done: () => { clearTimeout(timer); outer?.removeEventListener?.('abort', onOuter); },
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The body's chunks, each one resetting the idle clock. */
|
|
84
|
+
async function* touching(iterable, touch) {
|
|
85
|
+
for await (const chunk of iterable) { touch(); yield chunk; }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function networkError(error, outer) {
|
|
89
|
+
if (outer?.aborted) return maritacaError('ABORTED', 'The request was stopped.');
|
|
90
|
+
if (error?.name === 'AbortError' || /timeout/i.test(String(error?.message))) return maritacaError('TIMEOUT', 'Maritaca did not answer in time.');
|
|
91
|
+
return maritacaError('UNREACHABLE', 'Could not reach Maritaca.');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Parses one server-sent-events stream (OpenAI chat completion chunks). Pure over an async
|
|
96
|
+
* iterable of Uint8Array / string chunks; yields the parsed JSON of every `data:` line, and
|
|
97
|
+
* `{ done: true }` once for `[DONE]`.
|
|
98
|
+
*/
|
|
99
|
+
export async function* parseSseChunks(iterable) {
|
|
100
|
+
const decoder = new TextDecoder();
|
|
101
|
+
let buffer = '';
|
|
102
|
+
for await (const chunk of iterable) {
|
|
103
|
+
buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
|
|
104
|
+
let at;
|
|
105
|
+
while ((at = buffer.indexOf('\n')) >= 0) {
|
|
106
|
+
const line = buffer.slice(0, at).replace(/\r$/, '');
|
|
107
|
+
buffer = buffer.slice(at + 1);
|
|
108
|
+
if (!line.startsWith('data:')) continue;
|
|
109
|
+
const data = line.slice(5).trim();
|
|
110
|
+
if (!data) continue;
|
|
111
|
+
if (data === '[DONE]') { yield { done: true }; return; }
|
|
112
|
+
try { yield JSON.parse(data); } catch { /* a partial or malformed line: skipped */ }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const rest = buffer.trim();
|
|
116
|
+
if (rest.startsWith('data:')) {
|
|
117
|
+
const data = rest.slice(5).trim();
|
|
118
|
+
if (data === '[DONE]') yield { done: true };
|
|
119
|
+
else { try { yield JSON.parse(data); } catch { /* ignore */ } }
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Folds the chunks of one streamed completion into text, reasoning, tool calls and usage, reporting each piece. */
|
|
124
|
+
export function createStreamFolder(onEvent = () => {}) {
|
|
125
|
+
const calls = new Map(); // index → { id, name, arguments }
|
|
126
|
+
const out = { text: '', reasoning: '', toolCalls: [], usage: null, finishReason: null };
|
|
127
|
+
const emit = (event) => { try { onEvent(event); } catch { /* the listener's own problem */ } };
|
|
128
|
+
function flushCalls() {
|
|
129
|
+
for (const [index, call] of [...calls].sort((a, b) => a[0] - b[0])) {
|
|
130
|
+
const done = { index, id: call.id || `call_${index}`, name: call.name || '', arguments: call.arguments || '' };
|
|
131
|
+
out.toolCalls.push(done);
|
|
132
|
+
emit({ type: 'tool_call', ...done });
|
|
133
|
+
}
|
|
134
|
+
calls.clear();
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
push(chunk) {
|
|
138
|
+
if (!chunk || typeof chunk !== 'object') return;
|
|
139
|
+
if (chunk.done) { flushCalls(); emit({ type: 'done', finishReason: out.finishReason }); return; }
|
|
140
|
+
if (chunk.usage && typeof chunk.usage === 'object') { out.usage = chunk.usage; emit({ type: 'usage', usage: chunk.usage }); }
|
|
141
|
+
const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : null;
|
|
142
|
+
if (!choice) return;
|
|
143
|
+
const delta = choice.delta || choice.message || {};
|
|
144
|
+
if (typeof delta.content === 'string' && delta.content) { out.text += delta.content; emit({ type: 'delta', text: delta.content }); }
|
|
145
|
+
const reasoning = typeof delta.reasoning_content === 'string' ? delta.reasoning_content : typeof delta.reasoning === 'string' ? delta.reasoning : '';
|
|
146
|
+
if (reasoning) { out.reasoning += reasoning; emit({ type: 'reasoning', text: reasoning }); }
|
|
147
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
148
|
+
for (const piece of delta.tool_calls) {
|
|
149
|
+
const index = Number.isInteger(piece?.index) ? piece.index : calls.size;
|
|
150
|
+
const call = calls.get(index) || { id: '', name: '', arguments: '' };
|
|
151
|
+
if (piece?.id) call.id = String(piece.id);
|
|
152
|
+
if (piece?.function?.name) call.name += String(piece.function.name);
|
|
153
|
+
if (typeof piece?.function?.arguments === 'string') call.arguments += piece.function.arguments;
|
|
154
|
+
calls.set(index, call);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (choice.finish_reason) out.finishReason = String(choice.finish_reason);
|
|
158
|
+
},
|
|
159
|
+
end() {
|
|
160
|
+
flushCalls();
|
|
161
|
+
return out;
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The message list the API takes: role/content pairs only, bounded, tool messages kept as they are. */
|
|
167
|
+
export function normalizeMessages(messages) {
|
|
168
|
+
const out = [];
|
|
169
|
+
for (const m of Array.isArray(messages) ? messages : []) {
|
|
170
|
+
if (!m || typeof m !== 'object') continue;
|
|
171
|
+
const role = ['system', 'user', 'assistant', 'tool'].includes(m.role) ? m.role : null;
|
|
172
|
+
if (!role) continue;
|
|
173
|
+
const content = role === 'user' && Array.isArray(m.content)
|
|
174
|
+
? m.content.filter((p) => (p?.type === 'text' && typeof p.text === 'string') || (p?.type === 'image_url' && /^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+=*$/.test(p.image_url?.url || '')))
|
|
175
|
+
.map((p) => p.type === 'text' ? { type: 'text', text: p.text } : { type: 'image_url', image_url: { url: p.image_url.url } })
|
|
176
|
+
: typeof m.content === 'string' ? m.content : m.content == null ? '' : String(m.content);
|
|
177
|
+
const entry = { role, content };
|
|
178
|
+
if (role === 'assistant' && Array.isArray(m.tool_calls) && m.tool_calls.length) entry.tool_calls = m.tool_calls;
|
|
179
|
+
if (role === 'tool' && m.tool_call_id) entry.tool_call_id = String(m.tool_call_id);
|
|
180
|
+
out.push(entry);
|
|
181
|
+
}
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Does the model take only its default sampling? A row's own `fixedSampling` wins (models.js: the S5 family, probed
|
|
187
|
+
* live; Sabiá 4 Thinking reasons yet samples freely); a row without the flag falls back to `reasoning`, the safe guess
|
|
188
|
+
* for a model the table does not know, since S5 answers "'temperature' does not support 0 … Only the default (1)".
|
|
189
|
+
*/
|
|
190
|
+
export function maritacaFixedSampling(row) {
|
|
191
|
+
if (!row) return false;
|
|
192
|
+
if (typeof row.fixedSampling === 'boolean') return row.fixedSampling;
|
|
193
|
+
return row.reasoning === true;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** A 400 whose message says a sampling field (temperature / top_p) is not supported by the model. */
|
|
197
|
+
export function isSamplingRefusal(error) {
|
|
198
|
+
if (!error || Number(error.status) !== 400) return false;
|
|
199
|
+
return /unsupported (value|parameter)/i.test(String(error.message || '')) && /\b(temperature|top_p)\b/i.test(String(error.message || ''));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The body of a chat completion request from what the panel asks. */
|
|
203
|
+
export function buildChatBody({ model, messages, stream = true, maxTokens = null, temperature = null, reasoningEffort = null, tools = null, toolChoice = null } = {}) {
|
|
204
|
+
const row = findMaritacaModel(model);
|
|
205
|
+
const body = { model: row ? row.id : String(model || '').trim(), messages: normalizeMessages(messages), stream: stream === true };
|
|
206
|
+
if (row && row.vision !== true && body.messages.some((m) => Array.isArray(m.content) && m.content.some((p) => p.type === 'image_url'))) throw maritacaError('IMAGE_UNSUPPORTED', 'This model does not read images.');
|
|
207
|
+
if (body.stream) body.stream_options = { include_usage: true };
|
|
208
|
+
if (Number.isFinite(Number(maxTokens)) && Number(maxTokens) > 0) body.max_tokens = Math.min(Math.floor(Number(maxTokens)), row?.maxOutput || 32_000);
|
|
209
|
+
// Sampling is sent only when the user set it (null / '' / undefined is "the model's default": Number(null) is 0, which
|
|
210
|
+
// reasoning models refuse) and never to a model that takes only its default (`fixedSampling` in models.js).
|
|
211
|
+
if (temperature !== null && temperature !== undefined && temperature !== '' && Number.isFinite(Number(temperature)) && !maritacaFixedSampling(row)) {
|
|
212
|
+
body.temperature = Math.min(2, Math.max(0, Number(temperature)));
|
|
213
|
+
}
|
|
214
|
+
// reasoning_effort only on a model that reasons with levels (the S5 family); other models refuse unknown fields. An alias
|
|
215
|
+
// (xhigh, max, minimal) is sent as the level it names; a level the row does not list is left out (the model's default).
|
|
216
|
+
const effort = normalizeMaritacaEffort(reasoningEffort);
|
|
217
|
+
if (effort && row?.efforts?.length && row.efforts.includes(effort)) body.reasoning_effort = effort;
|
|
218
|
+
if (Array.isArray(tools) && tools.length && row?.toolcall !== false) {
|
|
219
|
+
body.tools = tools;
|
|
220
|
+
if (toolChoice) body.tool_choice = toolChoice;
|
|
221
|
+
}
|
|
222
|
+
return body;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* The client. `fetchImpl` is injectable (tests); `baseUrl` too (a proxy). `getKey` is asked for the
|
|
227
|
+
* key at every call, so a key saved while a panel is open is used at once.
|
|
228
|
+
*/
|
|
229
|
+
export function createMaritacaClient({ fetchImpl = globalThis.fetch, baseUrl = MARITACA_BASE_URL, timeoutMs = DEFAULT_TIMEOUT_MS, streamIdleMs = STREAM_IDLE_MS } = {}) {
|
|
230
|
+
if (typeof fetchImpl !== 'function') throw new Error('createMaritacaClient needs fetch');
|
|
231
|
+
const base = String(baseUrl).replace(/\/+$/, '');
|
|
232
|
+
|
|
233
|
+
async function request(path, { key, method = 'GET', body = null, signal = null, timeout = timeoutMs } = {}) {
|
|
234
|
+
if (!key) throw maritacaError('NO_KEY', 'No Maritaca API key is saved.');
|
|
235
|
+
const gate = abortIn(timeout, signal);
|
|
236
|
+
let response;
|
|
237
|
+
try {
|
|
238
|
+
response = await fetchImpl(`${base}${path}`, { method, headers: headers(key), body: body ? JSON.stringify(body) : undefined, signal: gate.signal, redirect: 'error' });
|
|
239
|
+
} catch (error) {
|
|
240
|
+
gate.done();
|
|
241
|
+
throw networkError(error, signal);
|
|
242
|
+
}
|
|
243
|
+
if (!response.ok) {
|
|
244
|
+
const message = await readErrorMessage(response);
|
|
245
|
+
gate.done();
|
|
246
|
+
throw maritacaError(codeForStatus(response.status), message, response.status);
|
|
247
|
+
}
|
|
248
|
+
return { response, done: gate.done, touch: gate.touch };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** GET /models when the API answers it; merged over the table. { models, source: 'live' | 'table', error? } */
|
|
252
|
+
async function listModels({ key, signal = null } = {}) {
|
|
253
|
+
const table = maritacaModelRows();
|
|
254
|
+
if (!key) return { models: table, source: 'table', error: 'NO_KEY' };
|
|
255
|
+
let live = null;
|
|
256
|
+
try {
|
|
257
|
+
const { response, done } = await request('/models', { key, signal });
|
|
258
|
+
try { live = await response.json(); } catch { live = null; }
|
|
259
|
+
done();
|
|
260
|
+
} catch (error) {
|
|
261
|
+
return { models: table, source: 'table', error: error.code || 'HTTP_ERROR', message: error.message };
|
|
262
|
+
}
|
|
263
|
+
const ids = Array.isArray(live?.data) ? live.data.map((m) => (typeof m === 'string' ? m : m?.id)).filter((id) => typeof id === 'string' && id.trim()) : [];
|
|
264
|
+
if (!ids.length) return { models: table, source: 'table', error: 'EMPTY' };
|
|
265
|
+
const seen = new Set();
|
|
266
|
+
const out = [];
|
|
267
|
+
for (const id of ids) {
|
|
268
|
+
const row = findMaritacaModel(id);
|
|
269
|
+
const canon = row ? row.id : id.trim();
|
|
270
|
+
if (seen.has(canon.toLowerCase())) continue;
|
|
271
|
+
seen.add(canon.toLowerCase());
|
|
272
|
+
out.push(row ? { ...table.find((t) => t.id === row.id), listed: true } : {
|
|
273
|
+
id: canon, label: canon, family: null, aliases: [], tier: null, contextWindow: null, maxOutput: null, reasoning: null, efforts: [], defaultEffort: null,
|
|
274
|
+
toolcall: null, vision: false, price: null, region: null, free: false, description: null, batch: true, flex: true, rateLimit: null, isDefault: false, known: false, listed: true,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
for (const row of table) if (!seen.has(row.id.toLowerCase())) out.push({ ...row, listed: false });
|
|
278
|
+
return { models: out, source: 'live' };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Is the key accepted? GET /models first (free, read-only); an API that has no /models (404 / 405) is asked for
|
|
283
|
+
* one token of the free model instead. Resolves { ok: true, via } or throws a maritacaError (KEY_REJECTED…).
|
|
284
|
+
*/
|
|
285
|
+
async function verifyKey({ key, signal = null } = {}) {
|
|
286
|
+
try {
|
|
287
|
+
const { response, done } = await request('/models', { key, signal });
|
|
288
|
+
try { await response.body?.cancel(); } catch { /* ignore */ }
|
|
289
|
+
done();
|
|
290
|
+
return { ok: true, via: 'models' };
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (error.code !== 'MODEL_UNKNOWN' && error.status !== 405) throw error;
|
|
293
|
+
}
|
|
294
|
+
const { response, done } = await request('/chat/completions', { key, method: 'POST', signal, body: { model: 'S5-free', messages: [{ role: 'user', content: 'oi' }], max_tokens: 1, stream: false } });
|
|
295
|
+
try { await response.body?.cancel(); } catch { /* ignore */ }
|
|
296
|
+
done();
|
|
297
|
+
return { ok: true, via: 'completion' };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* POST /chat/completions; a 400 that refuses a sampling field ("Unsupported value: 'temperature' …") is asked once more
|
|
302
|
+
* without temperature / top_p, so a model that takes only its default never fails a turn over a setting.
|
|
303
|
+
*/
|
|
304
|
+
async function postCompletion(body, { key, signal }) {
|
|
305
|
+
try {
|
|
306
|
+
return await request('/chat/completions', { key, method: 'POST', body, signal, timeout: streamIdleMs });
|
|
307
|
+
} catch (error) {
|
|
308
|
+
if (!isSamplingRefusal(error) || (!('temperature' in body) && !('top_p' in body))) throw error;
|
|
309
|
+
const { temperature: _t, top_p: _p, ...rest } = body;
|
|
310
|
+
return request('/chat/completions', { key, method: 'POST', body: rest, signal, timeout: streamIdleMs });
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** One non-streamed completion: resolves { text, reasoning, toolCalls, usage, finishReason, raw }. */
|
|
315
|
+
async function chat({ key, signal = null, ...params } = {}) {
|
|
316
|
+
const body = buildChatBody({ ...params, stream: false });
|
|
317
|
+
const { response, done } = await postCompletion(body, { key, signal });
|
|
318
|
+
let data = null;
|
|
319
|
+
try { data = await response.json(); } catch { data = null; }
|
|
320
|
+
done();
|
|
321
|
+
if (!data || typeof data !== 'object') throw maritacaError('BAD_ANSWER', 'Maritaca answered with something that is not JSON.');
|
|
322
|
+
const folder = createStreamFolder();
|
|
323
|
+
folder.push(data);
|
|
324
|
+
folder.push({ done: true });
|
|
325
|
+
return { ...folder.end(), raw: data };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* One streamed completion (see the header). `signal` stops it; a stream that goes quiet for streamIdleMs (no bytes,
|
|
330
|
+
* the clock reset by every chunk) ends with TIMEOUT; a long answer that keeps streaming has no total deadline.
|
|
331
|
+
*/
|
|
332
|
+
async function chatStream({ key, signal = null, onEvent = () => {}, ...params } = {}) {
|
|
333
|
+
const body = buildChatBody({ ...params, stream: true });
|
|
334
|
+
const { response, done, touch } = await postCompletion(body, { key, signal });
|
|
335
|
+
const folder = createStreamFolder(onEvent);
|
|
336
|
+
try {
|
|
337
|
+
if (!response.body) throw maritacaError('BAD_ANSWER', 'Maritaca sent no stream.');
|
|
338
|
+
const contentType = String(response.headers?.get?.('content-type') || '');
|
|
339
|
+
if (/application\/json/i.test(contentType) && !/event-stream/i.test(contentType)) {
|
|
340
|
+
// An API that ignored `stream`: fold the one answer.
|
|
341
|
+
let data = null;
|
|
342
|
+
try { data = await response.json(); } catch { data = null; }
|
|
343
|
+
folder.push(data);
|
|
344
|
+
folder.push({ done: true });
|
|
345
|
+
return folder.end();
|
|
346
|
+
}
|
|
347
|
+
let sawDone = false;
|
|
348
|
+
for await (const chunk of parseSseChunks(touching(response.body, touch))) {
|
|
349
|
+
if (chunk.done) sawDone = true;
|
|
350
|
+
folder.push(chunk);
|
|
351
|
+
if (sawDone) break;
|
|
352
|
+
}
|
|
353
|
+
if (!sawDone) folder.push({ done: true });
|
|
354
|
+
return folder.end();
|
|
355
|
+
} catch (error) {
|
|
356
|
+
if (error?.code) throw error;
|
|
357
|
+
throw networkError(error, signal);
|
|
358
|
+
} finally { done(); }
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
return { baseUrl: base, listModels, verifyKey, chat, chatStream, models: () => MARITACA_MODELS };
|
|
362
|
+
}
|