@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
@@ -182,6 +182,7 @@ let AdminHealthService = class AdminHealthService {
182
182
  },
183
183
  devices: { online: devicesOnline, dialIn, byProvider: devicesByProvider },
184
184
  sandboxes,
185
+ retentionBlockers: db?.retentionBlockers ?? null,
185
186
  unavailable,
186
187
  };
187
188
  }
@@ -219,7 +220,7 @@ let AdminHealthService = class AdminHealthService {
219
220
  }
220
221
  async readDb() {
221
222
  const db = this.db.db;
222
- const [channels, devices, instances] = await Promise.all([
223
+ const [channels, devices, instances, retentionBlockers] = await Promise.all([
223
224
  db
224
225
  .selectFrom("channel_connections as c")
225
226
  .innerJoin("orgs as o", "o.id", "c.org_id")
@@ -249,8 +250,33 @@ let AdminHealthService = class AdminHealthService {
249
250
  .where("o.deleted_at", "is", null)
250
251
  .groupBy(["i.provider", "i.status"])
251
252
  .execute(),
253
+ asPlatform("read retention blockers across organizations", () => {
254
+ // org-filter: deployment-wide retention blockers for the super admin health overview
255
+ return db
256
+ .selectFrom(db
257
+ .selectFrom("retention_work")
258
+ .select(["id as workId", "org_id as orgId", "blocked_reason as reason", "due_at"])
259
+ .where("state", "=", "blocked")
260
+ .where("blocked_reason", "!=", "recovery_hold")
261
+ .unionAll(db
262
+ .selectFrom("data_erasure_requests")
263
+ .select(["id as workId", "org_id as orgId", "blocked_reason as reason", "due_at"])
264
+ .where("stage", "!=", "done")
265
+ .where("blocked_reason", "is not", null)
266
+ .where("blocked_reason", "!=", "recovery-hold"))
267
+ .as("blocked"))
268
+ .select(["workId", "orgId", "reason"])
269
+ .orderBy("due_at")
270
+ .orderBy("workId")
271
+ .limit(10)
272
+ .execute();
273
+ }),
252
274
  ]);
253
275
  return {
276
+ retentionBlockers: retentionBlockers.map((row) => ({
277
+ ...row,
278
+ reason: row.reason ?? "processing_failed",
279
+ })),
254
280
  channels: channels.map((c) => ({ status: c.status, mode: c.mode, n: Number(c.n) })),
255
281
  devices: devices.map((d) => ({ provider: d.provider, n: Number(d.n) })),
256
282
  instances: instances.map((i) => ({
@@ -58,6 +58,11 @@ export interface AdminUsageWeek {
58
58
  /** End of today in `tz`, exclusive (ISO 8601, UTC). */
59
59
  to: string;
60
60
  tz: string;
61
+ /** Retention has removed some detail for these report ranges. */
62
+ retentionCoverage: {
63
+ usageIncompleteSince: string | null;
64
+ runsIncompleteSince: string | null;
65
+ };
61
66
  /** Exactly 7 days, oldest first, today last; days without usage are zeros. */
62
67
  days: UsageDay[];
63
68
  /** Nominal currency subtotals over the whole week. */
@@ -115,6 +115,17 @@ let AdminUsageService = class AdminUsageService {
115
115
  const tokens = await q.tokens.execute(db);
116
116
  const runs = await q.runs.execute(db);
117
117
  const modelUsage = await q.modelUsage.execute(db);
118
+ // org-filter: deployment-wide retention coverage for the super admin report
119
+ const { rows: [coverage], } = await asPlatform("read retention coverage across organizations", () => sql `
120
+ SELECT
121
+ min(usage_incomplete_since) FILTER (WHERE usage_incomplete_since < ${to}
122
+ AND usage_incomplete_through >= ${from}) AS usage,
123
+ min(runs_incomplete_since) FILTER (WHERE runs_incomplete_since < ${to}
124
+ AND runs_incomplete_through >= ${from}) AS runs
125
+ FROM capybara.retention_coverage
126
+ WHERE (usage_incomplete_since < ${to} AND usage_incomplete_through >= ${from})
127
+ OR (runs_incomplete_since < ${to} AND runs_incomplete_through >= ${from})
128
+ `.execute(db));
118
129
  const result = summarize({
119
130
  firstDay,
120
131
  tokens: [...tokens.rows, ...modelUsage.rows],
@@ -133,6 +144,10 @@ let AdminUsageService = class AdminUsageService {
133
144
  from: from.toISOString(),
134
145
  to: to.toISOString(),
135
146
  tz,
147
+ retentionCoverage: {
148
+ usageIncompleteSince: coverage?.usage?.toISOString() ?? null,
149
+ runsIncompleteSince: coverage?.runs?.toISOString() ?? null,
150
+ },
136
151
  days: result.days,
137
152
  cost: result.cost,
138
153
  orgs: result.top.map((o) => ({ ...o, name: nameOf.get(o.orgId) ?? o.orgId })),
@@ -141,10 +156,14 @@ let AdminUsageService = class AdminUsageService {
141
156
  }
142
157
  };
143
158
  __decorate([
144
- Cacheable({ key: "admin-usage-price-coverage:#{0}:#{1}", ttl: USAGE_CACHE_TTL })
159
+ Cacheable({ key: "admin-usage-retention-coverage:#{0}:#{1}", ttl: USAGE_CACHE_TTL })
145
160
  ], AdminUsageService.prototype, "cachedWeek", null);
146
161
  __decorate([
147
- Transactional({ propagation: "requires_new", accessMode: "read only" })
162
+ Transactional({
163
+ propagation: "requires_new",
164
+ accessMode: "read only",
165
+ isolationLevel: "repeatable read",
166
+ })
148
167
  ], AdminUsageService.prototype, "aggregate", null);
149
168
  AdminUsageService = __decorate([
150
169
  Injectable(),
@@ -20,7 +20,7 @@ export { paramIssues, SUBAGENT_ROSTER_MAX } from "./definition.js";
20
20
  export interface AgentVersion {
21
21
  version: number;
22
22
  definition: AgentDefinition;
23
- createdBy: string;
23
+ createdBy: string | null;
24
24
  createdAt: Date;
25
25
  }
26
26
  export type AgentVersionSummary = Omit<AgentVersion, "definition">;
@@ -1,4 +1,5 @@
1
1
  import { type AgentTemplate, type AgentTemplateTier, type LocalizedName, type PluginManifest, type ThemeScheme } from "@capybara-hq/plugin-sdk";
2
+ import { type ExtensionDbIdentity } from "../db/extension-db.js";
2
3
  import { ApiError } from "../errors.js";
3
4
  import { ExtensionAdminOps } from "../extensions/admin-ops.js";
4
5
  import { ExtensionAdmin } from "../extensions/admin-view.js";
@@ -411,6 +412,7 @@ export declare class PluginImport {
411
412
  private readonly approveLock;
412
413
  private readonly itemLock;
413
414
  private readonly config;
415
+ private readonly extensionDbIdentity;
414
416
  private readonly installs;
415
417
  private readonly ops;
416
418
  private readonly admin;
@@ -436,7 +438,7 @@ export declare class PluginImport {
436
438
  /** The super admin lock (identity/super-admin.ts): joins the caller's transaction. */
437
439
  adminLock: SuperAdminLock,
438
440
  /** The owner org's lock: an org upload re-checks its admin under it (ruling P3-7). */
439
- orgLock: OrgLock, installLock: PluginInstallLock, approveLock: PluginApproveLock, itemLock: CatalogItemLock, config: KernelConfigService, storage: StorageService, installs: ExtensionInstalls, ops: ExtensionAdminOps, admin: ExtensionAdmin,
441
+ orgLock: OrgLock, installLock: PluginInstallLock, approveLock: PluginApproveLock, itemLock: CatalogItemLock, config: KernelConfigService, extensionDbIdentity: ExtensionDbIdentity, storage: StorageService, installs: ExtensionInstalls, ops: ExtensionAdminOps, admin: ExtensionAdmin,
440
442
  /** Reads a package from the package store (confirm recomputes the permission set). */
441
443
  blobs: ExtensionBlobs,
442
444
  /** Config-declared names, loaded connectors and extension versions (the extension registry). */
@@ -13,6 +13,7 @@ import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import semver from "semver";
15
15
  import { checkClientFiles } from "../client/client-files.js";
16
+ import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
16
17
  import { ApiError } from "../errors.js";
17
18
  import { ExtensionAdminOps } from "../extensions/admin-ops.js";
18
19
  import { ExtensionAdmin } from "../extensions/admin-view.js";
@@ -150,6 +151,7 @@ let PluginImport = class PluginImport {
150
151
  approveLock;
151
152
  itemLock;
152
153
  config;
154
+ extensionDbIdentity;
153
155
  installs;
154
156
  ops;
155
157
  admin;
@@ -171,7 +173,7 @@ let PluginImport = class PluginImport {
171
173
  /** The super admin lock (identity/super-admin.ts): joins the caller's transaction. */
172
174
  adminLock,
173
175
  /** The owner org's lock: an org upload re-checks its admin under it (ruling P3-7). */
174
- orgLock, installLock, approveLock, itemLock, config, storage, installs, ops, admin,
176
+ orgLock, installLock, approveLock, itemLock, config, extensionDbIdentity, storage, installs, ops, admin,
175
177
  /** Reads a package from the package store (confirm recomputes the permission set). */
176
178
  blobs,
177
179
  /** Config-declared names, loaded connectors and extension versions (the extension registry). */
@@ -187,6 +189,7 @@ let PluginImport = class PluginImport {
187
189
  this.approveLock = approveLock;
188
190
  this.itemLock = itemLock;
189
191
  this.config = config;
192
+ this.extensionDbIdentity = extensionDbIdentity;
190
193
  this.installs = installs;
191
194
  this.ops = ops;
192
195
  this.admin = admin;
@@ -393,7 +396,7 @@ let PluginImport = class PluginImport {
393
396
  let extension;
394
397
  if (ext) {
395
398
  extension = await this.reviewExtension(ext, await this.extensionState(m.name, packageName));
396
- await assertDowngradable(this.db, extension, ext.migrationSql);
399
+ await assertDowngradable(this.db, extension, ext.migrationSql, this.extensionDbIdentity, this.config.get().db.connectTimeoutMs);
397
400
  }
398
401
  // Display files go to PG with the staging row; skills and templates need object storage, which a
399
402
  // bootstrap import never has (the object store may be a bootstrap plugin itself). A file that is
@@ -850,7 +853,7 @@ let PluginImport = class PluginImport {
850
853
  // A foreseeable deploy failure (a downgrade to a version with unrun migrations) is refused
851
854
  // before anything is written
852
855
  if (now.action === "upgrade" && stored) {
853
- await assertDowngradable(t, now, stored.migrationSql);
856
+ await assertDowngradable(t, now, stored.migrationSql, this.extensionDbIdentity, this.config.get().db.connectTimeoutMs);
854
857
  }
855
858
  if (now.action === "install" || now.action === "upgrade") {
856
859
  previous = await this.approve(actor, review, staged, now, stored, opts);
@@ -1587,16 +1590,17 @@ PluginImport = __decorate([
1587
1590
  __param(4, Inject(PluginApproveLock)),
1588
1591
  __param(5, Inject(CatalogItemLock)),
1589
1592
  __param(6, Inject(KernelConfigService)),
1590
- __param(7, Inject(StorageService)),
1591
- __param(8, Inject(ExtensionInstalls)),
1592
- __param(9, Inject(ExtensionAdminOps)),
1593
- __param(10, Inject(ExtensionAdmin)),
1594
- __param(11, Inject(ExtensionBlobs)),
1595
- __param(12, Inject(ExtensionRegistry)),
1596
- __param(13, Inject(KERNEL_LOGGER)),
1597
- __param(14, Inject(TransactionHost)),
1598
- __param(15, Inject(PlatformComponents)),
1599
- __param(16, Inject(OutboxService))
1593
+ __param(7, Inject(ConfiguredExtensionDbIdentity)),
1594
+ __param(8, Inject(StorageService)),
1595
+ __param(9, Inject(ExtensionInstalls)),
1596
+ __param(10, Inject(ExtensionAdminOps)),
1597
+ __param(11, Inject(ExtensionAdmin)),
1598
+ __param(12, Inject(ExtensionBlobs)),
1599
+ __param(13, Inject(ExtensionRegistry)),
1600
+ __param(14, Inject(KERNEL_LOGGER)),
1601
+ __param(15, Inject(TransactionHost)),
1602
+ __param(16, Inject(PlatformComponents)),
1603
+ __param(17, Inject(OutboxService))
1600
1604
  ], PluginImport);
1601
1605
  export { PluginImport };
1602
1606
  /**
@@ -1729,12 +1733,12 @@ function reviewClient(pkg) {
1729
1733
  * rule as `ExtensionAdminOps.install`: extension migrations are expand-only, a downgrade can only go
1730
1734
  * back to a version whose migrations have all run).
1731
1735
  */
1732
- async function assertDowngradable(db, p, migrationSql) {
1736
+ async function assertDowngradable(db, p, migrationSql, identity, connectTimeoutMs) {
1733
1737
  if (p.action !== "upgrade" || p.currentVersion === null)
1734
1738
  return;
1735
1739
  if (!semver.valid(p.currentVersion) || !semver.lt(p.version, p.currentVersion))
1736
1740
  return;
1737
- const unrun = await unrunMigrations(db, p.name, migrationSql);
1741
+ const unrun = await unrunMigrations(db, p.name, migrationSql, identity.resolve(p.name), connectTimeoutMs);
1738
1742
  if (unrun.length > 0) {
1739
1743
  throw new ApiError("extension.downgrade_unsupported", `The plugin's extension ${p.name} ${p.version} is older than the installed ${p.currentVersion}, and that version has migrations that were never run here (${unrun.join(", ")}); extension migrations only expand, so this downgrade is not possible`, unrun.map((file) => ({ file })));
1740
1744
  }
@@ -69,7 +69,7 @@ export interface ChannelConnectionView {
69
69
  path: string;
70
70
  set: boolean;
71
71
  }[];
72
- createdBy: string;
72
+ createdBy: string | null;
73
73
  createdAt: Date;
74
74
  updatedAt: Date;
75
75
  }
@@ -62,6 +62,18 @@ let ClientReports = class ClientReports {
62
62
  throw notFound();
63
63
  }
64
64
  async upsert(orgId, b) {
65
+ if (orgId !== null) {
66
+ // The parent fence prevents a previously authorized in-flight report from outliving its org.
67
+ const org = await this.db
68
+ .selectFrom("orgs")
69
+ .select("id")
70
+ .where("id", "=", orgId)
71
+ .where("deleted_at", "is", null)
72
+ .forShare()
73
+ .executeTakeFirst();
74
+ if (!org)
75
+ throw notFound();
76
+ }
65
77
  await this.db.db
66
78
  .insertInto("extension_client_reports")
67
79
  .values({
@@ -69,6 +69,7 @@ export declare const KernelConfigSchema: z.ZodObject<{
69
69
  url: z.ZodString;
70
70
  migrationUrl: z.ZodOptional<z.ZodString>;
71
71
  extensionsUrl: z.ZodOptional<z.ZodString>;
72
+ extensionPoolMax: z.ZodDefault<z.ZodNumber>;
72
73
  poolMax: z.ZodDefault<z.ZodNumber>;
73
74
  connectTimeoutMs: z.ZodDefault<z.ZodNumber>;
74
75
  idleTimeoutMs: z.ZodDefault<z.ZodNumber>;
@@ -126,8 +127,10 @@ export declare const KernelConfigSchema: z.ZodObject<{
126
127
  extensionPermissions: z.ZodDefault<z.ZodObject<{
127
128
  autoApprove: z.ZodDefault<z.ZodBoolean>;
128
129
  }, z.core.$strict>>;
129
- http: z.ZodDefault<z.ZodObject<{
130
+ http: z.ZodPrefault<z.ZodObject<{
130
131
  port: z.ZodDefault<z.ZodNumber>;
132
+ principalRequestsPerMinute: z.ZodDefault<z.ZodNumber>;
133
+ anonymousRequestsPerMinute: z.ZodDefault<z.ZodNumber>;
131
134
  trustProxy: z.ZodDefault<z.ZodPreprocess<z.ZodUnion<readonly [z.ZodBoolean, z.ZodNumber, z.ZodArray<z.ZodString>]>, unknown>>;
132
135
  replicaId: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
133
136
  swagger: z.ZodDefault<z.ZodBoolean>;
@@ -147,6 +150,7 @@ export declare const KernelConfigSchema: z.ZodObject<{
147
150
  }, z.core.$strict>>;
148
151
  runtime: z.ZodDefault<z.ZodObject<{
149
152
  maxSteps: z.ZodDefault<z.ZodNumber>;
153
+ memberRunConcurrency: z.ZodDefault<z.ZodNumber>;
150
154
  wakeOnBackgroundTask: z.ZodDefault<z.ZodBoolean>;
151
155
  maxRunSeconds: z.ZodDefault<z.ZodNumber>;
152
156
  streamIdleMs: z.ZodDefault<z.ZodNumber>;
@@ -198,6 +202,10 @@ export declare const KernelConfigSchema: z.ZodObject<{
198
202
  gateway: z.ZodPrefault<z.ZodObject<{
199
203
  internalUrl: z.ZodOptional<z.ZodURL>;
200
204
  }, z.core.$strict>>;
205
+ retention: z.ZodDefault<z.ZodObject<{
206
+ destructiveEnabled: z.ZodDefault<z.ZodBoolean>;
207
+ erasureEnabled: z.ZodDefault<z.ZodBoolean>;
208
+ }, z.core.$strict>>;
201
209
  storage: z.ZodDefault<z.ZodObject<{
202
210
  purgeDeletedOrgsAfterDays: z.ZodDefault<z.ZodNumber>;
203
211
  }, z.core.$strict>>;
@@ -344,6 +344,14 @@ export const KernelConfigSchema = z.strictObject({
344
344
  secret: true,
345
345
  description: "PostgreSQL connection URL for the shared extension login",
346
346
  })),
347
+ extensionPoolMax: z
348
+ .number()
349
+ .int()
350
+ .positive()
351
+ .default(2)
352
+ .meta(meta({
353
+ description: "Maximum PostgreSQL connections per active extension instance with a separate login",
354
+ })),
347
355
  poolMax: z
348
356
  .number()
349
357
  .int()
@@ -648,6 +656,22 @@ export const KernelConfigSchema = z.strictObject({
648
656
  .max(65535)
649
657
  .default(8080)
650
658
  .meta(meta({ description: "HTTP listen port" })),
659
+ principalRequestsPerMinute: z
660
+ .number()
661
+ .int()
662
+ .positive()
663
+ .default(600)
664
+ .meta(meta({
665
+ description: "Platform-wide API requests per minute for each authenticated principal",
666
+ })),
667
+ anonymousRequestsPerMinute: z
668
+ .number()
669
+ .int()
670
+ .positive()
671
+ .default(600)
672
+ .meta(meta({
673
+ description: "Platform-wide public API requests per minute for each anonymous client IP",
674
+ })),
651
675
  trustProxy: z
652
676
  .preprocess(
653
677
  // Also accept a comma-separated string of addresses / CIDRs (an env value that is not JSON
@@ -702,7 +726,7 @@ export const KernelConfigSchema = z.strictObject({
702
726
  description: "Externally reachable origin of the web app (apps/web, which proxies /api to the kernel), not the kernel's own address; required for OAuth connectors: the redirect URI is <publicUrl>/api/v1/oauth/callback (served through the web /api proxy, which also carries the OAuth binding cookie) and the callback redirects to web pages under it, e.g. https://capybara.example.com",
703
727
  })),
704
728
  })
705
- .default({ port: 8080, trustProxy: false, swagger: false }),
729
+ .prefault({}),
706
730
  roles: z
707
731
  .preprocess(
708
732
  // Also accept a comma-separated string (CAPYBARA_ROLES=api,worker; env values that are not
@@ -778,6 +802,15 @@ export const KernelConfigSchema = z.strictObject({
778
802
  .meta(meta({
779
803
  description: "Maximum model steps per agent run before the final wrap-up; 0 (the default) means no limit: a run goes on until the model stops calling tools or someone stops it",
780
804
  })),
805
+ memberRunConcurrency: z
806
+ .number()
807
+ .int()
808
+ .nonnegative()
809
+ .default(0)
810
+ .meta(meta({
811
+ hot: true,
812
+ description: "Maximum concurrent runs per member in an organization. Zero means no member cap. An organization can override the platform value.",
813
+ })),
781
814
  wakeOnBackgroundTask: z
782
815
  .boolean()
783
816
  .default(true)
@@ -858,6 +891,7 @@ export const KernelConfigSchema = z.strictObject({
858
891
  })
859
892
  .default({
860
893
  maxSteps: 0,
894
+ memberRunConcurrency: 0,
861
895
  wakeOnBackgroundTask: true,
862
896
  maxRunSeconds: 0,
863
897
  streamIdleMs: 60000,
@@ -1169,6 +1203,22 @@ export const KernelConfigSchema = z.strictObject({
1169
1203
  })),
1170
1204
  })
1171
1205
  .prefault({}),
1206
+ retention: z
1207
+ .strictObject({
1208
+ destructiveEnabled: z
1209
+ .boolean()
1210
+ .default(false)
1211
+ .meta(meta({
1212
+ description: "Allow retention and conversation purge workers to remove records after all older API and worker replicas have drained.",
1213
+ })),
1214
+ erasureEnabled: z
1215
+ .boolean()
1216
+ .default(false)
1217
+ .meta(meta({
1218
+ description: "Enable org purge and account erasure after all older writers have drained. Purging their conversation roots also requires retention.destructiveEnabled.",
1219
+ })),
1220
+ })
1221
+ .default({ destructiveEnabled: false, erasureEnabled: false }),
1172
1222
  storage: z
1173
1223
  .strictObject({
1174
1224
  purgeDeletedOrgsAfterDays: z
@@ -526,12 +526,20 @@ export declare class ConversationsService {
526
526
  * are stopped after the conversation is marked deleted, so no finish
527
527
  * (the stops' own, or one the poller writes meanwhile) can wake a run on it: `ensureRun` refuses a
528
528
  * deleted conversation (the stops' finishes carry `stoppedBy: "deletion"` as well). The event
529
- * log, runs and trajectory stay (super admins still see them).
529
+ * log, runs and trajectory remain available during the product recovery hold.
530
530
  */
531
531
  remove(orgId: string, conversationId: string, accountId: string): Promise<void>;
532
+ /** Tombstones one root inside a fenced org or account erasure transaction. */
533
+ tombstoneForErasure(orgId: string, rootId: string, accountId: string, inaccessibleSince: Date): Promise<boolean>;
534
+ /** Re-admit an expiry candidate found by a sweep. The root may already have disappeared. */
535
+ expireForRetention(orgId: string, conversationId: string, cutoff: Date, claimScan?: () => Promise<boolean>): Promise<boolean>;
536
+ private tombstone;
532
537
  /** The authority subject a deletion locks: the tree's root and its device, read without locks. */
533
538
  private deletionSubject;
534
539
  private markDeleted;
540
+ /** The root lock excludes dispatch and claimed writes. Lock children in tree order for
541
+ * unfenced writes, then use a fresh READ COMMITTED snapshot for the eligibility decision. */
542
+ private treeExpired;
535
543
  /** 读会话:非所有者、或 agent 已对所有者不可用 → `conversation.not_found`。 */
536
544
  get(orgId: string, conversationId: string, viewerAccountId: string): Promise<ConversationView>;
537
545
  /**
@@ -30,6 +30,8 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
30
30
  import { KernelEvents } from "../infra/events/kernel-events.js";
31
31
  import { OutboxService } from "../infra/outbox/outbox.service.js";
32
32
  import { cacheWriteTierRows } from "../models/cache-write-usage.js";
33
+ import { oweConversationPurge } from "../retention/jobs.js";
34
+ import { readOrgRetention } from "../retention/policy.js";
33
35
  import { projectSkillOf } from "../runtime/context/project-root.js";
34
36
  import { ProviderRegistry } from "../runtime/providers.js";
35
37
  import { RunControl as RunControlService } from "../runtime/run-control.js";
@@ -578,17 +580,69 @@ let ConversationsService = class ConversationsService {
578
580
  * are stopped after the conversation is marked deleted, so no finish
579
581
  * (the stops' own, or one the poller writes meanwhile) can wake a run on it: `ensureRun` refuses a
580
582
  * deleted conversation (the stops' finishes carry `stoppedBy: "deletion"` as well). The event
581
- * log, runs and trajectory stay (super admins still see them).
583
+ * log, runs and trajectory remain available during the product recovery hold.
582
584
  */
583
585
  async remove(orgId, conversationId, accountId) {
584
586
  await this.writable(orgId, conversationId, accountId);
585
- // Close entrances before the direct stop. The outbox owes the same claim-revoking cleanup.
586
- // The root authority lock is the transaction's ordered prelude: inside a run's fence (a
587
- // Platform call) it follows the org row and precedes the conversation rows
588
587
  const subject = await this.deletionSubject(orgId, conversationId);
589
- await withTransactionFencePrelude(() => this.ceilings.lock(subject, "root"), () => this.markDeleted(orgId, conversationId, accountId, subject));
588
+ await this.tombstone(orgId, conversationId, accountId, subject);
589
+ }
590
+ /** Tombstones one root inside a fenced org or account erasure transaction. */
591
+ async tombstoneForErasure(orgId, rootId, accountId, inaccessibleSince) {
592
+ const subject = await this.deletionSubject(orgId, rootId);
593
+ if (subject.rootConversationId !== rootId)
594
+ return false;
595
+ const changed = await this.markDeleted(orgId, rootId, accountId, subject, undefined, inaccessibleSince);
596
+ if (changed)
597
+ afterCommit(() => this.eventLog.publishChanged(rootId, "deleted"));
598
+ return changed;
599
+ }
600
+ /** Re-admit an expiry candidate found by a sweep. The root may already have disappeared. */
601
+ async expireForRetention(orgId, conversationId, cutoff, claimScan) {
602
+ const root = await this.db
603
+ .selectFrom("conversations")
604
+ .select(["account_id", "device_id"])
605
+ .where("org_id", "=", orgId)
606
+ .where("id", "=", conversationId)
607
+ .where("parent_conversation_id", "is", null)
608
+ .where("kind", "=", "chat")
609
+ .where("deleted_at", "is", null)
610
+ .executeTakeFirst();
611
+ if (!root)
612
+ return false;
613
+ return this.tombstone(orgId, conversationId, root.account_id, {
614
+ orgId,
615
+ rootConversationId: conversationId,
616
+ ...(root.device_id && { deviceId: root.device_id }),
617
+ }, cutoff, claimScan);
618
+ }
619
+ async tombstone(orgId, conversationId, accountId, subject, cutoff, claimScan) {
620
+ const expiry = cutoff ? { cutoff, days: null, admitted: true } : undefined;
621
+ const deleted = await withTransactionFencePrelude(async () => {
622
+ // A competing delivery can advance the scan after candidate selection. Lock its
623
+ // generation before the org and authority rows, in the same transaction as expiry.
624
+ if (expiry && claimScan) {
625
+ expiry.admitted = await claimScan();
626
+ if (!expiry.admitted)
627
+ return;
628
+ }
629
+ // Settings writers take the org row, authority, policy row, then the fenced root.
630
+ if (expiry)
631
+ await this.db
632
+ .selectFrom("orgs")
633
+ .select("id")
634
+ .where("id", "=", orgId)
635
+ .forShare()
636
+ .executeTakeFirstOrThrow();
637
+ await this.ceilings.lock(subject, "root");
638
+ if (expiry)
639
+ expiry.days = (await readOrgRetention(this.db.db, orgId, { lock: true })).conversationDays;
640
+ }, () => this.markDeleted(orgId, conversationId, accountId, subject, expiry));
641
+ if (!deleted)
642
+ return false;
590
643
  await this.deletion.stopTree(conversationId, accountId);
591
644
  await this.eventLog.publishChanged(conversationId, "deleted");
645
+ return true;
592
646
  }
593
647
  /** The authority subject a deletion locks: the tree's root and its device, read without locks. */
594
648
  async deletionSubject(orgId, conversationId) {
@@ -628,14 +682,10 @@ let ConversationsService = class ConversationsService {
628
682
  }
629
683
  // the publish happens after the commit, in the caller; the tree stop after it is owed here
630
684
  // (transactional outbox spec §6), so a process that dies before it still stops the tree
631
- async markDeleted(orgId, conversationId, accountId, locked) {
632
- // the prelude locked `locked`; a root or device that changed since is not covered by it
633
- const subject = await this.deletionSubject(orgId, conversationId);
634
- if (subject.rootConversationId !== locked.rootConversationId ||
635
- subject.deviceId !== locked.deviceId)
636
- throw new ApiError("conflict", "The conversation's device changed; retry the deletion");
637
- await this.ceilings.lock(subject, "root");
638
- await this.ceilings.publishLocked(subject, "root", (_scope, intent) => conversationId === subject.rootConversationId || intent.conversation_id === conversationId);
685
+ async markDeleted(orgId, conversationId, accountId, locked, expiry, erasedAt) {
686
+ if (expiry && !expiry.admitted)
687
+ return false;
688
+ await this.ceilings.lock(locked, "root");
639
689
  const row = await this.db
640
690
  .selectFrom("conversations")
641
691
  .select("id")
@@ -645,11 +695,28 @@ let ConversationsService = class ConversationsService {
645
695
  .where("deleted_at", "is", null)
646
696
  .forUpdate()
647
697
  .executeTakeFirst();
648
- if (!row)
698
+ if (!row) {
699
+ if (expiry || erasedAt)
700
+ return false;
649
701
  throw notFound();
702
+ }
703
+ // The prelude locked this authority. Recheck the subject before revoking it.
704
+ const subject = await this.deletionSubject(orgId, conversationId);
705
+ if (subject.rootConversationId !== locked.rootConversationId ||
706
+ subject.deviceId !== locked.deviceId) {
707
+ if (expiry || erasedAt)
708
+ return false;
709
+ throw new ApiError("conflict", "The conversation's device changed; retry the deletion");
710
+ }
711
+ if (expiry) {
712
+ const days = expiry.days;
713
+ if (days === null || !(await this.treeExpired(orgId, conversationId, expiry.cutoff, days)))
714
+ return false;
715
+ }
716
+ await this.ceilings.publishLocked(subject, "root", (_scope, intent) => conversationId === subject.rootConversationId || intent.conversation_id === conversationId);
650
717
  await this.db
651
718
  .updateTable("conversations")
652
- .set({ deleted_at: sql `now()` })
719
+ .set({ deleted_at: erasedAt ?? sql `now()` })
653
720
  .where("id", "=", conversationId)
654
721
  .where("org_id", "=", orgId)
655
722
  .execute();
@@ -678,6 +745,33 @@ let ConversationsService = class ConversationsService {
678
745
  rootConversationId: conversationId,
679
746
  });
680
747
  await revokeSiteGrantsOfConversation(this.db.db, { orgId, rootConversationId: conversationId });
748
+ // Dispatches for a child still belong to the root's run history.
749
+ if (conversationId === subject.rootConversationId)
750
+ await oweConversationPurge(this.db.db, this.outbox, { orgId, conversationId });
751
+ return true;
752
+ }
753
+ /** The root lock excludes dispatch and claimed writes. Lock children in tree order for
754
+ * unfenced writes, then use a fresh READ COMMITTED snapshot for the eligibility decision. */
755
+ async treeExpired(orgId, root, cutoff, days) {
756
+ const tree = await conversationTree(this.db.db, root);
757
+ const ids = tree.map(({ id }) => id);
758
+ // The root is already locked. Every tree locker takes descendants by level, then id.
759
+ await sql `SELECT c.id FROM unnest(${ids}::text[]) WITH ORDINALITY nodes(id, n)
760
+ JOIN capybara.conversations c ON c.id = nodes.id AND c.org_id = ${orgId}
761
+ ORDER BY nodes.n FOR NO KEY UPDATE OF c`.execute(this.db.db);
762
+ const bound = sql `LEAST(${cutoff}::timestamptz, now() - ${days} * interval '24 hours')`;
763
+ const result = await sql `SELECT NOT EXISTS (
764
+ SELECT 1 FROM capybara.conversations c WHERE c.org_id = ${orgId}
765
+ AND c.id = ANY(${ids}::text[]) AND (
766
+ c.updated_at >= ${bound}
767
+ OR EXISTS (SELECT 1 FROM capybara.runs r WHERE r.conversation_id = c.id
768
+ AND r.status IN ('queued', 'running', 'waiting'))
769
+ OR EXISTS (SELECT 1 FROM capybara.conversation_queue q WHERE q.conversation_id = c.id
770
+ AND q.updated_at >= ${bound})
771
+ OR (SELECT e.created_at FROM capybara.conversation_events e WHERE e.conversation_id = c.id
772
+ ORDER BY e.seq DESC LIMIT 1) >= ${bound}
773
+ )) AS expired`.execute(this.db.db);
774
+ return result.rows[0]?.expired === true;
681
775
  }
682
776
  /** 读会话:非所有者、或 agent 已对所有者不可用 → `conversation.not_found`。 */
683
777
  async get(orgId, conversationId, viewerAccountId) {
@@ -1876,6 +1970,9 @@ __decorate([
1876
1970
  __decorate([
1877
1971
  Transactional({ propagation: "requires_new" })
1878
1972
  ], ConversationsService.prototype, "createIn", null);
1973
+ __decorate([
1974
+ Transactional({ propagation: "mandatory" })
1975
+ ], ConversationsService.prototype, "tombstoneForErasure", null);
1879
1976
  __decorate([
1880
1977
  Transactional()
1881
1978
  ], ConversationsService.prototype, "markDeleted", null);
@@ -13,6 +13,8 @@ export interface EventBus {
13
13
  export interface AppendEvent {
14
14
  type: ConversationEventType;
15
15
  runId?: string;
16
+ /** For a run-less usage event, the persisted run whose trigger account incurred it. */
17
+ usageAccountRunId?: string;
16
18
  /** 幂等键:同一会话内已有同键事件时返回已有事件,不分配新 seq。 */
17
19
  idemKey?: string;
18
20
  payload: unknown;