@myrialabs/clopen 0.4.47 → 0.4.49

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 (390) 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/message-pages.test.ts +163 -0
  15. package/backend/chat/message-pages.ts +233 -0
  16. package/backend/chat/stream-manager.ts +91 -67
  17. package/backend/chat/turn-answer.test.ts +64 -0
  18. package/backend/chat/turn-answer.ts +125 -0
  19. package/backend/chat-apps/awaiting.test.ts +39 -0
  20. package/backend/chat-apps/awaiting.ts +49 -0
  21. package/backend/chat-apps/conversation.ts +746 -0
  22. package/backend/chat-apps/inbound.ts +324 -0
  23. package/backend/chat-apps/index.ts +309 -0
  24. package/backend/chat-apps/link-events.ts +20 -0
  25. package/backend/chat-apps/media.test.ts +62 -0
  26. package/backend/chat-apps/media.ts +208 -0
  27. package/backend/chat-apps/messages.test.ts +229 -0
  28. package/backend/chat-apps/messages.ts +365 -0
  29. package/backend/chat-apps/outbound.ts +243 -0
  30. package/backend/chat-apps/pairing.test.ts +45 -0
  31. package/backend/chat-apps/pairing.ts +74 -0
  32. package/backend/chat-apps/platforms/index.ts +20 -0
  33. package/backend/chat-apps/platforms/telegram.test.ts +35 -0
  34. package/backend/chat-apps/platforms/telegram.ts +191 -0
  35. package/backend/chat-apps/platforms/types.ts +114 -0
  36. package/backend/chat-apps/questions.ts +133 -0
  37. package/backend/chat-apps/runtime.ts +572 -0
  38. package/backend/chat-apps/storage.test.ts +201 -0
  39. package/backend/chat-apps/turns.test.ts +45 -0
  40. package/backend/chat-apps/turns.ts +208 -0
  41. package/backend/containers/pty.ts +3 -11
  42. package/backend/control/actions/accounts.ts +89 -0
  43. package/backend/control/actions/files.ts +116 -0
  44. package/backend/control/actions/models.ts +188 -0
  45. package/backend/control/actions/projects.ts +272 -0
  46. package/backend/control/actions/sessions.ts +280 -0
  47. package/backend/control/actions/skills.ts +111 -0
  48. package/backend/control/control.test.ts +169 -0
  49. package/backend/control/define.ts +20 -0
  50. package/backend/control/folders.test.ts +67 -0
  51. package/backend/control/index.ts +213 -0
  52. package/backend/control/invoke.ts +44 -0
  53. package/backend/control/links.ts +35 -0
  54. package/backend/control/paging.ts +26 -0
  55. package/backend/control/types.ts +117 -0
  56. package/backend/control/workspace.ts +127 -0
  57. package/backend/database/migrations/084_create_channel_links.ts +71 -0
  58. package/backend/database/migrations/085_add_home_projects.ts +36 -0
  59. package/backend/database/migrations/086_single_owner.ts +418 -0
  60. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  61. package/backend/database/migrations/index.ts +28 -0
  62. package/backend/database/queries/auth-queries.ts +7 -85
  63. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  64. package/backend/database/queries/channel-queries.ts +270 -0
  65. package/backend/database/queries/db-client-connection-queries.ts +18 -56
  66. package/backend/database/queries/file-share-queries.ts +5 -23
  67. package/backend/database/queries/git-identity-queries.ts +31 -42
  68. package/backend/database/queries/graph-queries.ts +1 -1
  69. package/backend/database/queries/index.ts +15 -1
  70. package/backend/database/queries/message-queries.test.ts +146 -0
  71. package/backend/database/queries/message-queries.ts +42 -1
  72. package/backend/database/queries/permission-set-queries.ts +1 -1
  73. package/backend/database/queries/profile-queries.ts +1 -1
  74. package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
  75. package/backend/database/queries/project-queries.ts +50 -63
  76. package/backend/database/queries/session-queries.ts +28 -56
  77. package/backend/database/queries/ssh-connection-queries.ts +18 -41
  78. package/backend/db-client/env/diff.ts +9 -33
  79. package/backend/db-client/env/env.test.ts +8 -8
  80. package/backend/db-client/env/service.ts +1 -1
  81. package/backend/db-client/integrations/projector.ts +0 -5
  82. package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
  83. package/backend/engine/adapters/claude/message-converter.ts +25 -2
  84. package/backend/engine/adapters/cline/message-converter.ts +0 -1
  85. package/backend/engine/adapters/cline/stream.ts +11 -15
  86. package/backend/engine/adapters/codex/message-converter.ts +0 -2
  87. package/backend/engine/adapters/copilot/message-converter.ts +1 -2
  88. package/backend/engine/adapters/cursor/message-converter.ts +0 -1
  89. package/backend/engine/adapters/opencode/message-converter.ts +2 -4
  90. package/backend/engine/adapters/opencode/stream.ts +11 -0
  91. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  92. package/backend/engine/adapters/parent-scope.ts +44 -0
  93. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  94. package/backend/engine/adapters/pi/stream.ts +4 -5
  95. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  96. package/backend/engine/bootstrap-default-engine.ts +2 -2
  97. package/backend/engine/docs/adapter-contract.md +8 -1
  98. package/backend/engine/install-runner.ts +8 -17
  99. package/backend/files/file-shares.ts +20 -44
  100. package/backend/files/file-size-limit.ts +3 -3
  101. package/backend/files/file-watcher.ts +19 -0
  102. package/backend/files/image-processing.ts +1 -1
  103. package/backend/files/os-clipboard.ts +2 -2
  104. package/backend/git/contributors.test.ts +35 -0
  105. package/backend/git/contributors.ts +46 -0
  106. package/backend/git/git-executor.ts +25 -5
  107. package/backend/git/git-service.ts +420 -19
  108. package/backend/git/identity/credential-helper.test.ts +2 -7
  109. package/backend/git/identity/import-local.test.ts +11 -16
  110. package/backend/git/identity/import-local.ts +12 -12
  111. package/backend/git/identity/index.ts +10 -24
  112. package/backend/git/identity/resolve.ts +13 -14
  113. package/backend/git/identity/scope-config.ts +33 -28
  114. package/backend/git/identity/service.ts +44 -47
  115. package/backend/git/op-lock.test.ts +111 -0
  116. package/backend/git/op-lock.ts +180 -0
  117. package/backend/git/remote-sync.test.ts +249 -0
  118. package/backend/host/metrics.ts +1 -1
  119. package/backend/http/bearer-auth.ts +1 -2
  120. package/backend/http/files-download.test.ts +8 -9
  121. package/backend/http/files-download.ts +2 -2
  122. package/backend/http/files-shared.test.ts +62 -89
  123. package/backend/http/files-shared.ts +2 -2
  124. package/backend/http/files-upload.test.ts +3 -7
  125. package/backend/http/files-upload.ts +3 -3
  126. package/backend/http/notes-images.test.ts +15 -38
  127. package/backend/http/notes-images.ts +6 -8
  128. package/backend/http/ssh-sftp.ts +5 -10
  129. package/backend/http/static-assets.test.ts +78 -0
  130. package/backend/http/static-assets.ts +104 -0
  131. package/backend/index.ts +32 -16
  132. package/backend/integrations/accounts.ts +61 -3
  133. package/backend/integrations/index.ts +2 -2
  134. package/backend/integrations/registry/define.ts +15 -0
  135. package/backend/integrations/registry/index.ts +2 -0
  136. package/backend/integrations/registry/providers/telegram.ts +54 -0
  137. package/backend/integrations/registry/types.ts +21 -1
  138. package/backend/integrations/webhooks/gateway.ts +7 -6
  139. package/backend/integrations/webhooks/verify.test.ts +30 -0
  140. package/backend/integrations/webhooks/verify.ts +4 -0
  141. package/backend/mcp/external/project.ts +1 -1
  142. package/backend/mcp/internal/remote-server.test.ts +1 -3
  143. package/backend/mcp/internal/remote-server.ts +4 -4
  144. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  145. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  146. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  147. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  148. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  149. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  150. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  151. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  152. package/backend/memory/redact.ts +1 -1
  153. package/backend/notes/access.test.ts +28 -29
  154. package/backend/notes/access.ts +6 -11
  155. package/backend/permissions/service.ts +1 -1
  156. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  157. package/backend/preview/browser/browser-clipboard.ts +67 -0
  158. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  159. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  160. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  161. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  162. package/backend/preview/browser/browser-pool.ts +67 -6
  163. package/backend/preview/browser/browser-preview-service.ts +383 -29
  164. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  165. package/backend/preview/browser/browser-video-capture.ts +92 -5
  166. package/backend/preview/browser/element-locator.ts +190 -17
  167. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  168. package/backend/preview/browser/keyboard-chords.ts +132 -0
  169. package/backend/preview/browser/paste.ts +81 -0
  170. package/backend/preview/browser/process-usage.ts +142 -0
  171. package/backend/preview/browser/profile-lock.ts +209 -0
  172. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  173. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  174. package/backend/preview/browser/types.ts +40 -2
  175. package/backend/preview/browser/viewport.test.ts +45 -0
  176. package/backend/preview/browser/viewport.ts +96 -0
  177. package/backend/profiles/service.ts +2 -2
  178. package/backend/project/status-manager.ts +43 -172
  179. package/backend/projects/home.ts +61 -0
  180. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  181. package/backend/projects/project-cleanup.ts +0 -8
  182. package/backend/skills/service.ts +2 -3
  183. package/backend/snapshot/blob-store.ts +9 -1
  184. package/backend/snapshot/helpers.ts +3 -11
  185. package/backend/snapshot/line-stats.test.ts +80 -0
  186. package/backend/snapshot/line-stats.ts +64 -0
  187. package/backend/snapshot/restore.ts +252 -0
  188. package/backend/snapshot/snapshot-service.ts +14 -27
  189. package/backend/snapshot/turn-changes.test.ts +10 -5
  190. package/backend/snapshot/turn-changes.ts +78 -40
  191. package/backend/ssh/ptykit.ts +1 -2
  192. package/backend/terminal/ptykit.ts +10 -8
  193. package/backend/tunnel/public-origin.ts +31 -20
  194. package/backend/utils/user-helpers.ts +0 -55
  195. package/backend/utils/ws-wire.test.ts +87 -0
  196. package/backend/utils/ws-wire.ts +189 -0
  197. package/backend/utils/ws.ts +101 -192
  198. package/backend/worktrees/branching/engine.ts +3 -16
  199. package/backend/worktrees/branching/index.ts +1 -1
  200. package/backend/worktrees/branching/projector.ts +1 -1
  201. package/backend/worktrees/branching/service.ts +13 -25
  202. package/backend/ws/access.ts +12 -21
  203. package/backend/ws/artifacts/generate.ts +2 -2
  204. package/backend/ws/auth/device.ts +16 -71
  205. package/backend/ws/auth/index.ts +4 -22
  206. package/backend/ws/auth/login.test.ts +14 -60
  207. package/backend/ws/auth/login.ts +24 -124
  208. package/backend/ws/auth/status.ts +0 -1
  209. package/backend/ws/chat/composer.ts +118 -118
  210. package/backend/ws/chat/stream.ts +105 -57
  211. package/backend/ws/chat-apps/index.ts +117 -0
  212. package/backend/ws/containers/actions.ts +11 -25
  213. package/backend/ws/containers/index.ts +3 -4
  214. package/backend/ws/containers/list.ts +10 -36
  215. package/backend/ws/containers/logs.ts +2 -2
  216. package/backend/ws/containers/tunnel.ts +1 -2
  217. package/backend/ws/db-client/access.ts +2 -16
  218. package/backend/ws/db-client/accounts.ts +5 -15
  219. package/backend/ws/db-client/connections.ts +17 -25
  220. package/backend/ws/db-client/context.ts +1 -1
  221. package/backend/ws/db-client/env.ts +7 -10
  222. package/backend/ws/db-client/index.ts +2 -2
  223. package/backend/ws/db-client/io.ts +5 -5
  224. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  225. package/backend/ws/db-client/query.ts +18 -17
  226. package/backend/ws/db-client/schema.ts +13 -13
  227. package/backend/ws/db-client/structure.ts +35 -35
  228. package/backend/ws/db-client/supabase.ts +4 -21
  229. package/backend/ws/deployments/context.ts +1 -1
  230. package/backend/ws/deployments/crud.ts +0 -5
  231. package/backend/ws/engine/access.ts +7 -20
  232. package/backend/ws/engine/claude/accounts.ts +4 -4
  233. package/backend/ws/engine/cline/accounts.ts +5 -5
  234. package/backend/ws/engine/codex/accounts.ts +3 -3
  235. package/backend/ws/engine/pi/accounts.ts +5 -5
  236. package/backend/ws/files/clipboard.ts +8 -27
  237. package/backend/ws/files/image-edit.ts +6 -6
  238. package/backend/ws/files/index.ts +1 -1
  239. package/backend/ws/files/path-access.test.ts +32 -131
  240. package/backend/ws/files/path-access.ts +8 -87
  241. package/backend/ws/files/read.ts +45 -19
  242. package/backend/ws/files/reveal.ts +3 -3
  243. package/backend/ws/files/search.ts +7 -7
  244. package/backend/ws/files/share.ts +9 -13
  245. package/backend/ws/files/state.ts +9 -12
  246. package/backend/ws/files/watch.ts +3 -3
  247. package/backend/ws/files/write.ts +30 -31
  248. package/backend/ws/git/branch.ts +80 -59
  249. package/backend/ws/git/commit.ts +63 -44
  250. package/backend/ws/git/conflict.ts +16 -18
  251. package/backend/ws/git/identity-context.ts +8 -17
  252. package/backend/ws/git/identity.ts +17 -27
  253. package/backend/ws/git/index.ts +3 -1
  254. package/backend/ws/git/log.ts +52 -0
  255. package/backend/ws/git/op-state.ts +139 -0
  256. package/backend/ws/git/remote.ts +241 -141
  257. package/backend/ws/git/repo-context.ts +67 -0
  258. package/backend/ws/git/staging.ts +18 -28
  259. package/backend/ws/git/status.ts +5 -2
  260. package/backend/ws/index.ts +5 -1
  261. package/backend/ws/instructions/crud.ts +1 -1
  262. package/backend/ws/integrations/crud.ts +1 -3
  263. package/backend/ws/mcp/crud.ts +3 -5
  264. package/backend/ws/mcp/tools.ts +1 -1
  265. package/backend/ws/memory/crud.ts +14 -46
  266. package/backend/ws/memory/index.ts +2 -2
  267. package/backend/ws/messages/crud.ts +78 -8
  268. package/backend/ws/notes/index.ts +33 -39
  269. package/backend/ws/permissions/crud.ts +3 -4
  270. package/backend/ws/ports/index.ts +1 -2
  271. package/backend/ws/ports/kill.ts +5 -10
  272. package/backend/ws/ports/list.ts +4 -10
  273. package/backend/ws/preview/access.ts +1 -1
  274. package/backend/ws/preview/browser/interact.ts +52 -79
  275. package/backend/ws/preview/browser/native-ui.ts +24 -0
  276. package/backend/ws/preview/browser/stats.ts +98 -1
  277. package/backend/ws/preview/browser/tab-info.ts +15 -0
  278. package/backend/ws/preview/browser/tab.ts +19 -4
  279. package/backend/ws/preview/index.ts +29 -0
  280. package/backend/ws/preview/watchers.ts +84 -0
  281. package/backend/ws/profiles/crud.ts +6 -8
  282. package/backend/ws/project-artifacts/index.ts +30 -31
  283. package/backend/ws/projects/crud.ts +33 -35
  284. package/backend/ws/projects/index.ts +3 -8
  285. package/backend/ws/projects/info.ts +3 -3
  286. package/backend/ws/projects/overview.ts +19 -30
  287. package/backend/ws/projects/status.ts +17 -57
  288. package/backend/ws/sessions/crud.ts +42 -57
  289. package/backend/ws/sessions/index.ts +1 -1
  290. package/backend/ws/settings/crud.ts +1 -1
  291. package/backend/ws/skills/crud.ts +3 -4
  292. package/backend/ws/skills/index.ts +1 -1
  293. package/backend/ws/snapshot/changes.ts +12 -13
  294. package/backend/ws/snapshot/restore.ts +11 -295
  295. package/backend/ws/snapshot/timeline.ts +2 -4
  296. package/backend/ws/ssh/access.ts +6 -21
  297. package/backend/ws/ssh/connections.ts +21 -31
  298. package/backend/ws/ssh/forwards.ts +12 -12
  299. package/backend/ws/ssh/sftp.ts +34 -34
  300. package/backend/ws/ssh/tunnel.ts +1 -2
  301. package/backend/ws/stack/install.ts +7 -17
  302. package/backend/ws/subagents/crud.ts +1 -1
  303. package/backend/ws/terminal/tunnel.ts +2 -2
  304. package/backend/ws/tunnel/share.ts +0 -2
  305. package/backend/ws/user/crud.ts +1 -59
  306. package/backend/ws/user/index.ts +1 -1
  307. package/backend/ws/work/context.ts +1 -1
  308. package/backend/ws/work/crud.ts +0 -5
  309. package/backend/ws/workspace/state.ts +10 -13
  310. package/backend/ws/worktrees/branching.ts +7 -36
  311. package/backend/ws/worktrees/crud.ts +2 -2
  312. package/bin/clopen.ts +46 -41
  313. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  314. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  315. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  316. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  317. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  318. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  319. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  320. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  321. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  322. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  323. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  324. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  325. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  326. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
  327. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
  328. package/dist/assets/{index-CwuKQelV.js → index-CrVWZH_D.js} +1 -1
  329. package/dist/assets/index-CrVWZH_D.js.br +0 -0
  330. package/dist/assets/index-CrVWZH_D.js.gz +0 -0
  331. package/dist/assets/{index-BTcR1byF.js → index-DD0-3EWg.js} +1 -1
  332. package/dist/assets/index-DD0-3EWg.js.br +0 -0
  333. package/dist/assets/index-DD0-3EWg.js.gz +0 -0
  334. package/dist/assets/main-D2_TmcwQ.js +1240 -0
  335. package/dist/assets/main-D2_TmcwQ.js.br +0 -0
  336. package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
  337. package/dist/assets/main-Yucigcmf.css +1 -0
  338. package/dist/assets/main-Yucigcmf.css.br +0 -0
  339. package/dist/assets/main-Yucigcmf.css.gz +0 -0
  340. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  341. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  342. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  343. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  344. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  345. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  346. package/dist/fonts/dm-sans.css.br +0 -0
  347. package/dist/fonts/dm-sans.css.gz +0 -0
  348. package/dist/index.html +2 -2
  349. package/dist/index.html.br +0 -0
  350. package/dist/index.html.gz +0 -0
  351. package/dist/sw.js.br +0 -0
  352. package/dist/sw.js.gz +0 -0
  353. package/package.json +3 -3
  354. package/shared/constants/attachments.ts +14 -0
  355. package/shared/constants/engine-tools.ts +1 -1
  356. package/shared/constants/preview.test.ts +259 -0
  357. package/shared/constants/preview.ts +1018 -57
  358. package/shared/constants/tool-icons.ts +5 -0
  359. package/shared/types/containers/container.ts +1 -1
  360. package/shared/types/database/schema.ts +9 -6
  361. package/shared/types/git-identity.ts +1 -1
  362. package/shared/types/git.ts +116 -0
  363. package/shared/types/integrations.ts +7 -0
  364. package/shared/types/stores/settings.ts +1 -1
  365. package/shared/types/unified/index.ts +1 -1
  366. package/shared/types/unified/message.ts +0 -7
  367. package/shared/types/unified/stream.ts +13 -5
  368. package/shared/types/unified/tool.ts +15 -1
  369. package/shared/utils/ask-user-question.test.ts +319 -0
  370. package/shared/utils/ask-user-question.ts +154 -0
  371. package/shared/utils/diff-calculator.test.ts +178 -41
  372. package/shared/utils/diff-calculator.ts +383 -100
  373. package/shared/utils/home-project.ts +25 -0
  374. package/shared/utils/logger.ts +2 -0
  375. package/shared/utils/process-supervisor.test.ts +172 -0
  376. package/shared/utils/process-supervisor.ts +251 -0
  377. package/shared/utils/ws-chunk.test.ts +33 -0
  378. package/shared/utils/ws-chunk.ts +73 -0
  379. package/shared/utils/ws-client-chunks.test.ts +45 -0
  380. package/shared/utils/ws-client.ts +43 -0
  381. package/shared/utils/ws-server.ts +49 -21
  382. package/backend/auth/session-invalidation.test.ts +0 -112
  383. package/backend/auth/session-invalidation.ts +0 -77
  384. package/backend/project/status-manager.test.ts +0 -32
  385. package/backend/ws/auth/invites.ts +0 -94
  386. package/backend/ws/auth/users.ts +0 -112
  387. package/backend/ws/projects/presence.ts +0 -46
  388. package/backend/ws/stack/access.ts +0 -31
  389. package/dist/assets/main-BiDNMWb3.css +0 -1
  390. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -0,0 +1,319 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { ToolResult, UserMessage } from '$shared/types/unified';
3
+ import { attachSubmittedAnswers, parseAskUserQuestionAnswers, readAskUserQuestionAnswers } from './ask-user-question';
4
+
5
+ type Answers = Record<string, string>;
6
+ type Question = { question: string };
7
+
8
+ /*
9
+ * Byte-for-byte replicas of what each engine sends back. Kept in sync with
10
+ * the engines' own templates so the parser is exercised on real output.
11
+ */
12
+
13
+ // Claude Code: answered pairs only (empty answers are omitted), several closings.
14
+ const claude = {
15
+ answered: (qs: Question[], a: Answers) =>
16
+ `Your questions have been answered: ${claudePairs(qs, a)}. You can now continue with these answers in mind.`,
17
+ freeText: (qs: Question[], a: Answers) =>
18
+ `The user answered: ${claudePairs(qs, a)}. Read the answers carefully — they may request clarification, changes, or that you not proceed — and follow what they actually say.`,
19
+ followUp: (qs: Question[], a: Answers) =>
20
+ `The user wants to discuss this further before you proceed. So far they answered: ${claudePairs(qs, a)}. Call AskUserQuestion again with follow-up questions that build on these answers (do not repeat these); do not start the task yet.`,
21
+ followUpWithNote: (qs: Question[], a: Answers) =>
22
+ `The user wants to discuss this further before you proceed. So far they answered: ${claudePairs(qs, a)}. They also wrote: "Ask about "auth". Then billing.". Call AskUserQuestion again with follow-up questions that build on these answers (do not repeat these); do not start the task yet.`,
23
+ afk: (qs: Question[], a: Answers) =>
24
+ `The user did not respond within 5 minutes.\n\nBefore going idle the user had selected: ${claudePairs(qs, a)}.`
25
+ };
26
+ function claudePairs(qs: Question[], a: Answers): string {
27
+ return qs.filter(({ question }) => a[question]).map(({ question }) => `"${question}"="${a[question]}"`).join(', ');
28
+ }
29
+
30
+ // OpenCode: every question, unanswered ones as "Unanswered".
31
+ const opencode = (qs: Question[], a: Answers) =>
32
+ `User has answered your questions: ${qs.map(({ question }) => `"${question}"="${a[question] || 'Unanswered'}"`).join(', ')}. You can now continue with the user's answers in mind.`;
33
+
34
+ // Clopen's own adapters (Cline, Cursor, Pi, Qwen): every submitted answer.
35
+ const clopen = (qs: Question[], a: Answers) =>
36
+ `User has answered your questions: ${qs.map(({ question }) => `"${question}"="${a[question]}"`).join(', ')}. You can now continue with the user's answers in mind.`;
37
+
38
+ // An engine this parser has never heard of, with a quote-free closing.
39
+ const unknownEngine = (qs: Question[], a: Answers) =>
40
+ `Answers: ${claudePairs(qs, a)}. Proceed with care.`;
41
+
42
+ const FORMATTERS = {
43
+ 'claude/answered': claude.answered,
44
+ 'claude/free-text': claude.freeText,
45
+ 'claude/follow-up': claude.followUp,
46
+ 'claude/follow-up with note': claude.followUpWithNote,
47
+ 'claude/afk': claude.afk,
48
+ opencode,
49
+ 'clopen adapters': clopen,
50
+ 'unknown engine': unknownEngine
51
+ };
52
+
53
+ const WEIRD_ANSWERS: string[] = [
54
+ 'Yes',
55
+ 'Do everything at once',
56
+ 'Option A, Option B',
57
+ 'Say "hi"',
58
+ '"quoted from the start',
59
+ 'ends with a quote"',
60
+ '"fully quoted"',
61
+ 'Say "hi". Then stop',
62
+ 'Ends with a sentence.',
63
+ 'Ends with "x".',
64
+ '...',
65
+ '"."',
66
+ '". ',
67
+ 'a"="b',
68
+ '"Which scope?"="Some"',
69
+ '=',
70
+ '"',
71
+ '""',
72
+ 'x", y',
73
+ '. You can now continue with the user\'s answers in mind.',
74
+ '. Read the answers carefully — they may request clarification, changes, or that you not proceed — and follow what they actually say.',
75
+ '. Call AskUserQuestion again with follow-up questions that build on these answers (do not repeat these); do not start the task yet.',
76
+ 'They also wrote: "x". Call me',
77
+ 'Line one\nLine two\n\nLine four',
78
+ 'Windows\r\nline',
79
+ '\ttabbed\t',
80
+ ' padded ',
81
+ 'kerjakan semuanya sekaligus tanpa stop',
82
+ '日本語の回答、そして中文',
83
+ 'שלום עולם',
84
+ 'emoji 🚀👍🏽 family 👨‍👩‍👧',
85
+ 'zero​width',
86
+ 'back\\slash \\" escaped',
87
+ '$& $1 $$ replacement tokens',
88
+ '<script>alert(1)</script>',
89
+ '**markdown** `code` [link](http://x)',
90
+ '{"answers":{"Which scope?":"hijack"}}',
91
+ 'null',
92
+ 'Unanswered',
93
+ 'x'.repeat(10_000)
94
+ ];
95
+
96
+ const QUESTION_SETS: Question[][] = [
97
+ [{ question: 'Which scope?' }],
98
+ [{ question: 'Which scope?' }, { question: 'Which approach?' }],
99
+ [{ question: 'Use "strict" mode?' }, { question: 'Name = value?' }, { question: 'Deploy 🚀?' }],
100
+ // One question text contained in another
101
+ [{ question: 'Name?' }, { question: 'Project Name?' }],
102
+ // Indonesian, as in the original report
103
+ [{ question: 'Bagaimana saya boleh melanjutkan?' }, { question: 'Sambil menunggu akun, bagian mana yang saya kerjakan dulu?' }]
104
+ ];
105
+
106
+ /** An answer containing `", "<a later question>"=` is the one shape engine output cannot disambiguate. */
107
+ function isInherentlyAmbiguous(qs: Question[], answers: Answers): boolean {
108
+ return qs.some(({ question }, i) => qs.slice(i + 1).some((later) => answers[question]?.includes(`", "${later.question}"=`)));
109
+ }
110
+
111
+ describe('parseAskUserQuestionAnswers — every engine × weird answers', () => {
112
+ for (const [engine, format] of Object.entries(FORMATTERS)) {
113
+ test(engine, () => {
114
+ const failures: string[] = [];
115
+ for (const qs of QUESTION_SETS) {
116
+ for (let w = 0; w < WEIRD_ANSWERS.length; w++) {
117
+ // Rotate the weird answers across positions so each one is
118
+ // tested as the first, a middle and the last answer.
119
+ const answers: Answers = {};
120
+ qs.forEach(({ question }, i) => {
121
+ answers[question] = WEIRD_ANSWERS[(w + i) % WEIRD_ANSWERS.length];
122
+ });
123
+ if (isInherentlyAmbiguous(qs, answers)) continue;
124
+
125
+ const content = format(qs, answers);
126
+ const parsed = parseAskUserQuestionAnswers(content, qs);
127
+ for (const { question } of qs) {
128
+ const expected = answers[question];
129
+ if (parsed[question] !== expected) {
130
+ failures.push(`${JSON.stringify(question)}: expected ${JSON.stringify(expected).slice(0, 80)}, got ${JSON.stringify(parsed[question]).slice(0, 80)}`);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ expect(failures).toEqual([]);
136
+ });
137
+ }
138
+ });
139
+
140
+ describe('parseAskUserQuestionAnswers', () => {
141
+ const qs = [{ question: 'Which scope?' }, { question: 'Which approach?' }];
142
+
143
+ test('drops the Claude Code closing from the reported answer', () => {
144
+ const content = claude.freeText(qs, { 'Which scope?': 'Some', 'Which approach?': 'kerjakan semuanya sekaligus tanpa stop' });
145
+ expect(parseAskUserQuestionAnswers(content, qs)).toEqual({
146
+ 'Which scope?': 'Some',
147
+ 'Which approach?': 'kerjakan semuanya sekaligus tanpa stop'
148
+ });
149
+ });
150
+
151
+ test('skips a question Claude omitted because it was left empty', () => {
152
+ const three = [...qs, { question: 'Which name?' }];
153
+ const content = claude.answered(three, { 'Which scope?': 'Some', 'Which approach?': '', 'Which name?': 'Foo' });
154
+ expect(parseAskUserQuestionAnswers(content, three)).toEqual({ 'Which scope?': 'Some', 'Which name?': 'Foo' });
155
+ });
156
+
157
+ test('reports OpenCode\'s own placeholder for an unanswered question verbatim', () => {
158
+ const content = opencode(qs, { 'Which scope?': 'Some' });
159
+ expect(parseAskUserQuestionAnswers(content, qs)).toEqual({ 'Which scope?': 'Some', 'Which approach?': 'Unanswered' });
160
+ });
161
+
162
+ test('an unknown closing that itself quotes is indistinguishable from the answer', () => {
163
+ // Documents the limit of the fallback: without knowing the closing,
164
+ // `"Bold". Go, "now".` reads the same as an answer ending in `". Go, "now`.
165
+ const content = '"Which scope?"="Bold". Go, "now".';
166
+ expect(parseAskUserQuestionAnswers(content, qs)).toEqual({ 'Which scope?': 'Bold". Go, "now' });
167
+ });
168
+
169
+ test('handles a result with no closing at all', () => {
170
+ expect(parseAskUserQuestionAnswers('"Which scope?"="Some"', qs)).toEqual({ 'Which scope?': 'Some' });
171
+ expect(parseAskUserQuestionAnswers('"Which scope?"="Some".', qs)).toEqual({ 'Which scope?': 'Some' });
172
+ expect(parseAskUserQuestionAnswers('"Which scope?"="Some" \n', qs)).toEqual({ 'Which scope?': 'Some' });
173
+ });
174
+
175
+ test('reads the JSON answers shape, coercing non-string values', () => {
176
+ expect(parseAskUserQuestionAnswers('{"answers":{"Which scope?":"Some"}}', qs)).toEqual({ 'Which scope?': 'Some' });
177
+ expect(parseAskUserQuestionAnswers('{"answers":{"Which scope?":["A","B"],"Which approach?":3}}', qs))
178
+ .toEqual({ 'Which scope?': 'A, B', 'Which approach?': '3' });
179
+ expect(parseAskUserQuestionAnswers('{"answers":{"Which scope?":null}}', qs)).toEqual({});
180
+ });
181
+
182
+ test('ignores JSON that is not an answers object', () => {
183
+ expect(parseAskUserQuestionAnswers('{"answers":["Some"]}', qs)).toEqual({});
184
+ expect(parseAskUserQuestionAnswers('null', qs)).toEqual({});
185
+ expect(parseAskUserQuestionAnswers('"Which scope?"', qs)).toEqual({});
186
+ });
187
+
188
+ test('returns nothing for results without answers', () => {
189
+ expect(parseAskUserQuestionAnswers('Error: questions is required', qs)).toEqual({});
190
+ expect(parseAskUserQuestionAnswers('The user did not answer the questions.', qs)).toEqual({});
191
+ expect(parseAskUserQuestionAnswers('The user responded: just do it', qs)).toEqual({});
192
+ expect(parseAskUserQuestionAnswers('', qs)).toEqual({});
193
+ expect(parseAskUserQuestionAnswers('"Which scope?"="Some"', [])).toEqual({});
194
+ });
195
+
196
+ test('does not hang on very large results', () => {
197
+ const huge = 'a'.repeat(1_000_000);
198
+ const started = performance.now();
199
+ expect(parseAskUserQuestionAnswers(claude.freeText(qs, { 'Which scope?': huge }), qs)).toEqual({ 'Which scope?': huge });
200
+ expect(parseAskUserQuestionAnswers(`"Which scope?"="${huge}`, qs)).toEqual({ 'Which scope?': huge });
201
+ expect(performance.now() - started).toBeLessThan(1000);
202
+ });
203
+ });
204
+
205
+ function toolResult(toolUseId: string, content: string, isError = false): ToolResult {
206
+ return { type: 'tool_result', toolUseId, content, isError };
207
+ }
208
+
209
+ function userMessage(...content: UserMessage['content']): UserMessage {
210
+ return { type: 'user', content, synthetic: false } as UserMessage;
211
+ }
212
+
213
+ describe('attachSubmittedAnswers → readAskUserQuestionAnswers (every engine × weird answers)', () => {
214
+ for (const [engine, format] of Object.entries(FORMATTERS)) {
215
+ test(engine, () => {
216
+ const failures: string[] = [];
217
+ for (const qs of QUESTION_SETS) {
218
+ for (let w = 0; w < WEIRD_ANSWERS.length; w++) {
219
+ const answers: Answers = {};
220
+ qs.forEach(({ question }, i) => {
221
+ answers[question] = WEIRD_ANSWERS[(w + i) % WEIRD_ANSWERS.length];
222
+ });
223
+ // No ambiguity carve-out: the structured path never reads the prose.
224
+ const message = userMessage(toolResult('call-1', format(qs, answers)));
225
+ attachSubmittedAnswers(message, new Map([['call-1', { ...answers }]]));
226
+
227
+ // Round-trip as the DB and the WS do, then read as the UI does.
228
+ const stored = JSON.parse(JSON.stringify(message)) as UserMessage;
229
+ const block = stored.content[0] as ToolResult;
230
+ const read = readAskUserQuestionAnswers(block, qs);
231
+ if (JSON.stringify(read) !== JSON.stringify(answers)) {
232
+ failures.push(`${JSON.stringify(answers).slice(0, 120)} → ${JSON.stringify(read).slice(0, 120)}`);
233
+ }
234
+ }
235
+ }
236
+ expect(failures).toEqual([]);
237
+ });
238
+ }
239
+ });
240
+
241
+ describe('attachSubmittedAnswers', () => {
242
+ const answers = { 'Which scope?': 'Some' };
243
+
244
+ test('attaches only to the matching tool_result and consumes the entry', () => {
245
+ const submitted = new Map([['call-1', answers]]);
246
+ const other = toolResult('call-2', 'unrelated');
247
+ const match = toolResult('call-1', 'engine prose');
248
+ const message = userMessage({ type: 'text', text: 'hi' }, other, match);
249
+
250
+ attachSubmittedAnswers(message, submitted);
251
+
252
+ expect(match.answers).toEqual(answers);
253
+ expect(match.content).toBe('engine prose');
254
+ expect(other.answers).toBeUndefined();
255
+ expect(submitted.size).toBe(0);
256
+ });
257
+
258
+ test('leaves an error result unanswered but still consumes the entry', () => {
259
+ const submitted = new Map([['call-1', answers]]);
260
+ const rejected = toolResult('call-1', 'Error: questions is required', true);
261
+
262
+ attachSubmittedAnswers(userMessage(rejected), submitted);
263
+
264
+ expect(rejected.answers).toBeUndefined();
265
+ expect(submitted.size).toBe(0);
266
+ });
267
+
268
+ test('keeps answers for a question whose result has not arrived yet', () => {
269
+ const submitted = new Map([['call-1', answers], ['call-9', { 'Later?': 'Yes' }]]);
270
+ attachSubmittedAnswers(userMessage(toolResult('call-1', 'x')), submitted);
271
+ expect([...submitted.keys()]).toEqual(['call-9']);
272
+ });
273
+
274
+ test('attaches each of several questions answered in one message', () => {
275
+ const a = toolResult('call-1', 'x');
276
+ const b = toolResult('call-2', 'y');
277
+ attachSubmittedAnswers(userMessage(a, b), new Map([['call-1', { Q1: 'A' }], ['call-2', { Q2: 'B' }]]));
278
+ expect(a.answers).toEqual({ Q1: 'A' });
279
+ expect(b.answers).toEqual({ Q2: 'B' });
280
+ });
281
+
282
+ test('does nothing without submitted answers', () => {
283
+ const block = toolResult('call-1', 'x');
284
+ attachSubmittedAnswers(userMessage(block), new Map());
285
+ expect(block.answers).toBeUndefined();
286
+ });
287
+
288
+ test('treats tool_use ids as opaque strings', () => {
289
+ const ids = ['toolu_01AbC', 'call_9f8e', 'copilot-ask-user-6b1f', '', ' ', 'id with "quotes" and 🚀', '__proto__', 'constructor'];
290
+ for (const id of ids) {
291
+ const block = toolResult(id, 'x');
292
+ attachSubmittedAnswers(userMessage(block), new Map([[id, { Q: id }]]));
293
+ expect(block.answers).toEqual({ Q: id });
294
+ }
295
+ });
296
+ });
297
+
298
+ describe('readAskUserQuestionAnswers', () => {
299
+ const qs = [{ question: 'Which scope?' }, { question: 'Which approach?' }];
300
+
301
+ test('prefers attached answers over anything the prose says', () => {
302
+ const content = claude.freeText(qs, { 'Which scope?': 'From prose' });
303
+ expect(readAskUserQuestionAnswers({ content, answers: { 'Which scope?': 'Submitted' } }, qs))
304
+ .toEqual({ 'Which scope?': 'Submitted' });
305
+ });
306
+
307
+ test('falls back to the prose for results saved before answers were attached', () => {
308
+ const content = claude.freeText(qs, { 'Which scope?': 'Some', 'Which approach?': 'kerjakan semuanya sekaligus tanpa stop' });
309
+ expect(readAskUserQuestionAnswers({ content }, qs)).toEqual({
310
+ 'Which scope?': 'Some',
311
+ 'Which approach?': 'kerjakan semuanya sekaligus tanpa stop'
312
+ });
313
+ });
314
+
315
+ test('keeps attached answers verbatim, including empty and question-keyed oddities', () => {
316
+ const attached = { 'Which scope?': '', 'Which approach?': '", "Which scope?"="spoof', 'Not asked?': 'extra' };
317
+ expect(readAskUserQuestionAnswers({ content: '', answers: attached }, qs)).toEqual(attached);
318
+ });
319
+ });
@@ -0,0 +1,154 @@
1
+ import type { ToolResult, UserMessage } from '$shared/types/unified';
2
+
3
+ /**
4
+ * The answers a user gave to an AskUserQuestion.
5
+ *
6
+ * The source of truth is `ToolResult.answers`: the stream manager attaches
7
+ * exactly what the user submitted to the tool_result the engine sends back
8
+ * (see `attachSubmittedAnswers`), so the UI never depends on how an engine
9
+ * words its result for the model.
10
+ *
11
+ * Results saved before that field existed only carry the engine's prose, so
12
+ * those fall back to `parseAskUserQuestionAnswers`. That history is frozen —
13
+ * every new result carries `answers` — so the closings it knows never need to
14
+ * grow when an engine rewords its output.
15
+ */
16
+ export function readAskUserQuestionAnswers(
17
+ result: Pick<ToolResult, 'content' | 'answers'>,
18
+ questions: readonly { question: string }[]
19
+ ): Record<string, string> {
20
+ return result.answers ?? parseAskUserQuestionAnswers(result.content, questions);
21
+ }
22
+
23
+ /**
24
+ * Stamp the answers the user submitted onto the matching tool_results of an
25
+ * engine's user message, consuming them from `submitted`. Matching is by
26
+ * tool_use id, the same id the UI answered with and pairs the result by.
27
+ * Error results are left alone: the question was rejected, not answered.
28
+ */
29
+ export function attachSubmittedAnswers(
30
+ message: UserMessage,
31
+ submitted: Map<string, Record<string, string>>
32
+ ): void {
33
+ if (submitted.size === 0) return;
34
+ for (const block of message.content) {
35
+ if (block.type !== 'tool_result') continue;
36
+ const answers = submitted.get(block.toolUseId);
37
+ if (!answers) continue;
38
+ submitted.delete(block.toolUseId);
39
+ if (!block.isError) block.answers = answers;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Legacy fallback: recover answers from a tool_result's prose.
45
+ *
46
+ * Two shapes reach the UI:
47
+ * - JSON `{"answers": {<question>: <answer>}}` (Copilot, rewritten by its converter)
48
+ * - Prose `<preamble> "Q1"="A1", "Q2"="A2".<closing>`
49
+ *
50
+ * The prose is never escaped, so an answer may itself contain `"`, `". ` or
51
+ * anything else. Two facts keep the split exact anyway: every question text is
52
+ * known, so an answer ends right before `", "<a later question>"=`; and the
53
+ * closing each engine appended is fixed text anchored at the end of the result,
54
+ * so the last answer ends where that closing starts. Closings not listed here
55
+ * fall back to the last `"` that is followed by a sentence break.
56
+ *
57
+ * Ambiguous by construction (the engine output is identical either way): an
58
+ * answer that literally contains `", "<a later question>"=`.
59
+ */
60
+
61
+ /** Closings engines appended after the answer list, each anchored to the end of the result. */
62
+ const KNOWN_CLOSINGS: readonly RegExp[] = [
63
+ // OpenCode and Clopen's own adapters (Cline, Cursor, Pi, Qwen)
64
+ /\. You can now continue with the user's answers in mind\.\s*$/,
65
+ // Claude Code — every answer matched an offered option
66
+ /\. You can now continue with these answers in mind\.\s*$/,
67
+ // Claude Code — at least one free-text answer
68
+ /\. Read the answers carefully — they may request clarification, changes, or that you not proceed — and follow what they actually say\.\s*$/,
69
+ // Claude Code — the user asked for follow-up questions, optionally with a note
70
+ /\.(?: They also wrote: "[\s\S]*"\.)? Call \S+ again with follow-up questions that build on these answers \(do not repeat these\); do not start the task yet\.\s*$/
71
+ ];
72
+
73
+ export function parseAskUserQuestionAnswers(
74
+ content: string,
75
+ questions: readonly { question: string }[]
76
+ ): Record<string, string> {
77
+ const fromJson = parseJsonAnswers(content);
78
+ if (fromJson) return fromJson;
79
+
80
+ // Where each question's answer opens, in question order.
81
+ const starts: { question: string; markerStart: number; answerStart: number }[] = [];
82
+ let cursor = 0;
83
+ for (const { question } of questions) {
84
+ const marker = `"${question}"="`;
85
+ const markerStart = content.indexOf(marker, cursor);
86
+ if (markerStart === -1) continue;
87
+ const answerStart = markerStart + marker.length;
88
+ starts.push({ question, markerStart, answerStart });
89
+ cursor = answerStart;
90
+ }
91
+
92
+ const answers: Record<string, string> = {};
93
+ for (let i = 0; i < starts.length; i++) {
94
+ const { question, answerStart } = starts[i];
95
+ const answerEnd = i < starts.length - 1
96
+ ? findNextAnswerBoundary(content, answerStart, starts.slice(i + 1).map((s) => s.question))
97
+ : findLastAnswerEnd(content, answerStart);
98
+ answers[question] = content.slice(answerStart, answerEnd);
99
+ }
100
+ return answers;
101
+ }
102
+
103
+ function parseJsonAnswers(content: string): Record<string, string> | null {
104
+ let json: unknown;
105
+ try {
106
+ json = JSON.parse(content);
107
+ } catch {
108
+ return null;
109
+ }
110
+ const answers = (json as { answers?: unknown } | null)?.answers;
111
+ if (!answers || typeof answers !== 'object' || Array.isArray(answers)) return null;
112
+
113
+ const result: Record<string, string> = {};
114
+ for (const [question, value] of Object.entries(answers)) {
115
+ if (value === null || value === undefined) continue;
116
+ result[question] = Array.isArray(value) ? value.map(String).join(', ') : String(value);
117
+ }
118
+ return result;
119
+ }
120
+
121
+ /** The earliest `", "<later question>"=` after this answer, i.e. its closing quote. */
122
+ function findNextAnswerBoundary(content: string, answerStart: number, laterQuestions: string[]): number {
123
+ let boundary = -1;
124
+ for (const question of laterQuestions) {
125
+ const idx = content.indexOf(`", "${question}"=`, answerStart);
126
+ if (idx !== -1 && (boundary === -1 || idx < boundary)) boundary = idx;
127
+ }
128
+ return boundary === -1 ? findLastAnswerEnd(content, answerStart) : boundary;
129
+ }
130
+
131
+ /** Index of the last answer's closing quote. */
132
+ function findLastAnswerEnd(content: string, answerStart: number): number {
133
+ const tail = content.slice(answerStart);
134
+ for (const closing of KNOWN_CLOSINGS) {
135
+ const match = closing.exec(tail);
136
+ if (match) return closingQuoteBefore(content, answerStart, answerStart + match.index);
137
+ }
138
+
139
+ const trimmed = content.trimEnd();
140
+ if (trimmed.endsWith('".')) return closingQuoteBefore(content, answerStart, trimmed.length - 1);
141
+ if (trimmed.endsWith('"')) return closingQuoteBefore(content, answerStart, trimmed.length);
142
+
143
+ // Unknown closing: it is joined by `". `, and the last such join wins so an
144
+ // answer that itself contains `". ` stays whole.
145
+ const sentenceJoin = content.lastIndexOf('". ');
146
+ if (sentenceJoin >= answerStart) return sentenceJoin;
147
+ const lastQuote = content.lastIndexOf('"');
148
+ return lastQuote >= answerStart ? lastQuote : content.length;
149
+ }
150
+
151
+ /** `listEnd` sits just past the closing quote; step back over it when present. */
152
+ function closingQuoteBefore(content: string, answerStart: number, listEnd: number): number {
153
+ return listEnd > answerStart && content[listEnd - 1] === '"' ? listEnd - 1 : listEnd;
154
+ }