@capybara-hq/kernel 0.1.0-rc.116 → 0.1.0-rc.118
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/usage.service.d.ts +4 -2
- package/dist/admin/usage.service.js +35 -15
- package/dist/catalog/catalog-content.d.ts +11 -0
- package/dist/catalog/catalog-content.js +1 -0
- package/dist/catalog/component-scope.service.js +2 -1
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/catalog/org-catalog.service.d.ts +1 -0
- package/dist/catalog/org-catalog.service.js +44 -2
- package/dist/catalog/plugin-install.d.ts +1 -0
- package/dist/catalog/plugin-install.js +11 -1
- package/dist/catalog/schema-path.d.ts +4 -6
- package/dist/catalog/schema-path.js +48 -21
- package/dist/channels/outbound.d.ts +5 -0
- package/dist/channels/outbound.js +6 -1
- package/dist/channels/supervisor.js +3 -0
- package/dist/conversations/conversations.controller.d.ts +1 -1
- package/dist/conversations/conversations.controller.js +1 -1
- package/dist/conversations/conversations.service.d.ts +4 -2
- package/dist/conversations/conversations.service.js +17 -3
- package/dist/conversations/events.d.ts +10 -1
- package/dist/conversations/events.js +8 -1
- package/dist/db/kernel-schema.d.ts +15 -1
- package/dist/devices/devices.controller.d.ts +5 -0
- package/dist/devices/devices.controller.js +20 -2
- package/dist/devices/devices.service.d.ts +11 -1
- package/dist/devices/devices.service.js +20 -0
- package/dist/evals/plan.d.ts +3 -1
- package/dist/evals/plan.js +25 -5
- package/dist/evals/runs.service.js +3 -2
- package/dist/evals/trajectory.js +1 -0
- package/dist/files/blob-references.d.ts +8 -0
- package/dist/files/blob-references.js +19 -0
- package/dist/files/blob-sweep.job.js +5 -23
- package/dist/files/library-files.service.js +8 -4
- package/dist/models/cache-write-usage.d.ts +3 -0
- package/dist/models/cache-write-usage.js +26 -0
- package/dist/models/images.js +5 -1
- package/dist/models/prices.d.ts +8 -6
- package/dist/models/prices.js +28 -3
- package/dist/orgs/settings.controller.d.ts +4 -17
- package/dist/orgs/settings.controller.js +5 -9
- package/dist/orgs/settings.service.d.ts +12 -0
- package/dist/orgs/settings.service.js +24 -0
- package/dist/platform/exclusions.js +11 -0
- package/dist/platform/ops/admin.ops.js +2 -2
- package/dist/platform/ops/conversations.ops.js +1 -1
- package/dist/platform/ops/devices.ops.js +21 -0
- package/dist/platform/ops/org-settings.ops.d.ts +3 -1
- package/dist/platform/ops/org-settings.ops.js +10 -10
- package/dist/runtime/context/build.d.ts +2 -0
- package/dist/runtime/context/build.js +9 -1
- package/dist/runtime/usage-report.js +3 -0
- package/dist/sandbox/legacy-retirement.d.ts +15 -0
- package/dist/sandbox/legacy-retirement.js +243 -3
- package/dist/sandbox/permission-instance-writes.d.ts +4 -1
- package/dist/sandbox/permission-instance-writes.js +55 -1
- package/dist/sandbox/providers.d.ts +6 -1
- package/dist/sandbox/providers.js +15 -1
- package/dist/sandbox/sandbox.service.d.ts +19 -3
- package/dist/sandbox/sandbox.service.js +167 -9
- package/dist/tools/builtins/sandbox/common.d.ts +2 -7
- package/dist/tools/builtins/sandbox/common.js +14 -8
- package/dist/tools/connector-tools-jobs.d.ts +3 -2
- package/dist/tools/connectors.service.d.ts +3 -1
- package/dist/tools/connectors.service.js +64 -12
- package/dist/tools/drift.d.ts +1 -1
- package/dist/tools/drift.js +13 -13
- package/dist/tools/pipeline.d.ts +4 -0
- package/dist/tools/pipeline.js +55 -16
- package/dist/ui/admin-ui.controller.d.ts +5 -2
- package/dist/ui/admin-ui.controller.js +14 -1
- package/dist/ui/ui.schemas.d.ts +9 -0
- package/dist/ui/ui.schemas.js +2 -0
- package/dist/ui/views.d.ts +1 -1
- package/dist/ui/views.js +4 -5
- package/package.json +3 -3
- package/src/migrations/0202_connector_endpoint_changed_at.sql +1 -0
- package/src/migrations/0203_model_cache_write_pricing.sql +5 -0
- package/src/migrations/0204_device_instance_retirement_identities.sql +46 -0
|
@@ -542,6 +542,7 @@ export const ContentBlockSchema = z.discriminatedUnion("type", [
|
|
|
542
542
|
source: RefMediaSourceSchema,
|
|
543
543
|
name: MediaNameSchema.optional(),
|
|
544
544
|
size: MediaBlockSizeSchema,
|
|
545
|
+
readByFileId: z.literal(true).optional(),
|
|
545
546
|
}),
|
|
546
547
|
z.object({
|
|
547
548
|
type: z.literal("file"),
|
|
@@ -549,6 +550,7 @@ export const ContentBlockSchema = z.discriminatedUnion("type", [
|
|
|
549
550
|
source: RefMediaSourceSchema,
|
|
550
551
|
name: MediaNameSchema.optional(),
|
|
551
552
|
size: MediaBlockSizeSchema,
|
|
553
|
+
readByFileId: z.literal(true).optional(),
|
|
552
554
|
}),
|
|
553
555
|
]);
|
|
554
556
|
const STOP_REASONS = ["end_turn", "tool_use", "max_tokens", "refusal", "other"];
|
|
@@ -870,7 +872,12 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
|
|
|
870
872
|
* port it asked to reach on the person's own device. Not model-visible.
|
|
871
873
|
*/
|
|
872
874
|
loopback: z
|
|
873
|
-
.object({
|
|
875
|
+
.object({
|
|
876
|
+
service: z.string(),
|
|
877
|
+
port: z.number().int().min(1).max(65535),
|
|
878
|
+
/** The attempt that reran under a live grant already held (ready-grant rerun). */
|
|
879
|
+
readyRerunAttempt: z.number().int().positive().optional(),
|
|
880
|
+
})
|
|
874
881
|
.optional(),
|
|
875
882
|
})),
|
|
876
883
|
ev("permission_profile_changed", z.object({
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ConversationSource, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SkillInvocation, TriggerFactValue, TriggerSubject } from "@capybara-hq/plugin-sdk";
|
|
1
|
+
import type { CacheWriteByTtl, ConversationSource, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SkillInvocation, TriggerFactValue, TriggerSubject } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import type { ColumnType, Generated, Kysely } from "kysely";
|
|
3
3
|
import type { ModelRef } from "../agents/definition.js";
|
|
4
4
|
import type { AutomationChat, AutomationEventMarker, AutomationMode, AutomationOrigin, AutomationPauseReason, AutomationPrincipal, AutomationStatus, AutomationTrigger, AutomationUnattendedAsk, ScheduleMarker, TaskRunSkipReason, TaskRunStatus } from "../automations/types.js";
|
|
@@ -648,6 +648,8 @@ export interface ConnectorsTable {
|
|
|
648
648
|
deleted_at: TsNullable;
|
|
649
649
|
/** 0015:最近一次成功拿到工具清单的时间;为空 = 从未拍过快照(首个快照按安装处理)。 */
|
|
650
650
|
tools_synced_at: TsNullable;
|
|
651
|
+
/** When the current endpoint was first written. Null for rows from before migration 0202. */
|
|
652
|
+
endpoint_changed_at: TsNullable;
|
|
651
653
|
/**
|
|
652
654
|
* 0037, renamed in 0042: the source item (an app's template records the app item) and version
|
|
653
655
|
* when installed from a catalog template.
|
|
@@ -1339,6 +1341,7 @@ export interface ModelPricesTable {
|
|
|
1339
1341
|
output_per_mtok: Numeric;
|
|
1340
1342
|
cache_read_per_mtok: NumericNullable;
|
|
1341
1343
|
cache_write_per_mtok: NumericNullable;
|
|
1344
|
+
cache_write_per_mtok_by_ttl: Json<Record<string, number>>;
|
|
1342
1345
|
updated_by: string | null;
|
|
1343
1346
|
updated_at: Ts;
|
|
1344
1347
|
}
|
|
@@ -1564,6 +1567,7 @@ export interface ModelUsageTable {
|
|
|
1564
1567
|
cache_read_tokens: Generated<number>;
|
|
1565
1568
|
/** 0160: the answer's cache write tokens (0 for an embedding call). */
|
|
1566
1569
|
cache_write_tokens: Generated<number>;
|
|
1570
|
+
cache_write_by_ttl: Json<CacheWriteByTtl[] | null>;
|
|
1567
1571
|
occurred_at: Ts;
|
|
1568
1572
|
reported_at: TsNullable;
|
|
1569
1573
|
/** Set when the row's `usage.report` job gave up after its last attempt. */
|
|
@@ -1956,6 +1960,15 @@ export interface DeviceRetirementMembersTable {
|
|
|
1956
1960
|
settled: ColumnType<boolean, boolean | undefined, boolean>;
|
|
1957
1961
|
created_at: Generated<Date>;
|
|
1958
1962
|
}
|
|
1963
|
+
/** 0204: the exact local provider identity of a committed kernel incarnation. */
|
|
1964
|
+
export interface DeviceInstanceRetirementIdentitiesTable {
|
|
1965
|
+
org_id: string;
|
|
1966
|
+
device_id: string;
|
|
1967
|
+
provider: string;
|
|
1968
|
+
instance_generation: string;
|
|
1969
|
+
provider_generation: string;
|
|
1970
|
+
attested_at: TsNullable;
|
|
1971
|
+
}
|
|
1959
1972
|
export interface DeviceInstanceDestructionsTable {
|
|
1960
1973
|
device_id: string;
|
|
1961
1974
|
provider: string;
|
|
@@ -1989,6 +2002,7 @@ export interface KernelDatabase {
|
|
|
1989
2002
|
device_retirement_members: DeviceRetirementMembersTable;
|
|
1990
2003
|
/** Migration 0157: provider-confirmed destruction of a cloud instance incarnation. */
|
|
1991
2004
|
device_instance_destructions: DeviceInstanceDestructionsTable;
|
|
2005
|
+
device_instance_retirement_identities: DeviceInstanceRetirementIdentitiesTable;
|
|
1992
2006
|
sandbox_operation_intents: SandboxOperationIntentsTable;
|
|
1993
2007
|
sandbox_operation_payload_chunks: SandboxOperationPayloadChunksTable;
|
|
1994
2008
|
permission_config_publication: PermissionConfigPublicationTable;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { FastifyReply } from "fastify";
|
|
1
2
|
import type { z } from "zod";
|
|
2
3
|
import { type Principal } from "../identity/principal.js";
|
|
3
4
|
import { type OrgContext } from "../orgs/org.guard.js";
|
|
@@ -25,6 +26,7 @@ import { type DeviceCreateBody, type DeviceParams, type DevicePatchBody, type De
|
|
|
25
26
|
* - `DELETE /:id` → 202 (destroyed by a job after the response);
|
|
26
27
|
* - `POST /:id/files/reset` → 202 (the reset is enqueued: a worker empties the files, the next use
|
|
27
28
|
* starts empty; 409 `device.files_on_device` when its provider's report offers no reset);
|
|
29
|
+
* - `POST /:id/retirement/check` → the owner's session asks the local machine for exact evidence;
|
|
28
30
|
* - a device's projects (project root design §4.1, §4.2), owner only (anyone else:
|
|
29
31
|
* `device.not_found`): `GET /:id/projects` → the ones its current mode can read;
|
|
30
32
|
* `GET /:id/projects/candidates` → the device's suggestions under its base;
|
|
@@ -51,6 +53,9 @@ export declare class DevicesController {
|
|
|
51
53
|
}>;
|
|
52
54
|
remove(principal: Principal, org: OrgContext, params: z.infer<typeof DeviceParams>): Promise<void>;
|
|
53
55
|
resetFiles(principal: Principal, org: OrgContext, params: z.infer<typeof DeviceParams>): Promise<void>;
|
|
56
|
+
checkRetirement(principal: Principal, org: OrgContext, params: z.infer<typeof DeviceParams>, reply: FastifyReply): Promise<{
|
|
57
|
+
status: "clear" | "blocked" | "busy";
|
|
58
|
+
}>;
|
|
54
59
|
listProjects(principal: Principal, org: OrgContext, params: z.infer<typeof DeviceParams>): Promise<DeviceProjectList>;
|
|
55
60
|
projectCandidates(principal: Principal, org: OrgContext, params: z.infer<typeof DeviceParams>): Promise<DeviceProjectCandidates>;
|
|
56
61
|
listProjectFiles(principal: Principal, org: OrgContext, params: z.infer<typeof DeviceProjectParams>, query: z.infer<typeof DeviceProjectFilesQuery>): Promise<ProjectFileList>;
|
|
@@ -7,8 +7,9 @@ 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 { Controller, Delete, Get, HttpCode, Inject, Patch, Post } from "@nestjs/common";
|
|
11
|
-
import {
|
|
10
|
+
import { Controller, Delete, Get, HttpCode, Inject, Patch, Post, Res } from "@nestjs/common";
|
|
11
|
+
import { requestSignal } from "../http/request-signal.js";
|
|
12
|
+
import { CurrentPrincipal, patTokenId, requireUser, SessionOnly, } from "../identity/principal.js";
|
|
12
13
|
import { ZBody, ZParam, ZQuery } from "../infra/validation/zod-params.js";
|
|
13
14
|
import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
|
|
14
15
|
import { DeviceProjectFilesService } from "./device-project-files.service.js";
|
|
@@ -35,6 +36,7 @@ import { DeviceCreateBodyDto, DeviceParamsDto, DevicePatchBodyDto, DeviceProject
|
|
|
35
36
|
* - `DELETE /:id` → 202 (destroyed by a job after the response);
|
|
36
37
|
* - `POST /:id/files/reset` → 202 (the reset is enqueued: a worker empties the files, the next use
|
|
37
38
|
* starts empty; 409 `device.files_on_device` when its provider's report offers no reset);
|
|
39
|
+
* - `POST /:id/retirement/check` → the owner's session asks the local machine for exact evidence;
|
|
38
40
|
* - a device's projects (project root design §4.1, §4.2), owner only (anyone else:
|
|
39
41
|
* `device.not_found`): `GET /:id/projects` → the ones its current mode can read;
|
|
40
42
|
* `GET /:id/projects/candidates` → the device's suggestions under its base;
|
|
@@ -87,6 +89,12 @@ let DevicesController = class DevicesController {
|
|
|
87
89
|
const p = requireUser(principal);
|
|
88
90
|
await this.devices.resetFiles(org.orgId, p.account.id, params.id, patTokenId(p));
|
|
89
91
|
}
|
|
92
|
+
async checkRetirement(principal, org, params, reply) {
|
|
93
|
+
const p = requireUser(principal);
|
|
94
|
+
return {
|
|
95
|
+
status: await this.devices.checkRetirement(org.orgId, p.account.id, params.id, requestSignal(reply)),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
90
98
|
async listProjects(principal, org, params) {
|
|
91
99
|
const p = requireUser(principal);
|
|
92
100
|
return this.projects.list(org.orgId, p.account.id, params.id);
|
|
@@ -157,6 +165,16 @@ __decorate([
|
|
|
157
165
|
__param(1, CurrentOrg()),
|
|
158
166
|
__param(2, ZParam(DeviceParamsDto))
|
|
159
167
|
], DevicesController.prototype, "resetFiles", null);
|
|
168
|
+
__decorate([
|
|
169
|
+
Post(":id/retirement/check"),
|
|
170
|
+
HttpCode(200),
|
|
171
|
+
SessionOnly(),
|
|
172
|
+
OrgAction("agents.use"),
|
|
173
|
+
__param(0, CurrentPrincipal()),
|
|
174
|
+
__param(1, CurrentOrg()),
|
|
175
|
+
__param(2, ZParam(DeviceParamsDto)),
|
|
176
|
+
__param(3, Res({ passthrough: true }))
|
|
177
|
+
], DevicesController.prototype, "checkRetirement", null);
|
|
160
178
|
__decorate([
|
|
161
179
|
Get(":id/projects"),
|
|
162
180
|
OrgAction("agents.use"),
|
|
@@ -63,6 +63,14 @@ export interface DeviceView {
|
|
|
63
63
|
reconcileRequired: boolean;
|
|
64
64
|
/** Its file system is gone at the provider; reset the files to use it again. */
|
|
65
65
|
filesLost: boolean;
|
|
66
|
+
/**
|
|
67
|
+
* A retirement obligation refuses every use (permission runtime cutover 8.5): `recreateRequired`
|
|
68
|
+
* when an earlier instance may still run background work no evidence can cover (quarantined:
|
|
69
|
+
* `device.recreate_required`), `pending` while a try to confirm an earlier instance destroyed
|
|
70
|
+
* failed and is retried (`device.unavailable`); null when nothing blocks it (an obligation not
|
|
71
|
+
* tried yet clears at the next use).
|
|
72
|
+
*/
|
|
73
|
+
retirement: "pending" | "recreateRequired" | null;
|
|
66
74
|
instance: {
|
|
67
75
|
status: "running" | "suspended";
|
|
68
76
|
lastUsedAt: string;
|
|
@@ -219,7 +227,7 @@ export declare class DevicesService {
|
|
|
219
227
|
private readonly dialIn;
|
|
220
228
|
/** The providers' device-connection guides. */
|
|
221
229
|
private readonly guides;
|
|
222
|
-
constructor(db: KernelDb, txHost: TransactionHost, config: Pick<KernelConfigService, "get" | "fieldSource">, selection: Pick<DeviceProviderSelection, "onInOrg" | "isOnInOrg" | "defaultFor">, sandbox: Pick<SandboxService, "devicePolicy" | "deviceLimits" | "limitsState">, sandboxJobs: Pick<SandboxJobs, "resetFiles">,
|
|
230
|
+
constructor(db: KernelDb, txHost: TransactionHost, config: Pick<KernelConfigService, "get" | "fieldSource">, selection: Pick<DeviceProviderSelection, "onInOrg" | "isOnInOrg" | "defaultFor">, sandbox: Pick<SandboxService, "devicePolicy" | "deviceLimits" | "limitsState" | "checkLocalRetirement">, sandboxJobs: Pick<SandboxJobs, "resetFiles">,
|
|
223
231
|
/** Owes a deleted device's destruction in the delete's transaction. */
|
|
224
232
|
outbox: Pick<OutboxService, "add">, access: Pick<DeviceAccess, "usable">,
|
|
225
233
|
/** Whether a dial-in device's machine is connected now. */
|
|
@@ -244,6 +252,8 @@ export declare class DevicesService {
|
|
|
244
252
|
private catalogDescriptions;
|
|
245
253
|
/** One of the person's live devices; anyone else's (or a missing one) → `not_found`. */
|
|
246
254
|
get(orgId: string, accountId: string, id: string): Promise<DeviceView>;
|
|
255
|
+
/** The owner's web action; the retirement gate rechecks ownership under its lifecycle lease. */
|
|
256
|
+
checkRetirement(orgId: string, accountId: string, deviceId: string, signal: AbortSignal): Promise<"blocked" | "busy" | "clear">;
|
|
247
257
|
/**
|
|
248
258
|
* A new personal device, ready at once (its instance and files are made on first use),
|
|
249
259
|
* bound for life to `input.provider` or, without one, the org's default provider: a provider not
|
|
@@ -196,6 +196,10 @@ let DevicesService = class DevicesService {
|
|
|
196
196
|
throw deviceNotFound();
|
|
197
197
|
return view;
|
|
198
198
|
}
|
|
199
|
+
/** The owner's web action; the retirement gate rechecks ownership under its lifecycle lease. */
|
|
200
|
+
checkRetirement(orgId, accountId, deviceId, signal) {
|
|
201
|
+
return this.sandbox.checkLocalRetirement({ orgId, accountId, deviceId }, signal);
|
|
202
|
+
}
|
|
199
203
|
/**
|
|
200
204
|
* A new personal device, ready at once (its instance and files are made on first use),
|
|
201
205
|
* bound for life to `input.provider` or, without one, the org's default provider: a provider not
|
|
@@ -873,6 +877,21 @@ let DevicesService = class DevicesService {
|
|
|
873
877
|
]);
|
|
874
878
|
return [r.id, { limits, state, box: facts.box, report }];
|
|
875
879
|
})));
|
|
880
|
+
// the devices a retirement obligation blocks: a quarantined one for good, an open one whose
|
|
881
|
+
// last try failed until a retry succeeds
|
|
882
|
+
const retirement = new Map();
|
|
883
|
+
for (const o of await this.db
|
|
884
|
+
.selectFrom("device_retirement_obligations")
|
|
885
|
+
.select(["device_id", "state", "attempts"])
|
|
886
|
+
.where("org_id", "=", orgId)
|
|
887
|
+
.where("device_id", "in", rows.map((r) => r.id))
|
|
888
|
+
.where("state", "in", ["open", "quarantined"])
|
|
889
|
+
.execute()) {
|
|
890
|
+
if (o.state === "quarantined")
|
|
891
|
+
retirement.set(o.device_id, "recreateRequired");
|
|
892
|
+
else if (o.attempts > 0 && !retirement.has(o.device_id))
|
|
893
|
+
retirement.set(o.device_id, "pending");
|
|
894
|
+
}
|
|
876
895
|
// a dial-in device is online while a replica holds its machine's connection
|
|
877
896
|
const dialIn = new Set(rows.filter((r) => this.isDialIn(r.provider)).map((r) => r.id));
|
|
878
897
|
const online = new Map(await Promise.all([...dialIn].map(async (deviceId) => [deviceId, await this.relay.online(deviceId)])));
|
|
@@ -913,6 +932,7 @@ let DevicesService = class DevicesService {
|
|
|
913
932
|
}),
|
|
914
933
|
reconcileRequired: r.permission_reconcile_required,
|
|
915
934
|
filesLost: r.fs_status === "lost",
|
|
935
|
+
retirement: retirement.get(r.id) ?? null,
|
|
916
936
|
instance: live
|
|
917
937
|
? {
|
|
918
938
|
status: r.status,
|
package/dist/evals/plan.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type CacheWriteByTtl, type ModelUsage } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import type { ModelRef } from "../agents/definition.js";
|
|
3
3
|
import { type CaseSnapshot } from "./snapshot.js";
|
|
4
4
|
/**
|
|
@@ -17,6 +17,8 @@ export interface CasePlan {
|
|
|
17
17
|
modelRequests: number;
|
|
18
18
|
/** Those requests' usage in the original run (summed per field). */
|
|
19
19
|
usage: ModelUsage;
|
|
20
|
+
/** Classified cache writes for pricing. Historical or untiered writes count in the total alone. */
|
|
21
|
+
cacheWriteByTtl?: CacheWriteByTtl[];
|
|
20
22
|
/**
|
|
21
23
|
* The judge's context estimate: each result's "user request" tokens plus both replies (the
|
|
22
24
|
* baseline's output tokens × 2; the candidate is estimated at the same amount). The judge's system
|
package/dist/evals/plan.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { validateCacheWriteByTtl, } from "@capybara-hq/plugin-sdk";
|
|
1
2
|
import { estimateTokens } from "../runtime/context/tokens.js";
|
|
2
3
|
import { addUsage } from "./budget.js";
|
|
3
4
|
import { replyParts } from "./diff.js";
|
|
@@ -15,6 +16,7 @@ const asUsage = (p) => {
|
|
|
15
16
|
outputTokens: x.outputTokens ?? 0,
|
|
16
17
|
cacheReadTokens: x.cacheReadTokens ?? 0,
|
|
17
18
|
cacheWriteTokens: x.cacheWriteTokens ?? 0,
|
|
19
|
+
...(x.cacheWriteByTtl !== undefined && { cacheWriteByTtl: x.cacheWriteByTtl }),
|
|
18
20
|
};
|
|
19
21
|
};
|
|
20
22
|
/** The token estimate of a text (the same estimator as the runtime). */
|
|
@@ -56,14 +58,32 @@ export function casePlan(s, mode) {
|
|
|
56
58
|
if (compactRun(s))
|
|
57
59
|
return { ...NO_PLAN, results: [], usage: { ...ZERO } };
|
|
58
60
|
const own = s.events.filter((e) => e.runId === s.runId);
|
|
61
|
+
let usage = ZERO;
|
|
62
|
+
const writeTokensByTtl = new Map();
|
|
63
|
+
const addRecordedUsage = (payload) => {
|
|
64
|
+
const recorded = asUsage(payload);
|
|
65
|
+
usage = addUsage(usage, recorded);
|
|
66
|
+
if (validateCacheWriteByTtl(recorded) === null) {
|
|
67
|
+
for (const { ttl, tokens } of recorded.cacheWriteByTtl ?? []) {
|
|
68
|
+
writeTokensByTtl.set(ttl, (writeTokensByTtl.get(ttl) ?? 0) + tokens);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return recorded;
|
|
72
|
+
};
|
|
73
|
+
const breakdown = () => writeTokensByTtl.size === 0
|
|
74
|
+
? {}
|
|
75
|
+
: {
|
|
76
|
+
cacheWriteByTtl: [...writeTokensByTtl]
|
|
77
|
+
.sort(([a], [b]) => a - b)
|
|
78
|
+
.map(([ttl, tokens]) => ({ ttl, tokens })),
|
|
79
|
+
};
|
|
59
80
|
if (mode === "run") {
|
|
60
|
-
let usage = ZERO;
|
|
61
81
|
let calls = 0;
|
|
62
82
|
for (const e of own) {
|
|
63
83
|
if (e.type === "model_call")
|
|
64
84
|
calls++;
|
|
65
85
|
else if (e.type === "usage")
|
|
66
|
-
|
|
86
|
+
addRecordedUsage(e.payload);
|
|
67
87
|
}
|
|
68
88
|
const start = own.find((e) => e.type === "run_started");
|
|
69
89
|
const request = userRequestOf(s, start?.seq ?? Number.POSITIVE_INFINITY);
|
|
@@ -71,25 +91,25 @@ export function casePlan(s, mode) {
|
|
|
71
91
|
results: [{ step: null, modelCallSeq: null }],
|
|
72
92
|
modelRequests: calls,
|
|
73
93
|
usage,
|
|
94
|
+
...breakdown(),
|
|
74
95
|
judgeContextTokens: textTokens(request) + 2 * usage.outputTokens,
|
|
75
96
|
};
|
|
76
97
|
}
|
|
77
98
|
const calls = replayableCalls(s);
|
|
78
|
-
let usage = ZERO;
|
|
79
99
|
let judgeContextTokens = 0;
|
|
80
100
|
for (const c of calls) {
|
|
81
101
|
const u = own.find((e) => e.type === "usage" &&
|
|
82
102
|
e.seq > c.seq &&
|
|
83
103
|
e.payload.step === c.step &&
|
|
84
104
|
e.payload.purpose === undefined);
|
|
85
|
-
const callUsage = u ?
|
|
86
|
-
usage = addUsage(usage, callUsage);
|
|
105
|
+
const callUsage = u ? addRecordedUsage(u.payload) : ZERO;
|
|
87
106
|
judgeContextTokens += textTokens(userRequestOf(s, c.seq)) + 2 * callUsage.outputTokens;
|
|
88
107
|
}
|
|
89
108
|
return {
|
|
90
109
|
results: calls.map((c) => ({ step: c.step, modelCallSeq: c.seq })),
|
|
91
110
|
modelRequests: calls.length,
|
|
92
111
|
usage,
|
|
112
|
+
...breakdown(),
|
|
93
113
|
judgeContextTokens,
|
|
94
114
|
};
|
|
95
115
|
}
|
|
@@ -20,7 +20,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
|
|
|
20
20
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
21
21
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
22
22
|
import { LockService } from "../infra/lock/lock.service.js";
|
|
23
|
-
import { costOf, PricesService, priceKey } from "../models/prices.js";
|
|
23
|
+
import { costOf, costOfUsageTotals, PricesService, priceKey, } from "../models/prices.js";
|
|
24
24
|
import { ModelPurposesService } from "../models/purposes.js";
|
|
25
25
|
import { OrgLock } from "../orgs/org-lock.js";
|
|
26
26
|
import { ProviderListError, ProviderRegistry } from "../runtime/providers.js";
|
|
@@ -308,7 +308,8 @@ let EvalRunsService = EvalRunsService_1 = class EvalRunsService {
|
|
|
308
308
|
}
|
|
309
309
|
}
|
|
310
310
|
}
|
|
311
|
-
|
|
311
|
+
const cost = problem ? 0 : costOfUsageTotals(p.usage, price, p.cacheWriteByTtl);
|
|
312
|
+
out.push({ ...p, caseId: row.id, cost, problem });
|
|
312
313
|
}
|
|
313
314
|
return out;
|
|
314
315
|
}
|
package/dist/evals/trajectory.js
CHANGED
|
@@ -17,6 +17,7 @@ const usageOf = (p) => ({
|
|
|
17
17
|
outputTokens: p.outputTokens,
|
|
18
18
|
cacheReadTokens: p.cacheReadTokens,
|
|
19
19
|
cacheWriteTokens: p.cacheWriteTokens,
|
|
20
|
+
...(p.cacheWriteByTtl !== undefined && { cacheWriteByTtl: p.cacheWriteByTtl }),
|
|
20
21
|
});
|
|
21
22
|
/**
|
|
22
23
|
* 由会话事件推出各次运行的轨迹,按 `run_started` 的 seq 排序。没有 `run_started` 的运行(排队时就被中止 /
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ExpressionBuilder } from "kysely";
|
|
2
|
+
import type { KernelDatabase } from "../db/kernel-schema.js";
|
|
3
|
+
/**
|
|
4
|
+
* No file row (any status: a `deleted` one within the retention keeps its bytes, and the rows past
|
|
5
|
+
* it are deleted first by the same sweep) and no share (`file_shares.blob_id`: the share sweep
|
|
6
|
+
* clears it on shares long expired or revoked) refers to the blob.
|
|
7
|
+
*/
|
|
8
|
+
export declare function blobUnreferenced(orgId: string): (eb: ExpressionBuilder<KernelDatabase, "blobs">) => import("kysely").ExpressionWrapper<KernelDatabase, "blobs", import("kysely").SqlBool>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* No file row (any status: a `deleted` one within the retention keeps its bytes, and the rows past
|
|
3
|
+
* it are deleted first by the same sweep) and no share (`file_shares.blob_id`: the share sweep
|
|
4
|
+
* clears it on shares long expired or revoked) refers to the blob.
|
|
5
|
+
*/
|
|
6
|
+
export function blobUnreferenced(orgId) {
|
|
7
|
+
return (eb) => eb.and([
|
|
8
|
+
eb.not(eb.exists(eb
|
|
9
|
+
.selectFrom("files")
|
|
10
|
+
.select("files.id")
|
|
11
|
+
.where("files.org_id", "=", orgId)
|
|
12
|
+
.whereRef("files.blob_id", "=", "blobs.id"))),
|
|
13
|
+
eb.not(eb.exists(eb
|
|
14
|
+
.selectFrom("file_shares")
|
|
15
|
+
.select("file_shares.id")
|
|
16
|
+
.where("file_shares.org_id", "=", orgId)
|
|
17
|
+
.whereRef("file_shares.blob_id", "=", "blobs.id"))),
|
|
18
|
+
]);
|
|
19
|
+
}
|
|
@@ -21,6 +21,7 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
|
21
21
|
import { revokeSharesIn } from "../shares/revoke.js";
|
|
22
22
|
import { StorageService } from "../storage/storage.service.js";
|
|
23
23
|
import { oweBlobDelete } from "./blob-objects.js";
|
|
24
|
+
import { blobUnreferenced } from "./blob-references.js";
|
|
24
25
|
import { blobContentMatches } from "./blobs.service.js";
|
|
25
26
|
import { FileLibraryBackfill } from "./library-backfill.js";
|
|
26
27
|
/** The daily blob sweep's name (scheduler key and lock; no `:`). */
|
|
@@ -48,25 +49,6 @@ const UNREFERENCED = {
|
|
|
48
49
|
olderThanHours: UNREFERENCED_AFTER_HOURS,
|
|
49
50
|
};
|
|
50
51
|
const ABANDONED = { statuses: ["pending"], olderThanHours: PENDING_AFTER_HOURS };
|
|
51
|
-
/**
|
|
52
|
-
* No file row (any status: a `deleted` one within the retention keeps its bytes, and the rows past
|
|
53
|
-
* it are deleted first by the same sweep) and no share (`file_shares.blob_id`: the share sweep
|
|
54
|
-
* clears it on shares long expired or revoked) refers to the blob.
|
|
55
|
-
*/
|
|
56
|
-
function unreferenced(orgId) {
|
|
57
|
-
return (eb) => eb.and([
|
|
58
|
-
eb.not(eb.exists(eb
|
|
59
|
-
.selectFrom("files")
|
|
60
|
-
.select("files.id")
|
|
61
|
-
.where("files.org_id", "=", orgId)
|
|
62
|
-
.whereRef("files.blob_id", "=", "blobs.id"))),
|
|
63
|
-
eb.not(eb.exists(eb
|
|
64
|
-
.selectFrom("file_shares")
|
|
65
|
-
.select("file_shares.id")
|
|
66
|
-
.where("file_shares.org_id", "=", orgId)
|
|
67
|
-
.whereRef("file_shares.blob_id", "=", "blobs.id"))),
|
|
68
|
-
]);
|
|
69
|
-
}
|
|
70
52
|
/**
|
|
71
53
|
* The daily blob sweep (file library spec §7), a `@LockedCron` (once per tick across replicas,
|
|
72
54
|
* provided only under `WorkerModule`). For each live org, in the org's scope:
|
|
@@ -243,7 +225,7 @@ let BlobSweepJob = class BlobSweepJob {
|
|
|
243
225
|
.where("org_id", "=", orgId)
|
|
244
226
|
.where("status", "in", [...kind.statuses])
|
|
245
227
|
.where("created_at", "<", old)
|
|
246
|
-
.where(
|
|
228
|
+
.where(blobUnreferenced(orgId))
|
|
247
229
|
.$if(kind.hashedOnly === true, (q) => q.where("sha256", "is not", null))
|
|
248
230
|
.$if(after !== null, (q) => q.where("id", ">", after))
|
|
249
231
|
.orderBy("id")
|
|
@@ -261,7 +243,7 @@ let BlobSweepJob = class BlobSweepJob {
|
|
|
261
243
|
.where("org_id", "=", orgId)
|
|
262
244
|
.where("id", "in", candidates.map((c) => c.id))
|
|
263
245
|
.where("status", "in", [...kind.statuses])
|
|
264
|
-
.where(
|
|
246
|
+
.where(blobUnreferenced(orgId))
|
|
265
247
|
.$if(kind.hashedOnly === true, (q) => q.where("sha256", "is not", null))
|
|
266
248
|
.returning("id")
|
|
267
249
|
.execute();
|
|
@@ -283,7 +265,7 @@ let BlobSweepJob = class BlobSweepJob {
|
|
|
283
265
|
const rows = await this.db
|
|
284
266
|
.selectFrom("blobs")
|
|
285
267
|
.select(["id", "object_key", "size", "etag"])
|
|
286
|
-
.select((eb) => eb.not(
|
|
268
|
+
.select((eb) => eb.not(blobUnreferenced(orgId)(eb)).as("referenced"))
|
|
287
269
|
.where("org_id", "=", orgId)
|
|
288
270
|
.where("status", "=", "deleting")
|
|
289
271
|
.where("created_at", "<", old)
|
|
@@ -340,7 +322,7 @@ let BlobSweepJob = class BlobSweepJob {
|
|
|
340
322
|
.select("id")
|
|
341
323
|
.where("org_id", "=", orgId)
|
|
342
324
|
.where("id", "in", locked.map((b) => b.id))
|
|
343
|
-
.where(
|
|
325
|
+
.where(blobUnreferenced(orgId))
|
|
344
326
|
.execute();
|
|
345
327
|
const freeIds = new Set(free.map((b) => b.id));
|
|
346
328
|
for (const id of freeIds)
|
|
@@ -59,16 +59,20 @@ export function fileContentBlock(f) {
|
|
|
59
59
|
size: f.size,
|
|
60
60
|
};
|
|
61
61
|
}
|
|
62
|
+
const metadata = {
|
|
63
|
+
source,
|
|
64
|
+
name: f.name,
|
|
65
|
+
size: f.size,
|
|
66
|
+
...(f.contentType.startsWith("text/") && { readByFileId: true }),
|
|
67
|
+
};
|
|
62
68
|
if (isMediaContentType(f.contentType)) {
|
|
63
69
|
return {
|
|
64
70
|
type: "document",
|
|
65
71
|
mediaType: f.contentType,
|
|
66
|
-
|
|
67
|
-
name: f.name,
|
|
68
|
-
size: f.size,
|
|
72
|
+
...metadata,
|
|
69
73
|
};
|
|
70
74
|
}
|
|
71
|
-
return { type: "file", mediaType: f.contentType,
|
|
75
|
+
return { type: "file", mediaType: f.contentType, ...metadata };
|
|
72
76
|
}
|
|
73
77
|
const notFound = () => new ApiError("file.not_found", "File not found");
|
|
74
78
|
const UPLOAD_COLUMNS = [
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
/** The classified writes of one stored event. A malformed breakdown leaves every write unclassified. */
|
|
3
|
+
export function cacheWriteTierRows(payload) {
|
|
4
|
+
return sql `
|
|
5
|
+
WITH entries AS (
|
|
6
|
+
SELECT CASE WHEN jsonb_typeof(tier->'ttl') = 'number'
|
|
7
|
+
THEN (tier->>'ttl')::numeric END AS ttl,
|
|
8
|
+
CASE WHEN jsonb_typeof(tier->'tokens') = 'number'
|
|
9
|
+
THEN (tier->>'tokens')::numeric END AS tokens
|
|
10
|
+
FROM jsonb_array_elements(
|
|
11
|
+
CASE WHEN jsonb_typeof(${payload}->'cacheWriteByTtl') = 'array'
|
|
12
|
+
THEN ${payload}->'cacheWriteByTtl' ELSE '[]'::jsonb END
|
|
13
|
+
) AS tiers(tier)
|
|
14
|
+
)
|
|
15
|
+
SELECT ttl, tokens
|
|
16
|
+
FROM entries
|
|
17
|
+
WHERE (
|
|
18
|
+
SELECT count(*) = count(DISTINCT ttl)
|
|
19
|
+
AND bool_and(coalesce(ttl > 0 AND trunc(ttl) = ttl
|
|
20
|
+
AND tokens >= 0 AND trunc(tokens) = tokens, false))
|
|
21
|
+
AND sum(tokens) = CASE WHEN jsonb_typeof(${payload}->'cacheWriteTokens') = 'number'
|
|
22
|
+
THEN (${payload}->>'cacheWriteTokens')::numeric END
|
|
23
|
+
FROM entries
|
|
24
|
+
)
|
|
25
|
+
`;
|
|
26
|
+
}
|
package/dist/models/images.js
CHANGED
|
@@ -18,7 +18,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
|
18
18
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
19
19
|
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
20
20
|
import { base64Bytes, fireObserve, imageDeniedAudit, } from "../runtime/hook-calls.js";
|
|
21
|
-
import { modelDeniedText } from "../runtime/model-call.js";
|
|
21
|
+
import { modelDeniedText, trustedUsage } from "../runtime/model-call.js";
|
|
22
22
|
import { ProviderRegistry } from "../runtime/providers.js";
|
|
23
23
|
import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
|
|
24
24
|
import { imageInputCaps } from "./image-usable.js";
|
|
@@ -197,6 +197,9 @@ let ModelImages = class ModelImages {
|
|
|
197
197
|
output_tokens: res.usage.outputTokens,
|
|
198
198
|
cache_read_tokens: res.usage.cacheReadTokens,
|
|
199
199
|
cache_write_tokens: res.usage.cacheWriteTokens,
|
|
200
|
+
...(res.usage.cacheWriteByTtl !== undefined && {
|
|
201
|
+
cache_write_by_ttl: JSON.stringify(res.usage.cacheWriteByTtl),
|
|
202
|
+
}),
|
|
200
203
|
output_images: billedImages(res),
|
|
201
204
|
})
|
|
202
205
|
.returning("id")
|
|
@@ -325,6 +328,7 @@ let ModelImages = class ModelImages {
|
|
|
325
328
|
throw err;
|
|
326
329
|
}
|
|
327
330
|
const latencyMs = Date.now() - sentAt;
|
|
331
|
+
res = { ...res, usage: trustedUsage(res.usage, ref.model, this.log) };
|
|
328
332
|
respond({
|
|
329
333
|
outcome: "ok",
|
|
330
334
|
images: res.images.map((i) => ({ mediaType: i.mediaType, size: base64Bytes(i.data) })),
|
package/dist/models/prices.d.ts
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type CacheWriteByTtl, type ModelUsage } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { SuperAdminLock } from "../identity/super-admin.js";
|
|
4
4
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
5
5
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
6
|
-
/**
|
|
7
|
-
* 一个模型的价格(C2):每百万 token,币种为部署设置 `priceCurrency`。由超级管理员录入,插件不声明价格。
|
|
8
|
-
* 缓存读 / 写价为 null 时按输入价计。
|
|
9
|
-
*/
|
|
6
|
+
/** Administrator-set prices per million tokens in the deployment's currency. */
|
|
10
7
|
export interface ModelPrice {
|
|
11
8
|
provider: string;
|
|
12
9
|
model: string;
|
|
@@ -14,13 +11,17 @@ export interface ModelPrice {
|
|
|
14
11
|
outputPerMTok: number;
|
|
15
12
|
cacheReadPerMTok: number | null;
|
|
16
13
|
cacheWritePerMTok: number | null;
|
|
14
|
+
/** Keys are TTLs in seconds. An absent rate inherits the generic cache-write price. */
|
|
15
|
+
cacheWritePerMTokByTtl?: Record<string, number>;
|
|
17
16
|
}
|
|
18
17
|
/** 价格表:键为 {@link priceKey}(`${provider}\n${model}`)。 */
|
|
19
18
|
export type PriceTable = ReadonlyMap<string, ModelPrice>;
|
|
20
19
|
/** 价格表的键。供应商名与模型 id 不含换行,拼接不会撞键。 */
|
|
21
20
|
export declare const priceKey: (provider: string, model: string) => string;
|
|
22
|
-
/**
|
|
21
|
+
/** Estimates a call's cost from its validated write breakdown, or the generic rates. */
|
|
23
22
|
export declare function costOf(usage: ModelUsage, price: ModelPrice | undefined): number | null;
|
|
23
|
+
/** Group totals can include both classified and unclassified writes. */
|
|
24
|
+
export declare function costOfUsageTotals(usage: ModelUsage, price: ModelPrice | undefined, classifiedWrites?: readonly CacheWriteByTtl[]): number | null;
|
|
24
25
|
/** `PUT /api/v1/admin/model-prices` 的 body:设一个价格,或 `price: null` 删除。 */
|
|
25
26
|
export declare const MODEL_PRICE_PUT: z.ZodUnion<readonly [z.ZodObject<{
|
|
26
27
|
provider: z.ZodString;
|
|
@@ -29,6 +30,7 @@ export declare const MODEL_PRICE_PUT: z.ZodUnion<readonly [z.ZodObject<{
|
|
|
29
30
|
outputPerMTok: z.ZodNumber;
|
|
30
31
|
cacheReadPerMTok: z.ZodNullable<z.ZodNumber>;
|
|
31
32
|
cacheWritePerMTok: z.ZodNullable<z.ZodNumber>;
|
|
33
|
+
cacheWritePerMTokByTtl: z.ZodExactOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
32
34
|
}, z.core.$strict>, z.ZodObject<{
|
|
33
35
|
provider: z.ZodString;
|
|
34
36
|
model: z.ZodString;
|