@myrialabs/clopen 0.4.46 → 0.4.48

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 (328) hide show
  1. package/README.md +11 -11
  2. package/backend/artifacts/project/sources.ts +1 -1
  3. package/backend/auth/auth-service.ts +52 -358
  4. package/backend/auth/onboarding.test.ts +2 -3
  5. package/backend/auth/permissions.test.ts +10 -20
  6. package/backend/auth/permissions.ts +4 -290
  7. package/backend/auth/rate-limiter.test.ts +8 -9
  8. package/backend/auth/rate-limiter.ts +0 -2
  9. package/backend/auth/tokens.ts +1 -8
  10. package/backend/bootstrap.ts +7 -0
  11. package/backend/chat/attachments.test.ts +88 -0
  12. package/backend/chat/attachments.ts +159 -0
  13. package/backend/chat/engine-handoff.test.ts +0 -2
  14. package/backend/chat/stream-manager.ts +62 -62
  15. package/backend/chat/turn-answer.test.ts +64 -0
  16. package/backend/chat/turn-answer.ts +125 -0
  17. package/backend/chat-apps/awaiting.test.ts +39 -0
  18. package/backend/chat-apps/awaiting.ts +49 -0
  19. package/backend/chat-apps/conversation.ts +746 -0
  20. package/backend/chat-apps/inbound.ts +324 -0
  21. package/backend/chat-apps/index.ts +309 -0
  22. package/backend/chat-apps/link-events.ts +20 -0
  23. package/backend/chat-apps/media.test.ts +62 -0
  24. package/backend/chat-apps/media.ts +208 -0
  25. package/backend/chat-apps/messages.test.ts +229 -0
  26. package/backend/chat-apps/messages.ts +365 -0
  27. package/backend/chat-apps/outbound.ts +243 -0
  28. package/backend/chat-apps/pairing.test.ts +45 -0
  29. package/backend/chat-apps/pairing.ts +74 -0
  30. package/backend/chat-apps/platforms/index.ts +20 -0
  31. package/backend/chat-apps/platforms/telegram.test.ts +35 -0
  32. package/backend/chat-apps/platforms/telegram.ts +191 -0
  33. package/backend/chat-apps/platforms/types.ts +114 -0
  34. package/backend/chat-apps/questions.ts +133 -0
  35. package/backend/chat-apps/runtime.ts +572 -0
  36. package/backend/chat-apps/storage.test.ts +201 -0
  37. package/backend/chat-apps/turns.test.ts +45 -0
  38. package/backend/chat-apps/turns.ts +208 -0
  39. package/backend/containers/pty.ts +3 -11
  40. package/backend/control/actions/accounts.ts +89 -0
  41. package/backend/control/actions/files.ts +116 -0
  42. package/backend/control/actions/models.ts +188 -0
  43. package/backend/control/actions/projects.ts +272 -0
  44. package/backend/control/actions/sessions.ts +280 -0
  45. package/backend/control/actions/skills.ts +111 -0
  46. package/backend/control/control.test.ts +169 -0
  47. package/backend/control/define.ts +20 -0
  48. package/backend/control/folders.test.ts +67 -0
  49. package/backend/control/index.ts +213 -0
  50. package/backend/control/invoke.ts +44 -0
  51. package/backend/control/links.ts +35 -0
  52. package/backend/control/paging.ts +26 -0
  53. package/backend/control/types.ts +117 -0
  54. package/backend/control/workspace.ts +127 -0
  55. package/backend/database/migrations/084_create_channel_links.ts +71 -0
  56. package/backend/database/migrations/085_add_home_projects.ts +36 -0
  57. package/backend/database/migrations/086_single_owner.test.ts +170 -0
  58. package/backend/database/migrations/086_single_owner.ts +418 -0
  59. package/backend/database/migrations/index.ts +21 -0
  60. package/backend/database/queries/auth-queries.ts +7 -85
  61. package/backend/database/queries/channel-queries.ts +270 -0
  62. package/backend/database/queries/db-client-connection-queries.ts +18 -56
  63. package/backend/database/queries/file-share-queries.ts +5 -23
  64. package/backend/database/queries/git-identity-queries.ts +31 -42
  65. package/backend/database/queries/graph-queries.ts +1 -1
  66. package/backend/database/queries/index.ts +13 -1
  67. package/backend/database/queries/message-queries.test.ts +146 -0
  68. package/backend/database/queries/message-queries.ts +42 -1
  69. package/backend/database/queries/permission-set-queries.ts +1 -1
  70. package/backend/database/queries/profile-queries.ts +1 -1
  71. package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
  72. package/backend/database/queries/project-queries.ts +50 -63
  73. package/backend/database/queries/session-queries.ts +28 -56
  74. package/backend/database/queries/ssh-connection-queries.ts +18 -41
  75. package/backend/db-client/integrations/projector.ts +0 -5
  76. package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
  77. package/backend/engine/adapters/claude/message-converter.ts +25 -2
  78. package/backend/engine/adapters/cline/message-converter.ts +0 -1
  79. package/backend/engine/adapters/cline/stream.ts +11 -15
  80. package/backend/engine/adapters/codex/message-converter.ts +0 -2
  81. package/backend/engine/adapters/copilot/message-converter.ts +1 -2
  82. package/backend/engine/adapters/cursor/message-converter.ts +0 -1
  83. package/backend/engine/adapters/opencode/message-converter.ts +2 -4
  84. package/backend/engine/adapters/opencode/presets.ts +27 -2
  85. package/backend/engine/adapters/opencode/server.ts +6 -4
  86. package/backend/engine/adapters/opencode/stream.ts +11 -0
  87. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  88. package/backend/engine/adapters/parent-scope.ts +44 -0
  89. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  90. package/backend/engine/adapters/pi/stream.ts +4 -5
  91. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  92. package/backend/engine/bootstrap-default-engine.ts +2 -2
  93. package/backend/engine/docs/adapter-contract.md +8 -1
  94. package/backend/engine/install-runner.ts +8 -17
  95. package/backend/files/file-shares.ts +20 -44
  96. package/backend/files/file-size-limit.ts +3 -3
  97. package/backend/files/image-processing.ts +1 -1
  98. package/backend/files/os-clipboard.ts +2 -2
  99. package/backend/git/git-executor.ts +25 -5
  100. package/backend/git/git-service.ts +420 -19
  101. package/backend/git/identity/credential-helper.test.ts +2 -7
  102. package/backend/git/identity/import-local.test.ts +11 -16
  103. package/backend/git/identity/import-local.ts +12 -12
  104. package/backend/git/identity/index.ts +10 -24
  105. package/backend/git/identity/resolve.ts +13 -14
  106. package/backend/git/identity/scope-config.ts +33 -28
  107. package/backend/git/identity/service.ts +44 -47
  108. package/backend/git/op-lock.test.ts +111 -0
  109. package/backend/git/op-lock.ts +180 -0
  110. package/backend/git/remote-sync.test.ts +249 -0
  111. package/backend/host/metrics.ts +1 -1
  112. package/backend/http/bearer-auth.ts +1 -2
  113. package/backend/http/files-download.test.ts +8 -9
  114. package/backend/http/files-download.ts +2 -2
  115. package/backend/http/files-shared.test.ts +62 -89
  116. package/backend/http/files-shared.ts +2 -2
  117. package/backend/http/files-upload.test.ts +3 -7
  118. package/backend/http/files-upload.ts +3 -3
  119. package/backend/http/notes-images.test.ts +15 -38
  120. package/backend/http/notes-images.ts +6 -8
  121. package/backend/http/ssh-sftp.ts +5 -10
  122. package/backend/index.ts +21 -7
  123. package/backend/integrations/accounts.ts +61 -3
  124. package/backend/integrations/index.ts +2 -2
  125. package/backend/integrations/registry/define.ts +15 -0
  126. package/backend/integrations/registry/index.ts +2 -0
  127. package/backend/integrations/registry/providers/telegram.ts +54 -0
  128. package/backend/integrations/registry/types.ts +21 -1
  129. package/backend/integrations/webhooks/gateway.ts +7 -6
  130. package/backend/integrations/webhooks/verify.test.ts +30 -0
  131. package/backend/integrations/webhooks/verify.ts +4 -0
  132. package/backend/mcp/external/project.ts +1 -1
  133. package/backend/mcp/internal/remote-server.test.ts +1 -3
  134. package/backend/mcp/internal/remote-server.ts +4 -4
  135. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  136. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  137. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  138. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  139. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  140. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  141. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  142. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  143. package/backend/memory/redact.ts +1 -1
  144. package/backend/notes/access.test.ts +28 -29
  145. package/backend/notes/access.ts +6 -11
  146. package/backend/permissions/service.ts +1 -1
  147. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  148. package/backend/preview/browser/browser-clipboard.ts +67 -0
  149. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  150. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  151. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  152. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  153. package/backend/preview/browser/browser-pool.ts +67 -6
  154. package/backend/preview/browser/browser-preview-service.ts +361 -25
  155. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  156. package/backend/preview/browser/browser-video-capture.ts +92 -5
  157. package/backend/preview/browser/element-locator.ts +190 -17
  158. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  159. package/backend/preview/browser/keyboard-chords.ts +132 -0
  160. package/backend/preview/browser/paste.ts +81 -0
  161. package/backend/preview/browser/process-usage.ts +142 -0
  162. package/backend/preview/browser/profile-lock.ts +209 -0
  163. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  164. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  165. package/backend/preview/browser/types.ts +40 -2
  166. package/backend/preview/browser/viewport.test.ts +45 -0
  167. package/backend/preview/browser/viewport.ts +96 -0
  168. package/backend/profiles/service.ts +2 -2
  169. package/backend/project/status-manager.ts +43 -172
  170. package/backend/projects/home.ts +61 -0
  171. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  172. package/backend/projects/project-cleanup.ts +0 -8
  173. package/backend/skills/service.ts +2 -3
  174. package/backend/snapshot/helpers.ts +0 -1
  175. package/backend/snapshot/restore.ts +252 -0
  176. package/backend/ssh/ptykit.ts +1 -2
  177. package/backend/terminal/ptykit.ts +5 -8
  178. package/backend/tunnel/public-origin.ts +31 -20
  179. package/backend/utils/user-helpers.ts +0 -55
  180. package/backend/utils/ws.ts +61 -154
  181. package/backend/worktrees/branching/engine.ts +3 -16
  182. package/backend/worktrees/branching/index.ts +1 -1
  183. package/backend/worktrees/branching/projector.ts +1 -1
  184. package/backend/worktrees/branching/service.ts +13 -25
  185. package/backend/ws/access.ts +12 -21
  186. package/backend/ws/artifacts/generate.ts +2 -2
  187. package/backend/ws/auth/device.ts +16 -71
  188. package/backend/ws/auth/index.ts +4 -22
  189. package/backend/ws/auth/login.test.ts +14 -60
  190. package/backend/ws/auth/login.ts +24 -124
  191. package/backend/ws/auth/status.ts +0 -1
  192. package/backend/ws/chat/composer.ts +118 -118
  193. package/backend/ws/chat/stream.ts +64 -47
  194. package/backend/ws/chat-apps/index.ts +117 -0
  195. package/backend/ws/containers/actions.ts +11 -25
  196. package/backend/ws/containers/index.ts +3 -4
  197. package/backend/ws/containers/list.ts +10 -36
  198. package/backend/ws/containers/logs.ts +2 -2
  199. package/backend/ws/containers/tunnel.ts +1 -2
  200. package/backend/ws/db-client/access.ts +2 -16
  201. package/backend/ws/db-client/accounts.ts +5 -15
  202. package/backend/ws/db-client/connections.ts +17 -25
  203. package/backend/ws/db-client/context.ts +1 -1
  204. package/backend/ws/db-client/env.ts +7 -10
  205. package/backend/ws/db-client/index.ts +2 -2
  206. package/backend/ws/db-client/io.ts +5 -5
  207. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  208. package/backend/ws/db-client/query.ts +18 -17
  209. package/backend/ws/db-client/schema.ts +13 -13
  210. package/backend/ws/db-client/structure.ts +35 -35
  211. package/backend/ws/db-client/supabase.ts +4 -21
  212. package/backend/ws/deployments/context.ts +1 -1
  213. package/backend/ws/deployments/crud.ts +0 -5
  214. package/backend/ws/engine/access.ts +7 -20
  215. package/backend/ws/engine/claude/accounts.ts +4 -4
  216. package/backend/ws/engine/cline/accounts.ts +5 -5
  217. package/backend/ws/engine/codex/accounts.ts +3 -3
  218. package/backend/ws/engine/opencode/providers.ts +2 -1
  219. package/backend/ws/engine/pi/accounts.ts +5 -5
  220. package/backend/ws/files/clipboard.ts +8 -27
  221. package/backend/ws/files/image-edit.ts +6 -6
  222. package/backend/ws/files/index.ts +1 -1
  223. package/backend/ws/files/path-access.test.ts +32 -131
  224. package/backend/ws/files/path-access.ts +8 -87
  225. package/backend/ws/files/read.ts +15 -19
  226. package/backend/ws/files/reveal.ts +3 -3
  227. package/backend/ws/files/search.ts +7 -7
  228. package/backend/ws/files/share.ts +9 -13
  229. package/backend/ws/files/state.ts +9 -12
  230. package/backend/ws/files/watch.ts +3 -3
  231. package/backend/ws/files/write.ts +30 -31
  232. package/backend/ws/git/branch.ts +80 -59
  233. package/backend/ws/git/commit.ts +63 -44
  234. package/backend/ws/git/conflict.ts +16 -18
  235. package/backend/ws/git/identity-context.ts +8 -17
  236. package/backend/ws/git/identity.ts +17 -27
  237. package/backend/ws/git/index.ts +3 -1
  238. package/backend/ws/git/op-state.ts +139 -0
  239. package/backend/ws/git/remote.ts +241 -141
  240. package/backend/ws/git/repo-context.ts +67 -0
  241. package/backend/ws/git/staging.ts +18 -28
  242. package/backend/ws/git/status.ts +5 -2
  243. package/backend/ws/index.ts +5 -1
  244. package/backend/ws/instructions/crud.ts +1 -1
  245. package/backend/ws/integrations/crud.ts +1 -3
  246. package/backend/ws/mcp/crud.ts +3 -5
  247. package/backend/ws/mcp/tools.ts +1 -1
  248. package/backend/ws/memory/crud.ts +14 -46
  249. package/backend/ws/memory/index.ts +2 -2
  250. package/backend/ws/messages/crud.ts +29 -8
  251. package/backend/ws/notes/index.ts +33 -39
  252. package/backend/ws/permissions/crud.ts +3 -4
  253. package/backend/ws/ports/index.ts +1 -2
  254. package/backend/ws/ports/kill.ts +5 -10
  255. package/backend/ws/ports/list.ts +4 -10
  256. package/backend/ws/preview/access.ts +1 -1
  257. package/backend/ws/preview/browser/interact.ts +52 -79
  258. package/backend/ws/preview/browser/native-ui.ts +24 -0
  259. package/backend/ws/preview/browser/stats.ts +98 -1
  260. package/backend/ws/preview/browser/tab-info.ts +15 -0
  261. package/backend/ws/preview/browser/tab.ts +19 -4
  262. package/backend/ws/preview/index.ts +27 -0
  263. package/backend/ws/profiles/crud.ts +6 -8
  264. package/backend/ws/project-artifacts/index.ts +30 -31
  265. package/backend/ws/projects/crud.ts +33 -35
  266. package/backend/ws/projects/index.ts +3 -8
  267. package/backend/ws/projects/info.ts +3 -3
  268. package/backend/ws/projects/overview.ts +19 -30
  269. package/backend/ws/projects/status.ts +17 -57
  270. package/backend/ws/sessions/crud.ts +34 -45
  271. package/backend/ws/sessions/index.ts +1 -1
  272. package/backend/ws/settings/crud.ts +1 -1
  273. package/backend/ws/skills/crud.ts +3 -4
  274. package/backend/ws/skills/index.ts +1 -1
  275. package/backend/ws/snapshot/changes.ts +7 -7
  276. package/backend/ws/snapshot/restore.ts +11 -295
  277. package/backend/ws/snapshot/timeline.ts +2 -4
  278. package/backend/ws/ssh/access.ts +6 -21
  279. package/backend/ws/ssh/connections.ts +21 -31
  280. package/backend/ws/ssh/forwards.ts +12 -12
  281. package/backend/ws/ssh/sftp.ts +34 -34
  282. package/backend/ws/ssh/tunnel.ts +1 -2
  283. package/backend/ws/stack/install.ts +7 -17
  284. package/backend/ws/subagents/crud.ts +1 -1
  285. package/backend/ws/tunnel/share.ts +0 -2
  286. package/backend/ws/user/crud.ts +1 -59
  287. package/backend/ws/user/index.ts +1 -1
  288. package/backend/ws/work/context.ts +1 -1
  289. package/backend/ws/work/crud.ts +0 -5
  290. package/backend/ws/workspace/state.ts +10 -13
  291. package/backend/ws/worktrees/branching.ts +7 -36
  292. package/backend/ws/worktrees/crud.ts +2 -2
  293. package/bin/clopen.ts +10 -11
  294. package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
  295. package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
  296. package/dist/assets/main-BUiUL3eZ.css +1 -0
  297. package/dist/assets/main-nBOb9YOA.js +1240 -0
  298. package/dist/index.html +2 -2
  299. package/package.json +2 -1
  300. package/shared/constants/attachments.ts +14 -0
  301. package/shared/constants/engine-tools.ts +1 -1
  302. package/shared/constants/preview.test.ts +259 -0
  303. package/shared/constants/preview.ts +1018 -57
  304. package/shared/constants/tool-icons.ts +5 -0
  305. package/shared/types/containers/container.ts +1 -1
  306. package/shared/types/database/schema.ts +9 -6
  307. package/shared/types/git-identity.ts +1 -1
  308. package/shared/types/git.ts +116 -0
  309. package/shared/types/integrations.ts +7 -0
  310. package/shared/types/stores/settings.ts +1 -1
  311. package/shared/types/unified/index.ts +1 -1
  312. package/shared/types/unified/message.ts +0 -7
  313. package/shared/types/unified/stream.ts +2 -4
  314. package/shared/types/unified/tool.ts +15 -1
  315. package/shared/utils/ask-user-question.test.ts +319 -0
  316. package/shared/utils/ask-user-question.ts +154 -0
  317. package/shared/utils/home-project.ts +25 -0
  318. package/shared/utils/logger.ts +2 -0
  319. package/shared/utils/ws-server.ts +32 -7
  320. package/backend/auth/session-invalidation.test.ts +0 -112
  321. package/backend/auth/session-invalidation.ts +0 -77
  322. package/backend/project/status-manager.test.ts +0 -32
  323. package/backend/ws/auth/invites.ts +0 -94
  324. package/backend/ws/auth/users.ts +0 -112
  325. package/backend/ws/projects/presence.ts +0 -46
  326. package/backend/ws/stack/access.ts +0 -31
  327. package/dist/assets/main-BiDNMWb3.css +0 -1
  328. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -0,0 +1,572 @@
1
+ /**
2
+ * The channel runtime — one backend-owned `ChatKit`, one adapter per connected
3
+ * bot, kept in step with the accounts table.
4
+ *
5
+ * DELIVERY IS ADAPTIVE, the way Share Link is. A platform that can push to a
6
+ * webhook gets one when Clopen has a public HTTPS origin: the configured URL,
7
+ * else the non-local origin a browser last reached Clopen on, else a
8
+ * Cloudflare quick tunnel started for it — the same three steps Remote Access
9
+ * resolves. When none can be had (the tunnel binary cannot be fetched, the
10
+ * platform refuses the URL) the bot long-polls instead, which needs no public
11
+ * URL at all. Either way the user connected a bot and it works.
12
+ *
13
+ * A quick tunnel's URL changes every time it restarts, so the runtime watches
14
+ * tunnelkit and re-registers when it moves. If the tunnel disappears the bot
15
+ * drops to polling rather than starting it again: a tunnel the user stopped by
16
+ * hand is a decision, and restarting it behind their back would be a fight.
17
+ * The next boot (or reconnecting the bot) brings webhooks back.
18
+ *
19
+ * Every reconcile is serialised on one promise chain. Adding and removing
20
+ * adapters, and registering webhooks, are all network round-trips, and two of
21
+ * them interleaving for one account is how a bot ends up registered twice.
22
+ */
23
+
24
+ import { createHash, createHmac } from 'crypto';
25
+ import { mkdirSync } from 'fs';
26
+ import { join } from 'path';
27
+ import { ChatKit, splitRuns, type AccountHealth, type SendResult, type TextRun, type UniversalMessage } from '@myrialabs/chatkit';
28
+ import { SqliteStore } from '@myrialabs/chatkit/store';
29
+ import { integrationAccountQueries, type IntegrationAccountRow } from '$backend/database/queries';
30
+ import { getMasterKey } from '$backend/database/crypto';
31
+ import { getProvider, withGeneratedCredentials, type WebhookEvent } from '$backend/integrations';
32
+ import { findPublicOrigin, isLocalHostname, resolvePublicOrigin, type PublicOrigin } from '$backend/tunnel/public-origin';
33
+ import { tunnelKit } from '$backend/tunnel/tunnel-config';
34
+ import { getClopenDir } from '$backend/utils/paths';
35
+ import { debug } from '$shared/utils/logger';
36
+ import {
37
+ getChannelPlatform,
38
+ listChannelPlatforms,
39
+ type ChannelButton,
40
+ type ChannelCard,
41
+ type ChannelCommand,
42
+ type ChannelFile,
43
+ type ChannelPlatform,
44
+ type DeliveryMode
45
+ } from './platforms';
46
+
47
+ export interface ActiveChannel {
48
+ accountId: string;
49
+ platform: ChannelPlatform;
50
+ mode: DeliveryMode;
51
+ /** The origin the webhook points at; null while polling. */
52
+ origin: PublicOrigin | null;
53
+ /** Changes when anything the adapter was built from changes. */
54
+ fingerprint: string;
55
+ }
56
+
57
+ export interface ChannelStatus {
58
+ running: boolean;
59
+ mode: DeliveryMode | null;
60
+ originSource: PublicOrigin['source'] | null;
61
+ connection: AccountHealth['state'] | null;
62
+ error: string | null;
63
+ }
64
+
65
+ export type InboundHandler = (message: UniversalMessage, channel: ActiveChannel) => Promise<void>;
66
+
67
+ /** What a bot's `/` menu holds — the same list `/help` shows. */
68
+ export interface CommandMenu {
69
+ commands(): ChannelCommand[];
70
+ /** The paired chats of a bot, whose own menus (from older versions) are cleared. */
71
+ chatsOf(accountId: string): string[];
72
+ }
73
+
74
+ /** A file a chat sent, read out of ChatKit's media store. */
75
+ export interface InboundFile {
76
+ data: Uint8Array;
77
+ mime: string | null;
78
+ filename: string | null;
79
+ }
80
+
81
+ /** The hook URL the gateway serves for a provider. */
82
+ function hookUrl(origin: string, provider: string): string {
83
+ return `${origin}/api/integrations/hooks/${provider}`;
84
+ }
85
+
86
+ /** Push platforms only deliver to HTTPS, and never to a host they cannot reach. */
87
+ function usableForWebhook(origin: PublicOrigin | null): origin is PublicOrigin {
88
+ if (!origin) return false;
89
+ try {
90
+ const url = new URL(origin.origin);
91
+ return url.protocol === 'https:' && !isLocalHostname(url.hostname);
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+
97
+ function fingerprintOf(row: IntegrationAccountRow, credentials: Record<string, string>): string {
98
+ return createHash('sha256').update(JSON.stringify([row.provider, credentials])).digest('hex');
99
+ }
100
+
101
+ function describe(error: unknown): string {
102
+ return error instanceof Error ? error.message : String(error);
103
+ }
104
+
105
+ /**
106
+ * ChatKit's own state (dedup keys, polling offsets, any adapter auth state)
107
+ * is sealed with a key DERIVED from Clopen's master key — so it rotates,
108
+ * backs up and restores with everything else Clopen seals, and is never a
109
+ * second secret for the operator to keep.
110
+ */
111
+ function deriveStateKey(): string {
112
+ return createHmac('sha256', getMasterKey().key).update('clopen/chatkit-state/v1').digest('base64url');
113
+ }
114
+
115
+ /** Namespace for Clopen's own entries in ChatKit's kv area. */
116
+ const KV_NAMESPACE = 'clopen';
117
+ const KV_BROWSER_ORIGIN = 'browser-origin';
118
+
119
+ /** Coalesces a burst of bot status changes into one "refresh" for Settings. */
120
+ const STATUS_DEBOUNCE_MS = 400;
121
+
122
+ /** Coalesces a burst of tunnel status events into one re-evaluation. */
123
+ const TUNNEL_DEBOUNCE_MS = 1500;
124
+
125
+ class ChannelRuntime {
126
+ private chat: ChatKit | null = null;
127
+ private readonly active = new Map<string, ActiveChannel>();
128
+ private readonly failures = new Map<string, string>();
129
+ private chain: Promise<void> = Promise.resolve();
130
+ private inboundHandler: InboundHandler | null = null;
131
+ private menu: CommandMenu | null = null;
132
+ private statusListener: (() => void) | null = null;
133
+ private statusTimer: ReturnType<typeof setTimeout> | null = null;
134
+ private browserOrigin: string | null = null;
135
+ private tunnelTimer: ReturnType<typeof setTimeout> | null = null;
136
+ private readonly onTunnelChange = (): void => {
137
+ if (this.tunnelTimer) clearTimeout(this.tunnelTimer);
138
+ this.tunnelTimer = setTimeout(() => {
139
+ this.tunnelTimer = null;
140
+ this.enqueue(() => this.reevaluateDelivery());
141
+ }, TUNNEL_DEBOUNCE_MS);
142
+ };
143
+
144
+ setInboundHandler(handler: InboundHandler): void {
145
+ this.inboundHandler = handler;
146
+ }
147
+
148
+ /**
149
+ * Told whenever what `status()` reports may have changed: a bot came up,
150
+ * went down, moved between webhook and polling, or its connection dropped
151
+ * or recovered. Settings refreshes on it instead of waiting to be reopened.
152
+ */
153
+ onStatusChanged(listener: () => void): void {
154
+ this.statusListener = listener;
155
+ }
156
+
157
+ /** Coalesced: a polling loop that drops and recovers would otherwise fire on every retry. */
158
+ private statusChanged(): void {
159
+ if (this.statusTimer) return;
160
+ this.statusTimer = setTimeout(() => {
161
+ this.statusTimer = null;
162
+ try {
163
+ this.statusListener?.();
164
+ } catch (error) {
165
+ debug.warn('chat-apps', 'Status listener failed:', describe(error));
166
+ }
167
+ }, STATUS_DEBOUNCE_MS);
168
+ this.statusTimer.unref?.();
169
+ }
170
+
171
+ /** The command menus every bot publishes when it comes up. */
172
+ setCommandMenu(menu: CommandMenu): void {
173
+ this.menu = menu;
174
+ }
175
+
176
+ /**
177
+ * Publish a bot's menu as its default, and drop any chat-specific menu a
178
+ * paired chat still carries so it shows the same one. Best effort: a bot
179
+ * whose menu could not be published still works by typing.
180
+ */
181
+ private publishCommands(platform: ChannelPlatform, accountId: string): void {
182
+ const adapter = this.chat?.adapterFor(platform.chatkit, accountId);
183
+ const menu = this.menu;
184
+ if (!adapter || !menu) return;
185
+ void platform.registerCommands(adapter, menu.commands()).catch((error) => {
186
+ debug.warn('chat-apps', 'Publishing the bot command menu failed:', describe(error));
187
+ });
188
+ for (const conversationId of menu.chatsOf(accountId)) {
189
+ void platform.clearCommands(adapter, conversationId).catch(() => {});
190
+ }
191
+ }
192
+
193
+ get isStarted(): boolean {
194
+ return this.chat !== null;
195
+ }
196
+
197
+ async start(): Promise<void> {
198
+ if (this.chat) return;
199
+ const dir = join(getClopenDir(), 'chatkit');
200
+ mkdirSync(dir, { recursive: true });
201
+
202
+ const chat = new ChatKit({
203
+ store: new SqliteStore({ path: join(dir, 'state.db'), stateKey: deriveStateKey() }),
204
+ logger: {
205
+ debug: (message, fields) => debug.log('chat-apps', `[chatkit] ${message}`, fields ?? ''),
206
+ info: (message, fields) => debug.log('chat-apps', `[chatkit] ${message}`, fields ?? ''),
207
+ warn: (message, fields) => debug.warn('chat-apps', `[chatkit] ${message}`, fields ?? ''),
208
+ error: (message, fields) => debug.error('chat-apps', `[chatkit] ${message}`, fields ?? '')
209
+ }
210
+ });
211
+ chat.on('message', (message) => this.dispatchInbound(message));
212
+ chat.on('connection', () => this.statusChanged());
213
+ chat.on('error', ({ platform, account, error }) => {
214
+ debug.warn('chat-apps', `Channel ${platform ?? '?'}:${account ?? '?'} error:`, error.message);
215
+ });
216
+ await chat.start();
217
+ this.chat = chat;
218
+
219
+ this.browserOrigin = await chat.store.kvGet(KV_NAMESPACE, KV_BROWSER_ORIGIN).catch(() => null);
220
+ tunnelKit.on('status-changed', this.onTunnelChange);
221
+ this.reconcile();
222
+ }
223
+
224
+ async stop(): Promise<void> {
225
+ tunnelKit.off('status-changed', this.onTunnelChange);
226
+ if (this.tunnelTimer) clearTimeout(this.tunnelTimer);
227
+ await this.chain.catch(() => {});
228
+ const chat = this.chat;
229
+ this.chat = null;
230
+ this.active.clear();
231
+ // Webhooks stay registered on purpose: the platform queues what arrives
232
+ // while Clopen is down and redelivers once it is reachable again.
233
+ await chat?.stop().catch((error) => debug.warn('chat-apps', 'ChatKit stop failed:', error));
234
+ }
235
+
236
+ /** Run `task` after every earlier one. Failures are logged, never propagated down the chain. */
237
+ private enqueue(task: () => Promise<void>): Promise<void> {
238
+ const next = this.chain
239
+ .then(task)
240
+ .catch((error) => debug.error('chat-apps', 'Channel runtime task failed:', error))
241
+ .finally(() => this.statusChanged());
242
+ this.chain = next;
243
+ return next;
244
+ }
245
+
246
+ /** Bring the running adapters in line with the accounts table. */
247
+ reconcile(): Promise<void> {
248
+ return this.enqueue(() => this.reconcileNow());
249
+ }
250
+
251
+ private desiredAccounts(): Array<{ row: IntegrationAccountRow; platform: ChannelPlatform; credentials: Record<string, string> }> {
252
+ const providers = new Set(listChannelPlatforms().map((platform) => platform.provider));
253
+ const out: Array<{ row: IntegrationAccountRow; platform: ChannelPlatform; credentials: Record<string, string> }> = [];
254
+ for (const row of integrationAccountQueries.getAll()) {
255
+ if (!providers.has(row.provider) || row.is_enabled !== 1) continue;
256
+ if (!integrationAccountQueries.capabilitiesOf(row).includes('control')) continue;
257
+ const platform = getChannelPlatform(row.provider)!;
258
+ let credentials = integrationAccountQueries.credentialsOf(row);
259
+ // An account sealed before its provider generated a secret (or one
260
+ // whose secret was lost with the key) gets one now, persisted, so the
261
+ // webhook it is about to register can be verified.
262
+ const provider = getProvider(row.provider);
263
+ if (provider) {
264
+ const filled = withGeneratedCredentials(provider, credentials);
265
+ if (JSON.stringify(filled) !== JSON.stringify(credentials)) {
266
+ integrationAccountQueries.setCredentials(row.id, filled);
267
+ credentials = filled;
268
+ }
269
+ }
270
+ out.push({ row, platform, credentials });
271
+ }
272
+ return out;
273
+ }
274
+
275
+ private async reconcileNow(): Promise<void> {
276
+ if (!this.chat) return;
277
+ const desired = this.desiredAccounts();
278
+ const desiredIds = new Set(desired.map((entry) => entry.row.id));
279
+
280
+ for (const [accountId, channel] of [...this.active]) {
281
+ if (!desiredIds.has(accountId)) await this.teardown(channel, { unregister: true });
282
+ }
283
+ for (const accountId of [...this.failures.keys()]) {
284
+ if (!desiredIds.has(accountId)) this.failures.delete(accountId);
285
+ }
286
+
287
+ for (const { row, platform, credentials } of desired) {
288
+ const fingerprint = fingerprintOf(row, credentials);
289
+ const current = this.active.get(row.id);
290
+ if (current?.fingerprint === fingerprint) continue;
291
+ if (current) await this.teardown(current, { unregister: false });
292
+ await this.setup(row, platform, credentials, fingerprint, { allowTunnelStart: true });
293
+ }
294
+ }
295
+
296
+ /** The webhook origin to use right now, optionally starting a tunnel to get one. */
297
+ private async resolveOrigin(allowTunnelStart: boolean): Promise<PublicOrigin | null> {
298
+ const found = findPublicOrigin(this.browserOrigin ?? undefined);
299
+ if (found || !allowTunnelStart) return usableForWebhook(found) ? found : null;
300
+ try {
301
+ const started = await resolvePublicOrigin(this.browserOrigin ?? undefined);
302
+ return usableForWebhook(started) ? started : null;
303
+ } catch (error) {
304
+ debug.warn('chat-apps', 'No public origin for channel webhooks, falling back to polling:', describe(error));
305
+ return null;
306
+ }
307
+ }
308
+
309
+ private async setup(
310
+ row: IntegrationAccountRow,
311
+ platform: ChannelPlatform,
312
+ credentials: Record<string, string>,
313
+ fingerprint: string,
314
+ options: { allowTunnelStart: boolean }
315
+ ): Promise<void> {
316
+ const chat = this.chat;
317
+ if (!chat) return;
318
+ const secret = credentials[getProvider(row.provider)?.webhook?.secretField ?? ''] ?? '';
319
+
320
+ if (platform.deliveryModes.includes('webhook') && secret) {
321
+ const origin = await this.resolveOrigin(options.allowTunnelStart);
322
+ if (origin) {
323
+ const adapter = platform.createAdapter({ account: row.id, credentials, mode: 'webhook' });
324
+ try {
325
+ await chat.add(adapter);
326
+ await platform.registerWebhook(adapter, hookUrl(origin.origin, row.provider), secret);
327
+ this.active.set(row.id, { accountId: row.id, platform, mode: 'webhook', origin, fingerprint });
328
+ this.failures.delete(row.id);
329
+ this.publishCommands(platform, row.id);
330
+ debug.log('chat-apps', `Channel ${row.provider} "${row.label}" receiving by webhook via ${origin.source}`);
331
+ return;
332
+ } catch (error) {
333
+ debug.warn('chat-apps', `Webhook for ${row.provider} "${row.label}" refused, falling back to polling:`, describe(error));
334
+ await chat.remove(platform.chatkit, row.id).catch(() => {});
335
+ }
336
+ }
337
+ }
338
+
339
+ if (!platform.deliveryModes.includes('polling')) {
340
+ this.failures.set(row.id, 'No public HTTPS address to receive messages at');
341
+ return;
342
+ }
343
+ const adapter = platform.createAdapter({ account: row.id, credentials, mode: 'polling' });
344
+ try {
345
+ await chat.add(adapter);
346
+ this.active.set(row.id, { accountId: row.id, platform, mode: 'polling', origin: null, fingerprint });
347
+ this.failures.delete(row.id);
348
+ this.publishCommands(platform, row.id);
349
+ debug.log('chat-apps', `Channel ${row.provider} "${row.label}" receiving by polling`);
350
+ } catch (error) {
351
+ this.failures.set(row.id, describe(error));
352
+ debug.warn('chat-apps', `Channel ${row.provider} "${row.label}" failed to start:`, describe(error));
353
+ }
354
+ }
355
+
356
+ private async teardown(channel: ActiveChannel, options: { unregister: boolean }): Promise<void> {
357
+ const chat = this.chat;
358
+ this.active.delete(channel.accountId);
359
+ if (!chat) return;
360
+ const adapter = chat.adapterFor(channel.platform.chatkit, channel.accountId);
361
+ if (options.unregister && adapter && channel.mode === 'webhook') {
362
+ await channel.platform.unregisterWebhook(adapter).catch((error) => {
363
+ debug.warn('chat-apps', 'Could not unregister channel webhook:', describe(error));
364
+ });
365
+ }
366
+ await chat.remove(channel.platform.chatkit, channel.accountId).catch(() => {});
367
+ }
368
+
369
+ /**
370
+ * Re-check every running bot against the origin available NOW, without
371
+ * starting a tunnel: a webhook whose origin moved or vanished is moved or
372
+ * dropped to polling, and a polling bot is promoted once an origin exists.
373
+ */
374
+ private async reevaluateDelivery(): Promise<void> {
375
+ if (!this.chat) return;
376
+ const origin = await this.resolveOrigin(false);
377
+ for (const channel of [...this.active.values()]) {
378
+ if (!channel.platform.deliveryModes.includes('webhook')) continue;
379
+ const stale = channel.mode === 'webhook' ? channel.origin?.origin !== origin?.origin : origin !== null;
380
+ if (!stale) continue;
381
+ const row = integrationAccountQueries.getById(channel.accountId);
382
+ if (!row) continue;
383
+ const credentials = integrationAccountQueries.credentialsOf(row);
384
+ await this.teardown(channel, { unregister: false });
385
+ await this.setup(row, channel.platform, credentials, channel.fingerprint, { allowTunnelStart: false });
386
+ }
387
+ }
388
+
389
+ /**
390
+ * A browser reached Clopen on this origin. A non-local one is a real
391
+ * deployment's address — better than a tunnel, so remember it (across
392
+ * restarts, which is when the server has no browser to ask) and move any
393
+ * bot that is on a tunnel or polling over to it.
394
+ */
395
+ rememberBrowserOrigin(origin: string | undefined): void {
396
+ if (!origin || origin === this.browserOrigin) return;
397
+ try {
398
+ if (isLocalHostname(new URL(origin).hostname)) return;
399
+ } catch {
400
+ return;
401
+ }
402
+ this.browserOrigin = origin;
403
+ void this.chat?.store.kvSet(KV_NAMESPACE, KV_BROWSER_ORIGIN, origin).catch(() => {});
404
+ this.enqueue(() => this.reevaluateDelivery());
405
+ }
406
+
407
+ /**
408
+ * Where a link back into Clopen should point, or null when there is no
409
+ * address another device can open. Never starts a tunnel — a link in a
410
+ * notification is a convenience, not a reason to expose the server.
411
+ */
412
+ publicOrigin(): string | null {
413
+ const origin = findPublicOrigin(this.browserOrigin ?? undefined);
414
+ return usableForWebhook(origin) ? origin.origin : null;
415
+ }
416
+
417
+ get(accountId: string): ActiveChannel | null {
418
+ return this.active.get(accountId) ?? null;
419
+ }
420
+
421
+ status(accountId: string): ChannelStatus {
422
+ const channel = this.active.get(accountId);
423
+ const health = channel ? this.chat?.health(channel.platform.chatkit, accountId)[0] : undefined;
424
+ return {
425
+ running: Boolean(channel),
426
+ mode: channel?.mode ?? null,
427
+ originSource: channel?.origin?.source ?? null,
428
+ connection: health?.state ?? null,
429
+ error: this.failures.get(accountId) ?? null
430
+ };
431
+ }
432
+
433
+ /** Deliver a verified webhook from the integration gateway to its bot. */
434
+ async receiveWebhook(event: WebhookEvent): Promise<void> {
435
+ const chat = this.chat;
436
+ const channel = this.active.get(event.accountId);
437
+ if (!chat || !channel) {
438
+ debug.warn('chat-apps', `Dropping ${event.provider} delivery for an account with no running channel`);
439
+ return;
440
+ }
441
+ const headers: Record<string, string> = {};
442
+ event.headers.forEach((value, key) => {
443
+ headers[key.toLowerCase()] = value;
444
+ });
445
+ await chat.receive(channel.platform.chatkit, event.accountId, { method: 'POST', headers, body: event.rawBody });
446
+ }
447
+
448
+ private dispatchInbound(message: UniversalMessage): void {
449
+ const channel = this.active.get(message.address.account);
450
+ if (!channel || !this.inboundHandler) return;
451
+ void this.inboundHandler(message, channel).catch((error) => {
452
+ debug.error('chat-apps', 'Handling an inbound channel message failed:', error);
453
+ });
454
+ }
455
+
456
+ private require(accountId: string): { chat: ChatKit; channel: ActiveChannel } {
457
+ const channel = this.active.get(accountId);
458
+ if (!this.chat || !channel) throw new Error('That channel is not running');
459
+ return { chat: this.chat, channel };
460
+ }
461
+
462
+ /**
463
+ * Read a file a chat sent out of ChatKit's media store — and drop it from
464
+ * there. ChatKit downloads every attachment as it arrives; whatever Clopen
465
+ * does not take out must not stay in memory for the life of the process.
466
+ */
467
+ async takeMedia(url: string | undefined): Promise<InboundFile | null> {
468
+ const store = this.chat?.media.store;
469
+ const id = url && store ? store.idFromUrl(url) : null;
470
+ if (!store || !id) return null;
471
+ try {
472
+ const stored = await store.get(id);
473
+ return stored ? { data: stored.data, mime: stored.mime ?? null, filename: stored.filename ?? null } : null;
474
+ } finally {
475
+ await store.delete(id).catch(() => {});
476
+ }
477
+ }
478
+
479
+ /** Send a file, inline when the platform can show it. */
480
+ async sendFile(accountId: string, conversationId: string, file: ChannelFile, replyTo?: string | null): Promise<SendResult> {
481
+ const { chat, channel } = this.require(accountId);
482
+ return chat.send({
483
+ to: { platform: channel.platform.chatkit, account: accountId, conversation_id: conversationId },
484
+ ...channel.platform.renderFile(file),
485
+ ...(replyTo ? { reply_to: replyTo } : {})
486
+ });
487
+ }
488
+
489
+ async send(accountId: string, conversationId: string, card: ChannelCard, replyTo?: string | null): Promise<SendResult> {
490
+ const { chat, channel } = this.require(accountId);
491
+ return chat.send({
492
+ to: { platform: channel.platform.chatkit, account: accountId, conversation_id: conversationId },
493
+ ...channel.platform.render(card),
494
+ ...(replyTo ? { reply_to: replyTo } : {})
495
+ });
496
+ }
497
+
498
+ /**
499
+ * Send formatted output of any length: split into as many messages as the
500
+ * platform needs, cutting at paragraph or line boundaries with formatting
501
+ * intact on both sides. Buttons ride on the last message, and only the
502
+ * first replies to `replyTo` — the rest follow it.
503
+ */
504
+ async sendLong(
505
+ accountId: string,
506
+ conversationId: string,
507
+ runs: TextRun[],
508
+ options: { buttons?: ChannelButton[][]; replyTo?: string | null } = {}
509
+ ): Promise<SendResult[]> {
510
+ const { channel } = this.require(accountId);
511
+ const chunks = splitRuns(runs, channel.platform.maxMessageLength);
512
+ if (chunks.length === 0) chunks.push([{ text: ' ' }]);
513
+ const results: SendResult[] = [];
514
+ for (const [index, chunk] of chunks.entries()) {
515
+ const last = index === chunks.length - 1;
516
+ results.push(
517
+ await this.send(
518
+ accountId,
519
+ conversationId,
520
+ { runs: chunk, ...(last && options.buttons ? { buttons: options.buttons } : {}) },
521
+ index === 0 ? options.replyTo : null
522
+ )
523
+ );
524
+ }
525
+ return results;
526
+ }
527
+
528
+ /** Best effort: "typing…" while a turn the chat started is running. */
529
+ async setTyping(accountId: string, conversationId: string): Promise<void> {
530
+ const channel = this.active.get(accountId);
531
+ if (!this.chat || !channel) return;
532
+ await this.chat.setTyping(channel.platform.chatkit, accountId, conversationId, true);
533
+ }
534
+
535
+ /** Best effort: remove a message the bot sent (a progress line once the answer is in). */
536
+ async deleteMessage(accountId: string, conversationId: string, platformMessageId: string): Promise<void> {
537
+ try {
538
+ const { chat, channel } = this.require(accountId);
539
+ await chat.deleteMessage({
540
+ address: { platform: channel.platform.chatkit, account: accountId, conversation_id: conversationId },
541
+ platform_message_id: platformMessageId
542
+ });
543
+ } catch (error) {
544
+ debug.log('chat-apps', 'Channel message delete skipped:', describe(error));
545
+ }
546
+ }
547
+
548
+ /**
549
+ * Re-render a sent message. Never throws: an edit is cosmetic, and the
550
+ * common failures (the message was deleted, or its content is unchanged)
551
+ * must not abort whatever state change prompted it.
552
+ */
553
+ async edit(accountId: string, conversationId: string, platformMessageId: string, card: ChannelCard): Promise<void> {
554
+ try {
555
+ const { chat, channel } = this.require(accountId);
556
+ await chat.send({
557
+ to: { platform: channel.platform.chatkit, account: accountId, conversation_id: conversationId },
558
+ ...channel.platform.renderEdit(platformMessageId, card)
559
+ });
560
+ } catch (error) {
561
+ debug.log('chat-apps', 'Channel message edit skipped:', describe(error));
562
+ }
563
+ }
564
+
565
+ /** The adapter behind a running channel — for pairing links and probes. */
566
+ adapterFor(accountId: string) {
567
+ const channel = this.active.get(accountId);
568
+ return channel ? this.chat?.adapterFor(channel.platform.chatkit, accountId) ?? null : null;
569
+ }
570
+ }
571
+
572
+ export const channelRuntime = new ChannelRuntime();