@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.
- package/dist/admin/account-erasures.d.ts +37 -0
- package/dist/admin/account-erasures.js +119 -0
- package/dist/admin/admin.controller.d.ts +35 -2
- package/dist/admin/admin.controller.js +75 -18
- package/dist/admin/admin.module.js +10 -0
- package/dist/admin/admin.schemas.d.ts +51 -0
- package/dist/admin/admin.schemas.js +20 -0
- package/dist/admin/erasure-dispositions.d.ts +23 -0
- package/dist/admin/erasure-dispositions.js +76 -0
- package/dist/admin/health.service.d.ts +6 -0
- package/dist/admin/health.service.js +27 -1
- package/dist/admin/usage.service.d.ts +5 -0
- package/dist/admin/usage.service.js +21 -2
- package/dist/agents/agents.service.d.ts +1 -1
- package/dist/channels/connections.service.d.ts +1 -1
- package/dist/client/client-reports.service.js +12 -0
- package/dist/config/schema.d.ts +8 -1
- package/dist/config/schema.js +43 -1
- package/dist/conversations/conversations.service.d.ts +9 -1
- package/dist/conversations/conversations.service.js +112 -15
- package/dist/conversations/event-log.d.ts +2 -0
- package/dist/conversations/event-log.js +77 -0
- package/dist/conversations/events.d.ts +11 -0
- package/dist/conversations/events.js +13 -1
- package/dist/conversations/prompt-suggestions.js +4 -0
- package/dist/conversations/titles.js +3 -2
- package/dist/db/kernel-schema.d.ts +71 -8
- package/dist/devices/devices.service.d.ts +13 -1
- package/dist/devices/devices.service.js +122 -9
- package/dist/erasure/account-batches.d.ts +9 -0
- package/dist/erasure/account-batches.js +567 -0
- package/dist/erasure/account-files.d.ts +34 -0
- package/dist/erasure/account-files.js +217 -0
- package/dist/erasure/account-residual.d.ts +15 -0
- package/dist/erasure/account-residual.js +149 -0
- package/dist/erasure/account-worker.d.ts +32 -0
- package/dist/erasure/account-worker.js +392 -0
- package/dist/erasure/device-cleanup.d.ts +23 -0
- package/dist/erasure/device-cleanup.js +221 -0
- package/dist/erasure/erasure.module.d.ts +2 -0
- package/dist/erasure/erasure.module.js +14 -0
- package/dist/erasure/external-evidence.d.ts +4 -0
- package/dist/erasure/external-evidence.js +28 -0
- package/dist/erasure/jobs.d.ts +5 -0
- package/dist/erasure/jobs.js +20 -0
- package/dist/erasure/org-batches.d.ts +11 -0
- package/dist/erasure/org-batches.js +159 -0
- package/dist/erasure/org-catalog.d.ts +2 -0
- package/dist/erasure/org-catalog.js +34 -0
- package/dist/erasure/org-rules.d.ts +14 -0
- package/dist/erasure/org-rules.js +227 -0
- package/dist/erasure/org-worker.d.ts +38 -0
- package/dist/erasure/org-worker.js +501 -0
- package/dist/erasure/requests.d.ts +61 -0
- package/dist/erasure/requests.js +180 -0
- package/dist/erasure/sweep.job.d.ts +19 -0
- package/dist/erasure/sweep.job.js +130 -0
- package/dist/erasure/worker.d.ts +17 -0
- package/dist/erasure/worker.js +110 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.js +4 -0
- package/dist/evals/judge.d.ts +5 -0
- package/dist/evals/judge.js +16 -1
- package/dist/evals/run-replay.js +12 -1
- package/dist/evals/step-replay.d.ts +5 -3
- package/dist/evals/step-replay.js +9 -5
- package/dist/evals/worker.d.ts +2 -0
- package/dist/evals/worker.js +60 -16
- package/dist/files/blob-objects.d.ts +7 -3
- package/dist/files/blob-objects.js +39 -22
- package/dist/files/blob-sweep.job.d.ts +11 -0
- package/dist/files/blob-sweep.job.js +67 -6
- package/dist/http/api.module.js +5 -1
- package/dist/identity/accounts.js +3 -0
- package/dist/identity/api-tokens.js +5 -0
- package/dist/identity/auth.guard.d.ts +1 -0
- package/dist/identity/auth.guard.js +1 -0
- package/dist/identity/erasure-admission.d.ts +3 -0
- package/dist/identity/erasure-admission.js +14 -0
- package/dist/identity/external.js +5 -0
- package/dist/identity/sessions.js +5 -0
- package/dist/identity/settings.d.ts +86 -1
- package/dist/identity/settings.js +38 -4
- package/dist/infra/config/kernel-config.service.js +1 -0
- package/dist/infra/metrics/kernel-metrics.d.ts +18 -0
- package/dist/infra/metrics/kernel-metrics.js +54 -0
- package/dist/infra/metrics/operational-metrics.d.ts +31 -0
- package/dist/infra/metrics/operational-metrics.js +188 -0
- package/dist/infra/outbox/registry.d.ts +23 -0
- package/dist/infra/outbox/registry.js +12 -0
- package/dist/infra/throttler/credential-throttler.js +8 -1
- package/dist/infra/throttler/named-throttlers.d.ts +6 -0
- package/dist/infra/throttler/named-throttlers.js +6 -0
- package/dist/infra/throttler/principal-throttler.guard.d.ts +10 -0
- package/dist/infra/throttler/principal-throttler.guard.js +50 -0
- package/dist/infra/throttler/redis-throttler-storage.d.ts +1 -0
- package/dist/infra/throttler/redis-throttler-storage.js +27 -5
- package/dist/infra/throttler/throttler.guard.d.ts +2 -3
- package/dist/infra/throttler/throttler.guard.js +2 -3
- package/dist/infra/throttler/throttler.module.js +3 -2
- package/dist/models/budget-admission.d.ts +31 -0
- package/dist/models/budget-admission.js +149 -0
- package/dist/models/budget-counters.d.ts +28 -0
- package/dist/models/budget-counters.js +117 -0
- package/dist/models/budget-policy.d.ts +88 -0
- package/dist/models/budget-policy.js +78 -0
- package/dist/models/embeddings.js +13 -2
- package/dist/models/images.js +12 -2
- package/dist/models/purposes.d.ts +5 -2
- package/dist/models/purposes.js +9 -5
- package/dist/orgs/invitations.service.d.ts +1 -1
- package/dist/orgs/members.service.d.ts +28 -1
- package/dist/orgs/members.service.js +74 -11
- package/dist/orgs/offboarding.js +4 -6
- package/dist/orgs/org-owner.d.ts +2 -0
- package/dist/orgs/org-owner.js +21 -6
- package/dist/orgs/orgs.controller.d.ts +22 -0
- package/dist/orgs/orgs.controller.js +24 -0
- package/dist/orgs/orgs.module.js +4 -0
- package/dist/orgs/orgs.schemas.js +7 -0
- package/dist/orgs/orgs.service.d.ts +5 -1
- package/dist/orgs/orgs.service.js +28 -3
- package/dist/orgs/settings.controller.js +6 -1
- package/dist/orgs/settings.service.d.ts +58 -1
- package/dist/orgs/settings.service.js +74 -9
- package/dist/platform/exclusions.js +20 -1
- package/dist/platform/ops/accounts.ops.js +58 -1
- package/dist/platform/ops/admin.ops.js +13 -5
- package/dist/platform/ops/org-settings.ops.js +11 -4
- package/dist/platform/ops/orgs.ops.js +28 -0
- package/dist/platform/ops/retention.d.ts +16 -0
- package/dist/platform/ops/retention.js +21 -0
- package/dist/retention/jobs.d.ts +21 -0
- package/dist/retention/jobs.js +48 -0
- package/dist/retention/policy.d.ts +70 -0
- package/dist/retention/policy.js +103 -0
- package/dist/retention/purge-batch.d.ts +17 -0
- package/dist/retention/purge-batch.js +355 -0
- package/dist/retention/report-obligations.d.ts +12 -0
- package/dist/retention/report-obligations.js +71 -0
- package/dist/retention/sweep.job.d.ts +17 -0
- package/dist/retention/sweep.job.js +95 -0
- package/dist/retention/worker.d.ts +29 -0
- package/dist/retention/worker.js +306 -0
- package/dist/roles/worker.module.js +12 -2
- package/dist/runtime/maintenance.d.ts +5 -1
- package/dist/runtime/maintenance.js +20 -2
- package/dist/runtime/model-call.d.ts +3 -1
- package/dist/runtime/model-call.js +25 -3
- package/dist/runtime/providers.d.ts +7 -2
- package/dist/runtime/providers.js +76 -10
- package/dist/runtime/quota.d.ts +12 -12
- package/dist/runtime/quota.js +42 -37
- package/dist/runtime/run-finish.js +2 -0
- package/dist/runtime/run-principal.d.ts +9 -0
- package/dist/runtime/run-principal.js +18 -0
- package/dist/runtime/run-worker.js +48 -10
- package/dist/runtime/usage-report-jobs.d.ts +4 -1
- package/dist/runtime/usage-report-jobs.js +36 -13
- package/dist/runtime/usage-report.d.ts +5 -3
- package/dist/runtime/usage-report.js +37 -19
- package/dist/sandbox/review/classifier.d.ts +2 -2
- package/dist/sandbox/review/classifier.js +6 -2
- package/dist/sandbox/sandbox.service.js +18 -7
- package/dist/storage/purge.js +5 -1
- package/dist/storage/storage.service.d.ts +17 -1
- package/dist/storage/storage.service.js +75 -4
- package/dist/tools/builtins/vision/read-image.js +3 -0
- package/dist/tools/builtins/web/extract.js +3 -0
- package/dist/tools/pipeline.js +5 -1
- package/package.json +3 -1
- package/src/migrations/0216_model_budget_counters.sql +24 -0
- package/src/migrations/0217_retention.sql +44 -0
- package/src/migrations/0218_data_erasure.sql +41 -0
|
@@ -0,0 +1,306 @@
|
|
|
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 { sql } from "kysely";
|
|
12
|
+
import { ConversationsModule } from "../conversations/conversations.module.js";
|
|
13
|
+
import { ConversationsService } from "../conversations/conversations.service.js";
|
|
14
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
15
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
16
|
+
import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
|
|
17
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
18
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
19
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
20
|
+
import { modelUsageJobId, USAGE_REPORT_QUEUE } from "../runtime/usage-report-jobs.js";
|
|
21
|
+
import { enqueueRetention, recordRetentionLoss, retentionJobId } from "./jobs.js";
|
|
22
|
+
import { readOrgRetention, readPlatformRetention } from "./policy.js";
|
|
23
|
+
import { prepareConversationBatch, purgeConversationBatch } from "./purge-batch.js";
|
|
24
|
+
import { RetentionReportObligations, RetentionReportObligationsModule, } from "./report-obligations.js";
|
|
25
|
+
const BATCH = 32;
|
|
26
|
+
// An empty cursor marks a completed stream while its sibling finishes the same scan.
|
|
27
|
+
const END = "";
|
|
28
|
+
const DAY = 86_400_000;
|
|
29
|
+
const REVISIT = 15 * 60_000;
|
|
30
|
+
const cutoff = (days) => new Date(Date.now() - days * DAY);
|
|
31
|
+
let RetentionWorker = class RetentionWorker {
|
|
32
|
+
db;
|
|
33
|
+
txHost;
|
|
34
|
+
outbox;
|
|
35
|
+
config;
|
|
36
|
+
conversations;
|
|
37
|
+
reports;
|
|
38
|
+
constructor(db, txHost, outbox, config, conversations, reports) {
|
|
39
|
+
this.db = db;
|
|
40
|
+
this.txHost = txHost;
|
|
41
|
+
this.outbox = outbox;
|
|
42
|
+
this.config = config;
|
|
43
|
+
this.conversations = conversations;
|
|
44
|
+
this.reports = reports;
|
|
45
|
+
}
|
|
46
|
+
async run(workId, jobId) {
|
|
47
|
+
if (!this.config.get().retention.destructiveEnabled)
|
|
48
|
+
return;
|
|
49
|
+
// org-filter: deployment-wide resolution of the owner of an opaque maintenance work ID
|
|
50
|
+
const owner = await asPlatform("resolve retention work owner", () => this.db
|
|
51
|
+
.selectFrom("retention_work")
|
|
52
|
+
.select("org_id")
|
|
53
|
+
.where("id", "=", workId)
|
|
54
|
+
.executeTakeFirst());
|
|
55
|
+
if (!owner)
|
|
56
|
+
return;
|
|
57
|
+
const handle = async () => {
|
|
58
|
+
const work = await this.row(workId, owner.org_id).selectAll().executeTakeFirst();
|
|
59
|
+
if (!work || work.state === "done" || retentionJobId(work.id, work.generation) !== jobId)
|
|
60
|
+
return;
|
|
61
|
+
try {
|
|
62
|
+
await this.dispatch(work);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
await this.recordFailure(work);
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
if (owner.org_id === null)
|
|
70
|
+
await asPlatform("sweep platform audit detail", handle);
|
|
71
|
+
else
|
|
72
|
+
await withOrgScope(owner.org_id, handle);
|
|
73
|
+
}
|
|
74
|
+
async recordFailure(work) {
|
|
75
|
+
await this.db
|
|
76
|
+
.updateTable("retention_work")
|
|
77
|
+
.set({ state: "blocked", blocked_reason: "processing_failed" })
|
|
78
|
+
.where("id", "=", work.id)
|
|
79
|
+
.where("org_id", work.org_id === null ? "is" : "=", work.org_id)
|
|
80
|
+
.where("generation", "=", work.generation)
|
|
81
|
+
.where("state", "!=", "done")
|
|
82
|
+
.execute();
|
|
83
|
+
}
|
|
84
|
+
async dispatch(work) {
|
|
85
|
+
if (work.kind === "org-scan" && work.org_id !== null) {
|
|
86
|
+
await this.scan(work, work.org_id);
|
|
87
|
+
}
|
|
88
|
+
else if (work.kind === "platform-audit") {
|
|
89
|
+
await this.platformAudit(work);
|
|
90
|
+
}
|
|
91
|
+
else if (work.org_id !== null && work.kind === "purge") {
|
|
92
|
+
const target = { orgId: work.org_id, conversationId: work.target };
|
|
93
|
+
const eligible = await this.root(target).select("deleted_at").executeTakeFirst();
|
|
94
|
+
const prepared = eligible?.deleted_at && eligible.deleted_at <= cutoff(30)
|
|
95
|
+
? await prepareConversationBatch(this.db.db, target, this.reports)
|
|
96
|
+
: undefined;
|
|
97
|
+
await this.purge(work, target, prepared);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
row(id, org) {
|
|
101
|
+
return this.db
|
|
102
|
+
.selectFrom("retention_work")
|
|
103
|
+
.where("id", "=", id)
|
|
104
|
+
.where("org_id", org === null ? "is" : "=", org);
|
|
105
|
+
}
|
|
106
|
+
async claim(work) {
|
|
107
|
+
if (!this.config.get().retention.destructiveEnabled)
|
|
108
|
+
return false;
|
|
109
|
+
return this.row(work.id, work.org_id)
|
|
110
|
+
.select("id")
|
|
111
|
+
.where("generation", "=", work.generation)
|
|
112
|
+
.where("state", "!=", "done")
|
|
113
|
+
.forUpdate()
|
|
114
|
+
.skipLocked()
|
|
115
|
+
.executeTakeFirst();
|
|
116
|
+
}
|
|
117
|
+
root({ orgId, conversationId }) {
|
|
118
|
+
return this.db
|
|
119
|
+
.selectFrom("conversations")
|
|
120
|
+
.where("org_id", "=", orgId)
|
|
121
|
+
.where("id", "=", conversationId)
|
|
122
|
+
.where("parent_conversation_id", "is", null);
|
|
123
|
+
}
|
|
124
|
+
async advance(work, state, delay = 0, cursors, reason = null) {
|
|
125
|
+
const due = new Date(Date.now() + delay);
|
|
126
|
+
const row = await this.db
|
|
127
|
+
.updateTable("retention_work")
|
|
128
|
+
.set({
|
|
129
|
+
generation: work.generation + 1,
|
|
130
|
+
state,
|
|
131
|
+
due_at: due,
|
|
132
|
+
blocked_reason: reason,
|
|
133
|
+
...cursors,
|
|
134
|
+
})
|
|
135
|
+
.where("id", "=", work.id)
|
|
136
|
+
.where("org_id", work.org_id === null ? "is" : "=", work.org_id)
|
|
137
|
+
.returning(["id", "org_id", "generation"])
|
|
138
|
+
.executeTakeFirstOrThrow();
|
|
139
|
+
if (state !== "done")
|
|
140
|
+
await enqueueRetention(this.outbox, row, due);
|
|
141
|
+
}
|
|
142
|
+
async purge(work, target, prepared) {
|
|
143
|
+
if (!(await this.claim(work)))
|
|
144
|
+
return;
|
|
145
|
+
const root = await this.root(target)
|
|
146
|
+
.select(["deleted_at", sql `now()`.as("now")])
|
|
147
|
+
.forUpdate()
|
|
148
|
+
.executeTakeFirst();
|
|
149
|
+
if (!root)
|
|
150
|
+
return this.advance(work, "done");
|
|
151
|
+
if (!root.deleted_at)
|
|
152
|
+
return this.advance(work, "blocked", REVISIT, undefined, "live_conversation");
|
|
153
|
+
const hold = root.deleted_at.getTime() + 30 * DAY - root.now.getTime();
|
|
154
|
+
if (hold > 0)
|
|
155
|
+
return this.advance(work, "blocked", hold, undefined, "recovery_hold");
|
|
156
|
+
// Any still-owed device notice belongs to its delivery sweep. A stopped or unreachable
|
|
157
|
+
// device can still owe an acknowledgement after the service restore window has elapsed.
|
|
158
|
+
const blockers = await sql `
|
|
159
|
+
WITH RECURSIVE tree(id,deleted_at) AS (
|
|
160
|
+
SELECT id,deleted_at FROM capybara.conversations WHERE id=${target.conversationId} AND org_id=${target.orgId}
|
|
161
|
+
UNION
|
|
162
|
+
SELECT c.id,c.deleted_at FROM capybara.conversations c JOIN tree t ON c.parent_conversation_id=t.id
|
|
163
|
+
WHERE c.org_id=${target.orgId}
|
|
164
|
+
) SELECT EXISTS (SELECT 1 FROM tree t WHERE t.deleted_at>now()-interval '30 days'
|
|
165
|
+
OR EXISTS (SELECT 1 FROM capybara.device_conversation_notices n WHERE n.org_id=${target.orgId} AND n.conversation_id=t.id)
|
|
166
|
+
OR EXISTS (SELECT 1 FROM capybara.runs r WHERE r.conversation_id=t.id AND r.status IN ('queued','running','waiting'))
|
|
167
|
+
) AS blocked`.execute(this.db.db);
|
|
168
|
+
if (blockers.rows[0]?.blocked || !prepared)
|
|
169
|
+
return this.advance(work, "blocked", REVISIT, undefined, "tree_obligation");
|
|
170
|
+
const result = await purgeConversationBatch(this.db.db, target, prepared);
|
|
171
|
+
await this.advance(work, result === "more" ? "ready" : result, result === "blocked" ? REVISIT : 0, undefined, result === "blocked" ? "dependent_cleanup" : null);
|
|
172
|
+
}
|
|
173
|
+
async scan(work, orgId) {
|
|
174
|
+
const policy = await readOrgRetention(this.db.db, orgId);
|
|
175
|
+
let candidates = this.db
|
|
176
|
+
.selectFrom("conversations")
|
|
177
|
+
.select("id")
|
|
178
|
+
.where("org_id", "=", orgId)
|
|
179
|
+
.where("deleted_at", "is", null)
|
|
180
|
+
.where("kind", "=", "chat")
|
|
181
|
+
.where("parent_conversation_id", "is", null);
|
|
182
|
+
if (work.cursor_id)
|
|
183
|
+
candidates = candidates.where("id", ">", work.cursor_id);
|
|
184
|
+
const ageDays = policy.conversationDays;
|
|
185
|
+
const roots = work.cursor_id === END || ageDays === null
|
|
186
|
+
? []
|
|
187
|
+
: await candidates
|
|
188
|
+
.where("updated_at", "<", cutoff(ageDays))
|
|
189
|
+
.orderBy("id")
|
|
190
|
+
.limit(BATCH)
|
|
191
|
+
.execute();
|
|
192
|
+
if (ageDays !== null) {
|
|
193
|
+
for (const root of roots) {
|
|
194
|
+
if (!this.config.get().retention.destructiveEnabled)
|
|
195
|
+
return;
|
|
196
|
+
await this.conversations.expireForRetention(orgId, root.id, cutoff(ageDays), async () => Boolean(await this.claim(work)));
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
let usage = this.db
|
|
200
|
+
.selectFrom("model_usage")
|
|
201
|
+
.select("id")
|
|
202
|
+
.where("org_id", "=", orgId)
|
|
203
|
+
.where((eb) => eb.or([eb("reported_at", "is not", null), eb("report_failed_at", "is", null)]));
|
|
204
|
+
if (work.usage_cursor)
|
|
205
|
+
usage = usage.where("id", ">", work.usage_cursor);
|
|
206
|
+
const rows = policy.usageDays === null || work.usage_cursor === END
|
|
207
|
+
? []
|
|
208
|
+
: await usage
|
|
209
|
+
.where("occurred_at", "<", cutoff(policy.usageDays))
|
|
210
|
+
.orderBy("id")
|
|
211
|
+
.limit(BATCH)
|
|
212
|
+
.execute();
|
|
213
|
+
const clear = [];
|
|
214
|
+
for (const row of rows) {
|
|
215
|
+
if (await this.reports.clear(orgId, [modelUsageJobId(row.id)]))
|
|
216
|
+
clear.push(row.id);
|
|
217
|
+
}
|
|
218
|
+
await this.scanBatch(work, orgId, clear, {
|
|
219
|
+
cursor_id: roots.length === BATCH ? (roots.at(-1)?.id ?? END) : END,
|
|
220
|
+
usage_cursor: rows.length === BATCH ? (rows.at(-1)?.id ?? END) : END,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
async scanBatch(work, orgId, usageIds, cursors) {
|
|
224
|
+
if (!(await this.claim(work)))
|
|
225
|
+
return;
|
|
226
|
+
const policy = await readOrgRetention(this.db.db, orgId, { lock: true });
|
|
227
|
+
if (usageIds.length && policy.usageDays !== null) {
|
|
228
|
+
const rows = await sql `
|
|
229
|
+
DELETE FROM capybara.model_usage u USING (
|
|
230
|
+
SELECT id FROM capybara.model_usage WHERE org_id=${orgId} AND id=ANY(${usageIds}::uuid[])
|
|
231
|
+
AND occurred_at<${cutoff(policy.usageDays)} AND (reported_at IS NOT NULL OR report_failed_at IS NULL)
|
|
232
|
+
AND NOT EXISTS (SELECT 1 FROM capybara.usage_report_obligations o WHERE o.org_id=${orgId}
|
|
233
|
+
AND o.job_id=('usage-model-' || model_usage.id::text))
|
|
234
|
+
AND NOT EXISTS (SELECT 1 FROM capybara.outbox b WHERE b.org_id=${orgId}
|
|
235
|
+
AND b.queue=${USAGE_REPORT_QUEUE} AND b.job_id=('usage-model-' || model_usage.id::text))
|
|
236
|
+
ORDER BY id FOR UPDATE SKIP LOCKED
|
|
237
|
+
) picked WHERE u.org_id=${orgId} AND u.id=picked.id RETURNING u.occurred_at`.execute(this.db.db);
|
|
238
|
+
if (rows.rows.length)
|
|
239
|
+
await recordRetentionLoss(this.db.db, orgId, {
|
|
240
|
+
usage: new Date(Math.min(...rows.rows.map((r) => r.occurred_at.getTime()))),
|
|
241
|
+
usageThrough: new Date(Math.max(...rows.rows.map((r) => r.occurred_at.getTime()))),
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
const auditCount = await this.auditBatch(orgId, policy.auditDays);
|
|
245
|
+
const finished = cursors.cursor_id === END && cursors.usage_cursor === END && auditCount < BATCH;
|
|
246
|
+
await this.advance(work, "ready", finished ? REVISIT : 0, finished ? { cursor_id: null, usage_cursor: null } : cursors);
|
|
247
|
+
}
|
|
248
|
+
async platformAudit(work) {
|
|
249
|
+
if (!(await this.claim(work)))
|
|
250
|
+
return;
|
|
251
|
+
const policy = await readPlatformRetention(this.db.db, true);
|
|
252
|
+
const count = await this.auditBatch(null, policy.platformAuditDays);
|
|
253
|
+
await this.advance(work, "ready", count === BATCH ? 0 : REVISIT);
|
|
254
|
+
}
|
|
255
|
+
async auditBatch(orgId, days) {
|
|
256
|
+
if (days === null)
|
|
257
|
+
return 0;
|
|
258
|
+
const picked = this.db
|
|
259
|
+
.selectFrom("audit_events")
|
|
260
|
+
.select("id")
|
|
261
|
+
.where("org_id", orgId === null ? "is" : "=", orgId)
|
|
262
|
+
.where("at", "<", cutoff(days))
|
|
263
|
+
.orderBy("id")
|
|
264
|
+
.limit(BATCH)
|
|
265
|
+
.forUpdate()
|
|
266
|
+
.skipLocked();
|
|
267
|
+
const result = await this.db
|
|
268
|
+
.deleteFrom("audit_events")
|
|
269
|
+
.where("org_id", orgId === null ? "is" : "=", orgId)
|
|
270
|
+
.where("id", "in", picked)
|
|
271
|
+
.executeTakeFirst();
|
|
272
|
+
return Number(result.numDeletedRows);
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
__decorate([
|
|
276
|
+
Transactional()
|
|
277
|
+
], RetentionWorker.prototype, "recordFailure", null);
|
|
278
|
+
__decorate([
|
|
279
|
+
Transactional()
|
|
280
|
+
], RetentionWorker.prototype, "purge", null);
|
|
281
|
+
__decorate([
|
|
282
|
+
Transactional()
|
|
283
|
+
], RetentionWorker.prototype, "scanBatch", null);
|
|
284
|
+
__decorate([
|
|
285
|
+
Transactional()
|
|
286
|
+
], RetentionWorker.prototype, "platformAudit", null);
|
|
287
|
+
RetentionWorker = __decorate([
|
|
288
|
+
Injectable(),
|
|
289
|
+
__param(0, Inject(KernelDb)),
|
|
290
|
+
__param(1, Inject(TransactionHost)),
|
|
291
|
+
__param(2, Inject(OutboxService)),
|
|
292
|
+
__param(3, Inject(KernelConfigService)),
|
|
293
|
+
__param(4, Inject(ConversationsService)),
|
|
294
|
+
__param(5, Inject(RetentionReportObligations))
|
|
295
|
+
], RetentionWorker);
|
|
296
|
+
export { RetentionWorker };
|
|
297
|
+
let RetentionWorkerModule = class RetentionWorkerModule {
|
|
298
|
+
};
|
|
299
|
+
RetentionWorkerModule = __decorate([
|
|
300
|
+
Module({
|
|
301
|
+
imports: [ConversationsModule, RetentionReportObligationsModule],
|
|
302
|
+
providers: [RetentionWorker],
|
|
303
|
+
exports: [RetentionWorker],
|
|
304
|
+
})
|
|
305
|
+
], RetentionWorkerModule);
|
|
306
|
+
export { RetentionWorkerModule };
|
|
@@ -6,6 +6,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
6
6
|
};
|
|
7
7
|
var WorkerModule_1;
|
|
8
8
|
import { Module } from "@nestjs/common";
|
|
9
|
+
import { DiscoveryModule } from "@nestjs/core";
|
|
9
10
|
import { AutomationFireModule } from "../automations/fire.js";
|
|
10
11
|
import { BackgroundModule } from "../background/background.module.js";
|
|
11
12
|
import { BackgroundTaskPollJob } from "../background/poll.job.js";
|
|
@@ -26,11 +27,13 @@ import { PromptSuggestionsModule } from "../conversations/prompt-suggestions.js"
|
|
|
26
27
|
import { TitlesModule } from "../conversations/titles.js";
|
|
27
28
|
import { ConversationNoticeSweepJob, ConversationNoticesModule, } from "../device-access/conversation-notice-delivery.js";
|
|
28
29
|
import { DeviceSiteGrantsModule } from "../device-access/site-grants.module.js";
|
|
30
|
+
import { ErasureModule } from "../erasure/erasure.module.js";
|
|
31
|
+
import { ErasureSweep } from "../erasure/sweep.job.js";
|
|
29
32
|
import { EvalWorkersModule } from "../evals/evals.module.js";
|
|
30
33
|
import { ExtensionsModule } from "../extensions/extensions.module.js";
|
|
31
34
|
import { PluginsReconcileJob } from "../extensions/lifecycle.js";
|
|
32
35
|
import { LifecycleHookWorkersModule } from "../extensions/lifecycle-hooks.js";
|
|
33
|
-
import {
|
|
36
|
+
import { BlobSweepModule } from "../files/blob-sweep.job.js";
|
|
34
37
|
import { FileDraftCleanupJob } from "../files/draft-cleanup.job.js";
|
|
35
38
|
import { FileLibraryKickoffJob } from "../files/hash-job.js";
|
|
36
39
|
import { LibraryFilesModule } from "../files/library.module.js";
|
|
@@ -38,12 +41,14 @@ import { FileLibraryJobsModule } from "../files/library-jobs.module.js";
|
|
|
38
41
|
import { AccountAvatarCleanupJob } from "../identity/account-avatars.service.js";
|
|
39
42
|
import { IdentityModule } from "../identity/identity.module.js";
|
|
40
43
|
import { InitialPasswordCleanupJob } from "../identity/initial-passwords.job.js";
|
|
44
|
+
import { OperationalMetricsSampler, operationalMetricsEnabled, } from "../infra/metrics/operational-metrics.js";
|
|
41
45
|
import { OutboxRelayModule } from "../infra/outbox/outbox-relay.module.js";
|
|
42
46
|
import { KernelScheduleModule } from "../infra/schedule/schedule.module.js";
|
|
43
47
|
import { DirectoryScanJob } from "../orgs/directory-sync.js";
|
|
44
48
|
import { OrgLockModule } from "../orgs/org-lock.js";
|
|
45
49
|
import { OrgsModule } from "../orgs/orgs.module.js";
|
|
46
50
|
import { PushWorkersModule } from "../push/push-processor.js";
|
|
51
|
+
import { RetentionSweep } from "../retention/sweep.job.js";
|
|
47
52
|
import { MaintenanceModule } from "../runtime/maintenance.js";
|
|
48
53
|
import { RunJobsModule } from "../runtime/run-jobs.js";
|
|
49
54
|
import { RunOrphanCheck } from "../runtime/run-orphan-check.job.js";
|
|
@@ -75,6 +80,7 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
|
|
|
75
80
|
return {
|
|
76
81
|
module: WorkerModule_1,
|
|
77
82
|
imports: [
|
|
83
|
+
DiscoveryModule,
|
|
78
84
|
DeviceSiteGrantsModule,
|
|
79
85
|
KernelScheduleModule,
|
|
80
86
|
// the outbox relay (`@LockedInterval`): delivers what the fast path did not
|
|
@@ -85,6 +91,8 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
|
|
|
85
91
|
EvalWorkersModule.forRoot(config),
|
|
86
92
|
ChannelWorkersModule.forRoot(config),
|
|
87
93
|
MaintenanceModule,
|
|
94
|
+
ErasureModule,
|
|
95
|
+
BlobSweepModule,
|
|
88
96
|
PluginScopeWorkersModule,
|
|
89
97
|
LifecycleHookWorkersModule,
|
|
90
98
|
// push deliveries (`cap-push-deliver`) and the daily stale registration prune
|
|
@@ -126,17 +134,19 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
|
|
|
126
134
|
ConversationNoticesModule,
|
|
127
135
|
],
|
|
128
136
|
providers: [
|
|
137
|
+
...(operationalMetricsEnabled() ? [OperationalMetricsSampler] : []),
|
|
129
138
|
// the one repair of a run nobody runs (transactional outbox spec §8.3)
|
|
130
139
|
RunOrphanCheck,
|
|
131
140
|
AttachmentCleanupJob,
|
|
132
141
|
// expired uploads and composer drafts of the file library (file library spec §3)
|
|
133
142
|
FileDraftCleanupJob,
|
|
134
143
|
// the daily blob sweep and the hourly kickoff of hashing and the catch-up copy (§7, §9)
|
|
135
|
-
BlobSweepJob,
|
|
136
144
|
FileLibraryKickoffJob,
|
|
137
145
|
// the periodic kickoff of the batched conversation_events.org_id backfill (issue #1175)
|
|
138
146
|
EventOrgBackfillKickoffJob,
|
|
139
147
|
StoragePurgeJob,
|
|
148
|
+
RetentionSweep,
|
|
149
|
+
ErasureSweep,
|
|
140
150
|
SandboxSweepJobs,
|
|
141
151
|
BackgroundTaskPollJob,
|
|
142
152
|
// owed conversation notices to devices' services (close tabs on delete design §4.3)
|
|
@@ -5,6 +5,7 @@ import { TriggerDispatcher } from "../automations/events/dispatcher.js";
|
|
|
5
5
|
import { AutomationFirer } from "../automations/fire.js";
|
|
6
6
|
import { EventOrgBackfillJob } from "../conversations/event-org-backfill.js";
|
|
7
7
|
import { ConversationNoticeDelivery } from "../device-access/conversation-notice-delivery.js";
|
|
8
|
+
import { ErasureWorker } from "../erasure/worker.js";
|
|
8
9
|
import { BlobObjects } from "../files/blob-objects.js";
|
|
9
10
|
import { FileLibraryHashJob } from "../files/hash-job.js";
|
|
10
11
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
@@ -12,6 +13,7 @@ import { ScheduledRuns } from "../infra/schedule/scheduled-runs.js";
|
|
|
12
13
|
import type { KernelLogger } from "../log.js";
|
|
13
14
|
import { DirectorySync } from "../orgs/directory-sync.js";
|
|
14
15
|
import { Offboarding } from "../orgs/offboarding.js";
|
|
16
|
+
import { RetentionWorker } from "../retention/worker.js";
|
|
15
17
|
import { LoopbackGrants } from "../sandbox/loopback-grants.js";
|
|
16
18
|
import { SandboxOperationReconcileJob } from "../sandbox/operation-reconcile.job.js";
|
|
17
19
|
import { SandboxService } from "../sandbox/sandbox.service.js";
|
|
@@ -64,7 +66,9 @@ export declare class MaintenanceProcessor extends WorkerHost<Worker> {
|
|
|
64
66
|
private readonly db;
|
|
65
67
|
private readonly loopback;
|
|
66
68
|
private readonly eventOrgBackfill;
|
|
67
|
-
|
|
69
|
+
private readonly retention;
|
|
70
|
+
private readonly erasure;
|
|
71
|
+
constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, automations: Pick<AutomationFirer, "fire" | "settle">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke" | "settleResumeProof">, blobObjects: Pick<BlobObjects, "deleteBlob" | "deleteStaging" | "releaseFile">, hashing: Pick<FileLibraryHashJob, "dispatch" | "runOrgBatch">, platformIcons: Pick<PlatformIconObjects, "deleteObject">, notices: Pick<ConversationNoticeDelivery, "attempt">, triggers: Pick<TriggerDispatcher, "dispatch">, coalescer: Pick<EventCoalescer, "flush">, idleCompaction: Pick<IdleCompactionJob, "fire">, db: KernelDb, loopback: Pick<LoopbackGrants, "refresh">, eventOrgBackfill: Pick<EventOrgBackfillJob, "runBatch">, retention: Pick<RetentionWorker, "run">, erasure: Pick<ErasureWorker, "run">);
|
|
68
72
|
process(job: Job, token?: string): Promise<void>;
|
|
69
73
|
/** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
|
|
70
74
|
start(): void;
|
|
@@ -21,6 +21,8 @@ import { EventOrgBackfillModule } from "../conversations/event-org-backfill.modu
|
|
|
21
21
|
import { resolveConversationOrg, resolveRunOrg } from "../conversations/job-org.js";
|
|
22
22
|
import { ConversationNoticeDelivery, ConversationNoticesModule, NOTICE_PROMPT_TIMEOUT_MS, } from "../device-access/conversation-notice-delivery.js";
|
|
23
23
|
import { CONVERSATION_NOTICE_JOB, } from "../device-access/conversation-notices.js";
|
|
24
|
+
import { DATA_ERASURE_JOB } from "../erasure/jobs.js";
|
|
25
|
+
import { ErasureWorker, ErasureWorkerModule } from "../erasure/worker.js";
|
|
24
26
|
import { BLOB_DELETE_JOB, BlobObjects, BlobObjectsModule, FILE_RELEASE_JOB, FILE_STAGING_DELETE_JOB, } from "../files/blob-objects.js";
|
|
25
27
|
import { FILE_LIBRARY_HASH_JOB, FILE_LIBRARY_HASH_ORG_JOB, FileLibraryHashJob, } from "../files/hash-job.js";
|
|
26
28
|
import { FileLibraryJobsModule } from "../files/library-jobs.module.js";
|
|
@@ -35,6 +37,8 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
|
35
37
|
import { DIRECTORY_SYNC_JOB, DirectorySync } from "../orgs/directory-sync.js";
|
|
36
38
|
import { Offboarding, RUN_STOP_JOB } from "../orgs/offboarding.js";
|
|
37
39
|
import { OrgsModule } from "../orgs/orgs.module.js";
|
|
40
|
+
import { RETENTION_JOB } from "../retention/jobs.js";
|
|
41
|
+
import { RetentionWorker, RetentionWorkerModule } from "../retention/worker.js";
|
|
38
42
|
import { runSandboxDestroyFor, runSandboxResetFiles, SANDBOX_DESTROY_FOR_JOB, SANDBOX_RESET_FILES_JOB, } from "../sandbox/jobs.js";
|
|
39
43
|
import { LOOPBACK_REFRESH_JOB, LOOPBACK_REFRESH_TIMEOUT_MS, } from "../sandbox/loopback-grant-records.js";
|
|
40
44
|
import { LoopbackGrants } from "../sandbox/loopback-grants.js";
|
|
@@ -98,7 +102,9 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
98
102
|
db;
|
|
99
103
|
loopback;
|
|
100
104
|
eventOrgBackfill;
|
|
101
|
-
|
|
105
|
+
retention;
|
|
106
|
+
erasure;
|
|
107
|
+
constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, automations, scheduled, log, operations, blobObjects, hashing, platformIcons, notices, triggers, coalescer, idleCompaction, db, loopback, eventOrgBackfill, retention, erasure) {
|
|
102
108
|
super();
|
|
103
109
|
this.permissionApprovals = permissionApprovals;
|
|
104
110
|
this.waits = waits;
|
|
@@ -122,6 +128,8 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
122
128
|
this.db = db;
|
|
123
129
|
this.loopback = loopback;
|
|
124
130
|
this.eventOrgBackfill = eventOrgBackfill;
|
|
131
|
+
this.retention = retention;
|
|
132
|
+
this.erasure = erasure;
|
|
125
133
|
}
|
|
126
134
|
process(job, token) {
|
|
127
135
|
return runJob(MAINTENANCE_QUEUE_NAME, job, () => this.dispatch(job, token), {
|
|
@@ -153,6 +161,12 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
153
161
|
}
|
|
154
162
|
async dispatch(job, token) {
|
|
155
163
|
switch (job.name) {
|
|
164
|
+
case DATA_ERASURE_JOB:
|
|
165
|
+
await this.erasure.run(job.data.requestId, job.id);
|
|
166
|
+
return;
|
|
167
|
+
case RETENTION_JOB:
|
|
168
|
+
await this.retention.run(job.data.workId, job.id);
|
|
169
|
+
return;
|
|
156
170
|
case PERMISSION_APPROVAL_RECHECK:
|
|
157
171
|
await this.permissionApprovals.recheck(job.data);
|
|
158
172
|
return;
|
|
@@ -350,7 +364,9 @@ MaintenanceProcessor = __decorate([
|
|
|
350
364
|
__param(18, Inject(IdleCompactionJob)),
|
|
351
365
|
__param(19, Inject(KernelDb)),
|
|
352
366
|
__param(20, Inject(LoopbackGrants)),
|
|
353
|
-
__param(21, Inject(EventOrgBackfillJob))
|
|
367
|
+
__param(21, Inject(EventOrgBackfillJob)),
|
|
368
|
+
__param(22, Inject(RetentionWorker)),
|
|
369
|
+
__param(23, Inject(ErasureWorker))
|
|
354
370
|
], MaintenanceProcessor);
|
|
355
371
|
export { MaintenanceProcessor };
|
|
356
372
|
/**
|
|
@@ -383,6 +399,8 @@ MaintenanceModule = __decorate([
|
|
|
383
399
|
FileLibraryJobsModule,
|
|
384
400
|
// batched conversation_events.org_id backfill
|
|
385
401
|
EventOrgBackfillModule,
|
|
402
|
+
RetentionWorkerModule,
|
|
403
|
+
ErasureWorkerModule,
|
|
386
404
|
// the platform icon object deletion
|
|
387
405
|
PlatformIconObjectsModule,
|
|
388
406
|
// a deleted conversation's notice to its device's services
|
|
@@ -6,6 +6,7 @@ import { type ConversationEvent } from "../conversations/events.js";
|
|
|
6
6
|
import type { IdleMode, KernelSchemaDb } from "../db/kernel-schema.js";
|
|
7
7
|
import type { CaseSnapshot } from "../evals/snapshot.js";
|
|
8
8
|
import type { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
9
|
+
import { type ModelBudgetErrorDetail } from "../models/budget-admission.js";
|
|
9
10
|
import type { ToolRegistry, UnavailableTool } from "../tools/registry.js";
|
|
10
11
|
import { type CompactionModelPort, type Summarizer } from "./compaction-model.js";
|
|
11
12
|
import type { CompactionProgressSink } from "./compaction-progress.js";
|
|
@@ -245,7 +246,8 @@ export interface ModelStepResult {
|
|
|
245
246
|
*/
|
|
246
247
|
export declare class RunError extends Error {
|
|
247
248
|
readonly code: string;
|
|
248
|
-
|
|
249
|
+
readonly budgetDetail?: ModelBudgetErrorDetail | undefined;
|
|
250
|
+
constructor(code: string, message: string, budgetDetail?: ModelBudgetErrorDetail | undefined);
|
|
249
251
|
}
|
|
250
252
|
/**
|
|
251
253
|
* A failure of the permission context boundary (the callback or its complete-log refresh) before
|
|
@@ -3,6 +3,7 @@ import { isModelError, isRetryableKind, ModelError, sanitizeParams, validateCach
|
|
|
3
3
|
import { MEDIA_EXCLUDED_MAX_IDS } from "../conversations/events.js";
|
|
4
4
|
import { ApiError } from "../errors.js";
|
|
5
5
|
import { ExtensionUnloadedError } from "../extensions/inflight.js";
|
|
6
|
+
import { ModelBudgetRefused } from "../models/budget-admission.js";
|
|
6
7
|
import { hasInvocation, skillLoadOffered } from "../skills/catalog.js";
|
|
7
8
|
import { chooseSummarizer } from "./compaction-model.js";
|
|
8
9
|
import { buildModelRequest, latestSummary, mediaRefs, planMedia, } from "./context/build.js";
|
|
@@ -94,9 +95,11 @@ export class MediaUnavailableError extends Error {
|
|
|
94
95
|
*/
|
|
95
96
|
export class RunError extends Error {
|
|
96
97
|
code;
|
|
97
|
-
|
|
98
|
+
budgetDetail;
|
|
99
|
+
constructor(code, message, budgetDetail) {
|
|
98
100
|
super(message);
|
|
99
101
|
this.code = code;
|
|
102
|
+
this.budgetDetail = budgetDetail;
|
|
100
103
|
this.name = "RunError";
|
|
101
104
|
}
|
|
102
105
|
}
|
|
@@ -1127,6 +1130,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
1127
1130
|
let plannedChunks = chunked ? chunkTranscript(plan.transcript, baseChunkSize).length : 0;
|
|
1128
1131
|
let lastChunkSize = baseChunkSize;
|
|
1129
1132
|
let failure = null;
|
|
1133
|
+
let budgetRefusal;
|
|
1130
1134
|
/** The 1-based chunk whose call failed or was denied, when the compaction was chunked. */
|
|
1131
1135
|
let failedChunk = null;
|
|
1132
1136
|
let denial = null;
|
|
@@ -1200,6 +1204,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
1200
1204
|
...ref,
|
|
1201
1205
|
orgId: input.orgId,
|
|
1202
1206
|
purpose: input.conversationKind === "eval" ? "eval" : "compaction",
|
|
1207
|
+
budgetSite: { conversationId, runId },
|
|
1203
1208
|
scope,
|
|
1204
1209
|
step,
|
|
1205
1210
|
attempt: retry ? 2 : 1,
|
|
@@ -1211,6 +1216,10 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
1211
1216
|
deps.compactionProgress?.clear(runId);
|
|
1212
1217
|
throw new StepAborted();
|
|
1213
1218
|
}
|
|
1219
|
+
if (err instanceof ModelBudgetRefused) {
|
|
1220
|
+
budgetRefusal = err;
|
|
1221
|
+
break;
|
|
1222
|
+
}
|
|
1214
1223
|
if (!(err instanceof ModelRequestDenied))
|
|
1215
1224
|
throw err;
|
|
1216
1225
|
denial = { verdict: err.verdict, chunk: chunkNo };
|
|
@@ -1305,7 +1314,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
1305
1314
|
}
|
|
1306
1315
|
break;
|
|
1307
1316
|
}
|
|
1308
|
-
if (failure !== null || denial !== null)
|
|
1317
|
+
if (failure !== null || denial !== null || budgetRefusal)
|
|
1309
1318
|
break;
|
|
1310
1319
|
// the whole transcript was this one call, or its last chunk is done
|
|
1311
1320
|
if (remaining === null)
|
|
@@ -1313,7 +1322,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
1313
1322
|
}
|
|
1314
1323
|
// only a compaction that still has something to write shows the writing phase: a failed or denied
|
|
1315
1324
|
// one jumps straight to its failure event (folded review Minor)
|
|
1316
|
-
if (failure === null && denial === null) {
|
|
1325
|
+
if (failure === null && denial === null && !budgetRefusal) {
|
|
1317
1326
|
progressOf({ phase: "writing", step, startedAt });
|
|
1318
1327
|
}
|
|
1319
1328
|
/** The chunk a failure stopped at, for the reason (empty when the compaction was not chunked). */
|
|
@@ -1332,6 +1341,16 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
1332
1341
|
...(chunk !== undefined ? { chunk, chunks: attempted } : {}),
|
|
1333
1342
|
},
|
|
1334
1343
|
}));
|
|
1344
|
+
if (budgetRefusal) {
|
|
1345
|
+
try {
|
|
1346
|
+
if (usages.length > 0)
|
|
1347
|
+
await appendCounted(deps, input, usageEvents());
|
|
1348
|
+
}
|
|
1349
|
+
finally {
|
|
1350
|
+
deps.compactionProgress?.clear(runId);
|
|
1351
|
+
}
|
|
1352
|
+
throw new RunError(budgetRefusal.code, budgetRefusal.message, budgetRefusal.budgetDetail);
|
|
1353
|
+
}
|
|
1335
1354
|
if (denial !== null) {
|
|
1336
1355
|
// compaction fails (generic reason in the log, raw detail only in the audit row, R12); the
|
|
1337
1356
|
// step continues and its own request meets the hooks next
|
|
@@ -1680,6 +1699,7 @@ longTtl, tools, wrapUpReason, streamed) {
|
|
|
1680
1699
|
...rung.ref,
|
|
1681
1700
|
orgId: input.orgId,
|
|
1682
1701
|
purpose: input.conversationKind === "eval" ? "eval" : "step",
|
|
1702
|
+
budgetSite: { conversationId, runId },
|
|
1683
1703
|
scope,
|
|
1684
1704
|
step,
|
|
1685
1705
|
attempt,
|
|
@@ -1792,6 +1812,8 @@ longTtl, tools, wrapUpReason, streamed) {
|
|
|
1792
1812
|
// a hook denial is final (not retried, not reclassified)
|
|
1793
1813
|
if (err instanceof RunError)
|
|
1794
1814
|
throw err;
|
|
1815
|
+
if (err instanceof ModelBudgetRefused)
|
|
1816
|
+
throw new RunError(err.code, err.message, err.budgetDetail);
|
|
1795
1817
|
if (err instanceof BudgetUsedUp)
|
|
1796
1818
|
throw err;
|
|
1797
1819
|
if (err instanceof NoReactiveTrim) {
|
|
@@ -5,6 +5,7 @@ import { ApiError } from "../errors.js";
|
|
|
5
5
|
import { EffectiveConfigs } from "../extensions/effective-config.js";
|
|
6
6
|
import { CacheService } from "../infra/cache/cache.service.js";
|
|
7
7
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
8
|
+
import { ModelBudgetAdmission, type ModelBudgetSite } from "../models/budget-admission.js";
|
|
8
9
|
import { ModelEnablement } from "../models/enablement.js";
|
|
9
10
|
import { type HookDenial, type HookRunner } from "./hook-calls.js";
|
|
10
11
|
/**
|
|
@@ -67,6 +68,8 @@ export type ExpectedKind = "chat" | "embedding" | "image_generation" | "callable
|
|
|
67
68
|
* the closure (never on the object, so logging or serialising it shows no secret).
|
|
68
69
|
*/
|
|
69
70
|
export interface BoundProvider {
|
|
71
|
+
/** The registry binds an admission check to this provider's organization. */
|
|
72
|
+
checkBudget?(site?: ModelBudgetSite): Promise<void>;
|
|
70
73
|
stream(req: ModelRequest, opts: {
|
|
71
74
|
signal: AbortSignal;
|
|
72
75
|
}): AsyncIterable<ModelStreamEvent>;
|
|
@@ -92,6 +95,7 @@ interface RequestSite {
|
|
|
92
95
|
export interface ChatRequestSite extends RequestSite {
|
|
93
96
|
purpose: ModelCallRequestHookPayload["purpose"] | "eval";
|
|
94
97
|
scope?: HookScope | null | undefined;
|
|
98
|
+
budgetSite?: ModelBudgetSite | undefined;
|
|
95
99
|
step: number;
|
|
96
100
|
attempt: number;
|
|
97
101
|
}
|
|
@@ -102,7 +106,7 @@ export declare function mapProviderStream(provider: BoundProvider, map: (request
|
|
|
102
106
|
export declare function supportsEmbedding(provider: BoundProvider): boolean;
|
|
103
107
|
/** Authorizes all input texts before the caller splits them into provider batches. */
|
|
104
108
|
export declare function prepareEmbedding(provider: BoundProvider, payload: EmbeddingRequestHookPayload, hooks: HookRunner | undefined, signal: AbortSignal): Promise<NonNullable<BoundProvider["embed"]>>;
|
|
105
|
-
export declare function prepareImageGeneration(provider: BoundProvider, payload: () => ImageRequestHookPayload, hooks: HookRunner | undefined, signal: AbortSignal, ref: ModelRef): Promise<NonNullable<BoundProvider["generateImage"]>>;
|
|
109
|
+
export declare function prepareImageGeneration(provider: BoundProvider, payload: () => ImageRequestHookPayload, hooks: HookRunner | undefined, signal: AbortSignal, ref: ModelRef, budgetSite?: ModelBudgetSite): Promise<NonNullable<BoundProvider["generateImage"]>>;
|
|
106
110
|
export type PlatformProviderState = "ok" | "error" | "org_configured";
|
|
107
111
|
export type OrgProviderState = "ok" | "error" | "needs_config";
|
|
108
112
|
/**
|
|
@@ -177,9 +181,10 @@ export declare class ProviderRegistry {
|
|
|
177
181
|
private readonly log?;
|
|
178
182
|
/** Overrides `models.listTimeoutMs` (tests). */
|
|
179
183
|
private readonly listTimeoutOverride?;
|
|
184
|
+
private readonly budgets?;
|
|
180
185
|
constructor(host: ProviderHost, effective: Pick<EffectiveConfigs, "get">, cacheService: CacheService, kv: Redis, config: Pick<KernelConfigService, "get">, enablement: Pick<ModelEnablement, "disabled" | "enabledIn">, log?: Pick<Logger, "warn"> | undefined,
|
|
181
186
|
/** Overrides `models.listTimeoutMs` (tests). */
|
|
182
|
-
listTimeoutOverride?: number | undefined);
|
|
187
|
+
listTimeoutOverride?: number | undefined, budgets?: ModelBudgetAdmission | undefined);
|
|
183
188
|
/**
|
|
184
189
|
* `listModels()` with a time limit: a timeout counts as a failure; the provider's call runs on in
|
|
185
190
|
* the background and its result is dropped.
|