@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
@@ -0,0 +1,180 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { asPlatform, currentScope } from "../infra/database/org-scope.js";
14
+ import { TransactionHost } from "../infra/database/transaction-host.js";
15
+ import { Transactional } from "../infra/database/transactional.decorator.js";
16
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
17
+ import { oweErasure } from "./jobs.js";
18
+ const statusColumns = [
19
+ "id",
20
+ "kind",
21
+ "stage",
22
+ "blocked_reason as blockedReason",
23
+ "scope_boundaries as scopeBoundaries",
24
+ "due_at as dueAt",
25
+ "completed_at as completedAt",
26
+ ];
27
+ let ErasureRequests = class ErasureRequests {
28
+ db;
29
+ txHost;
30
+ outbox;
31
+ constructor(db, txHost, outbox) {
32
+ this.db = db;
33
+ this.txHost = txHost;
34
+ this.outbox = outbox;
35
+ }
36
+ async enqueue(kind, targetId, progress) {
37
+ const orgId = kind === "org" ? targetId : null;
38
+ const scope = currentScope();
39
+ if (!scope || (scope.kind === "org" && scope.orgId !== orgId))
40
+ throw new Error("Erasure admission requires the target scope");
41
+ const inserted = await this.db
42
+ .insertInto("data_erasure_requests")
43
+ .values({
44
+ kind,
45
+ org_id: orgId,
46
+ target_id: targetId,
47
+ progress: progress === undefined ? null : JSON.stringify(progress),
48
+ })
49
+ .onConflict((oc) => oc.columns(["kind", "target_id"]).doNothing())
50
+ .returning(statusColumns)
51
+ .executeTakeFirst();
52
+ if (inserted) {
53
+ await oweErasure(this.outbox, inserted.id, 0, orgId);
54
+ return inserted;
55
+ }
56
+ const existing = await this.active(kind, targetId);
57
+ if (!existing)
58
+ throw new Error("Erasure request changed during admission");
59
+ return existing;
60
+ }
61
+ async active(kind, targetId) {
62
+ const orgId = kind === "org" ? targetId : null;
63
+ const scope = currentScope();
64
+ if (!scope || (scope.kind === "org" && scope.orgId !== orgId))
65
+ return;
66
+ return this.db
67
+ .selectFrom("data_erasure_requests")
68
+ .select(statusColumns)
69
+ .where("kind", "=", kind)
70
+ .where("target_id", "=", targetId)
71
+ .where("org_id", orgId === null ? "is" : "=", orgId)
72
+ .executeTakeFirst();
73
+ }
74
+ async status(id) {
75
+ const scope = currentScope();
76
+ if (!scope)
77
+ return;
78
+ if (scope.kind === "org")
79
+ return this.db
80
+ .selectFrom("data_erasure_requests")
81
+ .select(statusColumns)
82
+ .where("org_id", "=", scope.orgId)
83
+ .where("id", "=", id)
84
+ .executeTakeFirst();
85
+ // org-filter: deployment-wide authorized operator lookup of an opaque receipt
86
+ return asPlatform("read erasure receipt", () => this.db
87
+ .selectFrom("data_erasure_requests")
88
+ .select(statusColumns)
89
+ .where("id", "=", id)
90
+ .executeTakeFirst());
91
+ }
92
+ resolveOwner(id) {
93
+ // org-filter: deployment-wide worker lookup of the scope for an opaque request ID
94
+ return asPlatform("resolve erasure request scope", () => this.db
95
+ .selectFrom("data_erasure_requests")
96
+ .select("org_id")
97
+ .where("id", "=", id)
98
+ .executeTakeFirst());
99
+ }
100
+ async claim(id, generation) {
101
+ const scope = currentScope();
102
+ if (!scope)
103
+ throw new Error("Erasure claim requires a worker scope");
104
+ const owner = scope.kind === "org" ? scope.orgId : (await this.resolveOwner(id))?.org_id;
105
+ if (owner === undefined)
106
+ return;
107
+ return this.db
108
+ .selectFrom("data_erasure_requests")
109
+ .selectAll()
110
+ .where("org_id", owner === null ? "is" : "=", owner)
111
+ .where("id", "=", id)
112
+ .where("generation", "=", generation)
113
+ .where("stage", "!=", "done")
114
+ .where("due_at", "<=", sql `now()`)
115
+ .forUpdate()
116
+ .skipLocked()
117
+ .executeTakeFirst();
118
+ }
119
+ transition(row) {
120
+ return this.db
121
+ .updateTable("data_erasure_requests")
122
+ .where("id", "=", row.id)
123
+ .where("org_id", row.org_id === null ? "is" : "=", row.org_id)
124
+ .where("generation", "=", row.generation)
125
+ .where("stage", "!=", "done");
126
+ }
127
+ async advance(row, stage, blockedReason, dueAt, progress, scopeBoundaries) {
128
+ const next = await this.transition(row)
129
+ .set({
130
+ stage,
131
+ blocked_reason: blockedReason,
132
+ due_at: dueAt,
133
+ generation: row.generation + 1,
134
+ ...(scopeBoundaries !== undefined && { scope_boundaries: scopeBoundaries }),
135
+ ...(progress !== undefined && {
136
+ progress: progress === null ? null : JSON.stringify(progress),
137
+ }),
138
+ })
139
+ .returning("generation")
140
+ .executeTakeFirst();
141
+ if (next)
142
+ await oweErasure(this.outbox, row.id, next.generation, row.org_id, dueAt);
143
+ return !!next;
144
+ }
145
+ async complete(row) {
146
+ const completed = await this.transition(row)
147
+ .set({
148
+ stage: "done",
149
+ completed_at: sql `now()`,
150
+ due_at: sql `now()`,
151
+ target_id: null,
152
+ org_id: null,
153
+ progress: null,
154
+ blocked_reason: null,
155
+ generation: row.generation + 1,
156
+ })
157
+ .returning("id")
158
+ .executeTakeFirst();
159
+ return !!completed;
160
+ }
161
+ };
162
+ __decorate([
163
+ Transactional({ propagation: "mandatory" })
164
+ ], ErasureRequests.prototype, "enqueue", null);
165
+ __decorate([
166
+ Transactional({ propagation: "mandatory" })
167
+ ], ErasureRequests.prototype, "claim", null);
168
+ __decorate([
169
+ Transactional({ propagation: "mandatory" })
170
+ ], ErasureRequests.prototype, "advance", null);
171
+ __decorate([
172
+ Transactional({ propagation: "mandatory" })
173
+ ], ErasureRequests.prototype, "complete", null);
174
+ ErasureRequests = __decorate([
175
+ Injectable(),
176
+ __param(0, Inject(KernelDb)),
177
+ __param(1, Inject(TransactionHost)),
178
+ __param(2, Inject(OutboxService))
179
+ ], ErasureRequests);
180
+ export { ErasureRequests };
@@ -0,0 +1,19 @@
1
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { TransactionHost } from "../infra/database/transaction-host.js";
4
+ import { LockService } from "../infra/lock/lock.service.js";
5
+ import type { KernelLogger } from "../log.js";
6
+ import { ErasureRequests } from "./requests.js";
7
+ export declare class ErasureSweep {
8
+ private readonly db;
9
+ private readonly config;
10
+ readonly txHost: TransactionHost;
11
+ private readonly requests;
12
+ readonly lockService: LockService;
13
+ readonly log: KernelLogger;
14
+ constructor(db: KernelDb, config: KernelConfigService, txHost: TransactionHost, requests: ErasureRequests, lockService: LockService, log: KernelLogger);
15
+ run(): Promise<void>;
16
+ private enroll;
17
+ private recover;
18
+ private expireReceipts;
19
+ }
@@ -0,0 +1,130 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
15
+ import { TransactionHost } from "../infra/database/transaction-host.js";
16
+ import { Transactional } from "../infra/database/transactional.decorator.js";
17
+ import { LockService } from "../infra/lock/lock.service.js";
18
+ import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
19
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
20
+ import { ErasureRequests } from "./requests.js";
21
+ const PAGE = 32;
22
+ let ErasureSweep = class ErasureSweep {
23
+ db;
24
+ config;
25
+ txHost;
26
+ requests;
27
+ lockService;
28
+ log;
29
+ constructor(db, config, txHost, requests, lockService, log) {
30
+ this.db = db;
31
+ this.config = config;
32
+ this.txHost = txHost;
33
+ this.requests = requests;
34
+ this.lockService = lockService;
35
+ this.log = log;
36
+ }
37
+ async run() {
38
+ const settings = this.config.get().retention;
39
+ if (!settings.erasureEnabled || !settings.destructiveEnabled)
40
+ return;
41
+ // org-filter: deployment-wide lookup of old tombstones and due erasure requests.
42
+ const [orgs, stale] = await asPlatform("discover org tombstones and recover erasure work", () => Promise.all([
43
+ this.db
44
+ .selectFrom("orgs")
45
+ .select("id")
46
+ .where("deleted_at", "is not", null)
47
+ .where(({ not, exists, selectFrom }) => not(exists(selectFrom("data_erasure_requests")
48
+ .select("id")
49
+ .where("kind", "=", "org")
50
+ .whereRef("target_id", "=", "orgs.id"))))
51
+ .orderBy("deleted_at")
52
+ .orderBy("id")
53
+ .limit(PAGE)
54
+ .execute(),
55
+ this.db
56
+ .selectFrom("data_erasure_requests")
57
+ .select(["id", "org_id", "generation"])
58
+ .where("stage", "!=", "done")
59
+ .where("due_at", "<", sql `now() - interval '30 minutes'`)
60
+ .orderBy("due_at")
61
+ .orderBy("id")
62
+ .limit(PAGE)
63
+ .execute(),
64
+ ]));
65
+ for (const { id } of orgs)
66
+ await withOrgScope(id, () => this.enroll(id));
67
+ for (const { id, org_id: orgId, generation } of stale) {
68
+ if (orgId === null)
69
+ await asPlatform("recover an account erasure", () => this.recover(id, generation));
70
+ else
71
+ await withOrgScope(orgId, () => this.recover(id, generation));
72
+ }
73
+ await asPlatform("expire scrubbed erasure receipts", () => this.expireReceipts());
74
+ }
75
+ async enroll(orgId) {
76
+ const org = await this.db
77
+ .selectFrom("orgs")
78
+ .select("id")
79
+ .where("id", "=", orgId)
80
+ .where("deleted_at", "is not", null)
81
+ .forNoKeyUpdate()
82
+ .executeTakeFirst();
83
+ if (org)
84
+ await this.requests.enqueue("org", orgId);
85
+ }
86
+ async recover(id, generation) {
87
+ const request = await this.requests.claim(id, generation);
88
+ if (request && request.stage !== "done")
89
+ await this.requests.advance(request, request.stage, request.blocked_reason, new Date());
90
+ }
91
+ async expireReceipts() {
92
+ await this.db
93
+ .deleteFrom("data_erasure_requests")
94
+ .where("org_id", "is", null)
95
+ .where("id", "in", (query) => query
96
+ .selectFrom("data_erasure_requests")
97
+ .select("id")
98
+ .where("org_id", "is", null)
99
+ .where("stage", "=", "done")
100
+ .where("completed_at", "<", sql `now() - interval '30 days'`)
101
+ .orderBy("completed_at")
102
+ .orderBy("id")
103
+ .limit(PAGE)
104
+ .forUpdate()
105
+ .skipLocked())
106
+ .execute();
107
+ }
108
+ };
109
+ __decorate([
110
+ LockedCron("*/5 * * * *", { name: "data-erasure-sweep" })
111
+ ], ErasureSweep.prototype, "run", null);
112
+ __decorate([
113
+ Transactional()
114
+ ], ErasureSweep.prototype, "enroll", null);
115
+ __decorate([
116
+ Transactional()
117
+ ], ErasureSweep.prototype, "recover", null);
118
+ __decorate([
119
+ Transactional()
120
+ ], ErasureSweep.prototype, "expireReceipts", null);
121
+ ErasureSweep = __decorate([
122
+ Injectable(),
123
+ __param(0, Inject(KernelDb)),
124
+ __param(1, Inject(KernelConfigService)),
125
+ __param(2, Inject(TransactionHost)),
126
+ __param(3, Inject(ErasureRequests)),
127
+ __param(4, Inject(LockService)),
128
+ __param(5, Inject(KERNEL_LOGGER))
129
+ ], ErasureSweep);
130
+ export { ErasureSweep };
@@ -0,0 +1,17 @@
1
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
2
+ import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { AccountErasure } from "./account-worker.js";
4
+ import { OrgErasure } from "./org-worker.js";
5
+ import { ErasureRequests } from "./requests.js";
6
+ export declare class ErasureWorker {
7
+ private readonly config;
8
+ private readonly requests;
9
+ readonly txHost: TransactionHost;
10
+ private readonly orgs;
11
+ private readonly accounts;
12
+ constructor(config: KernelConfigService, requests: ErasureRequests, txHost: TransactionHost, orgs: OrgErasure, accounts: AccountErasure);
13
+ run(requestId: unknown, jobId: string | undefined): Promise<void>;
14
+ private recordFailure;
15
+ }
16
+ export declare class ErasureWorkerModule {
17
+ }
@@ -0,0 +1,110 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable, Module } from "@nestjs/common";
11
+ import { z } from "zod";
12
+ import { ConversationsModule } from "../conversations/conversations.module.js";
13
+ import { DevicesModule } from "../devices/devices.module.js";
14
+ import { BlobObjectsModule } from "../files/blob-objects.js";
15
+ import { BlobSweepModule } from "../files/blob-sweep.job.js";
16
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
17
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
18
+ import { TransactionHost } from "../infra/database/transaction-host.js";
19
+ import { Transactional } from "../infra/database/transactional.decorator.js";
20
+ import { OrgLockModule } from "../orgs/org-lock.js";
21
+ import { RetentionReportObligationsModule } from "../retention/report-obligations.js";
22
+ import { StorageModule } from "../storage/storage.module.js";
23
+ import { AccountErasure } from "./account-worker.js";
24
+ import { AccountDeviceCleanup } from "./device-cleanup.js";
25
+ import { ErasureModule } from "./erasure.module.js";
26
+ import { parseErasureGeneration } from "./jobs.js";
27
+ import { OrgErasure } from "./org-worker.js";
28
+ import { ErasureRequests } from "./requests.js";
29
+ let ErasureWorker = class ErasureWorker {
30
+ config;
31
+ requests;
32
+ txHost;
33
+ orgs;
34
+ accounts;
35
+ constructor(config, requests, txHost, orgs, accounts) {
36
+ this.config = config;
37
+ this.requests = requests;
38
+ this.txHost = txHost;
39
+ this.orgs = orgs;
40
+ this.accounts = accounts;
41
+ }
42
+ async run(requestId, jobId) {
43
+ const settings = this.config.get().retention;
44
+ if (!settings.erasureEnabled || !settings.destructiveEnabled)
45
+ return;
46
+ const id = z.uuid().safeParse(requestId);
47
+ if (!id.success)
48
+ return;
49
+ const generation = parseErasureGeneration(id.data, jobId);
50
+ if (generation === undefined)
51
+ return;
52
+ const owner = await this.requests.resolveOwner(id.data);
53
+ if (!owner)
54
+ return;
55
+ const orgId = owner.org_id;
56
+ const process = async () => {
57
+ try {
58
+ if (orgId === null)
59
+ await this.accounts.run(id.data, generation);
60
+ else
61
+ await this.orgs.run(id.data, generation, orgId);
62
+ }
63
+ catch (error) {
64
+ await this.recordFailure(id.data, generation);
65
+ throw error;
66
+ }
67
+ };
68
+ if (orgId === null)
69
+ await asPlatform("process a deployment account erasure request", process);
70
+ else
71
+ await withOrgScope(orgId, process);
72
+ }
73
+ async recordFailure(id, generation) {
74
+ const work = await this.requests.claim(id, generation);
75
+ if (!work || work.stage === "done")
76
+ return;
77
+ await this.requests.advance(work, work.stage, "processing-failed", new Date(Date.now() + 300_000));
78
+ }
79
+ };
80
+ __decorate([
81
+ Transactional()
82
+ ], ErasureWorker.prototype, "recordFailure", null);
83
+ ErasureWorker = __decorate([
84
+ Injectable(),
85
+ __param(0, Inject(KernelConfigService)),
86
+ __param(1, Inject(ErasureRequests)),
87
+ __param(2, Inject(TransactionHost)),
88
+ __param(3, Inject(OrgErasure)),
89
+ __param(4, Inject(AccountErasure))
90
+ ], ErasureWorker);
91
+ export { ErasureWorker };
92
+ let ErasureWorkerModule = class ErasureWorkerModule {
93
+ };
94
+ ErasureWorkerModule = __decorate([
95
+ Module({
96
+ imports: [
97
+ ErasureModule,
98
+ DevicesModule,
99
+ ConversationsModule,
100
+ BlobObjectsModule,
101
+ BlobSweepModule,
102
+ RetentionReportObligationsModule,
103
+ OrgLockModule,
104
+ StorageModule,
105
+ ],
106
+ providers: [ErasureWorker, OrgErasure, AccountErasure, AccountDeviceCleanup],
107
+ exports: [ErasureWorker],
108
+ })
109
+ ], ErasureWorkerModule);
110
+ export { ErasureWorkerModule };
package/dist/errors.d.ts CHANGED
@@ -71,6 +71,7 @@ export declare const ERROR_CODES: {
71
71
  readonly "org.security_ceiling_not_allowed": 400;
72
72
  readonly "org.security_widening_not_allowed": 403;
73
73
  readonly "org.security_revision_conflict": 409;
74
+ readonly "retention.confirmation_required": 409;
74
75
  readonly "org.security_confirmation_required": 409;
75
76
  readonly "org.permission_profile_not_allowed": 400;
76
77
  /** The org's default device provider names an extension that is not a `device-provider@1` provider on in the org. */
@@ -740,6 +741,9 @@ export declare const ERROR_CODES: {
740
741
  readonly "model.provider_not_found": 404;
741
742
  /** An extension's `ctx.models.embed` call was denied by a `model.request` policy hook. */
742
743
  readonly "model.hook_denied": 403;
744
+ readonly "model.budget_exceeded": 429;
745
+ readonly "model.budget_currency_mismatch": 409;
746
+ readonly "model.budget_unavailable": 503;
743
747
  readonly "eval.result_not_found": 404;
744
748
  /**
745
749
  * A push registration names a provider that is not loaded or whose credentials do not cover
package/dist/errors.js CHANGED
@@ -71,6 +71,7 @@ export const ERROR_CODES = {
71
71
  "org.security_ceiling_not_allowed": 400,
72
72
  "org.security_widening_not_allowed": 403,
73
73
  "org.security_revision_conflict": 409,
74
+ "retention.confirmation_required": 409,
74
75
  "org.security_confirmation_required": 409,
75
76
  "org.permission_profile_not_allowed": 400,
76
77
  /** The org's default device provider names an extension that is not a `device-provider@1` provider on in the org. */
@@ -740,6 +741,9 @@ export const ERROR_CODES = {
740
741
  "model.provider_not_found": 404,
741
742
  /** An extension's `ctx.models.embed` call was denied by a `model.request` policy hook. */
742
743
  "model.hook_denied": 403,
744
+ "model.budget_exceeded": 429,
745
+ "model.budget_currency_mismatch": 409,
746
+ "model.budget_unavailable": 503,
743
747
  "eval.result_not_found": 404,
744
748
  /**
745
749
  * A push registration names a provider that is not loaded or whose credentials do not cover
@@ -1,4 +1,5 @@
1
1
  import { type ModelUsage } from "@capybara-hq/plugin-sdk";
2
+ import { type ModelBudgetErrorDetail, type ModelBudgetSite } from "../models/budget-admission.js";
2
3
  import { type ModelPurposesService } from "../models/purposes.js";
3
4
  import type { HookDenial, HookRunner } from "../runtime/hook-calls.js";
4
5
  import { textTokens } from "./plan.js";
@@ -30,10 +31,13 @@ export interface JudgeVerdict {
30
31
  * `tokens` 是应计入预算的用量(解析失败 = 实际用量;请求发出后失败 = 估算;发出之前失败 = 0)。
31
32
  */
32
33
  export interface JudgeFailure {
34
+ message?: string;
35
+ budget?: ModelBudgetErrorDetail;
33
36
  error: string;
34
37
  provider?: string;
35
38
  model?: string;
36
39
  tokens: number;
40
+ usage?: ModelUsage;
37
41
  }
38
42
  /** 解析评委的回复:接受纯 JSON、带围栏的 JSON;verdict / score(1–5 的整数)/ reason(字符串)都要合法。 */
39
43
  export declare function parseVerdict(text: string): Omit<JudgeVerdict, "provider" | "model" | "usage"> | null;
@@ -48,6 +52,7 @@ export declare function judge(d: {
48
52
  hooks?: HookRunner | undefined;
49
53
  onDenied?: (verdict: HookDenial) => Promise<void>;
50
54
  maxOutputTokens?: number;
55
+ budgetSite?: ModelBudgetSite;
51
56
  }, orgId: string, input: {
52
57
  userRequest: string;
53
58
  baseline: string;
@@ -1,6 +1,7 @@
1
1
  import { isModelError } from "@capybara-hq/plugin-sdk";
2
2
  import { ApiError } from "../errors.js";
3
3
  import { ExtensionUnloadedError } from "../extensions/inflight.js";
4
+ import { ModelBudgetRefused, } from "../models/budget-admission.js";
4
5
  import { PurposeAttemptError } from "../models/purposes.js";
5
6
  import { usageTokens } from "./budget.js";
6
7
  import { textTokens } from "./plan.js";
@@ -119,7 +120,11 @@ export async function judge(d, orgId, input, signal) {
119
120
  tools: [],
120
121
  toolChoice: "none",
121
122
  maxOutputTokens: d.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
122
- }, signal, { hooks: d.hooks, ...(d.onDenied && { onDenied: d.onDenied }) });
123
+ }, signal, {
124
+ hooks: d.hooks,
125
+ ...(d.budgetSite && { budgetSite: d.budgetSite }),
126
+ ...(d.onDenied && { onDenied: d.onDenied }),
127
+ });
123
128
  }
124
129
  catch (err) {
125
130
  // 中止(停机):交给调用方(任务回到队列);已发出的请求由调用方按 PurposeAttemptError 的估算计费
@@ -131,6 +136,15 @@ export async function judge(d, orgId, input, signal) {
131
136
  provider: err.provider,
132
137
  model: err.model,
133
138
  tokens: err.tokens,
139
+ usage: err.usage,
140
+ };
141
+ }
142
+ if (err instanceof ModelBudgetRefused) {
143
+ return {
144
+ error: err.code,
145
+ message: err.message,
146
+ ...(err.budgetDetail && { budget: err.budgetDetail }),
147
+ tokens: 0,
134
148
  };
135
149
  }
136
150
  return { error: failureCode(err), tokens: 0 };
@@ -143,6 +157,7 @@ export async function judge(d, orgId, input, signal) {
143
157
  provider: out.provider,
144
158
  model: out.model,
145
159
  tokens: usageTokens(out.usage),
160
+ usage: out.usage,
146
161
  };
147
162
  }
148
163
  return { ...v, provider: out.provider, model: out.model, usage: out.usage };
@@ -343,6 +343,8 @@ export async function replayRun(d, s, candidate, evalRunId, signal) {
343
343
  .where("org_id", "=", s.orgId)
344
344
  .executeTakeFirstOrThrow();
345
345
  const accountId = run.created_by;
346
+ if (accountId === null)
347
+ throw new ApiError("forbidden", "Replay requires an existing evaluation run creator");
346
348
  const R = start.seq;
347
349
  const seeds = s.events.filter((e) => e.seq < R);
348
350
  // 原运行开始时会话的 consumed_seq:此前最近一次正常结束记下的位置(失败 / 中止的终态不带位置,取不到时为 0)
@@ -628,7 +630,16 @@ export async function replayRun(d, s, candidate, evalRunId, signal) {
628
630
  runId,
629
631
  status: "failed",
630
632
  consumed: null,
631
- event: { type: "run_failed", payload: { error: { code: err.code, message: err.message } } },
633
+ event: {
634
+ type: "run_failed",
635
+ payload: {
636
+ error: {
637
+ code: err.code,
638
+ message: err.message,
639
+ ...(err.budgetDetail && { budget: err.budgetDetail }),
640
+ },
641
+ },
642
+ },
632
643
  })
633
644
  .catch((x) => d.log.warn("cannot finish eval replay run", { runId, err: x }));
634
645
  await Promise.allSettled([...charges]);
@@ -2,6 +2,7 @@ import { type ContentBlock, type ModelUsage, type ParamValue, type StopReason }
2
2
  import type { AgentDefinition, ModelRef } from "../agents/definition.js";
3
3
  import { type Selection } from "../conversations/selection.js";
4
4
  import type { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
+ import type { ModelBudgetSite } from "../models/budget-admission.js";
5
6
  import type { CompactionSettingsService } from "../runtime/compaction-settings.service.js";
6
7
  import type { HookRunner } from "../runtime/hook-calls.js";
7
8
  import { type MediaSourceDeps } from "../runtime/model-call.js";
@@ -92,8 +93,9 @@ subagent?: SubagentSource): ResolvedCandidate;
92
93
  */
93
94
  export declare class ReplayAttemptError extends Error {
94
95
  readonly cause: unknown;
95
- readonly tokens: number;
96
- constructor(cause: unknown, tokens: number);
96
+ readonly usage: ModelUsage;
97
+ get tokens(): number;
98
+ constructor(cause: unknown, inputTokens: number, outputTokens?: number);
97
99
  }
98
100
  /**
99
101
  * 回放一步:基线取快照里该步的回复与用量;候选请求 = `reconstructRequest`(候选未变时按基线还原,
@@ -108,7 +110,7 @@ export declare function replayStep(d: StepReplayDeps, s: CaseSnapshot, call: {
108
110
  seq: number;
109
111
  step: number;
110
112
  assistantSeq: number;
111
- }, candidate: ResolvedCandidate, signal: AbortSignal): Promise<{
113
+ }, candidate: ResolvedCandidate, signal: AbortSignal, budgetSite?: ModelBudgetSite): Promise<{
112
114
  baseline: {
113
115
  content: ContentBlock[];
114
116
  stopReason: StopReason;
@@ -93,11 +93,14 @@ function withInstructions(def, instructions) {
93
93
  */
94
94
  export class ReplayAttemptError extends Error {
95
95
  cause;
96
- tokens;
97
- constructor(cause, tokens) {
96
+ usage;
97
+ get tokens() {
98
+ return this.usage.inputTokens + this.usage.outputTokens;
99
+ }
100
+ constructor(cause, inputTokens, outputTokens = 0) {
98
101
  super(cause instanceof Error ? cause.message : String(cause), { cause });
99
102
  this.cause = cause;
100
- this.tokens = tokens;
103
+ this.usage = { inputTokens, outputTokens, cacheReadTokens: 0, cacheWriteTokens: 0 };
101
104
  this.name = "ReplayAttemptError";
102
105
  }
103
106
  }
@@ -131,7 +134,7 @@ function baselineOf(s, call) {
131
134
  * config and disabled lists: a model disabled there is `agent.model_unavailable`, spec B §5.3).
132
135
  * 不另设单次请求的墙钟时限:与运行时一样只有流空闲看门狗(`streamIdleTimeoutMs` / `runtime.streamIdleMs`)。
133
136
  */
134
- export async function replayStep(d, s, call, candidate, signal) {
137
+ export async function replayStep(d, s, call, candidate, signal, budgetSite) {
135
138
  const baseline = baselineOf(s, call);
136
139
  const { provider, info } = await d.registry.resolve(s.orgId, candidate.model);
137
140
  // the reserve the run's hard fit guard used (a candidate recomputes the fit against its window)
@@ -170,6 +173,7 @@ export async function replayStep(d, s, call, candidate, signal) {
170
173
  orgId: s.orgId,
171
174
  purpose: "eval",
172
175
  hooks: d.hooks,
176
+ budgetSite,
173
177
  step: call.step,
174
178
  attempt: 1,
175
179
  }, signal);
@@ -185,7 +189,7 @@ export async function replayStep(d, s, call, candidate, signal) {
185
189
  // 请求已发出:供应商流里不带中途用量(model-provider@2 只在 message_complete 给 usage),
186
190
  // 按估算计费——输入 = 与运行时同一个估算器,输出 = 已流出的字符数 / 4
187
191
  const input = estimateTokens(request.messages, request.system, request.tools, mediaTokens);
188
- throw new ReplayAttemptError(err, input + Math.ceil(streamedChars / 4));
192
+ throw new ReplayAttemptError(err, input, Math.ceil(streamedChars / 4));
189
193
  }
190
194
  return {
191
195
  baseline,