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