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

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 (174) 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/channels/connections.service.d.ts +1 -1
  16. package/dist/client/client-reports.service.js +12 -0
  17. package/dist/config/schema.d.ts +8 -1
  18. package/dist/config/schema.js +43 -1
  19. package/dist/conversations/conversations.service.d.ts +9 -1
  20. package/dist/conversations/conversations.service.js +112 -15
  21. package/dist/conversations/event-log.d.ts +2 -0
  22. package/dist/conversations/event-log.js +77 -0
  23. package/dist/conversations/events.d.ts +11 -0
  24. package/dist/conversations/events.js +13 -1
  25. package/dist/conversations/prompt-suggestions.js +4 -0
  26. package/dist/conversations/titles.js +3 -2
  27. package/dist/db/kernel-schema.d.ts +71 -8
  28. package/dist/devices/devices.service.d.ts +13 -1
  29. package/dist/devices/devices.service.js +122 -9
  30. package/dist/erasure/account-batches.d.ts +9 -0
  31. package/dist/erasure/account-batches.js +567 -0
  32. package/dist/erasure/account-files.d.ts +34 -0
  33. package/dist/erasure/account-files.js +217 -0
  34. package/dist/erasure/account-residual.d.ts +15 -0
  35. package/dist/erasure/account-residual.js +149 -0
  36. package/dist/erasure/account-worker.d.ts +32 -0
  37. package/dist/erasure/account-worker.js +392 -0
  38. package/dist/erasure/device-cleanup.d.ts +23 -0
  39. package/dist/erasure/device-cleanup.js +221 -0
  40. package/dist/erasure/erasure.module.d.ts +2 -0
  41. package/dist/erasure/erasure.module.js +14 -0
  42. package/dist/erasure/external-evidence.d.ts +4 -0
  43. package/dist/erasure/external-evidence.js +28 -0
  44. package/dist/erasure/jobs.d.ts +5 -0
  45. package/dist/erasure/jobs.js +20 -0
  46. package/dist/erasure/org-batches.d.ts +11 -0
  47. package/dist/erasure/org-batches.js +159 -0
  48. package/dist/erasure/org-catalog.d.ts +2 -0
  49. package/dist/erasure/org-catalog.js +34 -0
  50. package/dist/erasure/org-rules.d.ts +14 -0
  51. package/dist/erasure/org-rules.js +227 -0
  52. package/dist/erasure/org-worker.d.ts +38 -0
  53. package/dist/erasure/org-worker.js +501 -0
  54. package/dist/erasure/requests.d.ts +61 -0
  55. package/dist/erasure/requests.js +180 -0
  56. package/dist/erasure/sweep.job.d.ts +19 -0
  57. package/dist/erasure/sweep.job.js +130 -0
  58. package/dist/erasure/worker.d.ts +17 -0
  59. package/dist/erasure/worker.js +110 -0
  60. package/dist/errors.d.ts +4 -0
  61. package/dist/errors.js +4 -0
  62. package/dist/evals/judge.d.ts +5 -0
  63. package/dist/evals/judge.js +16 -1
  64. package/dist/evals/run-replay.js +12 -1
  65. package/dist/evals/step-replay.d.ts +5 -3
  66. package/dist/evals/step-replay.js +9 -5
  67. package/dist/evals/worker.d.ts +2 -0
  68. package/dist/evals/worker.js +60 -16
  69. package/dist/files/blob-objects.d.ts +7 -3
  70. package/dist/files/blob-objects.js +39 -22
  71. package/dist/files/blob-sweep.job.d.ts +11 -0
  72. package/dist/files/blob-sweep.job.js +67 -6
  73. package/dist/http/api.module.js +5 -1
  74. package/dist/identity/accounts.js +3 -0
  75. package/dist/identity/api-tokens.js +5 -0
  76. package/dist/identity/auth.guard.d.ts +1 -0
  77. package/dist/identity/auth.guard.js +1 -0
  78. package/dist/identity/erasure-admission.d.ts +3 -0
  79. package/dist/identity/erasure-admission.js +14 -0
  80. package/dist/identity/external.js +5 -0
  81. package/dist/identity/sessions.js +5 -0
  82. package/dist/identity/settings.d.ts +86 -1
  83. package/dist/identity/settings.js +38 -4
  84. package/dist/infra/config/kernel-config.service.js +1 -0
  85. package/dist/infra/metrics/kernel-metrics.d.ts +18 -0
  86. package/dist/infra/metrics/kernel-metrics.js +54 -0
  87. package/dist/infra/metrics/operational-metrics.d.ts +31 -0
  88. package/dist/infra/metrics/operational-metrics.js +188 -0
  89. package/dist/infra/outbox/registry.d.ts +23 -0
  90. package/dist/infra/outbox/registry.js +12 -0
  91. package/dist/infra/throttler/credential-throttler.js +8 -1
  92. package/dist/infra/throttler/named-throttlers.d.ts +6 -0
  93. package/dist/infra/throttler/named-throttlers.js +6 -0
  94. package/dist/infra/throttler/principal-throttler.guard.d.ts +10 -0
  95. package/dist/infra/throttler/principal-throttler.guard.js +50 -0
  96. package/dist/infra/throttler/redis-throttler-storage.d.ts +1 -0
  97. package/dist/infra/throttler/redis-throttler-storage.js +27 -5
  98. package/dist/infra/throttler/throttler.guard.d.ts +2 -3
  99. package/dist/infra/throttler/throttler.guard.js +2 -3
  100. package/dist/infra/throttler/throttler.module.js +3 -2
  101. package/dist/models/budget-admission.d.ts +31 -0
  102. package/dist/models/budget-admission.js +149 -0
  103. package/dist/models/budget-counters.d.ts +28 -0
  104. package/dist/models/budget-counters.js +117 -0
  105. package/dist/models/budget-policy.d.ts +88 -0
  106. package/dist/models/budget-policy.js +78 -0
  107. package/dist/models/embeddings.js +13 -2
  108. package/dist/models/images.js +12 -2
  109. package/dist/models/purposes.d.ts +5 -2
  110. package/dist/models/purposes.js +9 -5
  111. package/dist/orgs/invitations.service.d.ts +1 -1
  112. package/dist/orgs/members.service.d.ts +28 -1
  113. package/dist/orgs/members.service.js +74 -11
  114. package/dist/orgs/offboarding.js +4 -6
  115. package/dist/orgs/org-owner.d.ts +2 -0
  116. package/dist/orgs/org-owner.js +21 -6
  117. package/dist/orgs/orgs.controller.d.ts +22 -0
  118. package/dist/orgs/orgs.controller.js +24 -0
  119. package/dist/orgs/orgs.module.js +4 -0
  120. package/dist/orgs/orgs.schemas.js +7 -0
  121. package/dist/orgs/orgs.service.d.ts +5 -1
  122. package/dist/orgs/orgs.service.js +28 -3
  123. package/dist/orgs/settings.controller.js +6 -1
  124. package/dist/orgs/settings.service.d.ts +58 -1
  125. package/dist/orgs/settings.service.js +74 -9
  126. package/dist/platform/exclusions.js +20 -1
  127. package/dist/platform/ops/accounts.ops.js +58 -1
  128. package/dist/platform/ops/admin.ops.js +13 -5
  129. package/dist/platform/ops/org-settings.ops.js +11 -4
  130. package/dist/platform/ops/orgs.ops.js +28 -0
  131. package/dist/platform/ops/retention.d.ts +16 -0
  132. package/dist/platform/ops/retention.js +21 -0
  133. package/dist/retention/jobs.d.ts +21 -0
  134. package/dist/retention/jobs.js +48 -0
  135. package/dist/retention/policy.d.ts +70 -0
  136. package/dist/retention/policy.js +103 -0
  137. package/dist/retention/purge-batch.d.ts +17 -0
  138. package/dist/retention/purge-batch.js +355 -0
  139. package/dist/retention/report-obligations.d.ts +12 -0
  140. package/dist/retention/report-obligations.js +71 -0
  141. package/dist/retention/sweep.job.d.ts +17 -0
  142. package/dist/retention/sweep.job.js +95 -0
  143. package/dist/retention/worker.d.ts +29 -0
  144. package/dist/retention/worker.js +306 -0
  145. package/dist/roles/worker.module.js +12 -2
  146. package/dist/runtime/maintenance.d.ts +5 -1
  147. package/dist/runtime/maintenance.js +20 -2
  148. package/dist/runtime/model-call.d.ts +3 -1
  149. package/dist/runtime/model-call.js +25 -3
  150. package/dist/runtime/providers.d.ts +7 -2
  151. package/dist/runtime/providers.js +76 -10
  152. package/dist/runtime/quota.d.ts +12 -12
  153. package/dist/runtime/quota.js +42 -37
  154. package/dist/runtime/run-finish.js +2 -0
  155. package/dist/runtime/run-principal.d.ts +9 -0
  156. package/dist/runtime/run-principal.js +18 -0
  157. package/dist/runtime/run-worker.js +48 -10
  158. package/dist/runtime/usage-report-jobs.d.ts +4 -1
  159. package/dist/runtime/usage-report-jobs.js +36 -13
  160. package/dist/runtime/usage-report.d.ts +5 -3
  161. package/dist/runtime/usage-report.js +37 -19
  162. package/dist/sandbox/review/classifier.d.ts +2 -2
  163. package/dist/sandbox/review/classifier.js +6 -2
  164. package/dist/sandbox/sandbox.service.js +18 -7
  165. package/dist/storage/purge.js +5 -1
  166. package/dist/storage/storage.service.d.ts +17 -1
  167. package/dist/storage/storage.service.js +75 -4
  168. package/dist/tools/builtins/vision/read-image.js +3 -0
  169. package/dist/tools/builtins/web/extract.js +3 -0
  170. package/dist/tools/pipeline.js +5 -1
  171. package/package.json +3 -1
  172. package/src/migrations/0216_model_budget_counters.sql +24 -0
  173. package/src/migrations/0217_retention.sql +44 -0
  174. package/src/migrations/0218_data_erasure.sql +41 -0
@@ -1,5 +1,6 @@
1
1
  import { OwnedItems } from "../catalog/owned-items.js";
2
2
  import { PluginScopeSync } from "../catalog/scope-sync.js";
3
+ import { ErasureRequests } from "../erasure/requests.js";
3
4
  import { EvalBudget } from "../evals/budget.js";
4
5
  import { LifecycleHooks } from "../extensions/lifecycle-hooks.js";
5
6
  import type { Account } from "../identity/accounts.js";
@@ -10,6 +11,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
10
11
  import { KernelEvents } from "../infra/events/kernel-events.js";
11
12
  import { OutboxService } from "../infra/outbox/outbox.service.js";
12
13
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
14
+ import { StorageService } from "../storage/storage.service.js";
13
15
  import { OrgLock } from "./org-lock.js";
14
16
  import type { OrgRole } from "./roles.js";
15
17
  export type Org = {
@@ -43,6 +45,8 @@ export declare class OrgsService {
43
45
  /** Records `org.deleted` for the subscribing plugins in the delete's transaction. */
44
46
  private readonly lifecycle;
45
47
  private readonly ceilings;
48
+ private readonly erasure;
49
+ private readonly storage;
46
50
  constructor(db: KernelDb, outbox: Pick<OutboxService, "add">, txHost: TransactionHost, settings: SettingsService, apiTokens: ApiTokenService, orgLock: OrgLock, events: KernelEvents,
47
51
  /** Cancels the deleted org's running eval runs (in the delete's transaction). */
48
52
  evalBudget: Pick<EvalBudget, "cancelRuns">,
@@ -51,7 +55,7 @@ export declare class OrgsService {
51
55
  /** What the deleted org owns is transferred or removed in the delete's transaction (P3-20). */
52
56
  ownedItems: Pick<OwnedItems, "onOrgDeleted">,
53
57
  /** Records `org.deleted` for the subscribing plugins in the delete's transaction. */
54
- lifecycle: Pick<LifecycleHooks, "recordIn">, ceilings: PermissionCeilingWrites);
58
+ lifecycle: Pick<LifecycleHooks, "recordIn">, ceilings: PermissionCeilingWrites, erasure: Pick<ErasureRequests, "enqueue">, storage: Pick<StorageService, "erasureIdentity">);
55
59
  /**
56
60
  * Creates an org with the actor as owner, in the caller's transaction when there is one (the
57
61
  * setup wizard creates it with the account); a slug conflict is `org.slug_taken` either way, but
@@ -13,11 +13,13 @@ import { sql } from "kysely";
13
13
  import { OwnedItems } from "../catalog/owned-items.js";
14
14
  import { cancelPendingRequests } from "../catalog/request-rules.js";
15
15
  import { PluginScopeSync } from "../catalog/scope-sync.js";
16
+ import { ErasureRequests } from "../erasure/requests.js";
16
17
  import { ApiError } from "../errors.js";
17
18
  import { EvalBudget } from "../evals/budget.js";
18
19
  import { LifecycleHooks } from "../extensions/lifecycle-hooks.js";
19
20
  import { ApiTokenService } from "../identity/api-tokens.js";
20
21
  import { audit } from "../identity/audit.js";
22
+ import { lockAccountForAdmission } from "../identity/erasure-admission.js";
21
23
  import { SettingsService } from "../identity/settings.js";
22
24
  import { afterCommit } from "../infra/database/after-commit.js";
23
25
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -30,6 +32,7 @@ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
30
32
  import { STOP_DELETED_ORG_JOB } from "../runtime/run-deletion.js";
31
33
  import { USAGE_REPORT_QUEUE } from "../runtime/usage-report-jobs.js";
32
34
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
35
+ import { StorageService } from "../storage/storage.service.js";
33
36
  import { OrgLock } from "./org-lock.js";
34
37
  /** 组织 slug:小写字母数字与 `-`,首尾不能是 `-`,1–40 个字符。 */
35
38
  export const SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;
@@ -95,6 +98,8 @@ let OrgsService = class OrgsService {
95
98
  ownedItems;
96
99
  lifecycle;
97
100
  ceilings;
101
+ erasure;
102
+ storage;
98
103
  constructor(db, outbox, txHost, settings, apiTokens, orgLock, events,
99
104
  /** Cancels the deleted org's running eval runs (in the delete's transaction). */
100
105
  evalBudget,
@@ -103,7 +108,7 @@ let OrgsService = class OrgsService {
103
108
  /** What the deleted org owns is transferred or removed in the delete's transaction (P3-20). */
104
109
  ownedItems,
105
110
  /** Records `org.deleted` for the subscribing plugins in the delete's transaction. */
106
- lifecycle, ceilings) {
111
+ lifecycle, ceilings, erasure, storage) {
107
112
  this.db = db;
108
113
  this.outbox = outbox;
109
114
  this.txHost = txHost;
@@ -116,6 +121,8 @@ let OrgsService = class OrgsService {
116
121
  this.ownedItems = ownedItems;
117
122
  this.lifecycle = lifecycle;
118
123
  this.ceilings = ceilings;
124
+ this.erasure = erasure;
125
+ this.storage = storage;
119
126
  }
120
127
  /**
121
128
  * Creates an org with the actor as owner, in the caller's transaction when there is one (the
@@ -135,6 +142,7 @@ let OrgsService = class OrgsService {
135
142
  const name = checkName(input.name);
136
143
  const slug = input.slug ?? slugFromName(name);
137
144
  checkSlug(slug);
145
+ await lockAccountForAdmission(this.db, actor.id);
138
146
  const row = await this.db
139
147
  .insertInto("orgs")
140
148
  .values({ id: randomUUID(), slug, name, created_by: actor.id })
@@ -277,6 +285,14 @@ let OrgsService = class OrgsService {
277
285
  jobId: `stop-deleted-org-${orgId}`,
278
286
  data: { orgId, byAccountId: actor.id },
279
287
  });
288
+ const installs = await this.db
289
+ .selectFrom("plugin_installs as i")
290
+ .innerJoin("catalog_items as c", "c.id", "i.item_id")
291
+ .select("c.name")
292
+ .where("i.org_id", "=", orgId)
293
+ .distinct()
294
+ .orderBy("c.name")
295
+ .execute();
280
296
  // after the org is marked deleted, so it counts as no user of what it shared (P3-18)
281
297
  await this.ownedItems.onOrgDeleted(orgId, actor.id, {
282
298
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -299,7 +315,14 @@ let OrgsService = class OrgsService {
299
315
  target: orgId,
300
316
  });
301
317
  // owed with the delete, carrying no org id, so the org's own outbox cleanup keeps them
302
- await this.lifecycle.recordIn("org.deleted", { orgId });
318
+ const lifecyclePlugins = await this.lifecycle.recordIn("org.deleted", { orgId });
319
+ await this.erasure.enqueue("org", orgId, {
320
+ plugins: [
321
+ ...new Set([...installs.map((install) => install.name), ...lifecyclePlugins]),
322
+ ].sort(),
323
+ lifecyclePlugins,
324
+ storageIdentity: this.storage.erasureIdentity(),
325
+ });
303
326
  // channel connections follow the org after the root commit (none after a rollback)
304
327
  afterCommit(() => this.events.emit("org.deleted", { orgId }));
305
328
  }
@@ -326,6 +349,8 @@ OrgsService = __decorate([
326
349
  __param(8, Inject(PluginScopeSync)),
327
350
  __param(9, Inject(OwnedItems)),
328
351
  __param(10, Inject(LifecycleHooks)),
329
- __param(11, Inject(PermissionCeilingWrites))
352
+ __param(11, Inject(PermissionCeilingWrites)),
353
+ __param(12, Inject(ErasureRequests)),
354
+ __param(13, Inject(StorageService))
330
355
  ], OrgsService);
331
356
  export { OrgsService };
@@ -11,6 +11,8 @@ import { Controller, Get, Inject, Patch } from "@nestjs/common";
11
11
  import { CurrentPrincipal, patTokenId, requireUser, } from "../identity/principal.js";
12
12
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
13
13
  import { ZBody, ZQuery } from "../infra/validation/zod-params.js";
14
+ import { resolveModelBudgets } from "../models/budget-policy.js";
15
+ import { resolveRetention } from "../retention/policy.js";
14
16
  import { CurrentOrg, OrgAction } from "./org.guard.js";
15
17
  import { OrgSecurityPatchSchema, OrgSecurityQuerySchema, OrgSecuritySettingsService, } from "./security-settings.service.js";
16
18
  import { OrgSettingsPatchSchema, OrgSettingsService, } from "./settings.service.js";
@@ -29,9 +31,12 @@ let OrgSettingsController = class OrgSettingsController {
29
31
  const p = requireUser(principal);
30
32
  // an API token may narrow auto mode and the cloud network, never widen them (auto mode spec §4.3)
31
33
  const settings = await this.settings.update(org.orgId, body, p.account.id, patTokenId(p), undefined, { onlyNarrows: patTokenId(p) !== undefined });
34
+ const deployment = await this.settings.deployment();
32
35
  return {
33
36
  settings,
34
- deployment: await this.settings.deployment(),
37
+ deployment,
38
+ effectiveRetention: resolveRetention(deployment.retention, settings.retention),
39
+ effectiveModelBudgets: resolveModelBudgets(deployment.modelBudgets, settings),
35
40
  effectiveNetwork: this.settings.effectiveNetwork(settings),
36
41
  sandboxLimits: await this.settings.sandboxLimits(org.orgId),
37
42
  };
@@ -4,10 +4,14 @@ import { type PlatformAttribution } from "../attribution/platform-attribution.js
4
4
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
5
5
  import type { ExtensionPointDefaults } from "../extensions/point-defaults.js";
6
6
  import { type CompactionSettings, type PromptCacheSettings } from "../identity/settings.js";
7
+ import { CacheService } from "../infra/cache/cache.service.js";
7
8
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
8
9
  import { KernelDb } from "../infra/database/kernel-db.js";
9
10
  import { TransactionHost } from "../infra/database/transaction-host.js";
10
11
  import type { KernelLogger } from "../log.js";
12
+ import { type SettledModelUsage } from "../models/budget-counters.js";
13
+ import { type PlatformModelBudgets, resolveModelBudgets } from "../models/budget-policy.js";
14
+ import { type OrgRetention } from "../retention/policy.js";
11
15
  import { type DeviceNetworkMode } from "../sandbox/device-sandbox.js";
12
16
  import { type DeviceSandboxSettingsView, type DevicesNetworkView, type DevicesOutsideSandboxView } from "../sandbox/device-sandbox-settings.js";
13
17
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
@@ -217,6 +221,28 @@ export declare const OrgSettingsSchema: z.ZodObject<{
217
221
  excludedHosts?: string[] | undefined;
218
222
  }>>>;
219
223
  deviceDefaultProvider: z.ZodCatch<z.ZodOptional<z.ZodString>>;
224
+ retention: z.ZodCatch<z.ZodOptional<z.ZodObject<{
225
+ conversationDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
226
+ auditDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
227
+ usageDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
228
+ }, z.core.$strict>>>;
229
+ modelBudgets: z.ZodCatch<z.ZodOptional<z.ZodObject<{
230
+ org: z.ZodOptional<z.ZodObject<{
231
+ tokens: z.ZodOptional<z.ZodNumber>;
232
+ spend: z.ZodOptional<z.ZodObject<{
233
+ amount: z.ZodString;
234
+ currency: z.ZodString;
235
+ }, z.core.$strict>>;
236
+ }, z.core.$strict>>;
237
+ memberDefault: z.ZodOptional<z.ZodObject<{
238
+ tokens: z.ZodOptional<z.ZodNumber>;
239
+ spend: z.ZodOptional<z.ZodObject<{
240
+ amount: z.ZodString;
241
+ currency: z.ZodString;
242
+ }, z.core.$strict>>;
243
+ }, z.core.$strict>>;
244
+ }, z.core.$strict>>>;
245
+ memberRunConcurrency: z.ZodCatch<z.ZodOptional<z.ZodNumber>>;
220
246
  wakeOnBackgroundTask: z.ZodCatch<z.ZodOptional<z.ZodBoolean>>;
221
247
  timeZone: z.ZodCatch<z.ZodOptional<z.ZodString>>;
222
248
  theme: z.ZodCatch<z.ZodOptional<z.ZodObject<{
@@ -317,6 +343,29 @@ export declare const OrgSettingsPatchSchema: z.ZodObject<{
317
343
  "read-only": "read-only";
318
344
  }>>;
319
345
  deviceDefaultProvider: z.ZodOptional<z.ZodNullable<z.ZodString>>;
346
+ retention: z.ZodOptional<z.ZodObject<{
347
+ conversationDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
348
+ auditDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
349
+ usageDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
350
+ }, z.core.$strict>>;
351
+ confirmRetentionShortening: z.ZodOptional<z.ZodLiteral<true>>;
352
+ modelBudgets: z.ZodOptional<z.ZodNullable<z.ZodObject<{
353
+ org: z.ZodOptional<z.ZodObject<{
354
+ tokens: z.ZodOptional<z.ZodNumber>;
355
+ spend: z.ZodOptional<z.ZodObject<{
356
+ amount: z.ZodString;
357
+ currency: z.ZodString;
358
+ }, z.core.$strict>>;
359
+ }, z.core.$strict>>;
360
+ memberDefault: z.ZodOptional<z.ZodObject<{
361
+ tokens: z.ZodOptional<z.ZodNumber>;
362
+ spend: z.ZodOptional<z.ZodObject<{
363
+ amount: z.ZodString;
364
+ currency: z.ZodString;
365
+ }, z.core.$strict>>;
366
+ }, z.core.$strict>>;
367
+ }, z.core.$strict>>>;
368
+ memberRunConcurrency: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
320
369
  wakeOnBackgroundTask: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
321
370
  outsideSandbox: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
322
371
  allowed: "allowed";
@@ -456,6 +505,9 @@ export interface OrgSettingsDeployment {
456
505
  externalSharing: ExternalSharingView;
457
506
  /** The longest expiry a share may take, in days. */
458
507
  shareMaxExpiryDays: number;
508
+ retention: OrgRetention;
509
+ modelBudgets: PlatformModelBudgets;
510
+ memberRunConcurrency: number;
459
511
  /** The platform's prompt suggestions switch (off: the org's own switch has no effect). */
460
512
  promptSuggestions: "on" | "off";
461
513
  }
@@ -463,10 +515,13 @@ export interface OrgSettingsDeployment {
463
515
  export interface OrgSettingsResponse {
464
516
  settings: OrgSettingsView;
465
517
  deployment: OrgSettingsDeployment;
518
+ effectiveRetention: OrgRetention;
519
+ effectiveModelBudgets: ReturnType<typeof resolveModelBudgets>;
466
520
  effectiveNetwork: OrgEffectiveNetwork;
467
521
  sandboxLimits: OrgSandboxLimits;
468
522
  /** Distinct ready blobs referenced by an org file or share, for user admins only. */
469
523
  fileLibraryBytes?: number;
524
+ modelBudgetUsage?: SettledModelUsage;
470
525
  }
471
526
  /** Parse the stored settings using the field-specific fallbacks in {@link OrgSettingsSchema}. */
472
527
  export declare function parseOrgSettings(raw: unknown): OrgSettings;
@@ -529,6 +584,7 @@ export declare class OrgSettingsService {
529
584
  * without a module cycle.
530
585
  */
531
586
  private readonly modules?;
587
+ private readonly budgetCache?;
532
588
  constructor(db: KernelDb, txHost: TransactionHost, orgLock: OrgLock,
533
589
  /**
534
590
  * The deployment config: `sandbox.limits` and the platform's device sandbox settings
@@ -544,7 +600,7 @@ export declare class OrgSettingsService {
544
600
  get(token: typeof ExtensionPointDefaults, opts: {
545
601
  strict: false;
546
602
  }): Pick<ExtensionPointDefaults, "providersFor">;
547
- } | undefined);
603
+ } | undefined, budgetCache?: CacheService | undefined);
548
604
  /** Parses stored settings and warns when malformed network or capability fields narrow. */
549
605
  private parseStored;
550
606
  /** The deployment defaults (what "follow the platform" means on the settings page). */
@@ -574,6 +630,7 @@ export declare class OrgSettingsService {
574
630
  effectiveNetwork(settings: Pick<OrgSettings, "deviceNetwork">): OrgEffectiveNetwork;
575
631
  /** 组织实际生效的沙箱 cpu / 内存(只读;由超级管理员在部署设置里覆盖)。 */
576
632
  sandboxLimits(orgId: string): Promise<OrgSandboxLimits>;
633
+ effectiveRetention(orgId: string): Promise<OrgRetention>;
577
634
  view(orgId: string, role: OrgRole | null): Promise<OrgSettingsResponse>;
578
635
  private fileLibraryBytes;
579
636
  get(orgId: string): Promise<OrgSettingsView>;
@@ -17,11 +17,16 @@ import { ApiError } from "../errors.js";
17
17
  import { blobUnreferenced } from "../files/blob-references.js";
18
18
  import { audit } from "../identity/audit.js";
19
19
  import { COMPACTION_SETTINGS_PARTIAL, COMPACTION_SETTINGS_PATCH, PROMPT_CACHE_SETTINGS_PARTIAL, PROMPT_CACHE_SETTINGS_PATCH, readPlatformCompactionSettings, readPlatformPromptCacheSettings, readPromptSuggestions, readSandboxLimitOverride, } from "../identity/settings.js";
20
+ import { CacheService } from "../infra/cache/cache.service.js";
20
21
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
22
+ import { afterCommit } from "../infra/database/after-commit.js";
21
23
  import { KernelDb } from "../infra/database/kernel-db.js";
22
24
  import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
23
25
  import { Transactional } from "../infra/database/transactional.decorator.js";
24
26
  import { KERNEL_LOGGER } from "../infra/tokens.js";
27
+ import { readSettledModelUsage } from "../models/budget-counters.js";
28
+ import { OrgModelBudgetsSchema, orgModelBudgetCacheKey, readPlatformModelBudgets, resolveModelBudgets, } from "../models/budget-policy.js";
29
+ import { confirmRetentionChange, mergeOrgRetention, OFF_RETENTION, OrgRetentionSchema, platformRetentionRow, readOrgRetention, readPlatformRetention, resolveRetention, } from "../retention/policy.js";
25
30
  import { hostGrantable, hostGrantCeiling, } from "../sandbox/device-sandbox.js";
26
31
  import { AllowedProfilesSchema, effectiveAllowedProfiles, effectiveProjectReach, OrgDeviceSandboxStoredSchema, ProjectReachSchema, readDeviceSandboxSettingsView, } from "../sandbox/device-sandbox-settings.js";
27
32
  import { coversHost, orgCloudMode, orgEffectiveHosts, orgHostOutsideCeiling, } from "../sandbox/modes.js";
@@ -199,6 +204,11 @@ export const OrgSettingsSchema = z.object({
199
204
  deviceNetwork: OrgDeviceSandboxStoredSchema.shape.deviceNetwork,
200
205
  /** The org's default device provider; absent follows the platform. */
201
206
  deviceDefaultProvider: DeviceProviderName.optional().catch(undefined),
207
+ // Workers validate raw policy before deleting. Unrelated org settings remain readable.
208
+ retention: OrgRetentionSchema.partial().optional().catch(undefined),
209
+ // Admission validates the raw policy separately. General org reads tolerate malformed budgets.
210
+ modelBudgets: OrgModelBudgetsSchema.optional().catch(undefined),
211
+ memberRunConcurrency: z.number().int().nonnegative().optional().catch(undefined),
202
212
  /** Overrides `runtime.wakeOnBackgroundTask`; absent follows the deployment. */
203
213
  wakeOnBackgroundTask: z.boolean().optional().catch(undefined),
204
214
  /** The org's default time zone (run context spec §3.3); absent = UTC. */
@@ -247,6 +257,10 @@ export const OrgSettingsPatchSchema = z
247
257
  */
248
258
  deviceDefaultProvider: DeviceProviderName.nullable().optional(),
249
259
  /** null clears (follow the deployment again). */
260
+ retention: OrgRetentionSchema.partial().optional(),
261
+ confirmRetentionShortening: z.literal(true).optional(),
262
+ modelBudgets: OrgModelBudgetsSchema.nullable().optional(),
263
+ memberRunConcurrency: z.number().int().nonnegative().nullable().optional(),
250
264
  wakeOnBackgroundTask: z.boolean().nullable().optional(),
251
265
  /**
252
266
  * The org's outside-sandbox ceiling; null clears it (follow the platform). `allowed` while the
@@ -411,6 +425,7 @@ let OrgSettingsService = class OrgSettingsService {
411
425
  ceilings;
412
426
  log;
413
427
  modules;
428
+ budgetCache;
414
429
  constructor(db, txHost, orgLock,
415
430
  /**
416
431
  * The deployment config: `sandbox.limits` and the platform's device sandbox settings
@@ -422,7 +437,7 @@ let OrgSettingsService = class OrgSettingsService {
422
437
  * providers on in the org) at the time of use: the extensions module cannot be imported here
423
438
  * without a module cycle.
424
439
  */
425
- modules) {
440
+ modules, budgetCache) {
426
441
  this.db = db;
427
442
  this.txHost = txHost;
428
443
  this.orgLock = orgLock;
@@ -430,6 +445,7 @@ let OrgSettingsService = class OrgSettingsService {
430
445
  this.ceilings = ceilings;
431
446
  this.log = log;
432
447
  this.modules = modules;
448
+ this.budgetCache = budgetCache;
433
449
  }
434
450
  /** Parses stored settings and warns when malformed network or capability fields narrow. */
435
451
  parseStored(orgId, raw) {
@@ -454,7 +470,7 @@ let OrgSettingsService = class OrgSettingsService {
454
470
  /** The deployment defaults (what "follow the platform" means on the settings page). */
455
471
  async deployment() {
456
472
  const lim = this.config.get().sandbox.limits;
457
- const [deviceSandbox, attribution, compaction, promptCache, externalSharing, shareMaxExpiry, promptSuggestions,] = await Promise.all([
473
+ const [deviceSandbox, attribution, compaction, promptCache, externalSharing, shareMaxExpiry, promptSuggestions, modelBudgets, retention,] = await Promise.all([
458
474
  readDeviceSandboxSettingsView(this.db.db, this.config, this.log),
459
475
  readPlatformAttribution(this.db.db, this.config, this.log),
460
476
  readPlatformCompactionSettings(this.db.db),
@@ -462,6 +478,8 @@ let OrgSettingsService = class OrgSettingsService {
462
478
  readExternalSharing(this.db.db, this.config, this.log),
463
479
  readShareMaxExpiry(this.db.db, this.config, this.log),
464
480
  readPromptSuggestions(this.db.db, this.log),
481
+ readPlatformModelBudgets(this.db.db),
482
+ readPlatformRetention(this.db.db),
465
483
  ]);
466
484
  return {
467
485
  outsideSandbox: deviceSandbox.outsideSandbox,
@@ -474,6 +492,9 @@ let OrgSettingsService = class OrgSettingsService {
474
492
  off: lim.egress === "none",
475
493
  },
476
494
  attribution,
495
+ modelBudgets,
496
+ retention: resolveRetention(retention),
497
+ memberRunConcurrency: this.config.get().runtime.memberRunConcurrency,
477
498
  publicUrl: this.config.get().http.publicUrl !== undefined,
478
499
  compaction,
479
500
  promptCache,
@@ -570,15 +591,24 @@ let OrgSettingsService = class OrgSettingsService {
570
591
  source: override === undefined ? "deployment" : "override",
571
592
  };
572
593
  }
594
+ effectiveRetention(orgId) {
595
+ return readOrgRetention(this.db.db, orgId);
596
+ }
573
597
  async view(orgId, role) {
574
598
  const settings = await this.get(orgId);
599
+ const deployment = await this.deployment();
575
600
  return {
576
601
  settings,
577
- deployment: await this.deployment(),
602
+ deployment,
603
+ effectiveRetention: resolveRetention(deployment.retention, settings.retention),
604
+ effectiveModelBudgets: resolveModelBudgets(deployment.modelBudgets, settings),
578
605
  effectiveNetwork: this.effectiveNetwork(settings),
579
606
  sandboxLimits: await this.sandboxLimits(orgId),
580
607
  ...(role !== null && can(role, "org.update")
581
- ? { fileLibraryBytes: await this.fileLibraryBytes(orgId) }
608
+ ? {
609
+ fileLibraryBytes: await this.fileLibraryBytes(orgId),
610
+ modelBudgetUsage: await readSettledModelUsage(this.db.db, orgId, null, new Date()),
611
+ }
582
612
  : {}),
583
613
  };
584
614
  }
@@ -688,6 +718,8 @@ let OrgSettingsService = class OrgSettingsService {
688
718
  await this.orgLock.lockAndAuthorize(orgId, actorAccountId, "org.update");
689
719
  if (patch.outsideSandbox !== undefined || patch.deviceNetwork !== undefined)
690
720
  await this.ceilings.lock({ orgId }, "org");
721
+ if (patch.retention !== undefined)
722
+ await platformRetentionRow(this.db.db, "share");
691
723
  }
692
724
  /**
693
725
  * Refuses a patch that widens the org's sandbox (only a person widens it, never the Platform tool
@@ -744,7 +776,7 @@ let OrgSettingsService = class OrgSettingsService {
744
776
  if (opts?.onlyNarrows)
745
777
  await this.assertOnlyNarrows(before, patch);
746
778
  const changes = Object.fromEntries(Object.entries(patch)
747
- .filter(([, v]) => v !== undefined)
779
+ .filter(([key, v]) => key !== "confirmRetentionShortening" && v !== undefined)
748
780
  // null clears outsideSandbox / deviceNetwork / wakeOnBackgroundTask (follow the deployment
749
781
  // again), externalSharing (off) and promptSuggestions (follow the platform)
750
782
  .map(([k, v]) => [k, v === null ? undefined : v]));
@@ -756,6 +788,22 @@ let OrgSettingsService = class OrgSettingsService {
756
788
  delete changes.automations;
757
789
  delete changes.compaction;
758
790
  const after = { ...before, ...changes };
791
+ let retentionAudit = {};
792
+ let repairsRetention = false;
793
+ if (patch.retention !== undefined) {
794
+ const platform = await readPlatformRetention(this.db.db);
795
+ repairsRetention = Object.hasOwn(stored, "retention") && before.retention === undefined;
796
+ const merged = mergeOrgRetention(platform, before.retention, patch.retention);
797
+ retentionAudit = confirmRetentionChange(repairsRetention
798
+ ? resolveRetention(OFF_RETENTION)
799
+ : resolveRetention(platform, before.retention), resolveRetention(platform, merged), patch.confirmRetentionShortening === true &&
800
+ !opts?.onlyNarrows &&
801
+ actorTokenId === undefined);
802
+ if (Object.keys(merged).length)
803
+ after.retention = merged;
804
+ else
805
+ delete after.retention;
806
+ }
759
807
  if (patch.automations !== undefined) {
760
808
  after.automations = AutomationsSettingsSchema.parse({
761
809
  ...before.automations,
@@ -780,6 +828,10 @@ let OrgSettingsService = class OrgSettingsService {
780
828
  if (Object.keys(after.uiArrangement).length === 0)
781
829
  delete after.uiArrangement;
782
830
  }
831
+ if (after.memberRunConcurrency === undefined)
832
+ delete after.memberRunConcurrency;
833
+ if (after.modelBudgets === undefined)
834
+ delete after.modelBudgets;
783
835
  if (after.allowedProfiles === undefined)
784
836
  delete after.allowedProfiles;
785
837
  if (after.projectReach === undefined)
@@ -817,7 +869,8 @@ let OrgSettingsService = class OrgSettingsService {
817
869
  delete after.externalSharing;
818
870
  if (after.promptSuggestions === undefined)
819
871
  delete after.promptSuggestions;
820
- if (sameSettings(before, after))
872
+ const clearsStoredBudget = patch.modelBudgets === null && Object.hasOwn(stored, "modelBudgets");
873
+ if (!repairsRetention && !clearsStoredBudget && sameSettings(before, after))
821
874
  return before;
822
875
  // Lock order: the org row (orgLock above), then the theme's catalog item and its row FOR
823
876
  // SHARE (assertThemeOnIn), then the check, so no scope writer changes what it read first
@@ -825,8 +878,15 @@ let OrgSettingsService = class OrgSettingsService {
825
878
  await assertThemeOnIn(this.db.db, orgId, patch.theme.id);
826
879
  }
827
880
  // Preserve unknown settings and apply cleared optional fields.
828
- const { allowedProfiles: _oldProfiles, projectReach: _oldReach, outsideSandbox: _oldOutside, deviceNetwork: _oldNetwork, deviceDefaultProvider: _oldDeviceProvider, wakeOnBackgroundTask: _oldWake, timeZone: _oldZone, theme: _oldTheme, uiArrangement: _oldArrangement, navigation: _oldNavigation, automations: _oldAutomations, compaction: _oldCompaction, promptCache: _oldPromptCache, externalSharing: _oldExternalSharing, promptSuggestions: _oldPromptSuggestions, ...rest } = stored;
881
+ const { memberRunConcurrency: _oldMemberConcurrency, modelBudgets: _oldBudgets, retention: _oldRetention, allowedProfiles: _oldProfiles, projectReach: _oldReach, outsideSandbox: _oldOutside, deviceNetwork: _oldNetwork, deviceDefaultProvider: _oldDeviceProvider, wakeOnBackgroundTask: _oldWake, timeZone: _oldZone, theme: _oldTheme, uiArrangement: _oldArrangement, navigation: _oldNavigation, automations: _oldAutomations, compaction: _oldCompaction, promptCache: _oldPromptCache, externalSharing: _oldExternalSharing, promptSuggestions: _oldPromptSuggestions, ...rest } = stored;
829
882
  const written = { ...rest, ...after };
883
+ if (patch.retention === undefined && Object.hasOwn(stored, "retention")) {
884
+ written.retention = stored.retention;
885
+ }
886
+ // Only an explicit budget change may repair a malformed raw policy and reopen admission.
887
+ if (patch.modelBudgets === undefined && Object.hasOwn(stored, "modelBudgets")) {
888
+ written.modelBudgets = stored.modelBudgets;
889
+ }
830
890
  written.automations =
831
891
  patch.automations === undefined && Object.hasOwn(stored, "automations")
832
892
  ? stored.automations
@@ -836,13 +896,16 @@ let OrgSettingsService = class OrgSettingsService {
836
896
  .set({ settings: JSON.stringify(written) })
837
897
  .where("id", "=", orgId)
838
898
  .execute();
899
+ if (patch.modelBudgets !== undefined) {
900
+ afterCommit(() => this.budgetCache?.del(orgModelBudgetCacheKey(orgId)));
901
+ }
839
902
  await audit(this.db.db, {
840
903
  actorAccountId,
841
904
  ...(actorTokenId !== undefined && { actorTokenId }),
842
905
  orgId,
843
906
  action: "org.settings_updated",
844
907
  target: orgId,
845
- detail: { before, after, ...auditDetail },
908
+ detail: { before, after, ...retentionAudit, ...auditDetail },
846
909
  });
847
910
  if (patch.outsideSandbox !== undefined || patch.deviceNetwork !== undefined) {
848
911
  // the consent reset follows the effective values as every reader sees them (re-read from
@@ -900,7 +963,9 @@ OrgSettingsService = __decorate([
900
963
  __param(5, Optional()),
901
964
  __param(5, Inject(KERNEL_LOGGER)),
902
965
  __param(6, Optional()),
903
- __param(6, Inject(ModuleRef))
966
+ __param(6, Inject(ModuleRef)),
967
+ __param(7, Optional()),
968
+ __param(7, Inject(CacheService))
904
969
  ], OrgSettingsService);
905
970
  export { OrgSettingsService };
906
971
  /**
@@ -24,7 +24,26 @@ export const PLATFORM_EXCLUSIONS = [
24
24
  category: "human-only",
25
25
  reason: "Interactive owner session permission selection and device-bound consent",
26
26
  },
27
- // platform-admin: every route is an operation (Task 7)
27
+ {
28
+ route: "POST /api/v1/admin/accounts/:accountId/erasure",
29
+ category: "human-only",
30
+ reason: "A super admin confirms irreversible erasure in a human session. The account operation opens the confirmation page.",
31
+ },
32
+ {
33
+ route: "GET /api/v1/admin/account-erasures/:workId",
34
+ category: "human-only",
35
+ reason: "Only the super admin's human session can read a receipt. The status operation opens its web page.",
36
+ },
37
+ {
38
+ route: "GET /api/v1/admin/erasure-requests/:workId",
39
+ category: "human-only",
40
+ reason: "Only a super admin using a web session reads the erasure receipt.",
41
+ },
42
+ {
43
+ route: "POST /api/v1/admin/erasure-requests/:workId/external-disposition",
44
+ category: "human-only",
45
+ reason: "A super admin verifies the current erasure blocker and records evidence in a human session. The Platform operation opens the receipt.",
46
+ },
28
47
  // extensions-admin
29
48
  {
30
49
  route: "GET /api/v1/admin/extensions/:name/org-overrides",
@@ -9,7 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { z } from "zod";
12
- import { AccountListQuery, AccountParams, CreateAccountBody } from "../../admin/admin.schemas.js";
12
+ import { AccountListQuery, AccountParams, CreateAccountBody, ErasureWorkParams, } from "../../admin/admin.schemas.js";
13
13
  import { ApiError } from "../../errors.js";
14
14
  import { AccountsService } from "../../identity/accounts.js";
15
15
  import { InitialPasswords } from "../../identity/initial-passwords.js";
@@ -230,6 +230,63 @@ let AccountsOperations = class AccountsOperations {
230
230
  return { account: accountView(account, login), initialPassword: INITIAL_PASSWORD_NOTE };
231
231
  },
232
232
  }),
233
+ defineOperation({
234
+ id: "accounts.request-erasure",
235
+ description: "Open the accounts page so a super admin can review and confirm permanent erasure of the selected account. Opening the link never submits the request.",
236
+ input: AccountParams.strict(),
237
+ example: { accountId: "00000000-0000-4000-8000-000000000000" },
238
+ authz: { superAdmin: true },
239
+ mirrors: [],
240
+ confirm: "read",
241
+ personOnly: true,
242
+ run: async (input) => ({ accountId: (await this.account(input.accountId)).id }),
243
+ handoff: (input) => ({
244
+ kind: "handoff",
245
+ title: { en: "Review account erasure", zh: "审核账号清除请求" },
246
+ target: {
247
+ type: "link",
248
+ url: `/admin/accounts?eraseAccount=${encodeURIComponent(input.accountId)}`,
249
+ },
250
+ }),
251
+ }),
252
+ defineOperation({
253
+ id: "accounts.erasure-status",
254
+ description: "Open the access-restricted account erasure receipt on the web. A super admin uses a human session to read its status.",
255
+ input: ErasureWorkParams.strict(),
256
+ example: { workId: "00000000-0000-4000-8000-000000000000" },
257
+ authz: { superAdmin: true },
258
+ mirrors: [],
259
+ confirm: "read",
260
+ personOnly: true,
261
+ run: async (input) => ({ workId: input.workId }),
262
+ handoff: (input) => ({
263
+ kind: "handoff",
264
+ title: { en: "View erasure status", zh: "查看清除进度" },
265
+ target: {
266
+ type: "link",
267
+ url: `/admin/accounts?erasure=${encodeURIComponent(input.workId)}`,
268
+ },
269
+ }),
270
+ }),
271
+ defineOperation({
272
+ id: "platform.record-erasure-evidence",
273
+ description: "Open an erasure receipt so a super admin can review the current blocker and record verified evidence on the web. Use the work ID shown in the blocked retention list.",
274
+ input: ErasureWorkParams.strict(),
275
+ example: { workId: "00000000-0000-4000-8000-000000000000" },
276
+ authz: { superAdmin: true },
277
+ mirrors: [],
278
+ confirm: "read",
279
+ personOnly: true,
280
+ run: async ({ workId }) => ({ workId }),
281
+ handoff: ({ workId }) => ({
282
+ kind: "handoff",
283
+ title: { en: "Review erasure evidence", zh: "审核清除凭据" },
284
+ target: {
285
+ type: "link",
286
+ url: `/admin/erasure-requests/${encodeURIComponent(workId)}`,
287
+ },
288
+ }),
289
+ }),
233
290
  defineOperation({
234
291
  id: "accounts.disable",
235
292
  description: "Disable an account (super admin): it can no longer sign in, and its sessions and personal access tokens are revoked at once (enabling it again does not bring them back). You cannot disable your own account or the last active super admin.",