@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
|
@@ -11,13 +11,18 @@ import { Inject, Injectable, Module, Optional } from "@nestjs/common";
|
|
|
11
11
|
import { sql } from "kysely";
|
|
12
12
|
import { oweDelivery } from "../channels/deliver-job.js";
|
|
13
13
|
import { ApiError } from "../errors.js";
|
|
14
|
+
import { afterCommit } from "../infra/database/after-commit.js";
|
|
14
15
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
15
16
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
16
17
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
18
|
+
import { recordRun } from "../infra/metrics/kernel-metrics.js";
|
|
17
19
|
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
18
20
|
import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
|
|
21
|
+
import { recordSettledModelUsage, settledUsageBucket } from "../models/budget-counters.js";
|
|
19
22
|
import { readPriceSnapshots } from "../models/price-snapshot.js";
|
|
20
23
|
import { PushOwed, PushOwedModule } from "../push/push-owed.js";
|
|
24
|
+
import { currentExecutionClaim } from "../runtime/run-execution.js";
|
|
25
|
+
import { runPrincipalAccount } from "../runtime/run-principal.js";
|
|
21
26
|
import { ConversationEventSchema, } from "./events.js";
|
|
22
27
|
/**
|
|
23
28
|
* The JSON stored for an event payload, with every NUL (U+0000) in a string or an object key
|
|
@@ -519,6 +524,78 @@ let EventLog = class EventLog {
|
|
|
519
524
|
}))
|
|
520
525
|
.returning(EVENT_COLUMNS)
|
|
521
526
|
.execute();
|
|
527
|
+
for (const row of inserted) {
|
|
528
|
+
if (row.type === "run_started")
|
|
529
|
+
afterCommit(() => recordRun("started"));
|
|
530
|
+
}
|
|
531
|
+
// Only the inserted rows count. Replay seeds bypass the live append, and an event
|
|
532
|
+
// referencing a run of another conversation cannot settle usage for this conversation.
|
|
533
|
+
const actors = new Map();
|
|
534
|
+
const freshUsage = inserted.flatMap((row) => {
|
|
535
|
+
if (row.type !== "usage")
|
|
536
|
+
return [];
|
|
537
|
+
const event = toEvent(row, true);
|
|
538
|
+
if (event.type !== "usage")
|
|
539
|
+
return [];
|
|
540
|
+
const inputIndex = fresh[Number(row.seq) - base - 1];
|
|
541
|
+
const sourceRunId = event.runId ??
|
|
542
|
+
(inputIndex === undefined ? undefined : events[inputIndex]?.usageAccountRunId);
|
|
543
|
+
return [{ event, sourceRunId }];
|
|
544
|
+
});
|
|
545
|
+
// All rows share the transaction timestamp and conversation shard. Resolve member keys
|
|
546
|
+
// before taking locks so appends acquire buckets and member rows in a stable order.
|
|
547
|
+
const settlements = [];
|
|
548
|
+
const claim = currentExecutionClaim();
|
|
549
|
+
let conversationAccount;
|
|
550
|
+
for (const { event, sourceRunId } of freshUsage) {
|
|
551
|
+
let accountId;
|
|
552
|
+
if (sourceRunId === undefined) {
|
|
553
|
+
conversationAccount ??= (await t
|
|
554
|
+
.selectFrom("conversations")
|
|
555
|
+
.select("account_id")
|
|
556
|
+
.where("id", "=", conversationId)
|
|
557
|
+
.where("org_id", "=", conv.org_id)
|
|
558
|
+
.executeTakeFirstOrThrow()).account_id;
|
|
559
|
+
accountId = conversationAccount;
|
|
560
|
+
}
|
|
561
|
+
else {
|
|
562
|
+
// Device review can surface its usage on the root log while a child owns the run.
|
|
563
|
+
const owningConversation = event.payload.purpose === "review" &&
|
|
564
|
+
claim?.runId === sourceRunId &&
|
|
565
|
+
claim.rootId === conversationId &&
|
|
566
|
+
claim.orgId === conv.org_id
|
|
567
|
+
? claim.conversationId
|
|
568
|
+
: conversationId;
|
|
569
|
+
const principalKey = `${owningConversation}/${sourceRunId}`;
|
|
570
|
+
if (!actors.has(principalKey)) {
|
|
571
|
+
const run = await t
|
|
572
|
+
.selectFrom("runs")
|
|
573
|
+
.select(["id", "trigger_account_id", "budget_run_id", "compact_origin"])
|
|
574
|
+
.where("id", "=", sourceRunId)
|
|
575
|
+
.where("conversation_id", "=", owningConversation)
|
|
576
|
+
.executeTakeFirst();
|
|
577
|
+
actors.set(principalKey, run && {
|
|
578
|
+
accountId: (await runPrincipalAccount(t.db, run, owningConversation === conversationId ? conv.kind : "subagent")) ?? null,
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
const actor = actors.get(principalKey);
|
|
582
|
+
if (!actor)
|
|
583
|
+
continue;
|
|
584
|
+
accountId = actor.accountId;
|
|
585
|
+
}
|
|
586
|
+
settlements.push({
|
|
587
|
+
orgId: conv.org_id,
|
|
588
|
+
accountId,
|
|
589
|
+
usageSourceId: conversationId,
|
|
590
|
+
at: event.createdAt,
|
|
591
|
+
usage: event.payload,
|
|
592
|
+
snapshot: event.payload.priceSnapshot ?? null,
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
settlements.sort((a, b) => settledUsageBucket(a.snapshot).localeCompare(settledUsageBucket(b.snapshot), "en") ||
|
|
596
|
+
(a.accountId ?? "").localeCompare(b.accountId ?? "", "en"));
|
|
597
|
+
for (const entry of settlements)
|
|
598
|
+
await recordSettledModelUsage(t.db, entry);
|
|
522
599
|
if (conv.im)
|
|
523
600
|
await oweDelivery(this.outbox, { conversationId, orgId: conv.org_id, seq: toSeq });
|
|
524
601
|
const bySeq = new Map(inserted.map((r) => [Number(r.seq), toEvent(r)]));
|
|
@@ -2143,6 +2143,17 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
|
|
|
2143
2143
|
error: z.ZodObject<{
|
|
2144
2144
|
code: z.ZodString;
|
|
2145
2145
|
message: z.ZodString;
|
|
2146
|
+
budget: z.ZodOptional<z.ZodObject<{
|
|
2147
|
+
scope: z.ZodOptional<z.ZodEnum<{
|
|
2148
|
+
member: "member";
|
|
2149
|
+
org: "org";
|
|
2150
|
+
}>>;
|
|
2151
|
+
constraint: z.ZodOptional<z.ZodEnum<{
|
|
2152
|
+
spend: "spend";
|
|
2153
|
+
tokens: "tokens";
|
|
2154
|
+
}>>;
|
|
2155
|
+
resetAt: z.ZodOptional<z.ZodISODateTime>;
|
|
2156
|
+
}, z.core.$strip>>;
|
|
2146
2157
|
}, z.core.$strip>;
|
|
2147
2158
|
}, z.core.$strip>;
|
|
2148
2159
|
}, z.core.$strip>, z.ZodObject<{
|
|
@@ -1961,7 +1961,19 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
|
|
|
1961
1961
|
reason: z.enum(["completed", "max_steps", "max_duration", "budget", "max_output"]),
|
|
1962
1962
|
consumedUpToSeq: seqNo,
|
|
1963
1963
|
})),
|
|
1964
|
-
ev("run_failed", z.object({
|
|
1964
|
+
ev("run_failed", z.object({
|
|
1965
|
+
error: z.object({
|
|
1966
|
+
code: z.string(),
|
|
1967
|
+
message: z.string(),
|
|
1968
|
+
budget: z
|
|
1969
|
+
.object({
|
|
1970
|
+
scope: z.enum(["org", "member"]).optional(),
|
|
1971
|
+
constraint: z.enum(["tokens", "spend"]).optional(),
|
|
1972
|
+
resetAt: z.iso.datetime().optional(),
|
|
1973
|
+
})
|
|
1974
|
+
.optional(),
|
|
1975
|
+
}),
|
|
1976
|
+
})),
|
|
1965
1977
|
ev("run_aborted", z.object({
|
|
1966
1978
|
byAccountId: z.string().nullable(),
|
|
1967
1979
|
/**
|
|
@@ -28,6 +28,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
|
28
28
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
29
29
|
import { QueueModule } from "../infra/queue/queue.module.js";
|
|
30
30
|
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
31
|
+
import { ModelBudgetRefused } from "../models/budget-admission.js";
|
|
31
32
|
import { OrgSettingsModule, OrgSettingsService } from "../orgs/settings.service.js";
|
|
32
33
|
import { resolveCompactionSettings } from "../runtime/compaction-settings.service.js";
|
|
33
34
|
import { fireObserve, hookDeniedAudit, hookDeniedEvent, } from "../runtime/hook-calls.js";
|
|
@@ -220,6 +221,8 @@ let PromptSuggestionGenerator = class PromptSuggestionGenerator {
|
|
|
220
221
|
}, signal, this.log);
|
|
221
222
|
}
|
|
222
223
|
catch (err) {
|
|
224
|
+
if (err instanceof ModelBudgetRefused)
|
|
225
|
+
return;
|
|
223
226
|
if (!(err instanceof ModelRequestDenied))
|
|
224
227
|
throw err;
|
|
225
228
|
await this.recordDenial(scope, err.verdict);
|
|
@@ -408,6 +411,7 @@ let PromptSuggestionGenerator = class PromptSuggestionGenerator {
|
|
|
408
411
|
async writeUsage(conversationId, runId, u) {
|
|
409
412
|
const event = {
|
|
410
413
|
type: "usage",
|
|
414
|
+
usageAccountRunId: runId,
|
|
411
415
|
idemKey: usageIdemKey(runId),
|
|
412
416
|
payload: {
|
|
413
417
|
step: 0,
|
|
@@ -20,6 +20,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
|
20
20
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
21
21
|
import { QueueModule } from "../infra/queue/queue.module.js";
|
|
22
22
|
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
23
|
+
import { ModelBudgetRefused } from "../models/budget-admission.js";
|
|
23
24
|
import { ModelsModule } from "../models/models.module.js";
|
|
24
25
|
import { ModelPurposesService, PurposeAttemptError } from "../models/purposes.js";
|
|
25
26
|
import { fireObserve, hookDeniedAudit, hookDeniedEvent, } from "../runtime/hook-calls.js";
|
|
@@ -239,8 +240,8 @@ export async function runTitleJob(d, conversationId, attempt) {
|
|
|
239
240
|
});
|
|
240
241
|
}
|
|
241
242
|
catch (err) {
|
|
242
|
-
if (err instanceof TitleDenied) {
|
|
243
|
-
//
|
|
243
|
+
if (err instanceof TitleDenied || err instanceof ModelBudgetRefused) {
|
|
244
|
+
// Request-policy and budget refusals end automatic attempts for this title.
|
|
244
245
|
await d.db
|
|
245
246
|
.updateTable("conversations")
|
|
246
247
|
.set({ title_attempts: TITLE_MAX_ATTEMPTS })
|
package/dist/ctx/create-ctx.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { type EmbedClaims, type ExtensionContext, type ExtensionManifest, type E
|
|
|
2
2
|
import type { Redis } from "ioredis";
|
|
3
3
|
import { Kysely } from "kysely";
|
|
4
4
|
import type { TriggerEventsService } from "../automations/events/trigger-events.service.js";
|
|
5
|
+
import { pluginSchemaName } from "../db/extension-db.js";
|
|
5
6
|
import type { DeviceAccessService } from "../device-access/device-access.service.js";
|
|
6
7
|
import type { DialInAccess } from "../dial-in/access.js";
|
|
7
8
|
import { type RegisteredHook } from "../extensions/hooks.js";
|
|
@@ -20,6 +21,7 @@ import { type UiActionHandler, type UiQueryHandler, type UiRender } from "../ui/
|
|
|
20
21
|
import { type BusSubscriber } from "./bus.js";
|
|
21
22
|
import { type ExtensionNetServices } from "./net.js";
|
|
22
23
|
import { type Keyring } from "./secrets.js";
|
|
24
|
+
export { pluginSchemaName };
|
|
23
25
|
/** 内核提供给插件宿主的共享依赖。 */
|
|
24
26
|
export interface KernelDeps {
|
|
25
27
|
db: Kysely<any>;
|
|
@@ -184,8 +186,6 @@ export declare function currentOrgRole(db: KernelDeps["db"], plugin: string, org
|
|
|
184
186
|
* token and the platform refresh stream re-check.
|
|
185
187
|
*/
|
|
186
188
|
export declare function currentPlatformAccount(db: KernelDeps["db"], accountId: string): Promise<boolean>;
|
|
187
|
-
/** 插件的 PG schema 名:`plugin_<name>`,name 中的 `-` 换成 `_`。 */
|
|
188
|
-
export declare function pluginSchemaName(name: string): string;
|
|
189
189
|
/** What {@link resolveUiSlots} returns for a manifest. */
|
|
190
190
|
export type UiResolution = ReturnType<typeof resolveUiSlots>;
|
|
191
191
|
/** 内核视角的插件 ctx:插件契约之外还带宿主要用的登记信息与关闭方法。 */
|
|
@@ -272,4 +272,5 @@ export declare function createExtensionContext(deps: KernelDeps, manifest: Exten
|
|
|
272
272
|
/** The package this instance was loaded from (null: not from an install record). */
|
|
273
273
|
identity?: {
|
|
274
274
|
sha256: string | null;
|
|
275
|
+
db?: Kysely<any>;
|
|
275
276
|
}): KernelExtensionContext;
|
package/dist/ctx/create-ctx.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { CtxReadError, DEVICE_PROVIDER_EXTENSION_POINT, DeviceAccessError, EXTENSION_POINTS, ExtensionPermissionError, ExtensionPointUnavailableError, FILE_PREVIEW_EXTENSION_POINT, InboxError, OBJECT_STORE_EXTENSION_POINT, parseExtensionPoint, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, TriggerError, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import { Command, ConnectionBuilder, ControlledTransactionBuilder, Kysely, TransactionBuilder, } from "kysely";
|
|
3
3
|
import { conversationTopic } from "../conversations/event-log.js";
|
|
4
|
+
import { pluginSchemaName } from "../db/extension-db.js";
|
|
4
5
|
import { kernelDb } from "../db/kernel-schema.js";
|
|
5
6
|
import { ApiError } from "../errors.js";
|
|
6
7
|
import { enabledExtensionsQuery, isExtensionEnabled } from "../extensions/enabled.js";
|
|
@@ -18,6 +19,7 @@ import { createLock } from "./lock.js";
|
|
|
18
19
|
import { createExtensionNet } from "./net.js";
|
|
19
20
|
import { createQueue } from "./queue.js";
|
|
20
21
|
import { createSecrets } from "./secrets.js";
|
|
22
|
+
export { pluginSchemaName };
|
|
21
23
|
/**
|
|
22
24
|
* A plain-data copy of an emitted event, taken once at the ctx boundary (check-then-use): every
|
|
23
25
|
* own enumerable field is read once (a getter cannot change a value after it was validated),
|
|
@@ -138,10 +140,6 @@ async function recordDenial(deps, plugin, item) {
|
|
|
138
140
|
deps.log.warn("plugin permission denial audit failed", { plugin, item, err: e });
|
|
139
141
|
}
|
|
140
142
|
}
|
|
141
|
-
/** 插件的 PG schema 名:`plugin_<name>`,name 中的 `-` 换成 `_`。 */
|
|
142
|
-
export function pluginSchemaName(name) {
|
|
143
|
-
return `plugin_${name.replaceAll("-", "_")}`;
|
|
144
|
-
}
|
|
145
143
|
/**
|
|
146
144
|
* 包装插件拿到的 Kysely:`destroy`(及 `Symbol.asyncDispose`)换成抛错的函数(连接池归内核所有,插件销毁会拖垮整个进程的 DB 访问),
|
|
147
145
|
* 其余属性透传。方法绑定到原对象(Kysely 用私有字段,以 Proxy 作 this 调用会失败)。
|
|
@@ -763,7 +761,7 @@ identity = { sha256: null }) {
|
|
|
763
761
|
},
|
|
764
762
|
add: queue.add,
|
|
765
763
|
},
|
|
766
|
-
db: guardDb(deps.db.withSchema(pluginSchemaName(name)), name),
|
|
764
|
+
db: guardDb((identity.db ?? deps.db).withSchema(pluginSchemaName(name)), name),
|
|
767
765
|
http: {
|
|
768
766
|
route(method, path, handler) {
|
|
769
767
|
if (typeof path !== "string" || !path.startsWith("/")) {
|
|
@@ -1037,8 +1035,13 @@ identity = { sha256: null }) {
|
|
|
1037
1035
|
key: r.key,
|
|
1038
1036
|
err,
|
|
1039
1037
|
}));
|
|
1040
|
-
|
|
1041
|
-
|
|
1038
|
+
try {
|
|
1039
|
+
await queue.close();
|
|
1040
|
+
await Promise.allSettled([...audits]);
|
|
1041
|
+
}
|
|
1042
|
+
finally {
|
|
1043
|
+
await identity.db?.destroy();
|
|
1044
|
+
}
|
|
1042
1045
|
})();
|
|
1043
1046
|
return closing;
|
|
1044
1047
|
},
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import pg from "pg";
|
|
2
|
+
import type { KernelConfig } from "../config/schema.js";
|
|
3
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
4
|
+
export type ExtensionDbConnection = {
|
|
5
|
+
login: string;
|
|
6
|
+
url: string;
|
|
7
|
+
separate: boolean;
|
|
8
|
+
};
|
|
9
|
+
/** Kernel-owned credentials, resolved from the canonical extension name. */
|
|
10
|
+
export interface ExtensionDbIdentity {
|
|
11
|
+
resolve(name: string): ExtensionDbConnection;
|
|
12
|
+
readonly sharedLogin?: string | undefined;
|
|
13
|
+
}
|
|
14
|
+
export declare class ConfiguredExtensionDbIdentity implements ExtensionDbIdentity {
|
|
15
|
+
private readonly identity;
|
|
16
|
+
constructor(config: KernelConfigService);
|
|
17
|
+
get sharedLogin(): string | undefined;
|
|
18
|
+
resolve(name: string): ExtensionDbConnection;
|
|
19
|
+
}
|
|
20
|
+
export declare function extensionDbIdentity(db: Pick<KernelConfig["db"], "url" | "extensionsUrl">): ExtensionDbIdentity;
|
|
21
|
+
export declare function pluginSchemaName(name: string): string;
|
|
22
|
+
export declare function assertExtensionSession(client: pg.ClientBase, login: string): Promise<void>;
|
|
23
|
+
/** A missing schema is normal before a plugin's first migration. */
|
|
24
|
+
export declare function assertExtensionSchemaOwner(client: pg.ClientBase, schema: string, login: string): Promise<void>;
|
|
25
|
+
/** One small, scope-aware pool per active extension instance. The host owns its lifetime. */
|
|
26
|
+
export declare function extensionDbPool(identity: ExtensionDbConnection, name: string, config: {
|
|
27
|
+
connectTimeoutMs?: number | undefined;
|
|
28
|
+
rls: KernelConfig["db"]["rls"];
|
|
29
|
+
extensionPoolMax: number;
|
|
30
|
+
}, onError?: (error: Error) => void): import("kysely").Kysely<any>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
11
|
+
import pg from "pg";
|
|
12
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
13
|
+
import { createDb } from "./pool.js";
|
|
14
|
+
let ConfiguredExtensionDbIdentity = class ConfiguredExtensionDbIdentity {
|
|
15
|
+
identity;
|
|
16
|
+
constructor(config) {
|
|
17
|
+
this.identity = extensionDbIdentity(config.get().db);
|
|
18
|
+
}
|
|
19
|
+
get sharedLogin() {
|
|
20
|
+
return this.identity.sharedLogin;
|
|
21
|
+
}
|
|
22
|
+
resolve(name) {
|
|
23
|
+
return this.identity.resolve(name);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
ConfiguredExtensionDbIdentity = __decorate([
|
|
27
|
+
Injectable(),
|
|
28
|
+
__param(0, Inject(KernelConfigService))
|
|
29
|
+
], ConfiguredExtensionDbIdentity);
|
|
30
|
+
export { ConfiguredExtensionDbIdentity };
|
|
31
|
+
export function extensionDbIdentity(db) {
|
|
32
|
+
const url = db.extensionsUrl ?? db.url;
|
|
33
|
+
const separate = db.extensionsUrl !== undefined;
|
|
34
|
+
let login;
|
|
35
|
+
try {
|
|
36
|
+
login = new pg.Client({ connectionString: url }).user;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
throw new Error("Invalid PostgreSQL connection URL for extensions");
|
|
40
|
+
}
|
|
41
|
+
if (!login)
|
|
42
|
+
throw new Error("PostgreSQL connection needs a login");
|
|
43
|
+
return { sharedLogin: separate ? login : undefined, resolve: () => ({ login, url, separate }) };
|
|
44
|
+
}
|
|
45
|
+
export function pluginSchemaName(name) {
|
|
46
|
+
return `plugin_${name.replaceAll("-", "_")}`;
|
|
47
|
+
}
|
|
48
|
+
const extensionLoginCheck = `
|
|
49
|
+
select r.rolcanlogin and not (r.rolsuper or r.rolbypassrls or r.rolcreaterole or r.rolreplication or r.rolcreatedb)
|
|
50
|
+
and not exists (select from pg_catalog.pg_auth_members where member = r.oid)
|
|
51
|
+
and not coalesce((
|
|
52
|
+
select pg_catalog.has_schema_privilege(r.oid, n.oid, 'USAGE,CREATE')
|
|
53
|
+
from pg_catalog.pg_namespace n where n.nspname = 'capybara'
|
|
54
|
+
), true)
|
|
55
|
+
and not coalesce((
|
|
56
|
+
select pg_catalog.has_schema_privilege(r.oid, n.oid, 'CREATE')
|
|
57
|
+
from pg_catalog.pg_namespace n where n.nspname = 'public'
|
|
58
|
+
), false) as isolated
|
|
59
|
+
from pg_catalog.pg_roles r where r.rolname = $1
|
|
60
|
+
`;
|
|
61
|
+
export async function assertExtensionSession(client, login) {
|
|
62
|
+
const { rows: [actual], } = await client.query("select current_user as login");
|
|
63
|
+
const { rows: [role], } = await client.query(extensionLoginCheck, [login]);
|
|
64
|
+
if (actual?.login !== login || !role?.isolated) {
|
|
65
|
+
throw new Error("db.extensionsUrl must authenticate as a restricted extension login with no access to capybara");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** A missing schema is normal before a plugin's first migration. */
|
|
69
|
+
export async function assertExtensionSchemaOwner(client, schema, login) {
|
|
70
|
+
const { rows: [namespace], } = await client.query(`select pg_catalog.pg_get_userbyid(nspowner) as owner
|
|
71
|
+
from pg_catalog.pg_namespace where nspname = $1`, [schema]);
|
|
72
|
+
if (namespace && namespace.owner !== login) {
|
|
73
|
+
throw new Error(`Extension schema ${schema} is owned by ${namespace.owner}, expected ${login}. Run capybara migrate with the owner URL to transfer plugin schemas.`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** One small, scope-aware pool per active extension instance. The host owns its lifetime. */
|
|
77
|
+
export function extensionDbPool(identity, name, config, onError) {
|
|
78
|
+
// Names come from validated manifests. Quote regardless so review and maintenance paths are safe too.
|
|
79
|
+
const schema = pluginSchemaName(name);
|
|
80
|
+
const searchPath = `"${schema.replaceAll('"', '""')}", public`;
|
|
81
|
+
return createDb(identity.url, config.extensionPoolMax, onError, {
|
|
82
|
+
connectTimeoutMs: config.connectTimeoutMs,
|
|
83
|
+
rls: config.rls,
|
|
84
|
+
closeActiveOnDestroy: true,
|
|
85
|
+
onConnect: async (client) => {
|
|
86
|
+
await assertExtensionSession(client, identity.login);
|
|
87
|
+
await assertExtensionSchemaOwner(client, schema, identity.login);
|
|
88
|
+
await client.query("select pg_catalog.set_config('search_path', $1, false)", [searchPath]);
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type ExtensionDbIdentity } from "./extension-db.js";
|
|
2
|
+
/**
|
|
3
|
+
* One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
|
|
4
|
+
* to transfer ownership. Run before starting replicas with the new extension identity.
|
|
5
|
+
*/
|
|
6
|
+
export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number): Promise<void>;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import pg from "pg";
|
|
3
|
+
import { assertExtensionSession, pluginSchemaName, } from "./extension-db.js";
|
|
4
|
+
import { assertSameMigrationDatabase, lockMigrationSchema } from "./migrator.js";
|
|
5
|
+
import { pgConnectOptions } from "./pool.js";
|
|
6
|
+
async function transferExtensionSchema(client, schema, target, sources) {
|
|
7
|
+
await lockMigrationSchema(client, schema, "transaction");
|
|
8
|
+
const { rows: [namespace], } = await client.query(`select oid, pg_catalog.pg_get_userbyid(nspowner) as owner
|
|
9
|
+
from pg_catalog.pg_namespace where nspname = $1`, [schema]);
|
|
10
|
+
if (!namespace)
|
|
11
|
+
return;
|
|
12
|
+
if (namespace.owner !== target && !sources.has(namespace.owner)) {
|
|
13
|
+
throw new Error(`Unexpected owner ${namespace.owner} for extension schema ${schema}`);
|
|
14
|
+
}
|
|
15
|
+
const { rows: objects } = await client.query(`
|
|
16
|
+
with objects(classid, objid) as (
|
|
17
|
+
select 'pg_class'::regclass::oid, oid from pg_class
|
|
18
|
+
where relnamespace = $1::oid and relkind in ('r', 'p', 'v', 'm', 'S', 'f')
|
|
19
|
+
union
|
|
20
|
+
select 'pg_proc'::regclass::oid, oid from pg_proc where pronamespace = $1::oid
|
|
21
|
+
union
|
|
22
|
+
select d.classid, d.objid from pg_depend d
|
|
23
|
+
where d.refclassid = 'pg_namespace'::regclass and d.refobjid = $1::oid
|
|
24
|
+
and d.objsubid = 0 and d.deptype = 'n' and d.classid <> 'pg_extension'::regclass
|
|
25
|
+
)
|
|
26
|
+
select object.identity,
|
|
27
|
+
case
|
|
28
|
+
when c.relkind in ('r', 'p') then 'TABLE'
|
|
29
|
+
when c.relkind = 'v' then 'VIEW'
|
|
30
|
+
when c.relkind = 'm' then 'MATERIALIZED VIEW'
|
|
31
|
+
when c.relkind = 'f' then 'FOREIGN TABLE'
|
|
32
|
+
when c.relkind = 'S' then 'SEQUENCE'
|
|
33
|
+
when p.oid is not null then 'ROUTINE'
|
|
34
|
+
when t.typtype = 'd' then 'DOMAIN'
|
|
35
|
+
when t.oid is not null then 'TYPE'
|
|
36
|
+
end as kind,
|
|
37
|
+
pg_get_userbyid(coalesce(c.relowner, p.proowner, t.typowner)) as owner,
|
|
38
|
+
c.relkind = 'S' and exists (
|
|
39
|
+
select from pg_depend d where d.classid = 'pg_class'::regclass and d.objid = c.oid
|
|
40
|
+
and d.refclassid = 'pg_class'::regclass and d.deptype in ('a', 'i')
|
|
41
|
+
) as attached_sequence,
|
|
42
|
+
exists (
|
|
43
|
+
select from pg_depend d where d.classid = o.classid and d.objid = o.objid
|
|
44
|
+
and d.objsubid = 0 and d.refclassid = 'pg_extension'::regclass and d.deptype = 'e'
|
|
45
|
+
) as extension_member
|
|
46
|
+
from objects o
|
|
47
|
+
cross join lateral pg_identify_object(o.classid, o.objid, 0) object
|
|
48
|
+
left join pg_class c on o.classid = 'pg_class'::regclass and c.oid = o.objid
|
|
49
|
+
left join pg_proc p on o.classid = 'pg_proc'::regclass and p.oid = o.objid
|
|
50
|
+
left join pg_type t on o.classid = 'pg_type'::regclass and t.oid = o.objid
|
|
51
|
+
order by object.identity
|
|
52
|
+
`, [namespace.oid]);
|
|
53
|
+
const unexpected = objects.filter((object) => !object.kind ||
|
|
54
|
+
object.extension_member ||
|
|
55
|
+
(object.owner !== target && object.owner !== namespace.owner));
|
|
56
|
+
if (unexpected.length) {
|
|
57
|
+
const names = unexpected.map((object) => `${object.identity} (owner ${object.owner ?? "unknown"})`);
|
|
58
|
+
throw new Error(`Unexpected objects in extension schema ${schema}: ${names.join(", ")}`);
|
|
59
|
+
}
|
|
60
|
+
const quotedTarget = pg.escapeIdentifier(target);
|
|
61
|
+
if (namespace.owner !== target) {
|
|
62
|
+
await client.query(`alter schema ${pg.escapeIdentifier(schema)} owner to ${quotedTarget}`);
|
|
63
|
+
}
|
|
64
|
+
// PostgreSQL moves table-owned sequences, row types and indexes with their parent table.
|
|
65
|
+
for (const object of objects) {
|
|
66
|
+
if (object.kind && object.owner !== target && !object.attached_sequence) {
|
|
67
|
+
// Kind is from the fixed catalog mapping. PostgreSQL returns the quoted object identity.
|
|
68
|
+
await client.query(`alter ${object.kind} ${object.identity} owner to ${quotedTarget}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
|
|
73
|
+
const client = new pg.Client({
|
|
74
|
+
connectionString: target.url,
|
|
75
|
+
...pgConnectOptions({ connectTimeoutMs }),
|
|
76
|
+
});
|
|
77
|
+
client.on("error", () => { });
|
|
78
|
+
try {
|
|
79
|
+
await client.connect();
|
|
80
|
+
await assertExtensionSession(client, target.login);
|
|
81
|
+
await assertSameMigrationDatabase(owner, client);
|
|
82
|
+
}
|
|
83
|
+
catch (cause) {
|
|
84
|
+
throw new Error(`Cannot verify extension database login ${target.login}. Check db.extensionsUrl and use the same database as db.url.`, { cause });
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
await client.end();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
|
|
92
|
+
* to transfer ownership. Run before starting replicas with the new extension identity.
|
|
93
|
+
*/
|
|
94
|
+
export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs) {
|
|
95
|
+
const owner = new pg.Client({
|
|
96
|
+
connectionString: bootstrapUrl,
|
|
97
|
+
...pgConnectOptions({ connectTimeoutMs }),
|
|
98
|
+
});
|
|
99
|
+
owner.on("error", () => { });
|
|
100
|
+
try {
|
|
101
|
+
await owner.connect();
|
|
102
|
+
await owner.query("begin");
|
|
103
|
+
try {
|
|
104
|
+
await owner.query("set local search_path = pg_catalog");
|
|
105
|
+
await owner.query("set local lock_timeout = '30s'");
|
|
106
|
+
const { rows: [legacy], } = await owner.query("select current_user as login");
|
|
107
|
+
if (!legacy)
|
|
108
|
+
throw new Error("Could not verify the schema transfer login");
|
|
109
|
+
const { rows: registered } = await owner.query(`select name from capybara.extension_name_owners
|
|
110
|
+
union select name from capybara.extension_installs`);
|
|
111
|
+
const names = new Set([...declaredNames, ...registered.map((row) => row.name)]);
|
|
112
|
+
const resolved = [...names].sort().map((name) => {
|
|
113
|
+
if (!EXTENSION_NAME_RE.test(name))
|
|
114
|
+
throw new Error(`Invalid extension name: ${name}`);
|
|
115
|
+
return { schema: pluginSchemaName(name), target: identity.resolve(name) };
|
|
116
|
+
});
|
|
117
|
+
const sources = new Set([legacy.login, ...resolved.map(({ target }) => target.login)]);
|
|
118
|
+
if (identity.sharedLogin !== undefined)
|
|
119
|
+
sources.add(identity.sharedLogin);
|
|
120
|
+
const targets = resolved.filter(({ target }) => target.separate);
|
|
121
|
+
const validated = new Set();
|
|
122
|
+
for (const { target } of targets) {
|
|
123
|
+
if (validated.has(target.url))
|
|
124
|
+
continue;
|
|
125
|
+
await confirmTargetDatabase(owner, target, connectTimeoutMs);
|
|
126
|
+
validated.add(target.url);
|
|
127
|
+
}
|
|
128
|
+
for (const { schema, target } of targets) {
|
|
129
|
+
await transferExtensionSchema(owner, schema, target.login, sources);
|
|
130
|
+
}
|
|
131
|
+
await owner.query("commit");
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
await owner.query("rollback").catch(() => { });
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
await owner.end();
|
|
140
|
+
}
|
|
141
|
+
}
|