@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
@@ -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">;
@@ -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({
@@ -126,8 +126,10 @@ export declare const KernelConfigSchema: z.ZodObject<{
126
126
  extensionPermissions: z.ZodDefault<z.ZodObject<{
127
127
  autoApprove: z.ZodDefault<z.ZodBoolean>;
128
128
  }, z.core.$strict>>;
129
- http: z.ZodDefault<z.ZodObject<{
129
+ http: z.ZodPrefault<z.ZodObject<{
130
130
  port: z.ZodDefault<z.ZodNumber>;
131
+ principalRequestsPerMinute: z.ZodDefault<z.ZodNumber>;
132
+ anonymousRequestsPerMinute: z.ZodDefault<z.ZodNumber>;
131
133
  trustProxy: z.ZodDefault<z.ZodPreprocess<z.ZodUnion<readonly [z.ZodBoolean, z.ZodNumber, z.ZodArray<z.ZodString>]>, unknown>>;
132
134
  replicaId: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
133
135
  swagger: z.ZodDefault<z.ZodBoolean>;
@@ -147,6 +149,7 @@ export declare const KernelConfigSchema: z.ZodObject<{
147
149
  }, z.core.$strict>>;
148
150
  runtime: z.ZodDefault<z.ZodObject<{
149
151
  maxSteps: z.ZodDefault<z.ZodNumber>;
152
+ memberRunConcurrency: z.ZodDefault<z.ZodNumber>;
150
153
  wakeOnBackgroundTask: z.ZodDefault<z.ZodBoolean>;
151
154
  maxRunSeconds: z.ZodDefault<z.ZodNumber>;
152
155
  streamIdleMs: z.ZodDefault<z.ZodNumber>;
@@ -198,6 +201,10 @@ export declare const KernelConfigSchema: z.ZodObject<{
198
201
  gateway: z.ZodPrefault<z.ZodObject<{
199
202
  internalUrl: z.ZodOptional<z.ZodURL>;
200
203
  }, z.core.$strict>>;
204
+ retention: z.ZodDefault<z.ZodObject<{
205
+ destructiveEnabled: z.ZodDefault<z.ZodBoolean>;
206
+ erasureEnabled: z.ZodDefault<z.ZodBoolean>;
207
+ }, z.core.$strict>>;
201
208
  storage: z.ZodDefault<z.ZodObject<{
202
209
  purgeDeletedOrgsAfterDays: z.ZodDefault<z.ZodNumber>;
203
210
  }, z.core.$strict>>;
@@ -648,6 +648,22 @@ export const KernelConfigSchema = z.strictObject({
648
648
  .max(65535)
649
649
  .default(8080)
650
650
  .meta(meta({ description: "HTTP listen port" })),
651
+ principalRequestsPerMinute: z
652
+ .number()
653
+ .int()
654
+ .positive()
655
+ .default(600)
656
+ .meta(meta({
657
+ description: "Platform-wide API requests per minute for each authenticated principal",
658
+ })),
659
+ anonymousRequestsPerMinute: z
660
+ .number()
661
+ .int()
662
+ .positive()
663
+ .default(600)
664
+ .meta(meta({
665
+ description: "Platform-wide public API requests per minute for each anonymous client IP",
666
+ })),
651
667
  trustProxy: z
652
668
  .preprocess(
653
669
  // Also accept a comma-separated string of addresses / CIDRs (an env value that is not JSON
@@ -702,7 +718,7 @@ export const KernelConfigSchema = z.strictObject({
702
718
  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
719
  })),
704
720
  })
705
- .default({ port: 8080, trustProxy: false, swagger: false }),
721
+ .prefault({}),
706
722
  roles: z
707
723
  .preprocess(
708
724
  // Also accept a comma-separated string (CAPYBARA_ROLES=api,worker; env values that are not
@@ -778,6 +794,15 @@ export const KernelConfigSchema = z.strictObject({
778
794
  .meta(meta({
779
795
  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
796
  })),
797
+ memberRunConcurrency: z
798
+ .number()
799
+ .int()
800
+ .nonnegative()
801
+ .default(0)
802
+ .meta(meta({
803
+ hot: true,
804
+ description: "Maximum concurrent runs per member in an organization. Zero means no member cap. An organization can override the platform value.",
805
+ })),
781
806
  wakeOnBackgroundTask: z
782
807
  .boolean()
783
808
  .default(true)
@@ -858,6 +883,7 @@ export const KernelConfigSchema = z.strictObject({
858
883
  })
859
884
  .default({
860
885
  maxSteps: 0,
886
+ memberRunConcurrency: 0,
861
887
  wakeOnBackgroundTask: true,
862
888
  maxRunSeconds: 0,
863
889
  streamIdleMs: 60000,
@@ -1169,6 +1195,22 @@ export const KernelConfigSchema = z.strictObject({
1169
1195
  })),
1170
1196
  })
1171
1197
  .prefault({}),
1198
+ retention: z
1199
+ .strictObject({
1200
+ destructiveEnabled: z
1201
+ .boolean()
1202
+ .default(false)
1203
+ .meta(meta({
1204
+ description: "Allow retention and conversation purge workers to remove records after all older API and worker replicas have drained.",
1205
+ })),
1206
+ erasureEnabled: z
1207
+ .boolean()
1208
+ .default(false)
1209
+ .meta(meta({
1210
+ description: "Enable org purge and account erasure after all older writers have drained. Purging their conversation roots also requires retention.destructiveEnabled.",
1211
+ })),
1212
+ })
1213
+ .default({ destructiveEnabled: false, erasureEnabled: false }),
1172
1214
  storage: z
1173
1215
  .strictObject({
1174
1216
  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;
@@ -11,13 +11,18 @@ import { Inject, Injectable, Module, Optional } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { oweDelivery } from "../channels/deliver-job.js";
13
13
  import { ApiError } from "../errors.js";
14
+ import { afterCommit } from "../infra/database/after-commit.js";
14
15
  import { KernelDb } from "../infra/database/kernel-db.js";
15
16
  import { TransactionHost } from "../infra/database/transaction-host.js";
16
17
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
+ import { recordRun } from "../infra/metrics/kernel-metrics.js";
17
19
  import { OutboxService } from "../infra/outbox/outbox.service.js";
18
20
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
21
+ import { recordSettledModelUsage, settledUsageBucket } from "../models/budget-counters.js";
19
22
  import { readPriceSnapshots } from "../models/price-snapshot.js";
20
23
  import { PushOwed, PushOwedModule } from "../push/push-owed.js";
24
+ import { currentExecutionClaim } from "../runtime/run-execution.js";
25
+ import { runPrincipalAccount } from "../runtime/run-principal.js";
21
26
  import { ConversationEventSchema, } from "./events.js";
22
27
  /**
23
28
  * The JSON stored for an event payload, with every NUL (U+0000) in a string or an object key
@@ -519,6 +524,78 @@ let EventLog = class EventLog {
519
524
  }))
520
525
  .returning(EVENT_COLUMNS)
521
526
  .execute();
527
+ for (const row of inserted) {
528
+ if (row.type === "run_started")
529
+ afterCommit(() => recordRun("started"));
530
+ }
531
+ // Only the inserted rows count. Replay seeds bypass the live append, and an event
532
+ // referencing a run of another conversation cannot settle usage for this conversation.
533
+ const actors = new Map();
534
+ const freshUsage = inserted.flatMap((row) => {
535
+ if (row.type !== "usage")
536
+ return [];
537
+ const event = toEvent(row, true);
538
+ if (event.type !== "usage")
539
+ return [];
540
+ const inputIndex = fresh[Number(row.seq) - base - 1];
541
+ const sourceRunId = event.runId ??
542
+ (inputIndex === undefined ? undefined : events[inputIndex]?.usageAccountRunId);
543
+ return [{ event, sourceRunId }];
544
+ });
545
+ // All rows share the transaction timestamp and conversation shard. Resolve member keys
546
+ // before taking locks so appends acquire buckets and member rows in a stable order.
547
+ const settlements = [];
548
+ const claim = currentExecutionClaim();
549
+ let conversationAccount;
550
+ for (const { event, sourceRunId } of freshUsage) {
551
+ let accountId;
552
+ if (sourceRunId === undefined) {
553
+ conversationAccount ??= (await t
554
+ .selectFrom("conversations")
555
+ .select("account_id")
556
+ .where("id", "=", conversationId)
557
+ .where("org_id", "=", conv.org_id)
558
+ .executeTakeFirstOrThrow()).account_id;
559
+ accountId = conversationAccount;
560
+ }
561
+ else {
562
+ // Device review can surface its usage on the root log while a child owns the run.
563
+ const owningConversation = event.payload.purpose === "review" &&
564
+ claim?.runId === sourceRunId &&
565
+ claim.rootId === conversationId &&
566
+ claim.orgId === conv.org_id
567
+ ? claim.conversationId
568
+ : conversationId;
569
+ const principalKey = `${owningConversation}/${sourceRunId}`;
570
+ if (!actors.has(principalKey)) {
571
+ const run = await t
572
+ .selectFrom("runs")
573
+ .select(["id", "trigger_account_id", "budget_run_id", "compact_origin"])
574
+ .where("id", "=", sourceRunId)
575
+ .where("conversation_id", "=", owningConversation)
576
+ .executeTakeFirst();
577
+ actors.set(principalKey, run && {
578
+ accountId: (await runPrincipalAccount(t.db, run, owningConversation === conversationId ? conv.kind : "subagent")) ?? null,
579
+ });
580
+ }
581
+ const actor = actors.get(principalKey);
582
+ if (!actor)
583
+ continue;
584
+ accountId = actor.accountId;
585
+ }
586
+ settlements.push({
587
+ orgId: conv.org_id,
588
+ accountId,
589
+ usageSourceId: conversationId,
590
+ at: event.createdAt,
591
+ usage: event.payload,
592
+ snapshot: event.payload.priceSnapshot ?? null,
593
+ });
594
+ }
595
+ settlements.sort((a, b) => settledUsageBucket(a.snapshot).localeCompare(settledUsageBucket(b.snapshot), "en") ||
596
+ (a.accountId ?? "").localeCompare(b.accountId ?? "", "en"));
597
+ for (const entry of settlements)
598
+ await recordSettledModelUsage(t.db, entry);
522
599
  if (conv.im)
523
600
  await oweDelivery(this.outbox, { conversationId, orgId: conv.org_id, seq: toSeq });
524
601
  const bySeq = new Map(inserted.map((r) => [Number(r.seq), toEvent(r)]));
@@ -2143,6 +2143,17 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
2143
2143
  error: z.ZodObject<{
2144
2144
  code: z.ZodString;
2145
2145
  message: z.ZodString;
2146
+ budget: z.ZodOptional<z.ZodObject<{
2147
+ scope: z.ZodOptional<z.ZodEnum<{
2148
+ member: "member";
2149
+ org: "org";
2150
+ }>>;
2151
+ constraint: z.ZodOptional<z.ZodEnum<{
2152
+ spend: "spend";
2153
+ tokens: "tokens";
2154
+ }>>;
2155
+ resetAt: z.ZodOptional<z.ZodISODateTime>;
2156
+ }, z.core.$strip>>;
2146
2157
  }, z.core.$strip>;
2147
2158
  }, z.core.$strip>;
2148
2159
  }, z.core.$strip>, z.ZodObject<{
@@ -1961,7 +1961,19 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1961
1961
  reason: z.enum(["completed", "max_steps", "max_duration", "budget", "max_output"]),
1962
1962
  consumedUpToSeq: seqNo,
1963
1963
  })),
1964
- ev("run_failed", z.object({ error: z.object({ code: z.string(), message: z.string() }) })),
1964
+ ev("run_failed", z.object({
1965
+ error: z.object({
1966
+ code: z.string(),
1967
+ message: z.string(),
1968
+ budget: z
1969
+ .object({
1970
+ scope: z.enum(["org", "member"]).optional(),
1971
+ constraint: z.enum(["tokens", "spend"]).optional(),
1972
+ resetAt: z.iso.datetime().optional(),
1973
+ })
1974
+ .optional(),
1975
+ }),
1976
+ })),
1965
1977
  ev("run_aborted", z.object({
1966
1978
  byAccountId: z.string().nullable(),
1967
1979
  /**
@@ -28,6 +28,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
28
28
  import { Transactional } from "../infra/database/transactional.decorator.js";
29
29
  import { QueueModule } from "../infra/queue/queue.module.js";
30
30
  import { KERNEL_LOGGER } from "../infra/tokens.js";
31
+ import { ModelBudgetRefused } from "../models/budget-admission.js";
31
32
  import { OrgSettingsModule, OrgSettingsService } from "../orgs/settings.service.js";
32
33
  import { resolveCompactionSettings } from "../runtime/compaction-settings.service.js";
33
34
  import { fireObserve, hookDeniedAudit, hookDeniedEvent, } from "../runtime/hook-calls.js";
@@ -220,6 +221,8 @@ let PromptSuggestionGenerator = class PromptSuggestionGenerator {
220
221
  }, signal, this.log);
221
222
  }
222
223
  catch (err) {
224
+ if (err instanceof ModelBudgetRefused)
225
+ return;
223
226
  if (!(err instanceof ModelRequestDenied))
224
227
  throw err;
225
228
  await this.recordDenial(scope, err.verdict);
@@ -408,6 +411,7 @@ let PromptSuggestionGenerator = class PromptSuggestionGenerator {
408
411
  async writeUsage(conversationId, runId, u) {
409
412
  const event = {
410
413
  type: "usage",
414
+ usageAccountRunId: runId,
411
415
  idemKey: usageIdemKey(runId),
412
416
  payload: {
413
417
  step: 0,
@@ -20,6 +20,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
20
20
  import { Transactional } from "../infra/database/transactional.decorator.js";
21
21
  import { QueueModule } from "../infra/queue/queue.module.js";
22
22
  import { KERNEL_LOGGER } from "../infra/tokens.js";
23
+ import { ModelBudgetRefused } from "../models/budget-admission.js";
23
24
  import { ModelsModule } from "../models/models.module.js";
24
25
  import { ModelPurposesService, PurposeAttemptError } from "../models/purposes.js";
25
26
  import { fireObserve, hookDeniedAudit, hookDeniedEvent, } from "../runtime/hook-calls.js";
@@ -239,8 +240,8 @@ export async function runTitleJob(d, conversationId, attempt) {
239
240
  });
240
241
  }
241
242
  catch (err) {
242
- if (err instanceof TitleDenied) {
243
- // a policy denial is deterministic: no retries (one audit row, not one per attempt)
243
+ if (err instanceof TitleDenied || err instanceof ModelBudgetRefused) {
244
+ // Request-policy and budget refusals end automatic attempts for this title.
244
245
  await d.db
245
246
  .updateTable("conversations")
246
247
  .set({ title_attempts: TITLE_MAX_ATTEMPTS })