@capybara-hq/kernel 0.1.0-rc.105 → 0.1.0-rc.107

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 (359) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/agents/agents.schemas.d.ts +9 -9
  3. package/dist/{schedules/schedules.controller.d.ts → automations/automations.controller.d.ts} +37 -32
  4. package/dist/{schedules/schedules.controller.js → automations/automations.controller.js} +68 -57
  5. package/dist/automations/automations.module.d.ts +16 -0
  6. package/dist/{schedules/schedules.module.js → automations/automations.module.js} +18 -15
  7. package/dist/{schedules/schedules.schemas.d.ts → automations/automations.schemas.d.ts} +151 -50
  8. package/dist/automations/automations.schemas.js +253 -0
  9. package/dist/{schedules/scheduled-tasks.service.d.ts → automations/automations.service.d.ts} +99 -52
  10. package/dist/{schedules/scheduled-tasks.service.js → automations/automations.service.js} +303 -134
  11. package/dist/{schedules → automations}/calendar.d.ts +8 -8
  12. package/dist/{schedules → automations}/calendar.js +2 -2
  13. package/dist/automations/effective-settings.d.ts +28 -0
  14. package/dist/automations/effective-settings.js +25 -0
  15. package/dist/automations/errors.d.ts +19 -0
  16. package/dist/automations/errors.js +19 -0
  17. package/dist/automations/events/coalesce.d.ts +28 -0
  18. package/dist/automations/events/coalesce.js +131 -0
  19. package/dist/automations/events/deadline.d.ts +10 -0
  20. package/dist/automations/events/deadline.js +24 -0
  21. package/dist/automations/events/dispatcher.d.ts +74 -0
  22. package/dist/automations/events/dispatcher.js +353 -0
  23. package/dist/automations/events/events.module.d.ts +7 -0
  24. package/dist/automations/events/events.module.js +26 -0
  25. package/dist/automations/events/guards.d.ts +32 -0
  26. package/dist/automations/events/guards.js +87 -0
  27. package/dist/automations/events/sweep.job.d.ts +49 -0
  28. package/dist/automations/events/sweep.job.js +202 -0
  29. package/dist/automations/events/token.d.ts +5 -0
  30. package/dist/automations/events/token.js +5 -0
  31. package/dist/automations/events/trigger-events.service.d.ts +47 -0
  32. package/dist/automations/events/trigger-events.service.js +254 -0
  33. package/dist/{schedules → automations}/fire.d.ts +57 -17
  34. package/dist/{schedules → automations}/fire.js +311 -79
  35. package/dist/{schedules → automations}/grant-rules.d.ts +1 -1
  36. package/dist/{schedules → automations}/grant-rules.js +5 -5
  37. package/dist/automations/job-ids.d.ts +113 -0
  38. package/dist/automations/job-ids.js +117 -0
  39. package/dist/{schedules → automations}/pause.d.ts +3 -3
  40. package/dist/{schedules → automations}/pause.js +3 -3
  41. package/dist/{schedules → automations}/run-tracker.d.ts +21 -10
  42. package/dist/{schedules → automations}/run-tracker.js +68 -56
  43. package/dist/{schedules → automations}/scan.job.d.ts +12 -8
  44. package/dist/{schedules → automations}/scan.job.js +39 -23
  45. package/dist/{schedules → automations}/schedule-math.d.ts +19 -12
  46. package/dist/{schedules → automations}/schedule-math.js +17 -7
  47. package/dist/{schedules → automations}/store.d.ts +57 -27
  48. package/dist/{schedules → automations}/store.js +102 -52
  49. package/dist/automations/store.module.d.ts +6 -0
  50. package/dist/{schedules → automations}/store.module.js +9 -9
  51. package/dist/automations/types.d.ts +178 -0
  52. package/dist/{schedules → automations}/unattended.d.ts +22 -11
  53. package/dist/{schedules → automations}/unattended.js +53 -30
  54. package/dist/catalog/marketplaces.service.d.ts +1 -1
  55. package/dist/channels/channels.module.js +7 -6
  56. package/dist/channels/file-delivery.d.ts +26 -11
  57. package/dist/channels/file-delivery.js +32 -11
  58. package/dist/channels/outbound.d.ts +8 -8
  59. package/dist/channels/outbound.js +32 -30
  60. package/dist/channels/threads.d.ts +1 -1
  61. package/dist/channels/threads.js +1 -1
  62. package/dist/config/schema.d.ts +8 -1
  63. package/dist/config/schema.js +56 -6
  64. package/dist/conversations/approval-profile.d.ts +2 -2
  65. package/dist/conversations/approval-profile.js +3 -3
  66. package/dist/conversations/artifacts.d.ts +20 -17
  67. package/dist/conversations/artifacts.js +30 -37
  68. package/dist/conversations/attachments.controller.d.ts +6 -19
  69. package/dist/conversations/attachments.controller.js +8 -59
  70. package/dist/conversations/attachments.service.d.ts +30 -74
  71. package/dist/conversations/attachments.service.js +51 -193
  72. package/dist/conversations/conversations.controller.d.ts +7 -1
  73. package/dist/conversations/conversations.controller.js +26 -10
  74. package/dist/conversations/conversations.module.js +4 -0
  75. package/dist/conversations/conversations.service.d.ts +112 -35
  76. package/dist/conversations/conversations.service.js +160 -43
  77. package/dist/conversations/event-log.d.ts +1 -0
  78. package/dist/conversations/events.d.ts +95 -27
  79. package/dist/conversations/events.js +108 -10
  80. package/dist/conversations/files.d.ts +66 -64
  81. package/dist/conversations/files.js +127 -147
  82. package/dist/conversations/message-context.d.ts +2 -2
  83. package/dist/conversations/message-context.js +1 -1
  84. package/dist/conversations/permission-profile-store.d.ts +2 -1
  85. package/dist/conversations/permission-profiles.controller.d.ts +3 -0
  86. package/dist/conversations/permission-profiles.service.js +1 -1
  87. package/dist/conversations/prompt-suggestion-request.d.ts +1 -1
  88. package/dist/conversations/prompt-suggestion-request.js +4 -2
  89. package/dist/conversations/prompt-suggestions.d.ts +3 -3
  90. package/dist/conversations/prompt-suggestions.js +11 -10
  91. package/dist/conversations/queue.d.ts +7 -4
  92. package/dist/conversations/queue.js +6 -2
  93. package/dist/conversations/queue.service.d.ts +5 -5
  94. package/dist/conversations/queue.service.js +27 -16
  95. package/dist/ctx/create-ctx.d.ts +23 -2
  96. package/dist/ctx/create-ctx.js +78 -3
  97. package/dist/db/kernel-schema.d.ts +184 -27
  98. package/dist/devices/device-project-files.service.d.ts +88 -0
  99. package/dist/devices/device-project-files.service.js +249 -0
  100. package/dist/devices/device-projects.service.d.ts +40 -0
  101. package/dist/devices/device-projects.service.js +16 -13
  102. package/dist/devices/devices.controller.d.ts +9 -3
  103. package/dist/devices/devices.controller.js +27 -5
  104. package/dist/devices/devices.module.js +9 -1
  105. package/dist/devices/devices.schemas.js +6 -1
  106. package/dist/devices/dto.d.ts +15 -0
  107. package/dist/devices/dto.js +11 -0
  108. package/dist/devices/project-paths.d.ts +29 -0
  109. package/dist/devices/project-paths.js +66 -0
  110. package/dist/devices/project-rules.d.ts +5 -1
  111. package/dist/devices/project-rules.js +5 -1
  112. package/dist/errors.d.ts +53 -13
  113. package/dist/errors.js +53 -13
  114. package/dist/evals/canonical-json.d.ts +7 -0
  115. package/dist/evals/canonical-json.js +21 -0
  116. package/dist/evals/reconstruct.d.ts +10 -1
  117. package/dist/evals/reconstruct.js +20 -1
  118. package/dist/evals/recorded-tools.d.ts +0 -2
  119. package/dist/evals/recorded-tools.js +1 -16
  120. package/dist/evals/snapshot.d.ts +26 -3
  121. package/dist/evals/snapshot.js +110 -57
  122. package/dist/evals/worker.d.ts +4 -3
  123. package/dist/evals/worker.js +8 -4
  124. package/dist/extensions/host.d.ts +9 -2
  125. package/dist/extensions/host.js +12 -0
  126. package/dist/extensions/instance.d.ts +3 -1
  127. package/dist/extensions/instance.js +4 -0
  128. package/dist/extensions/ledger.d.ts +1 -1
  129. package/dist/extensions/permission-set.d.ts +17 -1
  130. package/dist/extensions/permission-set.js +13 -1
  131. package/dist/extensions/permission-view.d.ts +1 -1
  132. package/dist/extensions/permission-view.js +4 -1
  133. package/dist/files/blob-objects.d.ts +124 -0
  134. package/dist/files/blob-objects.js +341 -0
  135. package/dist/files/blob-sweep.job.d.ts +122 -0
  136. package/dist/files/blob-sweep.job.js +389 -0
  137. package/dist/files/blobs.service.d.ts +135 -0
  138. package/dist/files/blobs.service.js +300 -0
  139. package/dist/files/conversation-media.d.ts +41 -0
  140. package/dist/files/conversation-media.js +124 -0
  141. package/dist/files/deliveries.d.ts +64 -0
  142. package/dist/files/deliveries.js +156 -0
  143. package/dist/files/deliveries.module.d.ts +6 -0
  144. package/dist/files/deliveries.module.js +24 -0
  145. package/dist/files/draft-cleanup.job.d.ts +26 -0
  146. package/dist/files/draft-cleanup.job.js +93 -0
  147. package/dist/files/files.module.d.ts +1 -1
  148. package/dist/files/files.module.js +3 -2
  149. package/dist/files/hash-job.d.ts +127 -0
  150. package/dist/files/hash-job.js +447 -0
  151. package/dist/files/library-backfill.d.ts +63 -0
  152. package/dist/files/library-backfill.js +143 -0
  153. package/dist/files/library-files.service.d.ts +255 -0
  154. package/dist/files/library-files.service.js +883 -0
  155. package/dist/files/library-jobs.module.d.ts +8 -0
  156. package/dist/files/library-jobs.module.js +27 -0
  157. package/dist/files/library-query.d.ts +127 -0
  158. package/dist/files/library-query.js +322 -0
  159. package/dist/files/library-read.module.d.ts +9 -0
  160. package/dist/files/library-read.module.js +30 -0
  161. package/dist/files/library.controller.d.ts +77 -0
  162. package/dist/files/library.controller.js +235 -0
  163. package/dist/files/library.module.d.ts +9 -0
  164. package/dist/files/library.module.js +29 -0
  165. package/dist/files/library.schemas.d.ts +46 -0
  166. package/dist/files/library.schemas.js +49 -0
  167. package/dist/files/previewers.controller.d.ts +20 -0
  168. package/dist/files/previewers.controller.js +47 -0
  169. package/dist/files/previewers.d.ts +25 -11
  170. package/dist/files/previewers.js +43 -27
  171. package/dist/files/referenced-files.d.ts +150 -0
  172. package/dist/files/referenced-files.js +234 -0
  173. package/dist/git/gateway.js +2 -2
  174. package/dist/html/html-document.controller.d.ts +8 -1
  175. package/dist/html/html-document.controller.js +19 -1
  176. package/dist/html/html-document.service.d.ts +19 -4
  177. package/dist/html/html-document.service.js +43 -22
  178. package/dist/html/html-token.d.ts +10 -1
  179. package/dist/html/html-token.js +14 -0
  180. package/dist/html/html.module.js +8 -1
  181. package/dist/http/api.module.js +10 -5
  182. package/dist/http/request-signal.d.ts +8 -0
  183. package/dist/http/request-signal.js +14 -0
  184. package/dist/identity/settings.d.ts +26 -0
  185. package/dist/identity/settings.js +33 -2
  186. package/dist/inbox/inbox.module.js +2 -2
  187. package/dist/inbox/inbox.service.d.ts +8 -8
  188. package/dist/inbox/inbox.service.js +7 -7
  189. package/dist/infra/config/kernel-config.service.js +10 -5
  190. package/dist/infra/outbox/registry.d.ts +111 -2
  191. package/dist/infra/outbox/registry.js +104 -9
  192. package/dist/infra/throttler/named-throttlers.d.ts +2 -0
  193. package/dist/infra/throttler/named-throttlers.js +14 -0
  194. package/dist/kernel.module.js +3 -0
  195. package/dist/lifecycle/kernel-lifecycle.js +6 -0
  196. package/dist/models/purposes.js +1 -1
  197. package/dist/orgs/offboarding.js +1 -1
  198. package/dist/orgs/roles.d.ts +1 -1
  199. package/dist/orgs/roles.js +3 -3
  200. package/dist/orgs/settings.controller.d.ts +1 -1
  201. package/dist/orgs/settings.service.d.ts +75 -13
  202. package/dist/orgs/settings.service.js +104 -26
  203. package/dist/platform/exclusions.js +45 -8
  204. package/dist/platform/file-ref.d.ts +18 -3
  205. package/dist/platform/file-ref.js +22 -11
  206. package/dist/platform/operation.js +6 -2
  207. package/dist/platform/ops/admin.ops.js +5 -2
  208. package/dist/platform/ops/{schedules.ops.d.ts → automations.ops.d.ts} +4 -4
  209. package/dist/platform/ops/automations.ops.js +560 -0
  210. package/dist/platform/ops/devices.ops.d.ts +3 -1
  211. package/dist/platform/ops/devices.ops.js +77 -3
  212. package/dist/platform/ops/files.ops.d.ts +18 -0
  213. package/dist/platform/ops/files.ops.js +267 -0
  214. package/dist/platform/ops/inbox.ops.js +4 -4
  215. package/dist/platform/ops/org-settings.ops.js +6 -2
  216. package/dist/platform/ops/orgs.ops.js +2 -1
  217. package/dist/platform/ops/platform.ops.js +4 -4
  218. package/dist/platform/ops/shares.ops.js +2 -2
  219. package/dist/platform/platform-ops.module.d.ts +3 -2
  220. package/dist/platform/platform-ops.module.js +10 -5
  221. package/dist/platform/route-schemas.js +6 -3
  222. package/dist/push/jobs.d.ts +3 -3
  223. package/dist/push/jobs.js +2 -2
  224. package/dist/push/preferences.service.js +1 -1
  225. package/dist/push/push-owed.d.ts +3 -3
  226. package/dist/push/push-owed.js +6 -6
  227. package/dist/push/push.schemas.d.ts +4 -4
  228. package/dist/push/push.schemas.js +3 -3
  229. package/dist/push/recipients.d.ts +4 -4
  230. package/dist/push/recipients.js +23 -23
  231. package/dist/push/texts.d.ts +3 -3
  232. package/dist/push/texts.js +2 -2
  233. package/dist/push/triggers.d.ts +1 -1
  234. package/dist/roles/worker.module.js +18 -4
  235. package/dist/runtime/compaction-settings.service.d.ts +13 -1
  236. package/dist/runtime/compaction-settings.service.js +16 -1
  237. package/dist/runtime/compaction.service.d.ts +3 -1
  238. package/dist/runtime/compaction.service.js +3 -1
  239. package/dist/runtime/context/build.d.ts +24 -1
  240. package/dist/runtime/context/build.js +33 -11
  241. package/dist/runtime/context/cache-expiry.d.ts +31 -0
  242. package/dist/runtime/context/cache-expiry.js +60 -0
  243. package/dist/runtime/context/cache-ttl.d.ts +18 -0
  244. package/dist/runtime/context/cache-ttl.js +30 -0
  245. package/dist/runtime/context/compaction.d.ts +9 -2
  246. package/dist/runtime/context/compaction.js +64 -21
  247. package/dist/runtime/context/in-context-compaction.d.ts +156 -0
  248. package/dist/runtime/context/in-context-compaction.js +310 -0
  249. package/dist/runtime/context/run-context.d.ts +38 -0
  250. package/dist/runtime/context/run-context.js +54 -0
  251. package/dist/runtime/hook-calls.d.ts +2 -1
  252. package/dist/runtime/hook-calls.js +5 -2
  253. package/dist/runtime/maintenance.d.ts +16 -4
  254. package/dist/runtime/maintenance.js +79 -18
  255. package/dist/runtime/model-call.d.ts +34 -5
  256. package/dist/runtime/model-call.js +207 -22
  257. package/dist/runtime/providers.js +11 -1
  258. package/dist/runtime/run-finish.d.ts +4 -4
  259. package/dist/runtime/run-finish.js +3 -3
  260. package/dist/runtime/run-queue.js +12 -7
  261. package/dist/runtime/run-steps.d.ts +4 -2
  262. package/dist/runtime/run-steps.js +10 -5
  263. package/dist/runtime/run-worker.js +7 -1
  264. package/dist/runtime/runtime.module.js +6 -3
  265. package/dist/runtime/subagents/dispatch.js +11 -3
  266. package/dist/sandbox/browse-roots.d.ts +8 -0
  267. package/dist/sandbox/browse-roots.js +22 -0
  268. package/dist/sandbox/network-grants.d.ts +4 -4
  269. package/dist/sandbox/network-grants.js +7 -7
  270. package/dist/sandbox/operation-authority.d.ts +10 -3
  271. package/dist/sandbox/operation-authority.js +20 -10
  272. package/dist/sandbox/operation-intents.d.ts +3 -1
  273. package/dist/sandbox/operation-intents.js +11 -4
  274. package/dist/sandbox/permission-call-grants.js +2 -2
  275. package/dist/sandbox/permission-facts.js +1 -1
  276. package/dist/sandbox/review/classifier.d.ts +2 -2
  277. package/dist/sandbox/review/classifier.js +22 -11
  278. package/dist/sandbox/review/permission-candidate.d.ts +1 -1
  279. package/dist/sandbox/review/permission-candidate.js +1 -1
  280. package/dist/sandbox/sandbox.service.d.ts +15 -5
  281. package/dist/sandbox/sandbox.service.js +14 -8
  282. package/dist/shares/liveness.d.ts +26 -12
  283. package/dist/shares/liveness.js +79 -20
  284. package/dist/shares/revoke.d.ts +16 -11
  285. package/dist/shares/revoke.js +18 -14
  286. package/dist/shares/share-objects.d.ts +16 -21
  287. package/dist/shares/share-objects.js +25 -55
  288. package/dist/shares/share-open.service.d.ts +8 -4
  289. package/dist/shares/share-open.service.js +14 -11
  290. package/dist/shares/shares.controller.d.ts +16 -5
  291. package/dist/shares/shares.controller.js +39 -5
  292. package/dist/shares/shares.module.d.ts +4 -4
  293. package/dist/shares/shares.module.js +7 -6
  294. package/dist/shares/shares.schemas.d.ts +4 -0
  295. package/dist/shares/shares.schemas.js +2 -0
  296. package/dist/shares/shares.service.d.ts +93 -54
  297. package/dist/shares/shares.service.js +292 -131
  298. package/dist/shares/sweep.job.d.ts +18 -39
  299. package/dist/shares/sweep.job.js +47 -206
  300. package/dist/storage/purge.d.ts +1 -1
  301. package/dist/storage/purge.js +2 -2
  302. package/dist/tools/approvals.service.d.ts +6 -6
  303. package/dist/tools/approvals.service.js +19 -19
  304. package/dist/tools/builtin-names.d.ts +12 -12
  305. package/dist/tools/builtin-names.js +29 -29
  306. package/dist/tools/builtins/artifacts.d.ts +21 -13
  307. package/dist/tools/builtins/artifacts.js +81 -51
  308. package/dist/tools/builtins/{schedules.d.ts → automations.d.ts} +35 -33
  309. package/dist/tools/builtins/{schedules.js → automations.js} +236 -105
  310. package/dist/tools/builtins/builtin-tools.d.ts +15 -9
  311. package/dist/tools/builtins/builtin-tools.js +33 -22
  312. package/dist/tools/builtins/conversation-files.d.ts +23 -13
  313. package/dist/tools/builtins/conversation-files.js +62 -83
  314. package/dist/tools/builtins/image/generate.d.ts +7 -1
  315. package/dist/tools/builtins/image/generate.js +1 -1
  316. package/dist/tools/builtins/platform.js +1 -0
  317. package/dist/tools/builtins/sandbox/common.d.ts +6 -2
  318. package/dist/tools/builtins/sandbox/deliver.js +6 -7
  319. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +6 -5
  320. package/dist/tools/builtins/sandbox/fetch-attachment.js +19 -12
  321. package/dist/tools/call-scope.d.ts +1 -1
  322. package/dist/tools/git-asks.js +1 -1
  323. package/dist/tools/git-push-policy.d.ts +3 -3
  324. package/dist/tools/git-push-policy.js +6 -6
  325. package/dist/tools/network-asks.d.ts +3 -3
  326. package/dist/tools/network-asks.js +3 -3
  327. package/dist/tools/pipeline.d.ts +4 -4
  328. package/dist/tools/pipeline.js +2 -2
  329. package/dist/tools/policy.d.ts +3 -3
  330. package/dist/tools/policy.js +3 -3
  331. package/dist/tools/tools.module.js +15 -9
  332. package/dist/ui/call-extension.d.ts +6 -4
  333. package/dist/ui/call-extension.js +5 -4
  334. package/dist/ui/embed-token.js +6 -3
  335. package/dist/ui/registry.d.ts +21 -5
  336. package/dist/ui/registry.js +24 -6
  337. package/dist/ui/ui.schemas.d.ts +22 -0
  338. package/dist/ui/ui.schemas.js +22 -4
  339. package/dist/ui/views.controller.d.ts +13 -3
  340. package/dist/ui/views.controller.js +33 -2
  341. package/dist/ui/views.d.ts +29 -1
  342. package/dist/ui/views.js +131 -7
  343. package/package.json +3 -3
  344. package/src/migrations/0188_automations_rename.sql +309 -0
  345. package/src/migrations/0189_event_automations.sql +136 -0
  346. package/src/migrations/0190_file_library.sql +285 -0
  347. package/src/migrations/0191_file_library_copy.sql +4 -0
  348. package/dist/platform/ops/schedules.ops.js +0 -509
  349. package/dist/schedules/effective-settings.d.ts +0 -22
  350. package/dist/schedules/effective-settings.js +0 -18
  351. package/dist/schedules/errors.d.ts +0 -8
  352. package/dist/schedules/errors.js +0 -8
  353. package/dist/schedules/job-ids.d.ts +0 -81
  354. package/dist/schedules/job-ids.js +0 -95
  355. package/dist/schedules/schedules.module.d.ts +0 -16
  356. package/dist/schedules/schedules.schemas.js +0 -213
  357. package/dist/schedules/store.module.d.ts +0 -6
  358. package/dist/schedules/types.d.ts +0 -110
  359. /package/dist/{schedules → automations}/types.js +0 -0
@@ -0,0 +1,883 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { createHash, randomUUID } from "node:crypto";
11
+ import { MEDIA_LIMITS } from "@capybara-hq/plugin-sdk";
12
+ import { Inject, Injectable } from "@nestjs/common";
13
+ import { sql } from "kysely";
14
+ import { countPdfPages, normalizeContentType, sniffMatches, } from "../conversations/attachments.service.js";
15
+ import { EventLog } from "../conversations/event-log.js";
16
+ import { isImageContentType, isMediaContentType } from "../conversations/media-types.js";
17
+ import { ApiError } from "../errors.js";
18
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
19
+ import { afterCommit } from "../infra/database/after-commit.js";
20
+ import { KernelDb } from "../infra/database/kernel-db.js";
21
+ import { TransactionHost } from "../infra/database/transaction-host.js";
22
+ import { Transactional } from "../infra/database/transactional.decorator.js";
23
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
24
+ import { revokeSharesIn } from "../shares/revoke.js";
25
+ import { StorageService } from "../storage/storage.service.js";
26
+ import { afterUploadForm, deferred, FILE_UPLOAD_TTL_SECONDS, oweBlobDelete, oweFileRelease, oweStagingDelete, stagingObjectKey, } from "./blob-objects.js";
27
+ import { BlobsService } from "./blobs.service.js";
28
+ /** Unfinished uploads (`uploading` + `draft`) one account may have in an org. */
29
+ export const MAX_PENDING_FILES = 50;
30
+ /** Expired uploads and drafts one cleanup batch takes. */
31
+ const CLEANUP_BATCH = 100;
32
+ /** How many leading bytes finalize checks against the declared type's signature. */
33
+ const SNIFF_BYTES = 1024;
34
+ /** How often {@link LibraryFilesService.addFromBytes} ensures a blob a deletion claimed. */
35
+ const ADD_BLOB_ATTEMPTS = 3;
36
+ /**
37
+ * {@link LibraryFilesService.addFromBytes} found the blob of these bytes claimed by a deletion
38
+ * {@link ADD_BLOB_ATTEMPTS} times in a row (nothing written): a transient race, worth a retry.
39
+ */
40
+ export class FileBlobClaimedError extends Error {
41
+ constructor() {
42
+ super("the stored bytes were being deleted while the file was added");
43
+ this.name = "FileBlobClaimedError";
44
+ }
45
+ }
46
+ /**
47
+ * The content block a message carries for a file (a `ref` to its id, never bytes): images, PDFs
48
+ * and text become blocks the model reads itself; every other accepted type a `file` block the
49
+ * model only gets a reference to.
50
+ */
51
+ export function fileContentBlock(f) {
52
+ const source = { kind: "ref", fileId: f.id };
53
+ if (isImageContentType(f.contentType)) {
54
+ return {
55
+ type: "image",
56
+ mediaType: f.contentType,
57
+ source,
58
+ name: f.name,
59
+ size: f.size,
60
+ };
61
+ }
62
+ if (isMediaContentType(f.contentType)) {
63
+ return {
64
+ type: "document",
65
+ mediaType: f.contentType,
66
+ source,
67
+ name: f.name,
68
+ size: f.size,
69
+ };
70
+ }
71
+ return { type: "file", mediaType: f.contentType, source, name: f.name, size: f.size };
72
+ }
73
+ const notFound = () => new ApiError("file.not_found", "File not found");
74
+ const UPLOAD_COLUMNS = [
75
+ "id",
76
+ "name",
77
+ "content_type",
78
+ "size",
79
+ "status",
80
+ "blob_id",
81
+ "staging_key",
82
+ "sha256",
83
+ "upload_purpose",
84
+ "created_at",
85
+ ];
86
+ const viewOf = (r) => {
87
+ if (r.status === "deleted")
88
+ throw notFound();
89
+ return {
90
+ id: r.id,
91
+ name: r.name,
92
+ contentType: r.content_type,
93
+ size: Number(r.size),
94
+ status: r.status,
95
+ };
96
+ };
97
+ /** How long finalize waits for the staging object's bytes before giving up (ms). */
98
+ const READ_TIMEOUT_MS = 60_000;
99
+ /** Finalizes one replica reads and copies at once (each holds up to one upload in memory). */
100
+ const FINALIZE_SLOTS = 4;
101
+ /**
102
+ * A process-local counting semaphore. It bounds this replica's memory and bandwidth only: it is a
103
+ * resource limit, not shared state (no answer depends on it, and each replica has its own), so it
104
+ * does not break the rule that cross-request state lives in PG or Redis.
105
+ */
106
+ class LocalSlots {
107
+ free;
108
+ waiting = [];
109
+ constructor(size) {
110
+ this.free = size;
111
+ }
112
+ async run(fn) {
113
+ if (this.free > 0)
114
+ this.free--;
115
+ else
116
+ await new Promise((resolve) => this.waiting.push(resolve));
117
+ try {
118
+ return await fn();
119
+ }
120
+ finally {
121
+ const next = this.waiting.shift();
122
+ if (next)
123
+ next();
124
+ else
125
+ this.free++;
126
+ }
127
+ }
128
+ }
129
+ /**
130
+ * The files of the file library (file library spec §2–§4 with the builder amendment of §3):
131
+ * account-owned rows over blobs.
132
+ *
133
+ * Uploading: `create` admits the upload and, unless the caller already holds the same bytes in a
134
+ * file of their own, inserts an `uploading` row (with the declared sha256 and the purpose) before
135
+ * presigning `uploads/<fileId>`. `finalize` checks the staging object (size, type, signature, PDF
136
+ * pages), reads it whole, compares its sha256 with the declared one, copies the verified bytes to a
137
+ * kernel-owned blob (`blobs/<blobId>`, intent first) and settles that blob in one transaction
138
+ * ({@link BlobsService.settle}); the staging object's deletion is always owed. No form can write a
139
+ * blob's key, and every branch does the same work, so nothing the caller can observe depends on
140
+ * whether another account stored the same bytes. `discard` drops a composer upload before it is
141
+ * sent; expired uploads and drafts go with {@link expireBatch}.
142
+ *
143
+ * Sending: {@link attachForMessage} turns the sender's drafts into `ready` files and records the
144
+ * conversation's reference, in the message's transaction. No process state.
145
+ */
146
+ let LibraryFilesService = class LibraryFilesService {
147
+ db;
148
+ txHost;
149
+ storage;
150
+ config;
151
+ blobs;
152
+ outbox;
153
+ eventLog;
154
+ constructor(db, txHost, storage, config, blobs, outbox,
155
+ /** The `files` change of the conversations that referred to a deleted file. */
156
+ eventLog) {
157
+ this.db = db;
158
+ this.txHost = txHost;
159
+ this.storage = storage;
160
+ this.config = config;
161
+ this.blobs = blobs;
162
+ this.outbox = outbox;
163
+ this.eventLog = eventLog;
164
+ }
165
+ /** This replica's bound on finalizes reading and copying at once ({@link LocalSlots}). */
166
+ finalizeSlots = new LocalSlots(FINALIZE_SLOTS);
167
+ /** The upload limits under the current config (needs no object store). */
168
+ limits() {
169
+ const cfg = this.config.get().attachments;
170
+ return {
171
+ types: [...cfg.allowedTypes],
172
+ extensions: [...cfg.allowedExtensions],
173
+ maxBytes: Math.min(cfg.maxBytes, MEDIA_LIMITS.documentBytes),
174
+ imageMaxBytes: Math.min(cfg.maxBytes, MEDIA_LIMITS.imageBytes),
175
+ maxPerMessage: cfg.maxPerMessage,
176
+ requestMediaBytes: cfg.requestMediaBytes,
177
+ available: this.storage.available,
178
+ };
179
+ }
180
+ /** One file's size limit: the configured `maxBytes`, an image also `MEDIA_LIMITS.imageBytes`. */
181
+ limitFor(contentType) {
182
+ return Math.min(this.config.get().attachments.maxBytes, isImageContentType(contentType) ? MEDIA_LIMITS.imageBytes : MEDIA_LIMITS.documentBytes);
183
+ }
184
+ /**
185
+ * Starts an upload. Admission: a type outside `attachments.allowedTypes` →
186
+ * `file.type_not_allowed`; over the size limit → `file.too_large`; {@link MAX_PENDING_FILES}
187
+ * unfinished files (`uploading` + `draft`) of the account in the org → `file.too_many_pending`
188
+ * (a soft cap); no object store → `storage.unavailable`.
189
+ *
190
+ * When one of the caller's own `ready` or unexpired `draft` files of the same type and size has
191
+ * this sha256 and a `ready` blob, the new file is created on that blob at once (`upload: null`):
192
+ * the caller already holds those bytes, so nothing is learned. In every other case (another
193
+ * account's bytes included) an `uploading` row is inserted with the declared sha256 and purpose
194
+ * (expiring after `attachments.unboundTtlHours`) before a form for `uploads/<fileId>` is
195
+ * presigned, the store enforcing the declared size and type.
196
+ */
197
+ async create(orgId, accountId, input) {
198
+ this.storage.assertAvailable();
199
+ const contentType = await this.admit(orgId, accountId, input);
200
+ const instant = await this.createOnOwnBlob(orgId, accountId, { ...input, contentType });
201
+ if (instant)
202
+ return { file: instant, upload: null, expiresAt: null };
203
+ const id = randomUUID();
204
+ const ttlHours = this.config.get().attachments.unboundTtlHours;
205
+ await this.db
206
+ .insertInto("files")
207
+ .values({
208
+ id,
209
+ org_id: orgId,
210
+ account_id: accountId,
211
+ blob_id: null,
212
+ name: input.name,
213
+ content_type: contentType,
214
+ size: input.size,
215
+ origin: "upload",
216
+ status: "uploading",
217
+ sha256: input.sha256,
218
+ upload_purpose: input.purpose,
219
+ expires_at: sql `now() + make_interval(hours => ${ttlHours})`,
220
+ })
221
+ .execute();
222
+ const upload = await this.storage.kernel(orgId).presignPut(stagingObjectKey(id), {
223
+ contentType,
224
+ maxSize: input.size,
225
+ ttlSeconds: FILE_UPLOAD_TTL_SECONDS,
226
+ });
227
+ return {
228
+ file: { id, name: input.name, contentType, size: input.size, status: "uploading" },
229
+ upload,
230
+ expiresAt: new Date(Date.now() + FILE_UPLOAD_TTL_SECONDS * 1000).toISOString(),
231
+ };
232
+ }
233
+ /** The admission checks of {@link create}; returns the normalized content type. */
234
+ async admit(orgId, accountId, input) {
235
+ const contentType = this.admitType(input);
236
+ const pending = await this.db
237
+ .selectFrom("files")
238
+ .select((eb) => eb.fn.countAll().as("n"))
239
+ .where("org_id", "=", orgId)
240
+ .where("account_id", "=", accountId)
241
+ .where("status", "in", ["uploading", "draft"])
242
+ .executeTakeFirst();
243
+ if (Number(pending?.n ?? 0) >= MAX_PENDING_FILES) {
244
+ throw new ApiError("file.too_many_pending", `Too many unfinished uploads (at most ${MAX_PENDING_FILES}); send, remove or wait for them first`);
245
+ }
246
+ return contentType;
247
+ }
248
+ /** The type and size checks of an upload; returns the normalized content type. */
249
+ admitType(input) {
250
+ const contentType = normalizeContentType(input.contentType);
251
+ if (!this.config.get().attachments.allowedTypes.includes(contentType)) {
252
+ throw new ApiError("file.type_not_allowed", `File type ${JSON.stringify(contentType)} is not allowed`);
253
+ }
254
+ const limit = this.limitFor(contentType);
255
+ if (input.size > limit) {
256
+ throw new ApiError("file.too_large", `File is ${input.size} bytes, over the limit of ${limit} bytes`);
257
+ }
258
+ return contentType;
259
+ }
260
+ /**
261
+ * The owner of a library file of the org that is not deleted, or null (no such file: a `read`
262
+ * copy, another org's id). A file has one owner (file library spec §2).
263
+ */
264
+ async ownerOf(orgId, fileId) {
265
+ const row = await this.db
266
+ .selectFrom("files")
267
+ .select("account_id")
268
+ .where("id", "=", fileId)
269
+ .where("org_id", "=", orgId)
270
+ .where("status", "<>", "deleted")
271
+ .executeTakeFirst();
272
+ return row?.account_id ?? null;
273
+ }
274
+ /**
275
+ * Adds bytes the kernel already holds (a conversation file the `Platform` tool resolved, never
276
+ * another account's library file: the caller refuses those) to the account's library as an
277
+ * upload, `ready` at once.
278
+ *
279
+ * - `referencedId` already one of the account's `ready` files: returned as it is
280
+ * (`existing: true`), or, with a `rename` other than its name, a new entry on its blob.
281
+ * - Otherwise: no object store → `storage.unavailable`, the upload's type and size checks, the
282
+ * signature check of finalize (`file.type_not_allowed`); the account's own `ready` file of the
283
+ * same name, type and sha256 is returned as it is (`existing: true`; a repeated call adds
284
+ * nothing). Else the bytes go through {@link BlobsService.ensureFromBytes} (the org's ready
285
+ * blob of this hash, else a new one written intent first and settled) and the file row is
286
+ * inserted on it behind {@link BlobsService.lockReady}; a blob a deletion claimed meanwhile is
287
+ * ensured again, and {@link FileBlobClaimedError} is thrown after
288
+ * {@link ADD_BLOB_ATTEMPTS} tries. No presigned form is involved.
289
+ */
290
+ async addFromBytes(orgId, accountId, input) {
291
+ const name = input.rename ?? input.name;
292
+ if (input.referencedId !== undefined) {
293
+ const own = await this.db
294
+ .selectFrom("files")
295
+ .select(["id", "name", "content_type", "size", "status", "blob_id", "sha256", "pages"])
296
+ .where("id", "=", input.referencedId)
297
+ .where("org_id", "=", orgId)
298
+ .where("account_id", "=", accountId)
299
+ .where("status", "=", "ready")
300
+ .executeTakeFirst();
301
+ if (own && (input.rename === undefined || input.rename === own.name)) {
302
+ return { ...viewOf(own), existing: true };
303
+ }
304
+ if (own?.blob_id) {
305
+ // a renamed copy of the account's own file: a new entry on the same blob, as `create`
306
+ // does for bytes the caller already holds
307
+ const copy = await this.insertReady(orgId, accountId, own.blob_id, {
308
+ name,
309
+ contentType: own.content_type,
310
+ size: Number(own.size),
311
+ sha256: own.sha256 ?? input.sha256,
312
+ pages: own.pages,
313
+ });
314
+ if (copy !== null)
315
+ return { ...copy, existing: false };
316
+ }
317
+ }
318
+ this.storage.assertAvailable();
319
+ const size = input.bytes.byteLength;
320
+ const contentType = this.admitType({ contentType: input.contentType, size });
321
+ if (!sniffMatches(contentType, input.bytes.subarray(0, SNIFF_BYTES))) {
322
+ throw new ApiError("file.type_not_allowed", `File content is not ${contentType}`);
323
+ }
324
+ // two concurrent calls may both miss this and insert one entry each: benign, both are valid
325
+ // files of the account on the same blob (the person may delete one); no lock is worth it
326
+ const same = await this.db
327
+ .selectFrom("files")
328
+ .select(["id", "name", "content_type", "size", "status"])
329
+ .where("org_id", "=", orgId)
330
+ .where("account_id", "=", accountId)
331
+ .where("status", "=", "ready")
332
+ .where("sha256", "=", input.sha256)
333
+ .where("content_type", "=", contentType)
334
+ .where("name", "=", name)
335
+ .orderBy("created_at", "desc")
336
+ .limit(1)
337
+ .executeTakeFirst();
338
+ if (same)
339
+ return { ...viewOf(same), existing: true };
340
+ const pages = contentType === "application/pdf" ? countPdfPages(input.bytes) || null : null;
341
+ for (let attempt = 1; attempt <= ADD_BLOB_ATTEMPTS; attempt++) {
342
+ const blob = await this.blobs.ensureFromBytes(orgId, input.sha256, input.bytes, {
343
+ contentType,
344
+ ...(input.signal !== undefined && { signal: input.signal }),
345
+ });
346
+ const added = await this.insertReady(orgId, accountId, blob.id, {
347
+ name,
348
+ contentType,
349
+ size,
350
+ sha256: input.sha256,
351
+ pages,
352
+ });
353
+ if (added !== null)
354
+ return { ...added, existing: false };
355
+ }
356
+ throw new FileBlobClaimedError();
357
+ }
358
+ /**
359
+ * The transaction of {@link addFromBytes}: the blob locked ready, then a `ready` upload file of
360
+ * the account on it. Null when a deletion claimed the blob (nothing written).
361
+ */
362
+ async insertReady(orgId, accountId, blobId, f) {
363
+ const blob = await this.blobs.lockReady(orgId, blobId);
364
+ if (!blob)
365
+ return null;
366
+ const id = randomUUID();
367
+ await this.db.db
368
+ .insertInto("files")
369
+ .values({
370
+ id,
371
+ org_id: orgId,
372
+ account_id: accountId,
373
+ blob_id: blob.id,
374
+ ref_key: blob.objectKey,
375
+ ref_etag: blob.etag,
376
+ name: f.name,
377
+ content_type: f.contentType,
378
+ size: f.size,
379
+ pages: f.pages,
380
+ origin: "upload",
381
+ status: "ready",
382
+ sha256: f.sha256,
383
+ upload_purpose: "library",
384
+ expires_at: null,
385
+ })
386
+ .execute();
387
+ return { id, name: f.name, contentType: f.contentType, size: f.size, status: "ready" };
388
+ }
389
+ /**
390
+ * The instant path of {@link create}: a new file on the blob of one of the caller's own files
391
+ * with this sha256, or undefined. The blob passes {@link BlobsService.lockReady}, so a deletion
392
+ * claiming it concurrently either waits for this file or makes the caller upload.
393
+ */
394
+ async createOnOwnBlob(orgId, accountId, input) {
395
+ const trx = this.db.db;
396
+ const mine = await trx
397
+ .selectFrom("files")
398
+ .innerJoin("blobs", "blobs.id", "files.blob_id")
399
+ .select(["files.blob_id", "files.pages"])
400
+ .where("files.org_id", "=", orgId)
401
+ .where("files.account_id", "=", accountId)
402
+ .where("files.sha256", "=", input.sha256)
403
+ .where("files.content_type", "=", input.contentType)
404
+ .where("files.size", "=", String(input.size))
405
+ .where((eb) => eb.or([
406
+ eb("files.status", "=", "ready"),
407
+ eb.and([eb("files.status", "=", "draft"), eb("files.expires_at", ">", sql `now()`)]),
408
+ ]))
409
+ .where("blobs.org_id", "=", orgId)
410
+ .where("blobs.status", "=", "ready")
411
+ .limit(1)
412
+ .executeTakeFirst();
413
+ if (!mine?.blob_id)
414
+ return undefined;
415
+ const blob = await this.blobs.lockReady(orgId, mine.blob_id);
416
+ if (!blob)
417
+ return undefined;
418
+ const id = randomUUID();
419
+ const draft = input.purpose === "composer";
420
+ const ttlHours = this.config.get().attachments.unboundTtlHours;
421
+ await trx
422
+ .insertInto("files")
423
+ .values({
424
+ id,
425
+ org_id: orgId,
426
+ account_id: accountId,
427
+ blob_id: blob.id,
428
+ // the reference the model may see stays this blob's after a later merge
429
+ ref_key: blob.objectKey,
430
+ ref_etag: blob.etag,
431
+ name: input.name,
432
+ content_type: input.contentType,
433
+ size: input.size,
434
+ pages: mine.pages,
435
+ origin: "upload",
436
+ status: draft ? "draft" : "ready",
437
+ sha256: input.sha256,
438
+ upload_purpose: input.purpose,
439
+ expires_at: draft ? sql `now() + make_interval(hours => ${ttlHours})` : null,
440
+ })
441
+ .execute();
442
+ return {
443
+ id,
444
+ name: input.name,
445
+ contentType: input.contentType,
446
+ size: input.size,
447
+ status: draft ? "draft" : "ready",
448
+ };
449
+ }
450
+ /**
451
+ * Finishes an upload (the uploader only; a file already `draft` or `ready` is answered as it
452
+ * is; an expired upload is `file.not_found`):
453
+ *
454
+ * - the staging object missing, or smaller than declared → `file.not_ready` (upload again);
455
+ * - larger than declared, a stored type or a signature that does not match →
456
+ * `file.type_not_allowed` / `file.too_large`, and the upload is rejected;
457
+ * - the whole object is read; a sha256 other than the declared one → `file.hash_mismatch`, and
458
+ * the upload is rejected.
459
+ *
460
+ * A rejected upload expires at once and owes its staging object's deletion (no direct delete:
461
+ * the outbox handler re-reads the row). Otherwise the verified bytes are copied to a new
462
+ * kernel-owned blob (intent first) and one transaction, holding the file row, settles that blob
463
+ * and makes the file `draft` (composer, expiring after `attachments.unboundTtlHours`) or `ready`
464
+ * (library), owing the staging object's deletion. The same work runs whether or not the org held
465
+ * these bytes already.
466
+ */
467
+ async finalize(orgId, accountId, fileId) {
468
+ this.storage.assertAvailable();
469
+ const row = await this.db
470
+ .selectFrom("files")
471
+ .select(UPLOAD_COLUMNS)
472
+ .select(sql `expires_at IS NOT NULL AND expires_at <= now()`.as("expired"))
473
+ .where("id", "=", fileId)
474
+ .where("org_id", "=", orgId)
475
+ .where("account_id", "=", accountId)
476
+ .where("origin", "=", "upload")
477
+ .where("status", "in", ["uploading", "draft", "ready"])
478
+ .executeTakeFirst();
479
+ if (!row)
480
+ throw notFound();
481
+ if (row.status !== "uploading")
482
+ return viewOf(row);
483
+ if (row.expired)
484
+ throw notFound();
485
+ const size = Number(row.size);
486
+ const key = row.staging_key ?? stagingObjectKey(row.id);
487
+ const store = this.storage.kernel(orgId);
488
+ const head = await store.head(key);
489
+ if (!head || head.size < size) {
490
+ throw new ApiError("file.not_ready", head
491
+ ? `Uploaded file is ${head.size} bytes, but ${size} bytes were declared; upload it again`
492
+ : "The file has not been uploaded yet");
493
+ }
494
+ if (head.size > size) {
495
+ await this.reject(orgId, accountId, row);
496
+ throw new ApiError("file.too_large", "Uploaded file is larger than declared");
497
+ }
498
+ if (normalizeContentType(head.contentType) !== row.content_type) {
499
+ await this.reject(orgId, accountId, row);
500
+ throw new ApiError("file.type_not_allowed", "Uploaded file type does not match");
501
+ }
502
+ return this.finalizeSlots.run(() => this.verifyAndCopy(orgId, accountId, row, key, size));
503
+ }
504
+ /**
505
+ * The bounded part of {@link finalize}: reads the staging object, checks its signature and hash,
506
+ * copies the verified bytes to a new blob and commits.
507
+ */
508
+ async verifyAndCopy(orgId, accountId, row, key, size) {
509
+ const store = this.storage.kernel(orgId);
510
+ const read = await this.readUpload(store, key, row.content_type, size);
511
+ if (!read) {
512
+ throw new ApiError("file.not_ready", "The uploaded file changed while it was checked; upload it again");
513
+ }
514
+ if (!read.sniffed) {
515
+ await this.reject(orgId, accountId, row);
516
+ throw new ApiError("file.type_not_allowed", `Uploaded file content is not ${row.content_type}`);
517
+ }
518
+ // a migrated upload declared no hash: the computed one stands
519
+ if (row.sha256 !== null && read.sha256 !== row.sha256) {
520
+ await this.reject(orgId, accountId, row);
521
+ throw new ApiError("file.hash_mismatch", "The uploaded bytes do not match the declared sha256; upload the file again");
522
+ }
523
+ const own = await this.blobs.writeVerified(orgId, read.bytes, {
524
+ contentType: row.content_type,
525
+ });
526
+ const done = await this.commitFinalize(orgId, accountId, row, own.id, read);
527
+ if (done === null)
528
+ throw notFound();
529
+ return done;
530
+ }
531
+ /**
532
+ * Streams the whole staging object once (bounded by the declared size and a timeout): its bytes,
533
+ * sha256, leading bytes' signature check and, for a PDF, its page count. Null when the object
534
+ * vanished or is not the declared size.
535
+ */
536
+ async readUpload(store, key, contentType, size) {
537
+ const got = await store.get(key, { signal: AbortSignal.timeout(READ_TIMEOUT_MS) });
538
+ if (!got)
539
+ return null;
540
+ if (got.head.size !== size) {
541
+ await got.body.cancel().catch(() => { });
542
+ return null;
543
+ }
544
+ const hash = createHash("sha256");
545
+ const chunks = [];
546
+ let total = 0;
547
+ const reader = got.body.getReader();
548
+ for (;;) {
549
+ const { done, value } = await reader.read();
550
+ if (done)
551
+ break;
552
+ total += value.byteLength;
553
+ if (total > size) {
554
+ await reader.cancel().catch(() => { });
555
+ return null;
556
+ }
557
+ hash.update(value);
558
+ chunks.push(value);
559
+ }
560
+ if (total !== size)
561
+ return null;
562
+ const bytes = Buffer.concat(chunks, total);
563
+ return {
564
+ bytes,
565
+ sha256: hash.digest("hex"),
566
+ pages: contentType === "application/pdf" ? countPdfPages(bytes) || null : null,
567
+ sniffed: sniffMatches(contentType, bytes.subarray(0, SNIFF_BYTES)),
568
+ };
569
+ }
570
+ /**
571
+ * A rejected upload: under the file row's lock, an upload still in progress expires now and its
572
+ * staging object's deletion is owed (the cleanup job then drops the row).
573
+ */
574
+ async reject(orgId, accountId, row) {
575
+ const trx = this.db.db;
576
+ const locked = await trx
577
+ .selectFrom("files")
578
+ .select("status")
579
+ .where("id", "=", row.id)
580
+ .where("org_id", "=", orgId)
581
+ .where("account_id", "=", accountId)
582
+ .forUpdate()
583
+ .executeTakeFirst();
584
+ if (locked?.status !== "uploading")
585
+ return;
586
+ await trx
587
+ .updateTable("files")
588
+ .set({ expires_at: sql `now()` })
589
+ .where("id", "=", row.id)
590
+ .where("org_id", "=", orgId)
591
+ .execute();
592
+ await oweStagingDelete(this.outbox, orgId, row.id, row.staging_key ?? stagingObjectKey(row.id), deferred(afterUploadForm(row.created_at)));
593
+ }
594
+ /**
595
+ * The transaction of {@link finalize}: the file row locked and still an unexpired upload, the new
596
+ * blob settled ({@link BlobsService.settle}), the file pointed at the result and set `draft` /
597
+ * `ready` with the verified hash, the staging object's deletion owed. When the file is no longer
598
+ * an upload in progress (a concurrent finalize, a discard, the cleanup) the new blob is released
599
+ * instead (`deleting`, its deletion owed); the answer is then the file as it is, or null when it
600
+ * expired or is gone.
601
+ */
602
+ async commitFinalize(orgId, accountId, row, blobId, read) {
603
+ const trx = this.db.db;
604
+ const locked = await trx
605
+ .selectFrom("files")
606
+ .select(UPLOAD_COLUMNS)
607
+ .select(sql `expires_at IS NOT NULL AND expires_at <= now()`.as("expired"))
608
+ .where("id", "=", row.id)
609
+ .where("org_id", "=", orgId)
610
+ .where("account_id", "=", accountId)
611
+ .forUpdate()
612
+ .executeTakeFirst();
613
+ if (locked?.status !== "uploading" || locked.expired) {
614
+ await trx
615
+ .updateTable("blobs")
616
+ .set({ status: "deleting" })
617
+ .where("id", "=", blobId)
618
+ .where("org_id", "=", orgId)
619
+ .where("status", "=", "pending")
620
+ .execute();
621
+ await oweBlobDelete(this.outbox, orgId, blobId, deferred());
622
+ return locked && locked.status !== "uploading" && locked.status !== "deleted"
623
+ ? viewOf(locked)
624
+ : null;
625
+ }
626
+ const blob = await this.blobs.settle(orgId, blobId, read.sha256);
627
+ const draft = (locked.upload_purpose ?? "composer") === "composer";
628
+ const ttlHours = this.config.get().attachments.unboundTtlHours;
629
+ await trx
630
+ .updateTable("files")
631
+ .set({
632
+ blob_id: blob.id,
633
+ ref_key: blob.objectKey,
634
+ ref_etag: blob.etag,
635
+ status: draft ? "draft" : "ready",
636
+ sha256: read.sha256,
637
+ pages: read.pages,
638
+ expires_at: draft ? sql `now() + make_interval(hours => ${ttlHours})` : null,
639
+ })
640
+ .where("id", "=", row.id)
641
+ .where("org_id", "=", orgId)
642
+ .execute();
643
+ await oweStagingDelete(this.outbox, orgId, row.id, locked.staging_key ?? stagingObjectKey(row.id), deferred(afterUploadForm(locked.created_at)));
644
+ return viewOf({ ...locked, status: draft ? "draft" : "ready" });
645
+ }
646
+ /**
647
+ * A composer upload removed before it was sent (the uploader only; an `uploading` or `draft`
648
+ * file no conversation refers to, else `file.not_found`): `deleted`, with the deferred release of
649
+ * what it held owed (`file-release`, run by `BlobObjects.releaseFile`): the request does the same
650
+ * work whatever else points at its blob.
651
+ */
652
+ async discard(orgId, accountId, fileId) {
653
+ const trx = this.db.db;
654
+ const row = await trx
655
+ .selectFrom("files")
656
+ .select(UPLOAD_COLUMNS)
657
+ .where("id", "=", fileId)
658
+ .where("org_id", "=", orgId)
659
+ .where("account_id", "=", accountId)
660
+ .where("status", "in", ["uploading", "draft"])
661
+ .forUpdate()
662
+ .executeTakeFirst();
663
+ if (!row)
664
+ throw notFound();
665
+ const referenced = await trx
666
+ .selectFrom("conversation_files")
667
+ .select("file_id")
668
+ .where("org_id", "=", orgId)
669
+ .where("file_id", "=", fileId)
670
+ .limit(1)
671
+ .executeTakeFirst();
672
+ if (referenced)
673
+ throw notFound();
674
+ await trx
675
+ .updateTable("files")
676
+ .set({ status: "deleted", deleted_at: sql `now()`, expires_at: null })
677
+ .where("id", "=", fileId)
678
+ .where("org_id", "=", orgId)
679
+ .execute();
680
+ await oweFileRelease(this.outbox, orgId, fileId, deferred(afterUploadForm(row.created_at)));
681
+ }
682
+ /**
683
+ * Expires one batch of the org's `uploading` / `draft` files past `expires_at` (`FOR UPDATE SKIP
684
+ * LOCKED`, so concurrent runs never share a row): each becomes `deleted` with the deferred release
685
+ * of what it held owed (`file-release`). Returns how many it took.
686
+ */
687
+ async expireBatch(orgId) {
688
+ const trx = this.db.db;
689
+ const rows = await trx
690
+ .selectFrom("files")
691
+ .select(UPLOAD_COLUMNS)
692
+ .where("org_id", "=", orgId)
693
+ .where("status", "in", ["uploading", "draft"])
694
+ .where("expires_at", "<", sql `now()`)
695
+ .orderBy("expires_at")
696
+ .limit(CLEANUP_BATCH)
697
+ .forUpdate()
698
+ .skipLocked()
699
+ .execute();
700
+ if (rows.length === 0)
701
+ return 0;
702
+ await trx
703
+ .updateTable("files")
704
+ .set({ status: "deleted", deleted_at: sql `now()`, expires_at: null })
705
+ .where("org_id", "=", orgId)
706
+ .where("id", "in", rows.map((r) => r.id))
707
+ .execute();
708
+ for (const r of rows) {
709
+ await oweFileRelease(this.outbox, orgId, r.id, deferred(afterUploadForm(r.created_at)));
710
+ }
711
+ return rows.length;
712
+ }
713
+ /**
714
+ * Attaches the sender's files to a message, in the message's transaction (rows `FOR UPDATE`, in
715
+ * id order). The caller has already checked that the sender may write to the conversation (this
716
+ * checks only the files' ownership). Returns the content blocks the `user_message` carries
717
+ * (`ref`, in `ids` order):
718
+ *
719
+ * - more than `attachments.maxPerMessage`, or an id twice → `validation_failed` (path `files`);
720
+ * - not found, another account's, deleted, or an expired draft → `file.not_found`;
721
+ * - still uploading → `file.not_ready`;
722
+ * both with details `[{ path: "files", message, fileId }]`, for the web to mark the entry.
723
+ *
724
+ * Drafts become `ready` (no expiry; `source_conversation_id` set when it has none), and each
725
+ * file gets the conversation's `attached` reference (`first_seq` when given; an existing one is
726
+ * kept). A file may be attached in any number of the owner's conversations.
727
+ */
728
+ async attachForMessage(orgId, conversationId, accountId, ids, firstSeq) {
729
+ const unique = [...new Set(ids)];
730
+ const max = this.config.get().attachments.maxPerMessage;
731
+ if (ids.length > max) {
732
+ throw new ApiError("validation_failed", "Request validation failed", [
733
+ { path: "files", message: `At most ${max} files per message` },
734
+ ]);
735
+ }
736
+ if (unique.length !== ids.length) {
737
+ throw new ApiError("validation_failed", "Request validation failed", [
738
+ { path: "files", message: "Each file may appear only once per message" },
739
+ ]);
740
+ }
741
+ if (unique.length === 0)
742
+ return [];
743
+ const trx = this.db.db;
744
+ const rows = await trx
745
+ .selectFrom("files")
746
+ .select([
747
+ "id",
748
+ "account_id",
749
+ "name",
750
+ "content_type",
751
+ "size",
752
+ "status",
753
+ sql `expires_at IS NOT NULL AND expires_at <= now()`.as("expired"),
754
+ ])
755
+ .where("org_id", "=", orgId)
756
+ .where("id", "in", unique)
757
+ .orderBy("id")
758
+ .forUpdate()
759
+ .execute();
760
+ const byId = new Map(rows.map((r) => [r.id, r]));
761
+ const blocks = [];
762
+ const drafts = [];
763
+ for (const id of unique) {
764
+ const r = byId.get(id);
765
+ if (!r ||
766
+ r.account_id !== accountId ||
767
+ r.status === "deleted" ||
768
+ (r.status !== "ready" && r.expired)) {
769
+ const message = `File ${id} not found or expired`;
770
+ throw new ApiError("file.not_found", message, [{ path: "files", message, fileId: id }]);
771
+ }
772
+ if (r.status === "uploading") {
773
+ const message = `File ${id} has not been finalized`;
774
+ throw new ApiError("file.not_ready", message, [{ path: "files", message, fileId: id }]);
775
+ }
776
+ if (r.status === "draft")
777
+ drafts.push(id);
778
+ blocks.push(fileContentBlock({ id, name: r.name, contentType: r.content_type, size: Number(r.size) }));
779
+ }
780
+ if (drafts.length > 0) {
781
+ await trx
782
+ .updateTable("files")
783
+ .set({
784
+ status: "ready",
785
+ expires_at: null,
786
+ source_conversation_id: sql `coalesce(source_conversation_id, ${conversationId})`,
787
+ })
788
+ .where("org_id", "=", orgId)
789
+ .where("id", "in", drafts)
790
+ .execute();
791
+ }
792
+ await trx
793
+ .insertInto("conversation_files")
794
+ .values(unique.map((fileId) => ({
795
+ conversation_id: conversationId,
796
+ file_id: fileId,
797
+ org_id: orgId,
798
+ role: "attached",
799
+ first_seq: firstSeq ?? null,
800
+ })))
801
+ // a file the conversation delivered and the person now sends into it becomes `attached`
802
+ // (FetchAttachment copies only those); a repeated attachment keeps its first reference
803
+ .onConflict((oc) => oc
804
+ .columns(["conversation_id", "file_id"])
805
+ .doUpdateSet({ role: "attached" })
806
+ .where("conversation_files.role", "=", "delivered"))
807
+ .execute();
808
+ return blocks;
809
+ }
810
+ /**
811
+ * Deletes one of the account's ready files from the library (file library spec §6; the owner
812
+ * only, else `file.not_found`): `deleted` with `deleted_at`, its shares revoked
813
+ * (`file_deleted`) in the same transaction. Its bytes stay until the blob sweep frees them after
814
+ * `files.deletedRetentionDays`; conversations that referred to it show it as no longer available
815
+ * and later model requests render the placeholder. Each referring conversation gets a `files`
816
+ * change after the commit (a lost publish only delays the panel's refresh).
817
+ */
818
+ async delete(orgId, accountId, fileId) {
819
+ const trx = this.db.db;
820
+ const row = await trx
821
+ .selectFrom("files")
822
+ .select("id")
823
+ .where("id", "=", fileId)
824
+ .where("org_id", "=", orgId)
825
+ .where("account_id", "=", accountId)
826
+ .where("status", "=", "ready")
827
+ .forUpdate()
828
+ .executeTakeFirst();
829
+ if (!row)
830
+ throw notFound();
831
+ await trx
832
+ .updateTable("files")
833
+ .set({ status: "deleted", deleted_at: sql `now()`, expires_at: null })
834
+ .where("id", "=", fileId)
835
+ .where("org_id", "=", orgId)
836
+ .execute();
837
+ await revokeSharesIn(trx, { orgId, fileIds: [fileId] }, "file_deleted");
838
+ const refs = await trx
839
+ .selectFrom("conversation_files")
840
+ .select("conversation_id")
841
+ .where("org_id", "=", orgId)
842
+ .where("file_id", "=", fileId)
843
+ .execute();
844
+ for (const r of refs) {
845
+ afterCommit(() => this.eventLog.publishChanged(r.conversation_id, "files"));
846
+ }
847
+ }
848
+ };
849
+ __decorate([
850
+ Transactional()
851
+ ], LibraryFilesService.prototype, "insertReady", null);
852
+ __decorate([
853
+ Transactional()
854
+ ], LibraryFilesService.prototype, "createOnOwnBlob", null);
855
+ __decorate([
856
+ Transactional()
857
+ ], LibraryFilesService.prototype, "reject", null);
858
+ __decorate([
859
+ Transactional()
860
+ ], LibraryFilesService.prototype, "commitFinalize", null);
861
+ __decorate([
862
+ Transactional()
863
+ ], LibraryFilesService.prototype, "discard", null);
864
+ __decorate([
865
+ Transactional()
866
+ ], LibraryFilesService.prototype, "expireBatch", null);
867
+ __decorate([
868
+ Transactional({ propagation: "mandatory" })
869
+ ], LibraryFilesService.prototype, "attachForMessage", null);
870
+ __decorate([
871
+ Transactional()
872
+ ], LibraryFilesService.prototype, "delete", null);
873
+ LibraryFilesService = __decorate([
874
+ Injectable(),
875
+ __param(0, Inject(KernelDb)),
876
+ __param(1, Inject(TransactionHost)),
877
+ __param(2, Inject(StorageService)),
878
+ __param(3, Inject(KernelConfigService)),
879
+ __param(4, Inject(BlobsService)),
880
+ __param(5, Inject(OutboxService)),
881
+ __param(6, Inject(EventLog))
882
+ ], LibraryFilesService);
883
+ export { LibraryFilesService };