synabun 2.4.0 → 2.4.2
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 +47 -0
- package/README.md +1 -1
- package/browser-extension/content.js +73 -11
- package/browser-extension/engine.js +196 -15
- package/browser-extension/manifest.json +4 -2
- package/browser-extension/popup-strings.js +10 -4
- package/browser-extension/popup-view.js +1 -1
- package/browser-extension/popup.css +1 -0
- package/browser-extension/popup.html +4 -1
- package/browser-extension/popup.js +22 -10
- package/browser-extension/protocol.js +102 -11
- package/browser-extension/service-worker.js +20 -4
- package/browser-extension/tokens.css +1 -1
- package/docs/browser-extension-bridge.md +25 -5
- package/lib/data-home-files.js +47 -0
- package/lib/data-home-migration.js +34 -58
- package/lib/first-launch-protection.js +8 -2
- package/lib/update-snapshot.js +11 -4
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +25 -2
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +62 -17
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-bench.d.ts +22 -22
- package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
- package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-maintenance.js +34 -45
- package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
- package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
- package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-copy.js +467 -0
- package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.js +60 -0
- package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-retrieval.js +188 -40
- package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
- package/mcp-server/dist/services/memory-schema.d.ts +58 -2
- package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-schema.js +190 -13
- package/mcp-server/dist/services/memory-schema.js.map +1 -1
- package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
- package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-sessions.js +56 -20
- package/mcp-server/dist/services/memory-sessions.js.map +1 -1
- package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-verification.js +8 -5
- package/mcp-server/dist/services/memory-verification.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +6 -0
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +19 -2
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.js +145 -0
- package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
- package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
- package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
- package/mcp-server/dist/services/sqlite-write.js +94 -0
- package/mcp-server/dist/services/sqlite-write.js.map +1 -0
- package/mcp-server/dist/services/sqlite.d.ts +39 -0
- package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
- package/mcp-server/dist/services/sqlite.js +249 -8
- package/mcp-server/dist/services/sqlite.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
- package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
- package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe-config.js +32 -10
- package/mcp-server/dist/services/typesafe-config.js.map +1 -1
- package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe.js +9 -7
- package/mcp-server/dist/services/typesafe.js.map +1 -1
- package/mcp-server/dist/services/vector-cache.d.ts +32 -0
- package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
- package/mcp-server/dist/services/vector-cache.js +161 -8
- package/mcp-server/dist/services/vector-cache.js.map +1 -1
- package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
- package/mcp-server/dist/tools/agents.d.ts +13 -8
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +35 -15
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +10 -3
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
- package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
- package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
- package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
- package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-interact.js +6 -1
- package/mcp-server/dist/tools/browser-interact.js.map +1 -1
- package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +20 -2
- package/mcp-server/src/index.ts +59 -17
- package/mcp-server/src/services/memory-maintenance.ts +31 -28
- package/mcp-server/src/services/memory-migration-copy.ts +419 -0
- package/mcp-server/src/services/memory-migration-worker.ts +55 -0
- package/mcp-server/src/services/memory-retrieval.ts +173 -32
- package/mcp-server/src/services/memory-schema.ts +194 -12
- package/mcp-server/src/services/memory-sessions.ts +54 -21
- package/mcp-server/src/services/memory-verification.ts +7 -4
- package/mcp-server/src/services/neural-interface.ts +23 -2
- package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
- package/mcp-server/src/services/retrieval-reader.ts +131 -0
- package/mcp-server/src/services/sqlite-write.ts +60 -0
- package/mcp-server/src/services/sqlite.ts +246 -8
- package/mcp-server/src/services/typesafe-config.ts +25 -6
- package/mcp-server/src/services/typesafe.ts +9 -7
- package/mcp-server/src/services/vector-cache.ts +154 -9
- package/mcp-server/src/tools/agents.ts +33 -14
- package/mcp-server/src/tools/browser-advanced.ts +10 -3
- package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
- package/mcp-server/src/tools/browser-interact.ts +5 -1
- package/neural-interface/i18n/en.json +266 -2
- package/neural-interface/i18n/pt-BR.json +267 -3
- package/neural-interface/lib/agents/builtins.json +207 -0
- package/neural-interface/lib/agents/registry.js +60 -15
- package/neural-interface/lib/agents/resolve.js +69 -10
- package/neural-interface/lib/agents/split.js +32 -4
- package/neural-interface/lib/assistant-api.js +19 -8
- package/neural-interface/lib/assistant-brains/claude.js +2 -0
- package/neural-interface/lib/assistant-brains/opencode.js +60 -11
- package/neural-interface/lib/assistant-catalog.js +2 -2
- package/neural-interface/lib/assistant-config.js +0 -7
- package/neural-interface/lib/assistant-dispatch.js +384 -119
- package/neural-interface/lib/assistant-persona.js +17 -5
- package/neural-interface/lib/assistant-pricing.js +65 -14
- package/neural-interface/lib/assistant-router.js +181 -54
- package/neural-interface/lib/assistant-run-wait.js +45 -28
- package/neural-interface/lib/assistant-runtime.js +48 -34
- package/neural-interface/lib/backup-contents.js +158 -0
- package/neural-interface/lib/backup-crypto-io.js +330 -0
- package/neural-interface/lib/backup-crypto-worker.js +130 -0
- package/neural-interface/lib/backup-crypto.js +525 -0
- package/neural-interface/lib/backup-download.js +268 -0
- package/neural-interface/lib/backup-encryption.js +318 -0
- package/neural-interface/lib/backup-groups.js +287 -0
- package/neural-interface/lib/backup-restore-session.js +176 -0
- package/neural-interface/lib/backup-restore-stage.js +60 -0
- package/neural-interface/lib/backup-service.js +836 -322
- package/neural-interface/lib/backup-zip-reader.js +30 -18
- package/neural-interface/lib/backup-zip-writer.js +34 -10
- package/neural-interface/lib/browser-extension-adapter.js +109 -24
- package/neural-interface/lib/browser-extension-bridge.js +42 -8
- package/neural-interface/lib/claude-agent-bridge.js +1 -0
- package/neural-interface/lib/claude-session-cleanup.js +5 -1
- package/neural-interface/lib/cli-update-planner.js +105 -6
- package/neural-interface/lib/client-diagnostics.js +42 -0
- package/neural-interface/lib/confined-fs.js +7 -2
- package/neural-interface/lib/coordination/README.md +8 -2
- package/neural-interface/lib/coordination/contract.js +161 -0
- package/neural-interface/lib/coordination/database.js +999 -0
- package/neural-interface/lib/coordination/operations.js +436 -0
- package/neural-interface/lib/coordination/service.js +68 -537
- package/neural-interface/lib/coordination/storage-worker.js +101 -0
- package/neural-interface/lib/coordination/store.js +219 -1111
- package/neural-interface/lib/db.js +70 -32
- package/neural-interface/lib/health-count.js +37 -0
- package/neural-interface/lib/loop-stall.js +139 -0
- package/neural-interface/lib/maritaca/client.js +2 -2
- package/neural-interface/lib/maritaca/models.js +12 -17
- package/neural-interface/lib/maritaca/opencode.js +4 -2
- package/neural-interface/lib/memory-api.js +9 -1
- package/neural-interface/lib/memory-session-capture.js +42 -10
- package/neural-interface/lib/memory-store-gate.js +313 -0
- package/neural-interface/lib/memory-store-migrate.js +65 -0
- package/neural-interface/lib/memory-timers.js +7 -7
- package/neural-interface/lib/native-loop-providers.js +13 -16
- package/neural-interface/lib/native-loop-runtime.js +34 -14
- package/neural-interface/lib/opencode-build-preflight.js +30 -8
- package/neural-interface/lib/opencode-native-boundary.js +69 -8
- package/neural-interface/lib/opencode-provider-view.js +14 -3
- package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
- package/neural-interface/lib/opencode2-client.js +2 -1
- package/neural-interface/lib/peer-identity.js +13 -8
- package/neural-interface/lib/recall-impact.js +122 -0
- package/neural-interface/lib/scratch-evidence.js +420 -0
- package/neural-interface/lib/scratch-process-guard.js +139 -0
- package/neural-interface/lib/scratch-references.js +279 -0
- package/neural-interface/lib/scratch-retention-core.js +385 -0
- package/neural-interface/lib/scratch-retention-worker.js +37 -0
- package/neural-interface/lib/scratch-retention.js +151 -0
- package/neural-interface/lib/session-cache-builder.js +70 -44
- package/neural-interface/lib/session-cache-worker.js +157 -0
- package/neural-interface/lib/session-indexer.js +28 -21
- package/neural-interface/lib/session-search-index.js +85 -0
- package/neural-interface/lib/skills/creation.js +1 -1
- package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
- package/neural-interface/lib/style-guide/store.js +43 -3
- package/neural-interface/lib/system-restore.js +50 -0
- package/neural-interface/lib/teams/api.js +15 -6
- package/neural-interface/lib/teams/claims.js +67 -31
- package/neural-interface/lib/teams/index.js +7 -7
- package/neural-interface/lib/teams/integration.js +40 -40
- package/neural-interface/lib/teams/landing.js +6 -6
- package/neural-interface/lib/teams/recovery.js +24 -23
- package/neural-interface/lib/teams/scheduler.js +196 -97
- package/neural-interface/lib/teams/schema.js +1 -1
- package/neural-interface/lib/teams/state.js +14 -14
- package/neural-interface/lib/teams/worktrees.js +27 -27
- package/neural-interface/lib/whatsapp/bridge.js +2 -1
- package/neural-interface/lib/worker-confinement.js +47 -2
- package/neural-interface/lib/worker-mcp-channel.js +2 -0
- package/neural-interface/lib/worker-resume.js +5 -0
- package/neural-interface/lib/worker-stop.js +86 -0
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/index.html +260 -0
- package/neural-interface/public/offline.html +4 -3
- package/neural-interface/public/onboarding.html +259 -34
- package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
- package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
- package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
- package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
- package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
- package/neural-interface/public/shared/agy/agy-options.js +11 -0
- package/neural-interface/public/shared/agy/agy-panel.js +29 -10
- package/neural-interface/public/shared/agy/agy-styles.js +14 -12
- package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
- package/neural-interface/public/shared/api.js +3 -2
- package/neural-interface/public/shared/assistant/asst-api.js +3 -3
- package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
- package/neural-interface/public/shared/assistant/asst-control.js +2 -0
- package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
- package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
- package/neural-interface/public/shared/assistant/asst-render.js +106 -38
- package/neural-interface/public/shared/assistant/asst-route.js +102 -21
- package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
- package/neural-interface/public/shared/assistant/asst-state.js +11 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
- package/neural-interface/public/shared/assistant/route-identity.js +2 -1
- package/neural-interface/public/shared/cc-dropdown.js +21 -15
- package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
- package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
- package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
- package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
- package/neural-interface/public/shared/client-diagnostics.js +94 -0
- package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
- package/neural-interface/public/shared/cp/cp-styles.js +1 -1
- package/neural-interface/public/shared/effort-i18n.js +118 -0
- package/neural-interface/public/shared/html-shell.js +4 -51
- package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
- package/neural-interface/public/shared/memory-store-wait.js +52 -0
- package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
- package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
- package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
- package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
- package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
- package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
- package/neural-interface/public/shared/output-format.js +294 -0
- package/neural-interface/public/shared/owner-authority-view.js +4 -10
- package/neural-interface/public/shared/page-session.js +1 -1
- package/neural-interface/public/shared/provider-icons.js +6 -0
- package/neural-interface/public/shared/schedules-view.js +2 -1
- package/neural-interface/public/shared/server-presence.js +77 -0
- package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
- package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
- package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
- package/neural-interface/public/shared/settings/settings-ia.js +1 -1
- package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
- package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
- package/neural-interface/public/shared/start-bridge.js +2 -2
- package/neural-interface/public/shared/studio-attention.js +6 -0
- package/neural-interface/public/shared/styles.css +354 -438
- package/neural-interface/public/shared/transcript-rows.js +28 -3
- package/neural-interface/public/shared/tray-auto-close.js +18 -5
- package/neural-interface/public/shared/ui-agents.js +1 -2
- package/neural-interface/public/shared/ui-automation-studio.js +168 -108
- package/neural-interface/public/shared/ui-claude-panel.js +42 -65
- package/neural-interface/public/shared/ui-loading.js +185 -25
- package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
- package/neural-interface/public/shared/ui-navbar.js +2 -1
- package/neural-interface/public/shared/ui-output.js +533 -0
- package/neural-interface/public/shared/ui-owner-authority.js +48 -25
- package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
- package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
- package/neural-interface/public/shared/ui-sessions.js +2 -2
- package/neural-interface/public/shared/ui-settings-entry.js +18 -0
- package/neural-interface/public/shared/ui-settings.js +234 -67
- package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
- package/neural-interface/public/shared/ui-sync.js +1 -0
- package/neural-interface/public/shared/ui-tooltip.js +16 -0
- package/neural-interface/public/shared/ui-tutorial.js +5 -6
- package/neural-interface/public/shared/ui-worker-end.js +27 -8
- package/neural-interface/public/shared/worker-end.js +9 -4
- package/neural-interface/public/sw.js +4 -3
- package/neural-interface/public/variant/2d/main.js +5 -0
- package/neural-interface/public/variant/3d/app.js +10 -0
- package/neural-interface/public/variant/3d/main.js +17 -4
- package/neural-interface/scripts/scratch-retention.mjs +20 -0
- package/neural-interface/server.js +507 -160
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/scripts/restore-data-home-from-backup.mjs +175 -8
- package/setup.js +18 -4
|
@@ -4,10 +4,12 @@
|
|
|
4
4
|
* Shares the same memory.db file as the MCP server (WAL mode for concurrent access).
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
+
import { withMemoryWrite } from '../../mcp-server/dist/services/sqlite-write.js';
|
|
7
8
|
import { DatabaseSync } from 'node:sqlite';
|
|
8
9
|
import { resolve, dirname } from 'path';
|
|
9
10
|
import { existsSync, mkdirSync } from 'fs';
|
|
10
11
|
import { getDb as sharedDb, closeDatabase, memoryVectors, chunkVectors, searchMemories as sharedSearch, searchSessionChunks as sharedSessionSearch, updatePayload as sharedUpdate, deleteMemory as sharedDelete } from '../../mcp-server/dist/services/sqlite.js';
|
|
12
|
+
import { readRows } from '../../mcp-server/dist/services/retrieval-reader.js';
|
|
11
13
|
import { generateEmbedding, generateEmbeddingBatch, warmupEmbeddings, EMBEDDING_MODEL, EMBEDDING_DIMENSIONS } from '../../mcp-server/dist/services/local-embeddings.js';
|
|
12
14
|
export { memoryVectors, chunkVectors, warmupEmbeddings, EMBEDDING_MODEL };
|
|
13
15
|
export const EMBEDDING_DIMS = EMBEDDING_DIMENSIONS;
|
|
@@ -93,6 +95,10 @@ CREATE VIRTUAL TABLE IF NOT EXISTS session_fts USING fts5(
|
|
|
93
95
|
body,
|
|
94
96
|
tokenize = 'porter unicode61 remove_diacritics 2'
|
|
95
97
|
);
|
|
98
|
+
CREATE TABLE IF NOT EXISTS session_fts_lookup (
|
|
99
|
+
session_id TEXT NOT NULL, provider TEXT NOT NULL, docid INTEGER NOT NULL,
|
|
100
|
+
PRIMARY KEY (session_id, provider)
|
|
101
|
+
);
|
|
96
102
|
`;
|
|
97
103
|
|
|
98
104
|
export function closeDb() {
|
|
@@ -111,6 +117,17 @@ export function closeDb() {
|
|
|
111
117
|
|
|
112
118
|
// --- X/Twitter engagement ledger (cross-schedule dedup) ---
|
|
113
119
|
|
|
120
|
+
// The ledger's statements filter on `tags`, which no index covers, and in a memory's row the tags come after its
|
|
121
|
+
// vector and its content: every candidate row is read whole. On the owner's store (35k memories, 2.6 GB) one of them
|
|
122
|
+
// held the server's only thread for 2,059 ms (2026-11-21, logged under `timer:memory-maintenance`, the label that
|
|
123
|
+
// had marked last). They run on the retrieval reader's thread instead (mcp-server retrieval-reader.ts: a read-only
|
|
124
|
+
// connection of its own, which sees every committed write as the statement starts), so every reader below is async.
|
|
125
|
+
// The statement and its answer are unchanged; when the reader cannot serve it, it runs on this connection as before.
|
|
126
|
+
async function ledgerRows(sql, params = []) {
|
|
127
|
+
getDb(); // the store's refusal while it is closed or migrating, before anything is asked of the reader
|
|
128
|
+
return readRows(sql, params);
|
|
129
|
+
}
|
|
130
|
+
|
|
114
131
|
/**
|
|
115
132
|
* Read the shared engagement ledger written by the X automations and return a
|
|
116
133
|
* deduped recent set of engaged handles + tweet status IDs, plus the permanent
|
|
@@ -126,9 +143,9 @@ export function closeDb() {
|
|
|
126
143
|
* failure must not block a scheduled launch).
|
|
127
144
|
*
|
|
128
145
|
* @param {{account?:string|null, days?:number, limit?:number}} opts
|
|
129
|
-
* @returns {{handles:string[], statusIds:string[], blocked:string[], error?:string}}
|
|
146
|
+
* @returns {Promise<{handles:string[], statusIds:string[], blocked:string[], error?:string}>}
|
|
130
147
|
*/
|
|
131
|
-
export function getRecentXEngagements({ account = null, days = 7, limit = 200 } = {}) {
|
|
148
|
+
export async function getRecentXEngagements({ account = null, days = 7, limit = 200 } = {}) {
|
|
132
149
|
const acct = account ? String(account).trim().replace(/^@/, '').toLowerCase() : null;
|
|
133
150
|
const acctLike = acct ? `%"acct:${acct}"%` : null;
|
|
134
151
|
const collect = (rows, handleSet, statusSet) => {
|
|
@@ -149,7 +166,6 @@ export function getRecentXEngagements({ account = null, days = 7, limit = 200 }
|
|
|
149
166
|
}
|
|
150
167
|
};
|
|
151
168
|
try {
|
|
152
|
-
const db = getDb();
|
|
153
169
|
const since = new Date(Date.now() - days * 86400000).toISOString();
|
|
154
170
|
const handles = new Set();
|
|
155
171
|
const statusIds = new Set();
|
|
@@ -165,7 +181,7 @@ export function getRecentXEngagements({ account = null, days = 7, limit = 200 }
|
|
|
165
181
|
if (acctLike) { engSql += ` AND tags LIKE ?`; engParams.push(acctLike); }
|
|
166
182
|
engSql += ` ORDER BY created_at DESC LIMIT ?`;
|
|
167
183
|
engParams.push(limit);
|
|
168
|
-
collect(
|
|
184
|
+
collect(await ledgerRows(engSql, engParams), handles, statusIds);
|
|
169
185
|
|
|
170
186
|
// Permanent blocklist (accounts that blocked us) — no time window.
|
|
171
187
|
let blkSql = `SELECT tags FROM memories
|
|
@@ -175,7 +191,7 @@ export function getRecentXEngagements({ account = null, days = 7, limit = 200 }
|
|
|
175
191
|
if (acctLike) { blkSql += ` AND tags LIKE ?`; blkParams.push(acctLike); }
|
|
176
192
|
blkSql += ` ORDER BY created_at DESC LIMIT ?`;
|
|
177
193
|
blkParams.push(limit);
|
|
178
|
-
collect(
|
|
194
|
+
collect(await ledgerRows(blkSql, blkParams), blocked, null);
|
|
179
195
|
|
|
180
196
|
return { handles: [...handles], statusIds: [...statusIds], blocked: [...blocked] };
|
|
181
197
|
} catch (err) {
|
|
@@ -201,14 +217,13 @@ export const X_ACTION_TYPES = ['reply', 'like', 'quote', 'follow', 'repost'];
|
|
|
201
217
|
* every counter reads 0 so a broken ledger fails open rather than freezing all lanes.
|
|
202
218
|
*
|
|
203
219
|
* @param {{account?:string|null, sinceIso?:string, limit?:number}} opts
|
|
204
|
-
* @returns {{reply:number, like:number, quote:number, follow:number, repost:number, total:number, error?:string}}
|
|
220
|
+
* @returns {Promise<{reply:number, like:number, quote:number, follow:number, repost:number, total:number, error?:string}>}
|
|
205
221
|
*/
|
|
206
|
-
export function getXActionBudget({ account = null, sinceIso, limit = 500 } = {}) {
|
|
222
|
+
export async function getXActionBudget({ account = null, sinceIso, limit = 500 } = {}) {
|
|
207
223
|
const counts = Object.fromEntries(X_ACTION_TYPES.map(t => [t, 0]));
|
|
208
224
|
const empty = { ...counts, total: 0 };
|
|
209
225
|
const acct = account ? String(account).trim().replace(/^@/, '').toLowerCase() : null;
|
|
210
226
|
try {
|
|
211
|
-
const db = getDb();
|
|
212
227
|
const since = sinceIso || new Date(Date.now() - 86400000).toISOString();
|
|
213
228
|
let sql = `SELECT tags FROM memories
|
|
214
229
|
WHERE trashed_at IS NULL
|
|
@@ -221,7 +236,7 @@ export function getXActionBudget({ account = null, sinceIso, limit = 500 } = {})
|
|
|
221
236
|
params.push(limit);
|
|
222
237
|
|
|
223
238
|
let total = 0;
|
|
224
|
-
for (const row of
|
|
239
|
+
for (const row of await ledgerRows(sql, params)) {
|
|
225
240
|
let tags;
|
|
226
241
|
try { tags = JSON.parse(row.tags || '[]'); } catch { continue; }
|
|
227
242
|
if (!Array.isArray(tags)) continue;
|
|
@@ -264,20 +279,19 @@ export const X_DEFAULT_TIER = 1;
|
|
|
264
279
|
* the budget, never widen it.
|
|
265
280
|
*
|
|
266
281
|
* @param {{account?:string|null}} opts
|
|
267
|
-
* @returns {{tier:number, caps:{reply:number,like:number,quote:number,follow:number,repost:number}, source:'memory'|'default', error?:string}}
|
|
282
|
+
* @returns {Promise<{tier:number, caps:{reply:number,like:number,quote:number,follow:number,repost:number}, source:'memory'|'default', error?:string}>}
|
|
268
283
|
*/
|
|
269
|
-
export function getXEngagementTier({ account = null } = {}) {
|
|
284
|
+
export async function getXEngagementTier({ account = null } = {}) {
|
|
270
285
|
const fallback = { tier: X_DEFAULT_TIER, caps: X_ENGAGEMENT_TIERS[X_DEFAULT_TIER], source: 'default' };
|
|
271
286
|
const acct = account ? String(account).trim().replace(/^@/, '').toLowerCase() : null;
|
|
272
287
|
try {
|
|
273
|
-
const db = getDb();
|
|
274
288
|
let sql = `SELECT content FROM memories
|
|
275
289
|
WHERE trashed_at IS NULL
|
|
276
290
|
AND tags LIKE '%-x-engagement-caps"%'`;
|
|
277
291
|
const params = [];
|
|
278
292
|
if (acct) { sql += ` AND (tags LIKE ? OR tags NOT LIKE '%"acct:%')`; params.push(`%"acct:${acct}"%`); }
|
|
279
293
|
sql += ` ORDER BY created_at DESC LIMIT 1`;
|
|
280
|
-
const row =
|
|
294
|
+
const row = (await ledgerRows(sql, params))[0];
|
|
281
295
|
if (!row?.content) return fallback;
|
|
282
296
|
const m = /\btier\s*[:=]\s*(\d+)/i.exec(row.content);
|
|
283
297
|
const tier = m ? Number(m[1]) : NaN;
|
|
@@ -321,14 +335,13 @@ export const FB_DEFAULT_TIER = 1;
|
|
|
321
335
|
* every counter reads 0 so a broken ledger fails open rather than freezing all lanes.
|
|
322
336
|
*
|
|
323
337
|
* @param {{account?:string|null, sinceIso?:string, limit?:number}} opts
|
|
324
|
-
* @returns {{page_post:number, group_post:number, comment:number, invite:number, join:number, total:number, error?:string}}
|
|
338
|
+
* @returns {Promise<{page_post:number, group_post:number, comment:number, invite:number, join:number, total:number, error?:string}>}
|
|
325
339
|
*/
|
|
326
|
-
export function getFbActionBudget({ account = null, sinceIso, limit = 500 } = {}) {
|
|
340
|
+
export async function getFbActionBudget({ account = null, sinceIso, limit = 500 } = {}) {
|
|
327
341
|
const counts = Object.fromEntries(FB_ACTION_TYPES.map(t => [t, 0]));
|
|
328
342
|
const empty = { ...counts, total: 0 };
|
|
329
343
|
const acct = account ? String(account).trim().replace(/^@/, '').toLowerCase() : null;
|
|
330
344
|
try {
|
|
331
|
-
const db = getDb();
|
|
332
345
|
const since = sinceIso || new Date(Date.now() - 86400000).toISOString();
|
|
333
346
|
let sql = `SELECT tags FROM memories
|
|
334
347
|
WHERE trashed_at IS NULL
|
|
@@ -341,7 +354,7 @@ export function getFbActionBudget({ account = null, sinceIso, limit = 500 } = {}
|
|
|
341
354
|
params.push(limit);
|
|
342
355
|
|
|
343
356
|
let total = 0;
|
|
344
|
-
for (const row of
|
|
357
|
+
for (const row of await ledgerRows(sql, params)) {
|
|
345
358
|
let tags;
|
|
346
359
|
try { tags = JSON.parse(row.tags || '[]'); } catch { continue; }
|
|
347
360
|
if (!Array.isArray(tags)) continue;
|
|
@@ -367,8 +380,9 @@ export function getFbActionBudget({ account = null, sinceIso, limit = 500 } = {}
|
|
|
367
380
|
|
|
368
381
|
// group_post: the fb_groups posting ledger. Guarded — the table is owned by the
|
|
369
382
|
// MCP server's schema, so a brand-new database may not have it yet (reads 0).
|
|
383
|
+
// An index range of a small table: read on this connection, as before.
|
|
370
384
|
try {
|
|
371
|
-
const row =
|
|
385
|
+
const row = getDb().prepare(
|
|
372
386
|
`SELECT COUNT(*) AS n FROM fb_post_log
|
|
373
387
|
WHERE posted_at >= ?
|
|
374
388
|
AND status IN ('visible-post', 'pending-approval', 'posted', 'pending')`,
|
|
@@ -390,18 +404,17 @@ export function getFbActionBudget({ account = null, sinceIso, limit = 500 } = {}
|
|
|
390
404
|
* unparseable, or names a tier that does not exist — an unreadable ledger must narrow
|
|
391
405
|
* the budget, never widen it.
|
|
392
406
|
*
|
|
393
|
-
* @returns {{tier:number, caps:{page_post:number, group_post:number, comment:number, invite:number, join:number}, source:'memory'|'default', error?:string}}
|
|
407
|
+
* @returns {Promise<{tier:number, caps:{page_post:number, group_post:number, comment:number, invite:number, join:number}, source:'memory'|'default', error?:string}>}
|
|
394
408
|
*/
|
|
395
|
-
export function getFbEngagementTier() {
|
|
409
|
+
export async function getFbEngagementTier() {
|
|
396
410
|
const fallback = { tier: FB_DEFAULT_TIER, caps: FB_ENGAGEMENT_TIERS[FB_DEFAULT_TIER], source: 'default' };
|
|
397
411
|
try {
|
|
398
|
-
const
|
|
399
|
-
const row = db.prepare(
|
|
412
|
+
const row = (await ledgerRows(
|
|
400
413
|
`SELECT content FROM memories
|
|
401
414
|
WHERE trashed_at IS NULL
|
|
402
415
|
AND tags LIKE '%critpix-fb-engagement-caps%'
|
|
403
416
|
ORDER BY created_at DESC LIMIT 1`,
|
|
404
|
-
)
|
|
417
|
+
))[0];
|
|
405
418
|
if (!row?.content) return fallback;
|
|
406
419
|
const m = /\btier\s*[:=]\s*(\d+)/i.exec(row.content);
|
|
407
420
|
const tier = m ? Number(m[1]) : NaN;
|
|
@@ -429,6 +442,13 @@ export function setKvConfig(key, value) {
|
|
|
429
442
|
d.prepare('INSERT OR REPLACE INTO kv_config (key, value) VALUES (?, ?)').run(key, String(value));
|
|
430
443
|
}
|
|
431
444
|
|
|
445
|
+
export function saveEmbeddingMetadata() {
|
|
446
|
+
return withMemoryWrite(getDb(), () => {
|
|
447
|
+
setKvConfig('embedding_model', EMBEDDING_MODEL);
|
|
448
|
+
setKvConfig('embedding_dims', String(EMBEDDING_DIMS));
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
|
|
432
452
|
// --- Vector helpers ---
|
|
433
453
|
|
|
434
454
|
export function encodeVector(vector) {
|
|
@@ -807,16 +827,33 @@ export function upsertSessionCache(entry) {
|
|
|
807
827
|
);
|
|
808
828
|
}
|
|
809
829
|
|
|
810
|
-
export function upsertSessionFts(entry) {
|
|
830
|
+
export function upsertSessionFts(entry, cacheEntry = null) {
|
|
811
831
|
const d = getDb();
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
);
|
|
832
|
+
const key = [entry.session_id, entry.provider];
|
|
833
|
+
const known = d.prepare('SELECT docid FROM session_fts_lookup WHERE session_id=? AND provider=?');
|
|
834
|
+
const previous = known.get(...key);
|
|
835
|
+
// Older stores have no docid. Find any legacy duplicates before acquiring
|
|
836
|
+
// the writer lock: equality on these UNINDEXED FTS columns scans all text.
|
|
837
|
+
const valid = previous && d.prepare('SELECT 1 FROM session_fts WHERE rowid=? AND session_id=? AND provider=?')
|
|
838
|
+
.get(previous.docid, ...key);
|
|
839
|
+
const candidates = valid ? [previous] : d.prepare('SELECT rowid AS docid FROM session_fts WHERE session_id=? AND provider=?').all(...key);
|
|
840
|
+
d.exec('SAVEPOINT session_fts_write');
|
|
841
|
+
try {
|
|
842
|
+
// Acquire the write lock before checking for a concurrent upsert of this
|
|
843
|
+
// key. A cleared/reused FTS rowid must never delete another conversation.
|
|
844
|
+
d.prepare('INSERT OR IGNORE INTO session_fts_lookup VALUES(?,?,0)').run(...key);
|
|
845
|
+
const current = known.get(...key);
|
|
846
|
+
const remove = d.prepare('DELETE FROM session_fts WHERE rowid=? AND session_id=? AND provider=?');
|
|
847
|
+
for (const docid of new Set([current.docid, ...candidates.map(row => row.docid)])) remove.run(docid, ...key);
|
|
848
|
+
const added = d.prepare('INSERT INTO session_fts(session_id,provider,project,first_prompt,body) VALUES(?,?,?,?,?)')
|
|
849
|
+
.run(...key, entry.project || null, entry.first_prompt || '', entry.body || '');
|
|
850
|
+
d.prepare('UPDATE session_fts_lookup SET docid=? WHERE session_id=? AND provider=?').run(added.lastInsertRowid, ...key);
|
|
851
|
+
if (cacheEntry) upsertSessionCache(cacheEntry);
|
|
852
|
+
d.exec('RELEASE session_fts_write');
|
|
853
|
+
} catch (error) {
|
|
854
|
+
d.exec('ROLLBACK TO session_fts_write; RELEASE session_fts_write');
|
|
855
|
+
throw error;
|
|
856
|
+
}
|
|
820
857
|
}
|
|
821
858
|
|
|
822
859
|
export function getSessionCacheEntry(sessionId, provider) {
|
|
@@ -864,6 +901,7 @@ export function clearSessionCacheProvider(provider) {
|
|
|
864
901
|
d.exec('BEGIN IMMEDIATE');
|
|
865
902
|
try {
|
|
866
903
|
d.prepare('DELETE FROM session_fts WHERE provider = ?').run(normalized);
|
|
904
|
+
d.prepare('DELETE FROM session_fts_lookup WHERE provider = ?').run(normalized);
|
|
867
905
|
d.prepare('DELETE FROM session_cache WHERE provider = ?').run(normalized);
|
|
868
906
|
d.exec('COMMIT');
|
|
869
907
|
} catch (error) {
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// The memory count GET /api/health reports, kept for a few seconds.
|
|
2
|
+
//
|
|
3
|
+
// /api/health is the probe every open page sends every 3 s to tell a running server from a stopped one. It used to
|
|
4
|
+
// run a synchronous COUNT(*) on the memory database for each of them, on the server's one thread, so the probe was
|
|
5
|
+
// only as fast as the slowest statement in front of it. The answer to "is the server up" must not wait on the
|
|
6
|
+
// database: the count is read once per `ttlMs` and every probe in between gets the kept one.
|
|
7
|
+
//
|
|
8
|
+
// A read that throws is never kept: it throws to the caller (the route then says `ok: false, reason: 'db_error'`, as
|
|
9
|
+
// it always did) and the next request reads again.
|
|
10
|
+
//
|
|
11
|
+
// While the memory store is being upgraded (lib/memory-store-gate.js) the probe runs no statement: the count is null,
|
|
12
|
+
// and `storeState()` is what the route adds to say why. In the normal case it adds nothing.
|
|
13
|
+
|
|
14
|
+
export const HEALTH_COUNT_TTL_MS = 15_000;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param {{ read: () => number, ttlMs?: number, now?: () => number, store?: { reported: () => object | null } | null }} o
|
|
18
|
+
* @returns {(() => number | null) & { invalidate: () => void, storeState: () => object }}
|
|
19
|
+
*/
|
|
20
|
+
export function createHealthCount({ read, ttlMs = HEALTH_COUNT_TTL_MS, now = Date.now, store = null } = {}) {
|
|
21
|
+
if (typeof read !== 'function') throw new Error('read is required');
|
|
22
|
+
let kept = null;
|
|
23
|
+
const closed = () => { const state = store?.reported()?.state; return state === 'migrating' || state === 'failed'; };
|
|
24
|
+
const count = () => {
|
|
25
|
+
if (closed()) return null;
|
|
26
|
+
const at = now();
|
|
27
|
+
if (kept && at - kept.at < ttlMs && at >= kept.at) return kept.value;
|
|
28
|
+
let value;
|
|
29
|
+
// This very read may be the one that found the migration and started it.
|
|
30
|
+
try { value = read(); } catch (error) { if (closed()) return null; throw error; }
|
|
31
|
+
kept = { value, at };
|
|
32
|
+
return value;
|
|
33
|
+
};
|
|
34
|
+
count.invalidate = () => { kept = null; };
|
|
35
|
+
count.storeState = () => { const reported = store?.reported() ?? null; return reported ? { store: reported } : {}; };
|
|
36
|
+
return count;
|
|
37
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { monitorEventLoopDelay, performance } from 'node:perf_hooks';
|
|
2
|
+
import { DatabaseSync, StatementSync } from 'node:sqlite';
|
|
3
|
+
|
|
4
|
+
let activeMonitor;
|
|
5
|
+
|
|
6
|
+
// `last` alone named whatever marked most recently, and the 2 s capture and maintenance timers mark every second:
|
|
7
|
+
// a multi-second recall or write wait that started before them was reported under their names
|
|
8
|
+
// (docs/startup-freeze-and-agents-audit.md → Third pass). A stall line now also says what was still in flight
|
|
9
|
+
// (beginActivity) and the slowest synchronous SQLite statement of the stalled interval (instrumentSqlite).
|
|
10
|
+
const open = new Map();
|
|
11
|
+
let openSeq = 0;
|
|
12
|
+
let slowest = null;
|
|
13
|
+
|
|
14
|
+
export function markActivity(label) {
|
|
15
|
+
activeMonitor?.mark(label);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Work that spans several turns of the event loop (a recall, an MCP request, a session-cache job). Returns the
|
|
20
|
+
* function that ends it; a stall while it is open names it with its age. Also marks the label, like markActivity.
|
|
21
|
+
*/
|
|
22
|
+
export function beginActivity(label) {
|
|
23
|
+
markActivity(label);
|
|
24
|
+
const id = ++openSeq;
|
|
25
|
+
open.set(id, { label, at: performance.now() });
|
|
26
|
+
if (open.size > 200) open.delete(open.keys().next().value);
|
|
27
|
+
let ended = false;
|
|
28
|
+
return () => { if (!ended) { ended = true; open.delete(id); } };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Synchronous work of `ms` that just ended on this thread (the stall line names the longest of its interval). */
|
|
32
|
+
export function noteBlockingWork(label, ms) {
|
|
33
|
+
if (!slowest || ms > slowest.ms) slowest = { label, ms };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function inFlight(now) {
|
|
37
|
+
const list = [];
|
|
38
|
+
for (const { label, at } of open.values()) { list.push(`${label} ${((now - at) / 1000).toFixed(1)} s`); if (list.length === 3) break; }
|
|
39
|
+
return list.length ? `; in flight: ${list.join(', ')}${open.size > 3 ? ` +${open.size - 3}` : ''}` : '';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let sqliteInstrumented = false;
|
|
43
|
+
/**
|
|
44
|
+
* Time every synchronous SQLite call on this thread (node:sqlite statements and exec) and keep the slowest of each
|
|
45
|
+
* monitor interval at or over `thresholdMs`, with the start of its SQL. A few tens of nanoseconds per call.
|
|
46
|
+
* Off with SYNABUN_LOOP_STALL_SQL=off. Only for the thread that runs the monitor: workers have their own classes.
|
|
47
|
+
*/
|
|
48
|
+
export function instrumentSqlite({ thresholdMs = 50 } = {}) {
|
|
49
|
+
if (sqliteInstrumented || process.env.SYNABUN_LOOP_STALL_SQL === 'off') return false;
|
|
50
|
+
sqliteInstrumented = true;
|
|
51
|
+
const describe = (sql) => String(sql || '').replace(/\s+/g, ' ').trim().slice(0, 100).trim();
|
|
52
|
+
for (const method of ['all', 'get', 'run']) {
|
|
53
|
+
const original = StatementSync.prototype[method];
|
|
54
|
+
if (typeof original !== 'function') continue;
|
|
55
|
+
StatementSync.prototype[method] = function timedStatement(...args) {
|
|
56
|
+
const started = performance.now();
|
|
57
|
+
try { return original.apply(this, args); } finally {
|
|
58
|
+
const ms = performance.now() - started;
|
|
59
|
+
if (ms >= thresholdMs) noteBlockingWork(`sql ${method} ${describe(this.sourceSQL)}`, ms);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
const exec = DatabaseSync.prototype.exec;
|
|
64
|
+
DatabaseSync.prototype.exec = function timedExec(sql) {
|
|
65
|
+
const started = performance.now();
|
|
66
|
+
try { return exec.call(this, sql); } finally {
|
|
67
|
+
const ms = performance.now() - started;
|
|
68
|
+
if (ms >= thresholdMs) noteBlockingWork(`sql exec ${describe(sql)}`, ms);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// All durations use the monotonic clock. Wall time is only for matching the line
|
|
75
|
+
// to server logs. A due timer may mark new work before our delayed tick runs.
|
|
76
|
+
//
|
|
77
|
+
// One line per `rateLimitMs` used to be all there was: on 2026-11-21 the log showed stalls of 0.6 to 2.8 s, none long
|
|
78
|
+
// enough to fail two health probes, while pages were shown as offline. Whatever came inside the 30 s after a line was
|
|
79
|
+
// dropped, so a run of stalls back to back, or a longer one after a short one, left no trace. Now a stall of `longMs`
|
|
80
|
+
// or more is always written (one such stall alone fails a probe: public/shared/api.js fetchHealth, 3 s), and every
|
|
81
|
+
// line ends with what the limit kept back since the line before it: how many stalls, their sum and the worst.
|
|
82
|
+
export function startLoopStallMonitor({
|
|
83
|
+
thresholdMs = 500, intervalMs = 100, resolution = 20, rateLimitMs = 30_000, longMs = 3000,
|
|
84
|
+
log = console.warn,
|
|
85
|
+
} = {}) {
|
|
86
|
+
if (activeMonitor) return activeMonitor;
|
|
87
|
+
const delay = monitorEventLoopDelay({ resolution });
|
|
88
|
+
delay.enable();
|
|
89
|
+
let lastTick = performance.now();
|
|
90
|
+
let lastReport = -Infinity;
|
|
91
|
+
let activity = 'startup';
|
|
92
|
+
let held = { count: 0, ms: 0, worst: 0 };
|
|
93
|
+
// One stall is seen twice (by the mark that follows it and by the delayed tick): `seenUntil` counts it once.
|
|
94
|
+
let seenUntil = -Infinity;
|
|
95
|
+
|
|
96
|
+
function check(now, histogram = 0) {
|
|
97
|
+
const blocked = Math.max(now - lastTick - intervalMs, histogram);
|
|
98
|
+
if (blocked < thresholdMs) return;
|
|
99
|
+
const limited = now - lastReport < rateLimitMs;
|
|
100
|
+
if (limited && !(blocked >= longMs)) {
|
|
101
|
+
if (now - blocked >= seenUntil) {
|
|
102
|
+
held = { count: held.count + 1, ms: held.ms + blocked, worst: Math.max(held.worst, blocked) };
|
|
103
|
+
seenUntil = now;
|
|
104
|
+
}
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (limited && now - blocked < seenUntil) return; // this long stall already has its line
|
|
108
|
+
lastReport = now;
|
|
109
|
+
seenUntil = now;
|
|
110
|
+
const work = slowest && slowest.ms >= Math.min(blocked / 4, 100) ? `; longest sync: ${slowest.label} ${Math.round(slowest.ms)} ms` : '';
|
|
111
|
+
slowest = null;
|
|
112
|
+
const more = held.count
|
|
113
|
+
? `; ${held.count} more ${held.count === 1 ? 'stall' : 'stalls'} since the last line, ${Math.round(held.ms)} ms in all, worst ${Math.round(held.worst)} ms`
|
|
114
|
+
: '';
|
|
115
|
+
held = { count: 0, ms: 0, worst: 0 };
|
|
116
|
+
log(`[loop-stall] ${new Date().toISOString()} blocked ${Math.round(blocked)} ms (last: ${activity}${inFlight(now)}${work})${more}`);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const timer = setInterval(() => {
|
|
120
|
+
const now = performance.now();
|
|
121
|
+
check(now, delay.max / 1e6 - resolution);
|
|
122
|
+
lastTick = now;
|
|
123
|
+
slowest = null;
|
|
124
|
+
delay.reset();
|
|
125
|
+
}, intervalMs);
|
|
126
|
+
timer.unref();
|
|
127
|
+
activeMonitor = {
|
|
128
|
+
mark(label) {
|
|
129
|
+
check(performance.now());
|
|
130
|
+
activity = label;
|
|
131
|
+
},
|
|
132
|
+
stop() {
|
|
133
|
+
clearInterval(timer);
|
|
134
|
+
delay.disable();
|
|
135
|
+
if (activeMonitor === this) activeMonitor = undefined;
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
return activeMonitor;
|
|
139
|
+
}
|
|
@@ -280,7 +280,7 @@ export function createMaritacaClient({ fetchImpl = globalThis.fetch, baseUrl = M
|
|
|
280
280
|
|
|
281
281
|
/**
|
|
282
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
|
|
283
|
+
* one token of the cheapest active model (`S5-nano`) instead. Resolves { ok: true, via } or throws a maritacaError (KEY_REJECTED…).
|
|
284
284
|
*/
|
|
285
285
|
async function verifyKey({ key, signal = null } = {}) {
|
|
286
286
|
try {
|
|
@@ -291,7 +291,7 @@ export function createMaritacaClient({ fetchImpl = globalThis.fetch, baseUrl = M
|
|
|
291
291
|
} catch (error) {
|
|
292
292
|
if (error.code !== 'MODEL_UNKNOWN' && error.status !== 405) throw error;
|
|
293
293
|
}
|
|
294
|
-
const { response, done } = await request('/chat/completions', { key, method: 'POST', signal, body: { model: 'S5-
|
|
294
|
+
const { response, done } = await request('/chat/completions', { key, method: 'POST', signal, body: { model: 'S5-nano', messages: [{ role: 'user', content: 'oi' }], max_tokens: 1, stream: false } });
|
|
295
295
|
try { await response.body?.cancel(); } catch { /* ignore */ }
|
|
296
296
|
done();
|
|
297
297
|
return { ok: true, via: 'completion' };
|
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
// SynaBun — Maritaca AI: the Sabiá model table (pure)
|
|
3
3
|
// ═══════════════════════════════════════════
|
|
4
4
|
//
|
|
5
|
-
// What Maritaca's documentation says about each model,
|
|
6
|
-
// https://docs.maritaca.ai/pt/modelos (ids, aliases, context, max output, capabilities)
|
|
5
|
+
// What Maritaca's documentation says about each model, verified 2026-11-20:
|
|
6
|
+
// https://docs.maritaca.ai/pt/modelos (ids, aliases, context, max output, capabilities, discontinued)
|
|
7
7
|
// https://docs.maritaca.ai/pt/precos (BRL per million tokens: input, output, cached input)
|
|
8
8
|
// https://docs.maritaca.ai/pt/raciocinio (reasoning_effort: none · minimal = low · medium · high = xhigh = max; default xhigh)
|
|
9
|
+
// 2026-11-20: S5-free was discontinued on 2026-11-18 (replaced by S5) and moved to MARITACA_RETIRED. All 9 active
|
|
10
|
+
// models retain their BRL list prices.
|
|
9
11
|
// 2026-11-08: the S5 family's output went to 64K, S5 Nano (open weights, 256K context) joined the list, and the
|
|
10
12
|
// reasoning levels are offered as Off / Low / Medium / High (`high` is the API's `xhigh`, its default). The S5 rows'
|
|
11
13
|
// reasoning is encrypted (never streamed as text); only S5 Nano's arrives as text (`reasoningVisible`).
|
|
@@ -25,7 +27,7 @@
|
|
|
25
27
|
// what the API said and `known: false`; a model here the API no longer lists is kept, marked
|
|
26
28
|
// `listed: false`, so a saved default still resolves.
|
|
27
29
|
|
|
28
|
-
export const MARITACA_PRICING_VERIFIED = '2026-11-
|
|
30
|
+
export const MARITACA_PRICING_VERIFIED = '2026-11-20';
|
|
29
31
|
export const MARITACA_PRICING_SOURCE = 'https://docs.maritaca.ai/pt/precos';
|
|
30
32
|
export const MARITACA_MODELS_SOURCE = 'https://docs.maritaca.ai/pt/modelos';
|
|
31
33
|
export const MARITACA_DEFAULT_MODEL = 'sabiazinho-4';
|
|
@@ -43,7 +45,6 @@ export function normalizeMaritacaEffort(value) {
|
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
const price = (input, output, cacheRead) => Object.freeze({ input, output, cacheRead, unit: 'brl_per_mtok', basis: 'list' });
|
|
46
|
-
const FREE = Object.freeze({ input: 0, output: 0, cacheRead: 0, unit: 'brl_per_mtok', basis: 'free' });
|
|
47
48
|
const ONE_M = 1_000_000;
|
|
48
49
|
const K128 = 128_000;
|
|
49
50
|
const K256 = 256_000;
|
|
@@ -63,14 +64,6 @@ export const MARITACA_MODELS = Object.freeze([
|
|
|
63
64
|
toolcall: true, vision: false, price: price(0.65, 3.25, 0.065), region: 'br-sp',
|
|
64
65
|
description: 'S5 with inference 100% in Brazil (data residency), 30% over S5.',
|
|
65
66
|
},
|
|
66
|
-
{
|
|
67
|
-
id: 'S5-free', label: 'S5 (free)', family: 's5', aliases: ['s5-free'],
|
|
68
|
-
tier: 'large', contextWindow: ONE_M, maxOutput: K64, reasoning: true, fixedSampling: true, efforts: MARITACA_REASONING_EFFORTS, defaultEffort: 'high',
|
|
69
|
-
toolcall: false, vision: false, batch: false, flex: false, price: FREE, region: 'global', free: true,
|
|
70
|
-
// docs → Rate Limits: the free model has fixed limits whatever the plan (no batch / flex rates either).
|
|
71
|
-
rateLimit: Object.freeze({ requestsPerMinute: 60, tokensPerMinuteIn: 256_000, tokensPerMinuteOut: 256_000 }),
|
|
72
|
-
description: 'S5 free for a limited time (launch offer): text only, no tool calling, no batch or flex; fixed 60 requests and 256k tokens per minute in and out.',
|
|
73
|
-
},
|
|
74
67
|
{
|
|
75
68
|
id: 'S5-nano', label: 'Sabiá 5 Nano (S5 Nano)', family: 's5', aliases: ['s5-nano'],
|
|
76
69
|
tier: 'small', contextWindow: K256, maxOutput: 32_000, reasoning: true, fixedSampling: true, efforts: MARITACA_REASONING_EFFORTS, defaultEffort: 'high',
|
|
@@ -118,11 +111,13 @@ export const MARITACA_MODELS = Object.freeze([
|
|
|
118
111
|
]);
|
|
119
112
|
|
|
120
113
|
/**
|
|
121
|
-
* Models Maritaca retired (docs → Modelos descontinuados
|
|
122
|
-
* catalog). They are not in the table; a saved default or a stored conversation that still
|
|
123
|
-
* the nearest current model (sabia-3 → sabia-4, sabiazinho-3 → sabiazinho-4,
|
|
114
|
+
* Models Maritaca retired (docs → Modelos descontinuados: S5-free ended 2026-11-18, sabia-3 and sabiazinho-3
|
|
115
|
+
* are gone from the catalog). They are not in the table; a saved default or a stored conversation that still
|
|
116
|
+
* names one resolves to the nearest current model (S5-free → S5, sabia-3 → sabia-4, sabiazinho-3 → sabiazinho-4,
|
|
117
|
+
* Sabiá 2 → sabiazinho-4) and never fails.
|
|
124
118
|
*/
|
|
125
119
|
export const MARITACA_RETIRED = Object.freeze({
|
|
120
|
+
's5-free': 'S5',
|
|
126
121
|
'sabia-2-medium': 'sabiazinho-4',
|
|
127
122
|
'sabia-2-small': 'sabiazinho-4',
|
|
128
123
|
'sabia-3': 'sabia-4',
|
|
@@ -145,7 +140,7 @@ export function findMaritacaModel(id) {
|
|
|
145
140
|
const direct = byKey.get(key);
|
|
146
141
|
if (direct) return direct;
|
|
147
142
|
const replacement = MARITACA_RETIRED[key];
|
|
148
|
-
return replacement ? byKey.get(replacement) || null : null;
|
|
143
|
+
return replacement ? byKey.get(replacement.toLowerCase()) || null : null;
|
|
149
144
|
}
|
|
150
145
|
|
|
151
146
|
/** The canonical id of a model spelling (its table id), or the spelling itself trimmed when unknown. */
|
|
@@ -173,7 +168,7 @@ export function maritacaModelRows() {
|
|
|
173
168
|
contextWindow: m.contextWindow, maxOutput: m.maxOutput, reasoning: m.reasoning, fixedSampling: m.fixedSampling === true,
|
|
174
169
|
efforts: [...m.efforts], defaultEffort: m.defaultEffort, toolcall: m.toolcall, vision: m.vision,
|
|
175
170
|
price: { ...m.price }, region: m.region, free: m.free === true, description: m.description,
|
|
176
|
-
// Whether the reasoning arrives as text: S5 Nano and Sabiá 4 Thinking yes; S5
|
|
171
|
+
// Whether the reasoning arrives as text: S5 Nano and Sabiá 4 Thinking yes; S5 and S5 BR-SP keep it encrypted.
|
|
177
172
|
reasoningVisible: m.reasoningVisible === true || (m.reasoning === true && m.family !== 's5'),
|
|
178
173
|
batch: m.batch !== false, flex: m.flex !== false, rateLimit: m.rateLimit ? { ...m.rateLimit } : null,
|
|
179
174
|
isDefault: m.id === MARITACA_DEFAULT_MODEL, known: true, listed: true,
|
|
@@ -40,7 +40,8 @@ export function maritacaApiKeyReference({ source, keyPath } = {}) {
|
|
|
40
40
|
/**
|
|
41
41
|
* OpenCode's `models` map of the table: name, limits and whether the model takes tools (prices are in BRL and would be
|
|
42
42
|
* read as USD). OpenCode 2's Config.Model says tools under `capabilities.tools` (default true when absent), so a row
|
|
43
|
-
* with `toolcall: false`
|
|
43
|
+
* with `toolcall: false` is written `capabilities: { tools: false }` and OpenCode never sends it tools (no current model
|
|
44
|
+
* has one since S5-free, the last, was retired on 2026-11-18).
|
|
44
45
|
*/
|
|
45
46
|
export function maritacaOpencodeModels(models = MARITACA_MODELS) {
|
|
46
47
|
const out = {};
|
|
@@ -104,7 +105,8 @@ export function maritacaOpencodeState({ config, keyStatus, keyPath, models = MAR
|
|
|
104
105
|
const currentIds = Object.keys(entry?.models && typeof entry.models === 'object' ? entry.models : {}).sort();
|
|
105
106
|
const expectedModels = maritacaOpencodeModels(models);
|
|
106
107
|
const expectedIds = Object.keys(expectedModels).sort();
|
|
107
|
-
// A block written before the tools flag (or edited by hand) is out of sync: OpenCode would send
|
|
108
|
+
// A block written before the tools flag (or edited by hand) is out of sync: OpenCode would send tools to a model
|
|
109
|
+
// that takes none (S5-free did until its retirement on 2026-11-18; a re-sync also drops its entry).
|
|
108
110
|
const currentTools = toolFlags(entry?.models);
|
|
109
111
|
const expectedTools = toolFlags(expectedModels);
|
|
110
112
|
const toolsInSync = expectedIds.every((id) => currentTools[id] === expectedTools[id]);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Router } from 'express';
|
|
2
2
|
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
|
+
import { beginActivity } from './loop-stall.js';
|
|
4
5
|
import { retrieveMemory, compactRecall, excerpt, estimateTokens } from '../../mcp-server/dist/services/memory-retrieval.js';
|
|
5
6
|
import { getDb, updatePayload, softDeleteMemory } from '../../mcp-server/dist/services/sqlite.js';
|
|
6
7
|
import { maintenanceStatus, pauseMaintenance, memoryHistory, memoryRevision, undoRevision, setRelation } from '../../mcp-server/dist/services/memory-maintenance.js';
|
|
@@ -329,7 +330,14 @@ async function planConflict(text, body, ctx, retrieve) {
|
|
|
329
330
|
// user-context engine) keeps those categories out of the rendered block: they
|
|
330
331
|
// are searched and ranked with the rest, then returned apart as `diverted`
|
|
331
332
|
// (never rendered, never committed here). The HTTP route never passes options.
|
|
332
|
-
export async function hookRecall(body = {}, retrieve = retrieveMemory,
|
|
333
|
+
export async function hookRecall(body = {}, retrieve = retrieveMemory, options = {}) {
|
|
334
|
+
// In flight until it answers: a stall during a recall names it however many timers mark in between.
|
|
335
|
+
const endActivity = beginActivity(options?.origin === 'assistant' ? 'memory:assistant-recall' : 'memory:hook-recall');
|
|
336
|
+
try { return await recallForHook(body, retrieve, options); }
|
|
337
|
+
finally { endActivity(); }
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
async function recallForHook(body, retrieve, { origin = null, defer = false, divert = null } = {}) {
|
|
333
341
|
const opts=input(body);
|
|
334
342
|
const divertSet=Array.isArray(divert) && divert.length ? new Set(divert.map(String)) : null;
|
|
335
343
|
const isDiverted=r=>!!divertSet && divertSet.has(String(r.category));
|