@aislop-inc/opencode-mem 0.0.0-stage → 2.41.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 (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,774 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { createServer } from "node:http";
3
+ import { Readable } from "node:stream";
4
+ import { join, dirname, extname, normalize, sep } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { log } from "./logger.js";
7
+ import { corsPreflightResponse, disallowedCorsResponse, isAllowedBrowserOrigin } from "./cors.js";
8
+ import { assertWebServerNetworkAuth, authorizeApiRequest } from "./web-api-auth.js";
9
+ import { getOrCreateAuthToken, isAuthorizedApiRequest } from "./auth-token.js";
10
+ import { WebAuth } from "./web-auth.js";
11
+ import { NODE_HTTP_IDLE_TIMEOUT_MS } from "./request-timeouts.js";
12
+ import { handleListTags, handleListMemories, handleAddMemory, handleDeleteMemory, handleListTrash, handleRestoreMemory, handleBulkDelete, handleUpdateMemory, handleSearch, handleStats, handlePinMemory, handleUnpinMemory, handleRunCleanup, handleRunDeduplication, handleDreamingStatus, handleRunDreaming, handleDetectMigration, handleRunMigration, handleDetectTagMigration, handleRunTagMigrationBatch, handleGetTagMigrationProgress, handleDeletePrompt, handleBulkDeletePrompts, handleGetUserProfile, handleGetProfileChangelog, handleGetProfileSnapshot, handleRefreshProfile, handleAICleanup, handleApplyCleanup, handleUpdateProfileItem, handleListSkills, handleGetSkill, handleCreateSkill, handleUpdateSkill, handleDeleteSkill, handleSkillsCatalogIndex, handleSkillsCatalogFile, handleMarkdownStatus, handleMarkdownReindex, handleGetMemory, } from "./api-handlers.js";
13
+ const isBun = typeof globalThis.Bun !== "undefined";
14
+ const MIN_FAILED_TAKEOVERS = 3;
15
+ export function attachNodeDisconnectHandlers(req, res, onDisconnect) {
16
+ let disconnected = false;
17
+ const disconnectOnce = () => {
18
+ if (disconnected || res.writableEnded)
19
+ return;
20
+ disconnected = true;
21
+ onDisconnect();
22
+ };
23
+ req.on("aborted", disconnectOnce);
24
+ req.on("close", () => {
25
+ if (req.aborted || !req.complete)
26
+ disconnectOnce();
27
+ });
28
+ req.socket.on("error", disconnectOnce);
29
+ req.socket.on("close", disconnectOnce);
30
+ res.on("close", disconnectOnce);
31
+ }
32
+ function serveFetch(opts) {
33
+ if (isBun) {
34
+ const bunHandle = globalThis.Bun.serve({
35
+ port: opts.port,
36
+ hostname: opts.hostname,
37
+ fetch: opts.fetch,
38
+ });
39
+ return { stop: () => bunHandle.stop() };
40
+ }
41
+ // Node path: wrap node:http around the fetch-style handler. The adapter
42
+ // converts IncomingMessage → Web Request and Web Response → ServerResponse.
43
+ // Bodies stream both directions via the WHATWG Streams ↔ Node Streams
44
+ // helpers that ship with Node 18+.
45
+ const server = createServer(async (req, res) => {
46
+ let destroyed = false;
47
+ const abortController = new AbortController();
48
+ const cleanup = () => {
49
+ if (destroyed)
50
+ return;
51
+ destroyed = true;
52
+ abortController.abort();
53
+ if (!res.writableEnded)
54
+ res.destroy();
55
+ if (!req.socket.destroyed)
56
+ req.socket.destroy();
57
+ };
58
+ attachNodeDisconnectHandlers(req, res, cleanup);
59
+ try {
60
+ const url = `http://${opts.hostname}:${opts.port}${req.url ?? "/"}`;
61
+ const method = req.method ?? "GET";
62
+ const hasBody = method !== "GET" && method !== "HEAD";
63
+ const webReq = new Request(url, {
64
+ method,
65
+ headers: req.headers,
66
+ body: hasBody ? Readable.toWeb(req) : undefined,
67
+ signal: abortController.signal,
68
+ ...(hasBody ? { duplex: "half" } : {}),
69
+ });
70
+ const webRes = await opts.fetch(webReq);
71
+ if (destroyed)
72
+ return;
73
+ res.statusCode = webRes.status;
74
+ webRes.headers.forEach((value, name) => res.setHeader(name, value));
75
+ res.setHeader("Connection", "close");
76
+ if (webRes.body) {
77
+ const src = Readable.fromWeb(webRes.body);
78
+ res.on("close", () => {
79
+ if (!src.destroyed)
80
+ src.destroy();
81
+ });
82
+ src.pipe(res);
83
+ }
84
+ else {
85
+ res.end();
86
+ }
87
+ }
88
+ catch (error) {
89
+ if (!res.headersSent) {
90
+ res.statusCode = 500;
91
+ res.setHeader("Content-Type", "text/plain");
92
+ }
93
+ if (!res.writableEnded) {
94
+ res.end(`Internal Server Error: ${error instanceof Error ? error.message : String(error)}`);
95
+ }
96
+ }
97
+ });
98
+ // Surface EADDRINUSE synchronously so callers can detect the
99
+ // already-running-instance case the same way they do under Bun.
100
+ let listenError;
101
+ server.on("error", (err) => {
102
+ if (err.code === "EADDRINUSE") {
103
+ listenError = err;
104
+ }
105
+ });
106
+ // exclusive: false disables SO_EXCLUSIVEADDRUSE on Windows, allowing
107
+ // rebind after a crashed predecessor left orphaned sockets behind.
108
+ server.listen({ port: opts.port, host: opts.hostname, reuseAddr: true, exclusive: false });
109
+ server.unref();
110
+ server.timeout = NODE_HTTP_IDLE_TIMEOUT_MS;
111
+ server.keepAliveTimeout = 10000;
112
+ server.headersTimeout = 11000;
113
+ if (listenError) {
114
+ throw listenError;
115
+ }
116
+ return {
117
+ stop: () => {
118
+ server.closeAllConnections();
119
+ server.close();
120
+ },
121
+ };
122
+ }
123
+ const __filename = fileURLToPath(import.meta.url);
124
+ const __dirname = dirname(__filename);
125
+ /**
126
+ * Port fallback policy for the takeover loop. A port that fails to bind AND
127
+ * answers no HTTP is treated as orphaned Windows kernel residue; after
128
+ * `minFailedTakeovers` consecutive failed takeovers the web server moves to
129
+ * `currentPort + 1`, bounded by `maxFallbackPort`.
130
+ */
131
+ export function nextFallbackPort(currentPort, failedTakeovers, maxFallbackPort, minFailedTakeovers = MIN_FAILED_TAKEOVERS) {
132
+ if (failedTakeovers < minFailedTakeovers || currentPort >= maxFallbackPort) {
133
+ return currentPort;
134
+ }
135
+ return currentPort + 1;
136
+ }
137
+ export class WebServer {
138
+ server = null;
139
+ config;
140
+ isOwner = false;
141
+ startPromise = null;
142
+ healthCheckInterval = null;
143
+ onTakeoverCallback = null;
144
+ onPortsExhaustedCallback = null;
145
+ portsExhaustedNotified = false;
146
+ takeoverFailures = 0;
147
+ maxFallbackPort;
148
+ constructor(config) {
149
+ this.config = config;
150
+ this.maxFallbackPort = config.port + 10;
151
+ }
152
+ setOnTakeoverCallback(callback) {
153
+ this.onTakeoverCallback = callback;
154
+ }
155
+ setOnPortsExhaustedCallback(callback) {
156
+ this.onPortsExhaustedCallback = callback;
157
+ }
158
+ async start() {
159
+ if (this.startPromise) {
160
+ return this.startPromise;
161
+ }
162
+ this.startPromise = this._start();
163
+ return this.startPromise;
164
+ }
165
+ async _start() {
166
+ if (!this.config.enabled) {
167
+ return;
168
+ }
169
+ assertWebServerNetworkAuth(this.config.host, this.config.apiToken, this.config.auth?.isEnabled() ?? false);
170
+ try {
171
+ this.server = serveFetch({
172
+ port: this.config.port,
173
+ hostname: this.config.host,
174
+ fetch: this.handleRequest.bind(this),
175
+ });
176
+ this.isOwner = true;
177
+ }
178
+ catch (error) {
179
+ const errorMsg = String(error);
180
+ if (errorMsg.includes("EADDRINUSE") ||
181
+ errorMsg.includes("address already in use") ||
182
+ /Failed to start server.*Is port \d+ in use/.test(errorMsg)) {
183
+ this.isOwner = false;
184
+ this.server = null;
185
+ this.startHealthCheckLoop();
186
+ }
187
+ else {
188
+ this.isOwner = false;
189
+ this.server = null;
190
+ log("Web server failed to start", { error: errorMsg });
191
+ throw error;
192
+ }
193
+ }
194
+ }
195
+ startHealthCheckLoop() {
196
+ if (this.healthCheckInterval) {
197
+ return;
198
+ }
199
+ this.healthCheckInterval = setInterval(async () => {
200
+ const isAvailable = await this.checkServerAvailable();
201
+ if (!isAvailable) {
202
+ this.stopHealthCheckLoop();
203
+ await this.attemptTakeover();
204
+ }
205
+ }, 5000);
206
+ }
207
+ stopHealthCheckLoop() {
208
+ if (this.healthCheckInterval) {
209
+ clearInterval(this.healthCheckInterval);
210
+ this.healthCheckInterval = null;
211
+ }
212
+ }
213
+ async attemptTakeover() {
214
+ // prevent thundering herd: multiple non-owners racing to bind port
215
+ const jitterMs = 500 + Math.random() * 1000;
216
+ await new Promise((resolve) => setTimeout(resolve, jitterMs));
217
+ if (await this.checkServerAvailable()) {
218
+ // The original owner recovered. Reset the failure counter so a stale
219
+ // count can't advance the port on the next, unrelated failure.
220
+ this.takeoverFailures = 0;
221
+ this.startHealthCheckLoop();
222
+ return;
223
+ }
224
+ // Windows can leave an orphaned LISTEN socket in the TCP table after a
225
+ // crash: the port refuses to bind (EADDRINUSE) yet nothing answers HTTP,
226
+ // so repeated takeovers fail forever. After a few consecutive failures,
227
+ // fall back to a free neighbor port instead of looping.
228
+ this.takeoverFailures += 1;
229
+ const nextPort = nextFallbackPort(this.config.port, this.takeoverFailures, this.maxFallbackPort);
230
+ if (nextPort !== this.config.port) {
231
+ this.takeoverFailures = 0;
232
+ log("Web server port held by a non-responsive process; falling back to next port", {
233
+ previousPort: this.config.port,
234
+ newPort: nextPort,
235
+ });
236
+ this.config.port = nextPort;
237
+ }
238
+ else if (this.config.port >= this.maxFallbackPort &&
239
+ this.takeoverFailures >= MIN_FAILED_TAKEOVERS) {
240
+ // Every candidate port is held by a non-responsive process. Stop the
241
+ // health loop instead of retrying every five seconds forever.
242
+ this.stopHealthCheckLoop();
243
+ this.notifyPortsExhausted();
244
+ return;
245
+ }
246
+ try {
247
+ // Reset startPromise so _start() can run again
248
+ this.startPromise = null;
249
+ await this._start();
250
+ }
251
+ catch {
252
+ this.startHealthCheckLoop();
253
+ return;
254
+ }
255
+ if (this.isOwner) {
256
+ this.takeoverFailures = 0;
257
+ log("Web server takeover successful", { port: this.config.port });
258
+ if (this.onTakeoverCallback) {
259
+ try {
260
+ await this.onTakeoverCallback();
261
+ }
262
+ catch (error) {
263
+ log("Takeover callback error", { error: String(error) });
264
+ }
265
+ }
266
+ }
267
+ }
268
+ notifyPortsExhausted() {
269
+ if (this.portsExhaustedNotified)
270
+ return;
271
+ this.portsExhaustedNotified = true;
272
+ log("Web server unavailable: every candidate port is held by a non-responsive process", {
273
+ port: this.config.port,
274
+ maxFallbackPort: this.maxFallbackPort,
275
+ });
276
+ try {
277
+ this.onPortsExhaustedCallback?.();
278
+ }
279
+ catch (error) {
280
+ log("Ports exhausted callback error", { error: String(error) });
281
+ }
282
+ }
283
+ async stop() {
284
+ this.stopHealthCheckLoop();
285
+ if (!this.isOwner || !this.server) {
286
+ return;
287
+ }
288
+ this.server.stop();
289
+ this.server = null;
290
+ this.isOwner = false;
291
+ }
292
+ isRunning() {
293
+ return this.server !== null;
294
+ }
295
+ isServerOwner() {
296
+ return this.isOwner;
297
+ }
298
+ getUrl() {
299
+ return `http://${this.config.host}:${this.config.port}`;
300
+ }
301
+ async checkServerAvailable() {
302
+ try {
303
+ const headers = this.config.apiToken
304
+ ? { Authorization: `Bearer ${this.config.apiToken}` }
305
+ : undefined;
306
+ // With an API token, probe authenticated /api/stats?probe=1 (cheap) so we
307
+ // prove ownership without walking shards or scanning logs. Health stays
308
+ // unauthenticated and is only safe when no token is configured.
309
+ const endpoint = this.config.apiToken ? "/api/stats?probe=1" : "/api/health";
310
+ const response = await fetch(`${this.getUrl()}${endpoint}`, {
311
+ method: "GET",
312
+ headers,
313
+ signal: AbortSignal.timeout(2000),
314
+ });
315
+ if (!response.ok)
316
+ return false;
317
+ // Fallback spans 10 neighbor ports; any 2xx from an unrelated local
318
+ // service must not be mistaken for an opencode-mem owner. Require the
319
+ // response to carry our API envelope.
320
+ const body = (await response.json());
321
+ if (endpoint === "/api/health") {
322
+ return body.success === true && body.status === "ok";
323
+ }
324
+ return body.success === true;
325
+ }
326
+ catch {
327
+ return false;
328
+ }
329
+ }
330
+ // --- HTTP request handling ---
331
+ async handleRequest(req) {
332
+ const url = new URL(req.url);
333
+ const path = url.pathname;
334
+ const method = req.method;
335
+ const origin = req.headers.get("Origin");
336
+ const auth = this.config.auth;
337
+ const corsOptions = { httpAuthEnabled: auth?.isEnabled() ?? false };
338
+ if (!isAllowedBrowserOrigin(origin, corsOptions)) {
339
+ return disallowedCorsResponse();
340
+ }
341
+ if (method === "OPTIONS") {
342
+ return corsPreflightResponse(req, corsOptions);
343
+ }
344
+ if (auth?.isEnabled()) {
345
+ const authCheck = auth.check(req, path);
346
+ if (!authCheck.ok && authCheck.response)
347
+ return authCheck.response;
348
+ }
349
+ if (path.startsWith("/api/") && path !== "/api/health" && !isAuthorizedApiRequest(req)) {
350
+ const configuredTokenFailure = this.config.apiToken
351
+ ? authorizeApiRequest(req, this.config.apiToken)
352
+ : null;
353
+ if (!this.config.apiToken || configuredTokenFailure) {
354
+ return (configuredTokenFailure ??
355
+ this.jsonResponse({ success: false, error: "Unauthorized" }, 401));
356
+ }
357
+ }
358
+ try {
359
+ if (path === "/api/health" && method === "GET") {
360
+ return this.jsonResponse({
361
+ success: true,
362
+ status: "ok",
363
+ authEnabled: auth?.isEnabled() ?? false,
364
+ });
365
+ }
366
+ if (path === "/" || path === "/index.html") {
367
+ return this.serveStaticFile("index.html", "text/html");
368
+ }
369
+ if (path === "/favicon.ico") {
370
+ return this.serveStaticFile("favicon.ico", "image/x-icon");
371
+ }
372
+ // Vite production assets (hashed JS/CSS/fonts) and other static files.
373
+ if (method === "GET" && !path.startsWith("/api/")) {
374
+ const relative = path.replace(/^\/+/, "");
375
+ if (relative && !relative.includes("..")) {
376
+ const staticResponse = this.serveStaticFile(relative, this.contentTypeFor(relative));
377
+ if (staticResponse.status !== 404) {
378
+ return staticResponse;
379
+ }
380
+ }
381
+ }
382
+ if (path === "/api/tags" && method === "GET") {
383
+ const result = await handleListTags();
384
+ return this.jsonResponse(result);
385
+ }
386
+ if (path === "/api/memories" && method === "GET") {
387
+ const tags = url.searchParams.getAll("tag").filter(Boolean);
388
+ const tag = tags.length === 0 ? undefined : tags.length === 1 ? tags[0] : tags;
389
+ const page = parseInt(url.searchParams.get("page") || "1");
390
+ const pageSize = parseInt(url.searchParams.get("pageSize") || "20");
391
+ const includePrompts = url.searchParams.get("includePrompts") !== "false";
392
+ const result = await handleListMemories(tag, page, pageSize, includePrompts);
393
+ return this.jsonResponse(result);
394
+ }
395
+ if (path === "/api/memories" && method === "POST") {
396
+ const body = (await req.json());
397
+ const result = await handleAddMemory(body);
398
+ return this.jsonResponse(result);
399
+ }
400
+ if (path === "/api/memories/trash" && method === "GET") {
401
+ const limit = parseInt(url.searchParams.get("limit") || "200");
402
+ const result = await handleListTrash(limit);
403
+ return this.jsonResponse(result);
404
+ }
405
+ if (path.startsWith("/api/memories/") && path.endsWith("/restore") && method === "POST") {
406
+ const parts = path.split("/");
407
+ const id = parts[3];
408
+ if (!id || id === "trash") {
409
+ return this.jsonResponse({ success: false, error: "Invalid ID" });
410
+ }
411
+ const result = await handleRestoreMemory(id);
412
+ return this.jsonResponse(result);
413
+ }
414
+ if (path.startsWith("/api/memories/") && method === "DELETE") {
415
+ const parts = path.split("/");
416
+ const id = parts[3];
417
+ if (!id || id === "bulk-delete" || id === "trash") {
418
+ return this.jsonResponse({ success: false, error: "Invalid ID" });
419
+ }
420
+ const cascade = url.searchParams.get("cascade") === "true";
421
+ const result = await handleDeleteMemory(id, cascade);
422
+ return this.jsonResponse(result);
423
+ }
424
+ if (path.startsWith("/api/memories/") && method === "GET") {
425
+ const id = path.split("/").pop();
426
+ if (!id || id === "bulk-delete" || id === "trash") {
427
+ return this.jsonResponse({ success: false, error: "Invalid ID" });
428
+ }
429
+ const result = await handleGetMemory(id);
430
+ return this.jsonResponse(result);
431
+ }
432
+ if (path.startsWith("/api/memories/") && method === "PUT") {
433
+ const id = path.split("/").pop();
434
+ if (!id) {
435
+ return this.jsonResponse({ success: false, error: "Invalid ID" });
436
+ }
437
+ const body = (await req.json());
438
+ const result = await handleUpdateMemory(id, body);
439
+ return this.jsonResponse(result);
440
+ }
441
+ if (path === "/api/memories/bulk-delete" && method === "POST") {
442
+ const body = (await req.json());
443
+ const cascade = body.cascade !== false;
444
+ const result = await handleBulkDelete(body.ids || [], cascade);
445
+ return this.jsonResponse(result);
446
+ }
447
+ if (path === "/api/search" && method === "GET") {
448
+ const query = url.searchParams.get("q");
449
+ const tags = url.searchParams.getAll("tag").filter(Boolean);
450
+ const tag = tags.length === 0 ? undefined : tags.length === 1 ? tags[0] : tags;
451
+ const page = parseInt(url.searchParams.get("page") || "1");
452
+ const pageSize = parseInt(url.searchParams.get("pageSize") || "20");
453
+ if (!query) {
454
+ return this.jsonResponse({ success: false, error: "query parameter required" });
455
+ }
456
+ const result = await handleSearch(query, tag, page, pageSize);
457
+ return this.jsonResponse(result);
458
+ }
459
+ if (path === "/api/markdown/status" && method === "GET") {
460
+ const result = await handleMarkdownStatus();
461
+ return this.jsonResponse(result);
462
+ }
463
+ if (path === "/api/markdown/reindex" && method === "POST") {
464
+ const result = await handleMarkdownReindex();
465
+ return this.jsonResponse(result);
466
+ }
467
+ if (path === "/api/stats" && method === "GET") {
468
+ const probe = url.searchParams.get("probe") === "1";
469
+ const result = await handleStats({ probe });
470
+ return this.jsonResponse(result);
471
+ }
472
+ if (path.match(/^\/api\/memories\/[^/]+\/pin$/) && method === "POST") {
473
+ const id = path.split("/")[3];
474
+ if (!id) {
475
+ return this.jsonResponse({ success: false, error: "Invalid ID" });
476
+ }
477
+ const result = await handlePinMemory(id);
478
+ return this.jsonResponse(result);
479
+ }
480
+ if (path.match(/^\/api\/memories\/[^/]+\/unpin$/) && method === "POST") {
481
+ const id = path.split("/")[3];
482
+ if (!id) {
483
+ return this.jsonResponse({ success: false, error: "Invalid ID" });
484
+ }
485
+ const result = await handleUnpinMemory(id);
486
+ return this.jsonResponse(result);
487
+ }
488
+ if (path === "/api/cleanup" && method === "POST") {
489
+ const result = await handleRunCleanup();
490
+ return this.jsonResponse(result);
491
+ }
492
+ if (path === "/api/deduplicate" && method === "POST") {
493
+ const result = await handleRunDeduplication();
494
+ return this.jsonResponse(result);
495
+ }
496
+ if (path === "/api/dreaming/status" && method === "GET") {
497
+ const result = await handleDreamingStatus();
498
+ return this.jsonResponse(result);
499
+ }
500
+ if (path === "/api/dreaming/run" && method === "POST") {
501
+ const result = await handleRunDreaming();
502
+ if (!result.success && result.error === "already_running") {
503
+ return this.jsonResponse(result, 409);
504
+ }
505
+ return this.jsonResponse(result);
506
+ }
507
+ if (path === "/api/migration/detect" && method === "GET") {
508
+ const result = await handleDetectMigration();
509
+ return this.jsonResponse(result);
510
+ }
511
+ if (path === "/api/migration/tags/detect" && method === "GET") {
512
+ const result = await handleDetectTagMigration();
513
+ return this.jsonResponse(result);
514
+ }
515
+ if (path === "/api/migration/tags/run-batch" && method === "POST") {
516
+ const body = (await req.json());
517
+ const batchSize = body?.batchSize || 5;
518
+ const result = await handleRunTagMigrationBatch(batchSize);
519
+ return this.jsonResponse(result);
520
+ }
521
+ if (path === "/api/migration/tags/progress" && method === "GET") {
522
+ const result = await handleGetTagMigrationProgress();
523
+ return this.jsonResponse(result);
524
+ }
525
+ if (path === "/api/migration/run" && method === "POST") {
526
+ const body = (await req.json());
527
+ const strategy = body.strategy || "fresh-start";
528
+ if (strategy !== "fresh-start" && strategy !== "re-embed") {
529
+ return this.jsonResponse({ success: false, error: "Invalid strategy" });
530
+ }
531
+ const result = await handleRunMigration(strategy);
532
+ return this.jsonResponse(result);
533
+ }
534
+ if (path.startsWith("/api/prompts/") && method === "DELETE") {
535
+ const parts = path.split("/");
536
+ const id = parts[3];
537
+ if (!id || id === "bulk-delete") {
538
+ return this.jsonResponse({ success: false, error: "Invalid ID" });
539
+ }
540
+ const cascade = url.searchParams.get("cascade") === "true";
541
+ const result = await handleDeletePrompt(id, cascade);
542
+ return this.jsonResponse(result);
543
+ }
544
+ if (path === "/api/prompts/bulk-delete" && method === "POST") {
545
+ const body = (await req.json());
546
+ const cascade = body.cascade !== false;
547
+ const result = await handleBulkDeletePrompts(body.ids || [], cascade);
548
+ return this.jsonResponse(result);
549
+ }
550
+ if (path === "/api/user-profile" && method === "GET") {
551
+ const userId = url.searchParams.get("userId") || undefined;
552
+ const result = await handleGetUserProfile(userId);
553
+ return this.jsonResponse(result);
554
+ }
555
+ if (path === "/api/user-profile/changelog" && method === "GET") {
556
+ const profileId = url.searchParams.get("profileId");
557
+ const limit = parseInt(url.searchParams.get("limit") || "5");
558
+ if (!profileId) {
559
+ return this.jsonResponse({ success: false, error: "profileId parameter required" });
560
+ }
561
+ const result = await handleGetProfileChangelog(profileId, limit);
562
+ return this.jsonResponse(result);
563
+ }
564
+ if (path === "/api/user-profile/snapshot" && method === "GET") {
565
+ const changelogId = url.searchParams.get("chlogId");
566
+ if (!changelogId) {
567
+ return this.jsonResponse({ success: false, error: "changelogId parameter required" });
568
+ }
569
+ const result = await handleGetProfileSnapshot(changelogId);
570
+ return this.jsonResponse(result);
571
+ }
572
+ if (path === "/api/user-profile/refresh" && method === "POST") {
573
+ const body = (await req.json().catch(() => ({})));
574
+ const userId = body.userId || undefined;
575
+ const result = await handleRefreshProfile(userId);
576
+ return this.jsonResponse(result);
577
+ }
578
+ if (path === "/api/user-profile/ai-cleanup" && method === "POST") {
579
+ const body = (await req.json().catch(() => ({})));
580
+ const userId = body.userId || undefined;
581
+ const includeIds = Array.isArray(body.includeIds)
582
+ ? body.includeIds
583
+ : undefined;
584
+ const profileVersion = typeof body.profileVersion === "number" ? body.profileVersion : undefined;
585
+ const result = await handleAICleanup(userId, includeIds, profileVersion);
586
+ return this.jsonResponse(result);
587
+ }
588
+ if (path === "/api/user-profile/ai-cleanup/apply" && method === "POST") {
589
+ const body = (await req.json().catch(() => ({})));
590
+ const userId = body.userId || undefined;
591
+ const result = await handleApplyCleanup(userId, body);
592
+ return this.jsonResponse(result);
593
+ }
594
+ if (path === "/api/user-profile/item" && method === "PATCH") {
595
+ const body = (await req.json().catch(() => ({})));
596
+ const result = await handleUpdateProfileItem(body);
597
+ return this.jsonResponse(result);
598
+ }
599
+ if (path === "/api/skills" && method === "GET") {
600
+ const containerTag = url.searchParams.get("tag") || undefined;
601
+ const enabledOnly = url.searchParams.get("enabledOnly") === "true";
602
+ const result = await handleListSkills({ containerTag, enabledOnly });
603
+ return this.jsonResponse(result);
604
+ }
605
+ if (path === "/api/skills" && method === "POST") {
606
+ const body = (await req.json().catch(() => ({})));
607
+ const result = await handleCreateSkill(body);
608
+ return this.jsonResponse(result, result.success ? 200 : 400);
609
+ }
610
+ if (path.startsWith("/api/skills/") && method === "GET") {
611
+ const id = decodeURIComponent(path.slice("/api/skills/".length));
612
+ if (!id || id.includes("/")) {
613
+ return this.jsonResponse({ success: false, error: "Invalid skill id" }, 400);
614
+ }
615
+ const result = await handleGetSkill(id);
616
+ return this.jsonResponse(result, result.success ? 200 : 404);
617
+ }
618
+ if (path.startsWith("/api/skills/") && method === "PUT") {
619
+ const id = decodeURIComponent(path.slice("/api/skills/".length));
620
+ if (!id || id.includes("/")) {
621
+ return this.jsonResponse({ success: false, error: "Invalid skill id" }, 400);
622
+ }
623
+ const body = (await req.json().catch(() => ({})));
624
+ const result = await handleUpdateSkill(id, body);
625
+ return this.jsonResponse(result, result.success ? 200 : 400);
626
+ }
627
+ if (path.startsWith("/api/skills/") && method === "DELETE") {
628
+ const id = decodeURIComponent(path.slice("/api/skills/".length));
629
+ if (!id || id.includes("/")) {
630
+ return this.jsonResponse({ success: false, error: "Invalid skill id" }, 400);
631
+ }
632
+ const result = await handleDeleteSkill(id);
633
+ return this.jsonResponse(result, result.success ? 200 : 404);
634
+ }
635
+ // OpenCode HTTP skill catalog (public path; prefer loopback / network auth).
636
+ if (path === "/skills/index.json" && method === "GET") {
637
+ const result = await handleSkillsCatalogIndex();
638
+ if (!result.success || !result.data) {
639
+ return this.jsonResponse(result, 500);
640
+ }
641
+ return new Response(JSON.stringify(result.data), {
642
+ status: 200,
643
+ headers: { "Content-Type": "application/json; charset=utf-8" },
644
+ });
645
+ }
646
+ // OpenCode catalog layout: /skills/{id}/{id}.md
647
+ if (path.startsWith("/skills/") && path.endsWith(".md") && method === "GET") {
648
+ const rest = path.slice("/skills/".length);
649
+ const parts = rest.split("/").filter(Boolean);
650
+ if (parts.length !== 2) {
651
+ return new Response("Not Found", { status: 404 });
652
+ }
653
+ const id = decodeURIComponent(parts[0]);
654
+ const filename = decodeURIComponent(parts[1]);
655
+ if (!id || filename !== `${id}.md`) {
656
+ return new Response("Not Found", { status: 404 });
657
+ }
658
+ const result = await handleSkillsCatalogFile(id);
659
+ if (!result.success || !result.data?.markdown) {
660
+ return new Response("Not Found", { status: 404 });
661
+ }
662
+ return new Response(result.data.markdown, {
663
+ status: 200,
664
+ headers: { "Content-Type": "text/markdown; charset=utf-8" },
665
+ });
666
+ }
667
+ // SPA fallback for client routes (e.g. /profile) — serve the app shell.
668
+ if (method === "GET" && !path.startsWith("/api/") && !extname(path)) {
669
+ return this.serveStaticFile("index.html", "text/html");
670
+ }
671
+ return new Response("Not Found", { status: 404 });
672
+ }
673
+ catch (error) {
674
+ return this.jsonResponse({
675
+ success: false,
676
+ error: String(error),
677
+ }, 500);
678
+ }
679
+ }
680
+ contentTypeFor(filename) {
681
+ switch (extname(filename).toLowerCase()) {
682
+ case ".html":
683
+ return "text/html";
684
+ case ".js":
685
+ case ".mjs":
686
+ return "application/javascript";
687
+ case ".css":
688
+ return "text/css";
689
+ case ".ico":
690
+ return "image/x-icon";
691
+ case ".svg":
692
+ return "image/svg+xml";
693
+ case ".png":
694
+ return "image/png";
695
+ case ".jpg":
696
+ case ".jpeg":
697
+ return "image/jpeg";
698
+ case ".woff":
699
+ return "font/woff";
700
+ case ".woff2":
701
+ return "font/woff2";
702
+ case ".ttf":
703
+ return "font/ttf";
704
+ case ".json":
705
+ return "application/json";
706
+ case ".map":
707
+ return "application/json";
708
+ default:
709
+ return "application/octet-stream";
710
+ }
711
+ }
712
+ serveStaticFile(filename, contentType) {
713
+ try {
714
+ const webDir = [
715
+ join(__dirname, "..", "web"),
716
+ join(__dirname, "..", "..", "dist", "web"),
717
+ ].find((candidate) => existsSync(candidate));
718
+ if (!webDir) {
719
+ return new Response("File not found", { status: 404 });
720
+ }
721
+ const filePath = normalize(join(webDir, filename));
722
+ const normalizedWebDir = normalize(webDir);
723
+ if (filePath !== normalizedWebDir && !filePath.startsWith(`${normalizedWebDir}${sep}`)) {
724
+ return new Response("File not found", { status: 404 });
725
+ }
726
+ if (!existsSync(filePath)) {
727
+ return new Response("File not found", { status: 404 });
728
+ }
729
+ const cacheControl = filename.startsWith("assets/") || contentType.startsWith("font/")
730
+ ? "public, max-age=31536000, immutable"
731
+ : contentType.startsWith("image/")
732
+ ? "public, max-age=86400"
733
+ : "no-cache";
734
+ if (contentType.startsWith("image/") ||
735
+ contentType.startsWith("font/") ||
736
+ contentType === "application/octet-stream") {
737
+ const content = readFileSync(filePath);
738
+ return new Response(content, {
739
+ headers: {
740
+ "Content-Type": contentType,
741
+ "Cache-Control": cacheControl,
742
+ },
743
+ });
744
+ }
745
+ let content = readFileSync(filePath, "utf-8");
746
+ if (filename === "index.html" || filename.endsWith("/index.html")) {
747
+ const token = getOrCreateAuthToken();
748
+ content = content.replace("</head>", `<script>window.__OPENCODE_MEM_TOKEN__=${JSON.stringify(token)};</script></head>`);
749
+ }
750
+ return new Response(content, {
751
+ headers: {
752
+ "Content-Type": contentType,
753
+ "Cache-Control": cacheControl,
754
+ },
755
+ });
756
+ }
757
+ catch {
758
+ return new Response("File not found", { status: 404 });
759
+ }
760
+ }
761
+ jsonResponse(data, status = 200) {
762
+ return new Response(JSON.stringify(data), {
763
+ status,
764
+ headers: {
765
+ "Content-Type": "application/json",
766
+ },
767
+ });
768
+ }
769
+ }
770
+ export async function startWebServer(config) {
771
+ const server = new WebServer(config);
772
+ await server.start();
773
+ return server;
774
+ }