@capybara-hq/kernel 0.1.0-rc.106 → 0.1.0-rc.108

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 (190) hide show
  1. package/bootstrap.json +13 -13
  2. package/dist/admin/admin.schemas.d.ts +3 -0
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/channels/channels.module.js +4 -3
  5. package/dist/channels/file-delivery.d.ts +26 -11
  6. package/dist/channels/file-delivery.js +32 -11
  7. package/dist/channels/outbound.d.ts +3 -3
  8. package/dist/channels/outbound.js +15 -13
  9. package/dist/config/schema.d.ts +3 -0
  10. package/dist/config/schema.js +12 -0
  11. package/dist/conversations/artifacts.d.ts +20 -17
  12. package/dist/conversations/artifacts.js +30 -37
  13. package/dist/conversations/attachments.controller.d.ts +6 -19
  14. package/dist/conversations/attachments.controller.js +8 -59
  15. package/dist/conversations/attachments.service.d.ts +30 -74
  16. package/dist/conversations/attachments.service.js +51 -193
  17. package/dist/conversations/conversations.module.js +4 -0
  18. package/dist/conversations/conversations.service.d.ts +10 -9
  19. package/dist/conversations/conversations.service.js +28 -11
  20. package/dist/conversations/event-log.d.ts +1 -0
  21. package/dist/conversations/events.d.ts +49 -27
  22. package/dist/conversations/events.js +54 -7
  23. package/dist/conversations/files.d.ts +66 -64
  24. package/dist/conversations/files.js +127 -147
  25. package/dist/conversations/prompt-suggestion-request.js +2 -1
  26. package/dist/conversations/prompt-suggestions.d.ts +3 -3
  27. package/dist/conversations/prompt-suggestions.js +11 -10
  28. package/dist/conversations/queue.service.js +7 -2
  29. package/dist/ctx/create-ctx.d.ts +3 -1
  30. package/dist/ctx/create-ctx.js +19 -1
  31. package/dist/db/kernel-schema.d.ts +80 -2
  32. package/dist/errors.d.ts +19 -0
  33. package/dist/errors.js +19 -0
  34. package/dist/evals/canonical-json.d.ts +7 -0
  35. package/dist/evals/canonical-json.js +21 -0
  36. package/dist/evals/reconstruct.js +13 -1
  37. package/dist/evals/recorded-tools.d.ts +0 -2
  38. package/dist/evals/recorded-tools.js +1 -16
  39. package/dist/evals/snapshot.d.ts +26 -3
  40. package/dist/evals/snapshot.js +110 -57
  41. package/dist/evals/worker.d.ts +4 -3
  42. package/dist/evals/worker.js +8 -4
  43. package/dist/extensions/host.d.ts +3 -1
  44. package/dist/extensions/host.js +2 -0
  45. package/dist/extensions/instance.d.ts +3 -1
  46. package/dist/extensions/instance.js +4 -0
  47. package/dist/extensions/ledger.d.ts +1 -1
  48. package/dist/files/blob-objects.d.ts +124 -0
  49. package/dist/files/blob-objects.js +341 -0
  50. package/dist/files/blob-sweep.job.d.ts +122 -0
  51. package/dist/files/blob-sweep.job.js +389 -0
  52. package/dist/files/blobs.service.d.ts +135 -0
  53. package/dist/files/blobs.service.js +300 -0
  54. package/dist/files/conversation-media.d.ts +41 -0
  55. package/dist/files/conversation-media.js +124 -0
  56. package/dist/files/deliveries.d.ts +64 -0
  57. package/dist/files/deliveries.js +156 -0
  58. package/dist/files/deliveries.module.d.ts +6 -0
  59. package/dist/files/deliveries.module.js +24 -0
  60. package/dist/files/draft-cleanup.job.d.ts +26 -0
  61. package/dist/files/draft-cleanup.job.js +93 -0
  62. package/dist/files/files.module.d.ts +1 -1
  63. package/dist/files/files.module.js +3 -2
  64. package/dist/files/hash-job.d.ts +127 -0
  65. package/dist/files/hash-job.js +447 -0
  66. package/dist/files/library-backfill.d.ts +63 -0
  67. package/dist/files/library-backfill.js +143 -0
  68. package/dist/files/library-files.service.d.ts +255 -0
  69. package/dist/files/library-files.service.js +883 -0
  70. package/dist/files/library-jobs.module.d.ts +8 -0
  71. package/dist/files/library-jobs.module.js +27 -0
  72. package/dist/files/library-query.d.ts +127 -0
  73. package/dist/files/library-query.js +322 -0
  74. package/dist/files/library-read.module.d.ts +9 -0
  75. package/dist/files/library-read.module.js +30 -0
  76. package/dist/files/library.controller.d.ts +77 -0
  77. package/dist/files/library.controller.js +235 -0
  78. package/dist/files/library.module.d.ts +9 -0
  79. package/dist/files/library.module.js +29 -0
  80. package/dist/files/library.schemas.d.ts +46 -0
  81. package/dist/files/library.schemas.js +49 -0
  82. package/dist/files/previewers.controller.d.ts +20 -0
  83. package/dist/files/previewers.controller.js +47 -0
  84. package/dist/files/previewers.d.ts +25 -11
  85. package/dist/files/previewers.js +43 -27
  86. package/dist/files/referenced-files.d.ts +150 -0
  87. package/dist/files/referenced-files.js +234 -0
  88. package/dist/html/html-document.controller.d.ts +8 -1
  89. package/dist/html/html-document.controller.js +19 -1
  90. package/dist/html/html-document.service.d.ts +19 -4
  91. package/dist/html/html-document.service.js +43 -22
  92. package/dist/html/html-token.d.ts +10 -1
  93. package/dist/html/html-token.js +14 -0
  94. package/dist/html/html.module.js +8 -1
  95. package/dist/http/api.module.js +5 -0
  96. package/dist/identity/settings.d.ts +26 -0
  97. package/dist/identity/settings.js +33 -2
  98. package/dist/infra/outbox/registry.d.ts +82 -0
  99. package/dist/infra/outbox/registry.js +74 -2
  100. package/dist/infra/throttler/named-throttlers.d.ts +2 -0
  101. package/dist/infra/throttler/named-throttlers.js +14 -0
  102. package/dist/lifecycle/kernel-lifecycle.js +6 -0
  103. package/dist/models/purposes.js +1 -1
  104. package/dist/orgs/offboarding.js +1 -1
  105. package/dist/orgs/settings.service.d.ts +48 -2
  106. package/dist/orgs/settings.service.js +63 -3
  107. package/dist/platform/exclusions.js +45 -8
  108. package/dist/platform/file-ref.d.ts +18 -3
  109. package/dist/platform/file-ref.js +22 -11
  110. package/dist/platform/operation.js +4 -0
  111. package/dist/platform/ops/admin.ops.js +5 -2
  112. package/dist/platform/ops/files.ops.d.ts +18 -0
  113. package/dist/platform/ops/files.ops.js +267 -0
  114. package/dist/platform/ops/org-settings.ops.js +6 -2
  115. package/dist/platform/ops/orgs.ops.js +1 -0
  116. package/dist/platform/ops/shares.ops.js +2 -2
  117. package/dist/platform/platform-ops.module.d.ts +2 -1
  118. package/dist/platform/platform-ops.module.js +5 -0
  119. package/dist/platform/route-schemas.js +3 -0
  120. package/dist/roles/worker.module.js +15 -1
  121. package/dist/runtime/compaction-settings.service.d.ts +13 -1
  122. package/dist/runtime/compaction-settings.service.js +16 -1
  123. package/dist/runtime/compaction.service.d.ts +3 -1
  124. package/dist/runtime/compaction.service.js +3 -1
  125. package/dist/runtime/context/build.d.ts +18 -1
  126. package/dist/runtime/context/build.js +19 -8
  127. package/dist/runtime/context/cache-expiry.d.ts +31 -0
  128. package/dist/runtime/context/cache-expiry.js +60 -0
  129. package/dist/runtime/context/cache-ttl.d.ts +18 -0
  130. package/dist/runtime/context/cache-ttl.js +30 -0
  131. package/dist/runtime/context/compaction.d.ts +9 -2
  132. package/dist/runtime/context/compaction.js +50 -17
  133. package/dist/runtime/context/in-context-compaction.d.ts +156 -0
  134. package/dist/runtime/context/in-context-compaction.js +310 -0
  135. package/dist/runtime/hook-calls.d.ts +2 -1
  136. package/dist/runtime/hook-calls.js +5 -2
  137. package/dist/runtime/maintenance.d.ts +10 -2
  138. package/dist/runtime/maintenance.js +48 -8
  139. package/dist/runtime/model-call.d.ts +34 -5
  140. package/dist/runtime/model-call.js +207 -22
  141. package/dist/runtime/providers.js +11 -1
  142. package/dist/runtime/run-steps.d.ts +4 -2
  143. package/dist/runtime/run-steps.js +10 -5
  144. package/dist/runtime/runtime.module.js +3 -0
  145. package/dist/shares/liveness.d.ts +26 -12
  146. package/dist/shares/liveness.js +79 -20
  147. package/dist/shares/revoke.d.ts +16 -11
  148. package/dist/shares/revoke.js +18 -14
  149. package/dist/shares/share-objects.d.ts +16 -21
  150. package/dist/shares/share-objects.js +25 -55
  151. package/dist/shares/share-open.service.d.ts +8 -4
  152. package/dist/shares/share-open.service.js +14 -11
  153. package/dist/shares/shares.controller.d.ts +16 -5
  154. package/dist/shares/shares.controller.js +39 -5
  155. package/dist/shares/shares.module.d.ts +4 -4
  156. package/dist/shares/shares.module.js +7 -6
  157. package/dist/shares/shares.schemas.d.ts +4 -0
  158. package/dist/shares/shares.schemas.js +2 -0
  159. package/dist/shares/shares.service.d.ts +93 -54
  160. package/dist/shares/shares.service.js +292 -131
  161. package/dist/shares/sweep.job.d.ts +18 -39
  162. package/dist/shares/sweep.job.js +47 -206
  163. package/dist/tools/builtins/artifacts.d.ts +21 -13
  164. package/dist/tools/builtins/artifacts.js +81 -51
  165. package/dist/tools/builtins/builtin-tools.d.ts +7 -1
  166. package/dist/tools/builtins/builtin-tools.js +17 -6
  167. package/dist/tools/builtins/conversation-files.d.ts +23 -13
  168. package/dist/tools/builtins/conversation-files.js +62 -83
  169. package/dist/tools/builtins/image/generate.d.ts +7 -1
  170. package/dist/tools/builtins/image/generate.js +1 -1
  171. package/dist/tools/builtins/platform.js +1 -0
  172. package/dist/tools/builtins/sandbox/common.d.ts +6 -2
  173. package/dist/tools/builtins/sandbox/deliver.js +6 -7
  174. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +6 -5
  175. package/dist/tools/builtins/sandbox/fetch-attachment.js +19 -12
  176. package/dist/tools/tools.module.js +6 -0
  177. package/dist/ui/call-extension.d.ts +6 -4
  178. package/dist/ui/call-extension.js +5 -4
  179. package/dist/ui/embed-token.js +6 -3
  180. package/dist/ui/registry.d.ts +21 -5
  181. package/dist/ui/registry.js +24 -6
  182. package/dist/ui/ui.schemas.d.ts +22 -0
  183. package/dist/ui/ui.schemas.js +22 -4
  184. package/dist/ui/views.controller.d.ts +13 -3
  185. package/dist/ui/views.controller.js +33 -2
  186. package/dist/ui/views.d.ts +29 -1
  187. package/dist/ui/views.js +131 -7
  188. package/package.json +3 -3
  189. package/src/migrations/0190_file_library.sql +285 -0
  190. package/src/migrations/0191_file_library_copy.sql +4 -0
@@ -11,9 +11,10 @@ import { randomUUID } from "node:crypto";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { ConversationAccess } from "../conversations/access.js";
14
- import { attachmentContentMatches } from "../conversations/attachments.service.js";
15
- import { ConversationFiles } from "../conversations/files.js";
14
+ import { ConversationFiles, FILE_VERSIONS_MAX } from "../conversations/files.js";
16
15
  import { ApiError } from "../errors.js";
16
+ import { BlobsService } from "../files/blobs.service.js";
17
+ import { ReferencedFiles } from "../files/referenced-files.js";
17
18
  import { avatarColumns, personAvatarUrl } from "../identity/account-avatar.js";
18
19
  import { audit } from "../identity/audit.js";
19
20
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -21,30 +22,31 @@ import { KernelDb } from "../infra/database/kernel-db.js";
21
22
  import { TransactionHost } from "../infra/database/transaction-host.js";
22
23
  import { Transactional } from "../infra/database/transactional.decorator.js";
23
24
  import { LockService } from "../infra/lock/lock.service.js";
24
- import { OutboxService } from "../infra/outbox/outbox.service.js";
25
25
  import { KERNEL_LOGGER } from "../infra/tokens.js";
26
+ import { isAnonymousGuest } from "../orgs/members.service.js";
26
27
  import { OrgLock } from "../orgs/org-lock.js";
27
28
  import { can } from "../orgs/roles.js";
28
29
  import { parseOrgSettings, readStoredOrgSettings } from "../orgs/settings.service.js";
29
- import { StorageService } from "../storage/storage.service.js";
30
30
  import { UUID_RE } from "../ui/registry.js";
31
- import { creatorStillHasAccess } from "./liveness.js";
31
+ import { creatorStillHasAccess, shareSourceOk } from "./liveness.js";
32
32
  import { effectiveExternalSharing, readExternalSharing, readShareMaxExpiry, } from "./settings.js";
33
33
  import { newShareCode } from "./share-code.js";
34
- import { oweShareObjectDelete, shareObjectKey, shareRefreshLockKey } from "./share-objects.js";
34
+ import { shareRefreshLockKey } from "./share-objects.js";
35
35
  /** Revoked or expired shares stay in the lists this long (the "recent" section). */
36
36
  export const SHARE_RECENT_DAYS = 7;
37
37
  /** The most shares one list returns (newest first). */
38
38
  export const SHARES_LIST_MAX = 500;
39
39
  /** Attempts at a unique code before giving up (a collision is ~2^-59 per pair). */
40
40
  const CODE_ATTEMPTS = 3;
41
- /** The refresh lock's lifetime without renewal (renewed while the copy runs). */
41
+ /** The refresh lock's lifetime without renewal. */
42
42
  const REFRESH_LOCK_TTL_MS = 30_000;
43
43
  /** How long a refresh waits for another refresh of the same share. */
44
44
  const REFRESH_LOCK_WAIT_MS = 10_000;
45
45
  const notFound = () => new ApiError("share.not_found", "Share not found");
46
46
  const fileUnavailable = (message = "The file is no longer available, so it cannot be shared") => new ApiError("share.file_unavailable", message);
47
47
  const conversationNotFound = () => new ApiError("conversation.not_found", "Conversation not found");
48
+ const fileNotFound = () => new ApiError("file.not_found", "File not found");
49
+ const guestCannotShare = () => new ApiError("member.anonymous_guest", "The anonymous guest of an organization cannot share files: sign in with your own account to share a file");
48
50
  const externalNotAllowed = (state) => new ApiError("share.external_not_allowed", state === "platform_denied"
49
51
  ? "External sharing is not allowed on this platform; a super admin must allow it first, then an org admin must turn it on in the organization settings."
50
52
  : "External sharing is off in this organization; an org admin can turn it on in the organization settings.");
@@ -61,20 +63,20 @@ let SharesService = class SharesService {
61
63
  db;
62
64
  txHost;
63
65
  files;
66
+ library;
67
+ blobs;
64
68
  access;
65
- storage;
66
- outbox;
67
69
  orgLock;
68
70
  locks;
69
71
  config;
70
72
  log;
71
- constructor(db, txHost, files, access, storage, outbox, orgLock, locks, config, log) {
73
+ constructor(db, txHost, files, library, blobs, access, orgLock, locks, config, log) {
72
74
  this.db = db;
73
75
  this.txHost = txHost;
74
76
  this.files = files;
77
+ this.library = library;
78
+ this.blobs = blobs;
75
79
  this.access = access;
76
- this.storage = storage;
77
- this.outbox = outbox;
78
80
  this.orgLock = orgLock;
79
81
  this.locks = locks;
80
82
  this.config = config;
@@ -94,12 +96,38 @@ let SharesService = class SharesService {
94
96
  }
95
97
  /**
96
98
  * Shares one file of the viewer's conversation (any version shown in the panel, or an
97
- * attachment sent in it). The snapshot is streamed into its object first, outside any
98
- * transaction; then {@link insertShare} writes the row and the `share.created` audit. A code
99
- * collision retries the insert with a new code (the object is keyed by the id, not the code).
99
+ * attachment sent in it): {@link insertShare} points the row at the file's blob. The anonymous
100
+ * guest cannot share (`member.anonymous_guest`).
100
101
  */
101
102
  async create(orgId, accountId, conversationId, fileId, body, actor = {}) {
103
+ await this.rejectGuest(accountId);
102
104
  const file = await this.fileToShare(orgId, conversationId, accountId, fileId);
105
+ return this.insertWithCode(orgId, accountId, conversationId, file, body, actor);
106
+ }
107
+ /**
108
+ * Shares one of the viewer's library files (file library spec §6): the file must be the
109
+ * viewer's and `ready` (else `file.not_found`) with its bytes still stored (else
110
+ * `share.file_unavailable`). The share has no conversation. The anonymous guest cannot share.
111
+ */
112
+ async createForFile(orgId, accountId, fileId, body, actor = {}) {
113
+ await this.rejectGuest(accountId);
114
+ const f = await this.ownedReady(orgId, accountId, fileId);
115
+ if (f.blob === null ||
116
+ f.blob.status !== "ready" ||
117
+ (await this.blobs.head(orgId, f.blob)) === null) {
118
+ throw fileUnavailable();
119
+ }
120
+ const file = {
121
+ id: f.id,
122
+ name: f.name,
123
+ contentType: f.contentType,
124
+ sourcePath: f.origin === "upload" ? null : f.sourcePath,
125
+ blob: { id: f.blob.id, objectKey: f.blob.objectKey, size: f.blob.size, etag: f.blob.etag },
126
+ };
127
+ return this.insertWithCode(orgId, accountId, null, file, body, actor);
128
+ }
129
+ /** The policy checks of a new share, then its insert (a code collision retries with a new code). */
130
+ async insertWithCode(orgId, accountId, conversationId, file, body, actor) {
103
131
  if (body.audience === "external") {
104
132
  const policy = await this.policy(orgId);
105
133
  if (policy.external !== "allowed")
@@ -109,8 +137,6 @@ let SharesService = class SharesService {
109
137
  }
110
138
  }
111
139
  const id = randomUUID();
112
- const objectKey = shareObjectKey(id, 1);
113
- const size = await this.copy(orgId, file, objectKey);
114
140
  for (let attempt = 1;; attempt++) {
115
141
  try {
116
142
  await this.insertShare({
@@ -118,14 +144,9 @@ let SharesService = class SharesService {
118
144
  orgId,
119
145
  code: newShareCode(),
120
146
  conversationId,
121
- fileId: file.id,
122
- sourcePath: file.sourcePath,
147
+ file,
123
148
  accountId,
124
149
  audience: body.audience,
125
- name: file.name,
126
- contentType: file.contentType,
127
- size,
128
- objectKey,
129
150
  expiresInDays: body.expiresInDays,
130
151
  }, actor);
131
152
  break;
@@ -139,38 +160,50 @@ let SharesService = class SharesService {
139
160
  return this.viewOf(orgId, id);
140
161
  }
141
162
  /**
142
- * The row and audit of a new share. The row's org is read from the conversation here (locked
143
- * `FOR SHARE`, so a concurrent delete waits and then revokes this share too), never taken from
144
- * the caller; the viewer's access is checked again inside the transaction, since the copy ran
145
- * without one. Internal: called by {@link create} only.
163
+ * The row and audit of a new share. A conversation's share locks the conversation `FOR SHARE`
164
+ * (a concurrent delete waits and then revokes this share too) and checks the viewer's access
165
+ * again. Either kind locks the file row `FOR SHARE` while it is the creator's and `ready` (a
166
+ * concurrent delete waits and then revokes this share too) and the blob through
167
+ * `BlobsService.lockReady` (a blob a deletion claimed is never pointed at again); a file deleted
168
+ * or bytes claimed meanwhile → `share.file_unavailable`. Internal: called by {@link create} and
169
+ * {@link createForFile} only.
146
170
  */
147
171
  async insertShare(s, actor) {
148
- const conv = await this.db
149
- .selectFrom("conversations")
150
- .select("org_id")
151
- .where("id", "=", s.conversationId)
152
- .where("org_id", "=", s.orgId)
153
- .where("deleted_at", "is", null)
154
- .forShare()
155
- .executeTakeFirst();
156
- if (!conv || !(await this.access.isAccessible(conv.org_id, s.conversationId, s.accountId))) {
157
- throw conversationNotFound();
172
+ if (s.conversationId !== null) {
173
+ const conv = await this.db
174
+ .selectFrom("conversations")
175
+ .select("id")
176
+ .where("id", "=", s.conversationId)
177
+ .where("org_id", "=", s.orgId)
178
+ .where("deleted_at", "is", null)
179
+ .forShare()
180
+ .executeTakeFirst();
181
+ if (!conv || !(await this.access.isAccessible(s.orgId, s.conversationId, s.accountId))) {
182
+ throw conversationNotFound();
183
+ }
184
+ }
185
+ if (!(await this.lockFile(s.orgId, s.accountId, s.file.id, s.file.blob.id))) {
186
+ throw fileUnavailable();
158
187
  }
188
+ const blob = await this.blobs.lockReady(s.orgId, s.file.blob.id);
189
+ if (blob === null)
190
+ throw fileUnavailable();
159
191
  await this.db
160
192
  .insertInto("file_shares")
161
193
  .values({
162
194
  id: s.id,
163
- org_id: conv.org_id,
195
+ org_id: s.orgId,
164
196
  code: s.code,
165
197
  conversation_id: s.conversationId,
166
- file_id: s.fileId,
167
- source_path: s.sourcePath,
198
+ file_id: s.file.id,
199
+ source_file_id: s.file.id,
200
+ source_path: s.file.sourcePath,
168
201
  created_by: s.accountId,
169
202
  audience: s.audience,
170
- name: s.name,
171
- content_type: s.contentType,
172
- size: s.size,
173
- object_key: s.objectKey,
203
+ name: s.file.name,
204
+ content_type: s.file.contentType,
205
+ size: blob.size,
206
+ blob_id: blob.id,
174
207
  generation: 1,
175
208
  expires_at: s.expiresInDays === null
176
209
  ? null
@@ -180,18 +213,19 @@ let SharesService = class SharesService {
180
213
  await audit(this.db.db, {
181
214
  actorAccountId: s.accountId,
182
215
  ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }),
183
- orgId: conv.org_id,
216
+ orgId: s.orgId,
184
217
  action: "share.created",
185
218
  target: s.id,
186
219
  detail: { shareId: s.id, audience: s.audience, ...actor.auditDetail },
187
220
  });
188
221
  }
189
222
  /**
190
- * "Update to latest" (creator only): copies the newest available version of the share's source
191
- * path delivered after its current snapshot as the next generation under the same code, then
192
- * {@link commitRefresh} moves the row and owes the previous snapshot's deletion. Refreshes of one
193
- * share are serialized by a lock (taken outside any transaction), so two never write the same
194
- * generation's object.
223
+ * "Update to latest" (creator only): points the share at the creator's newest ready version of
224
+ * the same file (same source conversation and source path) made after the current one whose
225
+ * bytes are still stored ({@link nextVersion}), as the next generation under the same code; nothing
226
+ * is copied or deleted. A share of an upload has no versions (`validation_failed`). A
227
+ * conversation's share also needs the creator to still own the conversation. Refreshes of one
228
+ * share are serialized by a lock (taken outside any transaction).
195
229
  */
196
230
  async refresh(orgId, accountId, shareId, actor = {}) {
197
231
  if (!UUID_RE.test(shareId))
@@ -199,7 +233,15 @@ let SharesService = class SharesService {
199
233
  await this.locks.run(shareRefreshLockKey(shareId), { ttlMs: REFRESH_LOCK_TTL_MS, waitMs: REFRESH_LOCK_WAIT_MS }, async () => {
200
234
  const s = await this.db
201
235
  .selectFrom("file_shares")
202
- .select(["conversation_id", "file_id", "source_path", "generation"])
236
+ .select([
237
+ "id",
238
+ "conversation_id",
239
+ "file_id",
240
+ "source_file_id",
241
+ "source_path",
242
+ "generation",
243
+ "created_by",
244
+ ])
203
245
  .where("id", "=", shareId)
204
246
  .where("org_id", "=", orgId)
205
247
  .where("created_by", "=", accountId)
@@ -211,31 +253,33 @@ let SharesService = class SharesService {
211
253
  if (s.source_path === null) {
212
254
  throw new ApiError("validation_failed", "A share of an uploaded file cannot be updated: it has no newer versions. Share the new file instead.");
213
255
  }
214
- const next = await this.files.latestAvailable(orgId, s.conversation_id, accountId, s.source_path, { after: s.file_id });
256
+ if (s.conversation_id !== null &&
257
+ !(await this.access.isAccessible(orgId, s.conversation_id, accountId))) {
258
+ throw conversationNotFound();
259
+ }
260
+ const next = await this.nextVersion(orgId, s);
215
261
  if (next === null) {
216
262
  throw fileUnavailable("There is no newer available version of this file to share");
217
263
  }
218
- const generation = s.generation + 1;
219
- const objectKey = shareObjectKey(shareId, generation);
220
- const size = await this.copy(orgId, next, objectKey);
221
- const moved = await this.commitRefresh({ orgId, accountId, shareId, from: s.generation }, { fileId: next.id, name: next.name, contentType: next.contentType, size, objectKey }, actor);
222
- // revoked or expired while copying: the new snapshot was owed for deletion instead
264
+ const moved = await this.commitRefresh({ orgId, accountId, shareId, from: s.generation }, next, actor);
265
+ // revoked or expired meanwhile
223
266
  if (!moved)
224
267
  throw notFound();
225
268
  });
226
269
  return this.viewOf(orgId, shareId);
227
270
  }
228
271
  /**
229
- * The row move of a refresh: generation `from` → `from + 1` with the new snapshot, the previous
230
- * snapshot's deletion owed, `share.refreshed` audited. If the share was revoked or expired (or
231
- * moved) since the copy began, nothing moves and the new snapshot's deletion is owed instead;
232
- * returns whether it moved. Internal: called by {@link refresh} only.
272
+ * The row move of a refresh: generation `from` → `from + 1` pointing at `next`'s file and blob
273
+ * (the file locked while it is the creator's and `ready`, the blob through `lockReady`; either
274
+ * gone meanwhile → `share.file_unavailable`), `share.refreshed` audited. If the share was revoked
275
+ * or expired (or moved) meanwhile, nothing moves; returns whether it moved. Internal: called by
276
+ * {@link refresh} only.
233
277
  */
234
- async commitRefresh(at, snap, actor) {
278
+ async commitRefresh(at, next, actor) {
235
279
  const generation = at.from + 1;
236
280
  const row = await this.db
237
281
  .selectFrom("file_shares")
238
- .select(["object_key"])
282
+ .select("id")
239
283
  .where("id", "=", at.shareId)
240
284
  .where("org_id", "=", at.orgId)
241
285
  .where("created_by", "=", at.accountId)
@@ -244,26 +288,29 @@ let SharesService = class SharesService {
244
288
  .where(notExpired)
245
289
  .forUpdate()
246
290
  .executeTakeFirst();
247
- if (!row) {
248
- await this.oweDelete(at.orgId, at.shareId, generation);
291
+ if (!row)
249
292
  return false;
293
+ if (!(await this.lockFile(at.orgId, at.accountId, next.id, next.blob.id))) {
294
+ throw fileUnavailable();
250
295
  }
296
+ const blob = await this.blobs.lockReady(at.orgId, next.blob.id);
297
+ if (blob === null)
298
+ throw fileUnavailable();
251
299
  await this.db
252
300
  .updateTable("file_shares")
253
301
  .set({
254
302
  generation,
255
- file_id: snap.fileId,
256
- name: snap.name,
257
- content_type: snap.contentType,
258
- size: snap.size,
259
- object_key: snap.objectKey,
303
+ file_id: next.id,
304
+ source_file_id: next.id,
305
+ name: next.name,
306
+ content_type: next.contentType,
307
+ size: blob.size,
308
+ blob_id: blob.id,
260
309
  updated_at: sql `now()`,
261
310
  })
262
311
  .where("id", "=", at.shareId)
263
312
  .where("org_id", "=", at.orgId)
264
313
  .execute();
265
- if (row.object_key !== null)
266
- await this.oweDelete(at.orgId, at.shareId, at.from);
267
314
  await audit(this.db.db, {
268
315
  actorAccountId: at.accountId,
269
316
  ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }),
@@ -275,8 +322,8 @@ let SharesService = class SharesService {
275
322
  return true;
276
323
  }
277
324
  /**
278
- * Revokes a share (its creator, or an org admin with `org.update`; anyone else: `share.not_found`)
279
- * and owes its snapshot's deletion. Idempotent: an already revoked share is left as it is, with
325
+ * Revokes a share (its creator, or an org admin with `org.update`; anyone else: `share.not_found`).
326
+ * Nothing is owed: the blob sweep frees the blob once nothing needs it. Idempotent: an already revoked share is left as it is, with
280
327
  * no second audit. An admin's role is re-read under the org row lock (taken before the share row).
281
328
  */
282
329
  async revoke(orgId, accountId, shareId, actor = {}) {
@@ -304,7 +351,7 @@ let SharesService = class SharesService {
304
351
  }
305
352
  const s = await this.db
306
353
  .selectFrom("file_shares")
307
- .select(["revoked_at", "object_key", "generation"])
354
+ .select("revoked_at")
308
355
  .where("id", "=", shareId)
309
356
  .where("org_id", "=", orgId)
310
357
  .forUpdate()
@@ -324,8 +371,6 @@ let SharesService = class SharesService {
324
371
  .where("id", "=", shareId)
325
372
  .where("org_id", "=", orgId)
326
373
  .execute();
327
- if (s.object_key !== null)
328
- await this.oweDelete(orgId, shareId, s.generation);
329
374
  await audit(this.db.db, {
330
375
  actorAccountId: accountId,
331
376
  ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }),
@@ -351,17 +396,46 @@ let SharesService = class SharesService {
351
396
  ])
352
397
  : eb("file_shares.source_path", "=", f.sourcePath))
353
398
  .execute();
354
- const shares = rows.map((r) => this.toView(r, policy.external));
355
- // only a newer version that is still stored can be shared: confirm the log's answer
356
- for (const s of shares) {
357
- if (!s.newerVersion || s.state === "revoked" || s.sourcePath === null)
358
- continue;
359
- s.newerVersion =
360
- (await this.files.latestAvailable(orgId, conversationId, accountId, s.sourcePath, {
361
- after: s.fileId,
362
- })) !== null;
399
+ return { shares: await this.confirmed(orgId, rows, policy.external), policy };
400
+ }
401
+ /**
402
+ * The live and recent shares the viewer made of one of their library files (file library spec
403
+ * §6): of any version of it (the same source conversation and source path) or, for an upload, of
404
+ * the file itself, from a conversation or from the library; newest first, with the share policy.
405
+ * Not the viewer's ready file → `file.not_found`.
406
+ */
407
+ async forLibraryFile(orgId, accountId, fileId) {
408
+ const f = await this.ownedReady(orgId, accountId, fileId);
409
+ const policy = await this.policy(orgId);
410
+ let ids = [f.id];
411
+ if (f.origin !== "upload" && f.sourcePath !== null && f.sourceConversationId !== null) {
412
+ const versions = await this.db
413
+ .selectFrom("files")
414
+ .select("id")
415
+ .where("org_id", "=", orgId)
416
+ .where("account_id", "=", accountId)
417
+ .where("source_conversation_id", "=", f.sourceConversationId)
418
+ .where("source_path", "=", f.sourcePath)
419
+ .execute();
420
+ ids = [...new Set([f.id, ...versions.map((v) => v.id)])];
363
421
  }
364
- return { shares, policy };
422
+ const rows = await this.views(orgId)
423
+ .where("file_shares.created_by", "=", accountId)
424
+ .where((eb) => eb.or([eb("file_shares.source_file_id", "in", ids), eb("file_shares.file_id", "in", ids)]))
425
+ .execute();
426
+ return { shares: await this.confirmed(orgId, rows, policy.external), policy };
427
+ }
428
+ /** The views of a per-file list: a newer version counts only while its bytes are stored. */
429
+ async confirmed(orgId, rows, external) {
430
+ const shares = [];
431
+ for (const r of rows) {
432
+ const v = this.toView(r, external);
433
+ if (v.newerVersion && v.state !== "revoked") {
434
+ v.newerVersion = (await this.nextVersion(orgId, r)) !== null;
435
+ }
436
+ shares.push(v);
437
+ }
438
+ return shares;
365
439
  }
366
440
  /**
367
441
  * The org's live and recent shares: the actor's own (`mine`), or every member's (`all`, org
@@ -406,6 +480,7 @@ let SharesService = class SharesService {
406
480
  "file_shares.audience",
407
481
  "file_shares.conversation_id",
408
482
  "file_shares.file_id",
483
+ "file_shares.source_file_id",
409
484
  "file_shares.source_path",
410
485
  "file_shares.name",
411
486
  "file_shares.content_type",
@@ -421,19 +496,28 @@ let SharesService = class SharesService {
421
496
  "file_shares.revoke_reason",
422
497
  sql `file_shares.expires_at IS NOT NULL AND file_shares.expires_at <= now()`.as("expired"),
423
498
  creatorStillHasAccess(eb).as("creator_ok"),
424
- // a later delivery of the same source path in the conversation (refresh offered)
499
+ shareSourceOk(eb).as("source_ok"),
500
+ // a newer ready version (its blob ready too, as refresh requires) of the snapshot's file,
501
+ // the creator's (refresh offered): the group
502
+ // and order {@link nextVersion} uses, including its fallback when the current file row is
503
+ // gone (the share's conversation, versions made after the share last moved)
425
504
  sql `file_shares.source_path IS NOT NULL AND EXISTS (
426
- SELECT 1 FROM capybara.conversation_events later
427
- WHERE later.conversation_id = file_shares.conversation_id
428
- AND later.type = 'artifact_created'
429
- AND later.payload->>'sourcePath' = file_shares.source_path
430
- AND later.seq > (
431
- SELECT e.seq FROM capybara.conversation_events e
432
- WHERE e.conversation_id = file_shares.conversation_id
433
- AND e.type = 'artifact_created'
434
- AND e.payload->>'artifactId' = file_shares.file_id
435
- LIMIT 1
436
- )
505
+ SELECT 1 FROM capybara.files later
506
+ JOIN capybara.blobs b ON b.org_id = later.org_id AND b.id = later.blob_id
507
+ AND b.status = 'ready'
508
+ LEFT JOIN capybara.files cur
509
+ ON cur.org_id = file_shares.org_id
510
+ AND cur.id = coalesce(file_shares.source_file_id, file_shares.file_id)
511
+ WHERE later.org_id = file_shares.org_id
512
+ AND later.account_id = file_shares.created_by
513
+ AND later.status = 'ready'
514
+ AND later.origin <> 'upload'
515
+ AND later.source_path = file_shares.source_path
516
+ AND later.source_conversation_id = CASE WHEN cur.id IS NOT NULL
517
+ THEN cur.source_conversation_id ELSE file_shares.conversation_id END
518
+ AND CASE WHEN cur.id IS NOT NULL
519
+ THEN (later.created_at, later.id) > (cur.created_at, cur.id)
520
+ ELSE later.created_at > file_shares.updated_at END
437
521
  )`.as("newer_delivery"),
438
522
  ])
439
523
  .where("file_shares.org_id", "=", orgId)
@@ -459,7 +543,7 @@ let SharesService = class SharesService {
459
543
  ? "revoked"
460
544
  : r.expired
461
545
  ? "expired"
462
- : !r.creator_ok || (r.audience === "external" && external !== "allowed")
546
+ : !r.creator_ok || !r.source_ok || (r.audience === "external" && external !== "allowed")
463
547
  ? "suspended"
464
548
  : "live";
465
549
  const publicUrl = this.config.get().http.publicUrl;
@@ -490,12 +574,19 @@ let SharesService = class SharesService {
490
574
  };
491
575
  }
492
576
  /**
493
- * The file to share, after the viewer's access check: a delivered version, or an attachment whose
494
- * stored object is still the one finalize checked (else `share.file_unavailable`).
577
+ * The file to share, after the viewer's access check: a delivered version, or an attachment,
578
+ * whose stored bytes are still its blob's (else `share.file_unavailable`).
495
579
  */
496
580
  async fileToShare(orgId, conversationId, accountId, fileId) {
497
581
  try {
498
- return await this.files.file(orgId, conversationId, accountId, fileId);
582
+ const f = await this.files.file(orgId, conversationId, accountId, fileId);
583
+ return {
584
+ id: f.id,
585
+ name: f.name,
586
+ contentType: f.contentType,
587
+ sourcePath: f.sourcePath,
588
+ blob: f.blob,
589
+ };
499
590
  }
500
591
  catch (e) {
501
592
  if (e instanceof ApiError && e.code === "conversation.artifact_removed") {
@@ -504,35 +595,105 @@ let SharesService = class SharesService {
504
595
  throw e;
505
596
  }
506
597
  }
598
+ /** One of the account's library files while it is `ready`; else `file.not_found`. */
599
+ async ownedReady(orgId, accountId, fileId) {
600
+ if (!UUID_RE.test(fileId))
601
+ throw fileNotFound();
602
+ const f = await this.library.owned(orgId, accountId, fileId);
603
+ if (f.status !== "ready")
604
+ throw fileNotFound();
605
+ return f;
606
+ }
507
607
  /**
508
- * Streams the file's object into `objectKey` (never buffered whole); returns the snapshot's size.
509
- * The object is gone, or an upload's object is no longer the one finalize checked →
510
- * `share.file_unavailable`. Runs with no transaction open.
608
+ * In the caller's transaction: locks the file row `FOR SHARE` while it is the account's, `ready`
609
+ * and still on `blobId` (the blob the caller then locks; a hashing merge that moved the file
610
+ * meanwhile refuses), so a delete waits for the caller, then revokes what it wrote; false
611
+ * otherwise.
511
612
  */
512
- async copy(orgId, file, objectKey) {
513
- const store = this.storage.kernel(orgId);
514
- const got = await store.get(file.objectKey);
515
- if (!got)
516
- throw fileUnavailable();
517
- if (file.recorded && !attachmentContentMatches(file.recorded, got.head)) {
518
- await got.body.cancel().catch(() => { });
519
- throw fileUnavailable();
520
- }
521
- try {
522
- await store.put(objectKey, got.body, {
523
- contentType: file.contentType,
524
- size: got.head.size,
525
- });
526
- }
527
- catch (e) {
528
- await got.body.cancel().catch(() => { });
529
- throw e;
613
+ async lockFile(orgId, accountId, fileId, blobId) {
614
+ const row = await this.db
615
+ .selectFrom("files")
616
+ .select("id")
617
+ .where("id", "=", fileId)
618
+ .where("org_id", "=", orgId)
619
+ .where("account_id", "=", accountId)
620
+ .where("status", "=", "ready")
621
+ .where("blob_id", "=", blobId)
622
+ .forShare()
623
+ .executeTakeFirst();
624
+ return row !== undefined;
625
+ }
626
+ /**
627
+ * The creator's newest ready version of a share's file made after the current one (the same
628
+ * source conversation and source path; file library spec §6) whose bytes are still stored, or
629
+ * null. The current file is the share's `source_file_id` (else `file_id`); when it no longer
630
+ * exists, the group is the share's conversation and versions made after the share last moved.
631
+ * At most {@link FILE_VERSIONS_MAX} candidates are looked at. Reads storage: no transaction open.
632
+ */
633
+ async nextVersion(orgId, s) {
634
+ if (s.source_path === null)
635
+ return null;
636
+ const cur = await this.db
637
+ .selectFrom("files")
638
+ .select(["id", "source_conversation_id"])
639
+ .where("org_id", "=", orgId)
640
+ .where("id", "=", s.source_file_id ?? s.file_id)
641
+ .executeTakeFirst();
642
+ const group = cur ? cur.source_conversation_id : s.conversation_id;
643
+ if (group === null)
644
+ return null;
645
+ const rows = await this.db
646
+ .selectFrom("files as f")
647
+ .innerJoin("blobs as b", (j) => j.onRef("b.id", "=", "f.blob_id").on("b.org_id", "=", orgId))
648
+ .select([
649
+ "f.id",
650
+ "f.name",
651
+ "f.content_type",
652
+ "b.id as blob_id",
653
+ "b.object_key",
654
+ "b.size",
655
+ "b.etag",
656
+ ])
657
+ .where("f.org_id", "=", orgId)
658
+ .where("f.account_id", "=", s.created_by)
659
+ .where("f.status", "=", "ready")
660
+ .where("f.origin", "<>", "upload")
661
+ .where("f.source_conversation_id", "=", group)
662
+ .where("f.source_path", "=", s.source_path)
663
+ .where("b.status", "=", "ready")
664
+ // compared in SQL: a JS Date would drop the microseconds of the stored time
665
+ .where((eb) => cur
666
+ ? eb(sql `(f.created_at, f.id)`, ">", sql `(SELECT c.created_at, c.id FROM capybara.files c
667
+ WHERE c.org_id = ${orgId} AND c.id = ${cur.id})`)
668
+ : eb("f.created_at", ">", sql `(SELECT sh.updated_at FROM capybara.file_shares sh
669
+ WHERE sh.org_id = ${orgId} AND sh.id = ${s.id})`))
670
+ .orderBy("f.created_at", "desc")
671
+ .orderBy("f.id", "desc")
672
+ .limit(FILE_VERSIONS_MAX)
673
+ .execute();
674
+ for (const r of rows) {
675
+ const blob = {
676
+ id: r.blob_id,
677
+ objectKey: r.object_key,
678
+ size: Number(r.size),
679
+ etag: r.etag,
680
+ };
681
+ if ((await this.blobs.head(orgId, blob)) === null)
682
+ continue;
683
+ return {
684
+ id: r.id,
685
+ name: r.name,
686
+ contentType: r.content_type,
687
+ sourcePath: s.source_path,
688
+ blob,
689
+ };
530
690
  }
531
- return got.head.size;
691
+ return null;
532
692
  }
533
- /** Owes the deletion of one share generation's snapshot (in the caller's transaction). */
534
- async oweDelete(orgId, shareId, generation) {
535
- await oweShareObjectDelete(this.outbox, orgId, shareId, generation);
693
+ /** The anonymous guest (channel guests, no sign-in) cannot share (file library spec §2). */
694
+ async rejectGuest(accountId) {
695
+ if (await isAnonymousGuest(this.db.db, accountId))
696
+ throw guestCannotShare();
536
697
  }
537
698
  };
538
699
  __decorate([
@@ -549,9 +710,9 @@ SharesService = __decorate([
549
710
  __param(0, Inject(KernelDb)),
550
711
  __param(1, Inject(TransactionHost)),
551
712
  __param(2, Inject(ConversationFiles)),
552
- __param(3, Inject(ConversationAccess)),
553
- __param(4, Inject(StorageService)),
554
- __param(5, Inject(OutboxService)),
713
+ __param(3, Inject(ReferencedFiles)),
714
+ __param(4, Inject(BlobsService)),
715
+ __param(5, Inject(ConversationAccess)),
555
716
  __param(6, Inject(OrgLock)),
556
717
  __param(7, Inject(LockService)),
557
718
  __param(8, Inject(KernelConfigService)),