@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,746 @@
1
+ /**
2
+ * Controlling Clopen from a chat — the conversation half of a chat app.
3
+ *
4
+ * A chat app has one thread per chat; Clopen has many sessions in many
5
+ * projects. Each paired chat therefore carries an ACTIVE TARGET — a project,
6
+ * and the session in it that a plain message continues:
7
+ *
8
+ * - A plain message (text, photos, files, an album) continues the active
9
+ * session (queued if it is busy), or starts one if the chat has none
10
+ * yet. With no project picked, the chat is in the user's Home: chatting
11
+ * never requires choosing a project.
12
+ * - A reply to an earlier message continues from THAT point. If it is the
13
+ * latest point that is just the next turn; if it is an older one, Clopen
14
+ * goes back to it — the same restore as the web UI's — and the new turn
15
+ * branches from there.
16
+ * - Editing a message the user sent from the chat is Edit Message — or, if
17
+ * it is still waiting in the queue, simply changes what will run.
18
+ *
19
+ * Everything else (sessions, files, skills, projects, models, engine
20
+ * accounts) is the CONTROL CATALOG (`backend/control/`). This
21
+ * module only turns a command into an action, an action's result into a
22
+ * message with buttons, and a button back into an action. It implements none
23
+ * of them.
24
+ *
25
+ * A button acts where it was SHOWN. A menu and a confirmation carry the
26
+ * target they were made for, so tapping one after switching sessions never
27
+ * acts on the session the chat moved to: "Delete 'A'?" deletes A.
28
+ *
29
+ * Going back restores FILES, not just the conversation. That is never done
30
+ * silently from a phone: it is asked first, with the session it touches and
31
+ * the message it will send, and files another session changed since are left
32
+ * as they are rather than overwritten. Destructive catalog actions are asked
33
+ * about the same way.
34
+ */
35
+
36
+ import { readFileSync } from 'fs';
37
+ import { markdownToRuns, type TextRun, type UniversalMessage } from '@myrialabs/chatkit';
38
+ import type { StreamRequest } from '$shared/types/unified';
39
+ import type { ChatSession, Project } from '$shared/types/database/schema';
40
+ import {
41
+ channelLinkQueries,
42
+ channelMessageQueries,
43
+ messageQueries,
44
+ sessionQueries,
45
+ type ChannelLinkRow,
46
+ type ChannelMessageRow
47
+ } from '$backend/database/queries';
48
+ import type { AuthUser } from '$backend/auth/auth-service';
49
+ import { checkSessionRestoreConflicts, restoreSessionTo, restoreTargetEnd } from '$backend/snapshot/restore';
50
+ import { INITIAL_NODE_ID } from '$backend/snapshot/helpers';
51
+ import { lastTurnAnswer, userMessageText } from '$backend/chat/turn-answer';
52
+ import {
53
+ accessibleSession,
54
+ accountFor,
55
+ normaliseSkillName,
56
+ checkArgs,
57
+ confirmationFor,
58
+ controlActionForCommand,
59
+ controlHelp,
60
+ createControlContext,
61
+ createSession,
62
+ getControlAction,
63
+ isSessionBusy,
64
+ modelOf,
65
+ parseCommandArgument,
66
+ pickModel,
67
+ projectLabel,
68
+ resolveTarget,
69
+ runControlAction,
70
+ type ControlChoice,
71
+ type ControlResult,
72
+ type ControlTarget
73
+ } from '$backend/control';
74
+ import { debug } from '$shared/utils/logger';
75
+ import { channelRuntime, type ActiveChannel } from './runtime';
76
+ import { accountHas, parsePayload } from './outbound';
77
+ import { expectTurn, forgetExpectedTurn, markStoppedByChat, queuedPromptFor, setExpectedQueueId } from './turns';
78
+ import { replyText } from './questions';
79
+ import { setAwaiting } from './awaiting';
80
+ import { promptContent, type PromptAttachment } from './media';
81
+ import { REPLIES, CHAT_COMMANDS, confirmCard, menuCard, textCard, type ButtonAction } from './messages';
82
+
83
+ /**
84
+ * The composer, as a chat app needs it: start (or queue) a turn exactly as
85
+ * the web does, and change a message still waiting in the queue. Injected by
86
+ * the chat composer at load: it lives in the WebSocket layer, which imports
87
+ * this module through the stream hooks, so importing it back would be a cycle.
88
+ */
89
+ export interface Composer {
90
+ submit(input: { request: StreamRequest }): Promise<{ outcome: 'started' | 'queued'; queueId: string }>;
91
+ replaceQueued(chatSessionId: string, queueId: string, content: unknown[]): boolean;
92
+ }
93
+
94
+ let composer: Composer | null = null;
95
+
96
+ export function registerComposer(instance: Composer): void {
97
+ composer = instance;
98
+ }
99
+
100
+ export interface Conversation {
101
+ channel: ActiveChannel;
102
+ message: UniversalMessage;
103
+ link: ChannelLinkRow;
104
+ user: AuthUser;
105
+ }
106
+
107
+ /** The project and session a plain message from this chat goes to. */
108
+ export function activeTarget(link: ChannelLinkRow): { project: Project; session: ChatSession | null } {
109
+ return resolveTarget({ projectId: link.active_project_id ?? undefined, sessionId: link.active_session_id });
110
+ }
111
+
112
+ function activeControlTarget(conversation: Conversation): ControlTarget {
113
+ const { project, session } = activeTarget(reload(conversation.link));
114
+ return { projectId: project.id, sessionId: session?.id ?? null };
115
+ }
116
+
117
+ /** Driving Clopen needs the bot's `control` capability. */
118
+ export function canControl(link: ChannelLinkRow): boolean {
119
+ return accountHas(link.account_id, 'control');
120
+ }
121
+
122
+ async function requireControl(conversation: Conversation): Promise<boolean> {
123
+ if (canControl(conversation.link)) return true;
124
+ await replyText(conversation.channel, conversation.message, REPLIES.controlOff);
125
+ return false;
126
+ }
127
+
128
+ function reload(link: ChannelLinkRow): ChannelLinkRow {
129
+ return channelLinkQueries.getById(link.id) ?? link;
130
+ }
131
+
132
+ // ── Sending ─────────────────────────────────────────────────────────────────
133
+
134
+ /**
135
+ * Send `text` and `attachments` as the next turn of `session` (or of a new
136
+ * session in `project`), on behalf of the chat's user. The turn's answer
137
+ * comes back to this chat; the user's message is mapped so it can be edited
138
+ * later.
139
+ */
140
+ export async function sendPrompt(
141
+ conversation: Conversation,
142
+ target: { project: Project; session: ChatSession | null },
143
+ text: string,
144
+ attachments: PromptAttachment[],
145
+ options: { platformMessageId: string | null }
146
+ ): Promise<void> {
147
+ const { channel, message, link, user } = conversation;
148
+ if (!composer) {
149
+ await replyText(channel, message, REPLIES.answerFailed);
150
+ return;
151
+ }
152
+ if (!text.trim() && attachments.length === 0) {
153
+ await replyText(channel, message, REPLIES.nothingToSend);
154
+ return;
155
+ }
156
+
157
+ let session = target.session;
158
+ if (!session) {
159
+ const model = pickModel(user.id, target.project.id);
160
+ if (!model) {
161
+ await replyText(channel, message, REPLIES.noModel);
162
+ return;
163
+ }
164
+ session = createSession(target.project, model);
165
+ }
166
+ const model = modelOf(session) ?? pickModel(user.id, target.project.id);
167
+ if (!model) {
168
+ await replyText(channel, message, REPLIES.noModel);
169
+ return;
170
+ }
171
+
172
+ // The web picker always sends an account; so must a chat. A session made
173
+ // here, or one that just switched engine, has none pinned yet.
174
+ const account = accountFor(session, model);
175
+ const engine = {
176
+ type: model.engine,
177
+ provider: model.provider,
178
+ model: { id: model.modelId, name: model.modelName },
179
+ account: account ?? { id: 0, name: '' }
180
+ };
181
+ const promptMessageId = crypto.randomUUID();
182
+ const request: StreamRequest = {
183
+ projectPath: target.project.path,
184
+ projectId: target.project.id,
185
+ chatSessionId: session.id,
186
+ prompt: {
187
+ type: 'user',
188
+ createdAt: new Date().toISOString(),
189
+ messageId: promptMessageId,
190
+ sessionId: session.id,
191
+ // The branch tip is resolved server-side from HEAD, as for a queued message.
192
+ parent: { messageId: null, sessionId: null, toolUseId: null },
193
+ engine,
194
+ content: promptContent(text, attachments),
195
+ synthetic: false
196
+ } as StreamRequest['prompt'],
197
+ engine: engine as StreamRequest['engine'],
198
+ profileId: session.profile_id ?? null,
199
+ reasoningEffort: session.reasoning_effort ?? null,
200
+ requestedByUserId: user.id
201
+ };
202
+
203
+ channelLinkQueries.setActive(link.id, target.project.id, session.id);
204
+ expectTurn(session.id, {
205
+ linkId: link.id,
206
+ accountId: channel.accountId,
207
+ conversationId: message.address.conversation_id,
208
+ projectId: target.project.id,
209
+ platformMessageId: options.platformMessageId,
210
+ promptMessageId
211
+ });
212
+
213
+ try {
214
+ const { outcome, queueId } = await composer.submit({ request });
215
+ if (outcome === 'queued') {
216
+ setExpectedQueueId(session.id, promptMessageId, queueId);
217
+ await replyText(channel, message, REPLIES.queued);
218
+ }
219
+ } catch (error) {
220
+ forgetExpectedTurn(session.id, promptMessageId);
221
+ debug.warn('chat-apps', 'Sending a prompt from a chat app failed:', error);
222
+ await replyText(channel, message, `${REPLIES.answerFailed}${error instanceof Error ? ` (${error.message})` : ''}`);
223
+ }
224
+ }
225
+
226
+ /** A plain message: continue the active target. */
227
+ export async function continueActive(conversation: Conversation, text: string, attachments: PromptAttachment[]): Promise<void> {
228
+ if (!(await requireControl(conversation))) return;
229
+ const target = activeTarget(reload(conversation.link));
230
+ await sendPrompt(conversation, target, text, attachments, { platformMessageId: conversation.message.platform_message_id ?? null });
231
+ }
232
+
233
+ // ── Confirmations ───────────────────────────────────────────────────────────
234
+
235
+ interface RewindPayload {
236
+ kind: 'rewind';
237
+ /** `undo` goes back without sending anything. */
238
+ action: 'branch' | 'edit' | 'retry' | 'undo';
239
+ projectId: string;
240
+ sessionId: string;
241
+ /** What to restore to: a message id, or `__initial__` for before the first message. */
242
+ restoreTo: string;
243
+ text: string;
244
+ /** The chat message to map the new turn's user message to (edit/branch), if any. */
245
+ platformMessageId: string | null;
246
+ }
247
+
248
+ /** A catalog action waiting for a yes — with the target it was asked about. */
249
+ interface ActionPayload {
250
+ kind: 'action';
251
+ actionId: string;
252
+ args: Record<string, unknown>;
253
+ target: ControlTarget;
254
+ }
255
+
256
+ /** Text that looked like a command but is not one, offered as a message. */
257
+ interface SendPayload {
258
+ kind: 'send';
259
+ text: string;
260
+ }
261
+
262
+ type ConfirmPayload = RewindPayload | ActionPayload | SendPayload;
263
+
264
+ /**
265
+ * Files riding on a confirmation (an edit or a reply that goes back first).
266
+ * Kept in memory rather than in the row: they can be megabytes, and a
267
+ * confirmation outliving a restart can still send its text.
268
+ */
269
+ const confirmAttachments = new Map<string, { attachments: PromptAttachment[]; at: number }>();
270
+ const CONFIRM_ATTACHMENTS_TTL_MS = 60 * 60 * 1000;
271
+
272
+ function keepAttachments(rowId: string, attachments: PromptAttachment[]): void {
273
+ const now = Date.now();
274
+ for (const [id, entry] of confirmAttachments) if (now - entry.at > CONFIRM_ATTACHMENTS_TTL_MS) confirmAttachments.delete(id);
275
+ if (attachments.length) confirmAttachments.set(rowId, { attachments, at: now });
276
+ }
277
+
278
+ function takeAttachments(rowId: string): PromptAttachment[] {
279
+ const entry = confirmAttachments.get(rowId);
280
+ confirmAttachments.delete(rowId);
281
+ return entry?.attachments ?? [];
282
+ }
283
+
284
+ /**
285
+ * Write the confirm row first — its id rides on the buttons — then send it.
286
+ * Older open confirmations that `supersedes` matches are closed: editing a
287
+ * message twice asks once, about the newest text.
288
+ */
289
+ async function sendConfirmation(
290
+ conversation: Conversation,
291
+ payload: ConfirmPayload,
292
+ card: { title: string; detail: string; confirmLabel: string },
293
+ scope: { projectId?: string; sessionId?: string },
294
+ options: { attachments?: PromptAttachment[]; supersedes?: (older: ConfirmPayload) => boolean } = {}
295
+ ): Promise<void> {
296
+ const { channel, message, link } = conversation;
297
+ if (options.supersedes) {
298
+ for (const older of channelMessageQueries.openConfirmsForLink(link.id)) {
299
+ if (!options.supersedes(parsePayload<ConfirmPayload>(older)) || !channelMessageQueries.settle(older.id, 'closed')) continue;
300
+ takeAttachments(older.id);
301
+ await channelRuntime.edit(link.account_id, link.conversation_id, older.platform_message_id, textCard(REPLIES.editReplaced));
302
+ }
303
+ }
304
+ const id = channelMessageQueries.create({
305
+ linkId: link.id,
306
+ kind: 'confirm',
307
+ projectId: scope.projectId ?? null,
308
+ chatSessionId: scope.sessionId ?? null,
309
+ platformMessageId: 'pending',
310
+ payload
311
+ }).id;
312
+ keepAttachments(id, options.attachments ?? []);
313
+ try {
314
+ const sent = await channelRuntime.send(channel.accountId, message.address.conversation_id, confirmCard(id, card), message.content.type === 'postback' ? null : message.platform_message_id ?? null);
315
+ if (sent.platform_message_id) channelMessageQueries.setPlatformMessage(id, sent.platform_message_id);
316
+ } catch (error) {
317
+ channelMessageQueries.settle(id, 'closed');
318
+ takeAttachments(id);
319
+ throw error;
320
+ }
321
+ }
322
+
323
+ // ── Going back: reply to an older point, edit, retry, undo ──────────────────
324
+
325
+ /**
326
+ * Continue from a specific point. The latest point is simply the next turn;
327
+ * an older one is a rewind, which is confirmed first.
328
+ */
329
+ export async function continueFrom(conversation: Conversation, row: ChannelMessageRow, text: string, attachments: PromptAttachment[]): Promise<void> {
330
+ if (!(await requireControl(conversation))) return;
331
+ const target = accessibleSession(row.chat_session_id);
332
+ if (!target) {
333
+ await replyText(conversation.channel, conversation.message, REPLIES.sessionGone);
334
+ return;
335
+ }
336
+ const head = sessionQueries.getHead(target.session.id);
337
+ const end = row.clopen_message_id ? restoreTargetEnd(target.session.id, row.clopen_message_id) : null;
338
+ // No point recorded, or the point IS the latest: this is just the next message.
339
+ if (!row.clopen_message_id || !end || end === head) {
340
+ await sendPrompt(conversation, target, text, attachments, { platformMessageId: conversation.message.platform_message_id ?? null });
341
+ return;
342
+ }
343
+ await askRewind(
344
+ conversation,
345
+ target,
346
+ {
347
+ kind: 'rewind',
348
+ action: 'branch',
349
+ projectId: target.project.id,
350
+ sessionId: target.session.id,
351
+ restoreTo: row.clopen_message_id,
352
+ text,
353
+ platformMessageId: conversation.message.platform_message_id ?? null
354
+ },
355
+ attachments
356
+ );
357
+ }
358
+
359
+ /**
360
+ * The user edited a message they sent from this chat. Still in the queue: it
361
+ * just changes what will run. Already a turn: Edit Message.
362
+ */
363
+ export async function editSent(conversation: Conversation, text: string, attachments: PromptAttachment[]): Promise<void> {
364
+ const { link, message } = conversation;
365
+ const platformMessageId = message.platform_message_id ?? null;
366
+ if (!platformMessageId) {
367
+ await replyText(conversation.channel, message, REPLIES.notEditable);
368
+ return;
369
+ }
370
+ if (!(await requireControl(conversation))) return;
371
+
372
+ const queued = queuedPromptFor(link.id, platformMessageId);
373
+ if (queued && composer?.replaceQueued(queued.chatSessionId, queued.prompt.queueId!, promptContent(text, attachments))) {
374
+ await replyText(conversation.channel, message, REPLIES.queuedEdited);
375
+ return;
376
+ }
377
+
378
+ const row = channelMessageQueries.getByMessage(link.id, platformMessageId);
379
+ if (!row || row.kind !== 'user' || !row.clopen_message_id) {
380
+ await replyText(conversation.channel, message, REPLIES.notEditable);
381
+ return;
382
+ }
383
+ const target = accessibleSession(row.chat_session_id);
384
+ const original = messageQueries.getById(row.clopen_message_id);
385
+ if (!target || !original) {
386
+ await replyText(conversation.channel, message, REPLIES.notEditable);
387
+ return;
388
+ }
389
+ await askRewind(
390
+ conversation,
391
+ target,
392
+ {
393
+ kind: 'rewind',
394
+ action: 'edit',
395
+ projectId: target.project.id,
396
+ sessionId: target.session.id,
397
+ restoreTo: original.parent_message_id || INITIAL_NODE_ID,
398
+ text,
399
+ platformMessageId
400
+ },
401
+ attachments
402
+ );
403
+ }
404
+
405
+ /** The active session's last turn: its user message and what it said. */
406
+ function lastTurn(conversation: Conversation) {
407
+ const { session } = activeTarget(reload(conversation.link));
408
+ const target = session ? accessibleSession(session.id) : null;
409
+ const turn = target ? lastTurnAnswer(target.session.id) : null;
410
+ const userRow = turn?.userMessageId ? messageQueries.getById(turn.userMessageId) : null;
411
+ return { target, userRow, text: turn?.userMessageId ? userMessageText(turn.userMessageId) : null };
412
+ }
413
+
414
+ /** /retry — ask the active session's last message again. */
415
+ async function retryLast(conversation: Conversation): Promise<void> {
416
+ const { target, userRow, text } = lastTurn(conversation);
417
+ if (!target || !text || !userRow) {
418
+ await replyText(conversation.channel, conversation.message, REPLIES.nothingToRetry);
419
+ return;
420
+ }
421
+ await askRewind(conversation, target, {
422
+ kind: 'rewind',
423
+ action: 'retry',
424
+ projectId: target.project.id,
425
+ sessionId: target.session.id,
426
+ restoreTo: userRow.parent_message_id || INITIAL_NODE_ID,
427
+ text,
428
+ platformMessageId: null
429
+ });
430
+ }
431
+
432
+ /** /undo — go back to before the active session's last message, sending nothing. */
433
+ async function undoLast(conversation: Conversation): Promise<void> {
434
+ const { target, userRow, text } = lastTurn(conversation);
435
+ if (!target || !userRow) {
436
+ await replyText(conversation.channel, conversation.message, REPLIES.nothingToUndo);
437
+ return;
438
+ }
439
+ await askRewind(conversation, target, {
440
+ kind: 'rewind',
441
+ action: 'undo',
442
+ projectId: target.project.id,
443
+ sessionId: target.session.id,
444
+ restoreTo: userRow.parent_message_id || INITIAL_NODE_ID,
445
+ text: text ?? '',
446
+ platformMessageId: null
447
+ });
448
+ }
449
+
450
+ const REWIND_WORDING: Record<RewindPayload['action'], { title: string; confirm: string }> = {
451
+ branch: { title: '↩️ Continue from that point?', confirm: 'Go back & send' },
452
+ edit: { title: '✏️ Edit and resend?', confirm: 'Edit & resend' },
453
+ retry: { title: '🔁 Ask again?', confirm: 'Ask again' },
454
+ undo: { title: '↩️ Undo the last message?', confirm: 'Undo' }
455
+ };
456
+
457
+ async function askRewind(
458
+ conversation: Conversation,
459
+ target: { project: Project; session: ChatSession },
460
+ payload: RewindPayload,
461
+ attachments: PromptAttachment[] = []
462
+ ): Promise<void> {
463
+ if (isSessionBusy(target.session)) {
464
+ await replyText(conversation.channel, conversation.message, REPLIES.busyBranch);
465
+ return;
466
+ }
467
+ let conflicts = 0;
468
+ try {
469
+ conflicts = (await checkSessionRestoreConflicts(target.session.id, payload.restoreTo)).conflicts.length;
470
+ } catch (error) {
471
+ debug.warn('chat-apps', 'Checking restore conflicts failed:', error);
472
+ }
473
+ const where = `"${target.session.title || 'this session'}" in ${projectLabel(target.project)}`;
474
+ const quoted = payload.text.length > 160 ? `${payload.text.slice(0, 159)}…` : payload.text;
475
+ const files = attachments.length ? ` (with ${attachments.length} file${attachments.length === 1 ? '' : 's'})` : '';
476
+ const kept = conflicts > 0 ? ` (${conflicts} file${conflicts === 1 ? '' : 's'} another session changed since will be left as they are)` : '';
477
+ const detail =
478
+ payload.action === 'undo'
479
+ ? `Clopen goes back to before the last message in ${where}. Like Restore in Clopen, files it changed are restored${kept}. Nothing is sent.`
480
+ : `Clopen goes back to that point in ${where}. Like Restore in Clopen, files the session changed after it are restored${kept}. Then it sends${files}:\n\n“${quoted}”`;
481
+ const wording = REWIND_WORDING[payload.action];
482
+ await sendConfirmation(
483
+ conversation,
484
+ payload,
485
+ { title: wording.title, detail, confirmLabel: wording.confirm },
486
+ { projectId: target.project.id, sessionId: target.session.id },
487
+ {
488
+ attachments,
489
+ // A newer edit of the same message replaces the question about the older one.
490
+ supersedes: payload.action === 'edit' && payload.platformMessageId
491
+ ? (older) => older.kind === 'rewind' && older.action === 'edit' && older.platformMessageId === payload.platformMessageId
492
+ : undefined
493
+ }
494
+ );
495
+ }
496
+
497
+ async function performRewind(conversation: Conversation, row: ChannelMessageRow, payload: RewindPayload): Promise<void> {
498
+ const { channel, message, link } = conversation;
499
+ const attachments = takeAttachments(row.id);
500
+ const target = accessibleSession(payload.sessionId);
501
+ if (!target) {
502
+ await replyText(channel, message, REPLIES.sessionGone);
503
+ return;
504
+ }
505
+ if (isSessionBusy(target.session)) {
506
+ await replyText(channel, message, REPLIES.busyRestore);
507
+ return;
508
+ }
509
+ try {
510
+ // Never overwrite what another session changed since: from a phone there
511
+ // is no conflict dialog to ask, so the safe answer is the default.
512
+ const check = await checkSessionRestoreConflicts(target.session.id, payload.restoreTo);
513
+ const keep = Object.fromEntries(check.conflicts.map((conflict) => [conflict.filepath, 'keep' as const]));
514
+ const result = await restoreSessionTo(target.session.id, payload.restoreTo, keep);
515
+ const done = payload.action === 'undo' ? REPLIES.undone(result.filesRestored) : REPLIES.branched(result.filesRestored);
516
+ await channelRuntime.edit(link.account_id, link.conversation_id, row.platform_message_id, textCard(done));
517
+ } catch (error) {
518
+ await replyText(channel, message, error instanceof Error ? error.message : REPLIES.answerFailed);
519
+ return;
520
+ }
521
+ const refreshed = sessionQueries.getById(target.session.id) ?? target.session;
522
+ if (payload.action === 'undo') {
523
+ channelLinkQueries.setActive(link.id, target.project.id, refreshed.id);
524
+ return;
525
+ }
526
+ await sendPrompt(
527
+ { ...conversation, message: { ...message, platform_message_id: payload.platformMessageId } },
528
+ { project: target.project, session: refreshed },
529
+ payload.text,
530
+ attachments,
531
+ { platformMessageId: payload.platformMessageId }
532
+ );
533
+ }
534
+
535
+ // ── The control catalog ─────────────────────────────────────────────────────
536
+
537
+ /** A menu's buttons, and the target they act on. */
538
+ interface MenuPayload {
539
+ choices: ControlChoice[];
540
+ target?: ControlTarget;
541
+ /** Set when the row asked for typed words rather than offering buttons. */
542
+ ask?: ControlResult['ask'];
543
+ }
544
+
545
+ async function sendMenu(conversation: Conversation, runs: TextRun[], payload: MenuPayload, extraButtons: Array<Array<{ label: string; url: string }>> = []): Promise<void> {
546
+ const { channel, message, link } = conversation;
547
+ const id = channelMessageQueries.create({ linkId: link.id, kind: 'menu', platformMessageId: 'pending', payload }).id;
548
+ const card = menuCard(id, runs, payload.choices);
549
+ const sent = await channelRuntime.send(channel.accountId, message.address.conversation_id, { ...card, buttons: [...(card.buttons ?? []), ...extraButtons] });
550
+ if (sent.platform_message_id) channelMessageQueries.setPlatformMessage(id, sent.platform_message_id);
551
+ }
552
+
553
+ /** An action asked for words: send the question, and take the next message as its answer. */
554
+ async function sendAsk(conversation: Conversation, ask: NonNullable<ControlResult['ask']>, target: ControlTarget): Promise<void> {
555
+ const { channel, message, link } = conversation;
556
+ const id = channelMessageQueries.create({ linkId: link.id, kind: 'menu', platformMessageId: 'pending', payload: { choices: [], ask, target } }).id;
557
+ const sent = await channelRuntime.send(channel.accountId, message.address.conversation_id, {
558
+ runs: [{ text: `✏️ ${ask.question}`, bold: true }, { text: '\n' }, { text: 'Type it and send. Any command cancels.', italic: true }]
559
+ });
560
+ if (sent.platform_message_id) channelMessageQueries.setPlatformMessage(id, sent.platform_message_id);
561
+ setAwaiting(link.id, { kind: 'ask', rowId: id });
562
+ }
563
+
564
+ /** Is this row an action waiting for typed words? */
565
+ export function isAsking(row: ChannelMessageRow): boolean {
566
+ return row.kind === 'menu' && row.state === 'open' && Boolean(parsePayload<MenuPayload>(row).ask);
567
+ }
568
+
569
+ /** The words an action asked for arrived: run it with them, once. */
570
+ export async function answerAsk(conversation: Conversation, row: ChannelMessageRow, text: string): Promise<void> {
571
+ const payload = parsePayload<MenuPayload>(row);
572
+ if (!payload.ask || !channelMessageQueries.settle(row.id, 'answered')) {
573
+ await replyText(conversation.channel, conversation.message, REPLIES.staleAction);
574
+ return;
575
+ }
576
+ if (!(await requireControl(conversation))) return;
577
+ const { action, args, key } = payload.ask;
578
+ await runAction(conversation, action, { ...(args ?? {}), [key]: text.trim() }, payload.target);
579
+ }
580
+
581
+ /** Send the files a result carries, each as its own message. */
582
+ async function sendResultFiles(conversation: Conversation, result: ControlResult): Promise<void> {
583
+ const { channel, message } = conversation;
584
+ for (const file of result.files ?? []) {
585
+ try {
586
+ await channelRuntime.sendFile(channel.accountId, message.address.conversation_id, { data: readFileSync(file.path), filename: file.filename, mime: file.mime });
587
+ } catch (error) {
588
+ await replyText(channel, message, `⚠️ ${file.filename} could not be sent${error instanceof Error ? `: ${error.message}` : '.'}`);
589
+ }
590
+ }
591
+ }
592
+
593
+ /**
594
+ * Show a catalog result: Markdown, then buttons for its choices and its link,
595
+ * then any files. `ranAt` is where the action ran — the target its choices
596
+ * act on unless the result moved the conversation.
597
+ */
598
+ async function showResult(conversation: Conversation, result: ControlResult, ranAt: ControlTarget): Promise<void> {
599
+ const { channel, message, link } = conversation;
600
+ if (result.target) channelLinkQueries.setActive(link.id, result.target.projectId, result.target.sessionId);
601
+ const runs: TextRun[] = markdownToRuns(result.text || ' ');
602
+ const linkButtons = result.link ? [[{ label: result.link.label, url: result.link.url }]] : [];
603
+
604
+ if (result.choices?.length) {
605
+ await sendMenu(conversation, runs, { choices: result.choices, target: result.target ?? ranAt }, linkButtons);
606
+ } else {
607
+ await channelRuntime.sendLong(channel.accountId, message.address.conversation_id, runs, { buttons: linkButtons.length ? linkButtons : undefined });
608
+ }
609
+ await sendResultFiles(conversation, result);
610
+ if (result.ask) await sendAsk(conversation, result.ask, result.target ?? ranAt);
611
+ // An action that starts a turn (a skill) names what to send; it goes where
612
+ // the action ran, exactly as if the user had typed it there.
613
+ if (result.prompt) {
614
+ const where = resolveTarget(result.target ?? ranAt);
615
+ await sendPrompt(conversation, where, result.prompt, [], { platformMessageId: null });
616
+ }
617
+ }
618
+
619
+ /** Does a skill by this name exist for the chat's active session? */
620
+ async function skillNamed(conversation: Conversation, name: string): Promise<boolean> {
621
+ const { project, session } = activeTarget(reload(conversation.link));
622
+ const ctx = createControlContext(conversation.user, { projectId: project.id, sessionId: session?.id ?? null });
623
+ try {
624
+ const { skills } = await ctx.call<{ skills: Array<{ slug: string }> }>('skills:available', { profileId: session?.profile_id ?? null, projectId: project.id });
625
+ return skills.some((skill) => skill.slug === normaliseSkillName(name));
626
+ } catch {
627
+ return false;
628
+ }
629
+ }
630
+
631
+ /**
632
+ * Run a catalog action for this chat: arguments, a confirmation when
633
+ * the action asks for one, then the action and its result. `at` pins the
634
+ * target (a menu's own); without it the action runs on the active one.
635
+ */
636
+ async function runAction(conversation: Conversation, actionId: string, rawArgs: Record<string, unknown>, at?: ControlTarget): Promise<void> {
637
+ const { user } = conversation;
638
+ const action = getControlAction(actionId);
639
+ if (!action) {
640
+ await replyText(conversation.channel, conversation.message, REPLIES.staleAction);
641
+ return;
642
+ }
643
+ const target = at ?? activeControlTarget(conversation);
644
+ const ctx = createControlContext(user, target);
645
+ const args = checkArgs(action, rawArgs);
646
+ const question = await confirmationFor(action, ctx, args);
647
+ if (question) {
648
+ await sendConfirmation(conversation, { kind: 'action', actionId, args, target }, { title: `⚠️ ${action.title}?`, detail: question, confirmLabel: action.title }, {});
649
+ return;
650
+ }
651
+ await runConfirmed(conversation, actionId, args, target);
652
+ }
653
+
654
+ async function runConfirmed(conversation: Conversation, actionId: string, args: Record<string, unknown>, target: ControlTarget): Promise<void> {
655
+ // This chat says "Stopped" itself; the turn ending must not say it twice.
656
+ if (actionId === 'sessions.stop' && target.sessionId) {
657
+ const found = accessibleSession(target.sessionId);
658
+ if (found && isSessionBusy(found.session)) markStoppedByChat(found.session.id);
659
+ }
660
+ const ctx = createControlContext(conversation.user, target);
661
+ await showResult(conversation, await runControlAction(ctx, actionId, args), target);
662
+ }
663
+
664
+ // ── The chat's own commands ─────────────────────────────────────────────────
665
+
666
+ /** Every command this chat answers to: its own, pairing's, and the catalog's. */
667
+ export function isKnownCommand(name: string): boolean {
668
+ return name === 'start' || name === 'unlink' || CHAT_COMMANDS.some((entry) => entry.command === name) || controlActionForCommand(name) !== null;
669
+ }
670
+
671
+ /** A `/command` that is not pairing: one of the chat's own, or a catalog action. */
672
+ export async function handleControlCommand(conversation: Conversation, name: string, argument: string, rawText: string): Promise<void> {
673
+ if (name === 'help') {
674
+ await channelRuntime.sendLong(conversation.channel.accountId, conversation.message.address.conversation_id, markdownToRuns(`${REPLIES.helpIntro}\n\n${controlHelp(CHAT_COMMANDS)}`));
675
+ return;
676
+ }
677
+ if (!(await requireControl(conversation))) return;
678
+ if (name === 'retry') {
679
+ await retryLast(conversation);
680
+ return;
681
+ }
682
+ if (name === 'undo') {
683
+ await undoLast(conversation);
684
+ return;
685
+ }
686
+ const action = controlActionForCommand(name);
687
+ if (!action) {
688
+ // Skills are not bot commands; say how to run the one that was meant.
689
+ if (await skillNamed(conversation, name)) {
690
+ await replyText(conversation.channel, conversation.message, REPLIES.skillNotACommand(name));
691
+ return;
692
+ }
693
+ // "/tmp/build.log is empty, why?" is a message, not a typo'd command: let the user say which.
694
+ await sendConfirmation(
695
+ conversation,
696
+ { kind: 'send', text: rawText },
697
+ { title: REPLIES.unknownCommand(name), detail: REPLIES.sendAsMessage, confirmLabel: 'Send as message' },
698
+ {}
699
+ );
700
+ return;
701
+ }
702
+ await runAction(conversation, action.id, parseCommandArgument(action, argument));
703
+ }
704
+
705
+ /** A tap on a menu or a confirmation. */
706
+ export async function handleControlButton(conversation: Conversation, row: ChannelMessageRow, action: ButtonAction): Promise<void> {
707
+ const { channel, message, link } = conversation;
708
+
709
+ if (row.kind === 'menu' && action.type === 'option') {
710
+ const payload = parsePayload<MenuPayload>(row);
711
+ const choice = payload.choices?.[action.index];
712
+ if (!choice) {
713
+ await replyText(channel, message, REPLIES.staleAction);
714
+ return;
715
+ }
716
+ if (!(await requireControl(conversation))) return;
717
+ await runAction(conversation, choice.action, choice.args ?? {}, payload.target);
718
+ return;
719
+ }
720
+
721
+ if (row.kind === 'confirm' && (action.type === 'confirm' || action.type === 'cancel')) {
722
+ if (!(await requireControl(conversation))) return;
723
+ if (!channelMessageQueries.settle(row.id, action.type === 'confirm' ? 'answered' : 'closed')) {
724
+ await replyText(channel, message, REPLIES.staleAction);
725
+ return;
726
+ }
727
+ if (action.type === 'cancel') {
728
+ takeAttachments(row.id);
729
+ await channelRuntime.edit(link.account_id, link.conversation_id, row.platform_message_id, textCard(REPLIES.cancelled));
730
+ return;
731
+ }
732
+ const payload = parsePayload<ConfirmPayload>(row);
733
+ if (payload.kind === 'action') {
734
+ await channelRuntime.edit(link.account_id, link.conversation_id, row.platform_message_id, textCard('✅ Confirmed.'));
735
+ await runConfirmed(conversation, payload.actionId, payload.args, payload.target ?? activeControlTarget(conversation));
736
+ return;
737
+ }
738
+ if (payload.kind === 'send') {
739
+ await channelRuntime.edit(link.account_id, link.conversation_id, row.platform_message_id, textCard('📨 Sent as a message.'));
740
+ const target = activeTarget(reload(link));
741
+ await sendPrompt(conversation, target, payload.text, takeAttachments(row.id), { platformMessageId: null });
742
+ return;
743
+ }
744
+ await performRewind(conversation, row, payload);
745
+ }
746
+ }