@capybara-hq/kernel 0.1.0-rc.106 → 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 (189) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/catalog/marketplaces.service.d.ts +1 -1
  3. package/dist/channels/channels.module.js +4 -3
  4. package/dist/channels/file-delivery.d.ts +26 -11
  5. package/dist/channels/file-delivery.js +32 -11
  6. package/dist/channels/outbound.d.ts +3 -3
  7. package/dist/channels/outbound.js +15 -13
  8. package/dist/config/schema.d.ts +3 -0
  9. package/dist/config/schema.js +12 -0
  10. package/dist/conversations/artifacts.d.ts +20 -17
  11. package/dist/conversations/artifacts.js +30 -37
  12. package/dist/conversations/attachments.controller.d.ts +6 -19
  13. package/dist/conversations/attachments.controller.js +8 -59
  14. package/dist/conversations/attachments.service.d.ts +30 -74
  15. package/dist/conversations/attachments.service.js +51 -193
  16. package/dist/conversations/conversations.module.js +4 -0
  17. package/dist/conversations/conversations.service.d.ts +10 -9
  18. package/dist/conversations/conversations.service.js +28 -11
  19. package/dist/conversations/event-log.d.ts +1 -0
  20. package/dist/conversations/events.d.ts +49 -27
  21. package/dist/conversations/events.js +54 -7
  22. package/dist/conversations/files.d.ts +66 -64
  23. package/dist/conversations/files.js +127 -147
  24. package/dist/conversations/prompt-suggestion-request.js +2 -1
  25. package/dist/conversations/prompt-suggestions.d.ts +3 -3
  26. package/dist/conversations/prompt-suggestions.js +11 -10
  27. package/dist/conversations/queue.service.js +7 -2
  28. package/dist/ctx/create-ctx.d.ts +3 -1
  29. package/dist/ctx/create-ctx.js +19 -1
  30. package/dist/db/kernel-schema.d.ts +80 -2
  31. package/dist/errors.d.ts +19 -0
  32. package/dist/errors.js +19 -0
  33. package/dist/evals/canonical-json.d.ts +7 -0
  34. package/dist/evals/canonical-json.js +21 -0
  35. package/dist/evals/reconstruct.js +13 -1
  36. package/dist/evals/recorded-tools.d.ts +0 -2
  37. package/dist/evals/recorded-tools.js +1 -16
  38. package/dist/evals/snapshot.d.ts +26 -3
  39. package/dist/evals/snapshot.js +110 -57
  40. package/dist/evals/worker.d.ts +4 -3
  41. package/dist/evals/worker.js +8 -4
  42. package/dist/extensions/host.d.ts +3 -1
  43. package/dist/extensions/host.js +2 -0
  44. package/dist/extensions/instance.d.ts +3 -1
  45. package/dist/extensions/instance.js +4 -0
  46. package/dist/extensions/ledger.d.ts +1 -1
  47. package/dist/files/blob-objects.d.ts +124 -0
  48. package/dist/files/blob-objects.js +341 -0
  49. package/dist/files/blob-sweep.job.d.ts +122 -0
  50. package/dist/files/blob-sweep.job.js +389 -0
  51. package/dist/files/blobs.service.d.ts +135 -0
  52. package/dist/files/blobs.service.js +300 -0
  53. package/dist/files/conversation-media.d.ts +41 -0
  54. package/dist/files/conversation-media.js +124 -0
  55. package/dist/files/deliveries.d.ts +64 -0
  56. package/dist/files/deliveries.js +156 -0
  57. package/dist/files/deliveries.module.d.ts +6 -0
  58. package/dist/files/deliveries.module.js +24 -0
  59. package/dist/files/draft-cleanup.job.d.ts +26 -0
  60. package/dist/files/draft-cleanup.job.js +93 -0
  61. package/dist/files/files.module.d.ts +1 -1
  62. package/dist/files/files.module.js +3 -2
  63. package/dist/files/hash-job.d.ts +127 -0
  64. package/dist/files/hash-job.js +447 -0
  65. package/dist/files/library-backfill.d.ts +63 -0
  66. package/dist/files/library-backfill.js +143 -0
  67. package/dist/files/library-files.service.d.ts +255 -0
  68. package/dist/files/library-files.service.js +883 -0
  69. package/dist/files/library-jobs.module.d.ts +8 -0
  70. package/dist/files/library-jobs.module.js +27 -0
  71. package/dist/files/library-query.d.ts +127 -0
  72. package/dist/files/library-query.js +322 -0
  73. package/dist/files/library-read.module.d.ts +9 -0
  74. package/dist/files/library-read.module.js +30 -0
  75. package/dist/files/library.controller.d.ts +77 -0
  76. package/dist/files/library.controller.js +235 -0
  77. package/dist/files/library.module.d.ts +9 -0
  78. package/dist/files/library.module.js +29 -0
  79. package/dist/files/library.schemas.d.ts +46 -0
  80. package/dist/files/library.schemas.js +49 -0
  81. package/dist/files/previewers.controller.d.ts +20 -0
  82. package/dist/files/previewers.controller.js +47 -0
  83. package/dist/files/previewers.d.ts +25 -11
  84. package/dist/files/previewers.js +43 -27
  85. package/dist/files/referenced-files.d.ts +150 -0
  86. package/dist/files/referenced-files.js +234 -0
  87. package/dist/html/html-document.controller.d.ts +8 -1
  88. package/dist/html/html-document.controller.js +19 -1
  89. package/dist/html/html-document.service.d.ts +19 -4
  90. package/dist/html/html-document.service.js +43 -22
  91. package/dist/html/html-token.d.ts +10 -1
  92. package/dist/html/html-token.js +14 -0
  93. package/dist/html/html.module.js +8 -1
  94. package/dist/http/api.module.js +5 -0
  95. package/dist/identity/settings.d.ts +26 -0
  96. package/dist/identity/settings.js +33 -2
  97. package/dist/infra/outbox/registry.d.ts +82 -0
  98. package/dist/infra/outbox/registry.js +74 -2
  99. package/dist/infra/throttler/named-throttlers.d.ts +2 -0
  100. package/dist/infra/throttler/named-throttlers.js +14 -0
  101. package/dist/lifecycle/kernel-lifecycle.js +6 -0
  102. package/dist/models/purposes.js +1 -1
  103. package/dist/orgs/offboarding.js +1 -1
  104. package/dist/orgs/settings.service.d.ts +48 -2
  105. package/dist/orgs/settings.service.js +63 -3
  106. package/dist/platform/exclusions.js +45 -8
  107. package/dist/platform/file-ref.d.ts +18 -3
  108. package/dist/platform/file-ref.js +22 -11
  109. package/dist/platform/operation.js +4 -0
  110. package/dist/platform/ops/admin.ops.js +5 -2
  111. package/dist/platform/ops/files.ops.d.ts +18 -0
  112. package/dist/platform/ops/files.ops.js +267 -0
  113. package/dist/platform/ops/org-settings.ops.js +6 -2
  114. package/dist/platform/ops/orgs.ops.js +1 -0
  115. package/dist/platform/ops/shares.ops.js +2 -2
  116. package/dist/platform/platform-ops.module.d.ts +2 -1
  117. package/dist/platform/platform-ops.module.js +5 -0
  118. package/dist/platform/route-schemas.js +3 -0
  119. package/dist/roles/worker.module.js +15 -1
  120. package/dist/runtime/compaction-settings.service.d.ts +13 -1
  121. package/dist/runtime/compaction-settings.service.js +16 -1
  122. package/dist/runtime/compaction.service.d.ts +3 -1
  123. package/dist/runtime/compaction.service.js +3 -1
  124. package/dist/runtime/context/build.d.ts +18 -1
  125. package/dist/runtime/context/build.js +19 -8
  126. package/dist/runtime/context/cache-expiry.d.ts +31 -0
  127. package/dist/runtime/context/cache-expiry.js +60 -0
  128. package/dist/runtime/context/cache-ttl.d.ts +18 -0
  129. package/dist/runtime/context/cache-ttl.js +30 -0
  130. package/dist/runtime/context/compaction.d.ts +9 -2
  131. package/dist/runtime/context/compaction.js +50 -17
  132. package/dist/runtime/context/in-context-compaction.d.ts +156 -0
  133. package/dist/runtime/context/in-context-compaction.js +310 -0
  134. package/dist/runtime/hook-calls.d.ts +2 -1
  135. package/dist/runtime/hook-calls.js +5 -2
  136. package/dist/runtime/maintenance.d.ts +10 -2
  137. package/dist/runtime/maintenance.js +48 -8
  138. package/dist/runtime/model-call.d.ts +34 -5
  139. package/dist/runtime/model-call.js +207 -22
  140. package/dist/runtime/providers.js +11 -1
  141. package/dist/runtime/run-steps.d.ts +4 -2
  142. package/dist/runtime/run-steps.js +10 -5
  143. package/dist/runtime/runtime.module.js +3 -0
  144. package/dist/shares/liveness.d.ts +26 -12
  145. package/dist/shares/liveness.js +79 -20
  146. package/dist/shares/revoke.d.ts +16 -11
  147. package/dist/shares/revoke.js +18 -14
  148. package/dist/shares/share-objects.d.ts +16 -21
  149. package/dist/shares/share-objects.js +25 -55
  150. package/dist/shares/share-open.service.d.ts +8 -4
  151. package/dist/shares/share-open.service.js +14 -11
  152. package/dist/shares/shares.controller.d.ts +16 -5
  153. package/dist/shares/shares.controller.js +39 -5
  154. package/dist/shares/shares.module.d.ts +4 -4
  155. package/dist/shares/shares.module.js +7 -6
  156. package/dist/shares/shares.schemas.d.ts +4 -0
  157. package/dist/shares/shares.schemas.js +2 -0
  158. package/dist/shares/shares.service.d.ts +93 -54
  159. package/dist/shares/shares.service.js +292 -131
  160. package/dist/shares/sweep.job.d.ts +18 -39
  161. package/dist/shares/sweep.job.js +47 -206
  162. package/dist/tools/builtins/artifacts.d.ts +21 -13
  163. package/dist/tools/builtins/artifacts.js +81 -51
  164. package/dist/tools/builtins/builtin-tools.d.ts +7 -1
  165. package/dist/tools/builtins/builtin-tools.js +17 -6
  166. package/dist/tools/builtins/conversation-files.d.ts +23 -13
  167. package/dist/tools/builtins/conversation-files.js +62 -83
  168. package/dist/tools/builtins/image/generate.d.ts +7 -1
  169. package/dist/tools/builtins/image/generate.js +1 -1
  170. package/dist/tools/builtins/platform.js +1 -0
  171. package/dist/tools/builtins/sandbox/common.d.ts +6 -2
  172. package/dist/tools/builtins/sandbox/deliver.js +6 -7
  173. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +6 -5
  174. package/dist/tools/builtins/sandbox/fetch-attachment.js +19 -12
  175. package/dist/tools/tools.module.js +6 -0
  176. package/dist/ui/call-extension.d.ts +6 -4
  177. package/dist/ui/call-extension.js +5 -4
  178. package/dist/ui/embed-token.js +6 -3
  179. package/dist/ui/registry.d.ts +21 -5
  180. package/dist/ui/registry.js +24 -6
  181. package/dist/ui/ui.schemas.d.ts +22 -0
  182. package/dist/ui/ui.schemas.js +22 -4
  183. package/dist/ui/views.controller.d.ts +13 -3
  184. package/dist/ui/views.controller.js +33 -2
  185. package/dist/ui/views.d.ts +29 -1
  186. package/dist/ui/views.js +131 -7
  187. package/package.json +3 -3
  188. package/src/migrations/0190_file_library.sql +285 -0
  189. package/src/migrations/0191_file_library_copy.sql +4 -0
@@ -1,56 +1,41 @@
1
1
  import { KernelDb } from "../infra/database/kernel-db.js";
2
2
  import { TransactionHost } from "../infra/database/transaction-host.js";
3
3
  import { LockService } from "../infra/lock/lock.service.js";
4
- import { OutboxService } from "../infra/outbox/outbox.service.js";
5
4
  import type { KernelLogger } from "../log.js";
6
- import { StorageService } from "../storage/storage.service.js";
7
- import { ShareObjects } from "./share-objects.js";
8
5
  /** The daily share sweep's name (scheduler key and lock; no `:`). */
9
6
  export declare const SHARE_SWEEP_JOB = "share-sweep";
10
7
  /** When the daily share sweep runs (the deployment's time zone). */
11
8
  export declare const SHARE_SWEEP_CRON = "40 3 * * *";
9
+ /** Shares expired or revoked longer ago than this stop pointing at their blob (rows kept). */
10
+ export declare const RETAIN_DAYS = 7;
12
11
  /** What one sweep did (logged; returned for tests). */
13
12
  export interface ShareSweepResult {
14
- /** Shares revoked with `creator_lost_access` (their snapshots owed for deletion). */
13
+ /** Shares revoked with `creator_lost_access`. */
15
14
  revoked: number;
16
- /** Snapshots of shares expired or revoked more than {@link RETAIN_DAYS} days ago deleted. */
15
+ /** Shares expired or revoked more than {@link RETAIN_DAYS} days ago that let go of their blob. */
17
16
  freed: number;
18
- /** Orphan objects under `shares/` deleted. */
19
- orphans: number;
20
17
  }
21
18
  /**
22
- * The daily share sweep (file sharing spec §9), a `@LockedCron` (once per tick across replicas,
23
- * provided only under `WorkerModule`). In order, with every storage call outside a transaction:
19
+ * The daily share sweep (file sharing spec §9, file library spec §7), a `@LockedCron` (once per
20
+ * tick across replicas, provided only under `WorkerModule`). In order:
24
21
  *
25
22
  * 1. revokes with `creator_lost_access` the unrevoked, unexpired shares whose creator fails the
26
23
  * live check's creator predicates (account disabled, no longer a member, agent deleted or hidden,
27
- * the conversation or its root deleted), one transaction per batch, owing each snapshot's
28
- * deletion through the outbox (the open routes already refuse them; this frees the snapshot and
29
- * shows a reason in the lists);
30
- * 2. deletes the snapshots of shares expired or revoked more than {@link RETAIN_DAYS} days ago that
31
- * still name one (a revoke owes its deletion at once; this is the expired shares' path and the
32
- * backstop) and clears `object_key`; the rows stay for the audit trail;
33
- * 3. per organization not deleted, lists `shares/` and deletes every object older than one hour
34
- * that is not the `object_key` of its row (no row: an insert that failed after its copy; another
35
- * generation: a refresh that died between its copy and its commit). An object whose age the
36
- * store does not report is kept. Its age is read again (`head`) just before the delete, and a
37
- * non-current generation of an existing share is deleted only under that share's refresh lock
38
- * (tried once), so a retried refresh writing the same key again is never undone.
24
+ * the conversation or its root deleted), one transaction per batch (the open routes already
25
+ * refuse them; this shows a reason in the lists);
26
+ * 2. frees the shares expired or revoked more than {@link RETAIN_DAYS} days ago: `blob_id` becomes
27
+ * null (the rows stay for the audit trail), so the blob sweep may delete a blob no file or other
28
+ * share still needs. No storage call: the bytes are the blob's.
39
29
  *
40
- * Steps 2 and 3 go through {@link ShareObjects.deleteObject}, which re-reads the row and never
41
- * deletes the snapshot a share that is neither revoked nor expired currently names. Deleted
42
- * organizations are skipped: their objects go with `storage-org-purge`. Nothing is kept in process
43
- * memory between runs; a run that stops midway (abort, error) is finished by the next one.
30
+ * Deleted organizations are skipped: their objects go with `storage-org-purge`. Nothing is kept in
31
+ * process memory between runs; a run that stops midway (abort, error) is finished by the next one.
44
32
  */
45
33
  export declare class ShareSweepJob {
46
34
  private readonly db;
47
35
  readonly txHost: TransactionHost;
48
- private readonly outbox;
49
- private readonly objects;
50
- private readonly storage;
51
36
  readonly lockService: LockService;
52
37
  readonly log: KernelLogger;
53
- constructor(db: KernelDb, txHost: TransactionHost, outbox: Pick<OutboxService, "add">, objects: Pick<ShareObjects, "deleteObject">, storage: Pick<StorageService, "available" | "kernel">, lockService: LockService, log: KernelLogger);
38
+ constructor(db: KernelDb, txHost: TransactionHost, lockService: LockService, log: KernelLogger);
54
39
  sweep(signal?: AbortSignal): Promise<void>;
55
40
  /** One sweep without the tick lock (the cron body; tests call it directly). */
56
41
  runOnce(signal?: AbortSignal): Promise<ShareSweepResult>;
@@ -58,17 +43,11 @@ export declare class ShareSweepJob {
58
43
  private revokeLostAccess;
59
44
  /** One batch of step 1 (the creator's access is checked again in the `UPDATE`). */
60
45
  revokeBatch(shareIds: readonly string[]): Promise<number>;
61
- /** Step 2: frees the snapshots of shares expired or revoked more than a week ago. */
46
+ /** Step 2: lets go of the blobs of shares expired or revoked more than a week ago. */
62
47
  private freeOld;
63
- /** Step 3: deletes the orphan objects under `shares/` of every organization not deleted. */
64
- private deleteOrphans;
65
- /** The orphan objects of one organization, page by page. */
66
- private orphansOf;
67
48
  /**
68
- * Whether `key` is still older than `cutoff` now: the listing may be stale (an upload that started
69
- * long ago, or a key written again since), so its age is read again just before deleting it.
49
+ * One batch of step 2 (one org, in its scope): the condition is checked again in the `UPDATE` (expiry is final and a
50
+ * revoke is never undone, so a row read as old is still old).
70
51
  */
71
- private stillOld;
72
- /** {@link ShareObjects.deleteObject}, logging instead of throwing (one bad object stops nothing). */
73
- private deleteGuarded;
52
+ freeBatch(orgId: string, shareIds: readonly string[]): Promise<number>;
74
53
  }
@@ -10,89 +10,58 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { withOrgScope } from "../infra/database/org-scope.js";
13
14
  import { TransactionHost } from "../infra/database/transaction-host.js";
14
15
  import { Transactional } from "../infra/database/transactional.decorator.js";
15
16
  import { LockService } from "../infra/lock/lock.service.js";
16
- import { OutboxService } from "../infra/outbox/outbox.service.js";
17
17
  import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
18
18
  import { KERNEL_LOGGER } from "../infra/tokens.js";
19
- import { StorageService } from "../storage/storage.service.js";
20
19
  import { creatorStillHasAccess } from "./liveness.js";
21
20
  import { revokeSharesIn } from "./revoke.js";
22
- import { ShareObjects, shareObjectKey, shareRefreshLockKey, } from "./share-objects.js";
23
21
  /** The daily share sweep's name (scheduler key and lock; no `:`). */
24
22
  export const SHARE_SWEEP_JOB = "share-sweep";
25
23
  /** When the daily share sweep runs (the deployment's time zone). */
26
24
  export const SHARE_SWEEP_CRON = "40 3 * * *";
27
- /** Rows per batch (one transaction per batch of revokes; one query per batch of reads). */
25
+ /** Rows per batch (one transaction per batch). */
28
26
  const BATCH = 200;
29
- /** Snapshots of shares expired or revoked longer ago than this are deleted (rows kept). */
30
- const RETAIN_DAYS = 7;
31
- /** An object under `shares/` no row names is deleted only once it is older than this. */
32
- const ORPHAN_AGE_MS = 60 * 60 * 1000;
33
- /** The objects listed per page when looking for orphans. */
34
- const LIST_PAGE = 1000;
35
- /** The sweep's hold on a share's refresh lock (tried once; a refresh holding it skips the key). */
36
- const REFRESH_LOCK_TTL_MS = 30_000;
27
+ /** Shares expired or revoked longer ago than this stop pointing at their blob (rows kept). */
28
+ export const RETAIN_DAYS = 7;
37
29
  /**
38
- * `shares/<shareId>/<generation>`, the only key shape the shares module writes. Only the shares
39
- * module writes under `shares/`, so a key of any other shape is no snapshot and is deleted directly.
40
- */
41
- const SHARE_KEY_RE = /^shares\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/(\d+)$/;
42
- /**
43
- * The daily share sweep (file sharing spec §9), a `@LockedCron` (once per tick across replicas,
44
- * provided only under `WorkerModule`). In order, with every storage call outside a transaction:
30
+ * The daily share sweep (file sharing spec §9, file library spec §7), a `@LockedCron` (once per
31
+ * tick across replicas, provided only under `WorkerModule`). In order:
45
32
  *
46
33
  * 1. revokes with `creator_lost_access` the unrevoked, unexpired shares whose creator fails the
47
34
  * live check's creator predicates (account disabled, no longer a member, agent deleted or hidden,
48
- * the conversation or its root deleted), one transaction per batch, owing each snapshot's
49
- * deletion through the outbox (the open routes already refuse them; this frees the snapshot and
50
- * shows a reason in the lists);
51
- * 2. deletes the snapshots of shares expired or revoked more than {@link RETAIN_DAYS} days ago that
52
- * still name one (a revoke owes its deletion at once; this is the expired shares' path and the
53
- * backstop) and clears `object_key`; the rows stay for the audit trail;
54
- * 3. per organization not deleted, lists `shares/` and deletes every object older than one hour
55
- * that is not the `object_key` of its row (no row: an insert that failed after its copy; another
56
- * generation: a refresh that died between its copy and its commit). An object whose age the
57
- * store does not report is kept. Its age is read again (`head`) just before the delete, and a
58
- * non-current generation of an existing share is deleted only under that share's refresh lock
59
- * (tried once), so a retried refresh writing the same key again is never undone.
35
+ * the conversation or its root deleted), one transaction per batch (the open routes already
36
+ * refuse them; this shows a reason in the lists);
37
+ * 2. frees the shares expired or revoked more than {@link RETAIN_DAYS} days ago: `blob_id` becomes
38
+ * null (the rows stay for the audit trail), so the blob sweep may delete a blob no file or other
39
+ * share still needs. No storage call: the bytes are the blob's.
60
40
  *
61
- * Steps 2 and 3 go through {@link ShareObjects.deleteObject}, which re-reads the row and never
62
- * deletes the snapshot a share that is neither revoked nor expired currently names. Deleted
63
- * organizations are skipped: their objects go with `storage-org-purge`. Nothing is kept in process
64
- * memory between runs; a run that stops midway (abort, error) is finished by the next one.
41
+ * Deleted organizations are skipped: their objects go with `storage-org-purge`. Nothing is kept in
42
+ * process memory between runs; a run that stops midway (abort, error) is finished by the next one.
65
43
  */
66
44
  let ShareSweepJob = class ShareSweepJob {
67
45
  db;
68
46
  txHost;
69
- outbox;
70
- objects;
71
- storage;
72
47
  lockService;
73
48
  log;
74
- constructor(db, txHost, outbox, objects, storage, lockService, log) {
49
+ constructor(db, txHost, lockService, log) {
75
50
  this.db = db;
76
51
  this.txHost = txHost;
77
- this.outbox = outbox;
78
- this.objects = objects;
79
- this.storage = storage;
80
52
  this.lockService = lockService;
81
53
  this.log = log;
82
54
  }
83
55
  async sweep(signal) {
84
56
  const r = await this.runOnce(signal);
85
- if (r.revoked + r.freed + r.orphans > 0)
57
+ if (r.revoked + r.freed > 0)
86
58
  this.log.info("share sweep done", { ...r });
87
59
  }
88
60
  /** One sweep without the tick lock (the cron body; tests call it directly). */
89
61
  async runOnce(signal) {
90
62
  const revoked = await this.revokeLostAccess(signal);
91
- if (!this.storage.available)
92
- return { revoked, freed: 0, orphans: 0 };
93
63
  const freed = await this.freeOld(signal);
94
- const orphans = await this.deleteOrphans(signal);
95
- return { revoked, freed, orphans };
64
+ return { revoked, freed };
96
65
  }
97
66
  /** Step 1: revokes, batch by batch, the shares whose creator lost access. */
98
67
  async revokeLostAccess(signal) {
@@ -105,7 +74,6 @@ let ShareSweepJob = class ShareSweepJob {
105
74
  .select("file_shares.id")
106
75
  .where("orgs.deleted_at", "is", null)
107
76
  .where("file_shares.revoked_at", "is", null)
108
- .where("file_shares.object_key", "is not", null)
109
77
  .where((eb) => eb.or([
110
78
  eb("file_shares.expires_at", "is", null),
111
79
  eb("file_shares.expires_at", ">", sql `now()`),
@@ -126,9 +94,9 @@ let ShareSweepJob = class ShareSweepJob {
126
94
  }
127
95
  /** One batch of step 1 (the creator's access is checked again in the `UPDATE`). */
128
96
  async revokeBatch(shareIds) {
129
- return revokeSharesIn(this.db.db, this.outbox, { shareIds }, "creator_lost_access");
97
+ return revokeSharesIn(this.db.db, { shareIds }, "creator_lost_access");
130
98
  }
131
- /** Step 2: frees the snapshots of shares expired or revoked more than a week ago. */
99
+ /** Step 2: lets go of the blobs of shares expired or revoked more than a week ago. */
132
100
  async freeOld(signal) {
133
101
  let freed = 0;
134
102
  let after = null;
@@ -137,14 +105,9 @@ let ShareSweepJob = class ShareSweepJob {
137
105
  const rows = await this.db
138
106
  .selectFrom("file_shares")
139
107
  .innerJoin("orgs", "orgs.id", "file_shares.org_id")
140
- .select([
141
- "file_shares.id",
142
- "file_shares.org_id",
143
- "file_shares.generation",
144
- "file_shares.object_key",
145
- ])
108
+ .select(["file_shares.id", "file_shares.org_id"])
146
109
  .where("orgs.deleted_at", "is", null)
147
- .where("file_shares.object_key", "is not", null)
110
+ .where("file_shares.blob_id", "is not", null)
148
111
  .where((eb) => eb.or([
149
112
  eb("file_shares.revoked_at", "<", old),
150
113
  eb.and([
@@ -158,17 +121,11 @@ let ShareSweepJob = class ShareSweepJob {
158
121
  .execute();
159
122
  if (rows.length === 0)
160
123
  break;
161
- for (const r of rows) {
162
- if (signal?.aborted)
163
- break;
164
- const data = {
165
- orgId: r.org_id,
166
- shareId: r.id,
167
- generation: r.generation,
168
- objectKey: r.object_key,
169
- };
170
- if (await this.deleteGuarded(data))
171
- freed++;
124
+ const byOrg = new Map();
125
+ for (const r of rows)
126
+ byOrg.set(r.org_id, [...(byOrg.get(r.org_id) ?? []), r.id]);
127
+ for (const [orgId, ids] of byOrg) {
128
+ freed += await withOrgScope(orgId, () => this.freeBatch(orgId, ids));
172
129
  }
173
130
  after = rows.at(-1).id;
174
131
  if (rows.length < BATCH)
@@ -176,141 +133,25 @@ let ShareSweepJob = class ShareSweepJob {
176
133
  }
177
134
  return freed;
178
135
  }
179
- /** Step 3: deletes the orphan objects under `shares/` of every organization not deleted. */
180
- async deleteOrphans(signal) {
181
- let deleted = 0;
182
- let after = null;
183
- while (!signal?.aborted) {
184
- const orgs = await this.db
185
- .selectFrom("orgs")
186
- .select("id")
187
- .where("deleted_at", "is", null)
188
- .$if(after !== null, (q) => q.where("id", ">", after))
189
- .orderBy("id")
190
- .limit(BATCH)
191
- .execute();
192
- for (const o of orgs) {
193
- if (signal?.aborted)
194
- break;
195
- try {
196
- deleted += await this.orphansOf(o.id, signal);
197
- }
198
- catch (err) {
199
- this.log.warn("share sweep: cannot clean orphan snapshots; the next run retries", {
200
- orgId: o.id,
201
- err,
202
- });
203
- }
204
- }
205
- if (orgs.length < BATCH)
206
- break;
207
- after = orgs.at(-1).id;
208
- }
209
- return deleted;
210
- }
211
- /** The orphan objects of one organization, page by page. */
212
- async orphansOf(orgId, signal) {
213
- const store = this.storage.kernel(orgId);
214
- let deleted = 0;
215
- let cursor;
216
- do {
217
- const page = await store.list("shares/", {
218
- limit: LIST_PAGE,
219
- ...(cursor !== undefined && { cursor }),
220
- });
221
- cursor = page.cursor;
222
- // the rows are read once per page; `deleteObject` reads its row again before deleting
223
- const cutoff = Date.now() - ORPHAN_AGE_MS;
224
- const old = page.items.filter((i) => {
225
- const at = i.lastModified === undefined ? Number.NaN : Date.parse(i.lastModified);
226
- return Number.isFinite(at) && at < cutoff;
227
- });
228
- const parsed = old.map((i) => ({ key: i.key, m: SHARE_KEY_RE.exec(i.key) }));
229
- const ids = [...new Set(parsed.flatMap((p) => (p.m ? [p.m[1]] : [])))];
230
- const named = new Map();
231
- if (ids.length > 0) {
232
- const rows = await this.db
233
- .selectFrom("file_shares")
234
- .select(["id", "object_key"])
235
- .where("org_id", "=", orgId)
236
- .where("id", "in", ids)
237
- .execute();
238
- for (const r of rows)
239
- named.set(r.id, r.object_key);
240
- }
241
- for (const p of parsed) {
242
- if (signal?.aborted)
243
- return deleted;
244
- const shareId = p.m?.[1];
245
- const generation = Number(p.m?.[2]);
246
- const snapshot = shareId !== undefined &&
247
- Number.isSafeInteger(generation) &&
248
- shareObjectKey(shareId, generation) === p.key;
249
- if (!snapshot || shareId === undefined) {
250
- if (await this.stillOld(store, p.key, cutoff)) {
251
- await store.delete(p.key);
252
- deleted++;
253
- }
254
- continue;
255
- }
256
- if (named.get(shareId) === p.key)
257
- continue; // its row's snapshot: step 2's, not an orphan
258
- const data = { orgId, shareId, generation, objectKey: p.key };
259
- if (!named.has(shareId)) {
260
- // no row (an insert that failed after its copy): a new create uses a new id
261
- if ((await this.stillOld(store, p.key, cutoff)) && (await this.deleteGuarded(data))) {
262
- deleted++;
263
- }
264
- continue;
265
- }
266
- // another generation of an existing share: a retried refresh may be writing this very key
267
- // again, its commit about to name it. Held, the refresh lock means no refresh is between its
268
- // copy and its commit, so the row `deleteObject` reads is the last word; a refresh holding
269
- // it now skips the key (the next run sees it again)
270
- const lock = await this.lockService.acquire(shareRefreshLockKey(shareId), {
271
- ttlMs: REFRESH_LOCK_TTL_MS,
272
- waitMs: 0,
273
- });
274
- if (!lock)
275
- continue;
276
- try {
277
- if ((await this.stillOld(store, p.key, cutoff)) && (await this.deleteGuarded(data))) {
278
- deleted++;
279
- }
280
- }
281
- finally {
282
- await lock.release();
283
- }
284
- }
285
- } while (cursor !== undefined && !signal?.aborted);
286
- return deleted;
287
- }
288
136
  /**
289
- * Whether `key` is still older than `cutoff` now: the listing may be stale (an upload that started
290
- * long ago, or a key written again since), so its age is read again just before deleting it.
137
+ * One batch of step 2 (one org, in its scope): the condition is checked again in the `UPDATE` (expiry is final and a
138
+ * revoke is never undone, so a row read as old is still old).
291
139
  */
292
- async stillOld(store, key, cutoff) {
293
- const head = await store.head(key);
294
- if (!head?.lastModified)
295
- return false;
296
- const at = Date.parse(head.lastModified);
297
- return Number.isFinite(at) && at < cutoff;
298
- }
299
- /** {@link ShareObjects.deleteObject}, logging instead of throwing (one bad object stops nothing). */
300
- async deleteGuarded(data) {
301
- try {
302
- await this.objects.deleteObject(data);
303
- return true;
304
- }
305
- catch (err) {
306
- this.log.warn("share sweep: cannot delete a share snapshot; the next run retries", {
307
- orgId: data.orgId,
308
- shareId: data.shareId,
309
- generation: data.generation,
310
- err,
311
- });
312
- return false;
313
- }
140
+ async freeBatch(orgId, shareIds) {
141
+ const old = sql `now() - make_interval(days => ${RETAIN_DAYS})`;
142
+ const rows = await this.db
143
+ .updateTable("file_shares")
144
+ .set({ blob_id: null })
145
+ .where("org_id", "=", orgId)
146
+ .where("id", "in", [...shareIds])
147
+ .where("blob_id", "is not", null)
148
+ .where((eb) => eb.or([
149
+ eb("revoked_at", "<", old),
150
+ eb.and([eb("revoked_at", "is", null), eb("expires_at", "<", old)]),
151
+ ]))
152
+ .returning("id")
153
+ .execute();
154
+ return rows.length;
314
155
  }
315
156
  };
316
157
  __decorate([
@@ -319,14 +160,14 @@ __decorate([
319
160
  __decorate([
320
161
  Transactional()
321
162
  ], ShareSweepJob.prototype, "revokeBatch", null);
163
+ __decorate([
164
+ Transactional()
165
+ ], ShareSweepJob.prototype, "freeBatch", null);
322
166
  ShareSweepJob = __decorate([
323
167
  Injectable(),
324
168
  __param(0, Inject(KernelDb)),
325
169
  __param(1, Inject(TransactionHost)),
326
- __param(2, Inject(OutboxService)),
327
- __param(3, Inject(ShareObjects)),
328
- __param(4, Inject(StorageService)),
329
- __param(5, Inject(LockService)),
330
- __param(6, Inject(KERNEL_LOGGER))
170
+ __param(2, Inject(LockService)),
171
+ __param(3, Inject(KERNEL_LOGGER))
331
172
  ], ShareSweepJob);
332
173
  export { ShareSweepJob };
@@ -1,5 +1,5 @@
1
1
  import type { EventLog } from "../../conversations/event-log.js";
2
- import { type StorageService } from "../../storage/storage.service.js";
2
+ import { type FileDeliveries } from "../../files/deliveries.js";
3
3
  import type { BuiltinCallContext } from "../registry.js";
4
4
  /**
5
5
  * The tool error when the deployment has no object store (or it went away): files cannot be
@@ -10,8 +10,12 @@ export declare const NO_STORAGE = "File storage is not configured in this deploy
10
10
  export declare const NO_STORAGE_REASON: string;
11
11
  /** What {@link storeArtifacts} needs. */
12
12
  export interface ArtifactStoreDeps {
13
- storage: Pick<StorageService, "kernel">;
14
- eventLog: Pick<EventLog, "append" | "readDeliveryScope"> & Partial<Pick<EventLog, "publishChanged">>;
13
+ eventLog: Pick<EventLog, "readDeliveryScope"> & Partial<Pick<EventLog, "publishChanged">>;
14
+ /**
15
+ * The blobs and the one transaction of a delivery (file library spec §4). Absent in test stubs
16
+ * without a store: nothing can be delivered then ({@link NO_STORAGE}).
17
+ */
18
+ deliveries?: Pick<FileDeliveries, "ensureBlob" | "appendDelivered"> | undefined;
15
19
  }
16
20
  /** One file to deliver as an artifact. */
17
21
  export interface ArtifactFile {
@@ -50,20 +54,24 @@ export declare const REPEAT_TEXT: (name: string, prior: {
50
54
  artifactId: string;
51
55
  }) => string;
52
56
  /**
53
- * Stores `files` as artifacts of the call's conversation, all or none: every object is uploaded
54
- * under the kernel prefix (`artifacts/<conversationId>/<artifactId>`), then all their
55
- * `artifact_created` events (the call's run and `callId`, the bytes' sha256) go into the log in
56
- * one append. Any failure, an abort of the call before the append included, deletes every object
57
- * uploaded so far (best effort; one left behind is unreferenced and goes with the conversation's
58
- * purge) and rethrows; a store that is not there is the {@link NO_STORAGE} tool error. The
59
- * conversation's files are announced changed once, when something new was stored.
57
+ * Stores `files` as artifacts of the call's conversation, all or none (file library spec §4): the
58
+ * bytes of every file become a ready blob of the org ({@link FileDeliveries.ensureBlob}: an
59
+ * existing blob of the same sha256 is reused with no upload, else a new one is written intent
60
+ * first), then all their `artifact_created` events (the call's run and `callId`, the bytes'
61
+ * sha256, `fileId` = the artifact id, `objectKey` = the blob's key) and their files (owner the
62
+ * conversation's owner, origin `generated` for a `generated/` source path, else `delivered`) are
63
+ * written in one transaction. A blob a deletion claimed in between aborts that transaction, and
64
+ * the bytes are ensured again and the whole unit retried (a bounded number of times). Nothing is
65
+ * cleaned up on failure: a blob may serve other files, and an unreferenced one is the blob sweep's.
66
+ * A store that is not there is the {@link NO_STORAGE} tool error. The conversation's files are
67
+ * announced changed once, when something new was stored.
60
68
  *
61
69
  * With a run, the same bytes reach the user once per delivery scope (truthful delivery spec §2):
62
70
  * a file equal to an earlier file of the call, or a repeat by {@link findRepeat} of the scope's
63
- * artifacts, is not uploaded and comes back with `repeatOf`. Each event's idempotency key is
71
+ * artifacts, is not stored and comes back with `repeatOf`. Each event's idempotency key is
64
72
  * `artifact:<runId>:<boundary>:<sha256>:<lastOfSource>`, so two parallel calls that both saw no
65
73
  * repeat compute the same key: the append's row lock and the unique key give the second the
66
- * first's event, and the one cleanup rule deletes every object whose returned event is not the
67
- * one generated for it, making that file a repeat of the returned event. No process state.
74
+ * first's event (and record no file for it), making that file a repeat of the returned event.
75
+ * No process state.
68
76
  */
69
77
  export declare function storeArtifacts(deps: ArtifactStoreDeps, ctx: BuiltinCallContext, files: readonly ArtifactFile[]): Promise<StoredArtifact[]>;