@capybara-hq/kernel 0.1.0-rc.130 → 0.1.0-rc.132
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/catalog/plugin-import.d.ts +3 -1
- package/dist/catalog/plugin-import.js +19 -15
- package/dist/channels/connections.service.d.ts +1 -1
- package/dist/client/client-reports.service.js +12 -0
- package/dist/config/schema.d.ts +9 -1
- package/dist/config/schema.js +51 -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/ctx/create-ctx.d.ts +3 -2
- package/dist/ctx/create-ctx.js +10 -7
- package/dist/db/extension-db.d.ts +30 -0
- package/dist/db/extension-db.js +91 -0
- package/dist/db/extension-schema-transfer.d.ts +6 -0
- package/dist/db/extension-schema-transfer.js +141 -0
- package/dist/db/kernel-schema.d.ts +73 -12
- package/dist/db/migrator.d.ts +6 -0
- package/dist/db/migrator.js +39 -4
- package/dist/db/pool.d.ts +4 -0
- package/dist/db/pool.js +36 -1
- 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/{conversations/event-org-backfill.module.js → erasure/erasure.module.js} +6 -10
- 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/extensions/admin-ops.d.ts +3 -1
- package/dist/extensions/admin-ops.js +11 -7
- package/dist/extensions/extensions.module.js +3 -0
- package/dist/extensions/host.d.ts +4 -1
- package/dist/extensions/host.js +29 -6
- package/dist/extensions/instance.d.ts +3 -0
- package/dist/extensions/instance.js +3 -1
- package/dist/extensions/migrate-lock.d.ts +4 -1
- package/dist/extensions/migrate-lock.js +19 -2
- 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 -14
- package/dist/infra/outbox/registry.js +12 -15
- 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/kernel.js +4 -0
- package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
- package/dist/lifecycle/kernel-lifecycle.js +26 -21
- 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 -8
- package/dist/runtime/maintenance.d.ts +5 -3
- package/dist/runtime/maintenance.js +19 -12
- 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
- package/src/migrations/0219_event_org_constraint_check.sql +29 -0
- package/src/migrations/0220_require_event_org.sql +18 -0
- package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
- package/dist/conversations/event-org-backfill.d.ts +0 -111
- package/dist/conversations/event-org-backfill.js +0 -264
- package/dist/conversations/event-org-backfill.module.d.ts +0 -3
|
@@ -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";
|
|
@@ -20,17 +21,17 @@ import { ClientReportsCron } from "../client/client-reports.cron.js";
|
|
|
20
21
|
import { AttachmentsModule } from "../conversations/attachments.module.js";
|
|
21
22
|
import { AttachmentCleanupJob } from "../conversations/attachments.service.js";
|
|
22
23
|
import { EventLogModule } from "../conversations/event-log.js";
|
|
23
|
-
import { EventOrgBackfillKickoffJob } from "../conversations/event-org-backfill.js";
|
|
24
|
-
import { EventOrgBackfillModule } from "../conversations/event-org-backfill.module.js";
|
|
25
24
|
import { PromptSuggestionsModule } from "../conversations/prompt-suggestions.js";
|
|
26
25
|
import { TitlesModule } from "../conversations/titles.js";
|
|
27
26
|
import { ConversationNoticeSweepJob, ConversationNoticesModule, } from "../device-access/conversation-notice-delivery.js";
|
|
28
27
|
import { DeviceSiteGrantsModule } from "../device-access/site-grants.module.js";
|
|
28
|
+
import { ErasureModule } from "../erasure/erasure.module.js";
|
|
29
|
+
import { ErasureSweep } from "../erasure/sweep.job.js";
|
|
29
30
|
import { EvalWorkersModule } from "../evals/evals.module.js";
|
|
30
31
|
import { ExtensionsModule } from "../extensions/extensions.module.js";
|
|
31
32
|
import { PluginsReconcileJob } from "../extensions/lifecycle.js";
|
|
32
33
|
import { LifecycleHookWorkersModule } from "../extensions/lifecycle-hooks.js";
|
|
33
|
-
import {
|
|
34
|
+
import { BlobSweepModule } from "../files/blob-sweep.job.js";
|
|
34
35
|
import { FileDraftCleanupJob } from "../files/draft-cleanup.job.js";
|
|
35
36
|
import { FileLibraryKickoffJob } from "../files/hash-job.js";
|
|
36
37
|
import { LibraryFilesModule } from "../files/library.module.js";
|
|
@@ -38,12 +39,14 @@ import { FileLibraryJobsModule } from "../files/library-jobs.module.js";
|
|
|
38
39
|
import { AccountAvatarCleanupJob } from "../identity/account-avatars.service.js";
|
|
39
40
|
import { IdentityModule } from "../identity/identity.module.js";
|
|
40
41
|
import { InitialPasswordCleanupJob } from "../identity/initial-passwords.job.js";
|
|
42
|
+
import { OperationalMetricsSampler, operationalMetricsEnabled, } from "../infra/metrics/operational-metrics.js";
|
|
41
43
|
import { OutboxRelayModule } from "../infra/outbox/outbox-relay.module.js";
|
|
42
44
|
import { KernelScheduleModule } from "../infra/schedule/schedule.module.js";
|
|
43
45
|
import { DirectoryScanJob } from "../orgs/directory-sync.js";
|
|
44
46
|
import { OrgLockModule } from "../orgs/org-lock.js";
|
|
45
47
|
import { OrgsModule } from "../orgs/orgs.module.js";
|
|
46
48
|
import { PushWorkersModule } from "../push/push-processor.js";
|
|
49
|
+
import { RetentionSweep } from "../retention/sweep.job.js";
|
|
47
50
|
import { MaintenanceModule } from "../runtime/maintenance.js";
|
|
48
51
|
import { RunJobsModule } from "../runtime/run-jobs.js";
|
|
49
52
|
import { RunOrphanCheck } from "../runtime/run-orphan-check.job.js";
|
|
@@ -75,6 +78,7 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
|
|
|
75
78
|
return {
|
|
76
79
|
module: WorkerModule_1,
|
|
77
80
|
imports: [
|
|
81
|
+
DiscoveryModule,
|
|
78
82
|
DeviceSiteGrantsModule,
|
|
79
83
|
KernelScheduleModule,
|
|
80
84
|
// the outbox relay (`@LockedInterval`): delivers what the fast path did not
|
|
@@ -85,6 +89,8 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
|
|
|
85
89
|
EvalWorkersModule.forRoot(config),
|
|
86
90
|
ChannelWorkersModule.forRoot(config),
|
|
87
91
|
MaintenanceModule,
|
|
92
|
+
ErasureModule,
|
|
93
|
+
BlobSweepModule,
|
|
88
94
|
PluginScopeWorkersModule,
|
|
89
95
|
LifecycleHookWorkersModule,
|
|
90
96
|
// push deliveries (`cap-push-deliver`) and the daily stale registration prune
|
|
@@ -107,8 +113,6 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
|
|
|
107
113
|
LibraryFilesModule,
|
|
108
114
|
// the hashing and catch-up copy the kickoff owes
|
|
109
115
|
FileLibraryJobsModule,
|
|
110
|
-
// the batched conversation_events.org_id backfill the kickoff owes
|
|
111
|
-
EventOrgBackfillModule,
|
|
112
116
|
IdentityModule,
|
|
113
117
|
StorageModule,
|
|
114
118
|
SandboxModule,
|
|
@@ -126,17 +130,17 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
|
|
|
126
130
|
ConversationNoticesModule,
|
|
127
131
|
],
|
|
128
132
|
providers: [
|
|
133
|
+
...(operationalMetricsEnabled() ? [OperationalMetricsSampler] : []),
|
|
129
134
|
// the one repair of a run nobody runs (transactional outbox spec §8.3)
|
|
130
135
|
RunOrphanCheck,
|
|
131
136
|
AttachmentCleanupJob,
|
|
132
137
|
// expired uploads and composer drafts of the file library (file library spec §3)
|
|
133
138
|
FileDraftCleanupJob,
|
|
134
139
|
// the daily blob sweep and the hourly kickoff of hashing and the catch-up copy (§7, §9)
|
|
135
|
-
BlobSweepJob,
|
|
136
140
|
FileLibraryKickoffJob,
|
|
137
|
-
// the periodic kickoff of the batched conversation_events.org_id backfill (issue #1175)
|
|
138
|
-
EventOrgBackfillKickoffJob,
|
|
139
141
|
StoragePurgeJob,
|
|
142
|
+
RetentionSweep,
|
|
143
|
+
ErasureSweep,
|
|
140
144
|
SandboxSweepJobs,
|
|
141
145
|
BackgroundTaskPollJob,
|
|
142
146
|
// owed conversation notices to devices' services (close tabs on delete design §4.3)
|
|
@@ -3,8 +3,8 @@ import type { Job, Worker } from "bullmq";
|
|
|
3
3
|
import { EventCoalescer } from "../automations/events/coalesce.js";
|
|
4
4
|
import { TriggerDispatcher } from "../automations/events/dispatcher.js";
|
|
5
5
|
import { AutomationFirer } from "../automations/fire.js";
|
|
6
|
-
import { EventOrgBackfillJob } from "../conversations/event-org-backfill.js";
|
|
7
6
|
import { ConversationNoticeDelivery } from "../device-access/conversation-notice-delivery.js";
|
|
7
|
+
import { ErasureWorker } from "../erasure/worker.js";
|
|
8
8
|
import { BlobObjects } from "../files/blob-objects.js";
|
|
9
9
|
import { FileLibraryHashJob } from "../files/hash-job.js";
|
|
10
10
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
@@ -12,6 +12,7 @@ import { ScheduledRuns } from "../infra/schedule/scheduled-runs.js";
|
|
|
12
12
|
import type { KernelLogger } from "../log.js";
|
|
13
13
|
import { DirectorySync } from "../orgs/directory-sync.js";
|
|
14
14
|
import { Offboarding } from "../orgs/offboarding.js";
|
|
15
|
+
import { RetentionWorker } from "../retention/worker.js";
|
|
15
16
|
import { LoopbackGrants } from "../sandbox/loopback-grants.js";
|
|
16
17
|
import { SandboxOperationReconcileJob } from "../sandbox/operation-reconcile.job.js";
|
|
17
18
|
import { SandboxService } from "../sandbox/sandbox.service.js";
|
|
@@ -63,8 +64,9 @@ export declare class MaintenanceProcessor extends WorkerHost<Worker> {
|
|
|
63
64
|
private readonly idleCompaction;
|
|
64
65
|
private readonly db;
|
|
65
66
|
private readonly loopback;
|
|
66
|
-
private readonly
|
|
67
|
-
|
|
67
|
+
private readonly retention;
|
|
68
|
+
private readonly erasure;
|
|
69
|
+
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">, retention: Pick<RetentionWorker, "run">, erasure: Pick<ErasureWorker, "run">);
|
|
68
70
|
process(job: Job, token?: string): Promise<void>;
|
|
69
71
|
/** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
|
|
70
72
|
start(): void;
|
|
@@ -16,11 +16,11 @@ import { AUTOMATION_COALESCE_JOB, AUTOMATION_FIRE_JOB, AUTOMATION_SETTLE_JOB, TR
|
|
|
16
16
|
import { BackgroundModule } from "../background/background.module.js";
|
|
17
17
|
import { BG_WAKE_JOB } from "../background/wake-rules.js";
|
|
18
18
|
import { EventLogModule } from "../conversations/event-log.js";
|
|
19
|
-
import { EVENT_ORG_BACKFILL_JOB, EventOrgBackfillJob, } from "../conversations/event-org-backfill.js";
|
|
20
|
-
import { EventOrgBackfillModule } from "../conversations/event-org-backfill.module.js";
|
|
21
19
|
import { resolveConversationOrg, resolveRunOrg } from "../conversations/job-org.js";
|
|
22
20
|
import { ConversationNoticeDelivery, ConversationNoticesModule, NOTICE_PROMPT_TIMEOUT_MS, } from "../device-access/conversation-notice-delivery.js";
|
|
23
21
|
import { CONVERSATION_NOTICE_JOB, } from "../device-access/conversation-notices.js";
|
|
22
|
+
import { DATA_ERASURE_JOB } from "../erasure/jobs.js";
|
|
23
|
+
import { ErasureWorker, ErasureWorkerModule } from "../erasure/worker.js";
|
|
24
24
|
import { BLOB_DELETE_JOB, BlobObjects, BlobObjectsModule, FILE_RELEASE_JOB, FILE_STAGING_DELETE_JOB, } from "../files/blob-objects.js";
|
|
25
25
|
import { FILE_LIBRARY_HASH_JOB, FILE_LIBRARY_HASH_ORG_JOB, FileLibraryHashJob, } from "../files/hash-job.js";
|
|
26
26
|
import { FileLibraryJobsModule } from "../files/library-jobs.module.js";
|
|
@@ -35,6 +35,8 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
|
35
35
|
import { DIRECTORY_SYNC_JOB, DirectorySync } from "../orgs/directory-sync.js";
|
|
36
36
|
import { Offboarding, RUN_STOP_JOB } from "../orgs/offboarding.js";
|
|
37
37
|
import { OrgsModule } from "../orgs/orgs.module.js";
|
|
38
|
+
import { RETENTION_JOB } from "../retention/jobs.js";
|
|
39
|
+
import { RetentionWorker, RetentionWorkerModule } from "../retention/worker.js";
|
|
38
40
|
import { runSandboxDestroyFor, runSandboxResetFiles, SANDBOX_DESTROY_FOR_JOB, SANDBOX_RESET_FILES_JOB, } from "../sandbox/jobs.js";
|
|
39
41
|
import { LOOPBACK_REFRESH_JOB, LOOPBACK_REFRESH_TIMEOUT_MS, } from "../sandbox/loopback-grant-records.js";
|
|
40
42
|
import { LoopbackGrants } from "../sandbox/loopback-grants.js";
|
|
@@ -97,8 +99,9 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
97
99
|
idleCompaction;
|
|
98
100
|
db;
|
|
99
101
|
loopback;
|
|
100
|
-
|
|
101
|
-
|
|
102
|
+
retention;
|
|
103
|
+
erasure;
|
|
104
|
+
constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, automations, scheduled, log, operations, blobObjects, hashing, platformIcons, notices, triggers, coalescer, idleCompaction, db, loopback, retention, erasure) {
|
|
102
105
|
super();
|
|
103
106
|
this.permissionApprovals = permissionApprovals;
|
|
104
107
|
this.waits = waits;
|
|
@@ -121,7 +124,8 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
121
124
|
this.idleCompaction = idleCompaction;
|
|
122
125
|
this.db = db;
|
|
123
126
|
this.loopback = loopback;
|
|
124
|
-
this.
|
|
127
|
+
this.retention = retention;
|
|
128
|
+
this.erasure = erasure;
|
|
125
129
|
}
|
|
126
130
|
process(job, token) {
|
|
127
131
|
return runJob(MAINTENANCE_QUEUE_NAME, job, () => this.dispatch(job, token), {
|
|
@@ -153,6 +157,12 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
153
157
|
}
|
|
154
158
|
async dispatch(job, token) {
|
|
155
159
|
switch (job.name) {
|
|
160
|
+
case DATA_ERASURE_JOB:
|
|
161
|
+
await this.erasure.run(job.data.requestId, job.id);
|
|
162
|
+
return;
|
|
163
|
+
case RETENTION_JOB:
|
|
164
|
+
await this.retention.run(job.data.workId, job.id);
|
|
165
|
+
return;
|
|
156
166
|
case PERMISSION_APPROVAL_RECHECK:
|
|
157
167
|
await this.permissionApprovals.recheck(job.data);
|
|
158
168
|
return;
|
|
@@ -301,10 +311,6 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
301
311
|
await this.inOwnerScope(job, resolveRunOrg(this.db.db, data.runId, data.conversationId), (orgId) => this.idleCompaction.fire({ ...data, orgId }));
|
|
302
312
|
return;
|
|
303
313
|
}
|
|
304
|
-
// batched backfill of conversation_events.org_id from conversations (issue #1175)
|
|
305
|
-
case EVENT_ORG_BACKFILL_JOB:
|
|
306
|
-
await this.eventOrgBackfill.runBatch((job.data ?? { after: null }));
|
|
307
|
-
return;
|
|
308
314
|
default:
|
|
309
315
|
if (await this.scheduled.runNow(job.name))
|
|
310
316
|
return;
|
|
@@ -350,7 +356,8 @@ MaintenanceProcessor = __decorate([
|
|
|
350
356
|
__param(18, Inject(IdleCompactionJob)),
|
|
351
357
|
__param(19, Inject(KernelDb)),
|
|
352
358
|
__param(20, Inject(LoopbackGrants)),
|
|
353
|
-
__param(21, Inject(
|
|
359
|
+
__param(21, Inject(RetentionWorker)),
|
|
360
|
+
__param(22, Inject(ErasureWorker))
|
|
354
361
|
], MaintenanceProcessor);
|
|
355
362
|
export { MaintenanceProcessor };
|
|
356
363
|
/**
|
|
@@ -381,8 +388,8 @@ MaintenanceModule = __decorate([
|
|
|
381
388
|
BlobObjectsModule,
|
|
382
389
|
// the file library's hashing
|
|
383
390
|
FileLibraryJobsModule,
|
|
384
|
-
|
|
385
|
-
|
|
391
|
+
RetentionWorkerModule,
|
|
392
|
+
ErasureWorkerModule,
|
|
386
393
|
// the platform icon object deletion
|
|
387
394
|
PlatformIconObjectsModule,
|
|
388
395
|
// 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) {
|