@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
@@ -4,6 +4,7 @@ import type { KernelSchemaDb } from "../db/kernel-schema.js";
4
4
  import { ExtensionHost } from "../extensions/host.js";
5
5
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
6
  import { KernelDb } from "../infra/database/kernel-db.js";
7
+ import { TransactionHost } from "../infra/database/transaction-host.js";
7
8
  import { LockService } from "../infra/lock/lock.service.js";
8
9
  import { type UsageReportJob } from "./usage-report-jobs.js";
9
10
  export { queryUsageSubscribers } from "../extensions/usage-subscribers.js";
@@ -65,7 +66,7 @@ export declare function narrowPending(stored: readonly string[] | undefined, fai
65
66
  * is read from the row when the job runs, and the row's `reported_at` is set once nothing is left
66
67
  * to deliver; a job that gives up after its last attempt sets `report_failed_at`. A row with
67
68
  * `reported_at IS NULL` is not necessarily pending: no job is owed when no enabled extension
68
- * subscribed to `usage.report` at the time of the call, and such a row is never reported.
69
+ * subscribed at write time. When erasure is enabled the writer explicitly settles those rows.
69
70
  */
70
71
  export declare class UsageReporter {
71
72
  private readonly kdb;
@@ -79,6 +80,7 @@ export declare class UsageReporter {
79
80
  /** The warning throttle's markers (`capk:usage-warn:<plugin>:<kind>`, SET NX PX). */
80
81
  private readonly locks;
81
82
  private readonly log;
83
+ readonly txHost: TransactionHost;
82
84
  private worker;
83
85
  private closed;
84
86
  private readonly stopping;
@@ -89,7 +91,7 @@ export declare class UsageReporter {
89
91
  */
90
92
  host: Pick<ExtensionHost, "hooks" | "current">, config: Pick<KernelConfigService, "get">,
91
93
  /** The warning throttle's markers (`capk:usage-warn:<plugin>:<kind>`, SET NX PX). */
92
- locks: Pick<LockService, "lease">, log: Logger);
94
+ locks: Pick<LockService, "lease">, log: Logger, txHost: TransactionHost);
93
95
  private get db();
94
96
  private get hooks();
95
97
  /**
@@ -132,7 +134,7 @@ export declare class UsageReporter {
132
134
  * conversation fields; `eventId` is the row id. Null when the row no longer exists.
133
135
  */
134
136
  private payloadOfUsage;
135
- /** A `model_usage` job is done (delivered, or nothing left to deliver to): marks the row. */
137
+ /** A definite drop keeps its durable obligation for manual retry. A full delivery settles it. */
136
138
  private markReported;
137
139
  /** A `model_usage` job gave up after its last attempt: the row records it. */
138
140
  private markFailed;
@@ -20,11 +20,13 @@ import { queryUsageSubscribers } from "../extensions/usage-subscribers.js";
20
20
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
21
21
  import { KernelDb } from "../infra/database/kernel-db.js";
22
22
  import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
23
+ import { TransactionHost } from "../infra/database/transaction-host.js";
24
+ import { Transactional } from "../infra/database/transactional.decorator.js";
23
25
  import { LockService } from "../infra/lock/lock.service.js";
24
26
  import { QueueModule } from "../infra/queue/queue.module.js";
25
27
  import { KERNEL_LOGGER } from "../infra/tokens.js";
26
28
  import { deliveryRowOfChildRun } from "./subagents/child.js";
27
- import { USAGE_REPORT_QUEUE, UsageReportJobsModule, } from "./usage-report-jobs.js";
29
+ import { modelUsageJobId, USAGE_REPORT_QUEUE, UsageReportJobsModule, usageReportJobId, } from "./usage-report-jobs.js";
28
30
  export { queryUsageSubscribers } from "../extensions/usage-subscribers.js";
29
31
  export { modelUsageJobId, USAGE_REPORT_JOB, USAGE_REPORT_QUEUE, UsageReportJobs, UsageReportJobsModule, usageReportJobId, } from "./usage-report-jobs.js";
30
32
  /** Warnings about a plugin that cannot take deliveries are logged at most once per this window. */
@@ -122,7 +124,7 @@ export function narrowPending(stored, failed) {
122
124
  * is read from the row when the job runs, and the row's `reported_at` is set once nothing is left
123
125
  * to deliver; a job that gives up after its last attempt sets `report_failed_at`. A row with
124
126
  * `reported_at IS NULL` is not necessarily pending: no job is owed when no enabled extension
125
- * subscribed to `usage.report` at the time of the call, and such a row is never reported.
127
+ * subscribed at write time. When erasure is enabled the writer explicitly settles those rows.
126
128
  */
127
129
  let UsageReporter = class UsageReporter {
128
130
  kdb;
@@ -131,6 +133,7 @@ let UsageReporter = class UsageReporter {
131
133
  config;
132
134
  locks;
133
135
  log;
136
+ txHost;
134
137
  worker;
135
138
  closed = false;
136
139
  stopping = new AbortController();
@@ -141,13 +144,14 @@ let UsageReporter = class UsageReporter {
141
144
  */
142
145
  host, config,
143
146
  /** The warning throttle's markers (`capk:usage-warn:<plugin>:<kind>`, SET NX PX). */
144
- locks, log) {
147
+ locks, log, txHost) {
145
148
  this.kdb = kdb;
146
149
  this.queue = queue;
147
150
  this.host = host;
148
151
  this.config = config;
149
152
  this.locks = locks;
150
153
  this.log = log;
154
+ this.txHost = txHost;
151
155
  queue.on("error", (err) => this.log.error("usage report queue error", { err }));
152
156
  }
153
157
  get db() {
@@ -290,17 +294,27 @@ let UsageReporter = class UsageReporter {
290
294
  occurredAt: new Date(row.occurred_at).toISOString(),
291
295
  };
292
296
  }
293
- /** A `model_usage` job is done (delivered, or nothing left to deliver to): marks the row. */
294
- // org-filter: marks the model_usage row of a kernel-written usage job id
295
- async markReported(data) {
296
- if (data.usageId === undefined)
297
- return;
298
- await this.db
299
- .updateTable("model_usage")
300
- .set({ reported_at: sql `now()` })
301
- .where("id", "=", data.usageId)
302
- .where("reported_at", "is", null)
303
- .execute();
297
+ /** A definite drop keeps its durable obligation for manual retry. A full delivery settles it. */
298
+ async markReported(orgId, data, settled) {
299
+ if (data.usageId !== undefined) {
300
+ await this.db
301
+ .updateTable("model_usage")
302
+ .set({ reported_at: sql `now()` })
303
+ .where("id", "=", data.usageId)
304
+ .where("org_id", "=", orgId)
305
+ .where("reported_at", "is", null)
306
+ .execute();
307
+ }
308
+ if (settled) {
309
+ const jobId = data.usageId === undefined
310
+ ? usageReportJobId(data.conversationId, data.seq)
311
+ : modelUsageJobId(data.usageId);
312
+ await this.db
313
+ .deleteFrom("usage_report_obligations")
314
+ .where("org_id", "=", orgId)
315
+ .where("job_id", "=", jobId)
316
+ .execute();
317
+ }
304
318
  }
305
319
  /** A `model_usage` job gave up after its last attempt: the row records it. */
306
320
  // org-filter: marks the model_usage row of a kernel-written usage job id
@@ -426,8 +440,9 @@ let UsageReporter = class UsageReporter {
426
440
  }
427
441
  // plugins the organization disabled meanwhile are dropped (not a failure)
428
442
  const targets = (j.data.pending ?? []).filter((p) => subscribers.has(p));
429
- if (targets.length === 0) {
430
- await this.markReported(j.data);
443
+ const pendingDrops = Object.keys(j.data.dropped ?? {}).some((plugin) => subscribers.has(plugin));
444
+ if (targets.length === 0 && !pendingDrops) {
445
+ await this.markReported(payload.orgId, j.data, true);
431
446
  return;
432
447
  }
433
448
  const byPlugin = new Map();
@@ -508,9 +523,8 @@ let UsageReporter = class UsageReporter {
508
523
  // m-1: pending = the dropped plugins only, so a manual retry reaches them and never the
509
524
  // plugins already served
510
525
  await this.writePending(j, [...allDropped.keys()], allDropped);
511
- // delivered to every target still servable (a definite drop is final too): the row is done
512
- await this.markReported(j.data);
513
526
  const traced = new Map([...allDropped].filter(([p]) => j.data.dropped?.[p] !== undefined));
527
+ await this.markReported(payload.orgId, j.data, traced.size === 0);
514
528
  if (traced.size === 0)
515
529
  return;
516
530
  // N-3: a definite drop leaves a durable trace: the job ends failed (kept under the failed-job
@@ -573,6 +587,9 @@ let UsageReporter = class UsageReporter {
573
587
  }
574
588
  }
575
589
  };
590
+ __decorate([
591
+ Transactional()
592
+ ], UsageReporter.prototype, "markReported", null);
576
593
  UsageReporter = __decorate([
577
594
  Injectable(),
578
595
  __param(0, Inject(KernelDb)),
@@ -580,7 +597,8 @@ UsageReporter = __decorate([
580
597
  __param(2, Inject(ExtensionHost)),
581
598
  __param(3, Inject(KernelConfigService)),
582
599
  __param(4, Inject(LockService)),
583
- __param(5, Inject(KERNEL_LOGGER))
600
+ __param(5, Inject(KERNEL_LOGGER)),
601
+ __param(6, Inject(TransactionHost))
584
602
  ], UsageReporter);
585
603
  export { UsageReporter };
586
604
  /** The usage report queue (one instance per process). */
@@ -245,8 +245,8 @@ export declare function reviewModelLimits(deps: Pick<ReviewClassifierDeps, "purp
245
245
  * Sends one prepared review call on the `review` purpose: the `model.request` policy hook, the
246
246
  * call bounded by `sandbox.review.timeoutMs` and the run's signal, `model.response`, the `usage`
247
247
  * event (a sent call that failed billed at its estimate), and the strict parse of the answer.
248
- * Never throws: a hook denial, a timeout, an error or an unparseable answer is `ask`, and so is an
249
- * `allow` on a truncated message.
248
+ * A budget refusal denies the action with its actionable model-facing reason. A hook denial,
249
+ * timeout, provider error or unparseable answer is `ask`, as is `allow` on a truncated message.
250
250
  */
251
251
  export declare function callReviewModel(deps: ReviewClassifierDeps, args: ReviewModelCallArgs, call: ReviewModelCall): Promise<ClassifierAnswer>;
252
252
  export {};
@@ -1,6 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { isModelError, } from "@capybara-hq/plugin-sdk";
3
3
  import { z } from "zod";
4
+ import { ModelBudgetRefused } from "../../models/budget-admission.js";
4
5
  import { PurposeAttemptError } from "../../models/purposes.js";
5
6
  import { estimateTokens } from "../../runtime/context/tokens.js";
6
7
  import { fireObserve, hookDeniedAudit, hookDeniedEvent, hookScope, } from "../../runtime/hook-calls.js";
@@ -456,8 +457,8 @@ export async function reviewModelLimits(deps, args, label) {
456
457
  * Sends one prepared review call on the `review` purpose: the `model.request` policy hook, the
457
458
  * call bounded by `sandbox.review.timeoutMs` and the run's signal, `model.response`, the `usage`
458
459
  * event (a sent call that failed billed at its estimate), and the strict parse of the answer.
459
- * Never throws: a hook denial, a timeout, an error or an unparseable answer is `ask`, and so is an
460
- * `allow` on a truncated message.
460
+ * A budget refusal denies the action with its actionable model-facing reason. A hook denial,
461
+ * timeout, provider error or unparseable answer is `ask`, as is `allow` on a truncated message.
461
462
  */
462
463
  export async function callReviewModel(deps, args, call) {
463
464
  const outcomes = call.outcomes ?? COMMAND_REVIEW_OUTCOMES;
@@ -514,6 +515,9 @@ export async function callReviewModel(deps, args, call) {
514
515
  });
515
516
  }
516
517
  catch (err) {
518
+ if (err instanceof ModelBudgetRefused) {
519
+ return { decision: "deny", reason: err.message };
520
+ }
517
521
  observe(deps, hookBase, sent, null, err, args.signal);
518
522
  deps.log.warn(`${outcomes.label} call failed`, {
519
523
  conversationId: args.conversationId,
@@ -3071,13 +3071,24 @@ let SandboxService = class SandboxService {
3071
3071
  this.log.info("sandbox instance destroyed", { deviceId: id });
3072
3072
  return;
3073
3073
  }
3074
- const r = await this.db
3075
- .deleteFrom("device_instances")
3076
- .where("device_id", "=", id)
3077
- .where("org_id", "=", row.org_id)
3078
- .where("generation", "=", fence.gen)
3079
- .executeTakeFirst();
3080
- if (Number(r.numDeletedRows) !== 1)
3074
+ // The acknowledgement and removal of its exact handles commit together. A dial-in
3075
+ // provider may acknowledge an offline machine without having destroyed its files.
3076
+ const result = await sql `
3077
+ WITH removed AS (
3078
+ DELETE FROM capybara.device_instances WHERE device_id = ${id}
3079
+ AND org_id = ${row.org_id} AND generation = ${fence.gen}
3080
+ RETURNING device_id, org_id, provider
3081
+ ), proof AS (
3082
+ UPDATE capybara.devices d SET files_destroyed_at = now() FROM removed r
3083
+ WHERE d.id = r.device_id AND d.org_id = r.org_id
3084
+ AND d.provider = r.provider AND r.provider = ${p.plugin}
3085
+ AND d.demoted_from_provider IS NULL AND ${!servesDialIn(p)}
3086
+ AND (d.deleted_at IS NOT NULL OR EXISTS (
3087
+ SELECT FROM capybara.orgs o WHERE o.id = d.org_id AND o.deleted_at IS NOT NULL
3088
+ ))
3089
+ ) SELECT EXISTS (SELECT FROM removed) AS retired
3090
+ `.execute(this.db.db);
3091
+ if (!result.rows[0]?.retired)
3081
3092
  throw new SandboxLockLostError(id, "generation");
3082
3093
  this.log.info("device destroyed", { deviceId: id });
3083
3094
  }
@@ -105,10 +105,14 @@ let StoragePurgeJob = class StoragePurgeJob {
105
105
  this.log = log;
106
106
  }
107
107
  async run() {
108
+ const config = this.config.get();
109
+ // The erasure worker owns the prefix once it can verify the database and external drains.
110
+ if (config.retention.erasureEnabled)
111
+ return;
108
112
  await purgeDeletedOrgStorage({
109
113
  db: this.db,
110
114
  storage: this.storage,
111
- afterDays: this.config.get().storage.purgeDeletedOrgsAfterDays,
115
+ afterDays: config.storage.purgeDeletedOrgsAfterDays,
112
116
  log: this.log,
113
117
  });
114
118
  }
@@ -1,4 +1,5 @@
1
1
  import { ExtensionPointUnavailableError, type ExtensionStorage, type ObjectStore } from "@capybara-hq/plugin-sdk";
2
+ import type { Keyring } from "../ctx/secrets.js";
2
3
  import { ExtensionRegistry } from "../extensions/registry.js";
3
4
  import { KernelDb } from "../infra/database/kernel-db.js";
4
5
  export { StorageKeyError } from "./prefix.js";
@@ -16,6 +17,10 @@ export declare function clampPresignTtl(ttlSeconds: number): number;
16
17
  export interface StorageSource {
17
18
  /** 当前的 `object-store@1` 提供方;每次调用时取(提供方在插件加载过程中才就绪)。 */
18
19
  provider: () => ObjectStore | undefined;
20
+ erasureTarget?: () => {
21
+ store: ObjectStore;
22
+ identity: string;
23
+ } | undefined;
19
24
  /** 可能存过数据的插件名(删除组织数据时逐个删 `plugins/<插件>/<orgId>/`)。 */
20
25
  plugins: () => Promise<string[]>;
21
26
  }
@@ -47,6 +52,17 @@ export declare class PrefixedStorage {
47
52
  private scopedStore;
48
53
  /** 删除该组织的全部对象:`kernel/<orgId>/` 与每个插件的 `plugins/<插件>/<orgId>/`。返回删除数。 */
49
54
  deleteOrg(orgId: string): Promise<number>;
55
+ /** Keyed fingerprint of the provider version and its full validated configuration. */
56
+ erasureIdentity(): string | null;
57
+ private requireErasureTarget;
58
+ /** Run erasure I/O on one verified provider instance. */
59
+ verifyErasureObjects(orgId: string, identity: string, verify: (store: ObjectStore) => Promise<void>): Promise<void>;
60
+ private assertSameErasureTarget;
61
+ /** Verify the exact account prefix with a single provider instance. */
62
+ deleteVerifiedAccountAvatars(accountId: string, identity: string): Promise<void>;
63
+ private verifyAbsent;
64
+ /** Verify each deleted prefix with the same provider before confirming the external phase. */
65
+ deleteVerifiedOrg(orgId: string, capturedPlugins: readonly string[], identity: string): Promise<number>;
50
66
  private require;
51
67
  }
52
68
  /**
@@ -56,5 +72,5 @@ export declare class PrefixedStorage {
56
72
  * uninstalled ones) plus the loaded ones.
57
73
  */
58
74
  export declare class StorageService extends PrefixedStorage {
59
- constructor(registry: ExtensionRegistry, db: KernelDb);
75
+ constructor(registry: ExtensionRegistry, db: KernelDb, keyring: Keyring);
60
76
  }
@@ -7,11 +7,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
+ import { createHmac } from "node:crypto";
10
11
  import { ExtensionPointUnavailableError, OBJECT_STORE_EXTENSION_POINT, } from "@capybara-hq/plugin-sdk";
11
12
  import { Inject, Injectable } from "@nestjs/common";
12
13
  import { ApiError } from "../errors.js";
13
14
  import { ExtensionRegistry } from "../extensions/registry.js";
14
15
  import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { KEYRING } from "../infra/tokens.js";
17
+ import { canonicalJson } from "../tools/canonical-json.js";
15
18
  import { KeySpace, kernelPrefix, normalizeOrgId, pluginPrefix } from "./prefix.js";
16
19
  export { StorageKeyError } from "./prefix.js";
17
20
  /** 部署级对象的键前缀(见 {@link StorageService.deployment})。 */
@@ -116,6 +119,55 @@ export class PrefixedStorage {
116
119
  }
117
120
  return n;
118
121
  }
122
+ /** Keyed fingerprint of the provider version and its full validated configuration. */
123
+ erasureIdentity() {
124
+ return this.d.erasureTarget?.()?.identity ?? null;
125
+ }
126
+ requireErasureTarget(identity) {
127
+ const target = this.d.erasureTarget?.();
128
+ if (target?.identity !== identity)
129
+ throw new Error("Object storage provider changed or cannot be verified");
130
+ return target.store;
131
+ }
132
+ /** Run erasure I/O on one verified provider instance. */
133
+ async verifyErasureObjects(orgId, identity, verify) {
134
+ const store = this.requireErasureTarget(identity);
135
+ await verify(new ScopedStore(store, new KeySpace(kernelPrefix(orgId))));
136
+ this.assertSameErasureTarget(identity, store);
137
+ }
138
+ assertSameErasureTarget(identity, store) {
139
+ if (this.requireErasureTarget(identity) !== store)
140
+ throw new Error("Object storage provider changed during erasure");
141
+ }
142
+ /** Verify the exact account prefix with a single provider instance. */
143
+ async deleteVerifiedAccountAvatars(accountId, identity) {
144
+ const store = this.requireErasureTarget(identity);
145
+ const prefix = `${DEPLOYMENT_PREFIX}account-avatars/${normalizeOrgId(accountId)}/`;
146
+ await store.deletePrefix(prefix);
147
+ await this.verifyAbsent(store, prefix);
148
+ this.assertSameErasureTarget(identity, store);
149
+ }
150
+ async verifyAbsent(store, prefix) {
151
+ const remaining = await store.list(prefix, { limit: 1 });
152
+ if (remaining.items.length !== 0 || remaining.cursor !== undefined)
153
+ throw new Error("Organization storage is still present or could not be verified");
154
+ }
155
+ /** Verify each deleted prefix with the same provider before confirming the external phase. */
156
+ async deleteVerifiedOrg(orgId, capturedPlugins, identity) {
157
+ const plugins = new Set([...capturedPlugins, ...(await this.d.plugins())]);
158
+ const store = this.requireErasureTarget(identity);
159
+ const prefixes = [
160
+ kernelPrefix(orgId),
161
+ ...[...plugins].sort().map((p) => pluginPrefix(p, orgId)),
162
+ ];
163
+ let removed = 0;
164
+ for (const prefix of prefixes) {
165
+ removed += await store.deletePrefix(prefix);
166
+ await this.verifyAbsent(store, prefix);
167
+ }
168
+ this.assertSameErasureTarget(identity, store);
169
+ return removed;
170
+ }
119
171
  require() {
120
172
  const store = this.d.provider();
121
173
  if (!store)
@@ -130,10 +182,28 @@ export class PrefixedStorage {
130
182
  * uninstalled ones) plus the loaded ones.
131
183
  */
132
184
  let StorageService = class StorageService extends PrefixedStorage {
133
- constructor(registry, db) {
185
+ constructor(registry, db, keyring) {
186
+ const key = keyring.deriveKey("erasure-storage-location").current;
187
+ const selected = () => registry
188
+ .list("object-store")
189
+ .find((entry) => entry.capability === OBJECT_STORE_EXTENSION_POINT);
134
190
  super({
135
- provider: () => registry.list("object-store").find((e) => e.capability === OBJECT_STORE_EXTENSION_POINT)
136
- ?.impl,
191
+ provider: () => selected()?.impl,
192
+ erasureTarget: () => {
193
+ const entry = selected();
194
+ if (!entry)
195
+ return undefined;
196
+ const config = registry.deploymentConfig(entry.plugin);
197
+ if (config == null)
198
+ return undefined;
199
+ const store = entry.impl;
200
+ // The registry's public hash deliberately omits credentials. A credential can select
201
+ // a private namespace, so use a dedicated keyed digest and never persist the config.
202
+ const identity = createHmac("sha256", key)
203
+ .update(canonicalJson([entry.plugin, entry.version, config]))
204
+ .digest("hex");
205
+ return { store, identity };
206
+ },
137
207
  plugins: async () => {
138
208
  const rows = await db
139
209
  .selectFrom("extension_permission_snapshots")
@@ -147,7 +217,8 @@ let StorageService = class StorageService extends PrefixedStorage {
147
217
  StorageService = __decorate([
148
218
  Injectable(),
149
219
  __param(0, Inject(ExtensionRegistry)),
150
- __param(1, Inject(KernelDb))
220
+ __param(1, Inject(KernelDb)),
221
+ __param(2, Inject(KEYRING))
151
222
  ], StorageService);
152
223
  export { StorageService };
153
224
  /** 一个前缀下的 ObjectStore 视图:键先校验再拼接,返回的键去掉前缀。 */
@@ -1,5 +1,6 @@
1
1
  import { IMAGE_MEDIA_TYPES, isModelError, ToolError, } from "@capybara-hq/plugin-sdk";
2
2
  import { ApiError } from "../../../errors.js";
3
+ import { ModelBudgetRefused } from "../../../models/budget-admission.js";
3
4
  import { PurposeAttemptError } from "../../../models/purposes.js";
4
5
  import { fireObserve, hookDeniedAudit, hookDeniedEvent, hookScope, } from "../../../runtime/hook-calls.js";
5
6
  import { appendCounted } from "../../../runtime/model-call.js";
@@ -106,6 +107,8 @@ export async function readImageWithVisionModel(deps, ctx, img) {
106
107
  });
107
108
  }
108
109
  catch (err) {
110
+ if (err instanceof ModelBudgetRefused)
111
+ throw err;
109
112
  if (err instanceof VisionDenied)
110
113
  throw new ToolError(VISION_DENIED_TEXT);
111
114
  // unmapped, or a target the org cannot use or that cannot view images: no fallback
@@ -1,5 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { isModelError, ToolError, } from "@capybara-hq/plugin-sdk";
3
+ import { ModelBudgetRefused } from "../../../models/budget-admission.js";
3
4
  import { PurposeAttemptError } from "../../../models/purposes.js";
4
5
  import { estimateTokens } from "../../../runtime/context/tokens.js";
5
6
  import { fireObserve, hookDeniedAudit, hookDeniedEvent, hookScope, } from "../../../runtime/hook-calls.js";
@@ -159,6 +160,8 @@ export async function extractAnswer(deps, ctx, page, prompt) {
159
160
  });
160
161
  }
161
162
  catch (err) {
163
+ if (err instanceof ModelBudgetRefused)
164
+ throw err;
162
165
  if (err instanceof ExtractionDenied)
163
166
  throw new ToolError(WEB_FETCH_DENIED_TEXT);
164
167
  observe(deps, hookBase, sent, null, err, ctx.signal);
@@ -3901,7 +3901,11 @@ let ToolPipeline = class ToolPipeline {
3901
3901
  return { kind: "error", message: e.message };
3902
3902
  // an extension tool's ctx.models.embed denied by a policy hook (spec B §5.4): the model sees the
3903
3903
  // deny text (sanitized reason), as for a denied tool call, not a generic failure
3904
- if (e instanceof ApiError && e.code === "model.hook_denied") {
3904
+ if (e instanceof ApiError &&
3905
+ (e.code === "model.hook_denied" ||
3906
+ e.code === "model.budget_exceeded" ||
3907
+ e.code === "model.budget_currency_mismatch" ||
3908
+ e.code === "model.budget_unavailable")) {
3905
3909
  return { kind: "error", message: e.message };
3906
3910
  }
3907
3911
  // 提供工具的插件实例在调用进行中被撤销(停用 / 升级),排空时限到后中止(C17)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.130",
3
+ "version": "0.1.0-rc.131",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -44,6 +44,7 @@
44
44
  "@nestjs/swagger": "12.0.5",
45
45
  "@nestjs/terminus": "12.1.0",
46
46
  "@nestjs/throttler": "6.7.1",
47
+ "@opentelemetry/api": "1.9.1",
47
48
  "ajv": "^8.20.0",
48
49
  "bullmq": "^6.3.15",
49
50
  "cron": "4.4.0",
@@ -70,6 +71,7 @@
70
71
  },
71
72
  "devDependencies": {
72
73
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
74
+ "@opentelemetry/sdk-metrics": "2.12.0",
73
75
  "@types/pg": "^8.23.1",
74
76
  "@types/semver": "^7.8.0",
75
77
  "@types/ws": "^8.18.2",
@@ -0,0 +1,24 @@
1
+ -- A bucket is the snapshot currency or the reason its tokens have no known price.
2
+ CREATE TABLE IF NOT EXISTS model_budget_org_usage (
3
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
4
+ period_start date NOT NULL,
5
+ bucket text NOT NULL CHECK (bucket ~ '^[A-Z]{3}$' OR bucket IN ('unpriced', 'unknown')),
6
+ tokens bigint NOT NULL,
7
+ amount numeric NOT NULL,
8
+ shard smallint NOT NULL CHECK (shard BETWEEN 0 AND 15),
9
+ PRIMARY KEY (org_id, period_start, bucket, shard)
10
+ );
11
+ DROP POLICY IF EXISTS org_scope ON model_budget_org_usage;
12
+ CREATE POLICY org_scope ON model_budget_org_usage USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
13
+
14
+ CREATE TABLE IF NOT EXISTS model_budget_member_usage (
15
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
16
+ account_id text NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
17
+ period_start date NOT NULL,
18
+ bucket text NOT NULL CHECK (bucket ~ '^[A-Z]{3}$' OR bucket IN ('unpriced', 'unknown')),
19
+ tokens bigint NOT NULL,
20
+ amount numeric NOT NULL,
21
+ PRIMARY KEY (org_id, account_id, period_start, bucket)
22
+ );
23
+ DROP POLICY IF EXISTS org_scope ON model_budget_member_usage;
24
+ CREATE POLICY org_scope ON model_budget_member_usage USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
@@ -0,0 +1,44 @@
1
+ -- The target may disappear in the last batch. Its progress row survives for replay and reporting.
2
+ CREATE TABLE IF NOT EXISTS retention_work (
3
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
4
+ org_id text REFERENCES orgs(id) ON DELETE CASCADE,
5
+ kind text NOT NULL CHECK (kind IN ('purge','org-scan','platform-audit')),
6
+ target text NOT NULL,
7
+ generation integer NOT NULL DEFAULT 0,
8
+ state text NOT NULL DEFAULT 'ready' CHECK (state IN ('ready','blocked','done')),
9
+ blocked_reason text,
10
+ cursor_id text,
11
+ usage_cursor text,
12
+ due_at timestamptz NOT NULL DEFAULT now(),
13
+ CHECK ((org_id IS NULL) = (kind = 'platform-audit')),
14
+ UNIQUE (kind,target)
15
+ );
16
+ DROP POLICY IF EXISTS org_scope ON retention_work;
17
+ CREATE POLICY org_scope ON retention_work USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
18
+ CREATE INDEX IF NOT EXISTS retention_due ON retention_work (due_at,id) WHERE state <> 'done';
19
+
20
+ CREATE TABLE IF NOT EXISTS retention_coverage (
21
+ org_id text PRIMARY KEY REFERENCES orgs(id) ON DELETE CASCADE,
22
+ usage_incomplete_since timestamptz,
23
+ usage_incomplete_through timestamptz,
24
+ runs_incomplete_through timestamptz,
25
+ runs_incomplete_since timestamptz
26
+ );
27
+ DROP POLICY IF EXISTS org_scope ON retention_coverage;
28
+ CREATE POLICY org_scope ON retention_coverage USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
29
+
30
+ CREATE INDEX IF NOT EXISTS retention_tombstones ON conversations (deleted_at,id)
31
+ WHERE deleted_at IS NOT NULL AND parent_conversation_id IS NULL;
32
+ CREATE INDEX IF NOT EXISTS retention_roots ON conversations (org_id,id) WHERE parent_conversation_id IS NULL;
33
+ CREATE INDEX IF NOT EXISTS retention_audit ON audit_events (org_id,at,id);
34
+ CREATE INDEX IF NOT EXISTS retention_usage ON model_usage (org_id,occurred_at,id)
35
+ WHERE reported_at IS NOT NULL OR report_failed_at IS NULL;
36
+
37
+ -- Failed report jobs may leave Redis before the source's recovery hold expires.
38
+ CREATE TABLE IF NOT EXISTS usage_report_obligations (
39
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
40
+ job_id text NOT NULL,
41
+ PRIMARY KEY (org_id,job_id)
42
+ );
43
+ DROP POLICY IF EXISTS org_scope ON usage_report_obligations;
44
+ CREATE POLICY org_scope ON usage_report_obligations USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
@@ -0,0 +1,41 @@
1
+ ALTER TABLE accounts ADD COLUMN IF NOT EXISTS erasure_requested boolean NOT NULL DEFAULT false;
2
+
3
+ -- Operation receipts survive the removal of their targets. A completed receipt has no target.
4
+ CREATE TABLE IF NOT EXISTS data_erasure_requests (
5
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
6
+ kind text NOT NULL CHECK (kind IN ('org', 'account')),
7
+ org_id text,
8
+ target_id text,
9
+ generation integer NOT NULL DEFAULT 0 CHECK (generation >= 0),
10
+ stage text NOT NULL DEFAULT 'pending' CHECK (stage IN ('pending', 'blocked', 'roots', 'objects', 'rows', 'prefix', 'late', 'account-orgs', 'account-external', 'account-final', 'done')),
11
+ blocked_reason text,
12
+ scope_boundaries text[] NOT NULL DEFAULT ARRAY[]::text[],
13
+ progress jsonb CHECK (jsonb_typeof(progress) = 'object'),
14
+ due_at timestamptz NOT NULL DEFAULT now(),
15
+ completed_at timestamptz,
16
+ UNIQUE (kind, target_id),
17
+ CHECK (scope_boundaries <@ ARRAY['third-party-conversation-content']::text[]),
18
+ CHECK (kind = 'account' OR cardinality(scope_boundaries) = 0),
19
+ CHECK ((stage = 'done') = (target_id IS NULL)),
20
+ CHECK ((stage = 'done') = (completed_at IS NOT NULL)),
21
+ CHECK (stage <> 'done' OR (blocked_reason IS NULL AND progress IS NULL)),
22
+ CHECK ((kind = 'account' AND org_id IS NULL) OR
23
+ (kind = 'org' AND org_id IS NOT DISTINCT FROM target_id))
24
+ );
25
+ DROP POLICY IF EXISTS org_scope ON data_erasure_requests;
26
+ CREATE POLICY org_scope ON data_erasure_requests USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
27
+ CREATE INDEX IF NOT EXISTS data_erasure_due ON data_erasure_requests (due_at, id) WHERE stage <> 'done';
28
+ CREATE INDEX IF NOT EXISTS data_erasure_completed ON data_erasure_requests (completed_at, id) WHERE stage = 'done';
29
+
30
+ -- Preserve shared records when an erased account was their historical author.
31
+ ALTER TABLE agent_versions ALTER COLUMN created_by DROP NOT NULL;
32
+ ALTER TABLE api_tokens ALTER COLUMN created_by DROP NOT NULL;
33
+ ALTER TABLE channel_connections ALTER COLUMN created_by DROP NOT NULL;
34
+ ALTER TABLE invitations ALTER COLUMN created_by DROP NOT NULL;
35
+ ALTER TABLE eval_runs ALTER COLUMN created_by DROP NOT NULL;
36
+ ALTER TABLE eval_sets ALTER COLUMN created_by DROP NOT NULL;
37
+ ALTER TABLE eval_cases ALTER COLUMN added_by DROP NOT NULL;
38
+ ALTER TABLE device_projects ALTER COLUMN created_by DROP NOT NULL;
39
+
40
+ -- Written only after the bound provider acknowledged both instance and file destruction.
41
+ ALTER TABLE devices ADD COLUMN IF NOT EXISTS files_destroyed_at timestamptz;