@things-factory/ai-assistant 10.1.278 → 10.1.280

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 (531) hide show
  1. package/dist-client/bootstrap.d.ts +4 -4
  2. package/dist-client/bootstrap.js +4 -8
  3. package/dist-client/components/ai-model-price-table.d.ts +32 -0
  4. package/dist-client/components/ai-model-price-table.js +311 -0
  5. package/dist-client/components/ai-usage-table.d.ts +17 -0
  6. package/dist-client/components/ai-usage-table.js +151 -0
  7. package/dist-client/index.d.ts +1 -0
  8. package/dist-client/index.js +2 -0
  9. package/dist-client/pages/ai-model-price-page.d.ts +37 -0
  10. package/dist-client/pages/ai-model-price-page.js +312 -0
  11. package/dist-client/route.d.ts +1 -1
  12. package/dist-client/route.js +4 -0
  13. package/dist-client/settings/ai-agent-setting-let.js +11 -0
  14. package/dist-client/utils/model-price-model.d.ts +31 -0
  15. package/dist-client/utils/model-price-model.js +30 -0
  16. package/dist-client/utils/usage-charts.d.ts +21 -0
  17. package/dist-client/utils/usage-charts.js +45 -0
  18. package/dist-client/utils/usage-model.d.ts +44 -0
  19. package/dist-client/utils/usage-model.js +44 -0
  20. package/dist-server/service/ai-agent-resolver.d.ts +46 -0
  21. package/dist-server/service/ai-agent-resolver.js +252 -0
  22. package/package.json +25 -10
  23. package/things-factory.config.js +4 -1
  24. package/translations/en.json +46 -4
  25. package/translations/es.json +43 -1
  26. package/translations/ja.json +43 -1
  27. package/translations/ko.json +46 -4
  28. package/translations/ms.json +43 -1
  29. package/translations/zh.json +43 -1
  30. package/client/bootstrap.ts +0 -27
  31. package/client/components/assistant-chat.test.ts +0 -149
  32. package/client/components/assistant-chat.ts +0 -5599
  33. package/client/components/assistant-dock.ts +0 -1036
  34. package/client/components/assistant-invite.ts +0 -138
  35. package/client/components/assistant-mode.test.ts +0 -119
  36. package/client/components/assistant-mode.ts +0 -174
  37. package/client/components/assistant-selection-bar.test.ts +0 -167
  38. package/client/components/assistant-selection-bar.ts +0 -178
  39. package/client/components/assistant-session-manager.ts +0 -915
  40. package/client/components/assistant-session-toolbar.ts +0 -80
  41. package/client/components/chat-defaults.ts +0 -64
  42. package/client/components/chat-echo-dedup.test.ts +0 -253
  43. package/client/components/chat-echo-dedup.ts +0 -190
  44. package/client/components/chat-input-builder.test.ts +0 -86
  45. package/client/components/chat-input-builder.ts +0 -133
  46. package/client/components/chat-proposal-survival.test.ts +0 -73
  47. package/client/components/entry-review.ts +0 -346
  48. package/client/components/markdown.test.ts +0 -518
  49. package/client/components/markdown.ts +0 -508
  50. package/client/components/mention-popup-helpers.ts +0 -433
  51. package/client/components/mention-popup.test.ts +0 -588
  52. package/client/components/mention-popup.ts +0 -261
  53. package/client/components/panel-aria.test.ts +0 -59
  54. package/client/components/proposal-outcome-line.ts +0 -74
  55. package/client/components/proposal-request.test.ts +0 -73
  56. package/client/components/reply-message.test.ts +0 -15
  57. package/client/components/reply-message.ts +0 -11
  58. package/client/components/roster-identity.test.ts +0 -8
  59. package/client/components/roster-identity.ts +0 -4
  60. package/client/components/workspace-view.ts +0 -486
  61. package/client/index.ts +0 -36
  62. package/client/pages/assistant-workspace-page.ts +0 -317
  63. package/client/route.ts +0 -9
  64. package/client/settings/agent-settings-model.ts +0 -164
  65. package/client/settings/ai-agent-setting-let.ts +0 -667
  66. package/client/settings/ai-usage-setting-let.ts +0 -240
  67. package/client/settings/usage-model.ts +0 -46
  68. package/client/setup-assistant-dock.ts +0 -177
  69. package/client/tsconfig.json +0 -13
  70. package/client/utils/addressed-draft.test.ts +0 -31
  71. package/client/utils/agent-choice.ts +0 -56
  72. package/client/utils/applied-screens.ts +0 -36
  73. package/client/utils/assistant-activity.ts +0 -122
  74. package/client/utils/assistant-ask.test.ts +0 -38
  75. package/client/utils/assistant-ask.ts +0 -93
  76. package/client/utils/assistant-capability-read.ts +0 -24
  77. package/client/utils/assistant-capability.test.ts +0 -17
  78. package/client/utils/assistant-capability.ts +0 -19
  79. package/client/utils/assistant-navigation.test.ts +0 -66
  80. package/client/utils/assistant-navigation.ts +0 -11
  81. package/client/utils/assistant-proposals.ts +0 -85
  82. package/client/utils/assistant-request-context.ts +0 -63
  83. package/client/utils/assistant-selection.test.ts +0 -54
  84. package/client/utils/assistant-selection.ts +0 -75
  85. package/client/utils/assistant-session-actions.ts +0 -32
  86. package/client/utils/assistant-session-admin.ts +0 -239
  87. package/client/utils/assistant-session-controller.test.ts +0 -75
  88. package/client/utils/assistant-session-controller.ts +0 -208
  89. package/client/utils/assistant-session-transport.ts +0 -46
  90. package/client/utils/assistant-surface.ts +0 -178
  91. package/client/utils/assistant-typing.test.ts +0 -33
  92. package/client/utils/assistant-typing.ts +0 -53
  93. package/client/utils/attachment-policy.ts +0 -106
  94. package/client/utils/composer-frame.ts +0 -77
  95. package/client/utils/document-text.ts +0 -332
  96. package/client/utils/entry-hash.ts +0 -35
  97. package/client/utils/entry-proposal.ts +0 -215
  98. package/client/utils/entry-workspace.ts +0 -70
  99. package/client/utils/invite-proposal-register.ts +0 -31
  100. package/client/utils/invite-proposal.test.ts +0 -40
  101. package/client/utils/invite-proposal.ts +0 -54
  102. package/client/utils/menu-room.ts +0 -33
  103. package/client/utils/open-page.ts +0 -21
  104. package/client/utils/pasted-table.ts +0 -145
  105. package/client/utils/pdf-pages.ts +0 -25
  106. package/client/utils/spreadsheet-text.ts +0 -125
  107. package/client/utils/workspace.ts +0 -89
  108. package/dist-client/bootstrap.js.map +0 -1
  109. package/dist-client/components/assistant-chat.js.map +0 -1
  110. package/dist-client/components/assistant-chat.test.d.ts +0 -1
  111. package/dist-client/components/assistant-chat.test.js +0 -138
  112. package/dist-client/components/assistant-chat.test.js.map +0 -1
  113. package/dist-client/components/assistant-dock.js.map +0 -1
  114. package/dist-client/components/assistant-invite.js.map +0 -1
  115. package/dist-client/components/assistant-mode.js.map +0 -1
  116. package/dist-client/components/assistant-mode.test.d.ts +0 -1
  117. package/dist-client/components/assistant-mode.test.js +0 -100
  118. package/dist-client/components/assistant-mode.test.js.map +0 -1
  119. package/dist-client/components/assistant-selection-bar.js.map +0 -1
  120. package/dist-client/components/assistant-selection-bar.test.d.ts +0 -1
  121. package/dist-client/components/assistant-selection-bar.test.js +0 -148
  122. package/dist-client/components/assistant-selection-bar.test.js.map +0 -1
  123. package/dist-client/components/assistant-session-manager.js.map +0 -1
  124. package/dist-client/components/assistant-session-toolbar.js.map +0 -1
  125. package/dist-client/components/chat-defaults.js.map +0 -1
  126. package/dist-client/components/chat-echo-dedup.js.map +0 -1
  127. package/dist-client/components/chat-echo-dedup.test.d.ts +0 -1
  128. package/dist-client/components/chat-echo-dedup.test.js +0 -223
  129. package/dist-client/components/chat-echo-dedup.test.js.map +0 -1
  130. package/dist-client/components/chat-input-builder.js.map +0 -1
  131. package/dist-client/components/chat-input-builder.test.d.ts +0 -1
  132. package/dist-client/components/chat-input-builder.test.js +0 -70
  133. package/dist-client/components/chat-input-builder.test.js.map +0 -1
  134. package/dist-client/components/chat-proposal-survival.test.d.ts +0 -1
  135. package/dist-client/components/chat-proposal-survival.test.js +0 -61
  136. package/dist-client/components/chat-proposal-survival.test.js.map +0 -1
  137. package/dist-client/components/entry-review.js.map +0 -1
  138. package/dist-client/components/markdown.js.map +0 -1
  139. package/dist-client/components/markdown.test.d.ts +0 -1
  140. package/dist-client/components/markdown.test.js +0 -418
  141. package/dist-client/components/markdown.test.js.map +0 -1
  142. package/dist-client/components/mention-popup-helpers.js.map +0 -1
  143. package/dist-client/components/mention-popup.js.map +0 -1
  144. package/dist-client/components/mention-popup.test.d.ts +0 -1
  145. package/dist-client/components/mention-popup.test.js +0 -474
  146. package/dist-client/components/mention-popup.test.js.map +0 -1
  147. package/dist-client/components/panel-aria.test.d.ts +0 -1
  148. package/dist-client/components/panel-aria.test.js +0 -53
  149. package/dist-client/components/panel-aria.test.js.map +0 -1
  150. package/dist-client/components/proposal-outcome-line.js.map +0 -1
  151. package/dist-client/components/proposal-request.test.d.ts +0 -1
  152. package/dist-client/components/proposal-request.test.js +0 -63
  153. package/dist-client/components/proposal-request.test.js.map +0 -1
  154. package/dist-client/components/reply-message.js.map +0 -1
  155. package/dist-client/components/reply-message.test.d.ts +0 -1
  156. package/dist-client/components/reply-message.test.js +0 -16
  157. package/dist-client/components/reply-message.test.js.map +0 -1
  158. package/dist-client/components/roster-identity.js.map +0 -1
  159. package/dist-client/components/roster-identity.test.d.ts +0 -1
  160. package/dist-client/components/roster-identity.test.js +0 -9
  161. package/dist-client/components/roster-identity.test.js.map +0 -1
  162. package/dist-client/components/workspace-view.js.map +0 -1
  163. package/dist-client/index.js.map +0 -1
  164. package/dist-client/pages/assistant-workspace-page.js.map +0 -1
  165. package/dist-client/route.js.map +0 -1
  166. package/dist-client/settings/agent-settings-model.js.map +0 -1
  167. package/dist-client/settings/ai-agent-setting-let.js.map +0 -1
  168. package/dist-client/settings/ai-usage-setting-let.d.ts +0 -25
  169. package/dist-client/settings/ai-usage-setting-let.js +0 -258
  170. package/dist-client/settings/ai-usage-setting-let.js.map +0 -1
  171. package/dist-client/settings/usage-model.d.ts +0 -32
  172. package/dist-client/settings/usage-model.js +0 -25
  173. package/dist-client/settings/usage-model.js.map +0 -1
  174. package/dist-client/setup-assistant-dock.js.map +0 -1
  175. package/dist-client/tsconfig.tsbuildinfo +0 -1
  176. package/dist-client/utils/addressed-draft.test.d.ts +0 -1
  177. package/dist-client/utils/addressed-draft.test.js +0 -27
  178. package/dist-client/utils/addressed-draft.test.js.map +0 -1
  179. package/dist-client/utils/agent-choice.js.map +0 -1
  180. package/dist-client/utils/applied-screens.js.map +0 -1
  181. package/dist-client/utils/assistant-activity.js.map +0 -1
  182. package/dist-client/utils/assistant-ask.js.map +0 -1
  183. package/dist-client/utils/assistant-ask.test.d.ts +0 -1
  184. package/dist-client/utils/assistant-ask.test.js +0 -40
  185. package/dist-client/utils/assistant-ask.test.js.map +0 -1
  186. package/dist-client/utils/assistant-capability-read.js.map +0 -1
  187. package/dist-client/utils/assistant-capability.js.map +0 -1
  188. package/dist-client/utils/assistant-capability.test.d.ts +0 -1
  189. package/dist-client/utils/assistant-capability.test.js +0 -16
  190. package/dist-client/utils/assistant-capability.test.js.map +0 -1
  191. package/dist-client/utils/assistant-navigation.js.map +0 -1
  192. package/dist-client/utils/assistant-navigation.test.d.ts +0 -1
  193. package/dist-client/utils/assistant-navigation.test.js +0 -63
  194. package/dist-client/utils/assistant-navigation.test.js.map +0 -1
  195. package/dist-client/utils/assistant-proposals.js.map +0 -1
  196. package/dist-client/utils/assistant-request-context.js.map +0 -1
  197. package/dist-client/utils/assistant-selection.js.map +0 -1
  198. package/dist-client/utils/assistant-selection.test.d.ts +0 -1
  199. package/dist-client/utils/assistant-selection.test.js +0 -46
  200. package/dist-client/utils/assistant-selection.test.js.map +0 -1
  201. package/dist-client/utils/assistant-session-actions.js.map +0 -1
  202. package/dist-client/utils/assistant-session-admin.js.map +0 -1
  203. package/dist-client/utils/assistant-session-controller.js.map +0 -1
  204. package/dist-client/utils/assistant-session-controller.test.d.ts +0 -1
  205. package/dist-client/utils/assistant-session-controller.test.js +0 -56
  206. package/dist-client/utils/assistant-session-controller.test.js.map +0 -1
  207. package/dist-client/utils/assistant-session-transport.js.map +0 -1
  208. package/dist-client/utils/assistant-surface.js.map +0 -1
  209. package/dist-client/utils/assistant-typing.js.map +0 -1
  210. package/dist-client/utils/assistant-typing.test.d.ts +0 -1
  211. package/dist-client/utils/assistant-typing.test.js +0 -30
  212. package/dist-client/utils/assistant-typing.test.js.map +0 -1
  213. package/dist-client/utils/attachment-policy.js.map +0 -1
  214. package/dist-client/utils/composer-frame.js.map +0 -1
  215. package/dist-client/utils/document-text.js.map +0 -1
  216. package/dist-client/utils/entry-hash.js.map +0 -1
  217. package/dist-client/utils/entry-proposal.js.map +0 -1
  218. package/dist-client/utils/entry-workspace.js.map +0 -1
  219. package/dist-client/utils/invite-proposal-register.js.map +0 -1
  220. package/dist-client/utils/invite-proposal.js.map +0 -1
  221. package/dist-client/utils/invite-proposal.test.d.ts +0 -1
  222. package/dist-client/utils/invite-proposal.test.js +0 -35
  223. package/dist-client/utils/invite-proposal.test.js.map +0 -1
  224. package/dist-client/utils/menu-room.js.map +0 -1
  225. package/dist-client/utils/open-page.js.map +0 -1
  226. package/dist-client/utils/pasted-table.js.map +0 -1
  227. package/dist-client/utils/pdf-pages.js.map +0 -1
  228. package/dist-client/utils/spreadsheet-text.js.map +0 -1
  229. package/dist-client/utils/workspace.js.map +0 -1
  230. package/dist-server/door-declaration-report.js.map +0 -1
  231. package/dist-server/index.js.map +0 -1
  232. package/dist-server/role-tasks.js.map +0 -1
  233. package/dist-server/service/ai-agent-resolver.js.map +0 -1
  234. package/dist-server/service/assistant-capability-resolver.js.map +0 -1
  235. package/dist-server/service/assistant-chat-resolver.js.map +0 -1
  236. package/dist-server/service/assistant-mode/assistant-mode-resolver.js.map +0 -1
  237. package/dist-server/service/assistant-mode/fallback-subjects.js.map +0 -1
  238. package/dist-server/service/assistant-mode/index.js.map +0 -1
  239. package/dist-server/service/assistant-mode/mode-categories.js.map +0 -1
  240. package/dist-server/service/assistant-mode/record-subject.js.map +0 -1
  241. package/dist-server/service/assistant-mode/registry.js.map +0 -1
  242. package/dist-server/service/assistant-mode/resolve.js.map +0 -1
  243. package/dist-server/service/assistant-mode/screen-rules.js.map +0 -1
  244. package/dist-server/service/assistant-mode/turn-lines.js.map +0 -1
  245. package/dist-server/service/assistant-mode/types.js.map +0 -1
  246. package/dist-server/service/chat-message/carried-turns.js.map +0 -1
  247. package/dist-server/service/chat-message/chat-message-broadcast.js.map +0 -1
  248. package/dist-server/service/chat-message/chat-message-publish.js.map +0 -1
  249. package/dist-server/service/chat-message/chat-message-room.js.map +0 -1
  250. package/dist-server/service/chat-message/chat-message-subscription.js.map +0 -1
  251. package/dist-server/service/chat-message/chat-message.js.map +0 -1
  252. package/dist-server/service/chat-message/chat-typing-subscription.js.map +0 -1
  253. package/dist-server/service/chat-message/chat-typing.js.map +0 -1
  254. package/dist-server/service/chat-message/door-access.js.map +0 -1
  255. package/dist-server/service/chat-message/fold-history.js.map +0 -1
  256. package/dist-server/service/chat-message/fold-session-history.js.map +0 -1
  257. package/dist-server/service/chat-message/history-summary.js.map +0 -1
  258. package/dist-server/service/chat-message/index.js.map +0 -1
  259. package/dist-server/service/chat-message/llm-history.js.map +0 -1
  260. package/dist-server/service/chat-message/message-doors.js.map +0 -1
  261. package/dist-server/service/chat-message/proposal-outcome.js.map +0 -1
  262. package/dist-server/service/chat-message/reader-gate.js.map +0 -1
  263. package/dist-server/service/chat-message/room-message.js.map +0 -1
  264. package/dist-server/service/chat-message/room-turn.js.map +0 -1
  265. package/dist-server/service/chat-message/used-tools.js.map +0 -1
  266. package/dist-server/service/chat-session/attachment-policy.js.map +0 -1
  267. package/dist-server/service/chat-session/attachment-route.js.map +0 -1
  268. package/dist-server/service/chat-session/attachment-tool-result.js.map +0 -1
  269. package/dist-server/service/chat-session/attachment-tools.js.map +0 -1
  270. package/dist-server/service/chat-session/chat-session.js.map +0 -1
  271. package/dist-server/service/chat-session/index.js.map +0 -1
  272. package/dist-server/service/chat-session/session-activity-broadcast.js.map +0 -1
  273. package/dist-server/service/chat-session/session-activity-publish.js.map +0 -1
  274. package/dist-server/service/chat-session/session-activity-subscription.js.map +0 -1
  275. package/dist-server/service/chat-session/session-anchor.js.map +0 -1
  276. package/dist-server/service/chat-session/session-attachments.js.map +0 -1
  277. package/dist-server/service/chat-session/session-cleanup.js.map +0 -1
  278. package/dist-server/service/chat-session/session-inbox.js.map +0 -1
  279. package/dist-server/service/chat-session/session-kind.js.map +0 -1
  280. package/dist-server/service/chat-session/session-name.js.map +0 -1
  281. package/dist-server/service/chat-session/session-purge.js.map +0 -1
  282. package/dist-server/service/chat-session/session-retention.js.map +0 -1
  283. package/dist-server/service/chat-session/session-visibility.js.map +0 -1
  284. package/dist-server/service/chat-session/session-write-gate.js.map +0 -1
  285. package/dist-server/service/chat-session/station-session-guard.js.map +0 -1
  286. package/dist-server/service/chat-session/turn-attachments.js.map +0 -1
  287. package/dist-server/service/chat-session-participant/chat-session-participant.js.map +0 -1
  288. package/dist-server/service/chat-session-participant/index.js.map +0 -1
  289. package/dist-server/service/chat-session-participant/invite-notification.js.map +0 -1
  290. package/dist-server/service/chat-session-participant/mention-invite.js.map +0 -1
  291. package/dist-server/service/chat-session-participant/participant-lookup-roles.js.map +0 -1
  292. package/dist-server/service/chat-session-participant/participant-lookup.js.map +0 -1
  293. package/dist-server/service/chat-session-participant/presence.js.map +0 -1
  294. package/dist-server/service/chat-session-participant/read-roster.js.map +0 -1
  295. package/dist-server/service/chat-session-resolver.js.map +0 -1
  296. package/dist-server/service/data-entry/entry-apply.js.map +0 -1
  297. package/dist-server/service/data-entry/entry-hash.js.map +0 -1
  298. package/dist-server/service/data-entry/entry-refusal.js.map +0 -1
  299. package/dist-server/service/data-entry/entry-resolver.js.map +0 -1
  300. package/dist-server/service/data-entry/entry-screen.js.map +0 -1
  301. package/dist-server/service/data-entry/entry-sources.js.map +0 -1
  302. package/dist-server/service/data-entry/entry-target.js.map +0 -1
  303. package/dist-server/service/data-entry/entry-tools.js.map +0 -1
  304. package/dist-server/service/data-entry/entry-update.js.map +0 -1
  305. package/dist-server/service/data-read/list-read.js.map +0 -1
  306. package/dist-server/service/data-read/read-target.js.map +0 -1
  307. package/dist-server/service/data-read/read-tools.js.map +0 -1
  308. package/dist-server/service/grounding-sources.js.map +0 -1
  309. package/dist-server/service/help-documents/help-keys.js.map +0 -1
  310. package/dist-server/service/help-documents/help-tools.js.map +0 -1
  311. package/dist-server/service/index.js.map +0 -1
  312. package/dist-server/service/people/index.js.map +0 -1
  313. package/dist-server/service/people/invite-tools.js.map +0 -1
  314. package/dist-server/service/people/people-keys.js.map +0 -1
  315. package/dist-server/service/people/people-read.js.map +0 -1
  316. package/dist-server/service/people/person-subject.js.map +0 -1
  317. package/dist-server/service/request-translator.js.map +0 -1
  318. package/dist-server/service/testing/conversation-script.js.map +0 -1
  319. package/dist-server/service/testing/mode-conformance.js.map +0 -1
  320. package/dist-server/service/tool-access.js.map +0 -1
  321. package/dist-server/service/types.js.map +0 -1
  322. package/dist-server/service/unattended-run/assistant-run.js.map +0 -1
  323. package/dist-server/service/unattended-run/index.js.map +0 -1
  324. package/dist-server/service/unattended-run/limits.js.map +0 -1
  325. package/dist-server/service/unattended-run/run-as.js.map +0 -1
  326. package/dist-server/service/unattended-run/run-budget.js.map +0 -1
  327. package/dist-server/service/unattended-run/run-ledger.js.map +0 -1
  328. package/dist-server/service/unattended-run/run-outcome.js.map +0 -1
  329. package/dist-server/service/unattended-run/run-store.js.map +0 -1
  330. package/dist-server/service/unattended-run/run-unattended.js.map +0 -1
  331. package/dist-server/service/unattended-run/unattended-prompt.js.map +0 -1
  332. package/dist-server/service/workspace/workspace-blocks.js.map +0 -1
  333. package/dist-server/service/workspace/workspace-tools.js.map +0 -1
  334. package/dist-server/tool-registry-boot-report.js.map +0 -1
  335. package/dist-server/tsconfig.tsbuildinfo +0 -1
  336. package/docs/session-controller.md +0 -52
  337. package/server/door-declaration-report.test.ts +0 -53
  338. package/server/door-declaration-report.ts +0 -61
  339. package/server/explicit-graphql-types.test.ts +0 -56
  340. package/server/index.ts +0 -36
  341. package/server/role-tasks.ts +0 -14
  342. package/server/service/ai-agent-resolver.ts +0 -330
  343. package/server/service/assistant-capability-resolver.ts +0 -66
  344. package/server/service/assistant-chat-resolver.ts +0 -640
  345. package/server/service/assistant-mode/assistant-mode-resolver.ts +0 -101
  346. package/server/service/assistant-mode/conversation-category.test.ts +0 -48
  347. package/server/service/assistant-mode/fallback-subjects.ts +0 -36
  348. package/server/service/assistant-mode/index.ts +0 -22
  349. package/server/service/assistant-mode/mode-categories.ts +0 -178
  350. package/server/service/assistant-mode/mode-front.test.ts +0 -183
  351. package/server/service/assistant-mode/one-conversation-per-subject.test.ts +0 -37
  352. package/server/service/assistant-mode/open-subject-door.test.ts +0 -52
  353. package/server/service/assistant-mode/record-subject.test.ts +0 -41
  354. package/server/service/assistant-mode/record-subject.ts +0 -44
  355. package/server/service/assistant-mode/registry.test.ts +0 -171
  356. package/server/service/assistant-mode/registry.ts +0 -139
  357. package/server/service/assistant-mode/resolve.test.ts +0 -129
  358. package/server/service/assistant-mode/resolve.ts +0 -113
  359. package/server/service/assistant-mode/screen-rules.test.ts +0 -99
  360. package/server/service/assistant-mode/screen-rules.ts +0 -103
  361. package/server/service/assistant-mode/turn-lines.ts +0 -43
  362. package/server/service/assistant-mode/types.ts +0 -138
  363. package/server/service/chat-message/carried-turns.test.ts +0 -80
  364. package/server/service/chat-message/carried-turns.ts +0 -112
  365. package/server/service/chat-message/chat-message-broadcast.integration.test.ts +0 -73
  366. package/server/service/chat-message/chat-message-broadcast.test.ts +0 -40
  367. package/server/service/chat-message/chat-message-broadcast.ts +0 -70
  368. package/server/service/chat-message/chat-message-publish.ts +0 -22
  369. package/server/service/chat-message/chat-message-room.test.ts +0 -145
  370. package/server/service/chat-message/chat-message-room.ts +0 -50
  371. package/server/service/chat-message/chat-message-subscription.ts +0 -77
  372. package/server/service/chat-message/chat-message.ts +0 -289
  373. package/server/service/chat-message/chat-typing-subscription.ts +0 -52
  374. package/server/service/chat-message/chat-typing.test.ts +0 -45
  375. package/server/service/chat-message/chat-typing.ts +0 -48
  376. package/server/service/chat-message/door-access.test.ts +0 -72
  377. package/server/service/chat-message/door-access.ts +0 -65
  378. package/server/service/chat-message/fold-history-window.test.ts +0 -184
  379. package/server/service/chat-message/fold-history.test.ts +0 -98
  380. package/server/service/chat-message/fold-history.ts +0 -77
  381. package/server/service/chat-message/fold-session-history.test.ts +0 -116
  382. package/server/service/chat-message/fold-session-history.ts +0 -115
  383. package/server/service/chat-message/history-summary.test.ts +0 -127
  384. package/server/service/chat-message/history-summary.ts +0 -100
  385. package/server/service/chat-message/index.ts +0 -13
  386. package/server/service/chat-message/llm-history.test.ts +0 -245
  387. package/server/service/chat-message/llm-history.ts +0 -182
  388. package/server/service/chat-message/message-doors.test.ts +0 -124
  389. package/server/service/chat-message/message-doors.ts +0 -132
  390. package/server/service/chat-message/proposal-outcome.test.ts +0 -111
  391. package/server/service/chat-message/proposal-outcome.ts +0 -99
  392. package/server/service/chat-message/reader-gate.ts +0 -44
  393. package/server/service/chat-message/room-message.test.ts +0 -21
  394. package/server/service/chat-message/room-message.ts +0 -22
  395. package/server/service/chat-message/room-turn.ts +0 -42
  396. package/server/service/chat-message/used-tools.test.ts +0 -19
  397. package/server/service/chat-message/used-tools.ts +0 -25
  398. package/server/service/chat-session/attachment-policy.test.ts +0 -42
  399. package/server/service/chat-session/attachment-policy.ts +0 -91
  400. package/server/service/chat-session/attachment-route.ts +0 -45
  401. package/server/service/chat-session/attachment-tool-result.test.ts +0 -63
  402. package/server/service/chat-session/attachment-tool-result.ts +0 -37
  403. package/server/service/chat-session/attachment-tools.ts +0 -66
  404. package/server/service/chat-session/chat-session.ts +0 -244
  405. package/server/service/chat-session/group-room.test.ts +0 -233
  406. package/server/service/chat-session/index.ts +0 -5
  407. package/server/service/chat-session/session-activity-broadcast.ts +0 -77
  408. package/server/service/chat-session/session-activity-publish.ts +0 -49
  409. package/server/service/chat-session/session-activity-receivers.test.ts +0 -26
  410. package/server/service/chat-session/session-activity-subscription.ts +0 -66
  411. package/server/service/chat-session/session-anchor.ts +0 -142
  412. package/server/service/chat-session/session-attachments.ts +0 -90
  413. package/server/service/chat-session/session-cleanup.test.ts +0 -83
  414. package/server/service/chat-session/session-cleanup.ts +0 -69
  415. package/server/service/chat-session/session-inbox.test.ts +0 -273
  416. package/server/service/chat-session/session-inbox.ts +0 -240
  417. package/server/service/chat-session/session-kind.test.ts +0 -24
  418. package/server/service/chat-session/session-kind.ts +0 -32
  419. package/server/service/chat-session/session-name.ts +0 -32
  420. package/server/service/chat-session/session-purge.test.ts +0 -24
  421. package/server/service/chat-session/session-purge.ts +0 -117
  422. package/server/service/chat-session/session-retention.ts +0 -17
  423. package/server/service/chat-session/session-visibility.test.ts +0 -130
  424. package/server/service/chat-session/session-visibility.ts +0 -68
  425. package/server/service/chat-session/session-write-gate.test.ts +0 -59
  426. package/server/service/chat-session/session-write-gate.ts +0 -31
  427. package/server/service/chat-session/station-session-guard.ts +0 -25
  428. package/server/service/chat-session/turn-attachments.test.ts +0 -106
  429. package/server/service/chat-session/turn-attachments.ts +0 -45
  430. package/server/service/chat-session-participant/chat-session-participant.ts +0 -135
  431. package/server/service/chat-session-participant/index.ts +0 -8
  432. package/server/service/chat-session-participant/invite-notification.test.ts +0 -80
  433. package/server/service/chat-session-participant/invite-notification.ts +0 -118
  434. package/server/service/chat-session-participant/mention-invite.test.ts +0 -173
  435. package/server/service/chat-session-participant/mention-invite.ts +0 -180
  436. package/server/service/chat-session-participant/participant-lookup-roles.ts +0 -6
  437. package/server/service/chat-session-participant/participant-lookup.ts +0 -22
  438. package/server/service/chat-session-participant/presence.test.ts +0 -39
  439. package/server/service/chat-session-participant/presence.ts +0 -21
  440. package/server/service/chat-session-participant/read-roster.test.ts +0 -27
  441. package/server/service/chat-session-participant/read-roster.ts +0 -17
  442. package/server/service/chat-session-resolver.ts +0 -1455
  443. package/server/service/data-entry/data-entry-update.test.ts +0 -378
  444. package/server/service/data-entry/data-entry.test.ts +0 -494
  445. package/server/service/data-entry/entry-apply.ts +0 -247
  446. package/server/service/data-entry/entry-hash.ts +0 -35
  447. package/server/service/data-entry/entry-refusal.test.ts +0 -73
  448. package/server/service/data-entry/entry-refusal.ts +0 -20
  449. package/server/service/data-entry/entry-resolver.ts +0 -74
  450. package/server/service/data-entry/entry-screen.ts +0 -14
  451. package/server/service/data-entry/entry-sources.ts +0 -39
  452. package/server/service/data-entry/entry-target.ts +0 -774
  453. package/server/service/data-entry/entry-tools.ts +0 -282
  454. package/server/service/data-entry/entry-update.ts +0 -238
  455. package/server/service/data-read/data-read.test.ts +0 -395
  456. package/server/service/data-read/detail-lists.test.ts +0 -61
  457. package/server/service/data-read/list-missing.test.ts +0 -49
  458. package/server/service/data-read/list-read.ts +0 -146
  459. package/server/service/data-read/list-status.test.ts +0 -46
  460. package/server/service/data-read/read-target.ts +0 -509
  461. package/server/service/data-read/read-tools.ts +0 -334
  462. package/server/service/data-read/read-words.test.ts +0 -99
  463. package/server/service/data-read/record-keys.test.ts +0 -42
  464. package/server/service/grounding-sources.test.ts +0 -55
  465. package/server/service/grounding-sources.ts +0 -46
  466. package/server/service/help-documents/help-keys.ts +0 -2
  467. package/server/service/help-documents/help-tools.test.ts +0 -40
  468. package/server/service/help-documents/help-tools.ts +0 -88
  469. package/server/service/index.ts +0 -99
  470. package/server/service/people/index.ts +0 -15
  471. package/server/service/people/invite-tools.ts +0 -159
  472. package/server/service/people/invite.test.ts +0 -159
  473. package/server/service/people/people-keys.ts +0 -16
  474. package/server/service/people/people-read.test.ts +0 -82
  475. package/server/service/people/people-read.ts +0 -56
  476. package/server/service/people/person-subject.test.ts +0 -161
  477. package/server/service/people/person-subject.ts +0 -83
  478. package/server/service/request-translator.test.ts +0 -45
  479. package/server/service/request-translator.ts +0 -33
  480. package/server/service/session-anchor.test.ts +0 -198
  481. package/server/service/station-session-guard.test.ts +0 -31
  482. package/server/service/testing/conversation-scenario.test.ts +0 -164
  483. package/server/service/testing/conversation-script.test.ts +0 -133
  484. package/server/service/testing/conversation-script.ts +0 -296
  485. package/server/service/testing/mode-conformance.test.ts +0 -61
  486. package/server/service/testing/mode-conformance.ts +0 -165
  487. package/server/service/tool-access.test.ts +0 -96
  488. package/server/service/tool-access.ts +0 -36
  489. package/server/service/types.ts +0 -15
  490. package/server/service/unattended-run/assistant-run.ts +0 -199
  491. package/server/service/unattended-run/index.ts +0 -10
  492. package/server/service/unattended-run/limits.ts +0 -24
  493. package/server/service/unattended-run/run-as.ts +0 -38
  494. package/server/service/unattended-run/run-budget.ts +0 -58
  495. package/server/service/unattended-run/run-ledger.ts +0 -31
  496. package/server/service/unattended-run/run-outcome.ts +0 -43
  497. package/server/service/unattended-run/run-store-race.pg.test.ts +0 -83
  498. package/server/service/unattended-run/run-store.ts +0 -162
  499. package/server/service/unattended-run/run-unattended.test.ts +0 -478
  500. package/server/service/unattended-run/run-unattended.ts +0 -248
  501. package/server/service/unattended-run/unattended-prompt.ts +0 -24
  502. package/server/service/workspace/workspace-blocks.ts +0 -134
  503. package/server/service/workspace/workspace-tools.ts +0 -108
  504. package/server/service/workspace/workspace.test.ts +0 -74
  505. package/server/tool-registry-boot-report.test.ts +0 -41
  506. package/server/tool-registry-boot-report.ts +0 -63
  507. package/test/ai-agent-settings.test.ts +0 -123
  508. package/test/applied-screens.test.ts +0 -65
  509. package/test/assistant-chat-call-sites.test.ts +0 -92
  510. package/test/assistant-dock.test.ts +0 -294
  511. package/test/assistant-request-context.test.ts +0 -72
  512. package/test/assistant-session-controller.test.ts +0 -87
  513. package/test/assistant-session-manager.test.ts +0 -186
  514. package/test/assistant-session-toolbar.test.ts +0 -43
  515. package/test/attachment-one-rule.test.ts +0 -46
  516. package/test/attachment-policy-agree.test.ts +0 -38
  517. package/test/composer-frame.test.ts +0 -173
  518. package/test/document-text.test.ts +0 -175
  519. package/test/entry-card-styles.test.ts +0 -18
  520. package/test/entry-proposal.test.ts +0 -186
  521. package/test/entry-workspace.test.ts +0 -89
  522. package/test/menu-room.test.ts +0 -33
  523. package/test/open-doors.test.ts +0 -164
  524. package/test/open-page.test.ts +0 -31
  525. package/test/pasted-table.test.ts +0 -147
  526. package/test/refusals-in-korean.test.ts +0 -80
  527. package/test/session-discovery.test.ts +0 -43
  528. package/test/spreadsheet-text.test.ts +0 -92
  529. package/test/translations.test.ts +0 -80
  530. package/test/workspace.test.ts +0 -54
  531. package/tsconfig.json +0 -9
@@ -1,1455 +0,0 @@
1
- /**
2
- * ChatSession lifecycle resolver — start/get/recordDirectPatch/revertPatch + 메시지·패치 페이징 query.
3
- *
4
- * 핵심: `recordDirectPatch` — 사용자가 모델러에서 직접 편집 시 클라이언트가 호출.
5
- * 이게 PatchEntry(source:'user-direct') + system 메시지 자동 추가 → AI 가 모든 변경을 인지.
6
- */
7
- import { Resolver, Query, Mutation, Arg, Ctx, Directive, Int, ObjectType, Field, ID } from 'type-graphql'
8
- import { GraphQLJSON } from 'graphql-scalars'
9
- import { User } from '@things-factory/auth-base'
10
- import { buildDomainUsersQueryBuilder } from '@things-factory/auth-base/dist-server/utils/get-domain-users.js'
11
-
12
- import { getRepository, pubsub } from '@things-factory/shell'
13
- import { config } from '@things-factory/env'
14
- import { In, IsNull, Like, Not } from 'typeorm'
15
-
16
- import { ChatSession } from './chat-session/chat-session.js'
17
- import { anchorColumns, anchorWhere } from './chat-session/session-anchor.js'
18
- import { buildInbox, applyHidden, activityPatch, listedEntries, searchInbox, filterInbox, searchReadableMessages, INBOX_SCAN_CAP, type InboxFilter } from './chat-session/session-inbox.js'
19
- import { carriedOriginalWhere, planCarriedTurns, quoteCarriedAnswer } from './chat-message/carried-turns.js'
20
- import { roomMessageBody } from './chat-message/room-message.js'
21
- import { readerGate } from './chat-message/reader-gate.js'
22
- import { requestTranslator } from './request-translator.js'
23
- import { initialVisibility, isOpenRoom, mayReadSession, maySeat, SESSION_VISIBILITIES } from './chat-session/session-visibility.js'
24
- import { PERSON_ROOM_REFUSALS, personOfAnchor, personRoomRefusal, personSeatOf } from './people/person-subject.js'
25
- import { tellRoomTurn } from './chat-message/room-turn.js'
26
- import { seatParticipants, seatTurn } from './chat-session-participant/mention-invite.js'
27
- import { CHAT_TYPING_TOPIC, typingNotice } from './chat-message/chat-typing.js'
28
- import { sendInviteNotification } from './chat-session-participant/invite-notification.js'
29
- import { readRoster } from './chat-session-participant/read-roster.js'
30
- import { isSessionParticipant } from './chat-session-participant/participant-lookup.js'
31
- import { assertMayWriteSession } from './chat-session/session-write-gate.js'
32
- import { archiveDaysOf, cleanupReason, idleDays, isArchived } from './chat-session/session-cleanup.js'
33
- import { DAY_MS, retentionDaysOf } from './chat-session/session-retention.js'
34
-
35
- /** The keeping periods the config asks for (shared-dock.md §9-5, §2-7). */
36
- function keeping(): { deletedDays: number | null; archiveDays: number | null } {
37
- const options = config.get('ai-assistant', {}) ?? {}
38
- return { deletedDays: retentionDaysOf(options.sessionRetentionDays), archiveDays: archiveDaysOf(options.sessionArchiveDays) }
39
- }
40
-
41
- /** One request reads the list once - the list, its total and its counts ask together and share it. */
42
- const inboxReads = new WeakMap<object, Map<string, Promise<any[]>>>()
43
-
44
- /** 초대 알림 — 발송은 호스트의 기전을 그대로 쓴다(`sendInviteNotification`, 문 셋이 같은 한 곳). */
45
- async function notifyInvited(context: any, invited: string[], inviter: any, sessionName?: string): Promise<void> {
46
- await sendInviteNotification((context.state as any)?.sendNotice, invited, inviter, sessionName, undefined, requestTranslator(context))
47
- }
48
-
49
- /**
50
- * A private room is the owner's alone (ADR-0073 decision 3) - closing a room to private sends its members out.
51
- * Returns who left, so their lists can be told once.
52
- */
53
- async function sendOutMembers(domainId: string, sessionId: string, tx?: any): Promise<string[]> {
54
- const repo = getRepository(ChatSessionParticipant, tx)
55
- const seats = await repo.find({ where: { domain: { id: domainId }, session: { id: sessionId }, role: 'member' } as any })
56
- for (const seat of seats) await repo.softDelete(seat.id!)
57
- return seats.map(seat => (seat as any).userId).filter(Boolean)
58
- }
59
-
60
- /** Every door that writes into a conversation passes this first (`session-write-gate.ts`). */
61
- async function writeGate(session: any, context: any, tx?: any): Promise<void> {
62
- const { domain, user } = context.state
63
- await assertMayWriteSession({
64
- session,
65
- userId: user?.id,
66
- isParticipant: () => isSessionParticipant(domain.id, session.id, user?.id, tx),
67
- t: (key, options) => (context.t ? context.t(key, options) : String(options?.defaultValue ?? key))
68
- })
69
- }
70
- import {
71
- formatProposalOutcomeLine,
72
- formatProposalRequestedLine,
73
- proposalAlreadyTaken,
74
- PROPOSAL_OUTCOME_PREFIX,
75
- PROPOSAL_VERDICTS,
76
- type ProposalOutcome
77
- } from './chat-message/proposal-outcome.js'
78
- import { publishSessionActivity } from './chat-session/session-activity-publish.js'
79
- import { ChatMessage } from './chat-message/chat-message.js'
80
- import { ChatSessionParticipant } from './chat-session-participant/chat-session-participant.js'
81
- import { publishChatMessage } from './chat-message/chat-message-publish.js'
82
- import GraphQLUpload from 'graphql-upload/GraphQLUpload.js'
83
- import type { FileUpload } from 'graphql-upload/GraphQLUpload.js'
84
- import { getAssistantMode } from './assistant-mode/registry.js'
85
- import { refuseAttachments, type AttachmentRefusal } from './chat-session/attachment-policy.js'
86
- import { attachmentKindWords, sessionNameOf } from './chat-session/session-name.js'
87
- import { removeAttachmentRows, saveChatAttachments } from './chat-session/session-attachments.js'
88
-
89
- @ObjectType({
90
- description:
91
- 'Session list entry for the inbox — a session plus this viewer\'s unread state. Ordered by recent activity so a user can find where to go back to.'
92
- })
93
- class ChatSessionInboxEntry {
94
- @Field(type => ID, { nullable: true, description: 'Session id.' })
95
- id?: string
96
-
97
- @Field({ nullable: true, description: 'User-given session name (tab label).' })
98
- name?: string
99
-
100
- /** 어느 대화인가 — 목록에서 고른 것이 지금 열린 대화와 다르면 화면이 그 대화로 따라간다. */
101
- @Field({ nullable: true, description: 'Which conversation this session is — the registered mode kind.' })
102
- kind?: string
103
-
104
- @Field({ nullable: true, description: "What the session is anchored to: 'board' | 'space' | 'instance' | 'none'." })
105
- anchorType?: string
106
-
107
- @Field({ nullable: true, description: 'Id of the anchored target.' })
108
- anchorId?: string
109
-
110
- @Field({ nullable: true, description: 'Connected board id (board-anchored sessions).' })
111
- boardId?: string
112
-
113
- @Field({ nullable: true, description: 'Timestamp of the last message (list ordering / unread comparison).' })
114
- lastMessageAt?: Date
115
-
116
- @Field({ nullable: true, description: 'Short preview of the last message.' })
117
- lastMessagePreview?: string
118
-
119
- /** 미리보기가 이 사람에게 가려져 나갔는가 — 목록도 대화와 같은 관문을 지난다(ADR-0073 판정 1). */
120
- @Field({ nullable: true, description: 'True when the preview was replaced because this reader does not pass the doors of the message it came from.' })
121
- previewRedacted?: boolean
122
-
123
- @Field({ nullable: true, description: 'Session creation timestamp.' })
124
- createdAt?: Date
125
-
126
- @Field({ description: 'Whether this viewer has unread activity in the session.' })
127
- unread!: boolean
128
-
129
- @Field({ description: 'Whether this viewer is a participant of the session (non-participants get no unread state).' })
130
- participant!: boolean
131
-
132
- /* 삭제는 되돌릴 수 없으므로 **만든 사람**만 한다 — 클라이언트가 버튼을 보일지 판단하는 근거.
133
- * (권한 판정은 서버가 다시 한다. 이 값은 UI 힌트일 뿐이다.) */
134
- @Field({ description: 'Whether this viewer created the session — only the creator may delete it.' })
135
- mine!: boolean
136
-
137
- /* 숨김은 나에게만 적용되고 되돌릴 수 있다 — 필터를 켠 사용자가 무엇이 숨겨진 것인지 알아야 한다. */
138
- @Field({ nullable: true, description: 'Whether this viewer hid the session from their own list (only returned when showHidden is on).' })
139
- hidden?: boolean
140
-
141
- /* 목록이 공개 범위를 그리고, owner 만 그것을 바꾸는 단추를 받는다 — 판정은 setSessionVisibility 가 다시 한다. */
142
- @Field({ description: "Who may read the session: 'open' (everyone in the domain), 'group' (the owner and the people brought in) or 'private' (the owner alone)." })
143
- visibility!: string
144
-
145
- @Field({ description: 'Whether this viewer is the owner of the session - only the owner may change its visibility.' })
146
- owner!: boolean
147
-
148
- /* No activity for the archive period: out of the list until asked for or searched. A new message brings it back. */
149
- @Field({ nullable: true, description: 'Whether the session has had no activity for the archive period (config sessionArchiveDays, default 60) - left out of the list unless includeArchived or a search asks for it.' })
150
- archived?: boolean
151
-
152
- @Field({ nullable: true, description: "Why the list suggests clearing this session: 'empty' (never asked anything) or 'inactive' (no activity for 30 days). Only on sessions this viewer created." })
153
- cleanupReason?: string
154
-
155
- @Field(type => Int, { nullable: true, description: 'Whole days since the last activity, or since the start when there is none.' })
156
- idleDays?: number
157
- }
158
-
159
- @ObjectType({ description: 'A session the caller deleted that is still kept - it can be brought back until it is emptied.' })
160
- class DeletedSessionEntry {
161
- @Field(type => ID, { description: 'Session id.' })
162
- id!: string
163
-
164
- @Field({ nullable: true, description: 'Session name.' })
165
- name?: string
166
-
167
- @Field({ nullable: true, description: 'Which conversation this session is - the registered mode kind.' })
168
- kind?: string
169
-
170
- @Field({ description: 'When it was deleted.' })
171
- deletedAt!: Date
172
-
173
- @Field({ nullable: true, description: 'When the daily job empties it for good; none when emptying is turned off.' })
174
- purgesAt?: Date
175
- }
176
-
177
- @ObjectType({ description: 'How long conversations are kept - what the list says when it deletes or archives.' })
178
- class SessionKeeping {
179
- @Field(type => Int, { nullable: true, description: 'Days a deleted session can still be brought back; none when deleted sessions are never emptied.' })
180
- deletedDays?: number
181
-
182
- @Field(type => Int, { nullable: true, description: 'Days without activity after which a session is archived; none when archiving is off.' })
183
- archiveDays?: number
184
- }
185
-
186
- @ObjectType({ description: 'A file stored with a conversation - opened only through the conversation.' })
187
- export class ChatAttachmentInfo {
188
- @Field(type => ID, { description: 'Attachment id.' })
189
- id!: string
190
-
191
- @Field({ description: 'File name.' })
192
- name!: string
193
-
194
- @Field({ description: 'MIME type.' })
195
- mimetype!: string
196
-
197
- @Field(type => Int, { description: 'Size in bytes.' })
198
- size!: number
199
- }
200
-
201
- function sessionNotFound(context: any): Error {
202
- return new Error(requestTranslator(context)('ai-assistant.text.session-not-found', { defaultValue: 'this conversation is not here any more. reload the list.' }))
203
- }
204
-
205
- /** A refusal said in the reader's words - code first, the sentence from it (ADR-0054). */
206
- function attachmentRefusalMessage(refusal: AttachmentRefusal, context: any): string {
207
- const t = (key: string, options: any) => (context.t ? context.t(key, options) : String(options?.defaultValue ?? key))
208
- switch (refusal.code) {
209
- case 'attachments-not-accepted':
210
- return t('ai-assistant.text.attachments-not-accepted', { defaultValue: 'this conversation does not take attachments.' })
211
- case 'attachment-kind-not-accepted':
212
- return t('ai-assistant.text.attachment-kind-not-accepted', {
213
- name: refusal.name,
214
- kinds: attachmentKindWords(refusal.kinds, t),
215
- defaultValue: '{name} cannot be attached here - this conversation takes {kinds}.'
216
- })
217
- case 'attachment-too-large':
218
- return t('ai-assistant.text.attachment-too-large', {
219
- name: refusal.name,
220
- max: Math.round(refusal.maxBytes / 1024 / 1024),
221
- defaultValue: '{name} is larger than {max} MB.'
222
- })
223
- case 'too-many-attachments':
224
- return t('ai-assistant.text.too-many-attachments', { max: refusal.maxFiles, defaultValue: 'at most {max} files can be sent at once.' })
225
- }
226
- }
227
-
228
-
229
- /**
230
- * A conversation about someone seats them as it is made - they read whatever is asked of their records (ADR-0200).
231
- * Their seat is a member's, given by the one who started it, as an invite gives it.
232
- */
233
- async function seatPersonOf(session: any, starter: any, tx: any): Promise<void> {
234
- const seat = personSeatOf(session.anchorType, session.anchorId, starter)
235
- if (!seat) return
236
- await getRepository(ChatSessionParticipant, tx).save({
237
- domain: session.domain,
238
- session: { id: session.id } as any,
239
- user: { id: seat.userId } as any,
240
- role: 'member',
241
- creator: starter,
242
- updater: starter
243
- } as any)
244
- }
245
-
246
- /** A conversation about someone stays a group they sit in - said in the asker's words when a change would undo that. */
247
- function refusePersonRoom(session: any, change: { visibility?: string; removing?: string }, context: ResolverContext): void {
248
- const refusal = session && personRoomRefusal({ ...session, creatorId: session.creatorId }, change)
249
- if (refusal) throw new Error(requestTranslator(context)(`ai-assistant.text.${refusal}`, { defaultValue: PERSON_ROOM_REFUSALS[refusal] }))
250
- }
251
- @Resolver()
252
- export class ChatSessionResolver {
253
- @Query(() => ChatSession, { nullable: true, description: 'Get AI chat session by id.' })
254
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
255
- async chatSession(
256
- @Arg('id') id: string,
257
- @Ctx() context: ResolverContext
258
- ): Promise<ChatSession | null> {
259
- const { domain, user } = context.state
260
- const session = await getRepository(ChatSession).findOneBy({ id, domain: { id: domain.id } })
261
- if (!session) return null
262
- /*
263
- * The row carries the name, the last preview and the summary of older messages - the conversation in
264
- * short. A room the caller cannot enter answers as a missing one (ADR-0073: every reading path passes the gate).
265
- */
266
- if (!isOpenRoom((session as any).visibility) && !mayReadSession((session as any).visibility, await isSessionParticipant(domain.id, id, user?.id))) return null
267
- return session
268
- }
269
-
270
- @Query(() => [ChatSession], {
271
- description:
272
- 'List AI chat sessions anchored to a target (oldest first). Anchor decides the nature and the history boundary of the conversation: board = authoring, space = the site and the twins running there. Board anchor also matches legacy rows that only have boardId.'
273
- })
274
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
275
- async chatSessionsByAnchor(
276
- @Arg('anchorType') anchorType: string,
277
- @Arg('anchorId') anchorId: string,
278
- @Ctx() context: ResolverContext
279
- ): Promise<ChatSession[]> {
280
- const { domain } = context.state
281
- return await getRepository(ChatSession).find({
282
- where: anchorWhere(domain.id, anchorType, anchorId),
283
- order: { createdAt: 'ASC' }
284
- })
285
- }
286
-
287
- /**
288
- * 받은편지함 — 앵커의 세션 목록 + 내 안 읽음 상태. 최근 활동순.
289
- * 집계 쿼리를 쓰지 않는다: 세션의 비정규화된 lastMessageAt 과 내 참여자 lastReadAt 을 **값 비교**한다
290
- * (5개 DB 드라이버 지원 때문에 group by/MAX 를 목록 경로에 두지 않는다).
291
- */
292
- @Query(() => [ChatSessionInboxEntry], {
293
- description:
294
- "List sessions anchored to a target with this viewer's unread state, most recent activity first. Supports free-text search over name and last preview, a mine-only filter, hidden inclusion, and paging. Uses the denormalized last-activity timestamp compared against the viewer's read point — no per-session aggregation."
295
- })
296
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
297
- async chatSessionInbox(
298
- @Arg('anchorType') anchorType: string,
299
- @Arg('anchorId') anchorId: string,
300
- @Ctx() context: ResolverContext,
301
- /* 숨긴 대화 보기 — 숨김이 한 번 넣으면 못 꺼내는 함정이 되지 않도록 필터를 준다. */
302
- @Arg('showHidden', { nullable: true }) showHidden?: boolean,
303
- /* 대량 목록 대응 — 검색·소유 필터·페이지. 목록 UI 는 처음부터 이걸 갖고 있어야 한다. */
304
- @Arg('search', { nullable: true }) search?: string,
305
- @Arg('mineOnly', { nullable: true }) mineOnly?: boolean,
306
- @Arg('limit', () => Int, { nullable: true }) limit?: number,
307
- @Arg('offset', () => Int, { nullable: true }) offset?: number,
308
- /* The manager's filters (shared dock §2-6) - the total takes the same, or "show more" miscounts. */
309
- @Arg('kind', { nullable: true, description: 'Only this conversation kind (mode).' }) kind?: string,
310
- @Arg('participantOnly', { nullable: true, description: 'Only conversations the caller is in.' }) participantOnly?: boolean,
311
- @Arg('visibility', { nullable: true, description: "Only 'open' or only 'private'." }) visibility?: string,
312
- @Arg('unreadOnly', { nullable: true, description: 'Only conversations with unread activity.' }) unreadOnly?: boolean,
313
- @Arg('includeArchived', { nullable: true, description: 'Also the archived ones - no activity for the archive period.' }) includeArchived?: boolean,
314
- @Arg('cleanupOnly', { nullable: true, description: "Only the caller's own the list suggests clearing (empty, or inactive for 30 days), hidden and archived ones included." }) cleanupOnly?: boolean
315
- ): Promise<ChatSessionInboxEntry[]> {
316
- const filtered = await this._inboxFiltered(anchorType, anchorId, context, {
317
- showHidden, search, mineOnly, kind, participantOnly, visibility, unreadOnly, includeArchived, cleanupOnly
318
- })
319
- const from = Math.max(0, offset ?? 0)
320
- const size = Math.min(Math.max(1, limit ?? 50), 200)
321
- return filtered.slice(from, from + size) as any
322
- }
323
-
324
- /**
325
- * 필터를 통과한 **전체 개수** — "더 보기" 가 남았는지, 검색 결과가 몇 건인지.
326
- *
327
- * 목록과 같은 요청에 담아 가져가므로 왕복은 늘지 않는다. 개수를 모르면 사용자는 목록의 끝이
328
- * 페이지의 끝인지 자료의 끝인지 구별할 수 없다.
329
- */
330
- @Query(() => Int, {
331
- description:
332
- 'Total number of sessions matching the same filters as chatSessionInbox (before paging). Request it alongside the list so the UI can tell "end of page" from "end of data".'
333
- })
334
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
335
- async chatSessionInboxTotal(
336
- @Arg('anchorType') anchorType: string,
337
- @Arg('anchorId') anchorId: string,
338
- @Ctx() context: ResolverContext,
339
- @Arg('showHidden', { nullable: true }) showHidden?: boolean,
340
- @Arg('search', { nullable: true }) search?: string,
341
- @Arg('mineOnly', { nullable: true }) mineOnly?: boolean,
342
- @Arg('kind', { nullable: true, description: 'Only this conversation kind (mode).' }) kind?: string,
343
- @Arg('participantOnly', { nullable: true, description: 'Only conversations the caller is in.' }) participantOnly?: boolean,
344
- @Arg('visibility', { nullable: true, description: "Only 'open' or only 'private'." }) visibility?: string,
345
- @Arg('unreadOnly', { nullable: true, description: 'Only conversations with unread activity.' }) unreadOnly?: boolean,
346
- @Arg('includeArchived', { nullable: true, description: 'Also the archived ones - no activity for the archive period.' }) includeArchived?: boolean,
347
- @Arg('cleanupOnly', { nullable: true, description: "Only the caller's own the list suggests clearing." }) cleanupOnly?: boolean
348
- ): Promise<number> {
349
- return (
350
- await this._inboxFiltered(anchorType, anchorId, context, {
351
- showHidden, search, mineOnly, kind, participantOnly, visibility, unreadOnly, includeArchived, cleanupOnly
352
- })
353
- ).length
354
- }
355
-
356
- /** 필터 적용(페이지 전) — 목록·개수가 **같은 규칙**을 쓰도록 한 곳에 둔다(어긋나면 "더 보기" 가 거짓말이 된다). */
357
- private async _inboxFiltered(
358
- anchorType: string,
359
- anchorId: string,
360
- context: ResolverContext,
361
- opts: { showHidden?: boolean; search?: string; includeArchived?: boolean; cleanupOnly?: boolean } & InboxFilter
362
- ): Promise<ChatSessionInboxEntry[]> {
363
- const all = await this._inboxEntries(anchorType, anchorId, context)
364
- let entries = listedEntries(all, opts)
365
- entries = filterInbox(entries as any, opts) as any
366
- if (!opts.search?.trim() || !entries.length) return entries
367
- // Search only readable rooms, then pass their messages through the SAME reader gate.
368
- // A match in a redacted answer must not reveal even that a conversation contains it.
369
- const messages = await getRepository(ChatMessage).find({
370
- where: { session: { id: In(entries.map(entry => entry.id)) } },
371
- order: { createdAt: 'DESC', id: 'DESC' },
372
- take: 2001
373
- })
374
- if (messages.length > 2000) {
375
- throw new Error(context.t('ai-assistant.session.search-too-broad', { defaultValue: 'Too many messages to search here. Narrow the conversation filters and try again.' }))
376
- }
377
- const readable = await readerGate(context)(messages)
378
- const matched = searchReadableMessages(readable, opts.search)
379
- const names = new Set(searchInbox(entries as any, opts.search).map(entry => entry.id))
380
- return entries.filter(entry => names.has(entry.id) || matched.has(entry.id))
381
- }
382
-
383
- /**
384
- * 내가 숨긴 대화 수 — 필터에 "몇 개가 접혀 있는지" 를 보여주기 위한 값.
385
- *
386
- * 숨긴 것이 몇 개인지 모르면 필터를 눌러 볼 이유가 생기지 않는다(숨긴 사실 자체를 잊는다).
387
- * 목록 조회와 **같은 요청**에 담아 가져갈 수 있으므로 왕복은 늘지 않는다.
388
- */
389
- @Query(() => Int, {
390
- description:
391
- "Number of sessions on this anchor that the caller has hidden and that have had no activity since. Meant to be requested alongside chatSessionInbox in the same operation so the filter can say how many are folded away."
392
- })
393
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
394
- async hiddenSessionCount(
395
- @Arg('anchorType') anchorType: string,
396
- @Arg('anchorId') anchorId: string,
397
- @Ctx() context: ResolverContext
398
- ): Promise<number> {
399
- const all = await this._inboxEntries(anchorType, anchorId, context)
400
- return all.filter(e => e.hidden).length
401
- }
402
-
403
- /* Like the hidden count: an archived conversation must not be forgotten, so the list says how many wait there. */
404
- @Query(() => Int, { description: 'Number of sessions on this anchor that are archived (no activity for the archive period) and not hidden by the caller.' })
405
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
406
- async archivedSessionCount(@Arg('anchorType') anchorType: string, @Arg('anchorId') anchorId: string, @Ctx() context: ResolverContext): Promise<number> {
407
- return (await this._inboxEntries(anchorType, anchorId, context)).filter(e => e.archived && !e.hidden).length
408
- }
409
-
410
- @Query(() => Int, { description: "Number of the caller's own sessions on this anchor the list suggests clearing - empty, or inactive for 30 days." })
411
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
412
- async cleanupSessionCount(@Arg('anchorType') anchorType: string, @Arg('anchorId') anchorId: string, @Ctx() context: ResolverContext): Promise<number> {
413
- return (await this._inboxEntries(anchorType, anchorId, context)).filter(e => e.cleanupReason).length
414
- }
415
-
416
- @Query(() => SessionKeeping, { description: 'How long deleted sessions can be brought back and after how long an idle one is archived.' })
417
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
418
- aiSessionKeeping(): SessionKeeping {
419
- const { deletedDays, archiveDays } = keeping()
420
- return { deletedDays: deletedDays ?? undefined, archiveDays: archiveDays ?? undefined }
421
- }
422
-
423
- /** What I deleted here and can still bring back - newest first. Only the creator deletes, so only the creator sees them. */
424
- @Query(() => [DeletedSessionEntry], { description: 'Sessions on this anchor that the caller deleted and that are still kept, newest deletion first. They can be brought back with restoreAISession until they are emptied.' })
425
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
426
- async deletedAISessions(@Arg('anchorType') anchorType: string, @Arg('anchorId') anchorId: string, @Ctx() context: ResolverContext): Promise<DeletedSessionEntry[]> {
427
- const { domain, user } = context.state
428
- if (!user?.id) return []
429
- const { deletedDays } = keeping()
430
- const rows = await getRepository(ChatSession).find({
431
- where: { ...anchorWhere(domain.id, anchorType, anchorId), creator: { id: user.id }, deletedAt: Not(IsNull()) } as any,
432
- withDeleted: true,
433
- order: { deletedAt: 'DESC' } as any,
434
- take: INBOX_SCAN_CAP
435
- })
436
- return rows.map(row => ({
437
- id: row.id!,
438
- name: (row as any).name ?? undefined,
439
- kind: (row as any).kind ?? undefined,
440
- deletedAt: (row as any).deletedAt,
441
- purgesAt: deletedDays === null ? undefined : new Date(new Date((row as any).deletedAt).getTime() + deletedDays * DAY_MS)
442
- }))
443
- }
444
-
445
- /** Bringing a deleted conversation back - its creator, while it is kept. Its messages and seats were never touched. */
446
- @Mutation(() => Boolean, { description: 'Bring back a session the caller deleted, while it is still kept (before the daily job empties it). Creator only, like deleting.' })
447
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
448
- async restoreAISession(@Arg('sessionId') sessionId: string, @Ctx() context: ResolverContext): Promise<boolean> {
449
- const { domain, user } = context.state
450
- const repo = getRepository(ChatSession)
451
- const session = await repo.findOne({ where: { id: sessionId, domain: { id: domain.id } } as any, withDeleted: true })
452
- if (!session || !(session as any).deletedAt) return false
453
- if (!user?.id || (session as any).creatorId !== user.id) {
454
- throw new Error(requestTranslator(context)('ai-assistant.text.restore-creator-only', { defaultValue: 'only the person who started this conversation can bring it back.' }))
455
- }
456
- await repo.restore(sessionId)
457
- publishSessionActivity({
458
- domainId: domain.id,
459
- sessionId,
460
- kind: 'meta',
461
- anchorType: (session as any).anchorType,
462
- anchorId: (session as any).anchorId,
463
- actorId: user.id
464
- })
465
- return true
466
- }
467
-
468
- /** 목록 조립 — 숨김 표시까지 붙인 **전체**. 목록·개수 두 진입점이 같은 규칙을 쓰도록 한 곳에 둔다. */
469
- private _inboxEntries(anchorType: string, anchorId: string, context: ResolverContext): Promise<ChatSessionInboxEntry[]> {
470
- const reads = inboxReads.get(context) ?? new Map<string, Promise<any[]>>()
471
- inboxReads.set(context, reads)
472
- const key = `${anchorType}\u0000${anchorId}`
473
- if (!reads.has(key)) reads.set(key, this._readInbox(anchorType, anchorId, context))
474
- return reads.get(key)!
475
- }
476
-
477
- private async _readInbox(
478
- anchorType: string,
479
- anchorId: string,
480
- context: ResolverContext
481
- ): Promise<ChatSessionInboxEntry[]> {
482
- const { domain, user } = context.state
483
- /* 조회 상한 — 한 앵커의 대화가 아무리 늘어도 한 번에 이만큼만 훑는다. 최근 활동순으로 자른다
484
- * (오래된 대화가 잘리는 것이 최근 대화가 잘리는 것보다 낫다). 정렬·검색·페이지는 순수 로직이 한다. */
485
- const sessions = await getRepository(ChatSession).find({
486
- where: anchorWhere(domain.id, anchorType, anchorId),
487
- order: { lastMessageAt: 'DESC' },
488
- take: INBOX_SCAN_CAP
489
- })
490
- if (sessions.length === 0) return []
491
- const rows = await getRepository(ChatSessionParticipant).find({
492
- where: { domain: { id: domain.id } as any, user: { id: user.id } as any, session: { id: In(sessions.map(s => s.id!)) } as any }
493
- })
494
- /* 'viewer' 는 대화에 낀 사람이 아니다 — 숨김을 기록하려고 만든 행이므로 읽음·안 읽음 판정에서 뺀다.
495
- * (참여자가 아닌 사람에게 남의 협의 배지를 띄우지 않는다.) */
496
- const participations = rows.filter(r => r.role !== 'viewer')
497
- const hiddenAt = new Map(rows.map(r => [(r as any).sessionId as string, r.hiddenAt]))
498
- /* 내가 만든 대화인지 표시 — 삭제 버튼을 보일지 결정하는 UI 힌트(권한은 서버가 다시 판정한다). */
499
- const createdByMe = new Set(sessions.filter(s => (s as any).creatorId === user?.id).map(s => s.id))
500
- const now = new Date()
501
- const { archiveDays } = keeping()
502
- const entries = buildInbox(sessions as any, participations as any).map(entry => {
503
- const mine = createdByMe.has(entry.id)
504
- return {
505
- ...entry,
506
- mine,
507
- idleDays: idleDays(entry, now),
508
- archived: isArchived(entry, now, archiveDays),
509
- cleanupReason: cleanupReason({ ...entry, mine }, now) ?? undefined
510
- }
511
- })
512
- /* showHidden=true 로 불러 **전체**를 얻는다 — 숨김 여부 판정을 두 곳에 복제하지 않기 위함. */
513
- const shown = applyHidden(entries as any, hiddenAt, true) as any[]
514
-
515
- /*
516
- * 목록도 같은 관문을 지난다 — ADR-0073 판정 1. 미리보기는 그 답을 **다시 읽는 두 번째 길**이고,
517
- * 한 길만 막으면 같은 문장이 다른 길로 그대로 나간다. 미리보기 자리를 `content` 로 바꿔 넣고
518
- * 가려진 것만 되돌려 담는다.
519
- */
520
- const gate = readerGate(context)
521
- const judged = await gate(
522
- shown.map(entry => ({ doors: entry.lastMessageDoors, content: entry.lastMessagePreview ?? '' }))
523
- )
524
- return shown.map((entry, index) => ({
525
- ...entry,
526
- lastMessagePreview: judged[index].content,
527
- previewRedacted: (judged[index] as any).redacted === true
528
- })) as any
529
- }
530
-
531
- /**
532
- * 세션 삭제 — **만든 사람만.**
533
- *
534
- * 협의는 여럿의 기록이고 삭제는 화면에서 되돌릴 수 없다. 그래서 권한을 좁힌다(이름 변경은 되돌릴 수
535
- * 있어서 누구나 할 수 있는 것과 대비). 권한이 없는 사람에게는 `hideAISession`(내 목록에서만 숨김)이
536
- * 있다 — 남의 기록을 지우지 않고 자기 목록을 정리하는 길.
537
- *
538
- * 소프트 삭제(deletedAt)다 — 메시지·패치는 세션을 통해서만 도달하므로 함께 사라지고, 잘못 지운 경우
539
- * 데이터로는 남아 있다. 다른 참여자 목록에서도 사라져야 하므로 meta 활동으로 방송한다.
540
- */
541
- @Mutation(() => Boolean, {
542
- description:
543
- 'Delete a chat session — creator only, since it disappears for every participant. Participants who are not the creator can hide it from their own list instead (hideAISession). Soft delete: the creator can bring it back with restoreAISession until the daily job empties it (sessionRetentionDays). Broadcast as meta activity so every list drops it.'
544
- })
545
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
546
- async deleteAISession(@Arg('sessionId') sessionId: string, @Ctx() context: ResolverContext): Promise<boolean> {
547
- const { domain, user } = context.state
548
- const repo = getRepository(ChatSession)
549
- const session = await repo.findOneBy({ id: sessionId, domain: { id: domain.id } as any })
550
- if (!session) return false
551
- if (!user?.id || (session as any).creatorId !== user.id) {
552
- /* 조용한 무동작이 아니라 명시 실패 — 지워진 줄 알고 넘어가면 안 된다. */
553
- throw new Error(
554
- requestTranslator(context)('ai-assistant.text.delete-creator-only', {
555
- defaultValue: 'only the person who started this conversation can delete it. hide it from your own list instead.'
556
- })
557
- )
558
- }
559
- await repo.softDelete(sessionId)
560
- publishSessionActivity({
561
- domainId: domain.id,
562
- sessionId,
563
- kind: 'meta',
564
- anchorType: (session as any).anchorType,
565
- anchorId: (session as any).anchorId,
566
- actorId: user?.id
567
- })
568
- return true
569
- }
570
-
571
- /**
572
- * 내 목록에서 숨기기·되돌리기 — **나에게만** 적용된다(대화·다른 참여자 목록은 그대로).
573
- *
574
- * 참여자가 아니어도 숨길 수 있어야 한다 — 목록에는 같은 공간의 남의 협의도 보이고, 그것을 정리하는
575
- * 것은 남에게 아무 영향이 없다. 그 경우 'viewer' 역할로 기록만 남긴다(참여자 명부·배지에는 들지 않는다).
576
- */
577
- @Mutation(() => Boolean, {
578
- description:
579
- 'Hide (or unhide) a session from the calling user\'s own list. Per-user and reversible — the session and other participants are unaffected. Activity newer than the hide makes it reappear; the inbox filter (showHidden) reveals hidden ones.'
580
- })
581
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
582
- async hideAISession(
583
- @Arg('sessionId') sessionId: string,
584
- @Ctx() context: ResolverContext,
585
- @Arg('hidden', { nullable: true }) hidden?: boolean
586
- ): Promise<boolean> {
587
- const { domain, user } = context.state
588
- if (!user?.id) return false
589
- const session = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
590
- if (!session) return false
591
- const repo = getRepository(ChatSessionParticipant)
592
- const existing = await repo.findOne({
593
- where: { domain: { id: domain.id } as any, session: { id: sessionId } as any, user: { id: user.id } as any }
594
- })
595
- const hiddenAt = hidden === false ? null : new Date()
596
- if (existing) {
597
- await repo.update(existing.id!, { hiddenAt, updater: user } as any)
598
- } else {
599
- if (hidden === false) return true // 숨긴 적이 없으면 되돌릴 것도 없다
600
- await repo.save({
601
- domain: { id: domain.id } as any,
602
- session: { id: sessionId } as any,
603
- user: { id: user.id } as any,
604
- role: 'viewer', // 대화에 낀 것이 아니라 숨김만 기록한다
605
- hiddenAt,
606
- creator: user,
607
- updater: user
608
- } as any)
609
- }
610
- return true
611
- }
612
-
613
- /**
614
- * 세션 이름 변경 — **참여자 누구나** 할 수 있다.
615
- *
616
- * 왜 소유자 전용이 아닌가: 이름은 대화의 주제표이고 협의는 여럿이 한다. 논의가 흘러 주제가 달라졌는데
617
- * 만든 사람만 고칠 수 있으면 그 사람이 없을 때 목록이 계속 어긋난다. 되돌릴 수 있는 변경이고 대화
618
- * 내용에 영향이 없으므로 권한을 좁힐 이유가 없다(되돌릴 수 없는 것만 좁힌다).
619
- *
620
- * 변경은 **meta 활동**으로 방송한다 — 모든 참여자 목록에 즉시 반영되지만 안 읽음 배지는 올리지 않는다
621
- * (이름 변경을 "새 소식" 으로 알리면 소음이다).
622
- */
623
- /**
624
- * 이 대화를 도메인 안 누구나 읽게 할 것인가 — ADR-0073 판정 2.
625
- *
626
- * owner 만 바꾼다. 이름 바꾸기는 어느 참여자나 하지만(되돌릴 수 있고 값을 드러내지 않는다), 공개로
627
- * 바꾸는 일은 이미 쓰인 글을 도메인 전체에 여는 일이다 — 되돌려도 읽힌 것은 읽힌 것이다.
628
- *
629
- * 화면은 공개로 바꾸기 전에 한 줄을 먼저 보인다(문구는 클라이언트가 가진다). 그 한 줄은 이 문이
630
- * 강제하지 않는다 — 문이 막을 수 있는 것은 누가 바꾸느냐까지다.
631
- */
632
- @Mutation(() => Boolean, {
633
- description:
634
- "Set who reads this conversation: 'open' (everyone in the domain), 'group' (the owner and the people the owner brings in) or 'private' (the owner alone - the members are sent out). Only the owner may change it. Opening exposes what is already written — the screen says so before asking. Door checks on assistant answers are unaffected (ADR-0073)."
635
- })
636
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
637
- async setSessionVisibility(
638
- @Arg('sessionId') sessionId: string,
639
- @Arg('visibility') visibility: string,
640
- @Ctx() context: ResolverContext
641
- ): Promise<boolean> {
642
- const { domain, user } = context.state
643
- if (!SESSION_VISIBILITIES.includes(visibility as any)) {
644
- throw new Error(requestTranslator(context)('ai-assistant.text.visibility-unknown', { defaultValue: 'a conversation is open, group or private.' }))
645
- }
646
-
647
- const session = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
648
- if (!session) return false
649
-
650
- const mine = await getRepository(ChatSessionParticipant).findOne({
651
- where: { domain: { id: domain.id } as any, session: { id: sessionId } as any, user: { id: user.id } as any }
652
- })
653
- if (mine?.role !== 'owner') return false
654
-
655
- if ((session as any).visibility === visibility) return true
656
- refusePersonRoom(session, { visibility }, context)
657
-
658
- /*
659
- * Private is the owner's alone (ADR-0073 decision 3). The members leave with the change - a private room
660
- * with people still seated in it would be a group under another name. Bringing them back is inviting
661
- * them again, in a group.
662
- */
663
- const sentOut = visibility === 'private' ? await sendOutMembers(domain.id, sessionId) : []
664
-
665
- await getRepository(ChatSession).update(sessionId, { visibility, updater: user } as any)
666
- publishSessionActivity({
667
- domainId: domain.id,
668
- sessionId,
669
- kind: 'meta',
670
- anchorType: (session as any).anchorType,
671
- anchorId: (session as any).anchorId,
672
- actorId: user?.id,
673
- alsoTo: sentOut
674
- })
675
- return true
676
- }
677
-
678
- /**
679
- * Bring people into this conversation - the same seat a mention gives, by the same rule (`maySeat`): anyone
680
- * in an open room, the owner in a group, nobody in a private one. Each person seated is told
681
- * (`notifyInvited`). People outside the domain are not seated.
682
- */
683
- @Mutation(() => [String], {
684
- description:
685
- "Bring people into this conversation and tell them. In a group only the owner may; a private conversation takes nobody (make it a group first). Returns the ids of the people seated now - people already in it are left out."
686
- })
687
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
688
- async inviteToAISession(
689
- @Arg('sessionId') sessionId: string,
690
- @Arg('userIds', () => [String]) userIds: string[],
691
- @Ctx() context: ResolverContext
692
- ): Promise<string[]> {
693
- const { domain, user } = context.state
694
- const session = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
695
- if (!session) throw sessionNotFound(context)
696
-
697
- /* Only people of this domain - an id from elsewhere is not a colleague here. */
698
- const wanted = [...new Set((userIds ?? []).filter(id => typeof id === 'string' && id))].slice(0, 50)
699
- if (wanted.length === 0) return []
700
- const members = await buildDomainUsersQueryBuilder(domain.id, 'USER').andWhere('USER.id IN (:...ids)', { ids: wanted }).getMany()
701
- const known = new Set(members.map(member => member.id))
702
-
703
- const seat = await seatParticipants({
704
- sessionId,
705
- domainId: domain.id,
706
- inviter: user,
707
- userIds: wanted.filter(id => known.has(id)),
708
- participants: getRepository(ChatSessionParticipant),
709
- visibility: (session as any).visibility
710
- })
711
- if (seat.notSeated?.length) {
712
- throw new Error(
713
- (session as any).visibility === 'private'
714
- ? requestTranslator(context)('ai-assistant.text.invite-private-refused', { defaultValue: 'a private conversation is yours alone. make it a group to bring people in.' })
715
- : requestTranslator(context)('ai-assistant.text.invite-owner-only', { defaultValue: 'only the person who started this group conversation can bring people in.' })
716
- )
717
- }
718
-
719
- await notifyInvited(context, seat.invited, user, (session as any).name)
720
- publishSessionActivity({
721
- domainId: domain.id,
722
- sessionId,
723
- kind: 'meta',
724
- anchorType: (session as any).anchorType,
725
- anchorId: (session as any).anchorId,
726
- actorId: user?.id
727
- })
728
- return seat.invited
729
- }
730
-
731
- /**
732
- * Send a member out - the owner only, and never the owner themself. In a group the seat was the key, so the
733
- * person no longer reads or writes here (every gate asks the seat). Their list is told once and drops it.
734
- */
735
- @Mutation(() => Boolean, {
736
- description: 'Send a member out of this conversation. Only the owner may, and the owner cannot be sent out. In a group the person no longer reads or writes here.'
737
- })
738
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
739
- async removeFromAISession(
740
- @Arg('sessionId') sessionId: string,
741
- @Arg('userId') userId: string,
742
- @Ctx() context: ResolverContext
743
- ): Promise<boolean> {
744
- const { domain, user } = context.state
745
- const repo = getRepository(ChatSessionParticipant)
746
- const seats = await repo.find({ where: { domain: { id: domain.id } as any, session: { id: sessionId } as any } as any })
747
- const mine = seats.find(seat => (seat as any).userId === user?.id)
748
- if (mine?.role !== 'owner') {
749
- throw new Error(requestTranslator(context)('ai-assistant.text.remove-owner-only', { defaultValue: 'only the person who started this conversation can send someone out.' }))
750
- }
751
- const theirs = seats.find(seat => (seat as any).userId === userId && seat.role === 'member')
752
- if (!theirs) return false
753
- refusePersonRoom(await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any }), { removing: userId }, context)
754
- return await this._leave(sessionId, theirs, context)
755
- }
756
-
757
- /**
758
- * Leave this conversation - a member steps out of their own seat. The owner does not leave: the room would be
759
- * nobody's. They delete it, or make it private.
760
- */
761
- @Mutation(() => Boolean, {
762
- description: 'Leave this conversation. A member may; the owner cannot (delete it or make it private instead). In a group, leaving ends reading and writing here.'
763
- })
764
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
765
- async leaveAISession(@Arg('sessionId') sessionId: string, @Ctx() context: ResolverContext): Promise<boolean> {
766
- const { domain, user } = context.state
767
- if (!user?.id) return false
768
- const mine = await getRepository(ChatSessionParticipant).findOne({
769
- where: { domain: { id: domain.id } as any, session: { id: sessionId } as any, user: { id: user.id } as any }
770
- })
771
- if (mine?.role === 'owner') {
772
- throw new Error(requestTranslator(context)('ai-assistant.text.owner-cannot-leave', { defaultValue: 'you started this conversation, so you cannot leave it. delete it, or make it private.' }))
773
- }
774
- if (mine?.role !== 'member') return false
775
- refusePersonRoom(await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any }), { removing: user.id }, context)
776
- return await this._leave(sessionId, mine, context)
777
- }
778
-
779
- private async _leave(sessionId: string, seat: ChatSessionParticipant, context: ResolverContext): Promise<boolean> {
780
- const { domain, user } = context.state
781
- const session = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
782
- await getRepository(ChatSessionParticipant).softDelete(seat.id!)
783
- publishSessionActivity({
784
- domainId: domain.id,
785
- sessionId,
786
- kind: 'meta',
787
- anchorType: (session as any)?.anchorType,
788
- anchorId: (session as any)?.anchorId,
789
- actorId: user?.id,
790
- alsoTo: [(seat as any).userId].filter(Boolean)
791
- })
792
- return true
793
- }
794
-
795
- /**
796
- * "I am typing" - a notice to the others in the room, stored nowhere. Only a person who may write here is
797
- * typing here (the write gate), and the listeners pass the room's read gate (`ChatTypingSubscription`).
798
- */
799
- @Mutation(() => Boolean, {
800
- description: 'Tell the others in this conversation that the caller is typing. Nothing is stored; send it every few seconds while typing. Only a person who may write here may send it.'
801
- })
802
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
803
- async sayTyping(@Arg('sessionId') sessionId: string, @Ctx() context: ResolverContext): Promise<boolean> {
804
- const { domain, user } = context.state
805
- const session = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
806
- if (!session) return false
807
- await writeGate(session, context)
808
- const notice = typingNotice({ domainId: domain.id, sessionId, user })
809
- if (!notice) return false
810
- try {
811
- pubsub.publish(CHAT_TYPING_TOPIC, notice)
812
- } catch {
813
- /* a missed notice is a line that does not show - nothing else rests on it */
814
- }
815
- return true
816
- }
817
-
818
- @Mutation(() => Boolean, {
819
- description:
820
- 'Rename a chat session. Any participant may rename it — the name is the topic label of a shared deliberation and the change is reversible. Broadcast as meta activity so every participant sees it without raising unread badges.'
821
- })
822
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
823
- async renameAISession(
824
- @Arg('sessionId') sessionId: string,
825
- @Arg('name') name: string,
826
- @Ctx() context: ResolverContext
827
- ): Promise<boolean> {
828
- const { domain, user } = context.state
829
- /* 빈 이름으로 지우지 않는다 — 지우려면 별도 의도가 필요하다. 거절은 말로 한다. */
830
- const trimmed = sessionNameOf(name, requestTranslator(context), false)
831
- const participant = await getRepository(ChatSessionParticipant).findOne({
832
- where: { domain: { id: domain.id } as any, session: { id: sessionId } as any, user: { id: user.id } as any }
833
- })
834
- if (!participant) return false // 참여자가 아니면 남의 대화 제목을 바꿀 수 없다
835
- const session = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
836
- if (!session) return false
837
- await getRepository(ChatSession).update(sessionId, { name: trimmed, updater: user } as any)
838
- publishSessionActivity({
839
- domainId: domain.id,
840
- sessionId,
841
- kind: 'meta',
842
- anchorType: (session as any).anchorType,
843
- anchorId: (session as any).anchorId,
844
- actorId: user?.id
845
- })
846
- return true
847
- }
848
-
849
- /**
850
- * 읽은 지점 갱신 — 이 세션을 여기까지 읽었다. 멱등(여러 번 호출해도 최신 시각으로만 이동).
851
- * 접속 표시(lastSeenAt)와 분리한다 — 창을 열어 두고 화면을 안 볼 수 있다.
852
- */
853
- @Mutation(() => Boolean, {
854
- description:
855
- "Mark a session as read up to now for the current user. Idempotent. Distinct from presence (lastSeenAt) — a window can be open without being read."
856
- })
857
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
858
- async markSessionRead(
859
- @Arg('sessionId') sessionId: string,
860
- @Ctx() context: ResolverContext
861
- ): Promise<boolean> {
862
- const { domain, user } = context.state
863
- const repo = getRepository(ChatSessionParticipant)
864
- const mine = await repo.findOne({
865
- where: { domain: { id: domain.id } as any, session: { id: sessionId } as any, user: { id: user.id } as any }
866
- })
867
- /* 참여자가 아니면 읽음 상태를 만들지 않는다 — 참여하지 않은 대화에 내 읽음 지점을 남기지 않는다. */
868
- if (!mine) return false
869
- await repo.update(mine.id!, { lastReadAt: new Date(), updater: user } as any)
870
- return true
871
- }
872
-
873
- @Query(() => [User], {
874
- description:
875
- 'List users in the current domain for the `@` mention popup. Anyone with the chat privilege may search here; this is separate from the admin-only users().'
876
- })
877
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
878
- async domainUsersForMention(
879
- @Arg('query', { nullable: true, description: 'Substring to match against name/email (case-insensitive). Empty → all.' }) query: string | undefined,
880
- @Arg('limit', () => Int, { nullable: true, defaultValue: 50 }) limit: number,
881
- @Ctx() context: ResolverContext
882
- ): Promise<User[]> {
883
- const { domain } = context.state
884
- const qb = buildDomainUsersQueryBuilder(domain.id, 'USER')
885
- if (query?.trim()) {
886
- const q = `%${query.trim().toLowerCase()}%`
887
- qb.andWhere('(LOWER(USER.name) LIKE :q OR LOWER(USER.email) LIKE :q)', { q })
888
- }
889
- qb.orderBy('USER.name', 'ASC').limit(limit)
890
- return await qb.getMany()
891
- }
892
-
893
- @Query(() => [ChatSessionParticipant], {
894
- description: 'List participants of a ChatSession (members / owner).'
895
- })
896
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
897
- async chatSessionParticipants(
898
- @Arg('sessionId') sessionId: string,
899
- @Ctx() context: ResolverContext
900
- ): Promise<ChatSessionParticipant[]> {
901
- const { domain, user } = context.state
902
- const session = await getRepository(ChatSession).findOneBy({
903
- id: sessionId,
904
- domain: { id: domain.id }
905
- })
906
- if (!session) return []
907
- return readRoster({id:sessionId,domainId:domain.id,visibility:(session as any).visibility}, {
908
- isParticipant: () => isSessionParticipant(domain.id,sessionId,user?.id),
909
- find: options => getRepository(ChatSessionParticipant).find(options)
910
- })
911
- }
912
-
913
- /**
914
- * May the caller seat someone here - the server's answer to the screen, so the screen keeps no copy of the
915
- * rule (`maySeat`). The invite button and the line under a mention read it; the doors decide again.
916
- */
917
- @Query(() => Boolean, {
918
- description: "Whether the caller may bring people into this conversation now - anyone in an open one, the owner of a group, nobody in a private one. A hint for the screen; the invite and the mention decide again."
919
- })
920
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
921
- async mayInviteToAISession(@Arg('sessionId') sessionId: string, @Ctx() context: ResolverContext): Promise<boolean> {
922
- const { domain, user } = context.state
923
- const session = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
924
- if (!session || !user?.id) return false
925
- const seat = await getRepository(ChatSessionParticipant).findOne({
926
- where: { domain: { id: domain.id } as any, session: { id: sessionId } as any, user: { id: user.id } as any }
927
- })
928
- return maySeat((session as any).visibility, seat?.role)
929
- }
930
-
931
- /**
932
- * The person this conversation is about, who always reads it (ADR-0200) - the screen offers no way to send them out,
933
- * and keeps no copy of the rule. The doors refuse again.
934
- */
935
- @Query(() => String, {
936
- nullable: true,
937
- description: 'The user this conversation is about, who cannot be sent out of it - none for any other conversation. A hint for the screen; the doors decide again.'
938
- })
939
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
940
- async keptInAISession(@Arg('sessionId') sessionId: string, @Ctx() context: ResolverContext): Promise<string | null> {
941
- const { domain } = context.state
942
- const session: any = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
943
- const personId = session && personOfAnchor(session.anchorType, session.anchorId)
944
- return personId && personRoomRefusal(session, { removing: personId }) ? personId : null
945
- }
946
-
947
- @Mutation(() => Boolean, {
948
- description: 'Presence heartbeat — bump current user\'s lastSeenAt in the session (online indicator).'
949
- })
950
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
951
- async touchPresence(@Arg('sessionId') sessionId: string, @Ctx() context: ResolverContext): Promise<boolean> {
952
- const { domain, user } = context.state
953
- const repo = getRepository(ChatSessionParticipant)
954
- const part = await repo.findOne({
955
- where: { session: { id: sessionId } as any, user: { id: user.id } as any, domain: { id: domain.id } as any }
956
- })
957
- if (!part) return false // 참여자가 아니면 heartbeat 무시 (초대 전)
958
- await repo.update(part.id!, { lastSeenAt: new Date(), updater: user } as any)
959
- return true
960
- }
961
-
962
- @Query(() => [ChatMessage], { description: 'List chat messages of a session, oldest first.' })
963
- @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
964
- async chatMessages(
965
- @Arg('sessionId') sessionId: string,
966
- @Arg('limit', () => Int, { nullable: true, defaultValue: 100 }) limit: number,
967
- @Arg('offset', () => Int, { nullable: true, defaultValue: 0 }) offset: number,
968
- @Ctx() context: ResolverContext
969
- ): Promise<ChatMessage[]> {
970
- const { domain, user } = context.state
971
- const session = await getRepository(ChatSession).findOneBy({
972
- id: sessionId,
973
- domain: { id: domain.id }
974
- })
975
- if (!session) return []
976
-
977
- /*
978
- * 공개 대화는 도메인 안이면 누구나 읽는다 — 초대 절차가 없다(ADR-0073 판정 2). 비공개 대화는
979
- * 참여자만. 여기서 막히는 것은 **방**이고, 방에 들어온 뒤 값을 읽는 일은 아래 문 판정이 따로 본다.
980
- */
981
- if (!isOpenRoom((session as any).visibility)) {
982
- /* A hide-only `viewer` row is not being in the room - it must not open a private conversation. */
983
- const part = await isSessionParticipant(domain.id, sessionId, user?.id)
984
- if (!mayReadSession((session as any).visibility, part)) return []
985
- }
986
-
987
- const rows = await getRepository(ChatMessage).find({
988
- where: { session: { id: sessionId } as any },
989
- // creator: 그룹챗 발신자 표시(name) + 자기 여부 판정(email). 내부 관리키(id)에 의존하지 않는다.
990
- relations: { creator: true },
991
- order: { createdAt: 'ASC' },
992
- take: limit,
993
- skip: offset
994
- })
995
-
996
- /*
997
- * 어시스턴트의 답은 도구 결과를 평문으로 옮겨 적은 것이다. 읽는 사람이 그 도구가 지난 문을 못 지나면
998
- * 본문 대신 한 줄이 나간다 — 행이 있다는 사실은 보이고 값만 안 보인다(ADR-0073 판정 1).
999
- */
1000
- return await readerGate(context)(rows)
1001
- }
1002
-
1003
- @Directive('@transaction')
1004
- @Mutation(() => ChatSession, {
1005
- description:
1006
- 'Start (or get existing) AI chat session anchored to a target. Idempotent — returns first existing or creates one. Use anchorType board for board authoring, space for a site (its co-located twins).'
1007
- })
1008
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
1009
- async startAISession(
1010
- @Arg('anchorType') anchorType: string,
1011
- @Arg('anchorId') anchorId: string,
1012
- @Ctx() context: ResolverContext
1013
- ): Promise<ChatSession> {
1014
- const { domain, user, tx } = context.state
1015
- const repo = getRepository(ChatSession, tx)
1016
-
1017
- const existing = await repo.findOneBy(anchorWhere(domain.id, anchorType, anchorId))
1018
- if (existing) return existing
1019
-
1020
- const session = await repo.save({
1021
- domain,
1022
- ...anchorColumns(anchorType, anchorId),
1023
- /* 새 대화는 비공개로 태어난다 — 공개는 owner 가 고른다(ADR-0073 결정 2, 2026-09-30 고침). */
1024
- visibility: personSeatOf(anchorType, anchorId, user)?.visibility ?? initialVisibility({ anchorType }),
1025
- creator: user,
1026
- updater: user
1027
- } as any)
1028
- // creator 를 owner participant 로 자동 등록 — 다자간 채팅 기반.
1029
- await getRepository(ChatSessionParticipant, tx).save({
1030
- domain,
1031
- session: { id: session.id } as any,
1032
- user,
1033
- role: 'owner',
1034
- creator: user,
1035
- updater: user
1036
- } as any)
1037
- await seatPersonOf(session, user, tx)
1038
- return session
1039
- }
1040
-
1041
- @Directive('@transaction')
1042
- @Mutation(() => ChatSession, {
1043
- description:
1044
- 'Always create a new AI chat session anchored to a target (no idempotent reuse). For multi-session UX — opening another tab.'
1045
- })
1046
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
1047
- async createAISession(
1048
- @Arg('anchorType') anchorType: string,
1049
- @Arg('anchorId') anchorId: string,
1050
- @Arg('name', { nullable: true, description: 'Optional name. If omitted, the first question names the conversation.' }) name: string | undefined,
1051
- @Ctx() context: ResolverContext
1052
- ): Promise<ChatSession> {
1053
- const { domain, user, tx } = context.state
1054
- const repo = getRepository(ChatSession, tx)
1055
-
1056
- // Do not prefill a numbered name: that prevents the first question from naming it.
1057
- const finalName = name?.trim() || null
1058
-
1059
- const session = await repo.save({
1060
- domain,
1061
- ...anchorColumns(anchorType, anchorId),
1062
- visibility: personSeatOf(anchorType, anchorId, user)?.visibility ?? initialVisibility({ anchorType }),
1063
- creator: user,
1064
- updater: user,
1065
- name: finalName
1066
- } as any)
1067
- // creator 를 owner participant 로 자동 등록.
1068
- await getRepository(ChatSessionParticipant, tx).save({
1069
- domain,
1070
- session: { id: session.id } as any,
1071
- user,
1072
- role: 'owner',
1073
- creator: user,
1074
- updater: user
1075
- } as any)
1076
- await seatPersonOf(session, user, tx)
1077
- return session
1078
- }
1079
-
1080
- @Directive('@transaction')
1081
- @Mutation(() => Boolean, {
1082
- description: 'Rename a ChatSession (tab label).'
1083
- })
1084
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
1085
- async renameChatSession(
1086
- @Arg('sessionId') sessionId: string,
1087
- @Arg('name') name: string,
1088
- @Ctx() context: ResolverContext
1089
- ): Promise<boolean> {
1090
- const { domain, user, tx } = context.state
1091
- const repo = getRepository(ChatSession, tx)
1092
- const session = await repo.findOneBy({ id: sessionId, domain: { id: domain.id } })
1093
- if (!session) throw sessionNotFound(context)
1094
- /* The board-era rename door had no gate at all - a private conversation's name was anyone's to change. */
1095
- await writeGate(session, context, tx)
1096
- await repo.update(sessionId, { name: sessionNameOf(name, requestTranslator(context), true) || null, updater: user } as any)
1097
- return true
1098
- }
1099
-
1100
- @Directive('@transaction')
1101
- @Mutation(() => Boolean, {
1102
- description:
1103
- "What the host did with a proposal the assistant made. The host calls this once per card it was asked to run; the server records it as a system row, so the panel shows it, a refreshed panel still shows it, and the model reads on its next turn that its proposal was refused instead of assuming it landed (ADR-0070)."
1104
- })
1105
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
1106
- async reportProposalOutcome(
1107
- @Arg('sessionId') sessionId: string,
1108
- @Arg('proposalKey') proposalKey: string,
1109
- @Arg('outcome', () => GraphQLJSON) outcome: ProposalOutcome,
1110
- @Ctx() context: ResolverContext
1111
- ): Promise<boolean> {
1112
- const { domain, user, tx } = context.state
1113
- const session = await getRepository(ChatSession, tx).findOneBy({ id: sessionId, domain: { id: domain.id } })
1114
- if (!session) throw sessionNotFound(context)
1115
- await writeGate(session, context, tx)
1116
-
1117
- const key = (proposalKey ?? '').trim()
1118
- if (!key) return false
1119
-
1120
- /*
1121
- * 낱말은 ADR-0042 의 것에 `declined` 하나다. 모르는 낱말을 받으면 그대로 적지 않는다 — 카드가
1122
- * 읽지 못하는 상태가 되고, 그때 화면은 아무 말도 못 한다.
1123
- */
1124
- if (!PROPOSAL_VERDICTS.includes(outcome?.verdict as any)) {
1125
- throw new Error(
1126
- `[ai-assistant] '${outcome?.verdict}' is not a proposal verdict. Use one of ${PROPOSAL_VERDICTS.join(', ')}.`
1127
- )
1128
- }
1129
-
1130
- const body = formatProposalOutcomeLine(key, outcome)
1131
-
1132
- const previousLast = await getRepository(ChatMessage, tx).findOne({
1133
- where: { session: { id: session.id } as any },
1134
- order: { createdAt: 'DESC' }
1135
- })
1136
- const sysMsg = await getRepository(ChatMessage, tx).save({
1137
- session: { id: session.id } as any,
1138
- role: 'system',
1139
- content: body,
1140
- creator: user,
1141
- updater: user,
1142
- parentMessage: previousLast ? ({ id: previousLast.id } as any) : undefined
1143
- } as any)
1144
-
1145
- /* 목록의 미리보기는 사람의 말로 두는 편이 낫다 — 이 줄은 기계의 기록이다. 방송만 한다. */
1146
- publishChatMessage({ domainId: domain.id, sessionId: session.id, message: sysMsg })
1147
- return true
1148
- }
1149
-
1150
- @Directive('@transaction')
1151
- @Mutation(() => Boolean, {
1152
- description:
1153
- "Ask before running a proposal: true when this conversation has not taken it yet, and the request is recorded as a system row; false when it was already requested or answered - then the host must not be asked again. The card reads its state from these rows, so a refreshed panel or another window does not offer the same proposal twice (ADR-0097)."
1154
- })
1155
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
1156
- async requestProposal(
1157
- @Arg('sessionId') sessionId: string,
1158
- @Arg('proposalKey') proposalKey: string,
1159
- @Ctx() context: ResolverContext
1160
- ): Promise<boolean> {
1161
- const { domain, user, tx } = context.state
1162
- const session = await getRepository(ChatSession, tx).findOneBy({ id: sessionId, domain: { id: domain.id } })
1163
- if (!session) throw sessionNotFound(context)
1164
- await writeGate(session, context, tx)
1165
-
1166
- const key = (proposalKey ?? '').trim()
1167
- if (!key) return false
1168
-
1169
- /* Only this conversation's proposal lines - a conversation is bounded, and the rule reads them all. */
1170
- const lines = await getRepository(ChatMessage, tx).find({
1171
- select: ['content'] as any,
1172
- where: { session: { id: session.id } as any, role: 'system', content: Like(`${PROPOSAL_OUTCOME_PREFIX}%`) } as any
1173
- })
1174
- if (proposalAlreadyTaken(key, lines.map(line => (line as any).content))) return false
1175
-
1176
- const previousLast = await getRepository(ChatMessage, tx).findOne({
1177
- where: { session: { id: session.id } as any },
1178
- order: { createdAt: 'DESC' }
1179
- })
1180
- const row = await getRepository(ChatMessage, tx).save({
1181
- session: { id: session.id } as any,
1182
- role: 'system',
1183
- content: formatProposalRequestedLine(key),
1184
- creator: user,
1185
- updater: user,
1186
- parentMessage: previousLast ? ({ id: previousLast.id } as any) : undefined
1187
- } as any)
1188
-
1189
- publishChatMessage({ domainId: domain.id, sessionId: session.id, message: row })
1190
- return true
1191
- }
1192
-
1193
- /**
1194
- * Stores files with a conversation before the turn that carries them (design/ai/shared-dock.md §9).
1195
- * Passes the write gate - a private conversation takes files from its people only - and the mode's
1196
- * attachment policy. The size is known only once stored, so a file over the limit is removed and refused.
1197
- */
1198
- @Directive('@transaction')
1199
- @Mutation(() => [ChatAttachmentInfo], {
1200
- description:
1201
- "Store files with a conversation, to be sent with the next turn (assistantChat attachmentIds). Private conversations take files from their participants only; what is accepted is the conversation mode's attachment policy."
1202
- })
1203
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
1204
- async attachToConversation(
1205
- @Arg('sessionId') sessionId: string,
1206
- @Arg('files', () => [GraphQLUpload]) files: FileUpload[],
1207
- @Ctx() context: ResolverContext,
1208
- @Arg('kind', { nullable: true, description: 'The conversation kind, for a session not stamped with one yet.' }) kind?: string
1209
- ): Promise<ChatAttachmentInfo[]> {
1210
- const { domain, tx } = context.state
1211
- const session = await getRepository(ChatSession, tx).findOneBy({ id: sessionId, domain: { id: domain.id } })
1212
- if (!session) throw sessionNotFound(context)
1213
- await writeGate(session, context, tx)
1214
-
1215
- const policy = getAssistantMode((session as any).kind || kind || '')?.attachments
1216
- const uploads = await Promise.all(files)
1217
- const before = refuseAttachments(policy, uploads.map(upload => ({ name: upload.filename, type: upload.mimetype })))
1218
- if (before) throw new Error(attachmentRefusalMessage(before, context))
1219
-
1220
- const saved = await saveChatAttachments(session.id!, uploads, context)
1221
- const after = refuseAttachments(policy, saved.map(file => ({ name: file.name, type: file.mimetype, size: file.size })))
1222
- if (after) {
1223
- await removeAttachmentRows(saved.map(file => file.id))
1224
- throw new Error(attachmentRefusalMessage(after, context))
1225
- }
1226
- return saved
1227
- }
1228
-
1229
- @Directive('@transaction')
1230
- @Mutation(() => String, {
1231
- nullable: true,
1232
- description:
1233
- "Say something to the people in this session. The turn is stored as the speaker's, addressed to the room, and the assistant is not called — it reads the line as context the next time someone asks it something. Returns the stored message id, or null when there was nothing to say (ADR-0070)."
1234
- })
1235
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
1236
- async sayToRoom(
1237
- @Arg('sessionId') sessionId: string,
1238
- @Arg('content') content: string,
1239
- @Arg('replyToId', { nullable: true }) replyToId: string | undefined,
1240
- @Ctx() context: ResolverContext
1241
- ): Promise<string | null> {
1242
- const { domain, user, tx } = context.state
1243
- const session = await getRepository(ChatSession, tx).findOneBy({ id: sessionId, domain: { id: domain.id } })
1244
- if (!session) throw sessionNotFound(context)
1245
- await writeGate(session, context, tx)
1246
-
1247
- const body = roomMessageBody(content)
1248
- if (!body) return null
1249
-
1250
- const messages = getRepository(ChatMessage, tx)
1251
- const previousLast = replyToId
1252
- ? await messages.findOneBy({ id: replyToId, session: { id: session.id } as any })
1253
- : await messages.findOne({ where: { session: { id: session.id } as any }, order: { createdAt: 'DESC' } })
1254
- if (replyToId && !previousLast) {
1255
- throw new Error(requestTranslator(context)('ai-assistant.text.reply-target-missing', { defaultValue: 'the message you are replying to is not in this conversation.' }))
1256
- }
1257
- const saved = await getRepository(ChatMessage, tx).save({
1258
- session: { id: session.id } as any,
1259
- role: 'user',
1260
- content: body,
1261
- /* 대상은 문이 정한다 — 이 문은 사람들에게 하는 말이다(ADR-0070 A15 결정 ①). */
1262
- addressee: 'room',
1263
- creator: user,
1264
- updater: user,
1265
- parentMessage: previousLast ? ({ id: previousLast.id } as any) : undefined
1266
- } as any)
1267
-
1268
- /*
1269
- * 멘션은 사람을 불러들인다 — **사람의 말을 저장하는 문**만 이것을 한다(ADR-0071 결정 1 ①).
1270
- * 누가 자리를 주는지는 `maySeat` 가 정한다. 공개 방에서는 말한 사람도 앉는다(`seatTurn`).
1271
- */
1272
- const invite = await seatTurn({
1273
- content: body,
1274
- sessionId: session.id!,
1275
- domainId: domain.id,
1276
- inviter: user,
1277
- participants: getRepository(ChatSessionParticipant, tx),
1278
- /* 비공개 대화에서는 이름만 닿는다 — ADR-0073 판정 2. */
1279
- visibility: (session as any).visibility
1280
- })
1281
- await notifyInvited(context, invite.invited, user, (session as any).name)
1282
- await tellRoomTurn({ domain, user, session: session as any, message: saved as any, tx, t: requestTranslator(context) })
1283
-
1284
- /* 사람의 말이다 — 목록의 최근 활동과 다른 참여자의 안 읽음이 이것으로 움직인다. */
1285
- try {
1286
- await getRepository(ChatSession, tx).update(session.id!, activityPatch(body) as any)
1287
- } catch {
1288
- /* 목록이 한 박자 늦는 것이 말을 못 하게 할 이유는 아니다. */
1289
- }
1290
- publishSessionActivity({
1291
- domainId: domain.id,
1292
- sessionId: session.id!,
1293
- kind: 'message',
1294
- anchorType: (session as any).anchorType,
1295
- anchorId: (session as any).anchorId,
1296
- preview: body,
1297
- actorId: user?.id
1298
- })
1299
- publishChatMessage({ domainId: domain.id, sessionId: session.id, message: saved })
1300
-
1301
- return saved.id ?? null
1302
- }
1303
-
1304
- @Directive('@transaction')
1305
- @Mutation(() => Boolean, {
1306
- description:
1307
- 'Append a system note to a session — context that did not come from a participant typing (e.g. a conversation carried over from another surface, an external state change). The AI sees it as part of the shared history.'
1308
- })
1309
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
1310
- async appendSessionNote(
1311
- @Arg('sessionId') sessionId: string,
1312
- @Arg('content') content: string,
1313
- @Ctx() context: ResolverContext
1314
- ): Promise<boolean> {
1315
- const { domain, user, tx } = context.state
1316
- const session = await getRepository(ChatSession, tx).findOneBy({ id: sessionId, domain: { id: domain.id } })
1317
- if (!session) throw sessionNotFound(context)
1318
- await writeGate(session, context, tx)
1319
- /* 프롬프트가 한 기록으로 폭증하지 않도록 자른다 — 맥락 전달이 목적이고 전문 보존이 아니다. */
1320
- const body = (content ?? '').trim().slice(0, 4000)
1321
- if (!body) return false
1322
-
1323
- const previousLast = await getRepository(ChatMessage, tx).findOne({
1324
- where: { session: { id: session.id } as any },
1325
- order: { createdAt: 'DESC' }
1326
- })
1327
- const sysMsg = await getRepository(ChatMessage, tx).save({
1328
- session: { id: session.id } as any,
1329
- role: 'system',
1330
- content: body,
1331
- creator: user,
1332
- updater: user,
1333
- parentMessage: previousLast ? ({ id: previousLast.id } as any) : undefined
1334
- } as any)
1335
-
1336
- /* 활동 갱신 + 방송 — 다른 참여자 목록·안 읽음과 열려 있는 화면의 transcript 일관성. best-effort. */
1337
- try {
1338
- await getRepository(ChatSession, tx).update(session.id!, activityPatch(body) as any)
1339
- } catch {
1340
- /* 기록 자체를 막지 않는다 */
1341
- }
1342
- publishSessionActivity({
1343
- domainId: domain.id,
1344
- sessionId: session.id!,
1345
- kind: 'message',
1346
- anchorType: (session as any).anchorType,
1347
- anchorId: (session as any).anchorId,
1348
- preview: body,
1349
- actorId: user?.id
1350
- })
1351
- publishChatMessage({ domainId: domain.id, sessionId: session.id, message: sysMsg })
1352
- return true
1353
- }
1354
-
1355
- @Directive('@transaction')
1356
- @Mutation(() => Boolean, {
1357
- description:
1358
- "Carry a conversation from another surface into this session as its own turns, preserving order. A person's turns are stored as theirs, addressed to the room. An assistant turn is stored as the assistant's only when it names its original (sourceSessionId, sourceMessageId) and the server can read it; otherwise it is kept as a quotation on a system row — roles are the server's to write (ADR-0070)."
1359
- })
1360
- @Directive('@privilege(category: "ai-assistant", privilege: "mutation", domainOwnerGranted: true)')
1361
- async appendSessionTurns(
1362
- @Arg('sessionId') sessionId: string,
1363
- @Arg('turns', () => GraphQLJSON) turns: { role?: string; content?: string }[],
1364
- @Ctx() context: ResolverContext
1365
- ): Promise<boolean> {
1366
- const { domain, user, tx } = context.state
1367
- const session = await getRepository(ChatSession, tx).findOneBy({ id: sessionId, domain: { id: domain.id } })
1368
- if (!session) throw sessionNotFound(context)
1369
- await writeGate(session, context, tx)
1370
-
1371
- /* 옮겨온 대화는 **그 대화의 발언 그대로** 들어간다 — 한 덩어리 기록으로 뭉치면 사람이 읽을 수 없고
1372
- * (화면 하나를 잡아먹는 이탤릭 덩어리), 마크다운도 죽는다. 대신 개수·길이는 제한한다: 맥락 전달이
1373
- * 목적이고 전문 보존이 아니다. */
1374
- /* **역할은 서버가 쓴다**(ADR-0070 A15 결정 ③). 어시스턴트의 답은 원본을 읽어 복사하고, 원본이 없으면
1375
- * 인용문으로 `system` 행에 남긴다 — 클라이언트가 보낸 글자를 어시스턴트의 말로 저장하지 않는다. */
1376
- const planned = planCarriedTurns(turns as any)
1377
- const rows: { role: string; content: string; addressee?: string; doors?: string[] }[] = []
1378
- /* 옮겨 적힌 원문이 소급해서 공개되지 않게, 받는 대화는 이 순간부터 비공개다 — ADR-0073 판정 2. */
1379
- let carried = false
1380
- for (const row of planned) {
1381
- if (!row.copyOf) {
1382
- rows.push({ role: row.role, content: row.content, addressee: row.addressee })
1383
- continue
1384
- }
1385
- /* 원본은 이 테넌트 안에서만 찾는다 — 남의 도메인 메시지를 옮겨 오는 길이 되지 않게. */
1386
- const original = await getRepository(ChatMessage, tx).findOne({
1387
- where: carriedOriginalWhere(domain.id, row.copyOf),
1388
- relations: ['session']
1389
- })
1390
- carried = true
1391
- if (original && original.role === 'assistant') {
1392
- /*
1393
- * 답과 함께 **그 답이 지나온 문**을 옮긴다 — ADR-0073 판정 1. 문을 두고 글만 옮기면, 문 하나를
1394
- * 지나 얻은 값이 문 없는 행이 되어 아무나 읽는다. 옮겨 적기가 권한을 씻는 길이 된다.
1395
- */
1396
- rows.push({ role: 'assistant', content: original.content, doors: (original as any).doors ?? [] })
1397
- } else {
1398
- /* 인용문에도 원문의 문을 실어 둔다 — 인용이라고 값이 달라지지 않는다. */
1399
- rows.push({ role: 'system', content: quoteCarriedAnswer(row.content), doors: (original as any)?.doors ?? [] })
1400
- }
1401
- }
1402
- if (!rows.length) return false
1403
-
1404
- let previous = await getRepository(ChatMessage, tx).findOne({
1405
- where: { session: { id: session.id } as any },
1406
- order: { createdAt: 'DESC' }
1407
- })
1408
- const saved: ChatMessage[] = []
1409
- for (const row of rows) {
1410
- previous = await getRepository(ChatMessage, tx).save({
1411
- session: { id: session.id } as any,
1412
- role: row.role,
1413
- content: row.content,
1414
- /* 사람의 말은 방을 향한 것이다 — 이 문은 어시스턴트를 부르는 문이 아니다. */
1415
- addressee: row.addressee,
1416
- doors: row.doors,
1417
- creator: user,
1418
- updater: user,
1419
- parentMessage: previous ? ({ id: previous.id } as any) : undefined
1420
- } as any)
1421
- saved.push(previous!)
1422
- }
1423
-
1424
- /*
1425
- * Carried words do not land in front of the whole domain. An open room closes to its owner; a group stays
1426
- * a group - its people were chosen by the owner, and carrying into it is writing to them.
1427
- */
1428
- if (carried && isOpenRoom((session as any).visibility)) {
1429
- await sendOutMembers(domain.id, session.id!, tx)
1430
- await getRepository(ChatSession, tx).update(session.id!, { visibility: 'private', updater: user } as any)
1431
- }
1432
-
1433
- /* 활동은 마지막 발언 기준 한 번만 — 옮긴 줄마다 목록을 흔들 이유가 없다. */
1434
- const last = rows[rows.length - 1]
1435
- try {
1436
- await getRepository(ChatSession, tx).update(session.id!, activityPatch(last.content) as any)
1437
- } catch {
1438
- /* best-effort — 옮기기 자체를 막지 않는다 */
1439
- }
1440
- publishSessionActivity({
1441
- domainId: domain.id,
1442
- sessionId: session.id!,
1443
- kind: 'message',
1444
- anchorType: (session as any).anchorType,
1445
- anchorId: (session as any).anchorId,
1446
- preview: last.content,
1447
- actorId: user?.id
1448
- })
1449
- for (const message of saved) {
1450
- publishChatMessage({ domainId: domain.id, sessionId: session.id, message })
1451
- }
1452
- return true
1453
- }
1454
-
1455
- }