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,273 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun — the Maritaca side panel's server end (/ws/maritaca)
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// One socket per panel window; no process (Maritaca is an HTTP API: lib/maritaca/client.js), so a
|
|
6
|
+
// turn is one streamed chat completion over the conversation's saved history (lib/maritaca/sessions.js).
|
|
7
|
+
// The page asks with `{ type, reqId, ... }` and gets `{ type: 'result', reqId, ok, data | error, code }`;
|
|
8
|
+
// what happens on its own comes as events:
|
|
9
|
+
//
|
|
10
|
+
// turn:start { sessionId, turnId, model, mode }
|
|
11
|
+
// turn:delta { sessionId, turnId, text } answer text as it streams
|
|
12
|
+
// turn:reasoning { sessionId, turnId, text } reasoning text (S5, Sabiá 4 Thinking)
|
|
13
|
+
// turn:end { sessionId, turnId, text, reasoning, usage, costBrl, finishReason, mode, error?, code? }
|
|
14
|
+
// settings:changed { status } the key or the defaults changed (any window)
|
|
15
|
+
//
|
|
16
|
+
// The hello carries the shipped model table whole (lib/maritaca/models.js rows), so the page can draw its pickers at
|
|
17
|
+
// once; `models` asks the API for the current list, merged over that table.
|
|
18
|
+
// Requests: hello, models, session:new, session:list, session:load, session:rename, session:delete, session:project,
|
|
19
|
+
// prompt, regenerate, cancel. `prompt` / `regenerate` take `mode: 'chat' | 'plan'` (lib/maritaca/modes.js: a plan turn
|
|
20
|
+
// carries the plan instruction after the user's system prompt and is saved as a plan; capability 'plan-mode') and a
|
|
21
|
+
// reasoning level, an alias of one included (models.js normalizeMaritacaEffort). The key is never on this socket: it is saved, tested and cleared through
|
|
22
|
+
// /api/maritaca/settings (lib/maritaca/api.js) and read here per prompt from the key store, so a key
|
|
23
|
+
// saved while a panel is open is used by its next prompt. `capabilities` in the hello answer lists
|
|
24
|
+
// what this server does; the page offers a feature only while it is listed (public/ reloads at any
|
|
25
|
+
// time, lib/ only with a restart). Nothing the page sends is trusted: ids are SynaBun's own 32-hex
|
|
26
|
+
// ids, text is bounded, a model is one the table or the API's list knows (the ids of the last `models` answer that
|
|
27
|
+
// came from the API are kept for that; else the saved default).
|
|
28
|
+
|
|
29
|
+
import { MARITACA_SESSION_LIMITS, historyForRequest, isSessionId } from './sessions.js';
|
|
30
|
+
import { findMaritacaModel, maritacaModelRows, maritacaUsageCostBrl, normalizeMaritacaEffort } from './models.js';
|
|
31
|
+
import { inlineMaritacaAttachments, MARITACA_ATTACHMENT_LIMITS } from './attachments.js';
|
|
32
|
+
import { maritacaSystemPrompt, normalizeMaritacaMode } from './modes.js';
|
|
33
|
+
|
|
34
|
+
export const MARITACA_WS_PATH = '/ws/maritaca';
|
|
35
|
+
export const MARITACA_PANEL_CAPABILITIES = Object.freeze([
|
|
36
|
+
'session-new', 'session-list', 'session-load', 'session-rename', 'session-delete', 'prompt', 'cancel', 'models',
|
|
37
|
+
'reasoning', 'reasoning-effort', 'usage', 'cost-brl', 'system-prompt', 'greeting-note',
|
|
38
|
+
'attachments', 'regenerate', 'edit-resend', 'session-project', 'plan-mode', 'effort-levels',
|
|
39
|
+
]);
|
|
40
|
+
export const MARITACA_LIMITS = Object.freeze({
|
|
41
|
+
maxPromptChars: MARITACA_SESSION_LIMITS.maxMessageChars,
|
|
42
|
+
maxTitleChars: MARITACA_SESSION_LIMITS.maxTitleChars,
|
|
43
|
+
maxProjectChars: 1000,
|
|
44
|
+
attachments: MARITACA_ATTACHMENT_LIMITS,
|
|
45
|
+
});
|
|
46
|
+
const REQ_ID_RE = /^[A-Za-z0-9._:-]{1,80}$/;
|
|
47
|
+
|
|
48
|
+
function bridgeError(code, message, status = 400) { return Object.assign(new Error(message), { code, status }); }
|
|
49
|
+
const str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {object} deps
|
|
53
|
+
* @param {object} deps.client lib/maritaca/client.js
|
|
54
|
+
* @param {object} deps.keyStore lib/maritaca/key-store.js
|
|
55
|
+
* @param {object} deps.sessions lib/maritaca/sessions.js
|
|
56
|
+
* @param {(info:{ sessionId:string, project:string|null, words:string })=>void} [deps.onHumanPrompt]
|
|
57
|
+
* @param {(line:string)=>void} [deps.log]
|
|
58
|
+
*/
|
|
59
|
+
export function createMaritacaPanelBridge({ client, keyStore, sessions, onHumanPrompt = null, log = () => {} } = {}) {
|
|
60
|
+
if (!client || !keyStore || !sessions) throw new Error('createMaritacaPanelBridge needs client, keyStore and sessions');
|
|
61
|
+
const live = new Set(); // socket states
|
|
62
|
+
const turns = new Map(); // sessionId → { turnId, controller, socket }
|
|
63
|
+
let liveModelIds = new Map(); // lower-cased id → id as the API listed it (the last live `models` answer)
|
|
64
|
+
let liveModelRows = new Map();
|
|
65
|
+
let turnSeq = 0;
|
|
66
|
+
|
|
67
|
+
function broadcast(message) { for (const state of live) state.send(message); }
|
|
68
|
+
|
|
69
|
+
function resolveModel(requested) {
|
|
70
|
+
const settings = keyStore.readSettings();
|
|
71
|
+
const row = findMaritacaModel(requested);
|
|
72
|
+
if (row) return row.id;
|
|
73
|
+
const wanted = str(requested, 80).trim();
|
|
74
|
+
const live = wanted ? liveModelIds.get(wanted.toLowerCase()) : null;
|
|
75
|
+
if (live) return live;
|
|
76
|
+
const fallback = findMaritacaModel(settings.model);
|
|
77
|
+
return fallback ? fallback.id : settings.model;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function runTurn(state, { sessionId, text, model, reasoningEffort, mode: requestedMode, attachments = [], messageIndex = null, editText }) {
|
|
81
|
+
const session = sessions.get(sessionId);
|
|
82
|
+
if (!session) throw bridgeError('SESSION_UNKNOWN', 'That conversation no longer exists.', 404);
|
|
83
|
+
if (turns.has(sessionId)) throw bridgeError('TURN_RUNNING', 'A reply is already streaming in this conversation.', 409);
|
|
84
|
+
const key = keyStore.readKey();
|
|
85
|
+
if (!key) throw bridgeError('NO_KEY', 'Save a Maritaca API key first.', 412);
|
|
86
|
+
const chosen = resolveModel(model || session.model);
|
|
87
|
+
const settings = keyStore.readSettings();
|
|
88
|
+
const row = findMaritacaModel(chosen) || liveModelRows.get(chosen.toLowerCase());
|
|
89
|
+
const asked = normalizeMaritacaEffort(reasoningEffort);
|
|
90
|
+
const saved = normalizeMaritacaEffort(settings.reasoningEffort);
|
|
91
|
+
const effort = asked && row?.efforts?.includes(asked) ? asked : saved && row?.efforts?.includes(saved) ? saved : null;
|
|
92
|
+
// A regenerate or an edit that names no mode keeps the mode of the prompt it reruns (a plan is regenerated as a plan).
|
|
93
|
+
const mode = requestedMode !== undefined ? normalizeMaritacaMode(requestedMode) : messageIndex !== null ? normalizeMaritacaMode(session.messages[messageIndex]?.mode) : 'chat';
|
|
94
|
+
if (messageIndex !== null) {
|
|
95
|
+
if (!Number.isInteger(messageIndex) || session.messages[messageIndex]?.role !== 'user') throw bridgeError('PROMPT_UNKNOWN', 'Choose a user message to retry.');
|
|
96
|
+
if (session.messages.slice(0, messageIndex + 1).some((m) => m.images?.length) && row?.vision !== true) throw bridgeError('IMAGE_UNSUPPORTED', 'This model does not read images.');
|
|
97
|
+
sessions.rewind(sessionId, messageIndex, editText, { mode });
|
|
98
|
+
} else {
|
|
99
|
+
if (session.messages.some((m) => m.images?.length) && row?.vision !== true) throw bridgeError('IMAGE_UNSUPPORTED', 'This model does not read images.');
|
|
100
|
+
const prompt = inlineMaritacaAttachments(text, attachments, { vision: row?.vision === true });
|
|
101
|
+
sessions.append(sessionId, { role: 'user', ...prompt, mode });
|
|
102
|
+
}
|
|
103
|
+
if (session.model !== chosen) sessions.update(sessionId, { model: chosen });
|
|
104
|
+
const history = historyForRequest(sessions.get(sessionId).messages, { systemPrompt: maritacaSystemPrompt({ systemPrompt: settings.systemPrompt, mode }) });
|
|
105
|
+
const turnId = `t${Date.now().toString(36)}-${++turnSeq}`;
|
|
106
|
+
const controller = new AbortController();
|
|
107
|
+
const snapshot = sessions.get(sessionId);
|
|
108
|
+
const turn = { turnId, controller, socket: state, sessionId, model: chosen, mode, startedAt: Date.now(), partialText: '', partialReasoning: '' };
|
|
109
|
+
turns.set(sessionId, turn);
|
|
110
|
+
try { onHumanPrompt?.({ sessionId, project: session.project || null, words: text }); } catch { /* the greeting's problem */ }
|
|
111
|
+
broadcast({ type: 'turn:start', sessionId, turnId, model: chosen, mode, startedAt: turn.startedAt, session: snapshot });
|
|
112
|
+
(async () => {
|
|
113
|
+
let result = null;
|
|
114
|
+
let failure = null;
|
|
115
|
+
try {
|
|
116
|
+
result = await client.chatStream({
|
|
117
|
+
key, model: chosen, messages: history, reasoningEffort: effort, temperature: settings.temperature, signal: controller.signal,
|
|
118
|
+
onEvent: (event) => {
|
|
119
|
+
// Kept here too: the client's chatStream rejects on a stop or a failure without handing back what streamed.
|
|
120
|
+
if (event.type === 'delta') { const offset = turn.partialText.length; turn.partialText += event.text || ''; broadcast({ type: 'turn:delta', sessionId, turnId, text: event.text, offset }); }
|
|
121
|
+
else if (event.type === 'reasoning') { const offset = turn.partialReasoning.length; turn.partialReasoning += event.text || ''; broadcast({ type: 'turn:reasoning', sessionId, turnId, text: event.text, offset }); }
|
|
122
|
+
},
|
|
123
|
+
partial: null,
|
|
124
|
+
});
|
|
125
|
+
} catch (error) {
|
|
126
|
+
failure = error;
|
|
127
|
+
}
|
|
128
|
+
turns.delete(sessionId);
|
|
129
|
+
const cancelled = controller.signal.aborted;
|
|
130
|
+
const text = result?.text || turn.partialText || '';
|
|
131
|
+
const reasoning = result?.reasoning || turn.partialReasoning || '';
|
|
132
|
+
const usage = result?.usage || null;
|
|
133
|
+
const costBrl = usage ? maritacaUsageCostBrl(chosen, usage) : null;
|
|
134
|
+
const finishReason = cancelled ? 'cancelled' : failure ? 'error' : result?.finishReason || 'stop';
|
|
135
|
+
const errorMessage = failure && !cancelled ? failure.message : null;
|
|
136
|
+
const code = failure && !cancelled ? failure.code || 'HTTP_ERROR' : null;
|
|
137
|
+
// The reply is saved whatever happened: a stop keeps what streamed (finishReason 'cancelled'); a failure leaves what
|
|
138
|
+
// streamed, or an empty assistant row, with its error, so the conversation shows what went wrong when it is opened again.
|
|
139
|
+
try { sessions.append(sessionId, { role: 'assistant', turnId, content: text, reasoning, usage, costBrl, model: chosen, finishReason, error: errorMessage, mode }); }
|
|
140
|
+
catch (error) { log(`[maritaca] could not save a reply: ${error?.message || error}`); }
|
|
141
|
+
if (failure && !cancelled) log(`[maritaca] turn failed: ${code} ${failure.message}`);
|
|
142
|
+
let saved = null;
|
|
143
|
+
try { saved = sessions.get(sessionId); } catch { /* completion still reaches the page after a storage failure */ }
|
|
144
|
+
broadcast({ type: 'turn:end', sessionId, turnId, text, reasoning, usage, costBrl, finishReason, mode, ...(saved ? { messageCount: saved.messages.length, priorCostBrl: saved.priorCostBrl || 0 } : {}), ...(errorMessage ? { error: errorMessage, code } : {}) });
|
|
145
|
+
})();
|
|
146
|
+
return { turnId, model: chosen, reasoningEffort: effort, mode, session: snapshot };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function removeSession(sessionId) {
|
|
150
|
+
if (!isSessionId(sessionId)) throw bridgeError('SESSION_INVALID', 'Unknown conversation.');
|
|
151
|
+
turns.get(sessionId)?.controller.abort(new Error('deleted'));
|
|
152
|
+
const deleted = sessions.remove(sessionId);
|
|
153
|
+
broadcast({ type: 'session:deleted', sessionId });
|
|
154
|
+
return { deleted };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function renameSession(sessionId, title) {
|
|
158
|
+
if (!isSessionId(sessionId)) throw bridgeError('SESSION_INVALID', 'Unknown conversation.');
|
|
159
|
+
const session = sessions.update(sessionId, { title: str(title, MARITACA_LIMITS.maxTitleChars) });
|
|
160
|
+
if (!session) throw bridgeError('SESSION_UNKNOWN', 'That conversation no longer exists.', 404);
|
|
161
|
+
broadcast({ type: 'session:renamed', sessionId, title: session.title });
|
|
162
|
+
return { session: { id: session.id, title: session.title } };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const handlers = {
|
|
166
|
+
async hello() {
|
|
167
|
+
const status = keyStore.status();
|
|
168
|
+
return { capabilities: [...MARITACA_PANEL_CAPABILITIES], limits: { ...MARITACA_LIMITS }, configured: status.configured, source: status.source, masked: status.masked, settings: status.settings, models: maritacaModelRows() };
|
|
169
|
+
},
|
|
170
|
+
async models() {
|
|
171
|
+
const listed = await client.listModels({ key: keyStore.readKey() });
|
|
172
|
+
if (listed.source === 'live' && Array.isArray(listed.models)) {
|
|
173
|
+
liveModelIds = new Map(listed.models.filter((m) => typeof m?.id === 'string' && m.id.trim()).map((m) => [m.id.trim().toLowerCase(), m.id.trim().slice(0, 80)]));
|
|
174
|
+
liveModelRows = new Map(listed.models.filter((m) => typeof m?.id === 'string').map((m) => [m.id.toLowerCase(), m]));
|
|
175
|
+
}
|
|
176
|
+
return { models: listed.models, source: listed.source, ...(listed.error ? { error: listed.error } : {}) };
|
|
177
|
+
},
|
|
178
|
+
async 'session:new'(msg) {
|
|
179
|
+
const session = sessions.create({ title: str(msg.title, MARITACA_LIMITS.maxTitleChars), model: resolveModel(msg.model), project: str(msg.project, MARITACA_LIMITS.maxProjectChars) || null });
|
|
180
|
+
return { session };
|
|
181
|
+
},
|
|
182
|
+
async 'session:list'(msg) {
|
|
183
|
+
return { sessions: sessions.list({ project: str(msg.project, MARITACA_LIMITS.maxProjectChars) || null, limit: msg.limit }) };
|
|
184
|
+
},
|
|
185
|
+
async 'session:load'(msg) {
|
|
186
|
+
if (!isSessionId(msg.sessionId)) throw bridgeError('SESSION_INVALID', 'Unknown conversation.');
|
|
187
|
+
const session = sessions.get(msg.sessionId);
|
|
188
|
+
if (!session) throw bridgeError('SESSION_UNKNOWN', 'That conversation no longer exists.', 404);
|
|
189
|
+
const turn = turns.get(session.id);
|
|
190
|
+
return { session, running: turn?.turnId || null, partial: turn ? { turnId: turn.turnId, text: turn.partialText, reasoning: turn.partialReasoning, startedAt: turn.startedAt, model: turn.model, mode: turn.mode } : null };
|
|
191
|
+
},
|
|
192
|
+
async 'session:rename'(msg) {
|
|
193
|
+
return renameSession(msg.sessionId, msg.title);
|
|
194
|
+
},
|
|
195
|
+
async 'session:delete'(msg) {
|
|
196
|
+
return removeSession(msg.sessionId);
|
|
197
|
+
},
|
|
198
|
+
async 'session:project'(msg) {
|
|
199
|
+
if (!isSessionId(msg.sessionId)) throw bridgeError('SESSION_INVALID', 'Unknown conversation.');
|
|
200
|
+
const session = sessions.update(msg.sessionId, { project: str(msg.project, MARITACA_LIMITS.maxProjectChars) || null });
|
|
201
|
+
if (!session) throw bridgeError('SESSION_UNKNOWN', 'That conversation no longer exists.', 404);
|
|
202
|
+
return { session: { id: session.id, project: session.project } };
|
|
203
|
+
},
|
|
204
|
+
async prompt(msg, state) {
|
|
205
|
+
if (!isSessionId(msg.sessionId)) throw bridgeError('SESSION_INVALID', 'Unknown conversation.');
|
|
206
|
+
const text = typeof msg.text === 'string' ? msg.text : '';
|
|
207
|
+
if (!text.trim() && !msg.attachments?.length) throw bridgeError('PROMPT_EMPTY', 'Type something first.');
|
|
208
|
+
if (text.length > MARITACA_LIMITS.maxPromptChars) throw bridgeError('PROMPT_TOO_LONG', `The message is longer than ${MARITACA_LIMITS.maxPromptChars} characters.`);
|
|
209
|
+
return runTurn(state, { sessionId: msg.sessionId, text, attachments: msg.attachments ?? [], model: str(msg.model, 80), reasoningEffort: str(msg.reasoningEffort, 20), mode: msg.mode === undefined ? 'chat' : str(msg.mode, 10) });
|
|
210
|
+
},
|
|
211
|
+
async regenerate(msg, state) {
|
|
212
|
+
if (!isSessionId(msg.sessionId)) throw bridgeError('SESSION_INVALID', 'Unknown conversation.');
|
|
213
|
+
const session = sessions.get(msg.sessionId);
|
|
214
|
+
if (!session) throw bridgeError('SESSION_UNKNOWN', 'That conversation no longer exists.', 404);
|
|
215
|
+
const messageIndex = msg.messageIndex === undefined ? session.messages.findLastIndex((m) => m.role === 'user') : msg.messageIndex;
|
|
216
|
+
if (!Number.isInteger(messageIndex) || session.messages[messageIndex]?.role !== 'user') throw bridgeError('PROMPT_UNKNOWN', 'Choose a user message to retry.');
|
|
217
|
+
if (msg.text !== undefined && (typeof msg.text !== 'string' || !msg.text.trim())) throw bridgeError('PROMPT_EMPTY', 'Type something first.');
|
|
218
|
+
if (typeof msg.text === 'string' && msg.text.length > MARITACA_LIMITS.maxPromptChars) throw bridgeError('PROMPT_TOO_LONG', 'The message is too long.');
|
|
219
|
+
return runTurn(state, { sessionId: msg.sessionId, text: msg.text ?? '', editText: msg.text, messageIndex, model: str(msg.model, 80), reasoningEffort: str(msg.reasoningEffort, 20), mode: msg.mode === undefined ? undefined : str(msg.mode, 10) });
|
|
220
|
+
},
|
|
221
|
+
async cancel(msg) {
|
|
222
|
+
if (!isSessionId(msg.sessionId)) throw bridgeError('SESSION_INVALID', 'Unknown conversation.');
|
|
223
|
+
const running = turns.get(msg.sessionId);
|
|
224
|
+
if (!running) return { cancelled: false };
|
|
225
|
+
running.controller.abort(new Error('cancelled'));
|
|
226
|
+
return { cancelled: true, turnId: running.turnId };
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
function handleSocket(ws) {
|
|
231
|
+
let closed = false;
|
|
232
|
+
const state = {
|
|
233
|
+
send(message) {
|
|
234
|
+
if (closed || ws.readyState !== 1) return;
|
|
235
|
+
try { ws.send(JSON.stringify(message)); } catch { /* the close handler cleans up */ }
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
live.add(state);
|
|
239
|
+
ws.on('message', async (raw) => {
|
|
240
|
+
let msg;
|
|
241
|
+
try { msg = JSON.parse(String(raw)); } catch { state.send({ type: 'result', reqId: null, ok: false, code: 'BAD_JSON', error: 'Not JSON.' }); return; }
|
|
242
|
+
const reqId = REQ_ID_RE.test(String(msg?.reqId || '')) ? String(msg.reqId) : null;
|
|
243
|
+
const type = typeof msg?.type === 'string' ? msg.type : '';
|
|
244
|
+
const handler = Object.hasOwn(handlers, type) ? handlers[type] : null;
|
|
245
|
+
if (!handler) { state.send({ type: 'result', reqId, ok: false, code: 'UNKNOWN_REQUEST', error: `Unknown request: ${type || '?'}` }); return; }
|
|
246
|
+
try {
|
|
247
|
+
const data = await handler(msg, state);
|
|
248
|
+
state.send({ type: 'result', reqId, ok: true, data });
|
|
249
|
+
} catch (error) {
|
|
250
|
+
state.send({ type: 'result', reqId, ok: false, code: error?.code || 'ERROR', error: error?.message || 'Something went wrong.' });
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
const end = () => { closed = true; live.delete(state); };
|
|
254
|
+
ws.on('close', end);
|
|
255
|
+
ws.on('error', end);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
return {
|
|
259
|
+
handleSocket,
|
|
260
|
+
liveCount: () => live.size,
|
|
261
|
+
turnsRunning: () => turns.size,
|
|
262
|
+
removeSession,
|
|
263
|
+
renameSession,
|
|
264
|
+
/** The key or the defaults changed (the REST router says so): every open panel is told. */
|
|
265
|
+
notifySettingsChanged: () => broadcast({ type: 'settings:changed', status: keyStore.status() }),
|
|
266
|
+
closeAll: async () => {
|
|
267
|
+
for (const turn of turns.values()) turn.controller.abort(new Error('shutdown'));
|
|
268
|
+
turns.clear();
|
|
269
|
+
live.clear();
|
|
270
|
+
},
|
|
271
|
+
_handlers: handlers,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun — Maritaca AI: the conversation store
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// Maritaca keeps no conversation on its side: every request carries the whole history. SynaBun keeps
|
|
6
|
+
// each conversation as one JSON file, DATA_HOME/data/maritaca/sessions/<id>.json ({ id, title, model,
|
|
7
|
+
// project, createdAt, updatedAt, messages: [{ role, content, reasoning?, usage?, costBrl?, mode?, at }] }),
|
|
8
|
+
// bounded in messages and bytes; an id is SynaBun's own (never from a page), a project is a plain
|
|
9
|
+
// string the page shows (no file is read from it). Pure helpers first, then the store.
|
|
10
|
+
|
|
11
|
+
import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import { randomUUID } from 'node:crypto';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
|
|
15
|
+
export const MARITACA_SESSION_LIMITS = Object.freeze({
|
|
16
|
+
maxMessages: 400,
|
|
17
|
+
maxMessageChars: 200_000,
|
|
18
|
+
maxTitleChars: 120,
|
|
19
|
+
maxSessions: 500,
|
|
20
|
+
maxHistoryChars: 1_500_000, // what one request may carry; older turns are dropped first (the system prompt stays)
|
|
21
|
+
pruneGraceMs: 60_000, // a conversation updated this recently is never pruned to make room for a new one
|
|
22
|
+
});
|
|
23
|
+
const ID_RE = /^[a-f0-9]{32}$/;
|
|
24
|
+
|
|
25
|
+
export function newSessionId() { return randomUUID().replace(/-/g, ''); }
|
|
26
|
+
export function isSessionId(id) { return typeof id === 'string' && ID_RE.test(id); }
|
|
27
|
+
|
|
28
|
+
/** The title a first prompt gives a conversation: its first line, trimmed and bounded. */
|
|
29
|
+
export function titleFromPrompt(text, max = MARITACA_SESSION_LIMITS.maxTitleChars) {
|
|
30
|
+
const line = String(text || '').split(/\r?\n/).map((s) => s.trim()).find(Boolean) || '';
|
|
31
|
+
return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The messages a request carries for a conversation: the system prompt (when any) and the newest
|
|
36
|
+
* turns that fit `maxChars`, oldest dropped first, never a tool message left without its call. An assistant row
|
|
37
|
+
* with no content (a failed or stopped turn) stays in the stored conversation for display but is left out of a
|
|
38
|
+
* request: some OpenAI-compatible servers refuse an empty assistant message with 400.
|
|
39
|
+
*/
|
|
40
|
+
export function historyForRequest(messages, { systemPrompt = '', maxChars = MARITACA_SESSION_LIMITS.maxHistoryChars } = {}) {
|
|
41
|
+
const turns = (Array.isArray(messages) ? messages : [])
|
|
42
|
+
.filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string')
|
|
43
|
+
.filter((m) => m.role !== 'assistant' || m.content.trim());
|
|
44
|
+
const out = [];
|
|
45
|
+
let used = systemPrompt.length;
|
|
46
|
+
for (let i = turns.length - 1; i >= 0; i--) {
|
|
47
|
+
const m = turns[i];
|
|
48
|
+
if (used + m.content.length > maxChars && out.length) break;
|
|
49
|
+
used += m.content.length;
|
|
50
|
+
out.unshift({ role: m.role, content: m.role === 'user' && m.images?.length ? [{ type: 'text', text: m.content }, ...m.images] : m.content });
|
|
51
|
+
}
|
|
52
|
+
return systemPrompt.trim() ? [{ role: 'system', content: systemPrompt }, ...out] : out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The summary row a list shows. */
|
|
56
|
+
export function sessionSummary(session) {
|
|
57
|
+
const messages = Array.isArray(session?.messages) ? session.messages : [];
|
|
58
|
+
const last = messages[messages.length - 1] || null;
|
|
59
|
+
return {
|
|
60
|
+
id: session.id, title: session.title || '', model: session.model || null, project: session.project || null,
|
|
61
|
+
createdAt: session.createdAt, updatedAt: session.updatedAt, messageCount: messages.length,
|
|
62
|
+
preview: last ? String(last.content || '').slice(0, 160) : '',
|
|
63
|
+
costBrl: (Number(session.priorCostBrl) || 0) + messages.reduce((sum, m) => sum + (Number(m.costBrl) || 0), 0),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function createMaritacaSessionStore({ dir, limits = MARITACA_SESSION_LIMITS, now = () => new Date().toISOString() } = {}) {
|
|
68
|
+
if (!dir) throw new Error('createMaritacaSessionStore needs dir');
|
|
69
|
+
const pathOf = (id) => { if (!isSessionId(id)) throw Object.assign(new Error('Unknown conversation.'), { code: 'SESSION_INVALID', status: 400 }); return join(dir, `${id}.json`); };
|
|
70
|
+
|
|
71
|
+
function write(session) {
|
|
72
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
73
|
+
const target = pathOf(session.id);
|
|
74
|
+
const temp = `${target}.${randomUUID()}.tmp`;
|
|
75
|
+
try { writeFileSync(temp, JSON.stringify(session), { mode: 0o600, flag: 'wx' }); renameSync(temp, target); }
|
|
76
|
+
finally { rmSync(temp, { force: true }); }
|
|
77
|
+
return session;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function get(id) {
|
|
81
|
+
const path = pathOf(id);
|
|
82
|
+
let raw;
|
|
83
|
+
try { raw = readFileSync(path, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
84
|
+
try {
|
|
85
|
+
const session = JSON.parse(raw);
|
|
86
|
+
if (!session || session.id !== id || !Array.isArray(session.messages)) return null;
|
|
87
|
+
return session;
|
|
88
|
+
} catch { return null; }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function create({ title = '', model = null, project = null } = {}) {
|
|
92
|
+
const at = now();
|
|
93
|
+
const existing = list({ limit: 1000 });
|
|
94
|
+
if (existing.length >= limits.maxSessions) {
|
|
95
|
+
// The oldest conversations make room, never one updated within the grace (a turn may be streaming into it);
|
|
96
|
+
// when every candidate is that fresh nothing is pruned and the cap is exceeded for a while.
|
|
97
|
+
const grace = Number.isFinite(limits.pruneGraceMs) ? limits.pruneGraceMs : MARITACA_SESSION_LIMITS.pruneGraceMs;
|
|
98
|
+
const fresh = (row) => Date.parse(at) - Date.parse(row.updatedAt) < grace;
|
|
99
|
+
let excess = existing.length - (limits.maxSessions - 1);
|
|
100
|
+
for (let i = existing.length - 1; i >= 0 && excess > 0; i--) {
|
|
101
|
+
if (fresh(existing[i])) continue;
|
|
102
|
+
rmSync(join(dir, `${existing[i].id}.json`), { force: true });
|
|
103
|
+
excess--;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const session = {
|
|
107
|
+
id: newSessionId(), title: String(title || '').slice(0, limits.maxTitleChars), model: model ? String(model).slice(0, 80) : null,
|
|
108
|
+
project: project ? String(project).slice(0, 1000) : null, createdAt: at, updatedAt: at, messages: [],
|
|
109
|
+
};
|
|
110
|
+
return write(session);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function update(id, patch = {}) {
|
|
114
|
+
const session = get(id);
|
|
115
|
+
if (!session) return null;
|
|
116
|
+
if (typeof patch.title === 'string') session.title = patch.title.trim().slice(0, limits.maxTitleChars);
|
|
117
|
+
if (patch.model !== undefined) session.model = patch.model ? String(patch.model).slice(0, 80) : null;
|
|
118
|
+
if (patch.project !== undefined) session.project = patch.project ? String(patch.project).slice(0, 1000) : null;
|
|
119
|
+
session.updatedAt = now();
|
|
120
|
+
return write(session);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Appends one message ({ role, content, reasoning?, usage?, costBrl?, model? }); the oldest go when the list is full. */
|
|
124
|
+
function append(id, message) {
|
|
125
|
+
const session = get(id);
|
|
126
|
+
if (!session) return null;
|
|
127
|
+
const role = ['user', 'assistant'].includes(message?.role) ? message.role : null;
|
|
128
|
+
if (!role) throw Object.assign(new Error('A message is a user or assistant message.'), { code: 'MESSAGE_INVALID', status: 400 });
|
|
129
|
+
const content = String(message.content ?? '').slice(0, limits.maxMessageChars);
|
|
130
|
+
const entry = { role, content, at: now() };
|
|
131
|
+
if (role === 'user') {
|
|
132
|
+
if (typeof message.displayText === 'string') entry.displayText = message.displayText.slice(0, limits.maxMessageChars);
|
|
133
|
+
if (typeof message.attachmentText === 'string') entry.attachmentText = message.attachmentText.slice(0, limits.maxMessageChars);
|
|
134
|
+
if (Array.isArray(message.attachments)) entry.attachments = message.attachments.slice(0, 5);
|
|
135
|
+
if (Array.isArray(message.images) && message.images.length) entry.images = message.images.slice(0, 5);
|
|
136
|
+
}
|
|
137
|
+
if (typeof message.reasoning === 'string' && message.reasoning) entry.reasoning = message.reasoning.slice(0, limits.maxMessageChars);
|
|
138
|
+
if (message.usage && typeof message.usage === 'object') entry.usage = message.usage;
|
|
139
|
+
if (message.costBrl != null && Number.isFinite(Number(message.costBrl))) entry.costBrl = Number(message.costBrl);
|
|
140
|
+
if (message.model) entry.model = String(message.model).slice(0, 80);
|
|
141
|
+
if (message.turnId) entry.turnId = String(message.turnId).slice(0, 80);
|
|
142
|
+
if (message.finishReason) entry.finishReason = String(message.finishReason).slice(0, 40);
|
|
143
|
+
if (message.error) entry.error = String(message.error).slice(0, 400);
|
|
144
|
+
// Only a plan turn is marked (lib/maritaca/modes.js); a message without `mode` is a chat message.
|
|
145
|
+
if (message.mode === 'plan') entry.mode = 'plan';
|
|
146
|
+
session.messages.push(entry);
|
|
147
|
+
while (session.messages.length > limits.maxMessages) {
|
|
148
|
+
const removed = session.messages.shift();
|
|
149
|
+
session.priorCostBrl = (Number(session.priorCostBrl) || 0) + (Number(removed.costBrl) || 0);
|
|
150
|
+
}
|
|
151
|
+
if (!session.title && role === 'user') session.title = titleFromPrompt(message.displayText || content, limits.maxTitleChars);
|
|
152
|
+
session.updatedAt = entry.at;
|
|
153
|
+
write(session);
|
|
154
|
+
return entry;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function remove(id) {
|
|
158
|
+
const path = pathOf(id);
|
|
159
|
+
try { statSync(path); } catch { return false; }
|
|
160
|
+
rmSync(path, { force: true });
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Rewind to a user prompt for regenerate/edit. Preserve the cost of discarded replies. `mode` re-marks the prompt. */
|
|
165
|
+
function rewind(id, messageIndex, text = undefined, { mode } = {}) {
|
|
166
|
+
const session = get(id);
|
|
167
|
+
if (!session) return null;
|
|
168
|
+
const prompt = session.messages[messageIndex];
|
|
169
|
+
if (!Number.isInteger(messageIndex) || prompt?.role !== 'user') throw Object.assign(new Error('Choose a user message to retry.'), { code: 'PROMPT_UNKNOWN', status: 400 });
|
|
170
|
+
const next = text === undefined ? prompt.content : [text, prompt.attachmentText].filter(Boolean).join('\n\n');
|
|
171
|
+
if (next.length > limits.maxMessageChars) throw Object.assign(new Error('The message including files is too long.'), { code: 'PROMPT_TOO_LONG', status: 400 });
|
|
172
|
+
const removed = session.messages.slice(messageIndex + 1);
|
|
173
|
+
session.priorCostBrl = (Number(session.priorCostBrl) || 0) + removed.reduce((sum, m) => sum + (Number(m.costBrl) || 0), 0);
|
|
174
|
+
session.messages = session.messages.slice(0, messageIndex + 1);
|
|
175
|
+
if (text !== undefined) { prompt.displayText = text; prompt.content = next; }
|
|
176
|
+
if (mode === 'plan') prompt.mode = 'plan';
|
|
177
|
+
else if (mode !== undefined) delete prompt.mode;
|
|
178
|
+
session.updatedAt = now();
|
|
179
|
+
return write(session);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Every conversation's summary, newest first; `project` narrows to one project. */
|
|
183
|
+
function list({ project = null, limit = 200 } = {}) {
|
|
184
|
+
let names = [];
|
|
185
|
+
try { names = readdirSync(dir).filter((name) => /^[a-f0-9]{32}\.json$/.test(name)); } catch { return []; }
|
|
186
|
+
const rows = [];
|
|
187
|
+
for (const name of names) {
|
|
188
|
+
const session = get(name.slice(0, 32));
|
|
189
|
+
if (!session) continue;
|
|
190
|
+
if (project && session.project !== project) continue;
|
|
191
|
+
rows.push(sessionSummary(session));
|
|
192
|
+
}
|
|
193
|
+
rows.sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)));
|
|
194
|
+
return rows.slice(0, Math.max(1, Math.min(1000, Number(limit) || 200)));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return { dir, create, get, update, append, rewind, remove, list };
|
|
198
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// ── The owner's list of MoreLogin profiles agents may choose (DOM-free, no imports) ──
|
|
2
|
+
//
|
|
3
|
+
// A MoreLogin profile is a separate logged-in account. Which account an automation acts in is the owner's choice
|
|
4
|
+
// (security review 972afb74 of 2026-11-05, finding 1). The per-session profile work of 2026-11-10 let a session pick a
|
|
5
|
+
// profile for itself (`morelogin` "use", browser_session create's moreloginProfile, agent_dispatch morelogin_profile)
|
|
6
|
+
// and let the launch routes take one from any caller; a review the same day (run b6631e9d) found that this handed
|
|
7
|
+
// every profile, and so every account, to any local process. The owner's decision: an allowlist, empty by default.
|
|
8
|
+
//
|
|
9
|
+
// What it means:
|
|
10
|
+
// • It is the owner's list of the profiles an agent may put itself, or be put by another agent, into. With nothing
|
|
11
|
+
// on it, no session, dispatch or agent-made launch can select a profile at all.
|
|
12
|
+
// • The owner at SynaBun's page (this boot's page secret, never a guest: server.js browserOwnerPageOnly) is not
|
|
13
|
+
// limited by it: a schedule, a group, a timer or a launch the owner sets up there may use any Chrome-type profile.
|
|
14
|
+
// • The Browser-settings default profile is not part of it.
|
|
15
|
+
// • It is checked where a profile is chosen AND where a pin is used (pinUseRefusal), so taking a profile off the
|
|
16
|
+
// list stops the sessions already pinned to it at their next browser call. They are refused; they never fall back
|
|
17
|
+
// to the default profile or to Chrome.
|
|
18
|
+
//
|
|
19
|
+
// Where it is kept: the `moreloginAgentProfiles` key of the owner's browser settings (DATA_HOME/data/
|
|
20
|
+
// browser-config.json), written only by PUT /api/morelogin/agent-profiles, a route of the owner's page alone
|
|
21
|
+
// (server.js moreLoginGate: not in MORELOGIN_AUTOMATION_ROUTES). PUT /api/browser/config keeps the saved list whatever
|
|
22
|
+
// its body says, so the Settings form cannot drop it and no other writer exists.
|
|
23
|
+
//
|
|
24
|
+
// Who chose a profile travels with the choice (`by`): 'owner' only where the server itself saw the owner's page make
|
|
25
|
+
// it; anything else, a record from before this rule included, is 'agent' and needs the list. scheduleProfileAuthority
|
|
26
|
+
// says which of the two a schedule's run is.
|
|
27
|
+
|
|
28
|
+
/** The key of the owner's browser settings that holds the list. */
|
|
29
|
+
export const AGENT_PROFILES_KEY = 'moreloginAgentProfiles';
|
|
30
|
+
/** Entries kept at most (MoreLogin accounts hold far fewer profiles). */
|
|
31
|
+
export const AGENT_PROFILES_MAX = 500;
|
|
32
|
+
/** The refusal's code, everywhere a profile off the list is chosen or used. */
|
|
33
|
+
export const PROFILE_NOT_ALLOWED = 'MORELOGIN_PROFILE_NOT_ALLOWED';
|
|
34
|
+
/** Where the owner edits the list, as the refusals and the tools name it. */
|
|
35
|
+
export const AGENT_PROFILES_WHERE = 'SynaBun → Settings → Connected tools → MoreLogin → MoreLogin profiles → "Agents may choose"';
|
|
36
|
+
|
|
37
|
+
const cleanId = (value) => {
|
|
38
|
+
const id = value === null || value === undefined ? '' : String(value).trim();
|
|
39
|
+
return id && id.length <= 128 && !/[\u0000-\u001f]/.test(id) ? id : '';
|
|
40
|
+
};
|
|
41
|
+
const cleanName = (value) => (typeof value === 'string' ? value.trim().slice(0, 200) : '');
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The list as it is kept: [{ envId, name }], one entry per profile id, in the order given. Anything that is not a
|
|
45
|
+
* list, or an entry without a usable id, is nothing: an unreadable list allows no profile.
|
|
46
|
+
* @param {unknown} value the saved value, or a browser config that holds it
|
|
47
|
+
*/
|
|
48
|
+
export function normalizeAgentProfiles(value) {
|
|
49
|
+
const rows = Array.isArray(value) ? value : (value && typeof value === 'object' && Array.isArray(value[AGENT_PROFILES_KEY]) ? value[AGENT_PROFILES_KEY] : []);
|
|
50
|
+
const seen = new Set();
|
|
51
|
+
const out = [];
|
|
52
|
+
for (const row of rows) {
|
|
53
|
+
const envId = cleanId(row && typeof row === 'object' ? row.envId : row);
|
|
54
|
+
if (!envId || seen.has(envId)) continue;
|
|
55
|
+
seen.add(envId);
|
|
56
|
+
out.push({ envId, name: (row && typeof row === 'object' ? cleanName(row.name) : '') || null });
|
|
57
|
+
if (out.length >= AGENT_PROFILES_MAX) break;
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Whether `envId` is on the list (`source`: the list, or a browser config that holds it). By id only, never by name. */
|
|
63
|
+
export function agentProfileAllowed(source, envId) {
|
|
64
|
+
const id = cleanId(envId);
|
|
65
|
+
return !!id && normalizeAgentProfiles(source).some((row) => row.envId === id);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The list with `envId` put on it (`allowed` true) or taken off it. The name is kept for display only. */
|
|
69
|
+
export function withAgentProfile(source, envId, name, allowed) {
|
|
70
|
+
const id = cleanId(envId);
|
|
71
|
+
const rows = normalizeAgentProfiles(source).filter((row) => row.envId !== id);
|
|
72
|
+
if (id && allowed === true) rows.push({ envId: id, name: cleanName(name) || null });
|
|
73
|
+
return rows.slice(0, AGENT_PROFILES_MAX);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// The id of a local profile (a Chrome SynaBun runs itself, lib/local-profiles.js LOCAL_PROFILE_ID_RE; this module has
|
|
77
|
+
// no imports). The list, the pins and the refusals hold both kinds of profile by id; only the words differ.
|
|
78
|
+
const LOCAL_PROFILE_REF_RE = /^lp-[0-9a-f]{12}$/;
|
|
79
|
+
/** 'local profile' for one of SynaBun's own profiles, 'MoreLogin profile' for every other id. */
|
|
80
|
+
export function profileKindLabel(envId) {
|
|
81
|
+
return LOCAL_PROFILE_REF_RE.test(cleanId(envId)) ? 'local profile' : 'MoreLogin profile';
|
|
82
|
+
}
|
|
83
|
+
/** A profile as the refusals and the log lines name it: `MoreLogin profile "P-4" (id)`, `local profile "Shop" (id)`. */
|
|
84
|
+
export function describeProfile(envId, name = null) {
|
|
85
|
+
const kind = profileKindLabel(envId);
|
|
86
|
+
return cleanName(name) ? `${kind} "${cleanName(name)}" (${cleanId(envId)})` : `${kind} ${cleanId(envId)}`;
|
|
87
|
+
}
|
|
88
|
+
const describe = describeProfile;
|
|
89
|
+
|
|
90
|
+
/** What a refused agent is told, and what it tells the user. */
|
|
91
|
+
export function profileNotAllowedText(envId, name = null) {
|
|
92
|
+
return `${describe(envId, name)} is not on the owner's list of profiles agents may choose, so nothing was opened: not that profile, not the default one, not Chrome. Tell the user: to let agents work in it, switch it on in ${AGENT_PROFILES_WHERE}. A schedule, group, timer or launch the user sets up in SynaBun's own page can use any profile without that. Never switch to another profile or browser by yourself.`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The refusal as an Error (status 403, code MORELOGIN_PROFILE_NOT_ALLOWED) for the routes' catch blocks. */
|
|
96
|
+
export function profileNotAllowedError(envId, name = null, extra = '') {
|
|
97
|
+
return Object.assign(new Error(`${profileNotAllowedText(envId, name)}${extra ? ` ${extra}` : ''}`), { status: 403, code: PROFILE_NOT_ALLOWED, envId: cleanId(envId) });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Why a pin may not be used now, or null. A pin the owner's page set (`by: 'owner'`) is never limited; every other
|
|
102
|
+
* pin (a session's own choice, a dispatch's, an agent-made launch's, one whose origin is not recorded) needs its
|
|
103
|
+
* profile on the list at every use, not only when it was set.
|
|
104
|
+
* @param {{ envId: string, name?: string|null, by?: string }|null} pin
|
|
105
|
+
* @param {unknown} source the list, or a browser config that holds it
|
|
106
|
+
* @returns {{ status: 403, code: string, error: string, envId: string }|null}
|
|
107
|
+
*/
|
|
108
|
+
export function pinUseRefusal(pin, source) {
|
|
109
|
+
if (!pin || !pin.envId || pin.by === 'owner') return null;
|
|
110
|
+
if (agentProfileAllowed(source, pin.envId)) return null;
|
|
111
|
+
return {
|
|
112
|
+
status: 403, code: PROFILE_NOT_ALLOWED, envId: String(pin.envId),
|
|
113
|
+
error: `${profileNotAllowedText(pin.envId, pin.name)} This session is set to that profile (the owner took it off the list, or never put it there): its browser calls are refused until the profile is allowed again, or until the session goes back to the default profile itself (morelogin with action "use" and envId "default").`,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Whether a schedule's run in the profile of `holder` (the schedule itself, or its group) is the owner's own choice.
|
|
119
|
+
* It is only when the server saw the owner's page choose that profile (`holder.moreloginEnvBy === 'owner'`) AND nothing
|
|
120
|
+
* an agent wrote since decides what runs there: the schedule's task-defining fields (`schedule.taskBy`: its template,
|
|
121
|
+
* its overrides, its day themes, the group it is in) and its template (`template.editedBy`). Otherwise an agent could
|
|
122
|
+
* ride the owner's record into a profile off the list: change its task, or put a schedule of its own into the owner's
|
|
123
|
+
* group. A record with no marker (one saved before this rule) is not proven the owner's.
|
|
124
|
+
* @returns {{ by: 'owner' } | { by: 'agent', why: string, cure: string }}
|
|
125
|
+
*/
|
|
126
|
+
export function scheduleProfileAuthority({ schedule = null, holder = null, template = null, source = 'schedule' } = {}) {
|
|
127
|
+
const page = 'SynaBun\'s page (Automation Studio)';
|
|
128
|
+
if (!holder || holder.moreloginEnvBy !== 'owner') {
|
|
129
|
+
return {
|
|
130
|
+
by: 'agent',
|
|
131
|
+
why: holder?.moreloginEnvBy === 'agent'
|
|
132
|
+
? `the ${source}'s profile was chosen by an agent, not by the owner in ${page}`
|
|
133
|
+
: `SynaBun has no record that the owner chose the ${source}'s profile in ${page} (it was saved before that was recorded, or by an agent)`,
|
|
134
|
+
cure: `or open the ${source} in ${page}, pick the profile again and save`,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
if (schedule && schedule.taskBy === 'agent') {
|
|
138
|
+
return { by: 'agent', why: 'an agent created this schedule or last changed what it runs (its template, overrides, day themes or group)', cure: `or open the schedule in ${page}, check what it runs, pick the profile again and save` };
|
|
139
|
+
}
|
|
140
|
+
if (template && template.editedBy === 'agent') {
|
|
141
|
+
return { by: 'agent', why: 'an agent created or last changed the template this schedule runs', cure: `or open that template in ${page}, check its task and save it` };
|
|
142
|
+
}
|
|
143
|
+
return { by: 'owner' };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The message of a schedule run refused for a profile off the list (scheduleProfileAuthority said 'agent'). */
|
|
147
|
+
export function scheduleProfileRefusalText(envId, name, authority) {
|
|
148
|
+
return `${describe(envId, name)} is not on the owner's list of profiles agents may choose, and ${authority?.why || 'this run is not the owner\'s own choice'}. The run was not started: not in that profile, not in the default one, not in Chrome. To run it, switch the profile on in ${AGENT_PROFILES_WHERE}, ${authority?.cure || 'or save it again in SynaBun\'s page'}.`;
|
|
149
|
+
}
|