@pixelbyte-software/pixcode 1.54.10 → 1.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (534) hide show
  1. package/CODE_OF_CONDUCT.md +41 -41
  2. package/CONTRIBUTING.md +156 -156
  3. package/LICENSE +21 -718
  4. package/README.de.md +169 -169
  5. package/README.ja.md +167 -167
  6. package/README.ko.md +167 -167
  7. package/README.md +435 -418
  8. package/README.ru.md +169 -169
  9. package/README.tr.md +298 -298
  10. package/README.zh-CN.md +167 -167
  11. package/SECURITY.md +46 -46
  12. package/dist-server/server/claude-sdk.js +1 -1
  13. package/dist-server/server/claude-sdk.js.map +1 -1
  14. package/dist-server/server/cli.js +100 -100
  15. package/dist-server/server/daemon/manager.js +33 -33
  16. package/dist-server/server/daemon-manager.js +64 -64
  17. package/dist-server/server/index.js +6 -11
  18. package/dist-server/server/index.js.map +1 -1
  19. package/dist-server/server/modules/security/permission-policy.js.map +1 -0
  20. package/dist-server/server/modules/tasks/git-worktree.js +98 -0
  21. package/dist-server/server/modules/tasks/git-worktree.js.map +1 -0
  22. package/dist-server/server/modules/tasks/index.js +8 -0
  23. package/dist-server/server/modules/tasks/index.js.map +1 -0
  24. package/dist-server/server/modules/tasks/prompt-builder.js +85 -0
  25. package/dist-server/server/modules/tasks/prompt-builder.js.map +1 -0
  26. package/dist-server/server/modules/tasks/role-presets.js +94 -0
  27. package/dist-server/server/modules/tasks/role-presets.js.map +1 -0
  28. package/dist-server/server/modules/tasks/runners/claude-runner.js +109 -0
  29. package/dist-server/server/modules/tasks/runners/claude-runner.js.map +1 -0
  30. package/dist-server/server/modules/tasks/runners/codex-runner.js +67 -0
  31. package/dist-server/server/modules/tasks/runners/codex-runner.js.map +1 -0
  32. package/dist-server/server/modules/tasks/runners/spawn-runner.js +111 -0
  33. package/dist-server/server/modules/tasks/runners/spawn-runner.js.map +1 -0
  34. package/dist-server/server/modules/tasks/runners/types.js +5 -0
  35. package/dist-server/server/modules/tasks/runners/types.js.map +1 -0
  36. package/dist-server/server/modules/tasks/scheduler.js +69 -0
  37. package/dist-server/server/modules/tasks/scheduler.js.map +1 -0
  38. package/dist-server/server/modules/tasks/task-queue.js +81 -0
  39. package/dist-server/server/modules/tasks/task-queue.js.map +1 -0
  40. package/dist-server/server/modules/tasks/task-routes.js +195 -0
  41. package/dist-server/server/modules/tasks/task-routes.js.map +1 -0
  42. package/dist-server/server/modules/tasks/task-runner.js +187 -0
  43. package/dist-server/server/modules/tasks/task-runner.js.map +1 -0
  44. package/dist-server/server/modules/tasks/task-store.js +196 -0
  45. package/dist-server/server/modules/tasks/task-store.js.map +1 -0
  46. package/dist-server/server/modules/tasks/task-types.js +5 -0
  47. package/dist-server/server/modules/tasks/task-types.js.map +1 -0
  48. package/dist-server/server/modules/tasks/user-interaction.js +73 -0
  49. package/dist-server/server/modules/tasks/user-interaction.js.map +1 -0
  50. package/dist-server/server/routes/commands.js +25 -25
  51. package/dist-server/server/routes/git.js +17 -17
  52. package/dist-server/server/routes/live-view.js +46 -46
  53. package/dist-server/server/services/control-room.js +9 -1
  54. package/dist-server/server/services/control-room.js.map +1 -1
  55. package/dist-server/server/services/public-api-manifest.js +54 -54
  56. package/dist-server/server/services/public-api-manifest.js.map +1 -1
  57. package/dist-server/server/services/telegram/control-center.js +10 -10
  58. package/dist-server/server/services/telegram/control-center.js.map +1 -1
  59. package/dist-server/server/services/telegram/telegram-gateway.js +2 -2
  60. package/dist-server/server/services/telegram/telegram-gateway.js.map +1 -1
  61. package/dist-server/server/services/telegram/translations.js +5 -5
  62. package/dist-server/server/services/telegram/translations.js.map +1 -1
  63. package/package.json +224 -224
  64. package/scripts/fix-node-pty.js +67 -67
  65. package/scripts/github/create-v1.38-issues.mjs +351 -351
  66. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  67. package/scripts/smoke/backend-resource-bounds.mjs +152 -152
  68. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  69. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  70. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  71. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  72. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  73. package/scripts/smoke/chat-session-state.mjs +19 -19
  74. package/scripts/smoke/code-editor-theme.mjs +55 -55
  75. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  76. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  77. package/scripts/smoke/command-center-non-git.mjs +46 -46
  78. package/scripts/smoke/context-packet.mjs +43 -43
  79. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  80. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  81. package/scripts/smoke/default-landing-routing.mjs +33 -33
  82. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  83. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  84. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  85. package/scripts/smoke/git-install-update.mjs +255 -255
  86. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  87. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  88. package/scripts/smoke/live-view-environment.mjs +92 -92
  89. package/scripts/smoke/live-view-integration.mjs +450 -450
  90. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  91. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  92. package/scripts/smoke/mobile-ux.mjs +76 -76
  93. package/scripts/smoke/model-registry.mjs +36 -36
  94. package/scripts/smoke/multi-project-ui.mjs +45 -45
  95. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  96. package/scripts/smoke/notification-center.mjs +87 -87
  97. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  98. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  99. package/scripts/smoke/orchestration-api.mjs +172 -172
  100. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  101. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  102. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  103. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  104. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  105. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  106. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  107. package/scripts/smoke/permission-policy.mjs +50 -50
  108. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  109. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  110. package/scripts/smoke/provider-rest-api.mjs +124 -124
  111. package/scripts/smoke/provider-selection-status.mjs +52 -52
  112. package/scripts/smoke/run-state-refresh.mjs +52 -52
  113. package/scripts/smoke/runtime-manager.mjs +99 -99
  114. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  115. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  116. package/scripts/smoke/static-root-routing.mjs +21 -21
  117. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  118. package/scripts/smoke/taskmaster-config.mjs +24 -24
  119. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  120. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  121. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  122. package/scripts/smoke/telegram-control.mjs +331 -331
  123. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  124. package/scripts/smoke/update-issue-progress.mjs +69 -69
  125. package/scripts/smoke/update-ux.mjs +55 -55
  126. package/scripts/smoke/v138-completion.mjs +132 -132
  127. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  128. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  129. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  130. package/scripts/smoke/v143-remote-control.mjs +76 -76
  131. package/scripts/smoke/v144-production-loop.mjs +47 -47
  132. package/scripts/smoke/v145-platformization.mjs +46 -46
  133. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  134. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  135. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  136. package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
  137. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  138. package/scripts/smoke/workflow-templates.mjs +43 -43
  139. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  140. package/scripts/update-git-install.mjs +298 -298
  141. package/server/claude-sdk.js +927 -927
  142. package/server/cli.js +1106 -1106
  143. package/server/constants/config.js +4 -4
  144. package/server/cursor-cli.js +344 -344
  145. package/server/daemon/manager.js +563 -563
  146. package/server/daemon-manager.js +964 -964
  147. package/server/database/db.js +988 -988
  148. package/server/database/json-store.js +197 -197
  149. package/server/gemini-cli.js +550 -550
  150. package/server/gemini-response-handler.js +79 -79
  151. package/server/index.js +5654 -5671
  152. package/server/load-env.js +35 -35
  153. package/server/middleware/account-lockout.js +112 -112
  154. package/server/middleware/auth.js +277 -277
  155. package/server/middleware/rate-limiter.js +87 -87
  156. package/server/modules/providers/index.ts +2 -2
  157. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  158. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  159. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  160. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  161. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  162. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  163. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  164. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  165. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  166. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  167. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  168. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  169. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  170. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  171. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  172. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  173. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  174. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  175. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  176. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  177. package/server/modules/providers/provider.registry.ts +40 -40
  178. package/server/modules/providers/provider.routes.ts +982 -982
  179. package/server/modules/providers/services/mcp.service.ts +86 -86
  180. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  181. package/server/modules/providers/services/sessions.service.ts +45 -45
  182. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  183. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  184. package/server/modules/providers/tests/mcp.test.ts +293 -293
  185. package/server/modules/{orchestration/security → security}/permission-policy.ts +401 -401
  186. package/server/modules/tasks/git-worktree.ts +102 -0
  187. package/server/modules/tasks/index.ts +9 -0
  188. package/server/modules/tasks/prompt-builder.ts +98 -0
  189. package/server/modules/tasks/role-presets.ts +113 -0
  190. package/server/modules/tasks/runners/claude-runner.ts +120 -0
  191. package/server/modules/tasks/runners/codex-runner.ts +80 -0
  192. package/server/modules/tasks/runners/spawn-runner.ts +122 -0
  193. package/server/modules/tasks/runners/types.ts +25 -0
  194. package/server/modules/tasks/scheduler.ts +75 -0
  195. package/server/modules/tasks/task-queue.ts +91 -0
  196. package/server/modules/tasks/task-routes.ts +245 -0
  197. package/server/modules/tasks/task-runner.ts +219 -0
  198. package/server/modules/tasks/task-store.ts +223 -0
  199. package/server/modules/tasks/task-types.ts +100 -0
  200. package/server/modules/tasks/user-interaction.ts +93 -0
  201. package/server/openai-codex.js +468 -468
  202. package/server/opencode-cli.js +491 -491
  203. package/server/opencode-response-handler.js +111 -111
  204. package/server/projects.js +3135 -3135
  205. package/server/qwen-code-cli.js +410 -410
  206. package/server/routes/agent.js +1462 -1462
  207. package/server/routes/auth.js +298 -298
  208. package/server/routes/codex.js +20 -20
  209. package/server/routes/commands.js +581 -581
  210. package/server/routes/cursor.js +61 -61
  211. package/server/routes/diagnostics.js +44 -44
  212. package/server/routes/gemini.js +25 -25
  213. package/server/routes/git.js +1822 -1822
  214. package/server/routes/live-view.js +434 -434
  215. package/server/routes/mcp-utils.js +13 -13
  216. package/server/routes/messages.js +97 -97
  217. package/server/routes/network.js +143 -143
  218. package/server/routes/platformization.js +231 -231
  219. package/server/routes/plugins.js +690 -690
  220. package/server/routes/production-agent-loop.js +90 -90
  221. package/server/routes/projects.js +918 -918
  222. package/server/routes/public-api.js +34 -34
  223. package/server/routes/qwen.js +27 -27
  224. package/server/routes/remote.js +56 -56
  225. package/server/routes/settings.js +321 -321
  226. package/server/routes/telegram.js +163 -163
  227. package/server/routes/user.js +125 -125
  228. package/server/routes/webhooks.js +63 -63
  229. package/server/services/control-room.js +111 -102
  230. package/server/services/diagnostics.js +165 -165
  231. package/server/services/external-access.js +403 -403
  232. package/server/services/install-jobs.js +715 -715
  233. package/server/services/live-view.js +956 -956
  234. package/server/services/managed-runtimes.js +493 -493
  235. package/server/services/model-registry.js +144 -144
  236. package/server/services/notification-orchestrator.js +365 -365
  237. package/server/services/notification-taxonomy.js +204 -204
  238. package/server/services/platformization.js +1052 -1052
  239. package/server/services/production-agent-loop.js +248 -248
  240. package/server/services/provider-cli-versions.js +149 -149
  241. package/server/services/provider-credentials.js +189 -189
  242. package/server/services/provider-models.js +396 -396
  243. package/server/services/public-api-manifest.js +181 -181
  244. package/server/services/qr-login.js +126 -126
  245. package/server/services/remote-connection.js +127 -127
  246. package/server/services/runtime-manager.js +323 -323
  247. package/server/services/startup-update.js +259 -259
  248. package/server/services/telegram/bot.js +393 -393
  249. package/server/services/telegram/control-center.js +2453 -2453
  250. package/server/services/telegram/telegram-gateway.js +314 -314
  251. package/server/services/telegram/telegram-http-client.js +201 -201
  252. package/server/services/telegram/translations.js +470 -470
  253. package/server/services/webhooks.js +216 -216
  254. package/server/sessionManager.js +225 -225
  255. package/server/setup-wizard.js +283 -283
  256. package/server/shared/interfaces.ts +54 -54
  257. package/server/shared/types.ts +172 -172
  258. package/server/shared/utils.ts +193 -193
  259. package/server/tsconfig.json +36 -36
  260. package/server/utils/colors.js +21 -21
  261. package/server/utils/commandParser.js +305 -305
  262. package/server/utils/frontmatter.js +18 -18
  263. package/server/utils/gitConfig.js +34 -34
  264. package/server/utils/plugin-loader.js +461 -461
  265. package/server/utils/plugin-process-manager.js +185 -185
  266. package/server/utils/port-access.js +227 -227
  267. package/server/utils/runtime-paths.js +37 -37
  268. package/server/utils/security-log.js +84 -84
  269. package/server/utils/url-detection.js +71 -71
  270. package/server/vite-daemon.js +79 -79
  271. package/shared/modelConstants.js +161 -161
  272. package/shared/networkHosts.js +22 -22
  273. package/dist/api-automation.html +0 -110
  274. package/dist/api-docs.html +0 -548
  275. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  276. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  277. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  278. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  279. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  280. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  281. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  282. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  283. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  284. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  285. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  286. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  287. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  288. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  289. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  290. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  291. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  292. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  293. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  294. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  295. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  296. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  297. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  298. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  299. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  300. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  301. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  302. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  303. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  304. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  305. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  306. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  307. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  308. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  309. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  310. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  311. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  312. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  313. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  314. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  315. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  316. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  317. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  318. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  319. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  320. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  321. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  322. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  323. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  324. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  325. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  326. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  327. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  328. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  329. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  330. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  331. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  332. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  333. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  334. package/dist/assets/index-DWOW_Jn0.js +0 -877
  335. package/dist/assets/index-Dz1luE0u.css +0 -32
  336. package/dist/assets/index-ak1p_4ew.js +0 -11
  337. package/dist/assets/localMonaco-DFIbtDNp.js +0 -1
  338. package/dist/assets/vendor-codemirror-CIYNS698.js +0 -41
  339. package/dist/assets/vendor-react-DB6V5Fl1.js +0 -59
  340. package/dist/assets/vendor-xterm-C7tpxJl7.js +0 -9
  341. package/dist/clear-cache.html +0 -85
  342. package/dist/convert-icons.md +0 -53
  343. package/dist/docs.html +0 -308
  344. package/dist/favicon.png +0 -0
  345. package/dist/favicon.svg +0 -8
  346. package/dist/features.html +0 -133
  347. package/dist/generate-icons.js +0 -49
  348. package/dist/humans.txt +0 -15
  349. package/dist/icons/claude-ai-icon.svg +0 -1
  350. package/dist/icons/codex-white.svg +0 -3
  351. package/dist/icons/codex.svg +0 -3
  352. package/dist/icons/cursor-white.svg +0 -12
  353. package/dist/icons/cursor.svg +0 -1
  354. package/dist/icons/gemini-ai-icon.svg +0 -1
  355. package/dist/icons/icon-128x128.png +0 -0
  356. package/dist/icons/icon-128x128.svg +0 -9
  357. package/dist/icons/icon-144x144.png +0 -0
  358. package/dist/icons/icon-144x144.svg +0 -9
  359. package/dist/icons/icon-152x152.png +0 -0
  360. package/dist/icons/icon-152x152.svg +0 -9
  361. package/dist/icons/icon-192x192.png +0 -0
  362. package/dist/icons/icon-192x192.svg +0 -9
  363. package/dist/icons/icon-384x384.png +0 -0
  364. package/dist/icons/icon-384x384.svg +0 -9
  365. package/dist/icons/icon-512x512.png +0 -0
  366. package/dist/icons/icon-512x512.svg +0 -9
  367. package/dist/icons/icon-72x72.png +0 -0
  368. package/dist/icons/icon-72x72.svg +0 -9
  369. package/dist/icons/icon-96x96.png +0 -0
  370. package/dist/icons/icon-96x96.svg +0 -9
  371. package/dist/icons/icon-template.svg +0 -9
  372. package/dist/icons/opencode-logo-dark.svg +0 -1
  373. package/dist/icons/opencode-logo-light.svg +0 -1
  374. package/dist/icons/qwen-ai-icon.png +0 -0
  375. package/dist/icons/qwen-logo.svg +0 -15
  376. package/dist/index.html +0 -62
  377. package/dist/landing.html +0 -268
  378. package/dist/llms-full.txt +0 -119
  379. package/dist/llms.txt +0 -53
  380. package/dist/logo-128.png +0 -0
  381. package/dist/logo-256.png +0 -0
  382. package/dist/logo-32.png +0 -0
  383. package/dist/logo-512.png +0 -0
  384. package/dist/logo-64.png +0 -0
  385. package/dist/logo.png +0 -0
  386. package/dist/logo.svg +0 -12
  387. package/dist/manifest.json +0 -61
  388. package/dist/openapi.yaml +0 -1696
  389. package/dist/orchestration.html +0 -125
  390. package/dist/robots.txt +0 -4
  391. package/dist/screenshots/cli-selection.png +0 -0
  392. package/dist/screenshots/desktop-main.png +0 -0
  393. package/dist/screenshots/mobile-chat.png +0 -0
  394. package/dist/screenshots/tools-modal.png +0 -0
  395. package/dist/site.css +0 -692
  396. package/dist/sitemap.xml +0 -51
  397. package/dist/sw.js +0 -132
  398. package/dist-server/server/modules/orchestration/a2a/adapter-registry.js +0 -73
  399. package/dist-server/server/modules/orchestration/a2a/adapter-registry.js.map +0 -1
  400. package/dist-server/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.js +0 -17
  401. package/dist-server/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.js.map +0 -1
  402. package/dist-server/server/modules/orchestration/a2a/adapters/claude-code.adapter.js +0 -236
  403. package/dist-server/server/modules/orchestration/a2a/adapters/claude-code.adapter.js.map +0 -1
  404. package/dist-server/server/modules/orchestration/a2a/adapters/codex.adapter.js +0 -202
  405. package/dist-server/server/modules/orchestration/a2a/adapters/codex.adapter.js.map +0 -1
  406. package/dist-server/server/modules/orchestration/a2a/adapters/cursor.adapter.js +0 -205
  407. package/dist-server/server/modules/orchestration/a2a/adapters/cursor.adapter.js.map +0 -1
  408. package/dist-server/server/modules/orchestration/a2a/adapters/gemini.adapter.js +0 -205
  409. package/dist-server/server/modules/orchestration/a2a/adapters/gemini.adapter.js.map +0 -1
  410. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.js +0 -84
  411. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.js.map +0 -1
  412. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.test.js +0 -43
  413. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.test.js.map +0 -1
  414. package/dist-server/server/modules/orchestration/a2a/adapters/opencode.adapter.js +0 -205
  415. package/dist-server/server/modules/orchestration/a2a/adapters/opencode.adapter.js.map +0 -1
  416. package/dist-server/server/modules/orchestration/a2a/adapters/qwen.adapter.js +0 -205
  417. package/dist-server/server/modules/orchestration/a2a/adapters/qwen.adapter.js.map +0 -1
  418. package/dist-server/server/modules/orchestration/a2a/agent-card.js +0 -50
  419. package/dist-server/server/modules/orchestration/a2a/agent-card.js.map +0 -1
  420. package/dist-server/server/modules/orchestration/a2a/auth.middleware.js +0 -25
  421. package/dist-server/server/modules/orchestration/a2a/auth.middleware.js.map +0 -1
  422. package/dist-server/server/modules/orchestration/a2a/bus.js +0 -34
  423. package/dist-server/server/modules/orchestration/a2a/bus.js.map +0 -1
  424. package/dist-server/server/modules/orchestration/a2a/routes.js +0 -502
  425. package/dist-server/server/modules/orchestration/a2a/routes.js.map +0 -1
  426. package/dist-server/server/modules/orchestration/a2a/task-dispatcher.js +0 -295
  427. package/dist-server/server/modules/orchestration/a2a/task-dispatcher.js.map +0 -1
  428. package/dist-server/server/modules/orchestration/a2a/task-store.js +0 -144
  429. package/dist-server/server/modules/orchestration/a2a/task-store.js.map +0 -1
  430. package/dist-server/server/modules/orchestration/a2a/types.js +0 -6
  431. package/dist-server/server/modules/orchestration/a2a/types.js.map +0 -1
  432. package/dist-server/server/modules/orchestration/a2a/validator.js +0 -101
  433. package/dist-server/server/modules/orchestration/a2a/validator.js.map +0 -1
  434. package/dist-server/server/modules/orchestration/index.js +0 -27
  435. package/dist-server/server/modules/orchestration/index.js.map +0 -1
  436. package/dist-server/server/modules/orchestration/preview/port-watcher.js +0 -90
  437. package/dist-server/server/modules/orchestration/preview/port-watcher.js.map +0 -1
  438. package/dist-server/server/modules/orchestration/preview/preview-proxy.js +0 -58
  439. package/dist-server/server/modules/orchestration/preview/preview-proxy.js.map +0 -1
  440. package/dist-server/server/modules/orchestration/preview/types.js +0 -2
  441. package/dist-server/server/modules/orchestration/preview/types.js.map +0 -1
  442. package/dist-server/server/modules/orchestration/security/permission-policy.js.map +0 -1
  443. package/dist-server/server/modules/orchestration/tasks/orchestration-task-store.js +0 -34
  444. package/dist-server/server/modules/orchestration/tasks/orchestration-task-store.js.map +0 -1
  445. package/dist-server/server/modules/orchestration/tasks/orchestration-task.routes.js +0 -70
  446. package/dist-server/server/modules/orchestration/tasks/orchestration-task.routes.js.map +0 -1
  447. package/dist-server/server/modules/orchestration/tasks/orchestration-task.service.js +0 -181
  448. package/dist-server/server/modules/orchestration/tasks/orchestration-task.service.js.map +0 -1
  449. package/dist-server/server/modules/orchestration/tasks/orchestration-task.types.js +0 -2
  450. package/dist-server/server/modules/orchestration/tasks/orchestration-task.types.js.map +0 -1
  451. package/dist-server/server/modules/orchestration/tasks/task-run-graph.js +0 -100
  452. package/dist-server/server/modules/orchestration/tasks/task-run-graph.js.map +0 -1
  453. package/dist-server/server/modules/orchestration/workflows/approval-queue.js +0 -72
  454. package/dist-server/server/modules/orchestration/workflows/approval-queue.js.map +0 -1
  455. package/dist-server/server/modules/orchestration/workflows/built-in-workflows.js +0 -126
  456. package/dist-server/server/modules/orchestration/workflows/built-in-workflows.js.map +0 -1
  457. package/dist-server/server/modules/orchestration/workflows/context-packet.js +0 -89
  458. package/dist-server/server/modules/orchestration/workflows/context-packet.js.map +0 -1
  459. package/dist-server/server/modules/orchestration/workflows/handoff-artifact.js +0 -123
  460. package/dist-server/server/modules/orchestration/workflows/handoff-artifact.js.map +0 -1
  461. package/dist-server/server/modules/orchestration/workflows/workflow-fallback-policy.js +0 -114
  462. package/dist-server/server/modules/orchestration/workflows/workflow-fallback-policy.js.map +0 -1
  463. package/dist-server/server/modules/orchestration/workflows/workflow-replay.js +0 -177
  464. package/dist-server/server/modules/orchestration/workflows/workflow-replay.js.map +0 -1
  465. package/dist-server/server/modules/orchestration/workflows/workflow-runner.js +0 -1718
  466. package/dist-server/server/modules/orchestration/workflows/workflow-runner.js.map +0 -1
  467. package/dist-server/server/modules/orchestration/workflows/workflow-store.js +0 -76
  468. package/dist-server/server/modules/orchestration/workflows/workflow-store.js.map +0 -1
  469. package/dist-server/server/modules/orchestration/workflows/workflow-templates.js +0 -242
  470. package/dist-server/server/modules/orchestration/workflows/workflow-templates.js.map +0 -1
  471. package/dist-server/server/modules/orchestration/workflows/workflow-trace.js +0 -388
  472. package/dist-server/server/modules/orchestration/workflows/workflow-trace.js.map +0 -1
  473. package/dist-server/server/modules/orchestration/workflows/workflow.routes.js +0 -508
  474. package/dist-server/server/modules/orchestration/workflows/workflow.routes.js.map +0 -1
  475. package/dist-server/server/modules/orchestration/workflows/workflow.types.js +0 -2
  476. package/dist-server/server/modules/orchestration/workflows/workflow.types.js.map +0 -1
  477. package/dist-server/server/modules/orchestration/workflows/workspace-target.js +0 -100
  478. package/dist-server/server/modules/orchestration/workflows/workspace-target.js.map +0 -1
  479. package/dist-server/server/modules/orchestration/workspace/docker-workspace.js +0 -123
  480. package/dist-server/server/modules/orchestration/workspace/docker-workspace.js.map +0 -1
  481. package/dist-server/server/modules/orchestration/workspace/path-safety.js +0 -48
  482. package/dist-server/server/modules/orchestration/workspace/path-safety.js.map +0 -1
  483. package/dist-server/server/modules/orchestration/workspace/types.js +0 -11
  484. package/dist-server/server/modules/orchestration/workspace/types.js.map +0 -1
  485. package/dist-server/server/modules/orchestration/workspace/workspace-manager.js +0 -84
  486. package/dist-server/server/modules/orchestration/workspace/workspace-manager.js.map +0 -1
  487. package/dist-server/server/modules/orchestration/workspace/worktree-workspace.js +0 -97
  488. package/dist-server/server/modules/orchestration/workspace/worktree-workspace.js.map +0 -1
  489. package/server/modules/orchestration/a2a/adapter-registry.ts +0 -108
  490. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +0 -63
  491. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +0 -286
  492. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +0 -244
  493. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +0 -249
  494. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +0 -248
  495. package/server/modules/orchestration/a2a/adapters/json-event.adapter.test.ts +0 -60
  496. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +0 -101
  497. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +0 -248
  498. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +0 -248
  499. package/server/modules/orchestration/a2a/agent-card.ts +0 -55
  500. package/server/modules/orchestration/a2a/auth.middleware.ts +0 -29
  501. package/server/modules/orchestration/a2a/bus.ts +0 -46
  502. package/server/modules/orchestration/a2a/routes.ts +0 -586
  503. package/server/modules/orchestration/a2a/task-dispatcher.ts +0 -345
  504. package/server/modules/orchestration/a2a/task-store.ts +0 -178
  505. package/server/modules/orchestration/a2a/types.ts +0 -126
  506. package/server/modules/orchestration/a2a/validator.ts +0 -113
  507. package/server/modules/orchestration/index.ts +0 -99
  508. package/server/modules/orchestration/preview/port-watcher.ts +0 -112
  509. package/server/modules/orchestration/preview/preview-proxy.ts +0 -60
  510. package/server/modules/orchestration/preview/types.ts +0 -19
  511. package/server/modules/orchestration/tasks/orchestration-task-store.ts +0 -41
  512. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +0 -81
  513. package/server/modules/orchestration/tasks/orchestration-task.service.ts +0 -201
  514. package/server/modules/orchestration/tasks/orchestration-task.types.ts +0 -40
  515. package/server/modules/orchestration/tasks/task-run-graph.ts +0 -155
  516. package/server/modules/orchestration/workflows/approval-queue.ts +0 -106
  517. package/server/modules/orchestration/workflows/built-in-workflows.ts +0 -127
  518. package/server/modules/orchestration/workflows/context-packet.ts +0 -186
  519. package/server/modules/orchestration/workflows/handoff-artifact.ts +0 -175
  520. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +0 -161
  521. package/server/modules/orchestration/workflows/workflow-replay.ts +0 -254
  522. package/server/modules/orchestration/workflows/workflow-runner.ts +0 -2062
  523. package/server/modules/orchestration/workflows/workflow-store.ts +0 -97
  524. package/server/modules/orchestration/workflows/workflow-templates.ts +0 -272
  525. package/server/modules/orchestration/workflows/workflow-trace.ts +0 -424
  526. package/server/modules/orchestration/workflows/workflow.routes.ts +0 -586
  527. package/server/modules/orchestration/workflows/workflow.types.ts +0 -111
  528. package/server/modules/orchestration/workflows/workspace-target.ts +0 -122
  529. package/server/modules/orchestration/workspace/docker-workspace.ts +0 -136
  530. package/server/modules/orchestration/workspace/path-safety.ts +0 -55
  531. package/server/modules/orchestration/workspace/types.ts +0 -52
  532. package/server/modules/orchestration/workspace/workspace-manager.ts +0 -102
  533. package/server/modules/orchestration/workspace/worktree-workspace.ts +0 -126
  534. /package/dist-server/server/modules/{orchestration/security → security}/permission-policy.js +0 -0
@@ -1,988 +1,988 @@
1
- import crypto from 'node:crypto';
2
- import fs from 'node:fs';
3
- import { createRequire } from 'node:module';
4
- import path from 'node:path';
5
-
6
- import { findAppRoot, getModuleDir } from '../utils/runtime-paths.js';
7
-
8
- import { JsonStore, nowIso } from './json-store.js';
9
-
10
- // CommonJS `require` shim — we only reach for it once, during the
11
- // legacy-to-JSON migration below, to dynamically import better-sqlite3
12
- // only when an old auth.db is actually present on disk.
13
- const require = createRequire(import.meta.url);
14
-
15
- const __dirname = getModuleDir(import.meta.url);
16
- // The compiled backend lives under dist-server/server/database, but the install root we log
17
- // should still point at the project/app root. Resolving it here avoids build-layout drift.
18
- const APP_ROOT = findAppRoot(__dirname);
19
-
20
- // ANSI color codes for terminal output
21
- const colors = {
22
- reset: '\x1b[0m',
23
- bright: '\x1b[1m',
24
- cyan: '\x1b[36m',
25
- dim: '\x1b[2m',
26
- };
27
-
28
- const c = {
29
- info: (text) => `${colors.cyan}${text}${colors.reset}`,
30
- bright: (text) => `${colors.bright}${text}${colors.reset}`,
31
- dim: (text) => `${colors.dim}${text}${colors.reset}`,
32
- };
33
-
34
- // DATABASE_PATH keeps its historical meaning (user override), but points
35
- // at a `.json` file now. If the user's env var still names a `.db`
36
- // extension, we swap to the corresponding `.json` sibling — the auth
37
- // store moved off SQLite in v1.33.0.
38
- const rawDbPath = process.env.DATABASE_PATH || path.join(__dirname, 'auth.db');
39
- const JSON_PATH = rawDbPath.endsWith('.db')
40
- ? rawDbPath.replace(/\.db$/, '.json')
41
- : (rawDbPath.endsWith('.json') ? rawDbPath : `${rawDbPath}.json`);
42
- const LEGACY_SQLITE_PATH = rawDbPath.endsWith('.db')
43
- ? rawDbPath
44
- : rawDbPath.replace(/\.json$/, '.db');
45
-
46
- // Ensure parent dir exists before migration / initial write.
47
- {
48
- const dir = path.dirname(JSON_PATH);
49
- if (!fs.existsSync(dir)) {
50
- try { fs.mkdirSync(dir, { recursive: true }); }
51
- catch (err) {
52
- console.error(`Failed to create database directory ${dir}:`, err.message);
53
- throw err;
54
- }
55
- }
56
- }
57
-
58
- /**
59
- * One-time migration from the previous better-sqlite3 auth.db to the
60
- * new JSON format. Triggered only when:
61
- * - The legacy .db exists
62
- * - AND no .json has been created yet
63
- * The legacy file is kept in place as `<name>.db.migrated-<timestamp>`
64
- * so a user can roll back by moving it into place and reinstalling
65
- * better-sqlite3 if they hit a showstopper. Runs synchronously because
66
- * all downstream modules (auth.js, vapid-keys.js) import `db` at module
67
- * load and can't wait for async startup.
68
- */
69
- function migrateSqliteIfPresent() {
70
- if (fs.existsSync(JSON_PATH)) return; // Already migrated or fresh install.
71
- if (!fs.existsSync(LEGACY_SQLITE_PATH)) return; // Nothing to migrate.
72
-
73
- console.log(`${c.info('[MIGRATION]')} Converting ${c.bright(LEGACY_SQLITE_PATH)} → ${c.bright(JSON_PATH)} (JSON auth store, v1.33.0)`);
74
-
75
- let Database;
76
- try {
77
- const mod = require('better-sqlite3');
78
- Database = mod.default || mod;
79
- } catch {
80
- // Auto-install path fell through — the user has a legacy file but
81
- // better-sqlite3 isn't present (they may have a trimmed dep tree).
82
- // Surface a clear error; we'd rather fail startup than silently
83
- // skip migration and strand the user's saved credentials.
84
- console.error('[MIGRATION] Legacy auth.db present but better-sqlite3 not installed.');
85
- console.error('[MIGRATION] Install it once to migrate: `npm install better-sqlite3` in your pixcode install dir, then restart.');
86
- throw new Error('Auth DB migration requires better-sqlite3 (legacy file detected).');
87
- }
88
-
89
- const legacy = new Database(LEGACY_SQLITE_PATH, { readonly: true });
90
- const store = new JsonStore(JSON_PATH);
91
-
92
- // Pull every table, skipping silently when it doesn't exist (old
93
- // installs that never ran some migrations). We rely on `IF NOT EXISTS`
94
- // patterns from the old schema.js — missing tables throw a SQLite
95
- // error which we catch per-table.
96
- const safeAll = (sql) => {
97
- try { return legacy.prepare(sql).all(); } catch { return []; }
98
- };
99
-
100
- const users = safeAll('SELECT id, username, password_hash, created_at, last_login, is_active, git_name, git_email, has_completed_onboarding FROM users');
101
- for (const u of users) {
102
- store.raw.users.push({
103
- id: u.id,
104
- username: u.username,
105
- password_hash: u.password_hash,
106
- created_at: u.created_at || nowIso(),
107
- last_login: u.last_login || null,
108
- is_active: u.is_active !== 0,
109
- git_name: u.git_name || null,
110
- git_email: u.git_email || null,
111
- has_completed_onboarding: u.has_completed_onboarding === 1,
112
- });
113
- store.raw._sequences.users = Math.max(store.raw._sequences.users, u.id);
114
- }
115
-
116
- const apiKeys = safeAll('SELECT id, user_id, key_name, api_key, created_at, last_used, is_active FROM api_keys');
117
- for (const k of apiKeys) {
118
- store.raw.api_keys.push({
119
- id: k.id,
120
- user_id: k.user_id,
121
- key_name: k.key_name,
122
- api_key: k.api_key,
123
- created_at: k.created_at || nowIso(),
124
- last_used: k.last_used || null,
125
- is_active: k.is_active !== 0,
126
- });
127
- store.raw._sequences.api_keys = Math.max(store.raw._sequences.api_keys, k.id);
128
- }
129
-
130
- const credentials = safeAll('SELECT id, user_id, credential_name, credential_type, credential_value, description, created_at, is_active FROM user_credentials');
131
- for (const cr of credentials) {
132
- store.raw.user_credentials.push({
133
- id: cr.id,
134
- user_id: cr.user_id,
135
- credential_name: cr.credential_name,
136
- credential_type: cr.credential_type,
137
- credential_value: cr.credential_value,
138
- description: cr.description || null,
139
- created_at: cr.created_at || nowIso(),
140
- is_active: cr.is_active !== 0,
141
- });
142
- store.raw._sequences.user_credentials = Math.max(store.raw._sequences.user_credentials, cr.id);
143
- }
144
-
145
- const prefs = safeAll('SELECT user_id, preferences_json, updated_at FROM user_notification_preferences');
146
- for (const p of prefs) {
147
- store.raw.user_notification_preferences.push({
148
- user_id: p.user_id,
149
- preferences_json: p.preferences_json,
150
- updated_at: p.updated_at || nowIso(),
151
- });
152
- }
153
-
154
- const vapid = safeAll('SELECT id, public_key, private_key, created_at FROM vapid_keys');
155
- for (const v of vapid) {
156
- store.raw.vapid_keys.push({
157
- id: v.id,
158
- public_key: v.public_key,
159
- private_key: v.private_key,
160
- created_at: v.created_at || nowIso(),
161
- });
162
- store.raw._sequences.vapid_keys = Math.max(store.raw._sequences.vapid_keys, v.id);
163
- }
164
-
165
- const pushSubs = safeAll('SELECT id, user_id, endpoint, keys_p256dh, keys_auth, created_at FROM push_subscriptions');
166
- for (const s of pushSubs) {
167
- store.raw.push_subscriptions.push({
168
- id: s.id,
169
- user_id: s.user_id,
170
- endpoint: s.endpoint,
171
- keys_p256dh: s.keys_p256dh,
172
- keys_auth: s.keys_auth,
173
- created_at: s.created_at || nowIso(),
174
- });
175
- store.raw._sequences.push_subscriptions = Math.max(store.raw._sequences.push_subscriptions, s.id);
176
- }
177
-
178
- const sessionNames = safeAll('SELECT session_id, provider, custom_name, created_at, updated_at FROM session_names');
179
- for (const sn of sessionNames) {
180
- store.raw.session_names.push({
181
- session_id: sn.session_id,
182
- provider: sn.provider,
183
- custom_name: sn.custom_name,
184
- created_at: sn.created_at || nowIso(),
185
- updated_at: sn.updated_at || nowIso(),
186
- });
187
- }
188
-
189
- const appConfig = safeAll('SELECT key, value, created_at FROM app_config');
190
- for (const a of appConfig) {
191
- store.raw.app_config.push({
192
- key: a.key,
193
- value: a.value,
194
- created_at: a.created_at || nowIso(),
195
- });
196
- }
197
-
198
- const telegramConfig = safeAll('SELECT id, bot_token, bot_username, updated_at FROM telegram_config');
199
- for (const t of telegramConfig) {
200
- store.raw.telegram_config.push({
201
- id: 1,
202
- bot_token: t.bot_token,
203
- bot_username: t.bot_username || null,
204
- updated_at: t.updated_at || nowIso(),
205
- });
206
- }
207
-
208
- const telegramLinks = safeAll('SELECT user_id, chat_id, telegram_username, language, pairing_code, pairing_code_expires_at, verified_at, notifications_enabled, bridge_enabled, updated_at FROM telegram_links');
209
- for (const tl of telegramLinks) {
210
- store.raw.telegram_links.push({
211
- user_id: tl.user_id,
212
- chat_id: tl.chat_id || null,
213
- telegram_username: tl.telegram_username || null,
214
- language: tl.language || 'en',
215
- pairing_code: tl.pairing_code || null,
216
- pairing_code_expires_at: tl.pairing_code_expires_at || null,
217
- verified_at: tl.verified_at || null,
218
- notifications_enabled: tl.notifications_enabled !== 0,
219
- bridge_enabled: tl.bridge_enabled !== 0,
220
- telegram_control: null,
221
- updated_at: tl.updated_at || nowIso(),
222
- });
223
- }
224
-
225
- store.save();
226
- legacy.close();
227
-
228
- // Rename the old .db out of the way so we never migrate it twice.
229
- // Keep it (not delete) so the user can roll back if needed.
230
- const backup = `${LEGACY_SQLITE_PATH}.migrated-${Date.now()}`;
231
- try {
232
- fs.renameSync(LEGACY_SQLITE_PATH, backup);
233
- for (const suffix of ['-wal', '-shm']) {
234
- if (fs.existsSync(LEGACY_SQLITE_PATH + suffix)) {
235
- try { fs.renameSync(LEGACY_SQLITE_PATH + suffix, backup + suffix); } catch { /* noop */ }
236
- }
237
- }
238
- } catch (err) {
239
- console.warn(`[MIGRATION] Migration succeeded but could not rename old DB: ${err.message}`);
240
- }
241
-
242
- console.log(`${c.info('[MIGRATION]')} Migration complete. Old DB preserved as ${c.dim(backup)}.`);
243
- }
244
-
245
- // Module-load order matters — auth middleware imports `db` and reads the
246
- // JWT secret before anything else gets to boot. So the store has to be
247
- // ready synchronously at the first `import { db } from './db.js'`.
248
- migrateSqliteIfPresent();
249
-
250
- const store = new JsonStore(JSON_PATH);
251
-
252
- console.log('');
253
- console.log(c.dim('═'.repeat(60)));
254
- console.log(`${c.info('[INFO]')} App Installation: ${c.bright(APP_ROOT)}`);
255
- console.log(`${c.info('[INFO]')} Auth store: ${c.dim(path.relative(APP_ROOT, JSON_PATH))}`);
256
- if (process.env.DATABASE_PATH) {
257
- console.log(` ${c.dim('(Using custom DATABASE_PATH from environment)')}`);
258
- }
259
- console.log(c.dim('═'.repeat(60)));
260
- console.log('');
261
-
262
- // initializeDatabase used to run `CREATE TABLE IF NOT EXISTS` + migrations.
263
- // The JSON store always has its shape pre-baked, so this is a no-op —
264
- // keeping the export preserves the server boot sequence.
265
- const initializeDatabase = async () => { /* schema lives in code, not in file */ };
266
-
267
- // ---------------------------------------------------------------------------
268
- // Back-compat `db` shim — a few modules outside database/db.js imported `db`
269
- // and called `db.prepare(sql)` directly. Most of those uses were for trivial
270
- // transaction markers (BEGIN/COMMIT/ROLLBACK — no-op under our JSON store)
271
- // or very specific SELECTs we've wrapped in explicit helpers. This shim
272
- // lets those call sites keep working without a bigger refactor.
273
- // ---------------------------------------------------------------------------
274
- const db = {
275
- prepare(sql) {
276
- const normalized = sql.trim().toUpperCase();
277
- // Transaction markers — our store writes atomically per op, so
278
- // there's no real transaction to start. No-op + success result.
279
- if (normalized === 'BEGIN' || normalized === 'COMMIT' || normalized === 'ROLLBACK') {
280
- return {
281
- run: () => ({ changes: 0, lastInsertRowid: 0 }),
282
- };
283
- }
284
-
285
- // Specific query routed through the new helpers — used by
286
- // server/routes/projects.js to fetch a single github credential.
287
- if (/FROM USER_CREDENTIALS\s+WHERE ID = \?\s+AND USER_ID = \?\s+AND CREDENTIAL_TYPE = \?\s+AND IS_ACTIVE = 1/.test(normalized)) {
288
- return {
289
- get: (id, userId, credentialType) =>
290
- store.findWhere('user_credentials',
291
- (r) => r.id === id && r.user_id === userId && r.credential_type === credentialType && r.is_active)
292
- || undefined,
293
- };
294
- }
295
-
296
- throw new Error(
297
- `db.prepare: unsupported SQL passed through the compat shim: ${sql.slice(0, 80)}`
298
- + '\nExtend server/database/db.js or use a dedicated helper (userDb, credentialsDb, …).',
299
- );
300
- },
301
- };
302
-
303
- // ---------------------------------------------------------------------------
304
- // User operations
305
- // ---------------------------------------------------------------------------
306
- const userDb = {
307
- hasUsers: () => store.count('users', (r) => r.is_active) > 0,
308
-
309
- listUsers: () => store.raw.users.map((row) => ({
310
- id: row.id,
311
- username: row.username,
312
- created_at: row.created_at,
313
- last_login: row.last_login,
314
- is_active: Boolean(row.is_active),
315
- git_name: row.git_name || null,
316
- git_email: row.git_email || null,
317
- has_completed_onboarding: Boolean(row.has_completed_onboarding),
318
- role: row.role || null,
319
- })),
320
-
321
- createUser: (username, passwordHash, metadata = {}) => {
322
- const row = store.insert('users', {
323
- username,
324
- password_hash: passwordHash,
325
- created_at: nowIso(),
326
- last_login: null,
327
- is_active: true,
328
- git_name: null,
329
- git_email: null,
330
- has_completed_onboarding: false,
331
- role: metadata.role || 'admin',
332
- });
333
- return { id: row.id, username: row.username, role: row.role || 'admin' };
334
- },
335
-
336
- createManagedUser: (username, passwordHash, metadata = {}) => {
337
- const existing = store.raw.users.find((r) => r.username === username);
338
- if (existing) {
339
- throw new Error('Username already exists.');
340
- }
341
-
342
- const row = store.insert('users', {
343
- username,
344
- password_hash: passwordHash,
345
- created_at: nowIso(),
346
- last_login: null,
347
- is_active: metadata.is_active !== false,
348
- git_name: metadata.git_name || null,
349
- git_email: metadata.git_email || null,
350
- has_completed_onboarding: false,
351
- role: metadata.role || 'member',
352
- });
353
- return {
354
- id: row.id,
355
- username: row.username,
356
- created_at: row.created_at,
357
- last_login: row.last_login,
358
- is_active: Boolean(row.is_active),
359
- role: row.role || 'member',
360
- };
361
- },
362
-
363
- getUserByUsername: (username) =>
364
- store.findWhere('users', (r) => r.username === username && r.is_active) || undefined,
365
-
366
- updateLastLogin: (userId) => {
367
- try {
368
- store.updateWhere('users', (r) => r.id === userId, { last_login: nowIso() });
369
- } catch (err) {
370
- console.warn('Failed to update last login:', err.message);
371
- }
372
- },
373
-
374
- getUserById: (userId) => {
375
- const row = store.findWhere('users', (r) => r.id === userId && r.is_active);
376
- if (!row) return undefined;
377
- return {
378
- id: row.id,
379
- username: row.username,
380
- created_at: row.created_at,
381
- last_login: row.last_login,
382
- role: row.role || null,
383
- };
384
- },
385
-
386
- getFirstUser: () => {
387
- const row = store.raw.users.find((r) => r.is_active);
388
- if (!row) return undefined;
389
- return {
390
- id: row.id,
391
- username: row.username,
392
- created_at: row.created_at,
393
- last_login: row.last_login,
394
- role: row.role || null,
395
- };
396
- },
397
-
398
- updateUser: (userId, patch = {}) => {
399
- const allowed = {};
400
- if (typeof patch.username === 'string' && patch.username.trim()) allowed.username = patch.username.trim();
401
- if (typeof patch.git_name === 'string') allowed.git_name = patch.git_name;
402
- if (typeof patch.git_email === 'string') allowed.git_email = patch.git_email;
403
- if (typeof patch.role === 'string') allowed.role = patch.role;
404
- if (typeof patch.is_active === 'boolean') allowed.is_active = patch.is_active;
405
- store.updateWhere('users', (r) => r.id === userId, allowed);
406
- return userDb.listUsers().find((user) => user.id === userId) || null;
407
- },
408
-
409
- setUserActive: (userId, isActive) => userDb.updateUser(userId, { is_active: Boolean(isActive) }),
410
-
411
- updateGitConfig: (userId, gitName, gitEmail) => {
412
- store.updateWhere('users', (r) => r.id === userId, { git_name: gitName, git_email: gitEmail });
413
- },
414
-
415
- getGitConfig: (userId) => {
416
- const row = store.findWhere('users', (r) => r.id === userId);
417
- if (!row) return undefined;
418
- return { git_name: row.git_name || null, git_email: row.git_email || null };
419
- },
420
-
421
- completeOnboarding: (userId) => {
422
- store.updateWhere('users', (r) => r.id === userId, { has_completed_onboarding: true });
423
- },
424
-
425
- hasCompletedOnboarding: (userId) => {
426
- const row = store.findWhere('users', (r) => r.id === userId);
427
- return Boolean(row?.has_completed_onboarding);
428
- },
429
- };
430
-
431
- function ensureAdminUser() {
432
- const activeUsers = store.raw.users.filter((row) => row.is_active);
433
- if (activeUsers.length === 0) return;
434
- if (activeUsers.some((row) => row.role === 'admin' || row.role === 'owner')) return;
435
-
436
- activeUsers[0].role = 'admin';
437
- store.save();
438
- }
439
-
440
- ensureAdminUser();
441
-
442
- // ---------------------------------------------------------------------------
443
- // API key operations
444
- // ---------------------------------------------------------------------------
445
- const apiKeysDb = {
446
- generateApiKey: () => 'px_' + crypto.randomBytes(32).toString('hex'),
447
-
448
- normalizeScopes: (scopes) => {
449
- if (!Array.isArray(scopes)) return [];
450
- return Array.from(new Set(scopes
451
- .filter((scope) => typeof scope === 'string')
452
- .map((scope) => scope.trim())
453
- .filter(Boolean)
454
- )).sort();
455
- },
456
-
457
- createApiKey: (userId, keyName, scopes = []) => {
458
- const apiKey = apiKeysDb.generateApiKey();
459
- const normalizedScopes = apiKeysDb.normalizeScopes(scopes);
460
- const row = store.insert('api_keys', {
461
- user_id: userId,
462
- key_name: keyName,
463
- api_key: apiKey,
464
- scopes: normalizedScopes,
465
- created_at: nowIso(),
466
- last_used: null,
467
- is_active: true,
468
- });
469
- return { id: row.id, keyName, apiKey, scopes: normalizedScopes };
470
- },
471
-
472
- getApiKeys: (userId) => {
473
- const rows = store.filterWhere('api_keys', (r) => r.user_id === userId);
474
- // Match the old ORDER BY created_at DESC behaviour.
475
- return rows
476
- .slice()
477
- .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
478
- .map((r) => ({
479
- id: r.id,
480
- key_name: r.key_name,
481
- api_key: r.api_key,
482
- scopes: apiKeysDb.normalizeScopes(r.scopes),
483
- created_at: r.created_at,
484
- last_used: r.last_used,
485
- is_active: r.is_active ? 1 : 0,
486
- }));
487
- },
488
-
489
- validateApiKey: (apiKey) => {
490
- const key = store.findWhere('api_keys', (r) => r.api_key === apiKey && r.is_active);
491
- if (!key) return undefined;
492
- const user = store.findWhere('users', (r) => r.id === key.user_id && r.is_active);
493
- if (!user) return undefined;
494
- // Mirror the SQL-era side effect: stamp last_used. Only relevant
495
- // for the "which key was used last" display in the UI.
496
- store.updateWhere('api_keys', (r) => r.id === key.id, { last_used: nowIso() });
497
- return {
498
- id: user.id,
499
- username: user.username,
500
- role: user.role || null,
501
- api_key_id: key.id,
502
- api_key_scopes: apiKeysDb.normalizeScopes(key.scopes),
503
- };
504
- },
505
-
506
- deleteApiKey: (userId, apiKeyId) =>
507
- store.deleteWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId) > 0,
508
-
509
- toggleApiKey: (userId, apiKeyId, isActive) =>
510
- store.updateWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
511
-
512
- updateApiKeyScopes: (userId, apiKeyId, scopes = []) =>
513
- store.updateWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId, {
514
- scopes: apiKeysDb.normalizeScopes(scopes),
515
- }) > 0,
516
- };
517
-
518
- // ---------------------------------------------------------------------------
519
- // Credentials (GitHub tokens, etc.) operations
520
- // ---------------------------------------------------------------------------
521
- const credentialsDb = {
522
- createCredential: (userId, credentialName, credentialType, credentialValue, description = null) => {
523
- const row = store.insert('user_credentials', {
524
- user_id: userId,
525
- credential_name: credentialName,
526
- credential_type: credentialType,
527
- credential_value: credentialValue,
528
- description,
529
- created_at: nowIso(),
530
- is_active: true,
531
- });
532
- return { id: row.id, credentialName, credentialType };
533
- },
534
-
535
- getCredentials: (userId, credentialType = null) => {
536
- const rows = store.filterWhere('user_credentials', (r) =>
537
- r.user_id === userId && (credentialType == null || r.credential_type === credentialType),
538
- );
539
- return rows
540
- .slice()
541
- .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
542
- .map((r) => ({
543
- id: r.id,
544
- credential_name: r.credential_name,
545
- credential_type: r.credential_type,
546
- description: r.description,
547
- created_at: r.created_at,
548
- is_active: r.is_active ? 1 : 0,
549
- }));
550
- },
551
-
552
- getActiveCredential: (userId, credentialType) => {
553
- const rows = store.filterWhere('user_credentials', (r) =>
554
- r.user_id === userId && r.credential_type === credentialType && r.is_active,
555
- );
556
- if (rows.length === 0) return null;
557
- // "Most recent active" — mirror ORDER BY created_at DESC LIMIT 1
558
- rows.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
559
- return rows[0].credential_value;
560
- },
561
-
562
- getCredentialById: (userId, credentialId, credentialType = null) => {
563
- const row = store.findWhere('user_credentials', (r) =>
564
- r.id === credentialId && r.user_id === userId && r.is_active
565
- && (credentialType == null || r.credential_type === credentialType),
566
- );
567
- return row || undefined;
568
- },
569
-
570
- deleteCredential: (userId, credentialId) =>
571
- store.deleteWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId) > 0,
572
-
573
- toggleCredential: (userId, credentialId, isActive) =>
574
- store.updateWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
575
- };
576
-
577
- // ---------------------------------------------------------------------------
578
- // Notification preferences
579
- // ---------------------------------------------------------------------------
580
- const DEFAULT_NOTIFICATION_PREFERENCES = {
581
- channels: { inApp: true, webPush: false, telegram: true, desktop: true },
582
- events: { actionRequired: true, stop: true, error: true, updates: true },
583
- };
584
-
585
- const normalizeNotificationPreferences = (value) => {
586
- const source = value && typeof value === 'object' ? value : {};
587
- return {
588
- channels: {
589
- inApp: source.channels?.inApp !== false,
590
- webPush: source.channels?.webPush === true,
591
- telegram: source.channels?.telegram !== false,
592
- desktop: source.channels?.desktop !== false,
593
- },
594
- events: {
595
- actionRequired: source.events?.actionRequired !== false,
596
- stop: source.events?.stop !== false,
597
- error: source.events?.error !== false,
598
- updates: source.events?.updates !== false,
599
- },
600
- };
601
- };
602
-
603
- const notificationPreferencesDb = {
604
- getPreferences: (userId) => {
605
- const row = store.findWhere('user_notification_preferences', (r) => r.user_id === userId);
606
- if (!row) {
607
- const defaults = normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
608
- store.insert('user_notification_preferences', {
609
- user_id: userId,
610
- preferences_json: JSON.stringify(defaults),
611
- updated_at: nowIso(),
612
- }, { autoId: false });
613
- return defaults;
614
- }
615
- try {
616
- return normalizeNotificationPreferences(JSON.parse(row.preferences_json));
617
- } catch {
618
- return normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
619
- }
620
- },
621
-
622
- updatePreferences: (userId, preferences) => {
623
- const normalized = normalizeNotificationPreferences(preferences);
624
- store.upsertWhere(
625
- 'user_notification_preferences',
626
- (r) => r.user_id === userId,
627
- { user_id: userId, preferences_json: JSON.stringify(normalized), updated_at: nowIso() },
628
- );
629
- return normalized;
630
- },
631
- };
632
-
633
- // ---------------------------------------------------------------------------
634
- // Push subscriptions
635
- // ---------------------------------------------------------------------------
636
- const pushSubscriptionsDb = {
637
- saveSubscription: (userId, endpoint, keysP256dh, keysAuth) => {
638
- // The old SQL path upserted on `endpoint`, updating user_id as
639
- // well. Preserve that exact behaviour.
640
- const existing = store.findWhere('push_subscriptions', (r) => r.endpoint === endpoint);
641
- if (existing) {
642
- store.updateWhere('push_subscriptions', (r) => r.endpoint === endpoint, {
643
- user_id: userId,
644
- keys_p256dh: keysP256dh,
645
- keys_auth: keysAuth,
646
- });
647
- return;
648
- }
649
- store.insert('push_subscriptions', {
650
- user_id: userId,
651
- endpoint,
652
- keys_p256dh: keysP256dh,
653
- keys_auth: keysAuth,
654
- created_at: nowIso(),
655
- });
656
- },
657
-
658
- getSubscriptions: (userId) =>
659
- store.filterWhere('push_subscriptions', (r) => r.user_id === userId).map((r) => ({
660
- endpoint: r.endpoint,
661
- keys_p256dh: r.keys_p256dh,
662
- keys_auth: r.keys_auth,
663
- })),
664
-
665
- removeSubscription: (endpoint) => {
666
- store.deleteWhere('push_subscriptions', (r) => r.endpoint === endpoint);
667
- },
668
-
669
- removeAllForUser: (userId) => {
670
- store.deleteWhere('push_subscriptions', (r) => r.user_id === userId);
671
- },
672
- };
673
-
674
- // ---------------------------------------------------------------------------
675
- // VAPID key storage (for web push)
676
- // ---------------------------------------------------------------------------
677
- const vapidKeysDb = {
678
- getLatest: () => {
679
- if (store.raw.vapid_keys.length === 0) return null;
680
- // Mirror ORDER BY id DESC LIMIT 1 — take the newest row.
681
- const rows = store.raw.vapid_keys.slice().sort((a, b) => b.id - a.id);
682
- return { public_key: rows[0].public_key, private_key: rows[0].private_key };
683
- },
684
- insert: (publicKey, privateKey) => {
685
- store.insert('vapid_keys', {
686
- public_key: publicKey,
687
- private_key: privateKey,
688
- created_at: nowIso(),
689
- });
690
- },
691
- };
692
-
693
- // ---------------------------------------------------------------------------
694
- // Session custom names
695
- // ---------------------------------------------------------------------------
696
- const sessionNamesDb = {
697
- setName: (sessionId, provider, customName) => {
698
- store.upsertWhere(
699
- 'session_names',
700
- (r) => r.session_id === sessionId && r.provider === provider,
701
- { session_id: sessionId, provider, custom_name: customName, updated_at: nowIso(), created_at: nowIso() },
702
- );
703
- },
704
-
705
- getName: (sessionId, provider) => {
706
- const row = store.findWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider);
707
- return row?.custom_name || null;
708
- },
709
-
710
- getNames: (sessionIds, provider) => {
711
- if (!sessionIds.length) return new Map();
712
- const lookup = new Set(sessionIds);
713
- const matches = store.filterWhere('session_names',
714
- (r) => r.provider === provider && lookup.has(r.session_id));
715
- return new Map(matches.map((r) => [r.session_id, r.custom_name]));
716
- },
717
-
718
- deleteName: (sessionId, provider) =>
719
- store.deleteWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider) > 0,
720
- };
721
-
722
- function applyCustomSessionNames(sessions, provider) {
723
- if (!sessions?.length) return;
724
- try {
725
- const ids = sessions.map((s) => s.id);
726
- const customNames = sessionNamesDb.getNames(ids, provider);
727
- for (const session of sessions) {
728
- const custom = customNames.get(session.id);
729
- if (custom) session.summary = custom;
730
- }
731
- } catch (error) {
732
- console.warn(`[DB] Failed to apply custom session names for ${provider}:`, error.message);
733
- }
734
- }
735
-
736
- // ---------------------------------------------------------------------------
737
- // App config (key/value)
738
- // ---------------------------------------------------------------------------
739
- const appConfigDb = {
740
- get: (key) => {
741
- const row = store.findWhere('app_config', (r) => r.key === key);
742
- return row?.value || null;
743
- },
744
-
745
- set: (key, value) => {
746
- store.upsertWhere('app_config', (r) => r.key === key,
747
- { key, value, created_at: nowIso() });
748
- },
749
-
750
- getOrCreateJwtSecret: () => {
751
- let secret = appConfigDb.get('jwt_secret');
752
- if (!secret) {
753
- secret = crypto.randomBytes(64).toString('hex');
754
- appConfigDb.set('jwt_secret', secret);
755
- }
756
- return secret;
757
- },
758
- };
759
-
760
- // ---------------------------------------------------------------------------
761
- // Telegram — singleton config + per-user links
762
- // ---------------------------------------------------------------------------
763
- const DEFAULT_TELEGRAM_CONTROL_STATE = {
764
- remoteControlEnabled: true,
765
- routerEnabled: true,
766
- routerMode: 'hybrid',
767
- routerProvider: null,
768
- routerModel: null,
769
- confirmationPolicy: 'strict',
770
- pendingConfirmation: null,
771
- progressMode: 'final',
772
- selectedProjectName: null,
773
- selectedProjectPath: null,
774
- selectedProvider: 'opencode',
775
- selectedModel: null,
776
- selectedWorkflowId: null,
777
- activeTerminal: null,
778
- awaiting: null,
779
- };
780
-
781
- function normalizeTelegramControlState(value = {}) {
782
- const raw = value && typeof value === 'object' ? value : {};
783
- const selectedProvider = ['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'].includes(raw.selectedProvider)
784
- ? raw.selectedProvider
785
- : DEFAULT_TELEGRAM_CONTROL_STATE.selectedProvider;
786
- const routerProvider = ['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'].includes(raw.routerProvider)
787
- ? raw.routerProvider
788
- : null;
789
- const progressMode = ['final', 'steps', 'all', 'errors'].includes(raw.progressMode)
790
- ? raw.progressMode
791
- : DEFAULT_TELEGRAM_CONTROL_STATE.progressMode;
792
- const pendingConfirmation = raw.pendingConfirmation && typeof raw.pendingConfirmation === 'object'
793
- && typeof raw.pendingConfirmation.id === 'string'
794
- && typeof raw.pendingConfirmation.action === 'string'
795
- && typeof raw.pendingConfirmation.expiresAt === 'string'
796
- ? {
797
- id: raw.pendingConfirmation.id,
798
- action: raw.pendingConfirmation.action,
799
- payload: raw.pendingConfirmation.payload && typeof raw.pendingConfirmation.payload === 'object'
800
- ? raw.pendingConfirmation.payload
801
- : {},
802
- expiresAt: raw.pendingConfirmation.expiresAt,
803
- }
804
- : null;
805
- const activeTerminal = raw.activeTerminal && typeof raw.activeTerminal === 'object'
806
- && ['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'].includes(raw.activeTerminal.provider)
807
- && typeof raw.activeTerminal.projectPath === 'string'
808
- && raw.activeTerminal.projectPath.trim()
809
- ? {
810
- provider: raw.activeTerminal.provider,
811
- projectPath: raw.activeTerminal.projectPath.trim(),
812
- projectName: typeof raw.activeTerminal.projectName === 'string' && raw.activeTerminal.projectName.trim()
813
- ? raw.activeTerminal.projectName.trim()
814
- : null,
815
- projectLabel: typeof raw.activeTerminal.projectLabel === 'string' && raw.activeTerminal.projectLabel.trim()
816
- ? raw.activeTerminal.projectLabel.trim()
817
- : null,
818
- sessionId: typeof raw.activeTerminal.sessionId === 'string' && raw.activeTerminal.sessionId.trim()
819
- ? raw.activeTerminal.sessionId.trim()
820
- : null,
821
- tabId: typeof raw.activeTerminal.tabId === 'string' && raw.activeTerminal.tabId.trim()
822
- ? raw.activeTerminal.tabId.trim()
823
- : null,
824
- attachedAt: typeof raw.activeTerminal.attachedAt === 'string' && raw.activeTerminal.attachedAt.trim()
825
- ? raw.activeTerminal.attachedAt.trim()
826
- : nowIso(),
827
- }
828
- : null;
829
-
830
- return {
831
- ...DEFAULT_TELEGRAM_CONTROL_STATE,
832
- ...raw,
833
- remoteControlEnabled: raw.remoteControlEnabled !== false,
834
- routerEnabled: raw.routerEnabled !== false,
835
- routerMode: raw.routerMode === 'hybrid' ? 'hybrid' : DEFAULT_TELEGRAM_CONTROL_STATE.routerMode,
836
- routerProvider,
837
- routerModel: typeof raw.routerModel === 'string' && raw.routerModel.trim() ? raw.routerModel.trim() : null,
838
- confirmationPolicy: 'strict',
839
- pendingConfirmation,
840
- progressMode,
841
- selectedProvider,
842
- selectedProjectName: typeof raw.selectedProjectName === 'string' ? raw.selectedProjectName : null,
843
- selectedProjectPath: typeof raw.selectedProjectPath === 'string' ? raw.selectedProjectPath : null,
844
- selectedModel: typeof raw.selectedModel === 'string' ? raw.selectedModel : null,
845
- selectedWorkflowId: typeof raw.selectedWorkflowId === 'string' ? raw.selectedWorkflowId : null,
846
- activeTerminal,
847
- awaiting: raw.awaiting && typeof raw.awaiting === 'object' ? raw.awaiting : null,
848
- };
849
- }
850
-
851
- const telegramConfigDb = {
852
- get: () => {
853
- const row = store.raw.telegram_config[0];
854
- if (!row) return null;
855
- return { bot_token: row.bot_token, bot_username: row.bot_username, updated_at: row.updated_at };
856
- },
857
- set: (botToken, botUsername = null) => {
858
- store.raw.telegram_config = [{
859
- id: 1,
860
- bot_token: botToken,
861
- bot_username: botUsername,
862
- updated_at: nowIso(),
863
- }];
864
- store.save();
865
- },
866
- clear: () => {
867
- store.raw.telegram_config = [];
868
- store.save();
869
- },
870
- };
871
-
872
- const telegramLinksDb = {
873
- setPairingCode: (userId, code, expiresAt, language) => {
874
- store.upsertWhere('telegram_links', (r) => r.user_id === userId, {
875
- user_id: userId,
876
- pairing_code: code,
877
- pairing_code_expires_at: expiresAt,
878
- language,
879
- chat_id: null,
880
- telegram_username: null,
881
- verified_at: null,
882
- notifications_enabled: true,
883
- bridge_enabled: true,
884
- telegram_control: normalizeTelegramControlState(),
885
- updated_at: nowIso(),
886
- });
887
- },
888
- findByPairingCode: (code) => {
889
- const row = store.findWhere('telegram_links', (r) => r.pairing_code === code);
890
- if (!row) return null;
891
- return {
892
- user_id: row.user_id,
893
- pairing_code: row.pairing_code,
894
- pairing_code_expires_at: row.pairing_code_expires_at,
895
- language: row.language,
896
- };
897
- },
898
- verify: (userId, chatId, telegramUsername) => {
899
- store.updateWhere('telegram_links', (r) => r.user_id === userId, {
900
- chat_id: chatId,
901
- telegram_username: telegramUsername,
902
- verified_at: nowIso(),
903
- pairing_code: null,
904
- pairing_code_expires_at: null,
905
- updated_at: nowIso(),
906
- });
907
- },
908
- getByUserId: (userId) => {
909
- const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
910
- return row ? { ...row } : null;
911
- },
912
- getByChatId: (chatId) => {
913
- const row = store.findWhere('telegram_links', (r) => r.chat_id === chatId);
914
- if (!row) return null;
915
- return {
916
- user_id: row.user_id,
917
- chat_id: row.chat_id,
918
- telegram_username: row.telegram_username,
919
- language: row.language,
920
- notifications_enabled: row.notifications_enabled,
921
- bridge_enabled: row.bridge_enabled,
922
- telegram_control: normalizeTelegramControlState(row.telegram_control),
923
- };
924
- },
925
- listVerified: () =>
926
- store.filterWhere('telegram_links', (r) => r.chat_id && r.verified_at).map((r) => ({
927
- user_id: r.user_id,
928
- chat_id: r.chat_id,
929
- telegram_username: r.telegram_username,
930
- language: r.language,
931
- notifications_enabled: r.notifications_enabled,
932
- bridge_enabled: r.bridge_enabled,
933
- telegram_control: normalizeTelegramControlState(r.telegram_control),
934
- })),
935
- updatePreferences: (userId, { language, notificationsEnabled, bridgeEnabled }) => {
936
- const patch = { updated_at: nowIso() };
937
- if (language !== undefined) patch.language = language;
938
- if (notificationsEnabled !== undefined) patch.notifications_enabled = Boolean(notificationsEnabled);
939
- if (bridgeEnabled !== undefined) patch.bridge_enabled = Boolean(bridgeEnabled);
940
- if (Object.keys(patch).length === 1) return; // only updated_at → no real change
941
- store.updateWhere('telegram_links', (r) => r.user_id === userId, patch);
942
- },
943
- getControlState: (userId) => {
944
- const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
945
- return normalizeTelegramControlState(row?.telegram_control);
946
- },
947
- updateControlState: (userId, patch) => {
948
- const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
949
- const current = normalizeTelegramControlState(row?.telegram_control);
950
- const next = normalizeTelegramControlState({ ...current, ...(patch || {}) });
951
- store.updateWhere('telegram_links', (r) => r.user_id === userId, {
952
- telegram_control: next,
953
- updated_at: nowIso(),
954
- });
955
- return next;
956
- },
957
- unlink: (userId) => {
958
- store.deleteWhere('telegram_links', (r) => r.user_id === userId);
959
- },
960
- };
961
-
962
- // Back-compat surface — older callers used `githubTokensDb.*`; internally
963
- // they always delegated to credentialsDb with `credential_type='github_token'`.
964
- const githubTokensDb = {
965
- createGithubToken: (userId, tokenName, githubToken, description = null) =>
966
- credentialsDb.createCredential(userId, tokenName, 'github_token', githubToken, description),
967
- getGithubTokens: (userId) => credentialsDb.getCredentials(userId, 'github_token'),
968
- getActiveGithubToken: (userId) => credentialsDb.getActiveCredential(userId, 'github_token'),
969
- deleteGithubToken: (userId, tokenId) => credentialsDb.deleteCredential(userId, tokenId),
970
- toggleGithubToken: (userId, tokenId, isActive) => credentialsDb.toggleCredential(userId, tokenId, isActive),
971
- };
972
-
973
- export {
974
- db,
975
- initializeDatabase,
976
- userDb,
977
- apiKeysDb,
978
- credentialsDb,
979
- notificationPreferencesDb,
980
- pushSubscriptionsDb,
981
- vapidKeysDb,
982
- sessionNamesDb,
983
- applyCustomSessionNames,
984
- appConfigDb,
985
- telegramConfigDb,
986
- telegramLinksDb,
987
- githubTokensDb,
988
- };
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import path from 'node:path';
5
+
6
+ import { findAppRoot, getModuleDir } from '../utils/runtime-paths.js';
7
+
8
+ import { JsonStore, nowIso } from './json-store.js';
9
+
10
+ // CommonJS `require` shim — we only reach for it once, during the
11
+ // legacy-to-JSON migration below, to dynamically import better-sqlite3
12
+ // only when an old auth.db is actually present on disk.
13
+ const require = createRequire(import.meta.url);
14
+
15
+ const __dirname = getModuleDir(import.meta.url);
16
+ // The compiled backend lives under dist-server/server/database, but the install root we log
17
+ // should still point at the project/app root. Resolving it here avoids build-layout drift.
18
+ const APP_ROOT = findAppRoot(__dirname);
19
+
20
+ // ANSI color codes for terminal output
21
+ const colors = {
22
+ reset: '\x1b[0m',
23
+ bright: '\x1b[1m',
24
+ cyan: '\x1b[36m',
25
+ dim: '\x1b[2m',
26
+ };
27
+
28
+ const c = {
29
+ info: (text) => `${colors.cyan}${text}${colors.reset}`,
30
+ bright: (text) => `${colors.bright}${text}${colors.reset}`,
31
+ dim: (text) => `${colors.dim}${text}${colors.reset}`,
32
+ };
33
+
34
+ // DATABASE_PATH keeps its historical meaning (user override), but points
35
+ // at a `.json` file now. If the user's env var still names a `.db`
36
+ // extension, we swap to the corresponding `.json` sibling — the auth
37
+ // store moved off SQLite in v1.33.0.
38
+ const rawDbPath = process.env.DATABASE_PATH || path.join(__dirname, 'auth.db');
39
+ const JSON_PATH = rawDbPath.endsWith('.db')
40
+ ? rawDbPath.replace(/\.db$/, '.json')
41
+ : (rawDbPath.endsWith('.json') ? rawDbPath : `${rawDbPath}.json`);
42
+ const LEGACY_SQLITE_PATH = rawDbPath.endsWith('.db')
43
+ ? rawDbPath
44
+ : rawDbPath.replace(/\.json$/, '.db');
45
+
46
+ // Ensure parent dir exists before migration / initial write.
47
+ {
48
+ const dir = path.dirname(JSON_PATH);
49
+ if (!fs.existsSync(dir)) {
50
+ try { fs.mkdirSync(dir, { recursive: true }); }
51
+ catch (err) {
52
+ console.error(`Failed to create database directory ${dir}:`, err.message);
53
+ throw err;
54
+ }
55
+ }
56
+ }
57
+
58
+ /**
59
+ * One-time migration from the previous better-sqlite3 auth.db to the
60
+ * new JSON format. Triggered only when:
61
+ * - The legacy .db exists
62
+ * - AND no .json has been created yet
63
+ * The legacy file is kept in place as `<name>.db.migrated-<timestamp>`
64
+ * so a user can roll back by moving it into place and reinstalling
65
+ * better-sqlite3 if they hit a showstopper. Runs synchronously because
66
+ * all downstream modules (auth.js, vapid-keys.js) import `db` at module
67
+ * load and can't wait for async startup.
68
+ */
69
+ function migrateSqliteIfPresent() {
70
+ if (fs.existsSync(JSON_PATH)) return; // Already migrated or fresh install.
71
+ if (!fs.existsSync(LEGACY_SQLITE_PATH)) return; // Nothing to migrate.
72
+
73
+ console.log(`${c.info('[MIGRATION]')} Converting ${c.bright(LEGACY_SQLITE_PATH)} → ${c.bright(JSON_PATH)} (JSON auth store, v1.33.0)`);
74
+
75
+ let Database;
76
+ try {
77
+ const mod = require('better-sqlite3');
78
+ Database = mod.default || mod;
79
+ } catch {
80
+ // Auto-install path fell through — the user has a legacy file but
81
+ // better-sqlite3 isn't present (they may have a trimmed dep tree).
82
+ // Surface a clear error; we'd rather fail startup than silently
83
+ // skip migration and strand the user's saved credentials.
84
+ console.error('[MIGRATION] Legacy auth.db present but better-sqlite3 not installed.');
85
+ console.error('[MIGRATION] Install it once to migrate: `npm install better-sqlite3` in your pixcode install dir, then restart.');
86
+ throw new Error('Auth DB migration requires better-sqlite3 (legacy file detected).');
87
+ }
88
+
89
+ const legacy = new Database(LEGACY_SQLITE_PATH, { readonly: true });
90
+ const store = new JsonStore(JSON_PATH);
91
+
92
+ // Pull every table, skipping silently when it doesn't exist (old
93
+ // installs that never ran some migrations). We rely on `IF NOT EXISTS`
94
+ // patterns from the old schema.js — missing tables throw a SQLite
95
+ // error which we catch per-table.
96
+ const safeAll = (sql) => {
97
+ try { return legacy.prepare(sql).all(); } catch { return []; }
98
+ };
99
+
100
+ const users = safeAll('SELECT id, username, password_hash, created_at, last_login, is_active, git_name, git_email, has_completed_onboarding FROM users');
101
+ for (const u of users) {
102
+ store.raw.users.push({
103
+ id: u.id,
104
+ username: u.username,
105
+ password_hash: u.password_hash,
106
+ created_at: u.created_at || nowIso(),
107
+ last_login: u.last_login || null,
108
+ is_active: u.is_active !== 0,
109
+ git_name: u.git_name || null,
110
+ git_email: u.git_email || null,
111
+ has_completed_onboarding: u.has_completed_onboarding === 1,
112
+ });
113
+ store.raw._sequences.users = Math.max(store.raw._sequences.users, u.id);
114
+ }
115
+
116
+ const apiKeys = safeAll('SELECT id, user_id, key_name, api_key, created_at, last_used, is_active FROM api_keys');
117
+ for (const k of apiKeys) {
118
+ store.raw.api_keys.push({
119
+ id: k.id,
120
+ user_id: k.user_id,
121
+ key_name: k.key_name,
122
+ api_key: k.api_key,
123
+ created_at: k.created_at || nowIso(),
124
+ last_used: k.last_used || null,
125
+ is_active: k.is_active !== 0,
126
+ });
127
+ store.raw._sequences.api_keys = Math.max(store.raw._sequences.api_keys, k.id);
128
+ }
129
+
130
+ const credentials = safeAll('SELECT id, user_id, credential_name, credential_type, credential_value, description, created_at, is_active FROM user_credentials');
131
+ for (const cr of credentials) {
132
+ store.raw.user_credentials.push({
133
+ id: cr.id,
134
+ user_id: cr.user_id,
135
+ credential_name: cr.credential_name,
136
+ credential_type: cr.credential_type,
137
+ credential_value: cr.credential_value,
138
+ description: cr.description || null,
139
+ created_at: cr.created_at || nowIso(),
140
+ is_active: cr.is_active !== 0,
141
+ });
142
+ store.raw._sequences.user_credentials = Math.max(store.raw._sequences.user_credentials, cr.id);
143
+ }
144
+
145
+ const prefs = safeAll('SELECT user_id, preferences_json, updated_at FROM user_notification_preferences');
146
+ for (const p of prefs) {
147
+ store.raw.user_notification_preferences.push({
148
+ user_id: p.user_id,
149
+ preferences_json: p.preferences_json,
150
+ updated_at: p.updated_at || nowIso(),
151
+ });
152
+ }
153
+
154
+ const vapid = safeAll('SELECT id, public_key, private_key, created_at FROM vapid_keys');
155
+ for (const v of vapid) {
156
+ store.raw.vapid_keys.push({
157
+ id: v.id,
158
+ public_key: v.public_key,
159
+ private_key: v.private_key,
160
+ created_at: v.created_at || nowIso(),
161
+ });
162
+ store.raw._sequences.vapid_keys = Math.max(store.raw._sequences.vapid_keys, v.id);
163
+ }
164
+
165
+ const pushSubs = safeAll('SELECT id, user_id, endpoint, keys_p256dh, keys_auth, created_at FROM push_subscriptions');
166
+ for (const s of pushSubs) {
167
+ store.raw.push_subscriptions.push({
168
+ id: s.id,
169
+ user_id: s.user_id,
170
+ endpoint: s.endpoint,
171
+ keys_p256dh: s.keys_p256dh,
172
+ keys_auth: s.keys_auth,
173
+ created_at: s.created_at || nowIso(),
174
+ });
175
+ store.raw._sequences.push_subscriptions = Math.max(store.raw._sequences.push_subscriptions, s.id);
176
+ }
177
+
178
+ const sessionNames = safeAll('SELECT session_id, provider, custom_name, created_at, updated_at FROM session_names');
179
+ for (const sn of sessionNames) {
180
+ store.raw.session_names.push({
181
+ session_id: sn.session_id,
182
+ provider: sn.provider,
183
+ custom_name: sn.custom_name,
184
+ created_at: sn.created_at || nowIso(),
185
+ updated_at: sn.updated_at || nowIso(),
186
+ });
187
+ }
188
+
189
+ const appConfig = safeAll('SELECT key, value, created_at FROM app_config');
190
+ for (const a of appConfig) {
191
+ store.raw.app_config.push({
192
+ key: a.key,
193
+ value: a.value,
194
+ created_at: a.created_at || nowIso(),
195
+ });
196
+ }
197
+
198
+ const telegramConfig = safeAll('SELECT id, bot_token, bot_username, updated_at FROM telegram_config');
199
+ for (const t of telegramConfig) {
200
+ store.raw.telegram_config.push({
201
+ id: 1,
202
+ bot_token: t.bot_token,
203
+ bot_username: t.bot_username || null,
204
+ updated_at: t.updated_at || nowIso(),
205
+ });
206
+ }
207
+
208
+ const telegramLinks = safeAll('SELECT user_id, chat_id, telegram_username, language, pairing_code, pairing_code_expires_at, verified_at, notifications_enabled, bridge_enabled, updated_at FROM telegram_links');
209
+ for (const tl of telegramLinks) {
210
+ store.raw.telegram_links.push({
211
+ user_id: tl.user_id,
212
+ chat_id: tl.chat_id || null,
213
+ telegram_username: tl.telegram_username || null,
214
+ language: tl.language || 'en',
215
+ pairing_code: tl.pairing_code || null,
216
+ pairing_code_expires_at: tl.pairing_code_expires_at || null,
217
+ verified_at: tl.verified_at || null,
218
+ notifications_enabled: tl.notifications_enabled !== 0,
219
+ bridge_enabled: tl.bridge_enabled !== 0,
220
+ telegram_control: null,
221
+ updated_at: tl.updated_at || nowIso(),
222
+ });
223
+ }
224
+
225
+ store.save();
226
+ legacy.close();
227
+
228
+ // Rename the old .db out of the way so we never migrate it twice.
229
+ // Keep it (not delete) so the user can roll back if needed.
230
+ const backup = `${LEGACY_SQLITE_PATH}.migrated-${Date.now()}`;
231
+ try {
232
+ fs.renameSync(LEGACY_SQLITE_PATH, backup);
233
+ for (const suffix of ['-wal', '-shm']) {
234
+ if (fs.existsSync(LEGACY_SQLITE_PATH + suffix)) {
235
+ try { fs.renameSync(LEGACY_SQLITE_PATH + suffix, backup + suffix); } catch { /* noop */ }
236
+ }
237
+ }
238
+ } catch (err) {
239
+ console.warn(`[MIGRATION] Migration succeeded but could not rename old DB: ${err.message}`);
240
+ }
241
+
242
+ console.log(`${c.info('[MIGRATION]')} Migration complete. Old DB preserved as ${c.dim(backup)}.`);
243
+ }
244
+
245
+ // Module-load order matters — auth middleware imports `db` and reads the
246
+ // JWT secret before anything else gets to boot. So the store has to be
247
+ // ready synchronously at the first `import { db } from './db.js'`.
248
+ migrateSqliteIfPresent();
249
+
250
+ const store = new JsonStore(JSON_PATH);
251
+
252
+ console.log('');
253
+ console.log(c.dim('═'.repeat(60)));
254
+ console.log(`${c.info('[INFO]')} App Installation: ${c.bright(APP_ROOT)}`);
255
+ console.log(`${c.info('[INFO]')} Auth store: ${c.dim(path.relative(APP_ROOT, JSON_PATH))}`);
256
+ if (process.env.DATABASE_PATH) {
257
+ console.log(` ${c.dim('(Using custom DATABASE_PATH from environment)')}`);
258
+ }
259
+ console.log(c.dim('═'.repeat(60)));
260
+ console.log('');
261
+
262
+ // initializeDatabase used to run `CREATE TABLE IF NOT EXISTS` + migrations.
263
+ // The JSON store always has its shape pre-baked, so this is a no-op —
264
+ // keeping the export preserves the server boot sequence.
265
+ const initializeDatabase = async () => { /* schema lives in code, not in file */ };
266
+
267
+ // ---------------------------------------------------------------------------
268
+ // Back-compat `db` shim — a few modules outside database/db.js imported `db`
269
+ // and called `db.prepare(sql)` directly. Most of those uses were for trivial
270
+ // transaction markers (BEGIN/COMMIT/ROLLBACK — no-op under our JSON store)
271
+ // or very specific SELECTs we've wrapped in explicit helpers. This shim
272
+ // lets those call sites keep working without a bigger refactor.
273
+ // ---------------------------------------------------------------------------
274
+ const db = {
275
+ prepare(sql) {
276
+ const normalized = sql.trim().toUpperCase();
277
+ // Transaction markers — our store writes atomically per op, so
278
+ // there's no real transaction to start. No-op + success result.
279
+ if (normalized === 'BEGIN' || normalized === 'COMMIT' || normalized === 'ROLLBACK') {
280
+ return {
281
+ run: () => ({ changes: 0, lastInsertRowid: 0 }),
282
+ };
283
+ }
284
+
285
+ // Specific query routed through the new helpers — used by
286
+ // server/routes/projects.js to fetch a single github credential.
287
+ if (/FROM USER_CREDENTIALS\s+WHERE ID = \?\s+AND USER_ID = \?\s+AND CREDENTIAL_TYPE = \?\s+AND IS_ACTIVE = 1/.test(normalized)) {
288
+ return {
289
+ get: (id, userId, credentialType) =>
290
+ store.findWhere('user_credentials',
291
+ (r) => r.id === id && r.user_id === userId && r.credential_type === credentialType && r.is_active)
292
+ || undefined,
293
+ };
294
+ }
295
+
296
+ throw new Error(
297
+ `db.prepare: unsupported SQL passed through the compat shim: ${sql.slice(0, 80)}`
298
+ + '\nExtend server/database/db.js or use a dedicated helper (userDb, credentialsDb, …).',
299
+ );
300
+ },
301
+ };
302
+
303
+ // ---------------------------------------------------------------------------
304
+ // User operations
305
+ // ---------------------------------------------------------------------------
306
+ const userDb = {
307
+ hasUsers: () => store.count('users', (r) => r.is_active) > 0,
308
+
309
+ listUsers: () => store.raw.users.map((row) => ({
310
+ id: row.id,
311
+ username: row.username,
312
+ created_at: row.created_at,
313
+ last_login: row.last_login,
314
+ is_active: Boolean(row.is_active),
315
+ git_name: row.git_name || null,
316
+ git_email: row.git_email || null,
317
+ has_completed_onboarding: Boolean(row.has_completed_onboarding),
318
+ role: row.role || null,
319
+ })),
320
+
321
+ createUser: (username, passwordHash, metadata = {}) => {
322
+ const row = store.insert('users', {
323
+ username,
324
+ password_hash: passwordHash,
325
+ created_at: nowIso(),
326
+ last_login: null,
327
+ is_active: true,
328
+ git_name: null,
329
+ git_email: null,
330
+ has_completed_onboarding: false,
331
+ role: metadata.role || 'admin',
332
+ });
333
+ return { id: row.id, username: row.username, role: row.role || 'admin' };
334
+ },
335
+
336
+ createManagedUser: (username, passwordHash, metadata = {}) => {
337
+ const existing = store.raw.users.find((r) => r.username === username);
338
+ if (existing) {
339
+ throw new Error('Username already exists.');
340
+ }
341
+
342
+ const row = store.insert('users', {
343
+ username,
344
+ password_hash: passwordHash,
345
+ created_at: nowIso(),
346
+ last_login: null,
347
+ is_active: metadata.is_active !== false,
348
+ git_name: metadata.git_name || null,
349
+ git_email: metadata.git_email || null,
350
+ has_completed_onboarding: false,
351
+ role: metadata.role || 'member',
352
+ });
353
+ return {
354
+ id: row.id,
355
+ username: row.username,
356
+ created_at: row.created_at,
357
+ last_login: row.last_login,
358
+ is_active: Boolean(row.is_active),
359
+ role: row.role || 'member',
360
+ };
361
+ },
362
+
363
+ getUserByUsername: (username) =>
364
+ store.findWhere('users', (r) => r.username === username && r.is_active) || undefined,
365
+
366
+ updateLastLogin: (userId) => {
367
+ try {
368
+ store.updateWhere('users', (r) => r.id === userId, { last_login: nowIso() });
369
+ } catch (err) {
370
+ console.warn('Failed to update last login:', err.message);
371
+ }
372
+ },
373
+
374
+ getUserById: (userId) => {
375
+ const row = store.findWhere('users', (r) => r.id === userId && r.is_active);
376
+ if (!row) return undefined;
377
+ return {
378
+ id: row.id,
379
+ username: row.username,
380
+ created_at: row.created_at,
381
+ last_login: row.last_login,
382
+ role: row.role || null,
383
+ };
384
+ },
385
+
386
+ getFirstUser: () => {
387
+ const row = store.raw.users.find((r) => r.is_active);
388
+ if (!row) return undefined;
389
+ return {
390
+ id: row.id,
391
+ username: row.username,
392
+ created_at: row.created_at,
393
+ last_login: row.last_login,
394
+ role: row.role || null,
395
+ };
396
+ },
397
+
398
+ updateUser: (userId, patch = {}) => {
399
+ const allowed = {};
400
+ if (typeof patch.username === 'string' && patch.username.trim()) allowed.username = patch.username.trim();
401
+ if (typeof patch.git_name === 'string') allowed.git_name = patch.git_name;
402
+ if (typeof patch.git_email === 'string') allowed.git_email = patch.git_email;
403
+ if (typeof patch.role === 'string') allowed.role = patch.role;
404
+ if (typeof patch.is_active === 'boolean') allowed.is_active = patch.is_active;
405
+ store.updateWhere('users', (r) => r.id === userId, allowed);
406
+ return userDb.listUsers().find((user) => user.id === userId) || null;
407
+ },
408
+
409
+ setUserActive: (userId, isActive) => userDb.updateUser(userId, { is_active: Boolean(isActive) }),
410
+
411
+ updateGitConfig: (userId, gitName, gitEmail) => {
412
+ store.updateWhere('users', (r) => r.id === userId, { git_name: gitName, git_email: gitEmail });
413
+ },
414
+
415
+ getGitConfig: (userId) => {
416
+ const row = store.findWhere('users', (r) => r.id === userId);
417
+ if (!row) return undefined;
418
+ return { git_name: row.git_name || null, git_email: row.git_email || null };
419
+ },
420
+
421
+ completeOnboarding: (userId) => {
422
+ store.updateWhere('users', (r) => r.id === userId, { has_completed_onboarding: true });
423
+ },
424
+
425
+ hasCompletedOnboarding: (userId) => {
426
+ const row = store.findWhere('users', (r) => r.id === userId);
427
+ return Boolean(row?.has_completed_onboarding);
428
+ },
429
+ };
430
+
431
+ function ensureAdminUser() {
432
+ const activeUsers = store.raw.users.filter((row) => row.is_active);
433
+ if (activeUsers.length === 0) return;
434
+ if (activeUsers.some((row) => row.role === 'admin' || row.role === 'owner')) return;
435
+
436
+ activeUsers[0].role = 'admin';
437
+ store.save();
438
+ }
439
+
440
+ ensureAdminUser();
441
+
442
+ // ---------------------------------------------------------------------------
443
+ // API key operations
444
+ // ---------------------------------------------------------------------------
445
+ const apiKeysDb = {
446
+ generateApiKey: () => 'px_' + crypto.randomBytes(32).toString('hex'),
447
+
448
+ normalizeScopes: (scopes) => {
449
+ if (!Array.isArray(scopes)) return [];
450
+ return Array.from(new Set(scopes
451
+ .filter((scope) => typeof scope === 'string')
452
+ .map((scope) => scope.trim())
453
+ .filter(Boolean)
454
+ )).sort();
455
+ },
456
+
457
+ createApiKey: (userId, keyName, scopes = []) => {
458
+ const apiKey = apiKeysDb.generateApiKey();
459
+ const normalizedScopes = apiKeysDb.normalizeScopes(scopes);
460
+ const row = store.insert('api_keys', {
461
+ user_id: userId,
462
+ key_name: keyName,
463
+ api_key: apiKey,
464
+ scopes: normalizedScopes,
465
+ created_at: nowIso(),
466
+ last_used: null,
467
+ is_active: true,
468
+ });
469
+ return { id: row.id, keyName, apiKey, scopes: normalizedScopes };
470
+ },
471
+
472
+ getApiKeys: (userId) => {
473
+ const rows = store.filterWhere('api_keys', (r) => r.user_id === userId);
474
+ // Match the old ORDER BY created_at DESC behaviour.
475
+ return rows
476
+ .slice()
477
+ .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
478
+ .map((r) => ({
479
+ id: r.id,
480
+ key_name: r.key_name,
481
+ api_key: r.api_key,
482
+ scopes: apiKeysDb.normalizeScopes(r.scopes),
483
+ created_at: r.created_at,
484
+ last_used: r.last_used,
485
+ is_active: r.is_active ? 1 : 0,
486
+ }));
487
+ },
488
+
489
+ validateApiKey: (apiKey) => {
490
+ const key = store.findWhere('api_keys', (r) => r.api_key === apiKey && r.is_active);
491
+ if (!key) return undefined;
492
+ const user = store.findWhere('users', (r) => r.id === key.user_id && r.is_active);
493
+ if (!user) return undefined;
494
+ // Mirror the SQL-era side effect: stamp last_used. Only relevant
495
+ // for the "which key was used last" display in the UI.
496
+ store.updateWhere('api_keys', (r) => r.id === key.id, { last_used: nowIso() });
497
+ return {
498
+ id: user.id,
499
+ username: user.username,
500
+ role: user.role || null,
501
+ api_key_id: key.id,
502
+ api_key_scopes: apiKeysDb.normalizeScopes(key.scopes),
503
+ };
504
+ },
505
+
506
+ deleteApiKey: (userId, apiKeyId) =>
507
+ store.deleteWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId) > 0,
508
+
509
+ toggleApiKey: (userId, apiKeyId, isActive) =>
510
+ store.updateWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
511
+
512
+ updateApiKeyScopes: (userId, apiKeyId, scopes = []) =>
513
+ store.updateWhere('api_keys', (r) => r.id === apiKeyId && r.user_id === userId, {
514
+ scopes: apiKeysDb.normalizeScopes(scopes),
515
+ }) > 0,
516
+ };
517
+
518
+ // ---------------------------------------------------------------------------
519
+ // Credentials (GitHub tokens, etc.) operations
520
+ // ---------------------------------------------------------------------------
521
+ const credentialsDb = {
522
+ createCredential: (userId, credentialName, credentialType, credentialValue, description = null) => {
523
+ const row = store.insert('user_credentials', {
524
+ user_id: userId,
525
+ credential_name: credentialName,
526
+ credential_type: credentialType,
527
+ credential_value: credentialValue,
528
+ description,
529
+ created_at: nowIso(),
530
+ is_active: true,
531
+ });
532
+ return { id: row.id, credentialName, credentialType };
533
+ },
534
+
535
+ getCredentials: (userId, credentialType = null) => {
536
+ const rows = store.filterWhere('user_credentials', (r) =>
537
+ r.user_id === userId && (credentialType == null || r.credential_type === credentialType),
538
+ );
539
+ return rows
540
+ .slice()
541
+ .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
542
+ .map((r) => ({
543
+ id: r.id,
544
+ credential_name: r.credential_name,
545
+ credential_type: r.credential_type,
546
+ description: r.description,
547
+ created_at: r.created_at,
548
+ is_active: r.is_active ? 1 : 0,
549
+ }));
550
+ },
551
+
552
+ getActiveCredential: (userId, credentialType) => {
553
+ const rows = store.filterWhere('user_credentials', (r) =>
554
+ r.user_id === userId && r.credential_type === credentialType && r.is_active,
555
+ );
556
+ if (rows.length === 0) return null;
557
+ // "Most recent active" — mirror ORDER BY created_at DESC LIMIT 1
558
+ rows.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
559
+ return rows[0].credential_value;
560
+ },
561
+
562
+ getCredentialById: (userId, credentialId, credentialType = null) => {
563
+ const row = store.findWhere('user_credentials', (r) =>
564
+ r.id === credentialId && r.user_id === userId && r.is_active
565
+ && (credentialType == null || r.credential_type === credentialType),
566
+ );
567
+ return row || undefined;
568
+ },
569
+
570
+ deleteCredential: (userId, credentialId) =>
571
+ store.deleteWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId) > 0,
572
+
573
+ toggleCredential: (userId, credentialId, isActive) =>
574
+ store.updateWhere('user_credentials', (r) => r.id === credentialId && r.user_id === userId, { is_active: Boolean(isActive) }) > 0,
575
+ };
576
+
577
+ // ---------------------------------------------------------------------------
578
+ // Notification preferences
579
+ // ---------------------------------------------------------------------------
580
+ const DEFAULT_NOTIFICATION_PREFERENCES = {
581
+ channels: { inApp: true, webPush: false, telegram: true, desktop: true },
582
+ events: { actionRequired: true, stop: true, error: true, updates: true },
583
+ };
584
+
585
+ const normalizeNotificationPreferences = (value) => {
586
+ const source = value && typeof value === 'object' ? value : {};
587
+ return {
588
+ channels: {
589
+ inApp: source.channels?.inApp !== false,
590
+ webPush: source.channels?.webPush === true,
591
+ telegram: source.channels?.telegram !== false,
592
+ desktop: source.channels?.desktop !== false,
593
+ },
594
+ events: {
595
+ actionRequired: source.events?.actionRequired !== false,
596
+ stop: source.events?.stop !== false,
597
+ error: source.events?.error !== false,
598
+ updates: source.events?.updates !== false,
599
+ },
600
+ };
601
+ };
602
+
603
+ const notificationPreferencesDb = {
604
+ getPreferences: (userId) => {
605
+ const row = store.findWhere('user_notification_preferences', (r) => r.user_id === userId);
606
+ if (!row) {
607
+ const defaults = normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
608
+ store.insert('user_notification_preferences', {
609
+ user_id: userId,
610
+ preferences_json: JSON.stringify(defaults),
611
+ updated_at: nowIso(),
612
+ }, { autoId: false });
613
+ return defaults;
614
+ }
615
+ try {
616
+ return normalizeNotificationPreferences(JSON.parse(row.preferences_json));
617
+ } catch {
618
+ return normalizeNotificationPreferences(DEFAULT_NOTIFICATION_PREFERENCES);
619
+ }
620
+ },
621
+
622
+ updatePreferences: (userId, preferences) => {
623
+ const normalized = normalizeNotificationPreferences(preferences);
624
+ store.upsertWhere(
625
+ 'user_notification_preferences',
626
+ (r) => r.user_id === userId,
627
+ { user_id: userId, preferences_json: JSON.stringify(normalized), updated_at: nowIso() },
628
+ );
629
+ return normalized;
630
+ },
631
+ };
632
+
633
+ // ---------------------------------------------------------------------------
634
+ // Push subscriptions
635
+ // ---------------------------------------------------------------------------
636
+ const pushSubscriptionsDb = {
637
+ saveSubscription: (userId, endpoint, keysP256dh, keysAuth) => {
638
+ // The old SQL path upserted on `endpoint`, updating user_id as
639
+ // well. Preserve that exact behaviour.
640
+ const existing = store.findWhere('push_subscriptions', (r) => r.endpoint === endpoint);
641
+ if (existing) {
642
+ store.updateWhere('push_subscriptions', (r) => r.endpoint === endpoint, {
643
+ user_id: userId,
644
+ keys_p256dh: keysP256dh,
645
+ keys_auth: keysAuth,
646
+ });
647
+ return;
648
+ }
649
+ store.insert('push_subscriptions', {
650
+ user_id: userId,
651
+ endpoint,
652
+ keys_p256dh: keysP256dh,
653
+ keys_auth: keysAuth,
654
+ created_at: nowIso(),
655
+ });
656
+ },
657
+
658
+ getSubscriptions: (userId) =>
659
+ store.filterWhere('push_subscriptions', (r) => r.user_id === userId).map((r) => ({
660
+ endpoint: r.endpoint,
661
+ keys_p256dh: r.keys_p256dh,
662
+ keys_auth: r.keys_auth,
663
+ })),
664
+
665
+ removeSubscription: (endpoint) => {
666
+ store.deleteWhere('push_subscriptions', (r) => r.endpoint === endpoint);
667
+ },
668
+
669
+ removeAllForUser: (userId) => {
670
+ store.deleteWhere('push_subscriptions', (r) => r.user_id === userId);
671
+ },
672
+ };
673
+
674
+ // ---------------------------------------------------------------------------
675
+ // VAPID key storage (for web push)
676
+ // ---------------------------------------------------------------------------
677
+ const vapidKeysDb = {
678
+ getLatest: () => {
679
+ if (store.raw.vapid_keys.length === 0) return null;
680
+ // Mirror ORDER BY id DESC LIMIT 1 — take the newest row.
681
+ const rows = store.raw.vapid_keys.slice().sort((a, b) => b.id - a.id);
682
+ return { public_key: rows[0].public_key, private_key: rows[0].private_key };
683
+ },
684
+ insert: (publicKey, privateKey) => {
685
+ store.insert('vapid_keys', {
686
+ public_key: publicKey,
687
+ private_key: privateKey,
688
+ created_at: nowIso(),
689
+ });
690
+ },
691
+ };
692
+
693
+ // ---------------------------------------------------------------------------
694
+ // Session custom names
695
+ // ---------------------------------------------------------------------------
696
+ const sessionNamesDb = {
697
+ setName: (sessionId, provider, customName) => {
698
+ store.upsertWhere(
699
+ 'session_names',
700
+ (r) => r.session_id === sessionId && r.provider === provider,
701
+ { session_id: sessionId, provider, custom_name: customName, updated_at: nowIso(), created_at: nowIso() },
702
+ );
703
+ },
704
+
705
+ getName: (sessionId, provider) => {
706
+ const row = store.findWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider);
707
+ return row?.custom_name || null;
708
+ },
709
+
710
+ getNames: (sessionIds, provider) => {
711
+ if (!sessionIds.length) return new Map();
712
+ const lookup = new Set(sessionIds);
713
+ const matches = store.filterWhere('session_names',
714
+ (r) => r.provider === provider && lookup.has(r.session_id));
715
+ return new Map(matches.map((r) => [r.session_id, r.custom_name]));
716
+ },
717
+
718
+ deleteName: (sessionId, provider) =>
719
+ store.deleteWhere('session_names', (r) => r.session_id === sessionId && r.provider === provider) > 0,
720
+ };
721
+
722
+ function applyCustomSessionNames(sessions, provider) {
723
+ if (!sessions?.length) return;
724
+ try {
725
+ const ids = sessions.map((s) => s.id);
726
+ const customNames = sessionNamesDb.getNames(ids, provider);
727
+ for (const session of sessions) {
728
+ const custom = customNames.get(session.id);
729
+ if (custom) session.summary = custom;
730
+ }
731
+ } catch (error) {
732
+ console.warn(`[DB] Failed to apply custom session names for ${provider}:`, error.message);
733
+ }
734
+ }
735
+
736
+ // ---------------------------------------------------------------------------
737
+ // App config (key/value)
738
+ // ---------------------------------------------------------------------------
739
+ const appConfigDb = {
740
+ get: (key) => {
741
+ const row = store.findWhere('app_config', (r) => r.key === key);
742
+ return row?.value || null;
743
+ },
744
+
745
+ set: (key, value) => {
746
+ store.upsertWhere('app_config', (r) => r.key === key,
747
+ { key, value, created_at: nowIso() });
748
+ },
749
+
750
+ getOrCreateJwtSecret: () => {
751
+ let secret = appConfigDb.get('jwt_secret');
752
+ if (!secret) {
753
+ secret = crypto.randomBytes(64).toString('hex');
754
+ appConfigDb.set('jwt_secret', secret);
755
+ }
756
+ return secret;
757
+ },
758
+ };
759
+
760
+ // ---------------------------------------------------------------------------
761
+ // Telegram — singleton config + per-user links
762
+ // ---------------------------------------------------------------------------
763
+ const DEFAULT_TELEGRAM_CONTROL_STATE = {
764
+ remoteControlEnabled: true,
765
+ routerEnabled: true,
766
+ routerMode: 'hybrid',
767
+ routerProvider: null,
768
+ routerModel: null,
769
+ confirmationPolicy: 'strict',
770
+ pendingConfirmation: null,
771
+ progressMode: 'final',
772
+ selectedProjectName: null,
773
+ selectedProjectPath: null,
774
+ selectedProvider: 'opencode',
775
+ selectedModel: null,
776
+ selectedWorkflowId: null,
777
+ activeTerminal: null,
778
+ awaiting: null,
779
+ };
780
+
781
+ function normalizeTelegramControlState(value = {}) {
782
+ const raw = value && typeof value === 'object' ? value : {};
783
+ const selectedProvider = ['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'].includes(raw.selectedProvider)
784
+ ? raw.selectedProvider
785
+ : DEFAULT_TELEGRAM_CONTROL_STATE.selectedProvider;
786
+ const routerProvider = ['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'].includes(raw.routerProvider)
787
+ ? raw.routerProvider
788
+ : null;
789
+ const progressMode = ['final', 'steps', 'all', 'errors'].includes(raw.progressMode)
790
+ ? raw.progressMode
791
+ : DEFAULT_TELEGRAM_CONTROL_STATE.progressMode;
792
+ const pendingConfirmation = raw.pendingConfirmation && typeof raw.pendingConfirmation === 'object'
793
+ && typeof raw.pendingConfirmation.id === 'string'
794
+ && typeof raw.pendingConfirmation.action === 'string'
795
+ && typeof raw.pendingConfirmation.expiresAt === 'string'
796
+ ? {
797
+ id: raw.pendingConfirmation.id,
798
+ action: raw.pendingConfirmation.action,
799
+ payload: raw.pendingConfirmation.payload && typeof raw.pendingConfirmation.payload === 'object'
800
+ ? raw.pendingConfirmation.payload
801
+ : {},
802
+ expiresAt: raw.pendingConfirmation.expiresAt,
803
+ }
804
+ : null;
805
+ const activeTerminal = raw.activeTerminal && typeof raw.activeTerminal === 'object'
806
+ && ['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'].includes(raw.activeTerminal.provider)
807
+ && typeof raw.activeTerminal.projectPath === 'string'
808
+ && raw.activeTerminal.projectPath.trim()
809
+ ? {
810
+ provider: raw.activeTerminal.provider,
811
+ projectPath: raw.activeTerminal.projectPath.trim(),
812
+ projectName: typeof raw.activeTerminal.projectName === 'string' && raw.activeTerminal.projectName.trim()
813
+ ? raw.activeTerminal.projectName.trim()
814
+ : null,
815
+ projectLabel: typeof raw.activeTerminal.projectLabel === 'string' && raw.activeTerminal.projectLabel.trim()
816
+ ? raw.activeTerminal.projectLabel.trim()
817
+ : null,
818
+ sessionId: typeof raw.activeTerminal.sessionId === 'string' && raw.activeTerminal.sessionId.trim()
819
+ ? raw.activeTerminal.sessionId.trim()
820
+ : null,
821
+ tabId: typeof raw.activeTerminal.tabId === 'string' && raw.activeTerminal.tabId.trim()
822
+ ? raw.activeTerminal.tabId.trim()
823
+ : null,
824
+ attachedAt: typeof raw.activeTerminal.attachedAt === 'string' && raw.activeTerminal.attachedAt.trim()
825
+ ? raw.activeTerminal.attachedAt.trim()
826
+ : nowIso(),
827
+ }
828
+ : null;
829
+
830
+ return {
831
+ ...DEFAULT_TELEGRAM_CONTROL_STATE,
832
+ ...raw,
833
+ remoteControlEnabled: raw.remoteControlEnabled !== false,
834
+ routerEnabled: raw.routerEnabled !== false,
835
+ routerMode: raw.routerMode === 'hybrid' ? 'hybrid' : DEFAULT_TELEGRAM_CONTROL_STATE.routerMode,
836
+ routerProvider,
837
+ routerModel: typeof raw.routerModel === 'string' && raw.routerModel.trim() ? raw.routerModel.trim() : null,
838
+ confirmationPolicy: 'strict',
839
+ pendingConfirmation,
840
+ progressMode,
841
+ selectedProvider,
842
+ selectedProjectName: typeof raw.selectedProjectName === 'string' ? raw.selectedProjectName : null,
843
+ selectedProjectPath: typeof raw.selectedProjectPath === 'string' ? raw.selectedProjectPath : null,
844
+ selectedModel: typeof raw.selectedModel === 'string' ? raw.selectedModel : null,
845
+ selectedWorkflowId: typeof raw.selectedWorkflowId === 'string' ? raw.selectedWorkflowId : null,
846
+ activeTerminal,
847
+ awaiting: raw.awaiting && typeof raw.awaiting === 'object' ? raw.awaiting : null,
848
+ };
849
+ }
850
+
851
+ const telegramConfigDb = {
852
+ get: () => {
853
+ const row = store.raw.telegram_config[0];
854
+ if (!row) return null;
855
+ return { bot_token: row.bot_token, bot_username: row.bot_username, updated_at: row.updated_at };
856
+ },
857
+ set: (botToken, botUsername = null) => {
858
+ store.raw.telegram_config = [{
859
+ id: 1,
860
+ bot_token: botToken,
861
+ bot_username: botUsername,
862
+ updated_at: nowIso(),
863
+ }];
864
+ store.save();
865
+ },
866
+ clear: () => {
867
+ store.raw.telegram_config = [];
868
+ store.save();
869
+ },
870
+ };
871
+
872
+ const telegramLinksDb = {
873
+ setPairingCode: (userId, code, expiresAt, language) => {
874
+ store.upsertWhere('telegram_links', (r) => r.user_id === userId, {
875
+ user_id: userId,
876
+ pairing_code: code,
877
+ pairing_code_expires_at: expiresAt,
878
+ language,
879
+ chat_id: null,
880
+ telegram_username: null,
881
+ verified_at: null,
882
+ notifications_enabled: true,
883
+ bridge_enabled: true,
884
+ telegram_control: normalizeTelegramControlState(),
885
+ updated_at: nowIso(),
886
+ });
887
+ },
888
+ findByPairingCode: (code) => {
889
+ const row = store.findWhere('telegram_links', (r) => r.pairing_code === code);
890
+ if (!row) return null;
891
+ return {
892
+ user_id: row.user_id,
893
+ pairing_code: row.pairing_code,
894
+ pairing_code_expires_at: row.pairing_code_expires_at,
895
+ language: row.language,
896
+ };
897
+ },
898
+ verify: (userId, chatId, telegramUsername) => {
899
+ store.updateWhere('telegram_links', (r) => r.user_id === userId, {
900
+ chat_id: chatId,
901
+ telegram_username: telegramUsername,
902
+ verified_at: nowIso(),
903
+ pairing_code: null,
904
+ pairing_code_expires_at: null,
905
+ updated_at: nowIso(),
906
+ });
907
+ },
908
+ getByUserId: (userId) => {
909
+ const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
910
+ return row ? { ...row } : null;
911
+ },
912
+ getByChatId: (chatId) => {
913
+ const row = store.findWhere('telegram_links', (r) => r.chat_id === chatId);
914
+ if (!row) return null;
915
+ return {
916
+ user_id: row.user_id,
917
+ chat_id: row.chat_id,
918
+ telegram_username: row.telegram_username,
919
+ language: row.language,
920
+ notifications_enabled: row.notifications_enabled,
921
+ bridge_enabled: row.bridge_enabled,
922
+ telegram_control: normalizeTelegramControlState(row.telegram_control),
923
+ };
924
+ },
925
+ listVerified: () =>
926
+ store.filterWhere('telegram_links', (r) => r.chat_id && r.verified_at).map((r) => ({
927
+ user_id: r.user_id,
928
+ chat_id: r.chat_id,
929
+ telegram_username: r.telegram_username,
930
+ language: r.language,
931
+ notifications_enabled: r.notifications_enabled,
932
+ bridge_enabled: r.bridge_enabled,
933
+ telegram_control: normalizeTelegramControlState(r.telegram_control),
934
+ })),
935
+ updatePreferences: (userId, { language, notificationsEnabled, bridgeEnabled }) => {
936
+ const patch = { updated_at: nowIso() };
937
+ if (language !== undefined) patch.language = language;
938
+ if (notificationsEnabled !== undefined) patch.notifications_enabled = Boolean(notificationsEnabled);
939
+ if (bridgeEnabled !== undefined) patch.bridge_enabled = Boolean(bridgeEnabled);
940
+ if (Object.keys(patch).length === 1) return; // only updated_at → no real change
941
+ store.updateWhere('telegram_links', (r) => r.user_id === userId, patch);
942
+ },
943
+ getControlState: (userId) => {
944
+ const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
945
+ return normalizeTelegramControlState(row?.telegram_control);
946
+ },
947
+ updateControlState: (userId, patch) => {
948
+ const row = store.findWhere('telegram_links', (r) => r.user_id === userId);
949
+ const current = normalizeTelegramControlState(row?.telegram_control);
950
+ const next = normalizeTelegramControlState({ ...current, ...(patch || {}) });
951
+ store.updateWhere('telegram_links', (r) => r.user_id === userId, {
952
+ telegram_control: next,
953
+ updated_at: nowIso(),
954
+ });
955
+ return next;
956
+ },
957
+ unlink: (userId) => {
958
+ store.deleteWhere('telegram_links', (r) => r.user_id === userId);
959
+ },
960
+ };
961
+
962
+ // Back-compat surface — older callers used `githubTokensDb.*`; internally
963
+ // they always delegated to credentialsDb with `credential_type='github_token'`.
964
+ const githubTokensDb = {
965
+ createGithubToken: (userId, tokenName, githubToken, description = null) =>
966
+ credentialsDb.createCredential(userId, tokenName, 'github_token', githubToken, description),
967
+ getGithubTokens: (userId) => credentialsDb.getCredentials(userId, 'github_token'),
968
+ getActiveGithubToken: (userId) => credentialsDb.getActiveCredential(userId, 'github_token'),
969
+ deleteGithubToken: (userId, tokenId) => credentialsDb.deleteCredential(userId, tokenId),
970
+ toggleGithubToken: (userId, tokenId, isActive) => credentialsDb.toggleCredential(userId, tokenId, isActive),
971
+ };
972
+
973
+ export {
974
+ db,
975
+ initializeDatabase,
976
+ userDb,
977
+ apiKeysDb,
978
+ credentialsDb,
979
+ notificationPreferencesDb,
980
+ pushSubscriptionsDb,
981
+ vapidKeysDb,
982
+ sessionNamesDb,
983
+ applyCustomSessionNames,
984
+ appConfigDb,
985
+ telegramConfigDb,
986
+ telegramLinksDb,
987
+ githubTokensDb,
988
+ };