@aislop-inc/opencode-mem 0.0.0-stage → 2.41.1

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 (357) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +811 -2
  3. package/dist/config.d.ts +577 -0
  4. package/dist/config.d.ts.map +1 -0
  5. package/dist/config.js +1141 -0
  6. package/dist/index.d.ts +50 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +1268 -0
  9. package/dist/plugin.d.ts +10 -0
  10. package/dist/plugin.d.ts.map +1 -0
  11. package/dist/plugin.js +10 -0
  12. package/dist/services/ai/ai-provider-factory.d.ts +8 -0
  13. package/dist/services/ai/ai-provider-factory.d.ts.map +1 -0
  14. package/dist/services/ai/ai-provider-factory.js +61 -0
  15. package/dist/services/ai/api-key-placeholder.d.ts +2 -0
  16. package/dist/services/ai/api-key-placeholder.d.ts.map +1 -0
  17. package/dist/services/ai/api-key-placeholder.js +14 -0
  18. package/dist/services/ai/internal-capture-sessions.d.ts +7 -0
  19. package/dist/services/ai/internal-capture-sessions.d.ts.map +1 -0
  20. package/dist/services/ai/internal-capture-sessions.js +31 -0
  21. package/dist/services/ai/opencode-diagnostics.d.ts +8 -0
  22. package/dist/services/ai/opencode-diagnostics.d.ts.map +1 -0
  23. package/dist/services/ai/opencode-diagnostics.js +36 -0
  24. package/dist/services/ai/opencode-host-config.d.ts +11 -0
  25. package/dist/services/ai/opencode-host-config.d.ts.map +1 -0
  26. package/dist/services/ai/opencode-host-config.js +51 -0
  27. package/dist/services/ai/opencode-provider-loader.d.ts +4 -0
  28. package/dist/services/ai/opencode-provider-loader.d.ts.map +1 -0
  29. package/dist/services/ai/opencode-provider-loader.js +4 -0
  30. package/dist/services/ai/opencode-provider.d.ts +154 -0
  31. package/dist/services/ai/opencode-provider.d.ts.map +1 -0
  32. package/dist/services/ai/opencode-provider.js +731 -0
  33. package/dist/services/ai/opencode-sdk-client.d.ts +7 -0
  34. package/dist/services/ai/opencode-sdk-client.d.ts.map +1 -0
  35. package/dist/services/ai/opencode-sdk-client.js +38 -0
  36. package/dist/services/ai/profile-llm-client.d.ts +3 -0
  37. package/dist/services/ai/profile-llm-client.d.ts.map +1 -0
  38. package/dist/services/ai/profile-llm-client.js +29 -0
  39. package/dist/services/ai/provider-config.d.ts +19 -0
  40. package/dist/services/ai/provider-config.d.ts.map +1 -0
  41. package/dist/services/ai/provider-config.js +36 -0
  42. package/dist/services/ai/providers/anthropic-messages.d.ts +35 -0
  43. package/dist/services/ai/providers/anthropic-messages.d.ts.map +1 -0
  44. package/dist/services/ai/providers/anthropic-messages.js +220 -0
  45. package/dist/services/ai/providers/api-route.d.ts +49 -0
  46. package/dist/services/ai/providers/api-route.d.ts.map +1 -0
  47. package/dist/services/ai/providers/api-route.js +57 -0
  48. package/dist/services/ai/providers/atlas-cloud.d.ts +51 -0
  49. package/dist/services/ai/providers/atlas-cloud.d.ts.map +1 -0
  50. package/dist/services/ai/providers/atlas-cloud.js +59 -0
  51. package/dist/services/ai/providers/base-provider.d.ts +33 -0
  52. package/dist/services/ai/providers/base-provider.d.ts.map +1 -0
  53. package/dist/services/ai/providers/base-provider.js +24 -0
  54. package/dist/services/ai/providers/cheaper-inference.d.ts +50 -0
  55. package/dist/services/ai/providers/cheaper-inference.d.ts.map +1 -0
  56. package/dist/services/ai/providers/cheaper-inference.js +58 -0
  57. package/dist/services/ai/providers/cloudgpu.d.ts +52 -0
  58. package/dist/services/ai/providers/cloudgpu.d.ts.map +1 -0
  59. package/dist/services/ai/providers/cloudgpu.js +60 -0
  60. package/dist/services/ai/providers/google-gemini.d.ts +16 -0
  61. package/dist/services/ai/providers/google-gemini.d.ts.map +1 -0
  62. package/dist/services/ai/providers/google-gemini.js +228 -0
  63. package/dist/services/ai/providers/minimax.d.ts +38 -0
  64. package/dist/services/ai/providers/minimax.d.ts.map +1 -0
  65. package/dist/services/ai/providers/minimax.js +57 -0
  66. package/dist/services/ai/providers/openai-chat-completion.d.ts +30 -0
  67. package/dist/services/ai/providers/openai-chat-completion.d.ts.map +1 -0
  68. package/dist/services/ai/providers/openai-chat-completion.js +532 -0
  69. package/dist/services/ai/providers/openai-responses.d.ts +14 -0
  70. package/dist/services/ai/providers/openai-responses.d.ts.map +1 -0
  71. package/dist/services/ai/providers/openai-responses.js +182 -0
  72. package/dist/services/ai/providers/orcarouter.d.ts +52 -0
  73. package/dist/services/ai/providers/orcarouter.d.ts.map +1 -0
  74. package/dist/services/ai/providers/orcarouter.js +66 -0
  75. package/dist/services/ai/providers/runcrate.d.ts +49 -0
  76. package/dist/services/ai/providers/runcrate.d.ts.map +1 -0
  77. package/dist/services/ai/providers/runcrate.js +57 -0
  78. package/dist/services/ai/session/ai-session-manager.d.ts +25 -0
  79. package/dist/services/ai/session/ai-session-manager.d.ts.map +1 -0
  80. package/dist/services/ai/session/ai-session-manager.js +180 -0
  81. package/dist/services/ai/session/session-types.d.ts +43 -0
  82. package/dist/services/ai/session/session-types.d.ts.map +1 -0
  83. package/dist/services/ai/session/session-types.js +1 -0
  84. package/dist/services/ai/tools/tool-schema.d.ts +41 -0
  85. package/dist/services/ai/tools/tool-schema.d.ts.map +1 -0
  86. package/dist/services/ai/tools/tool-schema.js +24 -0
  87. package/dist/services/ai/validators/user-profile-validator.d.ts +13 -0
  88. package/dist/services/ai/validators/user-profile-validator.d.ts.map +1 -0
  89. package/dist/services/ai/validators/user-profile-validator.js +114 -0
  90. package/dist/services/api-handlers.d.ts +277 -0
  91. package/dist/services/api-handlers.d.ts.map +1 -0
  92. package/dist/services/api-handlers.js +1740 -0
  93. package/dist/services/auth-token.d.ts +11 -0
  94. package/dist/services/auth-token.d.ts.map +1 -0
  95. package/dist/services/auth-token.js +44 -0
  96. package/dist/services/auto-capture-config-status.d.ts +15 -0
  97. package/dist/services/auto-capture-config-status.d.ts.map +1 -0
  98. package/dist/services/auto-capture-config-status.js +31 -0
  99. package/dist/services/auto-capture.d.ts +33 -0
  100. package/dist/services/auto-capture.d.ts.map +1 -0
  101. package/dist/services/auto-capture.js +906 -0
  102. package/dist/services/auto-update.d.ts +28 -0
  103. package/dist/services/auto-update.d.ts.map +1 -0
  104. package/dist/services/auto-update.js +197 -0
  105. package/dist/services/capture-evidence-events.d.ts +3 -0
  106. package/dist/services/capture-evidence-events.d.ts.map +1 -0
  107. package/dist/services/capture-evidence-events.js +15 -0
  108. package/dist/services/capture-evidence.d.ts +21 -0
  109. package/dist/services/capture-evidence.d.ts.map +1 -0
  110. package/dist/services/capture-evidence.js +168 -0
  111. package/dist/services/capture-tool-evidence.d.ts +21 -0
  112. package/dist/services/capture-tool-evidence.d.ts.map +1 -0
  113. package/dist/services/capture-tool-evidence.js +109 -0
  114. package/dist/services/cleanup-service.d.ts +26 -0
  115. package/dist/services/cleanup-service.d.ts.map +1 -0
  116. package/dist/services/cleanup-service.js +199 -0
  117. package/dist/services/client.d.ts +167 -0
  118. package/dist/services/client.d.ts.map +1 -0
  119. package/dist/services/client.js +535 -0
  120. package/dist/services/context.d.ts +15 -0
  121. package/dist/services/context.d.ts.map +1 -0
  122. package/dist/services/context.js +44 -0
  123. package/dist/services/cors.d.ts +13 -0
  124. package/dist/services/cors.d.ts.map +1 -0
  125. package/dist/services/cors.js +52 -0
  126. package/dist/services/deduplication-service.d.ts +29 -0
  127. package/dist/services/deduplication-service.d.ts.map +1 -0
  128. package/dist/services/deduplication-service.js +113 -0
  129. package/dist/services/dreaming-lock.d.ts +6 -0
  130. package/dist/services/dreaming-lock.d.ts.map +1 -0
  131. package/dist/services/dreaming-lock.js +84 -0
  132. package/dist/services/dreaming-service.d.ts +96 -0
  133. package/dist/services/dreaming-service.d.ts.map +1 -0
  134. package/dist/services/dreaming-service.js +626 -0
  135. package/dist/services/embedding.d.ts +92 -0
  136. package/dist/services/embedding.d.ts.map +1 -0
  137. package/dist/services/embedding.js +467 -0
  138. package/dist/services/injected-prompt-filter.d.ts +49 -0
  139. package/dist/services/injected-prompt-filter.d.ts.map +1 -0
  140. package/dist/services/injected-prompt-filter.js +79 -0
  141. package/dist/services/jsonc.d.ts +7 -0
  142. package/dist/services/jsonc.d.ts.map +1 -0
  143. package/dist/services/jsonc.js +110 -0
  144. package/dist/services/language-detector.d.ts +3 -0
  145. package/dist/services/language-detector.d.ts.map +1 -0
  146. package/dist/services/language-detector.js +33 -0
  147. package/dist/services/logger.d.ts +15 -0
  148. package/dist/services/logger.d.ts.map +1 -0
  149. package/dist/services/logger.js +171 -0
  150. package/dist/services/markdown/backend.d.ts +35 -0
  151. package/dist/services/markdown/backend.d.ts.map +1 -0
  152. package/dist/services/markdown/backend.js +111 -0
  153. package/dist/services/markdown/document.d.ts +44 -0
  154. package/dist/services/markdown/document.d.ts.map +1 -0
  155. package/dist/services/markdown/document.js +159 -0
  156. package/dist/services/markdown/reconcile.d.ts +26 -0
  157. package/dist/services/markdown/reconcile.d.ts.map +1 -0
  158. package/dist/services/markdown/reconcile.js +333 -0
  159. package/dist/services/markdown/vault.d.ts +32 -0
  160. package/dist/services/markdown/vault.d.ts.map +1 -0
  161. package/dist/services/markdown/vault.js +142 -0
  162. package/dist/services/markdown/watcher.d.ts +22 -0
  163. package/dist/services/markdown/watcher.d.ts.map +1 -0
  164. package/dist/services/markdown/watcher.js +131 -0
  165. package/dist/services/memory-portability-service.d.ts +38 -0
  166. package/dist/services/memory-portability-service.d.ts.map +1 -0
  167. package/dist/services/memory-portability-service.js +372 -0
  168. package/dist/services/memory-provenance.d.ts +16 -0
  169. package/dist/services/memory-provenance.d.ts.map +1 -0
  170. package/dist/services/memory-provenance.js +115 -0
  171. package/dist/services/memory-recall.d.ts +49 -0
  172. package/dist/services/memory-recall.d.ts.map +1 -0
  173. package/dist/services/memory-recall.js +196 -0
  174. package/dist/services/memory-scope.d.ts +17 -0
  175. package/dist/services/memory-scope.d.ts.map +1 -0
  176. package/dist/services/memory-scope.js +43 -0
  177. package/dist/services/migration-service.d.ts +43 -0
  178. package/dist/services/migration-service.d.ts.map +1 -0
  179. package/dist/services/migration-service.js +333 -0
  180. package/dist/services/onnxruntime-resolve.d.ts +25 -0
  181. package/dist/services/onnxruntime-resolve.d.ts.map +1 -0
  182. package/dist/services/onnxruntime-resolve.js +176 -0
  183. package/dist/services/privacy.d.ts +38 -0
  184. package/dist/services/privacy.d.ts.map +1 -0
  185. package/dist/services/privacy.js +156 -0
  186. package/dist/services/request-timeouts.d.ts +4 -0
  187. package/dist/services/request-timeouts.d.ts.map +1 -0
  188. package/dist/services/request-timeouts.js +5 -0
  189. package/dist/services/runtime-require.d.ts +18 -0
  190. package/dist/services/runtime-require.d.ts.map +1 -0
  191. package/dist/services/runtime-require.js +75 -0
  192. package/dist/services/secret-resolver.d.ts +2 -0
  193. package/dist/services/secret-resolver.d.ts.map +1 -0
  194. package/dist/services/secret-resolver.js +65 -0
  195. package/dist/services/shard-inventory-service.d.ts +70 -0
  196. package/dist/services/shard-inventory-service.d.ts.map +1 -0
  197. package/dist/services/shard-inventory-service.js +315 -0
  198. package/dist/services/shard-path-migration-service.d.ts +32 -0
  199. package/dist/services/shard-path-migration-service.d.ts.map +1 -0
  200. package/dist/services/shard-path-migration-service.js +386 -0
  201. package/dist/services/skills/skills-manager.d.ts +39 -0
  202. package/dist/services/skills/skills-manager.d.ts.map +1 -0
  203. package/dist/services/skills/skills-manager.js +231 -0
  204. package/dist/services/skills/types.d.ts +32 -0
  205. package/dist/services/skills/types.d.ts.map +1 -0
  206. package/dist/services/skills/types.js +5 -0
  207. package/dist/services/stats-service.d.ts +71 -0
  208. package/dist/services/stats-service.d.ts.map +1 -0
  209. package/dist/services/stats-service.js +288 -0
  210. package/dist/services/tags.d.ts +30 -0
  211. package/dist/services/tags.d.ts.map +1 -0
  212. package/dist/services/tags.js +245 -0
  213. package/dist/services/transformers-resolve.d.ts +17 -0
  214. package/dist/services/transformers-resolve.d.ts.map +1 -0
  215. package/dist/services/transformers-resolve.js +142 -0
  216. package/dist/services/turso/connection-manager.d.ts +66 -0
  217. package/dist/services/turso/connection-manager.d.ts.map +1 -0
  218. package/dist/services/turso/connection-manager.js +408 -0
  219. package/dist/services/turso/encryption-key.d.ts +17 -0
  220. package/dist/services/turso/encryption-key.d.ts.map +1 -0
  221. package/dist/services/turso/encryption-key.js +111 -0
  222. package/dist/services/turso/encryption-migrator.d.ts +6 -0
  223. package/dist/services/turso/encryption-migrator.d.ts.map +1 -0
  224. package/dist/services/turso/encryption-migrator.js +234 -0
  225. package/dist/services/turso/engine-migrator.d.ts +6 -0
  226. package/dist/services/turso/engine-migrator.d.ts.map +1 -0
  227. package/dist/services/turso/engine-migrator.js +318 -0
  228. package/dist/services/turso/error-classifiers.d.ts +4 -0
  229. package/dist/services/turso/error-classifiers.d.ts.map +1 -0
  230. package/dist/services/turso/error-classifiers.js +19 -0
  231. package/dist/services/turso/legacy-migrator.d.ts +2 -0
  232. package/dist/services/turso/legacy-migrator.d.ts.map +1 -0
  233. package/dist/services/turso/legacy-migrator.js +535 -0
  234. package/dist/services/turso/lifecycle.d.ts +11 -0
  235. package/dist/services/turso/lifecycle.d.ts.map +1 -0
  236. package/dist/services/turso/lifecycle.js +32 -0
  237. package/dist/services/turso/operation-lock.d.ts +26 -0
  238. package/dist/services/turso/operation-lock.d.ts.map +1 -0
  239. package/dist/services/turso/operation-lock.js +188 -0
  240. package/dist/services/turso/plugin-refs.d.ts +13 -0
  241. package/dist/services/turso/plugin-refs.d.ts.map +1 -0
  242. package/dist/services/turso/plugin-refs.js +43 -0
  243. package/dist/services/turso/ready.d.ts +3 -0
  244. package/dist/services/turso/ready.d.ts.map +1 -0
  245. package/dist/services/turso/ready.js +32 -0
  246. package/dist/services/turso/schema-migrations.d.ts +24 -0
  247. package/dist/services/turso/schema-migrations.d.ts.map +1 -0
  248. package/dist/services/turso/schema-migrations.js +367 -0
  249. package/dist/services/turso/shard-manager.d.ts +41 -0
  250. package/dist/services/turso/shard-manager.d.ts.map +1 -0
  251. package/dist/services/turso/shard-manager.js +419 -0
  252. package/dist/services/turso/sqlite-handle-release.d.ts +31 -0
  253. package/dist/services/turso/sqlite-handle-release.d.ts.map +1 -0
  254. package/dist/services/turso/sqlite-handle-release.js +101 -0
  255. package/dist/services/turso/turso-db.d.ts +61 -0
  256. package/dist/services/turso/turso-db.d.ts.map +1 -0
  257. package/dist/services/turso/turso-db.js +214 -0
  258. package/dist/services/turso/types.d.ts +52 -0
  259. package/dist/services/turso/types.d.ts.map +1 -0
  260. package/dist/services/turso/types.js +1 -0
  261. package/dist/services/turso/vector-search.d.ts +63 -0
  262. package/dist/services/turso/vector-search.d.ts.map +1 -0
  263. package/dist/services/turso/vector-search.js +510 -0
  264. package/dist/services/turso/vector-utils.d.ts +16 -0
  265. package/dist/services/turso/vector-utils.d.ts.map +1 -0
  266. package/dist/services/turso/vector-utils.js +98 -0
  267. package/dist/services/turso/wal-index-recovery.d.ts +51 -0
  268. package/dist/services/turso/wal-index-recovery.d.ts.map +1 -0
  269. package/dist/services/turso/wal-index-recovery.js +248 -0
  270. package/dist/services/update-on-capture.d.ts +77 -0
  271. package/dist/services/update-on-capture.d.ts.map +1 -0
  272. package/dist/services/update-on-capture.js +116 -0
  273. package/dist/services/user-memory-learning.d.ts +137 -0
  274. package/dist/services/user-memory-learning.d.ts.map +1 -0
  275. package/dist/services/user-memory-learning.js +787 -0
  276. package/dist/services/user-profile/ai-cleanup.d.ts +59 -0
  277. package/dist/services/user-profile/ai-cleanup.d.ts.map +1 -0
  278. package/dist/services/user-profile/ai-cleanup.js +488 -0
  279. package/dist/services/user-profile/learning-lock.d.ts +41 -0
  280. package/dist/services/user-profile/learning-lock.d.ts.map +1 -0
  281. package/dist/services/user-profile/learning-lock.js +619 -0
  282. package/dist/services/user-profile/profile-context.d.ts +2 -0
  283. package/dist/services/user-profile/profile-context.d.ts.map +1 -0
  284. package/dist/services/user-profile/profile-context.js +105 -0
  285. package/dist/services/user-profile/profile-utils.d.ts +17 -0
  286. package/dist/services/user-profile/profile-utils.d.ts.map +1 -0
  287. package/dist/services/user-profile/profile-utils.js +77 -0
  288. package/dist/services/user-profile/types.d.ts +93 -0
  289. package/dist/services/user-profile/types.d.ts.map +1 -0
  290. package/dist/services/user-profile/types.js +1 -0
  291. package/dist/services/user-profile/user-profile-manager.d.ts +106 -0
  292. package/dist/services/user-profile/user-profile-manager.d.ts.map +1 -0
  293. package/dist/services/user-profile/user-profile-manager.js +1793 -0
  294. package/dist/services/user-prompt/user-prompt-manager.d.ts +64 -0
  295. package/dist/services/user-prompt/user-prompt-manager.d.ts.map +1 -0
  296. package/dist/services/user-prompt/user-prompt-manager.js +428 -0
  297. package/dist/services/web-api-auth.d.ts +4 -0
  298. package/dist/services/web-api-auth.d.ts.map +1 -0
  299. package/dist/services/web-api-auth.js +24 -0
  300. package/dist/services/web-auth.d.ts +47 -0
  301. package/dist/services/web-auth.d.ts.map +1 -0
  302. package/dist/services/web-auth.js +105 -0
  303. package/dist/services/web-server.d.ts +58 -0
  304. package/dist/services/web-server.d.ts.map +1 -0
  305. package/dist/services/web-server.js +774 -0
  306. package/dist/shared/api/index.d.ts +5 -0
  307. package/dist/shared/api/index.d.ts.map +1 -0
  308. package/dist/shared/api/index.js +2 -0
  309. package/dist/shared/api/portability-schemas.d.ts +57 -0
  310. package/dist/shared/api/portability-schemas.d.ts.map +1 -0
  311. package/dist/shared/api/portability-schemas.js +39 -0
  312. package/dist/shared/api/schemas.d.ts +296 -0
  313. package/dist/shared/api/schemas.d.ts.map +1 -0
  314. package/dist/shared/api/schemas.js +134 -0
  315. package/dist/shared/api/types.d.ts +29 -0
  316. package/dist/shared/api/types.d.ts.map +1 -0
  317. package/dist/shared/api/types.js +1 -0
  318. package/dist/tui.d.ts +10 -0
  319. package/dist/tui.d.ts.map +1 -0
  320. package/dist/tui.js +17 -0
  321. package/dist/types/index.d.ts +19 -0
  322. package/dist/types/index.d.ts.map +1 -0
  323. package/dist/types/index.js +1 -0
  324. package/dist/utils/context-limit.d.ts +11 -0
  325. package/dist/utils/context-limit.d.ts.map +1 -0
  326. package/dist/utils/context-limit.js +43 -0
  327. package/dist/utils/math.d.ts +8 -0
  328. package/dist/utils/math.d.ts.map +1 -0
  329. package/dist/utils/math.js +48 -0
  330. package/dist/utils/profile.d.ts +3 -0
  331. package/dist/utils/profile.d.ts.map +1 -0
  332. package/dist/utils/profile.js +15 -0
  333. package/dist/v2/adapter.d.ts +3 -0
  334. package/dist/v2/adapter.d.ts.map +1 -0
  335. package/dist/v2/adapter.js +217 -0
  336. package/dist/v2/legacy-client.d.ts +22 -0
  337. package/dist/v2/legacy-client.d.ts.map +1 -0
  338. package/dist/v2/legacy-client.js +410 -0
  339. package/dist/v2/plugin.d.ts +4 -0
  340. package/dist/v2/plugin.d.ts.map +1 -0
  341. package/dist/v2/plugin.js +34 -0
  342. package/dist/v2/toast-rpc.d.ts +43 -0
  343. package/dist/v2/toast-rpc.d.ts.map +1 -0
  344. package/dist/v2/toast-rpc.js +26 -0
  345. package/dist/web/accent-preview.html +444 -0
  346. package/dist/web/assets/index-mTgxOb5l.css +2 -0
  347. package/dist/web/assets/index-ysje17yK.js +109 -0
  348. package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  349. package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  350. package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  351. package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  352. package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  353. package/dist/web/favicon.ico +0 -0
  354. package/dist/web/favicon.svg +11 -0
  355. package/dist/web/index.html +29 -0
  356. package/dist/web/opencode-mem-icon.png +0 -0
  357. package/package.json +122 -4
@@ -0,0 +1,408 @@
1
+ import { connect } from "@tursodatabase/database";
2
+ import { existsSync, mkdirSync } from "node:fs";
3
+ import { dirname, resolve, relative, isAbsolute, sep } from "node:path";
4
+ import { CONFIG } from "../../config.js";
5
+ import { log, safeLog } from "../logger.js";
6
+ import { collectReleasedSqliteHandles } from "./sqlite-handle-release.js";
7
+ import { TursoDb } from "./turso-db.js";
8
+ import { resolveOrCreateDatabaseEncryptionKey } from "./encryption-key.js";
9
+ import { isWalIndexCorruptionError, quarantineWalSidecars, acquireRecoveryLock, } from "./wal-index-recovery.js";
10
+ /** Always-on experimental flags for every Turso open. */
11
+ export const TURSO_BASE_EXPERIMENTAL_FEATURES = ["encryption", "vacuum"];
12
+ /**
13
+ * Multiprocess WAL is Unix-only. On Windows/WASM/32-bit the flag is accepted but
14
+ * ignored (single-process mode) — see Turso multi-process docs.
15
+ */
16
+ export function supportsTursoMultiprocessWal(platform = process.platform) {
17
+ return platform !== "win32";
18
+ }
19
+ /**
20
+ * Experimental flags required on every Turso open for the current platform.
21
+ * `multiprocessWal: false` opts into single-owner mode (Unix), so a foreign
22
+ * process gets a loud "database is locked" instead of silent divergence.
23
+ */
24
+ export function tursoExperimentalFeatures(platform = process.platform, multiprocessWal = CONFIG.tursoMultiprocessWal) {
25
+ if (multiprocessWal && supportsTursoMultiprocessWal(platform)) {
26
+ return [...TURSO_BASE_EXPERIMENTAL_FEATURES, "multiprocess_wal"];
27
+ }
28
+ return [...TURSO_BASE_EXPERIMENTAL_FEATURES];
29
+ }
30
+ function assertPathInsideStorage(dbPath) {
31
+ const storageRoot = resolve(CONFIG.storagePath);
32
+ const resolvedPath = resolve(dbPath);
33
+ const relativePath = relative(storageRoot, resolvedPath);
34
+ // Only treat path-segment traversal as escape (not filenames containing "..").
35
+ if (relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {
36
+ throw new Error(`Refusing to open database outside storagePath: ${dbPath}`);
37
+ }
38
+ }
39
+ /**
40
+ * Shared connect options for `@tursodatabase/database`.
41
+ * Always enables encryption; adds multiprocess_wal on Unix so concurrent
42
+ * OpenCode sessions can share the store. Windows stays single-process.
43
+ */
44
+ export function buildConnectOptions(encryption) {
45
+ const opts = {
46
+ experimental: tursoExperimentalFeatures(),
47
+ };
48
+ if (encryption) {
49
+ opts.encryption = encryption;
50
+ }
51
+ return opts;
52
+ }
53
+ export function resolveDatabaseEncryption() {
54
+ const hexkey = resolveOrCreateDatabaseEncryptionKey();
55
+ if (!hexkey)
56
+ return null;
57
+ return {
58
+ cipher: CONFIG.databaseEncryptionCipher,
59
+ hexkey,
60
+ };
61
+ }
62
+ const LOCK_ERROR_RE = /File is locked by another process|already open (with|without) experimental multiprocess WAL|Locking error/i;
63
+ export function isTursoMultiProcessLockError(error) {
64
+ const message = error instanceof Error ? error.message : String(error);
65
+ return LOCK_ERROR_RE.test(message);
66
+ }
67
+ export function wrapTursoOpenError(dbPath, error) {
68
+ const message = error instanceof Error ? error.message : String(error);
69
+ if (isTursoMultiProcessLockError(error)) {
70
+ const platformHint = process.platform === "win32"
71
+ ? "On Windows the Turso engine still allows only one process as database owner — close other OpenCode sessions."
72
+ : "Another OpenCode session (or an older opencode-mem without multiprocess_wal) still holds the database — close it and retry.";
73
+ return new Error(`Failed to open database ${dbPath}: ${message}. ${platformHint}`, {
74
+ cause: error,
75
+ });
76
+ }
77
+ return error instanceof Error ? error : new Error(message, { cause: error });
78
+ }
79
+ export class TursoConnectionManager {
80
+ connectFactory;
81
+ connections = new Map();
82
+ pending = new Map();
83
+ closingConnections = new Map();
84
+ closingPromise = null;
85
+ /**
86
+ * Paths that already had a completed recovery attempt this process (no loop).
87
+ * Set after a successful quarantine or a definitive skip — not when quarantine
88
+ * moved nothing, so a later open can still finish a blocked first attempt.
89
+ */
90
+ healedPaths = new Set();
91
+ warnedForeignShmPaths = new Set();
92
+ constructor(connectFactory = connect) {
93
+ this.connectFactory = connectFactory;
94
+ }
95
+ /**
96
+ * Connect, and on a stale-WAL-index failure quarantine the index sidecars once
97
+ * and retry once. Only the two known signatures heal (see #435); any other open
98
+ * error propagates unchanged.
99
+ *
100
+ * Recovery is serialised across processes (they share `storagePath` through
101
+ * `multiprocess_wal`) with `<storagePath>/recovery/<dbstem>.lock`. Under that
102
+ * lock the open is re-attempted before any file is moved, so a peer that
103
+ * healed first leaves us nothing to do. A non-empty WAL is never moved — see
104
+ * `wal-index-recovery.ts` for the data-safety contract.
105
+ */
106
+ async connectWithWalIndexRecovery(dbPath, opts) {
107
+ try {
108
+ return await this.connectFactory(dbPath, opts);
109
+ }
110
+ catch (error) {
111
+ if (!CONFIG.tursoAutoHeal || !isWalIndexCorruptionError(error)) {
112
+ throw error;
113
+ }
114
+ if (this.healedPaths.has(dbPath)) {
115
+ throw error;
116
+ }
117
+ let lock;
118
+ try {
119
+ lock = acquireRecoveryLock(dbPath);
120
+ }
121
+ catch (lockError) {
122
+ log("Turso WAL index recovery skipped: could not take the recovery lock", {
123
+ path: dbPath,
124
+ error: String(lockError),
125
+ originalError: String(error),
126
+ });
127
+ throw error;
128
+ }
129
+ if (!lock) {
130
+ log("Turso WAL index recovery skipped: another process owns the recovery lock", {
131
+ path: dbPath,
132
+ hint: "The owning process is healing this store; leaving its files untouched.",
133
+ error: String(error),
134
+ });
135
+ throw error;
136
+ }
137
+ if (lock.tookOverStaleLock) {
138
+ log("Took over a stale Turso WAL index recovery lock", {
139
+ path: dbPath,
140
+ lock: lock.lockPath,
141
+ });
142
+ }
143
+ try {
144
+ // The peer may have healed between our failed open and taking the lock.
145
+ try {
146
+ const connection = await this.connectFactory(dbPath, opts);
147
+ log("Turso open succeeded on the recovery-lock recheck; nothing was moved", {
148
+ path: dbPath,
149
+ });
150
+ return connection;
151
+ }
152
+ catch (recheckError) {
153
+ if (!isWalIndexCorruptionError(recheckError)) {
154
+ // e.g. a lock error: do not move a live owner's files.
155
+ log("Turso recovery-lock recheck failed with an unrelated error; store left untouched", {
156
+ path: dbPath,
157
+ error: String(recheckError),
158
+ originalError: String(error),
159
+ });
160
+ throw error;
161
+ }
162
+ }
163
+ const outcome = await quarantineWalSidecars(dbPath, this.connectFactory, opts);
164
+ if (outcome.status === "failed") {
165
+ log("Turso WAL index recovery failed; the store was left as-is where possible", {
166
+ path: dbPath,
167
+ reason: outcome.reason,
168
+ quarantineDir: outcome.quarantineDir,
169
+ moved: outcome.moved,
170
+ error: String(error),
171
+ });
172
+ // A partial move (e.g. -tshm gone, -shm rename failed) may already be
173
+ // enough to open. Retry once when anything moved; leave healedPaths
174
+ // clear when nothing moved so a later attempt can finish the job.
175
+ if (outcome.moved.length === 0) {
176
+ throw error;
177
+ }
178
+ this.healedPaths.add(dbPath);
179
+ try {
180
+ return await this.connectFactory(dbPath, opts);
181
+ }
182
+ catch (retryError) {
183
+ log("Turso open still failing after a partial WAL index recovery", {
184
+ path: dbPath,
185
+ quarantineDir: outcome.quarantineDir,
186
+ moved: outcome.moved,
187
+ error: String(retryError),
188
+ });
189
+ throw error;
190
+ }
191
+ }
192
+ if (outcome.status === "skipped") {
193
+ // Retrying the same path will not help (missing main file / bad copy /
194
+ // nothing to move). Remember so we do not keep copying the database.
195
+ this.healedPaths.add(dbPath);
196
+ log("Turso open failed and the store was left untouched (no recovery attempted)", {
197
+ path: dbPath,
198
+ reason: outcome.reason,
199
+ hint: "Restore this database from a backup; the sidecar files were not moved.",
200
+ error: String(error),
201
+ });
202
+ throw error;
203
+ }
204
+ // Quarantine completed: mark before the retry so a still-corrupt store
205
+ // cannot loop. Do not mark earlier — a mid-quarantine failure with
206
+ // nothing useful moved must remain retryable in this process.
207
+ this.healedPaths.add(dbPath);
208
+ log("Moved stale WAL index sidecars aside after a Turso open failure; retrying once", {
209
+ path: dbPath,
210
+ quarantineDir: outcome.quarantineDir,
211
+ moved: outcome.moved,
212
+ removedEmptyWal: outcome.removedEmptyWal,
213
+ retainedWalBytes: outcome.retainedWalBytes,
214
+ hint: outcome.retainedWalBytes > 0
215
+ ? "A non-empty -wal was kept; the engine rebuilds its index from it."
216
+ : undefined,
217
+ });
218
+ try {
219
+ return await this.connectFactory(dbPath, opts);
220
+ }
221
+ catch (retryError) {
222
+ log("Turso open still failing after WAL index recovery", {
223
+ path: dbPath,
224
+ quarantineDir: outcome.quarantineDir,
225
+ error: String(retryError),
226
+ walPreserved: outcome.retainedWalBytes > 0,
227
+ hint: outcome.retainedWalBytes > 0
228
+ ? "The non-empty -wal was not moved, so no committed data was discarded."
229
+ : "The -wal was empty or absent, so no committed data was discarded.",
230
+ });
231
+ throw error;
232
+ }
233
+ }
234
+ finally {
235
+ try {
236
+ lock.release();
237
+ }
238
+ catch (releaseError) {
239
+ try {
240
+ log("Failed to release the Turso WAL index recovery lock", {
241
+ path: dbPath,
242
+ lock: lock.lockPath,
243
+ error: String(releaseError),
244
+ });
245
+ }
246
+ catch {
247
+ // A logging failure must never replace the original open error.
248
+ }
249
+ }
250
+ }
251
+ }
252
+ }
253
+ /**
254
+ * A foreign sqlite process that wrote this store leaves `-shm` next to a
255
+ * Turso `-tshm`. Read-only access is harmless; a foreign writer diverges
256
+ * silently and loses its own next write, so warn once per path. Never delete
257
+ * `-shm` here — it may belong to a live reader.
258
+ */
259
+ warnOnForeignSqliteShm(dbPath) {
260
+ if (this.warnedForeignShmPaths.has(dbPath))
261
+ return;
262
+ if (!existsSync(`${dbPath}-shm`) || !existsSync(`${dbPath}-tshm`))
263
+ return;
264
+ this.warnedForeignShmPaths.add(dbPath);
265
+ log("Foreign SQLite process touched this store (-shm beside -tshm)", {
266
+ path: dbPath,
267
+ hint: "Read-only access is harmless, but a foreign writer silently loses data — " +
268
+ "see issue #435. Close other tools on this store, or set tursoMultiprocessWal=false " +
269
+ "for single-owner mode.",
270
+ });
271
+ }
272
+ async getConnection(dbPath) {
273
+ if (this.closingPromise) {
274
+ await this.closingPromise;
275
+ }
276
+ const closingConnection = this.closingConnections.get(dbPath);
277
+ if (closingConnection) {
278
+ await closingConnection;
279
+ }
280
+ assertPathInsideStorage(dbPath);
281
+ const existing = this.connections.get(dbPath);
282
+ if (existing) {
283
+ return existing;
284
+ }
285
+ const inFlight = this.pending.get(dbPath);
286
+ if (inFlight) {
287
+ return inFlight;
288
+ }
289
+ const openPromise = (async () => {
290
+ const dir = dirname(dbPath);
291
+ if (!existsSync(dir)) {
292
+ mkdirSync(dir, { recursive: true });
293
+ }
294
+ const encryption = resolveDatabaseEncryption();
295
+ const opts = buildConnectOptions(encryption);
296
+ let database = null;
297
+ try {
298
+ database = await this.connectWithWalIndexRecovery(dbPath, opts);
299
+ const db = new TursoDb(database);
300
+ await db.execute("PRAGMA foreign_keys = ON");
301
+ this.warnOnForeignSqliteShm(dbPath);
302
+ this.connections.set(dbPath, db);
303
+ return db;
304
+ }
305
+ catch (error) {
306
+ if (database) {
307
+ try {
308
+ await database.close();
309
+ }
310
+ catch {
311
+ // ignore close errors during cleanup
312
+ }
313
+ }
314
+ if (encryption) {
315
+ const message = error instanceof Error ? error.message : String(error);
316
+ if (isTursoMultiProcessLockError(error)) {
317
+ throw wrapTursoOpenError(dbPath, error);
318
+ }
319
+ throw new Error(`Failed to open encrypted database ${dbPath}: ${message}. ` +
320
+ `Check databaseEncryptionKey / cipher, or remove encryption config for plaintext shards.`, { cause: error });
321
+ }
322
+ throw wrapTursoOpenError(dbPath, error);
323
+ }
324
+ })();
325
+ this.pending.set(dbPath, openPromise);
326
+ try {
327
+ return await openPromise;
328
+ }
329
+ catch (error) {
330
+ this.connections.delete(dbPath);
331
+ throw error;
332
+ }
333
+ finally {
334
+ this.pending.delete(dbPath);
335
+ }
336
+ }
337
+ async closeConnection(dbPath) {
338
+ if (this.closingPromise) {
339
+ await this.closingPromise;
340
+ }
341
+ const existingClose = this.closingConnections.get(dbPath);
342
+ if (existingClose) {
343
+ return existingClose;
344
+ }
345
+ const closePromise = Promise.resolve()
346
+ .then(async () => {
347
+ const pending = this.pending.get(dbPath);
348
+ if (pending) {
349
+ await Promise.allSettled([pending]);
350
+ }
351
+ const db = this.connections.get(dbPath);
352
+ if (db) {
353
+ try {
354
+ await db.close();
355
+ }
356
+ catch (error) {
357
+ safeLog("Error closing Turso database", { path: dbPath, error: String(error) });
358
+ }
359
+ this.connections.delete(dbPath);
360
+ }
361
+ await collectReleasedSqliteHandles();
362
+ })
363
+ .finally(() => {
364
+ this.closingConnections.delete(dbPath);
365
+ });
366
+ this.closingConnections.set(dbPath, closePromise);
367
+ return closePromise;
368
+ }
369
+ async closeAll() {
370
+ if (this.closingPromise)
371
+ return this.closingPromise;
372
+ this.closingPromise = (async () => {
373
+ await Promise.allSettled([...this.pending.values(), ...this.closingConnections.values()]);
374
+ // Close in parallel: each close runs a bounded WAL checkpoint, and the
375
+ // host allows only ~5s between SIGTERM and SIGKILL.
376
+ await Promise.allSettled([...this.connections].map(async ([path, db]) => {
377
+ try {
378
+ await db.close();
379
+ }
380
+ catch (error) {
381
+ safeLog("Error closing Turso database", { path, error: String(error) });
382
+ }
383
+ }));
384
+ this.connections.clear();
385
+ this.pending.clear();
386
+ await collectReleasedSqliteHandles();
387
+ })();
388
+ try {
389
+ await this.closingPromise;
390
+ }
391
+ finally {
392
+ this.closingPromise = null;
393
+ }
394
+ }
395
+ closeAllSync() {
396
+ for (const [path, db] of this.connections) {
397
+ try {
398
+ db.closeSync();
399
+ }
400
+ catch (error) {
401
+ safeLog("Error closing Turso database (sync)", { path, error: String(error) });
402
+ }
403
+ }
404
+ this.connections.clear();
405
+ this.pending.clear();
406
+ }
407
+ }
408
+ export const tursoConnectionManager = new TursoConnectionManager();
@@ -0,0 +1,17 @@
1
+ export declare const DEFAULT_DATABASE_ENCRYPTION_KEY_PATH: string;
2
+ export declare function isValidDatabaseEncryptionHexKey(value: string): boolean;
3
+ /**
4
+ * Create a new AES-256 key (32 random bytes as 64 hex chars) at path with mode 0600.
5
+ * Refuses to create a new key when encrypted DBs already exist (fail-closed).
6
+ */
7
+ export declare function generateDatabaseEncryptionKeyFile(keyPath?: string): string;
8
+ /**
9
+ * Ensure a key file exists (generate once if missing), then return its hex contents.
10
+ */
11
+ export declare function ensureDatabaseEncryptionKeyFile(keyPath?: string): string;
12
+ /**
13
+ * Resolve the active encryption hex key, auto-generating the default key file when
14
+ * encryption is enabled and no key is configured yet.
15
+ */
16
+ export declare function resolveOrCreateDatabaseEncryptionKey(): string | null;
17
+ //# sourceMappingURL=encryption-key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryption-key.d.ts","sourceRoot":"","sources":["../../../src/services/turso/encryption-key.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,oCAAoC,QAKhD,CAAC;AAIF,wBAAgB,+BAA+B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAGtE;AAgBD;;;GAGG;AACH,wBAAgB,iCAAiC,CAC/C,OAAO,GAAE,MAA6C,GACrD,MAAM,CA2BR;AAED;;GAEG;AACH,wBAAgB,+BAA+B,CAC7C,OAAO,GAAE,MAA6C,GACrD,MAAM,CAuBR;AAED;;;GAGG;AACH,wBAAgB,oCAAoC,IAAI,MAAM,GAAG,IAAI,CAwCpE"}
@@ -0,0 +1,111 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { homedir, platform } from "node:os";
5
+ import { CONFIG } from "../../config.js";
6
+ import { log } from "../logger.js";
7
+ import { resolveSecretValue } from "../secret-resolver.js";
8
+ export const DEFAULT_DATABASE_ENCRYPTION_KEY_PATH = join(homedir(), ".config", "opencode", "opencode-mem-db.key");
9
+ const HEX_KEY_RE = /^[0-9a-fA-F]+$/;
10
+ export function isValidDatabaseEncryptionHexKey(value) {
11
+ const trimmed = value.trim();
12
+ return HEX_KEY_RE.test(trimmed) && (trimmed.length === 32 || trimmed.length === 64);
13
+ }
14
+ function expandPath(path) {
15
+ if (path.startsWith("~/")) {
16
+ return join(homedir(), path.slice(2));
17
+ }
18
+ if (path === "~") {
19
+ return homedir();
20
+ }
21
+ return path;
22
+ }
23
+ function encryptionMarkerPath() {
24
+ return join(CONFIG.storagePath, ".tursodb-encrypted-v1");
25
+ }
26
+ /**
27
+ * Create a new AES-256 key (32 random bytes as 64 hex chars) at path with mode 0600.
28
+ * Refuses to create a new key when encrypted DBs already exist (fail-closed).
29
+ */
30
+ export function generateDatabaseEncryptionKeyFile(keyPath = DEFAULT_DATABASE_ENCRYPTION_KEY_PATH) {
31
+ const resolved = expandPath(keyPath);
32
+ if (existsSync(encryptionMarkerPath())) {
33
+ throw new Error(`Cannot generate a new database encryption key at ${resolved}: ` +
34
+ `encrypted databases already exist under ${CONFIG.storagePath}. ` +
35
+ `Restore the original key file or decrypt/migrate with the old key first.`);
36
+ }
37
+ const dir = dirname(resolved);
38
+ if (!existsSync(dir)) {
39
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
40
+ }
41
+ const hexkey = randomBytes(32).toString("hex");
42
+ writeFileSync(resolved, `${hexkey}\n`, { encoding: "utf-8", mode: 0o600, flag: "wx" });
43
+ if (platform() !== "win32") {
44
+ try {
45
+ chmodSync(resolved, 0o600);
46
+ }
47
+ catch {
48
+ // best-effort; mode was set on write where supported
49
+ }
50
+ }
51
+ log("Generated database encryption key", { path: resolved });
52
+ return hexkey;
53
+ }
54
+ /**
55
+ * Ensure a key file exists (generate once if missing), then return its hex contents.
56
+ */
57
+ export function ensureDatabaseEncryptionKeyFile(keyPath = DEFAULT_DATABASE_ENCRYPTION_KEY_PATH) {
58
+ const resolved = expandPath(keyPath);
59
+ if (!existsSync(resolved)) {
60
+ return generateDatabaseEncryptionKeyFile(resolved);
61
+ }
62
+ const content = readFileSync(resolved, "utf-8").trim();
63
+ if (!isValidDatabaseEncryptionHexKey(content)) {
64
+ throw new Error(`Database encryption key file ${resolved} is invalid. ` +
65
+ `Expected a 32- or 64-character hex string (AES-128 or AES-256).`);
66
+ }
67
+ if (platform() !== "win32") {
68
+ try {
69
+ chmodSync(resolved, 0o600);
70
+ }
71
+ catch {
72
+ // ignore chmod failures on exotic filesystems
73
+ }
74
+ }
75
+ return content;
76
+ }
77
+ /**
78
+ * Resolve the active encryption hex key, auto-generating the default key file when
79
+ * encryption is enabled and no key is configured yet.
80
+ */
81
+ export function resolveOrCreateDatabaseEncryptionKey() {
82
+ const enabled = CONFIG.databaseEncryptionEnabled === true;
83
+ const raw = CONFIG.databaseEncryptionKey?.trim();
84
+ if (!enabled && !raw) {
85
+ return null;
86
+ }
87
+ // Explicit hex in config (discouraged, but supported).
88
+ if (raw && isValidDatabaseEncryptionHexKey(raw) && !raw.includes("://")) {
89
+ return raw.trim();
90
+ }
91
+ if (raw?.startsWith("env://")) {
92
+ const value = resolveSecretValue(raw)?.trim();
93
+ if (!value || !isValidDatabaseEncryptionHexKey(value)) {
94
+ throw new Error(`databaseEncryptionKey ${raw} must resolve to a 32- or 64-character hex string`);
95
+ }
96
+ return value;
97
+ }
98
+ if (raw?.startsWith("file://")) {
99
+ const filePath = expandPath(raw.slice(7));
100
+ return ensureDatabaseEncryptionKeyFile(filePath);
101
+ }
102
+ if (raw) {
103
+ // Treat bare paths as file paths for convenience.
104
+ if (raw.includes("/") || raw.startsWith("~")) {
105
+ return ensureDatabaseEncryptionKeyFile(raw);
106
+ }
107
+ throw new Error("databaseEncryptionKey must be env://VAR, file://path, or a 32/64-char hex string");
108
+ }
109
+ // Enabled without explicit key → default file, auto-create once.
110
+ return ensureDatabaseEncryptionKeyFile(DEFAULT_DATABASE_ENCRYPTION_KEY_PATH);
111
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * When database encryption is enabled (or a key is configured), convert
3
+ * plaintext shards to encrypted Turso DB files. No-op when encryption is off.
4
+ */
5
+ export declare function runDatabaseEncryptionMigration(): Promise<void>;
6
+ //# sourceMappingURL=encryption-migrator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryption-migrator.d.ts","sourceRoot":"","sources":["../../../src/services/turso/encryption-migrator.ts"],"names":[],"mappings":"AAqOA;;;GAGG;AACH,wBAAsB,8BAA8B,IAAI,OAAO,CAAC,IAAI,CAAC,CAgCpE"}