synabun 2.4.1 → 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.
Files changed (295) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +56 -14
  4. package/browser-extension/engine.js +158 -8
  5. package/browser-extension/manifest.json +3 -1
  6. package/browser-extension/protocol.js +91 -6
  7. package/browser-extension/service-worker.js +13 -5
  8. package/browser-extension/tokens.css +1 -1
  9. package/docs/browser-extension-bridge.md +24 -4
  10. package/lib/data-home-files.js +4 -2
  11. package/lib/first-launch-protection.js +8 -2
  12. package/lib/update-snapshot.js +11 -4
  13. package/mcp-server/dist/http.d.ts.map +1 -1
  14. package/mcp-server/dist/http.js +25 -2
  15. package/mcp-server/dist/http.js.map +1 -1
  16. package/mcp-server/dist/index.d.ts.map +1 -1
  17. package/mcp-server/dist/index.js +62 -17
  18. package/mcp-server/dist/index.js.map +1 -1
  19. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  20. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  21. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  22. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  23. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  24. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  25. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  26. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  27. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  28. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  29. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  30. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  31. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  32. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  33. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  34. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  35. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  36. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  37. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  38. package/mcp-server/dist/services/memory-schema.js +190 -13
  39. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  40. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  41. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  42. package/mcp-server/dist/services/memory-sessions.js +56 -20
  43. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  44. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  45. package/mcp-server/dist/services/memory-verification.js +8 -5
  46. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  47. package/mcp-server/dist/services/neural-interface.d.ts +5 -0
  48. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  49. package/mcp-server/dist/services/neural-interface.js +19 -2
  50. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  51. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  52. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  53. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  54. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  55. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  56. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  57. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  58. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  59. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  60. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  61. package/mcp-server/dist/services/sqlite-write.js +94 -0
  62. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  63. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  64. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  65. package/mcp-server/dist/services/sqlite.js +249 -8
  66. package/mcp-server/dist/services/sqlite.js.map +1 -1
  67. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  68. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  69. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  70. package/mcp-server/dist/services/typesafe-config.js +32 -10
  71. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  72. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  73. package/mcp-server/dist/services/typesafe.js +9 -7
  74. package/mcp-server/dist/services/typesafe.js.map +1 -1
  75. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  76. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  77. package/mcp-server/dist/services/vector-cache.js +161 -8
  78. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  79. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  80. package/mcp-server/dist/tools/agents.d.ts +11 -7
  81. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  82. package/mcp-server/dist/tools/agents.js +27 -9
  83. package/mcp-server/dist/tools/agents.js.map +1 -1
  84. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  85. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  86. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  87. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  88. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  89. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  90. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  91. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  92. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  93. package/mcp-server/dist/tools/browser-interact.js +6 -1
  94. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  95. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  96. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  97. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  98. package/mcp-server/package-lock.json +2 -2
  99. package/mcp-server/package.json +1 -1
  100. package/mcp-server/src/http.ts +20 -2
  101. package/mcp-server/src/index.ts +59 -17
  102. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  103. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  104. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  105. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  106. package/mcp-server/src/services/memory-schema.ts +194 -12
  107. package/mcp-server/src/services/memory-sessions.ts +54 -21
  108. package/mcp-server/src/services/memory-verification.ts +7 -4
  109. package/mcp-server/src/services/neural-interface.ts +22 -2
  110. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  111. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  112. package/mcp-server/src/services/sqlite-write.ts +60 -0
  113. package/mcp-server/src/services/sqlite.ts +246 -8
  114. package/mcp-server/src/services/typesafe-config.ts +25 -6
  115. package/mcp-server/src/services/typesafe.ts +9 -7
  116. package/mcp-server/src/services/vector-cache.ts +154 -9
  117. package/mcp-server/src/tools/agents.ts +26 -9
  118. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  119. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  120. package/mcp-server/src/tools/browser-interact.ts +5 -1
  121. package/neural-interface/i18n/en.json +263 -1
  122. package/neural-interface/i18n/pt-BR.json +264 -2
  123. package/neural-interface/lib/agents/split.js +32 -4
  124. package/neural-interface/lib/assistant-api.js +19 -8
  125. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  126. package/neural-interface/lib/assistant-catalog.js +2 -2
  127. package/neural-interface/lib/assistant-config.js +0 -7
  128. package/neural-interface/lib/assistant-dispatch.js +257 -95
  129. package/neural-interface/lib/assistant-persona.js +16 -4
  130. package/neural-interface/lib/assistant-pricing.js +65 -14
  131. package/neural-interface/lib/assistant-router.js +131 -47
  132. package/neural-interface/lib/assistant-run-wait.js +45 -28
  133. package/neural-interface/lib/assistant-runtime.js +39 -33
  134. package/neural-interface/lib/backup-contents.js +158 -0
  135. package/neural-interface/lib/backup-crypto-io.js +330 -0
  136. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  137. package/neural-interface/lib/backup-crypto.js +525 -0
  138. package/neural-interface/lib/backup-download.js +268 -0
  139. package/neural-interface/lib/backup-encryption.js +318 -0
  140. package/neural-interface/lib/backup-groups.js +287 -0
  141. package/neural-interface/lib/backup-restore-session.js +176 -0
  142. package/neural-interface/lib/backup-restore-stage.js +60 -0
  143. package/neural-interface/lib/backup-service.js +788 -233
  144. package/neural-interface/lib/backup-zip-reader.js +30 -18
  145. package/neural-interface/lib/backup-zip-writer.js +34 -10
  146. package/neural-interface/lib/browser-extension-adapter.js +89 -13
  147. package/neural-interface/lib/browser-extension-bridge.js +18 -7
  148. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  149. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  150. package/neural-interface/lib/cli-update-planner.js +105 -6
  151. package/neural-interface/lib/client-diagnostics.js +42 -0
  152. package/neural-interface/lib/confined-fs.js +7 -2
  153. package/neural-interface/lib/coordination/README.md +8 -2
  154. package/neural-interface/lib/coordination/contract.js +161 -0
  155. package/neural-interface/lib/coordination/database.js +999 -0
  156. package/neural-interface/lib/coordination/operations.js +436 -0
  157. package/neural-interface/lib/coordination/service.js +68 -537
  158. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  159. package/neural-interface/lib/coordination/store.js +219 -1111
  160. package/neural-interface/lib/db.js +70 -32
  161. package/neural-interface/lib/health-count.js +37 -0
  162. package/neural-interface/lib/loop-stall.js +139 -0
  163. package/neural-interface/lib/maritaca/client.js +2 -2
  164. package/neural-interface/lib/maritaca/models.js +12 -17
  165. package/neural-interface/lib/maritaca/opencode.js +4 -2
  166. package/neural-interface/lib/memory-api.js +9 -1
  167. package/neural-interface/lib/memory-session-capture.js +42 -10
  168. package/neural-interface/lib/memory-store-gate.js +313 -0
  169. package/neural-interface/lib/memory-store-migrate.js +65 -0
  170. package/neural-interface/lib/memory-timers.js +7 -7
  171. package/neural-interface/lib/native-loop-providers.js +13 -16
  172. package/neural-interface/lib/native-loop-runtime.js +28 -7
  173. package/neural-interface/lib/opencode-build-preflight.js +18 -1
  174. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  175. package/neural-interface/lib/opencode-provider-view.js +14 -3
  176. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  177. package/neural-interface/lib/opencode2-client.js +2 -1
  178. package/neural-interface/lib/recall-impact.js +122 -0
  179. package/neural-interface/lib/scratch-evidence.js +420 -0
  180. package/neural-interface/lib/scratch-process-guard.js +139 -0
  181. package/neural-interface/lib/scratch-references.js +279 -0
  182. package/neural-interface/lib/scratch-retention-core.js +385 -0
  183. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  184. package/neural-interface/lib/scratch-retention.js +151 -0
  185. package/neural-interface/lib/session-cache-builder.js +31 -43
  186. package/neural-interface/lib/session-cache-worker.js +157 -0
  187. package/neural-interface/lib/session-indexer.js +28 -21
  188. package/neural-interface/lib/session-search-index.js +85 -0
  189. package/neural-interface/lib/skills/creation.js +1 -1
  190. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  191. package/neural-interface/lib/style-guide/store.js +43 -3
  192. package/neural-interface/lib/system-restore.js +50 -0
  193. package/neural-interface/lib/teams/api.js +15 -6
  194. package/neural-interface/lib/teams/claims.js +67 -31
  195. package/neural-interface/lib/teams/index.js +7 -7
  196. package/neural-interface/lib/teams/integration.js +40 -40
  197. package/neural-interface/lib/teams/landing.js +6 -6
  198. package/neural-interface/lib/teams/recovery.js +24 -23
  199. package/neural-interface/lib/teams/scheduler.js +194 -95
  200. package/neural-interface/lib/teams/state.js +14 -14
  201. package/neural-interface/lib/teams/worktrees.js +27 -27
  202. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  203. package/neural-interface/lib/worker-confinement.js +47 -2
  204. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  205. package/neural-interface/lib/worker-resume.js +5 -0
  206. package/neural-interface/lib/worker-stop.js +86 -0
  207. package/neural-interface/package-lock.json +2 -2
  208. package/neural-interface/package.json +1 -1
  209. package/neural-interface/public/index.html +233 -24
  210. package/neural-interface/public/onboarding.html +259 -34
  211. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  212. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  213. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  214. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  215. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  216. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  217. package/neural-interface/public/shared/api.js +1 -1
  218. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  219. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  220. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  221. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  222. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  223. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  224. package/neural-interface/public/shared/assistant/asst-render.js +105 -38
  225. package/neural-interface/public/shared/assistant/asst-route.js +100 -21
  226. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  227. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  228. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  229. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  230. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  231. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  232. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  233. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  234. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  235. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  236. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  237. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  238. package/neural-interface/public/shared/effort-i18n.js +118 -0
  239. package/neural-interface/public/shared/html-shell.js +4 -52
  240. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  241. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  242. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  243. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  244. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  245. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  246. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  247. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  248. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  249. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  250. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  251. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  252. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  253. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  254. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  255. package/neural-interface/public/shared/output-format.js +294 -0
  256. package/neural-interface/public/shared/provider-icons.js +6 -0
  257. package/neural-interface/public/shared/schedules-view.js +2 -1
  258. package/neural-interface/public/shared/server-presence.js +77 -0
  259. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  260. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  261. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  262. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  263. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  264. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  265. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  266. package/neural-interface/public/shared/studio-attention.js +6 -0
  267. package/neural-interface/public/shared/styles.css +341 -437
  268. package/neural-interface/public/shared/transcript-rows.js +28 -3
  269. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  270. package/neural-interface/public/shared/ui-agents.js +1 -2
  271. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  272. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  273. package/neural-interface/public/shared/ui-loading.js +124 -17
  274. package/neural-interface/public/shared/ui-native-loop-router.js +10 -0
  275. package/neural-interface/public/shared/ui-navbar.js +2 -1
  276. package/neural-interface/public/shared/ui-output.js +533 -0
  277. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  278. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  279. package/neural-interface/public/shared/ui-sessions.js +2 -2
  280. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  281. package/neural-interface/public/shared/ui-settings.js +224 -65
  282. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  283. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  284. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  285. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  286. package/neural-interface/public/shared/worker-end.js +9 -4
  287. package/neural-interface/public/variant/2d/main.js +5 -0
  288. package/neural-interface/public/variant/3d/app.js +10 -0
  289. package/neural-interface/public/variant/3d/main.js +5 -1
  290. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  291. package/neural-interface/server.js +477 -139
  292. package/npm-shrinkwrap.json +2 -2
  293. package/package.json +1 -1
  294. package/scripts/restore-data-home-from-backup.mjs +175 -8
  295. 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(db.prepare(engSql).all(...engParams), handles, statusIds);
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(db.prepare(blkSql).all(...blkParams), blocked, null);
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 db.prepare(sql).all(...params)) {
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 = db.prepare(sql).all(...params)[0];
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 db.prepare(sql).all(...params)) {
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 = db.prepare(
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 db = getDb();
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
- ).all()[0];
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
- d.prepare('DELETE FROM session_fts WHERE session_id = ? AND provider = ?')
813
- .run(entry.session_id, entry.provider);
814
- d.prepare(`INSERT INTO session_fts
815
- (session_id, provider, project, first_prompt, body)
816
- VALUES (?, ?, ?, ?, ?)`).run(
817
- entry.session_id, entry.provider, entry.project || null,
818
- entry.first_prompt || '', entry.body || '',
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 free model instead. Resolves { ok: true, via } or throws a maritacaError (KEY_REJECTED…).
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-free', messages: [{ role: 'user', content: 'oi' }], max_tokens: 1, stream: false } });
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, read 2026-11-06 and again 2026-11-08:
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-08';
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, 2026-11-06: sabia-3 and sabiazinho-3 are gone from the
122
- * catalog). They are not in the table; a saved default or a stored conversation that still names one resolves to
123
- * the nearest current model (sabia-3 → sabia-4, sabiazinho-3 → sabiazinho-4, Sabiá 2 → sabiazinho-4) and never fails.
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, S5 BR-SP and S5 Free keep it encrypted.
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` (S5-free) is written `capabilities: { tools: false }` and OpenCode never sends it tools.
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 S5-free tools.
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, { origin = null, defer = false, divert = null } = {}) {
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));