@capybara-hq/kernel 0.1.0-rc.130 → 0.1.0-rc.132

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 (204) hide show
  1. package/dist/admin/account-erasures.d.ts +37 -0
  2. package/dist/admin/account-erasures.js +119 -0
  3. package/dist/admin/admin.controller.d.ts +35 -2
  4. package/dist/admin/admin.controller.js +75 -18
  5. package/dist/admin/admin.module.js +10 -0
  6. package/dist/admin/admin.schemas.d.ts +51 -0
  7. package/dist/admin/admin.schemas.js +20 -0
  8. package/dist/admin/erasure-dispositions.d.ts +23 -0
  9. package/dist/admin/erasure-dispositions.js +76 -0
  10. package/dist/admin/health.service.d.ts +6 -0
  11. package/dist/admin/health.service.js +27 -1
  12. package/dist/admin/usage.service.d.ts +5 -0
  13. package/dist/admin/usage.service.js +21 -2
  14. package/dist/agents/agents.service.d.ts +1 -1
  15. package/dist/catalog/plugin-import.d.ts +3 -1
  16. package/dist/catalog/plugin-import.js +19 -15
  17. package/dist/channels/connections.service.d.ts +1 -1
  18. package/dist/client/client-reports.service.js +12 -0
  19. package/dist/config/schema.d.ts +9 -1
  20. package/dist/config/schema.js +51 -1
  21. package/dist/conversations/conversations.service.d.ts +9 -1
  22. package/dist/conversations/conversations.service.js +112 -15
  23. package/dist/conversations/event-log.d.ts +2 -0
  24. package/dist/conversations/event-log.js +77 -0
  25. package/dist/conversations/events.d.ts +11 -0
  26. package/dist/conversations/events.js +13 -1
  27. package/dist/conversations/prompt-suggestions.js +4 -0
  28. package/dist/conversations/titles.js +3 -2
  29. package/dist/ctx/create-ctx.d.ts +3 -2
  30. package/dist/ctx/create-ctx.js +10 -7
  31. package/dist/db/extension-db.d.ts +30 -0
  32. package/dist/db/extension-db.js +91 -0
  33. package/dist/db/extension-schema-transfer.d.ts +6 -0
  34. package/dist/db/extension-schema-transfer.js +141 -0
  35. package/dist/db/kernel-schema.d.ts +73 -12
  36. package/dist/db/migrator.d.ts +6 -0
  37. package/dist/db/migrator.js +39 -4
  38. package/dist/db/pool.d.ts +4 -0
  39. package/dist/db/pool.js +36 -1
  40. package/dist/devices/devices.service.d.ts +13 -1
  41. package/dist/devices/devices.service.js +122 -9
  42. package/dist/erasure/account-batches.d.ts +9 -0
  43. package/dist/erasure/account-batches.js +567 -0
  44. package/dist/erasure/account-files.d.ts +34 -0
  45. package/dist/erasure/account-files.js +217 -0
  46. package/dist/erasure/account-residual.d.ts +15 -0
  47. package/dist/erasure/account-residual.js +149 -0
  48. package/dist/erasure/account-worker.d.ts +32 -0
  49. package/dist/erasure/account-worker.js +392 -0
  50. package/dist/erasure/device-cleanup.d.ts +23 -0
  51. package/dist/erasure/device-cleanup.js +221 -0
  52. package/dist/erasure/erasure.module.d.ts +2 -0
  53. package/dist/{conversations/event-org-backfill.module.js → erasure/erasure.module.js} +6 -10
  54. package/dist/erasure/external-evidence.d.ts +4 -0
  55. package/dist/erasure/external-evidence.js +28 -0
  56. package/dist/erasure/jobs.d.ts +5 -0
  57. package/dist/erasure/jobs.js +20 -0
  58. package/dist/erasure/org-batches.d.ts +11 -0
  59. package/dist/erasure/org-batches.js +159 -0
  60. package/dist/erasure/org-catalog.d.ts +2 -0
  61. package/dist/erasure/org-catalog.js +34 -0
  62. package/dist/erasure/org-rules.d.ts +14 -0
  63. package/dist/erasure/org-rules.js +227 -0
  64. package/dist/erasure/org-worker.d.ts +38 -0
  65. package/dist/erasure/org-worker.js +501 -0
  66. package/dist/erasure/requests.d.ts +61 -0
  67. package/dist/erasure/requests.js +180 -0
  68. package/dist/erasure/sweep.job.d.ts +19 -0
  69. package/dist/erasure/sweep.job.js +130 -0
  70. package/dist/erasure/worker.d.ts +17 -0
  71. package/dist/erasure/worker.js +110 -0
  72. package/dist/errors.d.ts +4 -0
  73. package/dist/errors.js +4 -0
  74. package/dist/evals/judge.d.ts +5 -0
  75. package/dist/evals/judge.js +16 -1
  76. package/dist/evals/run-replay.js +12 -1
  77. package/dist/evals/step-replay.d.ts +5 -3
  78. package/dist/evals/step-replay.js +9 -5
  79. package/dist/evals/worker.d.ts +2 -0
  80. package/dist/evals/worker.js +60 -16
  81. package/dist/extensions/admin-ops.d.ts +3 -1
  82. package/dist/extensions/admin-ops.js +11 -7
  83. package/dist/extensions/extensions.module.js +3 -0
  84. package/dist/extensions/host.d.ts +4 -1
  85. package/dist/extensions/host.js +29 -6
  86. package/dist/extensions/instance.d.ts +3 -0
  87. package/dist/extensions/instance.js +3 -1
  88. package/dist/extensions/migrate-lock.d.ts +4 -1
  89. package/dist/extensions/migrate-lock.js +19 -2
  90. package/dist/files/blob-objects.d.ts +7 -3
  91. package/dist/files/blob-objects.js +39 -22
  92. package/dist/files/blob-sweep.job.d.ts +11 -0
  93. package/dist/files/blob-sweep.job.js +67 -6
  94. package/dist/http/api.module.js +5 -1
  95. package/dist/identity/accounts.js +3 -0
  96. package/dist/identity/api-tokens.js +5 -0
  97. package/dist/identity/auth.guard.d.ts +1 -0
  98. package/dist/identity/auth.guard.js +1 -0
  99. package/dist/identity/erasure-admission.d.ts +3 -0
  100. package/dist/identity/erasure-admission.js +14 -0
  101. package/dist/identity/external.js +5 -0
  102. package/dist/identity/sessions.js +5 -0
  103. package/dist/identity/settings.d.ts +86 -1
  104. package/dist/identity/settings.js +38 -4
  105. package/dist/infra/config/kernel-config.service.js +1 -0
  106. package/dist/infra/metrics/kernel-metrics.d.ts +18 -0
  107. package/dist/infra/metrics/kernel-metrics.js +54 -0
  108. package/dist/infra/metrics/operational-metrics.d.ts +31 -0
  109. package/dist/infra/metrics/operational-metrics.js +188 -0
  110. package/dist/infra/outbox/registry.d.ts +23 -14
  111. package/dist/infra/outbox/registry.js +12 -15
  112. package/dist/infra/throttler/credential-throttler.js +8 -1
  113. package/dist/infra/throttler/named-throttlers.d.ts +6 -0
  114. package/dist/infra/throttler/named-throttlers.js +6 -0
  115. package/dist/infra/throttler/principal-throttler.guard.d.ts +10 -0
  116. package/dist/infra/throttler/principal-throttler.guard.js +50 -0
  117. package/dist/infra/throttler/redis-throttler-storage.d.ts +1 -0
  118. package/dist/infra/throttler/redis-throttler-storage.js +27 -5
  119. package/dist/infra/throttler/throttler.guard.d.ts +2 -3
  120. package/dist/infra/throttler/throttler.guard.js +2 -3
  121. package/dist/infra/throttler/throttler.module.js +3 -2
  122. package/dist/kernel.js +4 -0
  123. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  124. package/dist/lifecycle/kernel-lifecycle.js +26 -21
  125. package/dist/models/budget-admission.d.ts +31 -0
  126. package/dist/models/budget-admission.js +149 -0
  127. package/dist/models/budget-counters.d.ts +28 -0
  128. package/dist/models/budget-counters.js +117 -0
  129. package/dist/models/budget-policy.d.ts +88 -0
  130. package/dist/models/budget-policy.js +78 -0
  131. package/dist/models/embeddings.js +13 -2
  132. package/dist/models/images.js +12 -2
  133. package/dist/models/purposes.d.ts +5 -2
  134. package/dist/models/purposes.js +9 -5
  135. package/dist/orgs/invitations.service.d.ts +1 -1
  136. package/dist/orgs/members.service.d.ts +28 -1
  137. package/dist/orgs/members.service.js +74 -11
  138. package/dist/orgs/offboarding.js +4 -6
  139. package/dist/orgs/org-owner.d.ts +2 -0
  140. package/dist/orgs/org-owner.js +21 -6
  141. package/dist/orgs/orgs.controller.d.ts +22 -0
  142. package/dist/orgs/orgs.controller.js +24 -0
  143. package/dist/orgs/orgs.module.js +4 -0
  144. package/dist/orgs/orgs.schemas.js +7 -0
  145. package/dist/orgs/orgs.service.d.ts +5 -1
  146. package/dist/orgs/orgs.service.js +28 -3
  147. package/dist/orgs/settings.controller.js +6 -1
  148. package/dist/orgs/settings.service.d.ts +58 -1
  149. package/dist/orgs/settings.service.js +74 -9
  150. package/dist/platform/exclusions.js +20 -1
  151. package/dist/platform/ops/accounts.ops.js +58 -1
  152. package/dist/platform/ops/admin.ops.js +13 -5
  153. package/dist/platform/ops/org-settings.ops.js +11 -4
  154. package/dist/platform/ops/orgs.ops.js +28 -0
  155. package/dist/platform/ops/retention.d.ts +16 -0
  156. package/dist/platform/ops/retention.js +21 -0
  157. package/dist/retention/jobs.d.ts +21 -0
  158. package/dist/retention/jobs.js +48 -0
  159. package/dist/retention/policy.d.ts +70 -0
  160. package/dist/retention/policy.js +103 -0
  161. package/dist/retention/purge-batch.d.ts +17 -0
  162. package/dist/retention/purge-batch.js +355 -0
  163. package/dist/retention/report-obligations.d.ts +12 -0
  164. package/dist/retention/report-obligations.js +71 -0
  165. package/dist/retention/sweep.job.d.ts +17 -0
  166. package/dist/retention/sweep.job.js +95 -0
  167. package/dist/retention/worker.d.ts +29 -0
  168. package/dist/retention/worker.js +306 -0
  169. package/dist/roles/worker.module.js +12 -8
  170. package/dist/runtime/maintenance.d.ts +5 -3
  171. package/dist/runtime/maintenance.js +19 -12
  172. package/dist/runtime/model-call.d.ts +3 -1
  173. package/dist/runtime/model-call.js +25 -3
  174. package/dist/runtime/providers.d.ts +7 -2
  175. package/dist/runtime/providers.js +76 -10
  176. package/dist/runtime/quota.d.ts +12 -12
  177. package/dist/runtime/quota.js +42 -37
  178. package/dist/runtime/run-finish.js +2 -0
  179. package/dist/runtime/run-principal.d.ts +9 -0
  180. package/dist/runtime/run-principal.js +18 -0
  181. package/dist/runtime/run-worker.js +48 -10
  182. package/dist/runtime/usage-report-jobs.d.ts +4 -1
  183. package/dist/runtime/usage-report-jobs.js +36 -13
  184. package/dist/runtime/usage-report.d.ts +5 -3
  185. package/dist/runtime/usage-report.js +37 -19
  186. package/dist/sandbox/review/classifier.d.ts +2 -2
  187. package/dist/sandbox/review/classifier.js +6 -2
  188. package/dist/sandbox/sandbox.service.js +18 -7
  189. package/dist/storage/purge.js +5 -1
  190. package/dist/storage/storage.service.d.ts +17 -1
  191. package/dist/storage/storage.service.js +75 -4
  192. package/dist/tools/builtins/vision/read-image.js +3 -0
  193. package/dist/tools/builtins/web/extract.js +3 -0
  194. package/dist/tools/pipeline.js +5 -1
  195. package/package.json +3 -1
  196. package/src/migrations/0216_model_budget_counters.sql +24 -0
  197. package/src/migrations/0217_retention.sql +44 -0
  198. package/src/migrations/0218_data_erasure.sql +41 -0
  199. package/src/migrations/0219_event_org_constraint_check.sql +29 -0
  200. package/src/migrations/0220_require_event_org.sql +18 -0
  201. package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
  202. package/dist/conversations/event-org-backfill.d.ts +0 -111
  203. package/dist/conversations/event-org-backfill.js +0 -264
  204. package/dist/conversations/event-org-backfill.module.d.ts +0 -3
@@ -9,7 +9,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable, Module } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
12
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { asPlatform } from "../infra/database/org-scope.js";
13
15
  import { TransactionHost } from "../infra/database/transaction-host.js";
14
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
15
17
  import { OutboxService } from "../infra/outbox/outbox.service.js";
@@ -129,12 +131,14 @@ let BlobObjects = class BlobObjects {
129
131
  db;
130
132
  txHost;
131
133
  storage;
134
+ config;
132
135
  outbox;
133
136
  log;
134
- constructor(db, txHost, storage, outbox, log) {
137
+ constructor(db, txHost, storage, config, outbox, log) {
135
138
  this.db = db;
136
139
  this.txHost = txHost;
137
140
  this.storage = storage;
141
+ this.config = config;
138
142
  this.outbox = outbox;
139
143
  this.log = log;
140
144
  }
@@ -210,7 +214,7 @@ let BlobObjects = class BlobObjects {
210
214
  return null;
211
215
  }
212
216
  /** Deletes one staging object; see the class comment. */
213
- async deleteStaging(data) {
217
+ async deleteStaging(data, store) {
214
218
  const file = await this.db
215
219
  .selectFrom("files")
216
220
  .select([
@@ -240,16 +244,39 @@ let BlobObjects = class BlobObjects {
240
244
  .executeTakeFirst();
241
245
  if (adopted)
242
246
  return;
243
- await this.storage.kernel(data.orgId).delete(data.objectKey);
247
+ await this.deleteObject(data.orgId, data.objectKey, store);
244
248
  }
245
249
  /** Deletes one `deleting` blob, its object first; see the class comment. */
246
- async deleteBlob(data) {
250
+ async deleteBlob(data, store) {
247
251
  const key = await this.claimUnreferenced(data);
248
252
  if (key === null)
249
253
  return;
250
- await this.storage.kernel(data.orgId).delete(key);
254
+ await this.deleteObject(data.orgId, key, store);
251
255
  await this.dropRow(data);
252
256
  }
257
+ async deleteObject(orgId, key, store) {
258
+ if (store)
259
+ return store.delete(key);
260
+ const { erasureEnabled, destructiveEnabled } = this.config.get().retention;
261
+ if (erasureEnabled && destructiveEnabled) {
262
+ const fenced = await this.db
263
+ .selectFrom("orgs")
264
+ .leftJoin("data_erasure_requests", (join) => join
265
+ .onRef("data_erasure_requests.org_id", "=", "orgs.id")
266
+ .on("data_erasure_requests.kind", "=", "org")
267
+ .on("data_erasure_requests.stage", "!=", "done"))
268
+ .select(sql `data_erasure_requests.progress ->> 'storageIdentity'`.as("identity"))
269
+ .where("orgs.id", "=", orgId)
270
+ .where("orgs.deleted_at", "is not", null)
271
+ .executeTakeFirst();
272
+ if (fenced) {
273
+ if (!fenced.identity)
274
+ throw new Error("Object storage provider is unverified for erasure");
275
+ return this.storage.verifyErasureObjects(orgId, fenced.identity, (target) => target.delete(key));
276
+ }
277
+ }
278
+ return this.storage.kernel(orgId).delete(key);
279
+ }
253
280
  /**
254
281
  * Under `FOR UPDATE` on the blob: when it is `deleting` (or `gone`: a retry) and nothing points
255
282
  * at it, sets it `gone` and returns its object key; else null (logged when it is still
@@ -266,21 +293,10 @@ let BlobObjects = class BlobObjects {
266
293
  .executeTakeFirst();
267
294
  if (blob?.status !== "deleting" && blob?.status !== "gone")
268
295
  return null;
269
- const file = await trx
270
- .selectFrom("files")
271
- .select("id")
272
- .where("org_id", "=", data.orgId)
273
- .where("blob_id", "=", data.blobId)
274
- .limit(1)
275
- .executeTakeFirst();
276
- const share = await trx
277
- .selectFrom("file_shares")
278
- .select("id")
279
- .where("org_id", "=", data.orgId)
280
- .where("blob_id", "=", data.blobId)
281
- .limit(1)
282
- .executeTakeFirst();
283
- if (file || share) {
296
+ // org-filter: deployment-wide a legacy foreign reference can point at this globally unique id.
297
+ const referenced = await asPlatform("check all orgs before deleting a shared blob's bytes", () => sql `SELECT FROM capybara.files WHERE blob_id = ${data.blobId}
298
+ UNION ALL SELECT FROM capybara.file_shares WHERE blob_id = ${data.blobId} LIMIT 1`.execute(trx));
299
+ if (referenced.rows.length) {
284
300
  this.log.warn("a blob marked for deletion is still referenced; keeping it", { ...data });
285
301
  return null;
286
302
  }
@@ -328,8 +344,9 @@ BlobObjects = __decorate([
328
344
  __param(0, Inject(KernelDb)),
329
345
  __param(1, Inject(TransactionHost)),
330
346
  __param(2, Inject(StorageService)),
331
- __param(3, Inject(OutboxService)),
332
- __param(4, Inject(KERNEL_LOGGER))
347
+ __param(3, Inject(KernelConfigService)),
348
+ __param(4, Inject(OutboxService)),
349
+ __param(5, Inject(KERNEL_LOGGER))
333
350
  ], BlobObjects);
334
351
  export { BlobObjects };
335
352
  /** {@link BlobObjects} for the maintenance worker (storage and the database only). */
@@ -39,6 +39,7 @@ export interface BlobSweepResult {
39
39
  interface ReleaseKind {
40
40
  statuses: readonly BlobStatus[];
41
41
  olderThanHours: number;
42
+ verifyForeignReferences?: true;
42
43
  }
43
44
  /**
44
45
  * The daily blob sweep (file library spec §7), a `@LockedCron` (once per tick across replicas,
@@ -79,6 +80,12 @@ export declare class BlobSweepJob {
79
80
  private orgPage;
80
81
  /** The four steps for one org (in its scope). */
81
82
  private sweepOrg;
83
+ /** One bounded file and blob sweep for a tombstoned org after its recovery hold. */
84
+ sweepFencedOrgBatch(orgId: string, cutoff: Date): Promise<{
85
+ filesDeleted: number;
86
+ blobsReleased: number;
87
+ blocked?: "foreign-file-reference" | "foreign-blob-reference";
88
+ }>;
82
89
  /** Step 2 or 3 for one org, batch by batch along the blob ids. */
83
90
  private releaseAll;
84
91
  /**
@@ -88,6 +95,7 @@ export declare class BlobSweepJob {
88
95
  * shares' `source_file_id` (defense in depth: deleting the file already revoked them).
89
96
  */
90
97
  deleteExpiredFiles(orgId: string): Promise<number>;
98
+ private deleteFilesBefore;
91
99
  /**
92
100
  * Steps 2 and 3, one batch: claims up to {@link BATCH} candidates after `after` (see the class
93
101
  * comment), turns the still unreferenced ones `deleting` and owes their deletions. `last` is the
@@ -96,6 +104,7 @@ export declare class BlobSweepJob {
96
104
  releaseBatch(orgId: string, kind: ReleaseKind, after: string | null): Promise<{
97
105
  released: number;
98
106
  last: string | null;
107
+ blocked?: "foreign-blob-reference";
99
108
  }>;
100
109
  /**
101
110
  * Step 4, one batch of up to {@link BATCH} stale `deleting` blobs after `after`: the objects of
@@ -110,4 +119,6 @@ export declare class BlobSweepJob {
110
119
  restored: number;
111
120
  }>;
112
121
  }
122
+ export declare class BlobSweepModule {
123
+ }
113
124
  export {};
@@ -7,11 +7,11 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { Inject, Injectable } from "@nestjs/common";
10
+ import { Inject, Injectable, Module } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
13
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
- import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
14
+ import { asPlatform, currentScope, withOrgScope } from "../infra/database/org-scope.js";
15
15
  import { TransactionHost } from "../infra/database/transaction-host.js";
16
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
17
17
  import { LockService } from "../infra/lock/lock.service.js";
@@ -19,6 +19,7 @@ import { OutboxService } from "../infra/outbox/outbox.service.js";
19
19
  import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
20
20
  import { KERNEL_LOGGER } from "../infra/tokens.js";
21
21
  import { revokeSharesIn } from "../shares/revoke.js";
22
+ import { StorageModule } from "../storage/storage.module.js";
22
23
  import { StorageService } from "../storage/storage.service.js";
23
24
  import { oweBlobDelete } from "./blob-objects.js";
24
25
  import { blobUnreferenced } from "./blob-references.js";
@@ -153,6 +154,36 @@ let BlobSweepJob = class BlobSweepJob {
153
154
  after = batch.last;
154
155
  }
155
156
  }
157
+ /** One bounded file and blob sweep for a tombstoned org after its recovery hold. */
158
+ async sweepFencedOrgBatch(orgId, cutoff) {
159
+ const scope = currentScope();
160
+ if (scope?.kind !== "org" || scope.orgId !== orgId)
161
+ throw new Error("An erasure blob sweep requires the organization scope");
162
+ const fenced = await this.db
163
+ .selectFrom("orgs")
164
+ .select("id")
165
+ .where("id", "=", orgId)
166
+ .where("deleted_at", "is not", null)
167
+ .forNoKeyUpdate()
168
+ .executeTakeFirst();
169
+ if (!fenced)
170
+ throw new Error("Organization must be fenced for erasure");
171
+ const files = await this.deleteFilesBefore(orgId, sql `${cutoff}`, true);
172
+ const filesDeleted = files.deleted;
173
+ if (files.blocked)
174
+ return { filesDeleted, blobsReleased: 0, blocked: files.blocked };
175
+ const blobs = await this.releaseBatch(orgId, { statuses: ["ready", "gone", "pending"], olderThanHours: 0, verifyForeignReferences: true }, null);
176
+ if (blobs.blocked)
177
+ return { filesDeleted, blobsReleased: 0, blocked: blobs.blocked };
178
+ if (!filesDeleted && !blobs.released) {
179
+ // The normal sweep skips fenced orgs. Re-owe interrupted deletions under the same job IDs.
180
+ // Let the erasure worker defer until these jobs settle instead of spinning on them.
181
+ const deleting = await this.releaseBatch(orgId, { statuses: ["deleting"], olderThanHours: 0, verifyForeignReferences: true }, null);
182
+ if (deleting.blocked)
183
+ return { filesDeleted, blobsReleased: 0, blocked: deleting.blocked };
184
+ }
185
+ return { filesDeleted, blobsReleased: blobs.released };
186
+ }
156
187
  /** Step 2 or 3 for one org, batch by batch along the blob ids. */
157
188
  async releaseAll(orgId, kind, signal) {
158
189
  let released = 0;
@@ -173,9 +204,12 @@ let BlobSweepJob = class BlobSweepJob {
173
204
  * shares' `source_file_id` (defense in depth: deleting the file already revoked them).
174
205
  */
175
206
  async deleteExpiredFiles(orgId) {
176
- const trx = this.db.db;
177
207
  const days = this.config.get().files.deletedRetentionDays;
178
- const cutoff = sql `now() - make_interval(days => ${days})`;
208
+ return (await this.deleteFilesBefore(orgId, sql `now() - make_interval(days => ${days})`))
209
+ .deleted;
210
+ }
211
+ async deleteFilesBefore(orgId, cutoff, verifyForeignReferences = false) {
212
+ const trx = this.db.db;
179
213
  const claimed = await trx
180
214
  .selectFrom("files")
181
215
  .select("id")
@@ -188,8 +222,17 @@ let BlobSweepJob = class BlobSweepJob {
188
222
  .skipLocked()
189
223
  .execute();
190
224
  if (claimed.length === 0)
191
- return 0;
225
+ return { deleted: 0 };
192
226
  const ids = claimed.map((r) => r.id);
227
+ if (verifyForeignReferences) {
228
+ // org-filter: deployment-wide read of incoming references to already locked candidate files.
229
+ const conflict = await asPlatform("check for foreign references to erased files", () => sql `SELECT FROM capybara.conversation_files WHERE org_id <> ${orgId}
230
+ AND file_id = ANY(${ids}::text[])
231
+ UNION ALL SELECT FROM capybara.file_shares WHERE org_id <> ${orgId}
232
+ AND (source_file_id = ANY(${ids}::text[]) OR file_id = ANY(${ids}::text[])) LIMIT 1`.execute(trx));
233
+ if (conflict.rows.length)
234
+ return { deleted: 0, blocked: "foreign-file-reference" };
235
+ }
193
236
  await revokeSharesIn(trx, { orgId, fileIds: ids }, "file_deleted");
194
237
  const rows = await trx
195
238
  .deleteFrom("files")
@@ -198,7 +241,7 @@ let BlobSweepJob = class BlobSweepJob {
198
241
  .where("status", "=", "deleted")
199
242
  .returning("id")
200
243
  .execute();
201
- return rows.length;
244
+ return { deleted: rows.length };
202
245
  }
203
246
  /**
204
247
  * Steps 2 and 3, one batch: claims up to {@link BATCH} candidates after `after` (see the class
@@ -223,6 +266,15 @@ let BlobSweepJob = class BlobSweepJob {
223
266
  .execute();
224
267
  if (candidates.length === 0)
225
268
  return { released: 0, last: null };
269
+ if (kind.verifyForeignReferences) {
270
+ const ids = candidates.map(({ id }) => id);
271
+ // org-filter: deployment-wide read of incoming references to already locked candidate blobs.
272
+ const conflict = await asPlatform("check for foreign references to erased blobs", () => sql `SELECT FROM capybara.files WHERE org_id <> ${orgId} AND blob_id = ANY(${ids}::text[])
273
+ UNION ALL SELECT FROM capybara.file_shares WHERE org_id <> ${orgId}
274
+ AND blob_id = ANY(${ids}::text[]) LIMIT 1`.execute(trx));
275
+ if (conflict.rows.length)
276
+ return { released: 0, last: null, blocked: "foreign-blob-reference" };
277
+ }
226
278
  // a statement of its own (READ COMMITTED: a fresh snapshot): a reference committed after the
227
279
  // claim's snapshot but before its row lock is seen here and keeps the blob
228
280
  const released = await trx
@@ -335,6 +387,9 @@ let BlobSweepJob = class BlobSweepJob {
335
387
  __decorate([
336
388
  LockedCron(BLOB_SWEEP_CRON, { name: BLOB_SWEEP_JOB })
337
389
  ], BlobSweepJob.prototype, "sweep", null);
390
+ __decorate([
391
+ Transactional()
392
+ ], BlobSweepJob.prototype, "sweepFencedOrgBatch", null);
338
393
  __decorate([
339
394
  Transactional()
340
395
  ], BlobSweepJob.prototype, "deleteExpiredFiles", null);
@@ -355,3 +410,9 @@ BlobSweepJob = __decorate([
355
410
  __param(6, Inject(KERNEL_LOGGER))
356
411
  ], BlobSweepJob);
357
412
  export { BlobSweepJob };
413
+ let BlobSweepModule = class BlobSweepModule {
414
+ };
415
+ BlobSweepModule = __decorate([
416
+ Module({ imports: [StorageModule], providers: [BlobSweepJob], exports: [BlobSweepJob] })
417
+ ], BlobSweepModule);
418
+ export { BlobSweepModule };
@@ -77,6 +77,7 @@ import { BindController, MeIdentitiesController, SsoController, } from "../ident
77
77
  import { InboxModule } from "../inbox/inbox.module.js";
78
78
  import { InboxItemsController } from "../inbox/inbox-items.controller.js";
79
79
  import { PlatformInboxController } from "../inbox/platform-inbox.controller.js";
80
+ import { PrincipalThrottlerGuard } from "../infra/throttler/principal-throttler.guard.js";
80
81
  import { ModelEnablementController } from "../models/enablement.controller.js";
81
82
  import { ModelsModule } from "../models/models.module.js";
82
83
  import { ModelPurposesController } from "../models/purposes.controller.js";
@@ -280,7 +281,10 @@ ApiModule = __decorate([
280
281
  HandoffModule,
281
282
  ],
282
283
  controllers: CONTROLLERS,
283
- providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
284
+ providers: [
285
+ { provide: APP_GUARD, useClass: AuthGuard },
286
+ { provide: APP_GUARD, useExisting: PrincipalThrottlerGuard },
287
+ ],
284
288
  })
285
289
  ], ApiModule);
286
290
  export { ApiModule };
@@ -583,6 +583,9 @@ let AccountsService = class AccountsService {
583
583
  */
584
584
  async applyUpdate(before, patch, auditAs) {
585
585
  const id = before.id;
586
+ if (before.erasure_requested && patch.status === "active") {
587
+ throw new ApiError("conflict", "Account erasure is in progress");
588
+ }
586
589
  const values = { updated_at: new Date() };
587
590
  if (patch.displayName !== undefined) {
588
591
  values.display_name = checkDisplayNameChange(before.display_name, patch.displayName);
@@ -19,6 +19,7 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
19
19
  import { OrgLock } from "../orgs/org-lock.js";
20
20
  import { roleAtLeast } from "../orgs/roles.js";
21
21
  import { audit } from "./audit.js";
22
+ import { lockAccountForAdmission } from "./erasure-admission.js";
22
23
  import { sha256Hex } from "./hash.js";
23
24
  /** 令牌过期时间:完整 ISO 8601 datetime 字符串(`2099-01-01T00:00:00Z`),必须晚于当前时间;解析为 `Date`。 */
24
25
  export const FutureIsoDate = z.iso
@@ -61,6 +62,7 @@ let ApiTokenService = class ApiTokenService {
61
62
  this.orgLock = orgLock;
62
63
  }
63
64
  async createPersonal(accountId, input) {
65
+ await lockAccountForAdmission(this.db, accountId);
64
66
  validate(input);
65
67
  // org-filter: deployment-wide account token write with a null org_id.
66
68
  return asPlatform("Create the account's personal token without an org", () => this.insertToken("personal", {
@@ -222,6 +224,9 @@ let ApiTokenService = class ApiTokenService {
222
224
  return { token, record: toRecord(row) };
223
225
  }
224
226
  };
227
+ __decorate([
228
+ Transactional()
229
+ ], ApiTokenService.prototype, "createPersonal", null);
225
230
  __decorate([
226
231
  Transactional()
227
232
  ], ApiTokenService.prototype, "createServiceAs", null);
@@ -50,6 +50,7 @@ export declare function authenticatePersonalToken(req: FastifyRequest, s: Pick<A
50
50
  * `@SuperAdmin` needs a super admin (`forbidden`).
51
51
  * 5. Unsafe methods of `@Public` routes need the CSRF header, cookie or not.
52
52
  * The account state is read live from PG on every request, never cached in the process.
53
+ * The default HTTP quota runs next and uses the principal placed on the request here.
53
54
  * Extension routes `/plugins/*` do not go through Nest or this guard: the plugin dispatch
54
55
  * authenticates them by their declared access (plugin-route-access.ts, personal tokens only).
55
56
  */
@@ -142,6 +142,7 @@ export async function authenticatePersonalToken(req, s) {
142
142
  * `@SuperAdmin` needs a super admin (`forbidden`).
143
143
  * 5. Unsafe methods of `@Public` routes need the CSRF header, cookie or not.
144
144
  * The account state is read live from PG on every request, never cached in the process.
145
+ * The default HTTP quota runs next and uses the principal placed on the request here.
145
146
  * Extension routes `/plugins/*` do not go through Nest or this guard: the plugin dispatch
146
147
  * authenticates them by their declared access (plugin-route-access.ts, personal tokens only).
147
148
  */
@@ -0,0 +1,3 @@
1
+ import type { KernelDb } from "../infra/database/kernel-db.js";
2
+ /** The caller's transaction holds the shared account lock until the admitted write commits. */
3
+ export declare function lockAccountForAdmission(db: KernelDb, accountId: string): Promise<void>;
@@ -0,0 +1,14 @@
1
+ import { ApiError } from "../errors.js";
2
+ /** The caller's transaction holds the shared account lock until the admitted write commits. */
3
+ export async function lockAccountForAdmission(db, accountId) {
4
+ const account = await db
5
+ .selectFrom("accounts")
6
+ .select("erasure_requested")
7
+ .where("id", "=", accountId)
8
+ .forShare()
9
+ .executeTakeFirst();
10
+ if (!account)
11
+ throw new ApiError("account.not_found", "Account not found");
12
+ if (account.erasure_requested)
13
+ throw new ApiError("conflict", "Account erasure is in progress");
14
+ }
@@ -15,6 +15,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
15
15
  import { TransactionHost } from "../infra/database/transaction-host.js";
16
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
17
17
  import { audit } from "./audit.js";
18
+ import { lockAccountForAdmission } from "./erasure-admission.js";
18
19
  import { ExternalIdentityLock } from "./external-identity-lock.js";
19
20
  import { LoginSourcesService } from "./login-sources.js";
20
21
  import { decideSsoCallback } from "./sso-decisions.js";
@@ -111,6 +112,7 @@ let ExternalIdentities = class ExternalIdentities {
111
112
  await this.lockIdentity(id);
112
113
  const existing = await this.findRow(id);
113
114
  if (existing !== undefined) {
115
+ await lockAccountForAdmission(this.db, existing.accountId);
114
116
  await this.refreshIdentity(id);
115
117
  return { accountId: existing.accountId, created: false };
116
118
  }
@@ -173,6 +175,7 @@ let ExternalIdentities = class ExternalIdentities {
173
175
  }
174
176
  case "signin":
175
177
  case "refresh":
178
+ await lockAccountForAdmission(this.db, decision.accountId);
176
179
  await this.refreshIdentity(id);
177
180
  break;
178
181
  case "upgrade":
@@ -215,6 +218,7 @@ let ExternalIdentities = class ExternalIdentities {
215
218
  async linkVerified(accountId, identity, via) {
216
219
  const id = normalize(identity);
217
220
  await this.lockIdentity(id);
221
+ await lockAccountForAdmission(this.db, accountId);
218
222
  const row = await this.findRow(id);
219
223
  if (row !== undefined && row.accountId !== accountId)
220
224
  throw taken();
@@ -339,6 +343,7 @@ let ExternalIdentities = class ExternalIdentities {
339
343
  async link(accountId, identity) {
340
344
  const id = normalize(identity);
341
345
  await this.lockIdentity(id);
346
+ await lockAccountForAdmission(this.db, accountId);
342
347
  const owner = await this.findAccount(id.source, id.externalId);
343
348
  if (owner !== undefined && owner !== accountId)
344
349
  throw taken();
@@ -21,6 +21,7 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
21
21
  import { KEYRING, REDIS } from "../infra/tokens.js";
22
22
  import { deletePushRegistrationsForSessions } from "../push/registration-cleanup.js";
23
23
  import { ACCOUNT_COLUMNS, toAccount } from "./accounts.js";
24
+ import { lockAccountForAdmission } from "./erasure-admission.js";
24
25
  import { sha256Hex } from "./hash.js";
25
26
  /** 旧 refresh token 在被轮换后多久内重放视为并发刷新(不吊销会话)。 */
26
27
  export const REFRESH_RACE_GRACE_MS = 30_000;
@@ -62,6 +63,7 @@ let SessionService = class SessionService {
62
63
  * commit.
63
64
  */
64
65
  async create(accountId, meta) {
66
+ await lockAccountForAdmission(this.db, accountId);
65
67
  const id = randomUUID();
66
68
  const refreshToken = newRefreshToken();
67
69
  const refreshTtlDays = this.config.get().auth.refreshTokenTtlDays;
@@ -371,6 +373,9 @@ let SessionService = class SessionService {
371
373
  };
372
374
  }
373
375
  };
376
+ __decorate([
377
+ Transactional()
378
+ ], SessionService.prototype, "create", null);
374
379
  __decorate([
375
380
  Transactional()
376
381
  ], SessionService.prototype, "revokeIn", null);
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { type PlatformAttributionPatch, type PlatformAttributionStored, type PlatformAttributionView } from "../attribution/platform-attribution.js";
3
3
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
4
4
  import { type DevicesDefaultProviderPatch, type DevicesDefaultProviderView } from "../devices/default-provider-setting.js";
5
+ import { CacheService } from "../infra/cache/cache.service.js";
5
6
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
7
  import { KernelDb } from "../infra/database/kernel-db.js";
7
8
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -156,6 +157,52 @@ export declare const DEPLOYMENT_SETTINGS: z.ZodObject<{
156
157
  super_admin: "super_admin";
157
158
  }>>;
158
159
  runConcurrencyOverrides: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;
160
+ retention: z.ZodDefault<z.ZodPipe<z.ZodObject<{
161
+ conversationDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
162
+ auditDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
163
+ usageDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
164
+ platformAuditDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
165
+ }, z.core.$strict>, z.ZodTransform<{
166
+ conversationDays: number | null;
167
+ auditDays: number | null;
168
+ usageDays: number | null;
169
+ platformAuditDays: number | null;
170
+ }, {
171
+ conversationDays?: number | null | undefined;
172
+ auditDays?: number | null | undefined;
173
+ usageDays?: number | null | undefined;
174
+ platformAuditDays?: number | null | undefined;
175
+ }>>>;
176
+ modelBudgets: z.ZodDefault<z.ZodObject<{
177
+ orgDefault: z.ZodOptional<z.ZodObject<{
178
+ tokens: z.ZodOptional<z.ZodNumber>;
179
+ spend: z.ZodOptional<z.ZodObject<{
180
+ amount: z.ZodString;
181
+ currency: z.ZodString;
182
+ }, z.core.$strict>>;
183
+ }, z.core.$strict>>;
184
+ orgCeiling: z.ZodOptional<z.ZodObject<{
185
+ tokens: z.ZodOptional<z.ZodNumber>;
186
+ spend: z.ZodOptional<z.ZodObject<{
187
+ amount: z.ZodString;
188
+ currency: z.ZodString;
189
+ }, z.core.$strict>>;
190
+ }, z.core.$strict>>;
191
+ memberDefault: z.ZodOptional<z.ZodObject<{
192
+ tokens: z.ZodOptional<z.ZodNumber>;
193
+ spend: z.ZodOptional<z.ZodObject<{
194
+ amount: z.ZodString;
195
+ currency: z.ZodString;
196
+ }, z.core.$strict>>;
197
+ }, z.core.$strict>>;
198
+ memberCeiling: z.ZodOptional<z.ZodObject<{
199
+ tokens: z.ZodOptional<z.ZodNumber>;
200
+ spend: z.ZodOptional<z.ZodObject<{
201
+ amount: z.ZodString;
202
+ currency: z.ZodString;
203
+ }, z.core.$strict>>;
204
+ }, z.core.$strict>>;
205
+ }, z.core.$strict>>;
159
206
  priceCurrency: z.ZodDefault<z.ZodString>;
160
207
  sandboxLimitOverrides: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
161
208
  cpu: z.ZodOptional<z.ZodNumber>;
@@ -245,6 +292,43 @@ export declare const DEPLOYMENT_SETTINGS_PATCH: z.ZodObject<{
245
292
  super_admin: "super_admin";
246
293
  }>>;
247
294
  runConcurrencyOverrides: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodNumber>>>;
295
+ retention: z.ZodOptional<z.ZodObject<{
296
+ conversationDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
297
+ auditDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
298
+ usageDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
299
+ platformAuditDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
300
+ }, z.core.$strict>>;
301
+ confirmRetentionShortening: z.ZodOptional<z.ZodLiteral<true>>;
302
+ modelBudgets: z.ZodOptional<z.ZodNullable<z.ZodObject<{
303
+ orgDefault: z.ZodOptional<z.ZodObject<{
304
+ tokens: z.ZodOptional<z.ZodNumber>;
305
+ spend: z.ZodOptional<z.ZodObject<{
306
+ amount: z.ZodString;
307
+ currency: z.ZodString;
308
+ }, z.core.$strict>>;
309
+ }, z.core.$strict>>;
310
+ orgCeiling: z.ZodOptional<z.ZodObject<{
311
+ tokens: z.ZodOptional<z.ZodNumber>;
312
+ spend: z.ZodOptional<z.ZodObject<{
313
+ amount: z.ZodString;
314
+ currency: z.ZodString;
315
+ }, z.core.$strict>>;
316
+ }, z.core.$strict>>;
317
+ memberDefault: z.ZodOptional<z.ZodObject<{
318
+ tokens: z.ZodOptional<z.ZodNumber>;
319
+ spend: z.ZodOptional<z.ZodObject<{
320
+ amount: z.ZodString;
321
+ currency: z.ZodString;
322
+ }, z.core.$strict>>;
323
+ }, z.core.$strict>>;
324
+ memberCeiling: z.ZodOptional<z.ZodObject<{
325
+ tokens: z.ZodOptional<z.ZodNumber>;
326
+ spend: z.ZodOptional<z.ZodObject<{
327
+ amount: z.ZodString;
328
+ currency: z.ZodString;
329
+ }, z.core.$strict>>;
330
+ }, z.core.$strict>>;
331
+ }, z.core.$strict>>>;
248
332
  priceCurrency: z.ZodOptional<z.ZodString>;
249
333
  sandboxLimitOverrides: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodObject<{
250
334
  cpu: z.ZodOptional<z.ZodNumber>;
@@ -397,9 +481,10 @@ export declare class SettingsService {
397
481
  /** The startup config's `devices.outsideSandbox` / `devices.network.*`, which win over the stored choice. */
398
482
  private readonly config;
399
483
  private readonly ceilings;
484
+ private readonly budgetCache?;
400
485
  constructor(db: KernelDb, txHost: TransactionHost, adminLock: SuperAdminLock, log: Pick<KernelLogger, "warn">,
401
486
  /** The startup config's `devices.outsideSandbox` / `devices.network.*`, which win over the stored choice. */
402
- config: Pick<KernelConfigService, "get" | "fieldSource">, ceilings: PermissionCeilingWrites);
487
+ config: Pick<KernelConfigService, "get" | "fieldSource">, ceilings: PermissionCeilingWrites, budgetCache?: CacheService | undefined);
403
488
  /** The settings with the platform's device sandbox settings and attribution defaults in effect. */
404
489
  view(): Promise<DeploymentSettingsView>;
405
490
  private attributionView;