@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
@@ -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;
@@ -8,18 +8,22 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { EXTENSION_NAME_RE, narrowerProjectReach } from "@capybara-hq/plugin-sdk";
11
- import { Inject, Injectable } from "@nestjs/common";
11
+ import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { z } from "zod";
13
13
  import { applyPlatformAttributionPatch, PLATFORM_ATTRIBUTION_FIELDS, PLATFORM_ATTRIBUTION_PATCH, PLATFORM_ATTRIBUTION_SETTING, readStoredPlatformAttribution, resolvePlatformAttribution, } from "../attribution/platform-attribution.js";
14
14
  import { productName } from "../config/product-name.js";
15
15
  import { DEVICES_DEFAULT_PROVIDER_PATCH, DEVICES_DEFAULT_PROVIDER_SETTING, readPlatformDefaultProvider, } from "../devices/default-provider-setting.js";
16
16
  import { ApiError } from "../errors.js";
17
+ import { CacheService } from "../infra/cache/cache.service.js";
17
18
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
19
+ import { afterCommit } from "../infra/database/after-commit.js";
18
20
  import { KernelDb } from "../infra/database/kernel-db.js";
19
21
  import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
20
22
  import { Transactional } from "../infra/database/transactional.decorator.js";
21
23
  import { KERNEL_LOGGER } from "../infra/tokens.js";
24
+ import { PLATFORM_MODEL_BUDGET_CACHE_KEY, PlatformModelBudgetsSchema, } from "../models/budget-policy.js";
22
25
  import { DEFAULT_PRICE_CURRENCY, PriceCurrency } from "../models/price-snapshot.js";
26
+ import { confirmRetentionChange, OFF_RETENTION, PlatformRetentionSchema, platformRetentionRow, StoredPlatformRetentionSchema, } from "../retention/policy.js";
23
27
  import { applyDevicesNetworkPatch, applyDevicesOutsideSandboxPatch, configuredDeviceSandbox, DEVICES_ALLOWED_PROFILES_PATCH, DEVICES_ALLOWED_PROFILES_SETTING, DEVICES_NETWORK_PATCH, DEVICES_NETWORK_SETTING, DEVICES_OUTSIDE_SANDBOX_PATCH, DEVICES_OUTSIDE_SANDBOX_SETTING, DEVICES_PROJECT_REACH_PATCH, DEVICES_PROJECT_REACH_SETTING, orgDeviceSandboxOf, readDeviceSandboxSettingsView, readStoredDeviceSandbox, resolveDeviceSandboxSettings, } from "../sandbox/device-sandbox-settings.js";
24
28
  import { devicesFollowingDefault, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, reachNarrowed, } from "../sandbox/permission-ceiling-writes.js";
25
29
  import { EXTERNAL_SHARING_SETTING, ExternalSharingValue, HTML_CDN_ALLOWLIST_DEFAULT, HtmlCdnAllowlistSchema, readExternalSharing, readHtmlCdnAllowlist, readShareMaxExpiry, SHARE_MAX_EXPIRY_DEFAULT, SHARE_MAX_EXPIRY_SETTING, ShareMaxExpiryDays, } from "../shares/settings.js";
@@ -202,7 +206,9 @@ export const DEPLOYMENT_SETTINGS = z.object({
202
206
  orgCreation: z.enum(["anyone", "super_admin"]).default("anyone"),
203
207
  /** 按组织覆盖运行并发上限(orgId → 上限);未列出的组织用 `runtime.orgConcurrency`。 */
204
208
  runConcurrencyOverrides: z.record(z.string().min(1), z.number().int().positive()).default({}),
205
- /** 模型价格表(`model_prices`)的币种;只用于显示估算成本,不做换算。 */
209
+ retention: StoredPlatformRetentionSchema.default(OFF_RETENTION),
210
+ modelBudgets: PlatformModelBudgetsSchema.default({}),
211
+ /** The currency of model prices used for cost estimates, without conversion. */
206
212
  priceCurrency: PriceCurrency.default(DEFAULT_PRICE_CURRENCY),
207
213
  /** 按组织覆盖沙箱 cpu / 内存(orgId → 覆盖,C19);只对之后新建的沙箱生效。组织管理员只读。 */
208
214
  sandboxLimitOverrides: z.record(z.string().min(1), SANDBOX_LIMIT_OVERRIDE).default({}),
@@ -288,6 +294,9 @@ export const DEPLOYMENT_SETTINGS_PATCH = z
288
294
  runConcurrencyOverrides: z
289
295
  .record(z.string().min(1), z.number().int().positive().nullable())
290
296
  .optional(),
297
+ retention: PlatformRetentionSchema.partial().optional(),
298
+ confirmRetentionShortening: z.literal(true).optional(),
299
+ modelBudgets: PlatformModelBudgetsSchema.nullable().optional(),
291
300
  priceCurrency: PriceCurrency.optional(),
292
301
  sandboxLimitOverrides: z
293
302
  .record(z.string().min(1), SANDBOX_LIMIT_OVERRIDE.nullable())
@@ -552,15 +561,17 @@ let SettingsService = class SettingsService {
552
561
  log;
553
562
  config;
554
563
  ceilings;
564
+ budgetCache;
555
565
  constructor(db, txHost, adminLock, log,
556
566
  /** The startup config's `devices.outsideSandbox` / `devices.network.*`, which win over the stored choice. */
557
- config, ceilings) {
567
+ config, ceilings, budgetCache) {
558
568
  this.db = db;
559
569
  this.txHost = txHost;
560
570
  this.adminLock = adminLock;
561
571
  this.log = log;
562
572
  this.config = config;
563
573
  this.ceilings = ceilings;
574
+ this.budgetCache = budgetCache;
564
575
  }
565
576
  /** The settings with the platform's device sandbox settings and attribution defaults in effect. */
566
577
  async view() {
@@ -848,6 +859,8 @@ let SettingsService = class SettingsService {
848
859
  patch.devicesAllowedProfiles !== undefined ||
849
860
  patch.devicesProjectReach !== undefined)
850
861
  await this.ceilings.lock({}, "platform");
862
+ if (patch.retention !== undefined)
863
+ await platformRetentionRow(this.db.db, "update");
851
864
  }
852
865
  async write(patch, actorAccountId, actorTokenId, auditDetail, opts) {
853
866
  // held since the prelude (`lockFor`); naming them again re-checks the actor
@@ -855,6 +868,17 @@ let SettingsService = class SettingsService {
855
868
  // The super admin lock serializes every settings write: the current overrides are read
856
869
  // and merged under it, so no concurrent change is lost
857
870
  const next = {};
871
+ let retentionAudit = {};
872
+ if (patch.retention !== undefined) {
873
+ const raw = await platformRetentionRow(this.db.db);
874
+ const stored = StoredPlatformRetentionSchema.safeParse(raw?.value);
875
+ const before = stored.success ? stored.data : OFF_RETENTION;
876
+ const after = PlatformRetentionSchema.parse({ ...before, ...patch.retention });
877
+ retentionAudit = confirmRetentionChange(before, after, patch.confirmRetentionShortening === true &&
878
+ !opts.onlyNarrows &&
879
+ actorTokenId === undefined, !stored.success);
880
+ next.retention = after;
881
+ }
858
882
  if (patch.orgCreation !== undefined)
859
883
  next.orgCreation = patch.orgCreation;
860
884
  if (patch.priceCurrency !== undefined)
@@ -1013,6 +1037,13 @@ let SettingsService = class SettingsService {
1013
1037
  else
1014
1038
  writes.push([DEVICES_DEFAULT_PROVIDER_SETTING, patch.devicesDefaultProvider]);
1015
1039
  }
1040
+ if (patch.modelBudgets !== undefined) {
1041
+ afterCommit(() => this.budgetCache?.del(PLATFORM_MODEL_BUDGET_CACHE_KEY));
1042
+ }
1043
+ if (patch.modelBudgets === null)
1044
+ deletes.push("modelBudgets");
1045
+ else if (patch.modelBudgets !== undefined)
1046
+ writes.push(["modelBudgets", patch.modelBudgets]);
1016
1047
  if (patch.promptSuggestions === null)
1017
1048
  deletes.push(PROMPT_SUGGESTIONS_SETTING);
1018
1049
  else if (patch.promptSuggestions !== undefined) {
@@ -1039,6 +1070,7 @@ let SettingsService = class SettingsService {
1039
1070
  action: "deployment.settings.updated",
1040
1071
  detail: {
1041
1072
  ...patch,
1073
+ ...retentionAudit,
1042
1074
  ...(deviceSandboxChange !== undefined && { deviceSandboxEffective: deviceSandboxChange }),
1043
1075
  ...auditDetail,
1044
1076
  },
@@ -1061,6 +1093,8 @@ SettingsService = __decorate([
1061
1093
  __param(2, Inject(SuperAdminLock)),
1062
1094
  __param(3, Inject(KERNEL_LOGGER)),
1063
1095
  __param(4, Inject(KernelConfigService)),
1064
- __param(5, Inject(PermissionCeilingWrites))
1096
+ __param(5, Inject(PermissionCeilingWrites)),
1097
+ __param(6, Optional()),
1098
+ __param(6, Inject(CacheService))
1065
1099
  ], SettingsService);
1066
1100
  export { SettingsService };
@@ -68,6 +68,7 @@ const HOT_APPLIERS = {
68
68
  "subagents.maxDepth": () => { },
69
69
  "subagents.maxConcurrentPerConversation": () => { },
70
70
  "subagents.maxDispatchesPerRun": () => { },
71
+ "runtime.memberRunConcurrency": () => { },
71
72
  "subagents.maxTokensPerRun": () => { },
72
73
  // The web tools read these limits through the config service on every call.
73
74
  "web.search.maxResults": () => { },
@@ -0,0 +1,18 @@
1
+ import type { UsagePurpose } from "@capybara-hq/plugin-sdk";
2
+ import { type Meter } from "@opentelemetry/api";
3
+ export declare const KERNEL_METER = "capybara.kernel";
4
+ export declare const kernelMeter: () => Meter;
5
+ type Purpose = UsagePurpose | "eval";
6
+ type ModelKind = "chat" | "embedding" | "image_generation";
7
+ type AttemptOutcome = "completed" | "failed" | "aborted";
8
+ type TokenUsage = {
9
+ inputTokens: number;
10
+ outputTokens?: number;
11
+ cacheReadTokens?: number;
12
+ cacheWriteTokens?: number;
13
+ };
14
+ export declare function recordRun(outcome: "started" | "completed" | "failed" | "aborted"): void;
15
+ export declare function recordModelAttempt(kind: ModelKind, purpose: Purpose, elapsedSeconds: number, outcome: AttemptOutcome): void;
16
+ export declare function recordModelTokens(kind: ModelKind, purpose: Purpose, usage: TokenUsage | undefined): void;
17
+ export declare function recordThrottle(policy: "default" | "route" | "credential", outcome: "allowed" | "limited" | "unavailable"): void;
18
+ export {};
@@ -0,0 +1,54 @@
1
+ import { metrics } from "@opentelemetry/api";
2
+ export const KERNEL_METER = "capybara.kernel";
3
+ export const kernelMeter = () => metrics.getMeter(KERNEL_METER);
4
+ function instruments(meter) {
5
+ return {
6
+ runs: meter.createCounter("capybara.run.transitions", {
7
+ description: "Committed run starts and terminal outcomes",
8
+ unit: "{run}",
9
+ }),
10
+ tokens: meter.createCounter("capybara.model.tokens", {
11
+ description: "Tokens reported by model provider attempts",
12
+ unit: "{token}",
13
+ }),
14
+ duration: meter.createHistogram("capybara.model.attempt.duration", {
15
+ description: "Time spent in one admitted model provider attempt",
16
+ unit: "s",
17
+ }),
18
+ throttles: meter.createCounter("capybara.http.throttle", {
19
+ description: "HTTP throttler decisions by policy",
20
+ unit: "{decision}",
21
+ }),
22
+ };
23
+ }
24
+ let cached;
25
+ function counters() {
26
+ const meter = kernelMeter();
27
+ if (cached?.meter !== meter)
28
+ cached = { meter, instruments: instruments(meter) };
29
+ return cached.instruments;
30
+ }
31
+ export function recordRun(outcome) {
32
+ counters().runs.add(1, { outcome });
33
+ }
34
+ export function recordModelAttempt(kind, purpose, elapsedSeconds, outcome) {
35
+ counters().duration.record(elapsedSeconds, { kind, purpose, outcome });
36
+ }
37
+ export function recordModelTokens(kind, purpose, usage) {
38
+ if (typeof usage !== "object" || usage === null)
39
+ return;
40
+ const counts = {
41
+ input: usage.inputTokens,
42
+ output: usage.outputTokens,
43
+ cache_read: usage.cacheReadTokens,
44
+ cache_write: usage.cacheWriteTokens,
45
+ };
46
+ for (const [token_class, count] of Object.entries(counts)) {
47
+ if (typeof count === "number" && Number.isSafeInteger(count) && count > 0) {
48
+ counters().tokens.add(count, { kind, purpose, token_class });
49
+ }
50
+ }
51
+ }
52
+ export function recordThrottle(policy, outcome) {
53
+ counters().throttles.add(1, { policy, outcome });
54
+ }
@@ -0,0 +1,31 @@
1
+ import { type OnModuleDestroy, type OnModuleInit } from "@nestjs/common";
2
+ import { DiscoveryService } from "@nestjs/core";
3
+ import type { Redis } from "ioredis";
4
+ import type { KernelLogger } from "../../log.js";
5
+ import { KernelConfigService } from "../config/kernel-config.service.js";
6
+ import { KernelDb } from "../database/kernel-db.js";
7
+ import { TransactionHost } from "../database/transaction-host.js";
8
+ import { LockService } from "../lock/lock.service.js";
9
+ export declare const METRICS_SAMPLE_INTERVAL_MS = 30000;
10
+ export declare const operationalMetricsEnabled: () => boolean;
11
+ /** Each collection uses the most recent successful local read, with no backend calls on export. */
12
+ export declare class OperationalMetricsSampler implements OnModuleInit, OnModuleDestroy {
13
+ private readonly discovery;
14
+ private readonly redis;
15
+ private readonly db;
16
+ readonly txHost: TransactionHost;
17
+ readonly lockService: LockService;
18
+ readonly config: KernelConfigService;
19
+ readonly log: KernelLogger;
20
+ private readonly depths;
21
+ private readonly outbox;
22
+ private detach?;
23
+ constructor(discovery: DiscoveryService, redis: Redis, db: KernelDb, txHost: TransactionHost, lockService: LockService, config: KernelConfigService, log: KernelLogger);
24
+ onModuleInit(): void;
25
+ onModuleDestroy(): void;
26
+ run(signal?: AbortSignal): Promise<void>;
27
+ collectSamples(signal?: AbortSignal): Promise<void>;
28
+ private sample;
29
+ private readQueues;
30
+ private readOutbox;
31
+ }
@@ -0,0 +1,188 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { DiscoveryService } from "@nestjs/core";
12
+ import { createNoopMeter } from "@opentelemetry/api";
13
+ import { Queue } from "bullmq";
14
+ import { sql } from "kysely";
15
+ import { waitWithin } from "../close-within.js";
16
+ import { KernelConfigService } from "../config/kernel-config.service.js";
17
+ import { KernelDb } from "../database/kernel-db.js";
18
+ import { asPlatform } from "../database/org-scope.js";
19
+ import { TransactionHost } from "../database/transaction-host.js";
20
+ import { Transactional } from "../database/transactional.decorator.js";
21
+ import { LockService } from "../lock/lock.service.js";
22
+ import { KERNEL_QUEUES } from "../queue/queue-names.js";
23
+ import { LockedInterval } from "../schedule/locked-interval.js";
24
+ import { KERNEL_LOGGER, REDIS } from "../tokens.js";
25
+ import { kernelMeter } from "./kernel-metrics.js";
26
+ export const METRICS_SAMPLE_INTERVAL_MS = 30_000;
27
+ const SAMPLE_FRESH_MS = 90_000;
28
+ const SAMPLE_TIMEOUT_MS = 2_000;
29
+ const QUEUE_STATES = ["waiting", "active", "delayed", "failed"];
30
+ export const operationalMetricsEnabled = () => kernelMeter() !== createNoopMeter();
31
+ function fresh(sample, now) {
32
+ return sample.latest && now - sample.latest.at < SAMPLE_FRESH_MS
33
+ ? sample.latest.value
34
+ : undefined;
35
+ }
36
+ /** Each collection uses the most recent successful local read, with no backend calls on export. */
37
+ let OperationalMetricsSampler = class OperationalMetricsSampler {
38
+ discovery;
39
+ redis;
40
+ db;
41
+ txHost;
42
+ lockService;
43
+ config;
44
+ log;
45
+ depths = { latest: undefined, reading: false };
46
+ outbox = { latest: undefined, reading: false };
47
+ detach;
48
+ constructor(discovery, redis, db, txHost, lockService, config, log) {
49
+ this.discovery = discovery;
50
+ this.redis = redis;
51
+ this.db = db;
52
+ this.txHost = txHost;
53
+ this.lockService = lockService;
54
+ this.config = config;
55
+ this.log = log;
56
+ }
57
+ onModuleInit() {
58
+ const meter = kernelMeter();
59
+ const depth = meter.createObservableGauge("capybara.queue.depth", { unit: "{job}" });
60
+ const oldest = meter.createObservableGauge("capybara.outbox.oldest_due.age", { unit: "s" });
61
+ const dead = meter.createObservableGauge("capybara.outbox.dead", { unit: "{row}" });
62
+ const available = meter.createObservableGauge("capybara.operations.sample.fresh", {
63
+ description: "Whether the sampled source has a recent successful measurement",
64
+ unit: "1",
65
+ });
66
+ const observe = (result) => {
67
+ const now = Date.now();
68
+ const queues = fresh(this.depths, now);
69
+ const outbox = fresh(this.outbox, now);
70
+ // Cumulative readers can repeat a previous gauge point even if it is not observed again.
71
+ // Publish validity on every collection so a repeated value never looks like a fresh sample.
72
+ result.observe(available, queues ? 1 : 0, { source: "queue" });
73
+ result.observe(available, outbox ? 1 : 0, { source: "outbox" });
74
+ for (const { queue, counts } of queues ?? []) {
75
+ for (const state of QUEUE_STATES)
76
+ result.observe(depth, counts[state], { queue, state });
77
+ }
78
+ if (outbox) {
79
+ result.observe(oldest, outbox.oldest_due_seconds);
80
+ result.observe(dead, outbox.dead_count);
81
+ }
82
+ };
83
+ const gauges = [depth, oldest, dead, available];
84
+ meter.addBatchObservableCallback(observe, gauges);
85
+ this.detach = () => meter.removeBatchObservableCallback(observe, gauges);
86
+ }
87
+ onModuleDestroy() {
88
+ this.detach?.();
89
+ }
90
+ run(signal) {
91
+ return this.collectSamples(signal);
92
+ }
93
+ async collectSamples(signal) {
94
+ await Promise.all([
95
+ this.sample(this.depths, "queue", () => this.readQueues(), signal),
96
+ this.sample(this.outbox, "outbox", () => this.readOutbox(), signal),
97
+ ]);
98
+ }
99
+ async sample(state, source, read, signal) {
100
+ if (state.reading || signal?.aborted)
101
+ return;
102
+ state.reading = true;
103
+ const at = Date.now();
104
+ let value;
105
+ const pending = read()
106
+ .then((sample) => {
107
+ value = sample;
108
+ })
109
+ .finally(() => {
110
+ state.reading = false;
111
+ });
112
+ try {
113
+ if (!(await waitWithin(pending, SAMPLE_TIMEOUT_MS)))
114
+ throw new Error("Sample timed out");
115
+ if (!signal?.aborted && value !== undefined)
116
+ state.latest = { at, value };
117
+ }
118
+ catch {
119
+ state.latest = undefined;
120
+ this.log.warn("operational metrics sample unavailable", { source });
121
+ }
122
+ }
123
+ async readQueues() {
124
+ if (this.redis.status !== "ready")
125
+ throw new Error("Redis is unavailable");
126
+ const queues = new Map();
127
+ for (const { instance } of this.discovery.getProviders()) {
128
+ if (instance instanceof Queue)
129
+ queues.set(instance.name, instance);
130
+ }
131
+ return Promise.all(KERNEL_QUEUES.flatMap((name) => {
132
+ const queue = queues.get(name);
133
+ if (!queue)
134
+ return [];
135
+ return [
136
+ (async () => {
137
+ if ((await queue.getBackend().client).status !== "ready") {
138
+ throw new Error("Queue connection is unavailable");
139
+ }
140
+ const counts = await queue.getJobCounts("wait", "prioritized", "active", "delayed", "failed");
141
+ return {
142
+ queue: name,
143
+ counts: {
144
+ waiting: (counts.wait ?? 0) + (counts.prioritized ?? 0),
145
+ active: counts.active ?? 0,
146
+ delayed: counts.delayed ?? 0,
147
+ failed: counts.failed ?? 0,
148
+ },
149
+ };
150
+ })(),
151
+ ];
152
+ }));
153
+ }
154
+ async readOutbox() {
155
+ await sql `SET LOCAL statement_timeout = '1500ms'`.execute(this.db.db);
156
+ // org-filter: deployment-wide outbox lag and dead count without org labels
157
+ return asPlatform("sample outbox health across the deployment", async () => {
158
+ const facts = await sql `
159
+ SELECT
160
+ coalesce(extract(epoch FROM statement_timestamp() -
161
+ min(greatest(next_attempt_at, run_at)) FILTER (
162
+ WHERE dead_at IS NULL AND next_attempt_at <= statement_timestamp()
163
+ AND (run_at IS NULL OR run_at <= statement_timestamp())
164
+ )), 0)::float8 AS oldest_due_seconds,
165
+ count(*) FILTER (WHERE dead_at IS NOT NULL)::float8 AS dead_count
166
+ FROM capybara.outbox
167
+ `.execute(this.db.db);
168
+ return facts.rows[0];
169
+ });
170
+ }
171
+ };
172
+ __decorate([
173
+ LockedInterval("operational-metrics", () => METRICS_SAMPLE_INTERVAL_MS, { runOnStart: true })
174
+ ], OperationalMetricsSampler.prototype, "run", null);
175
+ __decorate([
176
+ Transactional()
177
+ ], OperationalMetricsSampler.prototype, "readOutbox", null);
178
+ OperationalMetricsSampler = __decorate([
179
+ Injectable(),
180
+ __param(0, Inject(DiscoveryService)),
181
+ __param(1, Inject(REDIS)),
182
+ __param(2, Inject(KernelDb)),
183
+ __param(3, Inject(TransactionHost)),
184
+ __param(4, Inject(LockService)),
185
+ __param(5, Inject(KernelConfigService)),
186
+ __param(6, Inject(KERNEL_LOGGER))
187
+ ], OperationalMetricsSampler);
188
+ export { OperationalMetricsSampler };
@@ -19,6 +19,29 @@ export interface OutboxJobSpec {
19
19
  * name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
20
20
  */
21
21
  export declare const OUTBOX_JOBS: {
22
+ readonly "data-erasure": {
23
+ readonly queue: "cap-kernel-maintenance";
24
+ readonly idempotent: "Each generation claims the durable request under a row lock. Stale and completed deliveries do nothing.";
25
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
26
+ readonly opts: {
27
+ readonly attempts: 1;
28
+ readonly removeOnComplete: true;
29
+ readonly removeOnFail: true;
30
+ };
31
+ };
32
+ readonly "retention-batch": {
33
+ readonly queue: "cap-kernel-maintenance";
34
+ readonly idempotent: "Locks the work row and checks the queued generation before committing one batch and its continuation";
35
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
36
+ readonly opts: {
37
+ readonly attempts: 5;
38
+ readonly backoff: {
39
+ readonly type: "exponential";
40
+ readonly delay: 5000;
41
+ };
42
+ readonly removeOnComplete: true;
43
+ };
44
+ };
22
45
  readonly "trigger-dispatch": {
23
46
  readonly queue: "cap-kernel-maintenance";
24
47
  readonly idempotent: "Dispatches one stored event by id; the dispatcher reads the event's state and delivers each automation at most once (deliveries keyed by automation and event)";
@@ -21,6 +21,18 @@ const SCOPE_JOB_OPTS = {
21
21
  * name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
22
22
  */
23
23
  export const OUTBOX_JOBS = {
24
+ "data-erasure": {
25
+ queue: "cap-kernel-maintenance",
26
+ idempotent: "Each generation claims the durable request under a row lock. Stale and completed deliveries do nothing.",
27
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
28
+ opts: { attempts: 1, removeOnComplete: true, removeOnFail: true },
29
+ },
30
+ "retention-batch": {
31
+ queue: "cap-kernel-maintenance",
32
+ idempotent: "Locks the work row and checks the queued generation before committing one batch and its continuation",
33
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
34
+ opts: { attempts: 5, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
35
+ },
24
36
  // `automations/job-ids.ts` TRIGGER_DISPATCH_JOB: owed by the transaction that stores a trigger
25
37
  // event (`TriggerEventsService.emit`, collaboration spec §4.2), under `trigger-dispatch-<eventId>`
26
38
  "trigger-dispatch": {
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { getStorageToken } from "@nestjs/throttler";
12
12
  import { ApiError } from "../../errors.js";
13
+ import { recordThrottle } from "../metrics/kernel-metrics.js";
13
14
  import { NAMED_THROTTLERS, throttlerKey } from "./named-throttlers.js";
14
15
  /**
15
16
  * The Redis key of one counter. All counters of a credential group share the hash tag
@@ -44,7 +45,13 @@ let CredentialThrottler = class CredentialThrottler {
44
45
  */
45
46
  async reserve(names, req, reply) {
46
47
  const ts = this.resolve(names);
47
- const r = await this.redisStorage().reserve(ts.map((t) => credentialRedisKey(t, t.getTracker(req))), ts.map((t) => t.limit), ts[0]?.ttl ?? 0);
48
+ const r = await this.redisStorage()
49
+ .reserve(ts.map((t) => credentialRedisKey(t, t.getTracker(req))), ts.map((t) => t.limit), ts[0]?.ttl ?? 0)
50
+ .catch((error) => {
51
+ recordThrottle("credential", "unavailable");
52
+ throw error;
53
+ });
54
+ recordThrottle("credential", r.allowed ? "allowed" : "limited");
48
55
  if (r.allowed)
49
56
  return;
50
57
  reply.header("retry-after", String(r.retryAfterSeconds));
@@ -1,6 +1,12 @@
1
1
  import type { FastifyRequest } from "fastify";
2
2
  /** The counting window of every credential throttler, ms (first attempt starts it). */
3
3
  export declare const CREDENTIAL_WINDOW_MS = 900000;
4
+ /** Deployment-wide quota shared across the Nest API routes. */
5
+ export declare const API_DEFAULT_THROTTLER: {
6
+ readonly name: "api-default";
7
+ readonly ttl: 60000;
8
+ readonly message: "Too many requests; try again later";
9
+ };
4
10
  /** A named throttler: a limit over a tracker, answering 429 `auth.rate_limited` with `message`. */
5
11
  export interface NamedThrottler {
6
12
  name: string;