@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
@@ -19,23 +19,71 @@ import { UUID_RE } from "../ui/registry.js";
19
19
  import { effectiveExternalSharing, readExternalSharing } from "./settings.js";
20
20
  import { SHARE_CODE_RE } from "./share-code.js";
21
21
  /**
22
- * Whether its creator could still open the conversation the share was taken from: the conversation
23
- * predicate of `ConversationAccess.isAccessible` with the share's `created_by` as the viewer, over
24
- * the conversation of the share's org (so a row can never reach another org's conversation).
22
+ * Whether its creator may still have the share open (file sharing spec §1, file library spec §6).
23
+ * A share taken from a conversation: the conversation predicate of `ConversationAccess.isAccessible`
24
+ * with the share's `created_by` as the viewer, over the conversation of the share's org (so a row can
25
+ * never reach another org's conversation). A share made from the library (no conversation): the
26
+ * creator's account is active and still a member of the share's org.
25
27
  */
26
- export const creatorStillHasAccess = (eb) => eb.exists(eb
27
- .selectFrom("conversations")
28
- .select(sql `1`.as("one"))
29
- .whereRef("conversations.id", "=", "file_shares.conversation_id")
30
- .whereRef("conversations.org_id", "=", "file_shares.org_id")
31
- .where((c) => accessibleTo(sql.ref("file_shares.created_by"))(c)));
28
+ export const creatorStillHasAccess = (eb) => eb.or([
29
+ eb.and([
30
+ eb("file_shares.conversation_id", "is", null),
31
+ eb.exists(eb
32
+ .selectFrom("accounts")
33
+ .select(sql `1`.as("one"))
34
+ .whereRef("accounts.id", "=", "file_shares.created_by")
35
+ .where("accounts.status", "=", "active")),
36
+ eb.exists(eb
37
+ .selectFrom("memberships")
38
+ .select(sql `1`.as("one"))
39
+ .whereRef("memberships.account_id", "=", "file_shares.created_by")
40
+ .whereRef("memberships.org_id", "=", "file_shares.org_id")),
41
+ ]),
42
+ eb.exists(eb
43
+ .selectFrom("conversations")
44
+ .select(sql `1`.as("one"))
45
+ .whereRef("conversations.id", "=", "file_shares.conversation_id")
46
+ .whereRef("conversations.org_id", "=", "file_shares.org_id")
47
+ .where((c) => accessibleTo(sql.ref("file_shares.created_by"))(c))),
48
+ ]);
32
49
  /**
33
- * The live check of a share (file sharing spec §1), the one the open routes, the HTML document
34
- * token and share-scoped embed tokens use: not revoked, not expired, its snapshot not freed, the
35
- * org not deleted, its creator passes `ConversationAccess.isAccessible`'s predicates (active
36
- * account, still a member, the conversation and its tree root not deleted, the agent not deleted
37
- * and still visible to the creator), and for an external share the effective external sharing
38
- * switch allows it now. One query (plus the platform switch for an external share, read live), no
50
+ * Whether the share's bytes may still be served (file library spec §6): it points at a blob of its
51
+ * org that is `ready`, and the library file it was made from is not deleted and is still its
52
+ * creator's. Only a conversation's share may name no file (`source_file_id` is set null when the
53
+ * file row is purged; the conversation checks still hold it); a library share whose file row is
54
+ * gone never serves again, whether or not its revoke landed. `object_key` is never read: it stays only for old replicas
55
+ * during a rolling deploy.
56
+ */
57
+ export const shareSourceOk = (eb) => eb.and([
58
+ eb.exists(eb
59
+ .selectFrom("blobs")
60
+ .select(sql `1`.as("one"))
61
+ .whereRef("blobs.id", "=", "file_shares.blob_id")
62
+ .whereRef("blobs.org_id", "=", "file_shares.org_id")
63
+ .where("blobs.status", "=", "ready")),
64
+ eb.or([
65
+ eb.and([
66
+ eb("file_shares.source_file_id", "is", null),
67
+ eb("file_shares.conversation_id", "is not", null),
68
+ ]),
69
+ eb.exists(eb
70
+ .selectFrom("files")
71
+ .select(sql `1`.as("one"))
72
+ .whereRef("files.id", "=", "file_shares.source_file_id")
73
+ .whereRef("files.org_id", "=", "file_shares.org_id")
74
+ .whereRef("files.account_id", "=", "file_shares.created_by")
75
+ .where("files.status", "<>", "deleted")),
76
+ ]),
77
+ ]);
78
+ /**
79
+ * The live check of a share (file sharing spec §1, file library spec §6), the one the open routes,
80
+ * the HTML document token and share-scoped embed tokens use: not revoked, not expired, its blob
81
+ * `ready` and its source file not deleted and still the creator's ({@link shareSourceOk}), the org
82
+ * not deleted, its creator passes {@link creatorStillHasAccess} (for a conversation's share
83
+ * `ConversationAccess.isAccessible`'s predicates: active account, still a member, the conversation
84
+ * and its tree root not deleted, the agent not deleted and still visible to the creator; for a
85
+ * library share: active account, still a member), and for an external share the effective external
86
+ * sharing switch allows it now. One query (plus the platform switch for an external share, read live), no
39
87
  * cache: a cause going away (the switch back on) makes a share not expired live again.
40
88
  */
41
89
  let ShareLiveness = class ShareLiveness {
@@ -81,6 +129,9 @@ let ShareLiveness = class ShareLiveness {
81
129
  .selectFrom("file_shares")
82
130
  .innerJoin("orgs", "orgs.id", "file_shares.org_id")
83
131
  .innerJoin("accounts as creator", "creator.id", "file_shares.created_by")
132
+ .innerJoin("blobs", (j) => j
133
+ .onRef("blobs.id", "=", "file_shares.blob_id")
134
+ .onRef("blobs.org_id", "=", "file_shares.org_id"))
84
135
  .select([
85
136
  "file_shares.id",
86
137
  "file_shares.org_id",
@@ -92,19 +143,22 @@ let ShareLiveness = class ShareLiveness {
92
143
  "file_shares.name",
93
144
  "file_shares.content_type",
94
145
  "file_shares.size",
95
- "file_shares.object_key",
96
146
  "file_shares.generation",
97
147
  "file_shares.expires_at",
98
148
  "orgs.settings",
149
+ "blobs.id as blob_id",
150
+ "blobs.object_key as blob_object_key",
151
+ "blobs.size as blob_size",
152
+ "blobs.etag as blob_etag",
99
153
  ])
100
154
  .where("orgs.deleted_at", "is", null)
101
155
  .where("file_shares.revoked_at", "is", null)
102
- .where("file_shares.object_key", "is not", null)
103
156
  .where((eb) => eb.or([
104
157
  eb("file_shares.expires_at", "is", null),
105
158
  eb("file_shares.expires_at", ">", sql `now()`),
106
159
  ]))
107
- .where((eb) => creatorStillHasAccess(eb));
160
+ .where((eb) => creatorStillHasAccess(eb))
161
+ .where((eb) => shareSourceOk(eb));
108
162
  if (by.code !== undefined)
109
163
  q = q.where("file_shares.code", "=", by.code);
110
164
  if (by.id !== undefined)
@@ -121,7 +175,7 @@ let ShareLiveness = class ShareLiveness {
121
175
  .where("en.plugin", "=", plugin)));
122
176
  }
123
177
  const row = await q.executeTakeFirst();
124
- if (!row || row.object_key === null)
178
+ if (!row)
125
179
  return null;
126
180
  if (row.audience === "external") {
127
181
  const platform = await readExternalSharing(this.db.db, this.config, this.log);
@@ -140,7 +194,12 @@ let ShareLiveness = class ShareLiveness {
140
194
  name: row.name,
141
195
  contentType: row.content_type,
142
196
  size: Number(row.size),
143
- objectKey: row.object_key,
197
+ blob: {
198
+ id: row.blob_id,
199
+ objectKey: row.blob_object_key,
200
+ size: Number(row.blob_size),
201
+ etag: row.blob_etag,
202
+ },
144
203
  generation: row.generation,
145
204
  expiresAt: row.expires_at,
146
205
  };
@@ -1,7 +1,6 @@
1
1
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
- import type { OutboxService } from "../infra/outbox/outbox.service.js";
3
- /** The reasons of the revokes the kernel makes on its own (file sharing spec §9). */
4
- export type LifecycleRevokeReason = "conversation_deleted" | "member_offboarded" | "creator_lost_access";
2
+ /** The reasons of the revokes the kernel makes on its own (file sharing spec §9, file library §6). */
3
+ export type LifecycleRevokeReason = "conversation_deleted" | "member_offboarded" | "creator_lost_access" | "file_deleted";
5
4
  /** Which shares a lifecycle revoke covers. */
6
5
  export type LifecycleRevokeTarget = {
7
6
  conversationId: string;
@@ -12,15 +11,21 @@ export type LifecycleRevokeTarget = {
12
11
  /** The daily sweep's batch (with `creator_lost_access`). */
13
12
  | {
14
13
  shareIds: readonly string[];
14
+ }
15
+ /** The shares made from these library files (with `file_deleted`, in the deleting transaction). */
16
+ | {
17
+ orgId: string;
18
+ fileIds: readonly string[];
15
19
  };
16
20
  /**
17
21
  * In the caller's transaction: marks the matching unrevoked rows revoked with `reason` (no
18
- * `revoked_by`: the kernel revokes, the act that caused it is audited by its own flow) and owes each
19
- * current snapshot's deletion through the outbox (`share-object-delete-<id>-<generation>`), so the
20
- * snapshot is freed right away, not at the daily sweep. Expired rows are revoked too: their snapshot
21
- * is freed with the rest. With `creator_lost_access` the creator's access is checked again in the
22
- * `UPDATE` (a cause that went away since the sweep read the row keeps the share). Each row is
23
- * locked by the `UPDATE`; a refresh committing concurrently is serialized on the row lock, so the
24
- * generation read back is the one current at the revoke. Returns the number of rows revoked.
22
+ * `revoked_by`: the kernel revokes, the act that caused it is audited by its own flow). Expired rows
23
+ * are revoked too. With `creator_lost_access` the creator's access is checked again in the `UPDATE`
24
+ * (a cause that went away since the sweep read the row keeps the share). Each row is locked by the
25
+ * `UPDATE`; a refresh committing concurrently is serialized on the row lock. Returns the number of
26
+ * rows revoked.
27
+ *
28
+ * No deletion is owed: a share points at a blob (file library spec §1), which the blob sweep frees
29
+ * once no file or live share needs it; the share sweep stops pointing at it after the retention.
25
30
  */
26
- export declare function revokeSharesIn(db: KernelSchemaDb, outbox: Pick<OutboxService, "add">, where: LifecycleRevokeTarget, reason: LifecycleRevokeReason): Promise<number>;
31
+ export declare function revokeSharesIn(db: KernelSchemaDb, where: LifecycleRevokeTarget, reason: LifecycleRevokeReason): Promise<number>;
@@ -1,19 +1,21 @@
1
1
  import { sql } from "kysely";
2
2
  import { creatorStillHasAccess } from "./liveness.js";
3
- import { oweShareObjectDelete } from "./share-objects.js";
4
3
  /**
5
4
  * In the caller's transaction: marks the matching unrevoked rows revoked with `reason` (no
6
- * `revoked_by`: the kernel revokes, the act that caused it is audited by its own flow) and owes each
7
- * current snapshot's deletion through the outbox (`share-object-delete-<id>-<generation>`), so the
8
- * snapshot is freed right away, not at the daily sweep. Expired rows are revoked too: their snapshot
9
- * is freed with the rest. With `creator_lost_access` the creator's access is checked again in the
10
- * `UPDATE` (a cause that went away since the sweep read the row keeps the share). Each row is
11
- * locked by the `UPDATE`; a refresh committing concurrently is serialized on the row lock, so the
12
- * generation read back is the one current at the revoke. Returns the number of rows revoked.
5
+ * `revoked_by`: the kernel revokes, the act that caused it is audited by its own flow). Expired rows
6
+ * are revoked too. With `creator_lost_access` the creator's access is checked again in the `UPDATE`
7
+ * (a cause that went away since the sweep read the row keeps the share). Each row is locked by the
8
+ * `UPDATE`; a refresh committing concurrently is serialized on the row lock. Returns the number of
9
+ * rows revoked.
10
+ *
11
+ * No deletion is owed: a share points at a blob (file library spec §1), which the blob sweep frees
12
+ * once no file or live share needs it; the share sweep stops pointing at it after the retention.
13
13
  */
14
- export async function revokeSharesIn(db, outbox, where, reason) {
14
+ export async function revokeSharesIn(db, where, reason) {
15
15
  if ("shareIds" in where && where.shareIds.length === 0)
16
16
  return 0;
17
+ if ("fileIds" in where && where.fileIds.length === 0)
18
+ return 0;
17
19
  let q = db
18
20
  .updateTable("file_shares")
19
21
  .set({
@@ -28,16 +30,18 @@ export async function revokeSharesIn(db, outbox, where, reason) {
28
30
  else if ("shareIds" in where) {
29
31
  q = q.where("id", "in", [...where.shareIds]);
30
32
  }
33
+ else if ("fileIds" in where) {
34
+ const ids = [...where.fileIds];
35
+ q = q
36
+ .where("org_id", "=", where.orgId)
37
+ .where((eb) => eb.or([eb("source_file_id", "in", ids), eb("file_id", "in", ids)]));
38
+ }
31
39
  else {
32
40
  q = q.where("org_id", "=", where.orgId).where("created_by", "=", where.createdBy);
33
41
  }
34
42
  if (reason === "creator_lost_access") {
35
43
  q = q.where((eb) => eb.not(creatorStillHasAccess(eb)));
36
44
  }
37
- const revoked = await q.returning(["id", "org_id", "generation", "object_key"]).execute();
38
- for (const r of revoked) {
39
- if (r.object_key !== null)
40
- await oweShareObjectDelete(outbox, r.org_id, r.id, r.generation);
41
- }
45
+ const revoked = await q.returning(["id"]).execute();
42
46
  return revoked.length;
43
47
  }
@@ -1,18 +1,18 @@
1
1
  import { KernelDb } from "../infra/database/kernel-db.js";
2
- import { TransactionHost } from "../infra/database/transaction-host.js";
3
- import type { OutboxService } from "../infra/outbox/outbox.service.js";
4
2
  import { StorageService } from "../storage/storage.service.js";
5
3
  /**
6
- * Share snapshots in object storage (file sharing spec §1, §2): generation `n` of share `id` is the
7
- * object `shares/<id>/<n>` under the org's kernel prefix (`kernel/<orgId>/`). A snapshot is written
8
- * before the row that names it; deleting one is owed through the outbox
9
- * ({@link SHARE_OBJECT_DELETE_JOB}) by the transaction that stops using it (a refresh, a revoke).
4
+ * Share snapshots of before the file library (file sharing spec §1, §2): generation `n` of share
5
+ * `id` was the object `shares/<id>/<n>` under the org's kernel prefix (`kernel/<orgId>/`), and
6
+ * deleting one was owed through the outbox ({@link SHARE_OBJECT_DELETE_JOB}). Shares now point at
7
+ * blobs (file library spec §1; 0190 made every snapshot a blob keeping its key) and nothing owes this
8
+ * job any more; its handler stays for the rows owed before the deploy and for old replicas during
9
+ * a rolling deploy, and never deletes a key a blob uses.
10
10
  */
11
11
  /** The object key of a share's generation, relative to the org's kernel prefix. */
12
12
  export declare const shareObjectKey: (shareId: string, generation: number) => string;
13
13
  /**
14
- * The lock (`LockService`) a refresh of one share holds while it copies and commits its next
15
- * generation; the daily sweep takes it before deleting a non-current generation of an existing share.
14
+ * The lock (`LockService`) a refresh of one share holds while it picks and commits its next
15
+ * generation, so two refreshes of one share never race for the same generation.
16
16
  */
17
17
  export declare const shareRefreshLockKey: (shareId: string) => string;
18
18
  /** The maintenance job that deletes one share snapshot. */
@@ -26,26 +26,21 @@ export interface ShareObjectDeleteData {
26
26
  generation: number;
27
27
  objectKey: string;
28
28
  }
29
- /** Owes the deletion of one share generation's snapshot, in the caller's transaction. */
30
- export declare function oweShareObjectDelete(outbox: Pick<OutboxService, "add">, orgId: string, shareId: string, generation: number): Promise<void>;
31
29
  /**
32
- * Runs a {@link SHARE_OBJECT_DELETE_JOB} (the maintenance processor dispatches it here). Delivered
33
- * twice, it is harmless: deleting a missing object is a no-op. A snapshot a share may still serve
34
- * (the row is neither revoked nor expired and names the key) is never deleted, whatever the job
35
- * says; a revoked or expired row whose snapshot is gone gets its `object_key` cleared (the row stays
36
- * for the audit trail and the lists' recent section). Expiry is final (no route moves
37
- * `expires_at`), so an expired row never serves again. The daily sweep (`ShareSweepJob`) calls
38
- * {@link deleteObject} directly for expired shares and orphan snapshots.
30
+ * Runs a {@link SHARE_OBJECT_DELETE_JOB} (the maintenance processor dispatches it here) for the rows
31
+ * owed before the file library (or by an old replica during the rolling deploy). Delivered twice, it
32
+ * is harmless: deleting a missing object is a no-op. A key any blob of the org uses (0190 made every
33
+ * snapshot a blob keeping its key) is never deleted: the blob sweep owns it. A snapshot an old
34
+ * replica's share may still serve (the row is neither revoked nor expired and names the key) is never
35
+ * deleted either. `object_key` is never cleared (file library amendment K7: the contract migration
36
+ * drops the column).
39
37
  */
40
38
  export declare class ShareObjects {
41
39
  private readonly db;
42
- readonly txHost: TransactionHost;
43
40
  private readonly storage;
44
- constructor(db: KernelDb, txHost: TransactionHost, storage: Pick<StorageService, "kernel">);
41
+ constructor(db: KernelDb, storage: Pick<StorageService, "kernel">);
45
42
  /** Deletes the snapshot of one share generation; see the class comment. */
46
43
  deleteObject(data: ShareObjectDeleteData): Promise<void>;
47
- /** Clears a revoked or expired row's `object_key` once its snapshot is gone. */
48
- cleared(data: ShareObjectDeleteData): Promise<void>;
49
44
  }
50
45
  /** {@link ShareObjects} for the maintenance worker (storage and the database only). */
51
46
  export declare class ShareObjectsModule {
@@ -10,60 +10,41 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable, Module } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { KernelDb } from "../infra/database/kernel-db.js";
13
- import { TransactionHost } from "../infra/database/transaction-host.js";
14
- import { Transactional } from "../infra/database/transactional.decorator.js";
15
- import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
16
13
  import { StorageModule } from "../storage/storage.module.js";
17
14
  import { StorageService } from "../storage/storage.service.js";
18
15
  /**
19
- * Share snapshots in object storage (file sharing spec §1, §2): generation `n` of share `id` is the
20
- * object `shares/<id>/<n>` under the org's kernel prefix (`kernel/<orgId>/`). A snapshot is written
21
- * before the row that names it; deleting one is owed through the outbox
22
- * ({@link SHARE_OBJECT_DELETE_JOB}) by the transaction that stops using it (a refresh, a revoke).
16
+ * Share snapshots of before the file library (file sharing spec §1, §2): generation `n` of share
17
+ * `id` was the object `shares/<id>/<n>` under the org's kernel prefix (`kernel/<orgId>/`), and
18
+ * deleting one was owed through the outbox ({@link SHARE_OBJECT_DELETE_JOB}). Shares now point at
19
+ * blobs (file library spec §1; 0190 made every snapshot a blob keeping its key) and nothing owes this
20
+ * job any more; its handler stays for the rows owed before the deploy and for old replicas during
21
+ * a rolling deploy, and never deletes a key a blob uses.
23
22
  */
24
23
  /** The object key of a share's generation, relative to the org's kernel prefix. */
25
24
  export const shareObjectKey = (shareId, generation) => `shares/${shareId}/${generation}`;
26
25
  /**
27
- * The lock (`LockService`) a refresh of one share holds while it copies and commits its next
28
- * generation; the daily sweep takes it before deleting a non-current generation of an existing share.
26
+ * The lock (`LockService`) a refresh of one share holds while it picks and commits its next
27
+ * generation, so two refreshes of one share never race for the same generation.
29
28
  */
30
29
  export const shareRefreshLockKey = (shareId) => `share-refresh-${shareId}`;
31
30
  /** The maintenance job that deletes one share snapshot. */
32
31
  export const SHARE_OBJECT_DELETE_JOB = "share-object-delete";
33
32
  /** Deterministic outbox / BullMQ id of a snapshot's deletion (no `:`). */
34
33
  export const shareObjectDeleteJobId = (shareId, generation) => `share-object-delete-${shareId}-${generation}`;
35
- /** Owes the deletion of one share generation's snapshot, in the caller's transaction. */
36
- export async function oweShareObjectDelete(outbox, orgId, shareId, generation) {
37
- const data = {
38
- orgId,
39
- shareId,
40
- generation,
41
- objectKey: shareObjectKey(shareId, generation),
42
- };
43
- await outbox.add({
44
- queue: MAINTENANCE_QUEUE_NAME,
45
- name: SHARE_OBJECT_DELETE_JOB,
46
- jobId: shareObjectDeleteJobId(shareId, generation),
47
- data,
48
- orgId,
49
- });
50
- }
51
34
  /**
52
- * Runs a {@link SHARE_OBJECT_DELETE_JOB} (the maintenance processor dispatches it here). Delivered
53
- * twice, it is harmless: deleting a missing object is a no-op. A snapshot a share may still serve
54
- * (the row is neither revoked nor expired and names the key) is never deleted, whatever the job
55
- * says; a revoked or expired row whose snapshot is gone gets its `object_key` cleared (the row stays
56
- * for the audit trail and the lists' recent section). Expiry is final (no route moves
57
- * `expires_at`), so an expired row never serves again. The daily sweep (`ShareSweepJob`) calls
58
- * {@link deleteObject} directly for expired shares and orphan snapshots.
35
+ * Runs a {@link SHARE_OBJECT_DELETE_JOB} (the maintenance processor dispatches it here) for the rows
36
+ * owed before the file library (or by an old replica during the rolling deploy). Delivered twice, it
37
+ * is harmless: deleting a missing object is a no-op. A key any blob of the org uses (0190 made every
38
+ * snapshot a blob keeping its key) is never deleted: the blob sweep owns it. A snapshot an old
39
+ * replica's share may still serve (the row is neither revoked nor expired and names the key) is never
40
+ * deleted either. `object_key` is never cleared (file library amendment K7: the contract migration
41
+ * drops the column).
59
42
  */
60
43
  let ShareObjects = class ShareObjects {
61
44
  db;
62
- txHost;
63
45
  storage;
64
- constructor(db, txHost, storage) {
46
+ constructor(db, storage) {
65
47
  this.db = db;
66
- this.txHost = txHost;
67
48
  this.storage = storage;
68
49
  }
69
50
  /** Deletes the snapshot of one share generation; see the class comment. */
@@ -72,6 +53,14 @@ let ShareObjects = class ShareObjects {
72
53
  // never delete anything outside the share's own key, whatever the job data says
73
54
  throw new Error(`share-object-delete: unexpected object key for share ${data.shareId}`);
74
55
  }
56
+ const blob = await this.db
57
+ .selectFrom("blobs")
58
+ .select("id")
59
+ .where("org_id", "=", data.orgId)
60
+ .where("object_key", "=", data.objectKey)
61
+ .executeTakeFirst();
62
+ if (blob)
63
+ return;
75
64
  const row = await this.db
76
65
  .selectFrom("file_shares")
77
66
  .select([
@@ -87,31 +76,12 @@ let ShareObjects = class ShareObjects {
87
76
  const store = this.storage.kernel(data.orgId);
88
77
  if (await store.head(data.objectKey))
89
78
  await store.delete(data.objectKey);
90
- await this.cleared(data);
91
- }
92
- /** Clears a revoked or expired row's `object_key` once its snapshot is gone. */
93
- async cleared(data) {
94
- await this.db
95
- .updateTable("file_shares")
96
- .set({ object_key: null })
97
- .where("id", "=", data.shareId)
98
- .where("org_id", "=", data.orgId)
99
- .where("object_key", "=", data.objectKey)
100
- .where((eb) => eb.or([
101
- eb("revoked_at", "is not", null),
102
- eb.and([eb("expires_at", "is not", null), eb("expires_at", "<=", sql `now()`)]),
103
- ]))
104
- .execute();
105
79
  }
106
80
  };
107
- __decorate([
108
- Transactional()
109
- ], ShareObjects.prototype, "cleared", null);
110
81
  ShareObjects = __decorate([
111
82
  Injectable(),
112
83
  __param(0, Inject(KernelDb)),
113
- __param(1, Inject(TransactionHost)),
114
- __param(2, Inject(StorageService))
84
+ __param(1, Inject(StorageService))
115
85
  ], ShareObjects);
116
86
  export { ShareObjects };
117
87
  /** {@link ShareObjects} for the maintenance worker (storage and the database only). */
@@ -1,13 +1,13 @@
1
1
  import type { FastifyReply, FastifyRequest } from "fastify";
2
2
  import { type FileOutput } from "../conversations/files.js";
3
3
  import { ApiError } from "../errors.js";
4
+ import { BlobsService } from "../files/blobs.service.js";
4
5
  import { type PreviewerItem, PreviewerRegistry } from "../files/previewers.js";
5
6
  import { HtmlTokens } from "../html/html-token.js";
6
7
  import { KernelDb } from "../infra/database/kernel-db.js";
7
8
  import { TransactionHost } from "../infra/database/transaction-host.js";
8
9
  import { LockService } from "../infra/lock/lock.service.js";
9
10
  import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
10
- import { StorageService } from "../storage/storage.service.js";
11
11
  import { type LiveShare, ShareLiveness } from "./liveness.js";
12
12
  /** What `GET /api/v1/s/:code` answers (the web's `ShareMeta`). */
13
13
  export interface ShareMeta {
@@ -49,19 +49,23 @@ export declare function attachmentDisposition(name: string): string;
49
49
  * share needs a web session of an active member of the share's own org (not the session's current
50
50
  * org): without one 401 `share.sign_in_required`, a signed-in non-member 404. `ShareLiveness`
51
51
  * checks the share and its creator; this service checks the viewer. The bytes are always streamed
52
- * by the kernel from the snapshot, never a presigned URL; nothing lives in process memory (the
52
+ * by the kernel from the share's blob (`BlobsService.open`: size and etag checked), never a
53
+ * presigned URL; nothing lives in process memory (the
53
54
  * throttler and the open dedupe are Redis keys with a TTL).
54
55
  */
55
56
  export declare class ShareOpenService {
56
57
  private readonly db;
57
58
  readonly txHost: TransactionHost;
58
59
  private readonly liveness;
59
- private readonly storage;
60
+ /** The share's blob, size and etag checked (a replaced object is not the snapshot). */
61
+ private readonly blobs;
60
62
  private readonly tokens;
61
63
  private readonly locks;
62
64
  private readonly previewers;
63
65
  private readonly throttler;
64
- constructor(db: KernelDb, txHost: TransactionHost, liveness: Pick<ShareLiveness, "byCode">, storage: Pick<StorageService, "kernel">, tokens: Pick<HtmlTokens, "issue">, locks: Pick<LockService, "lease" | "releaseIf">, previewers: Pick<PreviewerRegistry, "forShare">, throttler: Pick<CredentialThrottler, "reserve" | "succeeded">);
66
+ constructor(db: KernelDb, txHost: TransactionHost, liveness: Pick<ShareLiveness, "byCode">,
67
+ /** The share's blob, size and etag checked (a replaced object is not the snapshot). */
68
+ blobs: Pick<BlobsService, "open">, tokens: Pick<HtmlTokens, "issue">, locks: Pick<LockService, "lease" | "releaseIf">, previewers: Pick<PreviewerRegistry, "forShare">, throttler: Pick<CredentialThrottler, "reserve" | "succeeded">);
65
69
  /**
66
70
  * The live share with this code that the request may open, after reserving a `share-open`
67
71
  * attempt; the attempt is refunded only when it is returned. See the class comment.
@@ -15,6 +15,7 @@ import { sql } from "kysely";
15
15
  import { isInlineArtifactType, isTextArtifactType } from "../conversations/artifacts.js";
16
16
  import { FILE_CONTENT_MAX_BYTES, previewKind, readPrefix, trimUtf8, } from "../conversations/files.js";
17
17
  import { ApiError } from "../errors.js";
18
+ import { BlobsService } from "../files/blobs.service.js";
18
19
  import { PreviewerRegistry } from "../files/previewers.js";
19
20
  import { HTML_TOKEN_TTL_SECONDS, HtmlTokens } from "../html/html-token.js";
20
21
  import { isHtmlType } from "../html/html-type.js";
@@ -24,7 +25,6 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
24
25
  import { Transactional } from "../infra/database/transactional.decorator.js";
25
26
  import { LockService } from "../infra/lock/lock.service.js";
26
27
  import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
27
- import { StorageService } from "../storage/storage.service.js";
28
28
  import { ShareLiveness } from "./liveness.js";
29
29
  /** The share-open throttler (`NAMED_THROTTLERS`): per client address, misses count. */
30
30
  const THROTTLER = ["share-open"];
@@ -66,23 +66,26 @@ export function attachmentDisposition(name) {
66
66
  * share needs a web session of an active member of the share's own org (not the session's current
67
67
  * org): without one 401 `share.sign_in_required`, a signed-in non-member 404. `ShareLiveness`
68
68
  * checks the share and its creator; this service checks the viewer. The bytes are always streamed
69
- * by the kernel from the snapshot, never a presigned URL; nothing lives in process memory (the
69
+ * by the kernel from the share's blob (`BlobsService.open`: size and etag checked), never a
70
+ * presigned URL; nothing lives in process memory (the
70
71
  * throttler and the open dedupe are Redis keys with a TTL).
71
72
  */
72
73
  let ShareOpenService = class ShareOpenService {
73
74
  db;
74
75
  txHost;
75
76
  liveness;
76
- storage;
77
+ blobs;
77
78
  tokens;
78
79
  locks;
79
80
  previewers;
80
81
  throttler;
81
- constructor(db, txHost, liveness, storage, tokens, locks, previewers, throttler) {
82
+ constructor(db, txHost, liveness,
83
+ /** The share's blob, size and etag checked (a replaced object is not the snapshot). */
84
+ blobs, tokens, locks, previewers, throttler) {
82
85
  this.db = db;
83
86
  this.txHost = txHost;
84
87
  this.liveness = liveness;
85
- this.storage = storage;
88
+ this.blobs = blobs;
86
89
  this.tokens = tokens;
87
90
  this.locks = locks;
88
91
  this.previewers = previewers;
@@ -146,7 +149,7 @@ let ShareOpenService = class ShareOpenService {
146
149
  }
147
150
  /** Streams the snapshot as `application/octet-stream` (spec §3); `download` adds the attachment name. */
148
151
  async content(share, download, reply) {
149
- const got = await this.storage.kernel(share.orgId).get(share.objectKey);
152
+ const got = await this.blobs.open(share.orgId, share.blob);
150
153
  if (!got)
151
154
  throw shareNotFound();
152
155
  sandboxedBytes(reply)
@@ -166,9 +169,9 @@ let ShareOpenService = class ShareOpenService {
166
169
  throw notPreviewable("Only text files have content");
167
170
  }
168
171
  const max = Math.min(limit, FILE_CONTENT_MAX_BYTES);
169
- const got = await this.storage
170
- .kernel(share.orgId)
171
- .get(share.objectKey, { range: { start: 0, end: max - 1 } });
172
+ const got = await this.blobs.open(share.orgId, share.blob, {
173
+ range: { start: 0, end: max - 1 },
174
+ });
172
175
  if (!got)
173
176
  throw shareNotFound();
174
177
  let body = await readPrefix(got.body, max);
@@ -190,7 +193,7 @@ let ShareOpenService = class ShareOpenService {
190
193
  async inline(share, reply) {
191
194
  if (!isInlineArtifactType(share.contentType))
192
195
  throw shareNotFound();
193
- const got = await this.storage.kernel(share.orgId).get(share.objectKey);
196
+ const got = await this.blobs.open(share.orgId, share.blob);
194
197
  if (!got)
195
198
  throw shareNotFound();
196
199
  const type = (share.contentType.split(";")[0] ?? "").trim().toLowerCase();
@@ -279,7 +282,7 @@ ShareOpenService = __decorate([
279
282
  __param(0, Inject(KernelDb)),
280
283
  __param(1, Inject(TransactionHost)),
281
284
  __param(2, Inject(ShareLiveness)),
282
- __param(3, Inject(StorageService)),
285
+ __param(3, Inject(BlobsService)),
283
286
  __param(4, Inject(HtmlTokens)),
284
287
  __param(5, Inject(LockService)),
285
288
  __param(6, Inject(PreviewerRegistry)),
@@ -1,13 +1,15 @@
1
1
  import type { z } from "zod";
2
2
  import { type Principal } from "../identity/principal.js";
3
3
  import { type OrgContext } from "../orgs/org.guard.js";
4
- import { CreateShareBody, ListSharesQuery, ShareFileParams, ShareIdParams } from "./shares.schemas.js";
4
+ import { CreateShareBody, LibraryShareParams, ListSharesQuery, ShareFileParams, ShareIdParams } from "./shares.schemas.js";
5
5
  import { type SharePolicy, SharesService, type ShareView } from "./shares.service.js";
6
6
  /**
7
- * Shares of conversation files (file sharing spec §2): `agents.use`, a person only (a service
8
- * token is refused by `requireUser`). Creating and listing a file's shares need the conversation's
9
- * owner (`ConversationAccess.isAccessible`, else `conversation.not_found`); refreshing needs the
10
- * creator, revoking the creator or an org admin (else `share.not_found`).
7
+ * Shares of files (file sharing spec §2, file library spec §6): `agents.use`, a person only (a
8
+ * service token is refused by `requireUser`). Creating and listing a conversation file's shares
9
+ * need the conversation's owner (`ConversationAccess.isAccessible`, else `conversation.not_found`);
10
+ * a library file's, the file's owner (else `file.not_found`); the anonymous guest creates none
11
+ * (`member.anonymous_guest`). Refreshing needs the creator, revoking the creator or an org admin
12
+ * (else `share.not_found`).
11
13
  */
12
14
  export declare class SharesController {
13
15
  private readonly shares;
@@ -21,6 +23,15 @@ export declare class SharesController {
21
23
  shares: ShareView[];
22
24
  policy: SharePolicy;
23
25
  }>;
26
+ /** Shares one of the caller's library files (no conversation): 201 `{ share }`. */
27
+ createForFile(principal: Principal, org: OrgContext, params: z.infer<typeof LibraryShareParams>, body: z.infer<typeof CreateShareBody>): Promise<{
28
+ share: ShareView;
29
+ }>;
30
+ /** The live and recent shares the caller made of one library file (any version of it). */
31
+ forLibraryFile(principal: Principal, org: OrgContext, params: z.infer<typeof LibraryShareParams>): Promise<{
32
+ shares: ShareView[];
33
+ policy: SharePolicy;
34
+ }>;
24
35
  /** "Update to latest": the newest available version as the next generation (creator only). */
25
36
  refresh(principal: Principal, org: OrgContext, params: z.infer<typeof ShareIdParams>): Promise<{
26
37
  share: ShareView;