@capybara-hq/kernel 0.1.0-rc.117 → 0.1.0-rc.119

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.
Files changed (106) hide show
  1. package/dist/admin/usage.service.d.ts +4 -2
  2. package/dist/admin/usage.service.js +35 -15
  3. package/dist/automations/unattended.d.ts +2 -0
  4. package/dist/automations/unattended.js +10 -3
  5. package/dist/catalog/component-scope.service.js +2 -1
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/plugin-install.d.ts +1 -0
  8. package/dist/catalog/plugin-install.js +11 -1
  9. package/dist/channels/cards.d.ts +2 -4
  10. package/dist/channels/cards.js +11 -6
  11. package/dist/channels/phrases.d.ts +4 -0
  12. package/dist/channels/phrases.js +1 -0
  13. package/dist/conversations/conversations.controller.d.ts +1 -1
  14. package/dist/conversations/conversations.controller.js +1 -1
  15. package/dist/conversations/conversations.service.d.ts +4 -2
  16. package/dist/conversations/conversations.service.js +19 -3
  17. package/dist/conversations/events.d.ts +35 -1
  18. package/dist/conversations/events.js +29 -4
  19. package/dist/ctx/create-ctx.d.ts +1 -1
  20. package/dist/ctx/create-ctx.js +4 -0
  21. package/dist/db/kernel-schema.d.ts +31 -1
  22. package/dist/device-access/device-access.module.js +2 -0
  23. package/dist/device-access/device-access.service.d.ts +16 -2
  24. package/dist/device-access/device-access.service.js +59 -2
  25. package/dist/device-access/site-access-request.d.ts +14 -0
  26. package/dist/device-access/site-access-request.js +35 -0
  27. package/dist/device-access/site-grants.d.ts +53 -0
  28. package/dist/device-access/site-grants.js +268 -0
  29. package/dist/device-access/site-grants.module.d.ts +2 -0
  30. package/dist/device-access/site-grants.module.js +14 -0
  31. package/dist/devices/devices.controller.d.ts +5 -0
  32. package/dist/devices/devices.controller.js +20 -2
  33. package/dist/devices/devices.service.d.ts +3 -1
  34. package/dist/devices/devices.service.js +6 -0
  35. package/dist/evals/plan.d.ts +3 -1
  36. package/dist/evals/plan.js +25 -5
  37. package/dist/evals/runs.service.js +3 -2
  38. package/dist/evals/trajectory.js +1 -0
  39. package/dist/extensions/admin-ops.js +7 -0
  40. package/dist/extensions/org-config.js +4 -0
  41. package/dist/extensions/permission-set.d.ts +3 -0
  42. package/dist/extensions/permission-set.js +5 -0
  43. package/dist/extensions/permission-view.d.ts +1 -1
  44. package/dist/extensions/permission-view.js +7 -1
  45. package/dist/files/blob-references.d.ts +8 -0
  46. package/dist/files/blob-references.js +19 -0
  47. package/dist/files/blob-sweep.job.js +5 -23
  48. package/dist/files/library-files.service.js +8 -4
  49. package/dist/models/cache-write-usage.d.ts +3 -0
  50. package/dist/models/cache-write-usage.js +26 -0
  51. package/dist/models/images.js +5 -1
  52. package/dist/models/prices.d.ts +8 -6
  53. package/dist/models/prices.js +28 -3
  54. package/dist/orgs/offboarding.js +2 -0
  55. package/dist/orgs/settings.controller.d.ts +4 -17
  56. package/dist/orgs/settings.controller.js +5 -9
  57. package/dist/orgs/settings.service.d.ts +12 -0
  58. package/dist/orgs/settings.service.js +24 -0
  59. package/dist/platform/exclusions.js +6 -0
  60. package/dist/platform/ops/admin.ops.js +2 -2
  61. package/dist/platform/ops/conversations.ops.js +1 -1
  62. package/dist/platform/ops/devices.ops.js +7 -0
  63. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  64. package/dist/platform/ops/org-settings.ops.js +10 -10
  65. package/dist/roles/worker.module.js +2 -0
  66. package/dist/runtime/context/build.d.ts +2 -0
  67. package/dist/runtime/context/build.js +9 -1
  68. package/dist/runtime/usage-report.js +3 -0
  69. package/dist/sandbox/legacy-retirement.d.ts +15 -0
  70. package/dist/sandbox/legacy-retirement.js +243 -3
  71. package/dist/sandbox/loopback-expiry.job.d.ts +3 -1
  72. package/dist/sandbox/loopback-expiry.job.js +9 -3
  73. package/dist/sandbox/operation-authority.d.ts +1 -1
  74. package/dist/sandbox/operation-authority.js +14 -6
  75. package/dist/sandbox/permission-call-types.d.ts +2 -2
  76. package/dist/sandbox/permission-instance-writes.d.ts +4 -1
  77. package/dist/sandbox/permission-instance-writes.js +55 -1
  78. package/dist/sandbox/providers.d.ts +6 -1
  79. package/dist/sandbox/providers.js +15 -1
  80. package/dist/sandbox/review/classifier.d.ts +13 -4
  81. package/dist/sandbox/review/classifier.js +73 -22
  82. package/dist/sandbox/review/permission-candidate.d.ts +3 -3
  83. package/dist/sandbox/review/permission-candidate.js +10 -8
  84. package/dist/sandbox/review/review.service.d.ts +26 -19
  85. package/dist/sandbox/review/review.service.js +69 -15
  86. package/dist/sandbox/sandbox.service.d.ts +6 -3
  87. package/dist/sandbox/sandbox.service.js +116 -5
  88. package/dist/tools/approvals.service.d.ts +30 -4
  89. package/dist/tools/approvals.service.js +143 -12
  90. package/dist/tools/builtins/sandbox/common.js +10 -6
  91. package/dist/tools/call-scope.d.ts +3 -0
  92. package/dist/tools/call-scope.js +1 -0
  93. package/dist/tools/connector-tools-jobs.d.ts +3 -2
  94. package/dist/tools/connectors.service.d.ts +3 -1
  95. package/dist/tools/connectors.service.js +64 -12
  96. package/dist/tools/drift.d.ts +1 -1
  97. package/dist/tools/drift.js +13 -13
  98. package/dist/tools/network-asks.js +7 -0
  99. package/dist/tools/pipeline.d.ts +16 -5
  100. package/dist/tools/pipeline.js +314 -11
  101. package/dist/tools/tools.module.js +2 -0
  102. package/package.json +2 -2
  103. package/src/migrations/0202_connector_endpoint_changed_at.sql +1 -0
  104. package/src/migrations/0203_model_cache_write_pricing.sql +5 -0
  105. package/src/migrations/0204_device_instance_retirement_identities.sql +46 -0
  106. package/src/migrations/0205_device_site_grants.sql +30 -0
@@ -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 { CurrentPrincipal, patTokenId, requireUser, } from "../identity/principal.js";
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"),
@@ -227,7 +227,7 @@ export declare class DevicesService {
227
227
  private readonly dialIn;
228
228
  /** The providers' device-connection guides. */
229
229
  private readonly guides;
230
- 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">,
231
231
  /** Owes a deleted device's destruction in the delete's transaction. */
232
232
  outbox: Pick<OutboxService, "add">, access: Pick<DeviceAccess, "usable">,
233
233
  /** Whether a dial-in device's machine is connected now. */
@@ -252,6 +252,8 @@ export declare class DevicesService {
252
252
  private catalogDescriptions;
253
253
  /** One of the person's live devices; anyone else's (or a missing one) → `not_found`. */
254
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">;
255
257
  /**
256
258
  * A new personal device, ready at once (its instance and files are made on first use),
257
259
  * bound for life to `input.provider` or, without one, the org's default provider: a provider not
@@ -11,6 +11,7 @@ import { randomUUID } from "node:crypto";
11
11
  import { pluginDescription, validateAllowHost, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
+ import { revokeSiteGrantsOfDevice } from "../device-access/site-grants.js";
14
15
  import { DialInHandlers } from "../dial-in/handlers.js";
15
16
  import { DialInMachines } from "../dial-in/machines.js";
16
17
  import { DialInRelay } from "../dial-in/relay.js";
@@ -196,6 +197,10 @@ let DevicesService = class DevicesService {
196
197
  throw deviceNotFound();
197
198
  return view;
198
199
  }
200
+ /** The owner's web action; the retirement gate rechecks ownership under its lifecycle lease. */
201
+ checkRetirement(orgId, accountId, deviceId, signal) {
202
+ return this.sandbox.checkLocalRetirement({ orgId, accountId, deviceId }, signal);
203
+ }
199
204
  /**
200
205
  * A new personal device, ready at once (its instance and files are made on first use),
201
206
  * bound for life to `input.provider` or, without one, the org's default provider: a provider not
@@ -674,6 +679,7 @@ let DevicesService = class DevicesService {
674
679
  await this.machines.revokeActive(id, "deleted");
675
680
  // its loopback port grants end with it (browser loopback port grants design §4)
676
681
  await revokeLoopbackGrantsOfDevice(this.db.db, this.outbox, { orgId, deviceId: id });
682
+ await revokeSiteGrantsOfDevice(this.db.db, { orgId, deviceId: id });
677
683
  await audit(this.db.db, {
678
684
  actorAccountId: accountId,
679
685
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -1,4 +1,4 @@
1
- import type { ModelUsage } from "@capybara-hq/plugin-sdk";
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
@@ -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
- usage = addUsage(usage, asUsage(e.payload));
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 ? asUsage(u.payload) : ZERO;
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
- out.push({ ...p, caseId: row.id, cost: problem ? 0 : costOf(p.usage, price), problem });
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
  }
@@ -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` 的运行(排队时就被中止 /
@@ -14,6 +14,7 @@ import semver from "semver";
14
14
  import { itemRemovedError } from "../catalog/ownership.js";
15
15
  import { oweDeployedExtensionSync } from "../catalog/scope-jobs.js";
16
16
  import { pluginSchemaName } from "../ctx/create-ctx.js";
17
+ import { revokeSiteGrantsOfExtensionEverywhere } from "../device-access/site-grants.js";
17
18
  import { ApiError } from "../errors.js";
18
19
  import { audit } from "../identity/audit.js";
19
20
  import { SuperAdminLock } from "../identity/super-admin.js";
@@ -282,6 +283,10 @@ let ExtensionAdminOps = class ExtensionAdminOps {
282
283
  updated_at: sql `now()`,
283
284
  }))
284
285
  .execute();
286
+ if (leftDisabled !== undefined ||
287
+ target.section.manifest.permissions?.deviceAccess?.siteAccess !== true) {
288
+ await revokeSiteGrantsOfExtensionEverywhere(db, name);
289
+ }
285
290
  await this.audit(actor, actorTokenId, "extension.installed", name, pkg.version, sha256, {
286
291
  catalogItemId,
287
292
  ...ownerDetail(opts.owner),
@@ -401,6 +406,8 @@ let ExtensionAdminOps = class ExtensionAdminOps {
401
406
  })
402
407
  .where("name", "=", name)
403
408
  .execute();
409
+ if (state === "disabled")
410
+ await revokeSiteGrantsOfExtensionEverywhere(db, name);
404
411
  await this.audit(actor, actorTokenId, state === "enabled" ? "extension.enabled" : "extension.disabled", name, row.version, row.sha256, { ...ownerDetail(owner), ...auditDetail });
405
412
  afterCommit(() => this.notify(name));
406
413
  // The enable is the deploy: it owes its plugin's scope sync, which installs it where its scope
@@ -11,6 +11,7 @@ import { EXTENSION_POINTS, parseExtensionPoint, } from "@capybara-hq/plugin-sdk"
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { assertItemInstallable, assertPluginSourcesInstallable, disabledPluginItems, pluginItemDisabled, } from "../catalog/request-rules.js";
13
13
  import { oweTemplateConnectors } from "../catalog/template-connector-jobs.js";
14
+ import { revokeSiteGrantsOfExtension } from "../device-access/site-grants.js";
14
15
  import { ApiError } from "../errors.js";
15
16
  import { audit } from "../identity/audit.js";
16
17
  import { afterCommit } from "../infra/database/after-commit.js";
@@ -262,6 +263,8 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
262
263
  updated_at: new Date(),
263
264
  }))
264
265
  .execute();
266
+ if (!enabled)
267
+ await revokeSiteGrantsOfExtension(t, { orgId, extensionName: plugin });
265
268
  // Switched on: it may provide the connector kind of a template whose plugin is installed in
266
269
  // the org without its connector; a worker creates the connectors it never had, once the
267
270
  // extension is loaded there (ruling R27)
@@ -380,6 +383,7 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
380
383
  .executeTakeFirst();
381
384
  if (!r)
382
385
  return false;
386
+ await revokeSiteGrantsOfExtension(t, { orgId, extensionName: plugin });
383
387
  await audit(t, {
384
388
  actorAccountId,
385
389
  orgId,
@@ -80,6 +80,7 @@ export interface PermissionSet {
80
80
  deviceAccess?: {
81
81
  services: string[];
82
82
  loopbackPorts?: true;
83
+ siteAccess?: true;
83
84
  };
84
85
  /**
85
86
  * The event types the extension may emit (`permissions.triggers.emit`, collaboration spec
@@ -187,6 +188,8 @@ export declare const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
187
188
  * upgrade without approval again. Recorded only when declared.
188
189
  */
189
190
  export declare const DEVICE_LOOPBACK_PORTS_KEY = "permissions.deviceaccess.loopbackports";
191
+ /** Blocking permission for profile decisions on non-loopback site actions. */
192
+ export declare const DEVICE_SITE_ACCESS_KEY = "permissions.deviceaccess.siteaccess";
190
193
  /**
191
194
  * Key prefix of an event type the extension emits (`permissions.triggers.emit`): blocking, not
192
195
  * sensitive (an event only reaches automations an org built on it, collaboration spec §4.2).
@@ -123,6 +123,7 @@ export function buildPermissionSet(input) {
123
123
  deviceAccess: {
124
124
  services: sortedUnique(p.deviceAccess.services),
125
125
  ...(p.deviceAccess.loopbackPorts === true && { loopbackPorts: true }),
126
+ ...(p.deviceAccess.siteAccess === true && { siteAccess: true }),
126
127
  },
127
128
  }
128
129
  : {}),
@@ -197,6 +198,8 @@ export function permissionKeys(set) {
197
198
  keys.push(`${DEVICE_ACCESS_KEY_PREFIX}${svc}`);
198
199
  if (p.deviceAccess?.loopbackPorts === true)
199
200
  keys.push(DEVICE_LOOPBACK_PORTS_KEY);
201
+ if (p.deviceAccess?.siteAccess === true)
202
+ keys.push(DEVICE_SITE_ACCESS_KEY);
200
203
  for (const t of p.triggers?.emit ?? [])
201
204
  keys.push(`${TRIGGERS_KEY_PREFIX}${t}`);
202
205
  if (p.inbox === true)
@@ -238,6 +241,8 @@ export const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
238
241
  * upgrade without approval again. Recorded only when declared.
239
242
  */
240
243
  export const DEVICE_LOOPBACK_PORTS_KEY = "permissions.deviceaccess.loopbackports";
244
+ /** Blocking permission for profile decisions on non-loopback site actions. */
245
+ export const DEVICE_SITE_ACCESS_KEY = "permissions.deviceaccess.siteaccess";
241
246
  /**
242
247
  * Key prefix of an event type the extension emits (`permissions.triggers.emit`): blocking, not
243
248
  * sensitive (an event only reaches automations an org built on it, collaboration spec §4.2).
@@ -34,7 +34,7 @@ export interface PermissionGroup {
34
34
  * ({@link SENSITIVE_EXTENSION_POINTS}; the code is the extension point name without `@<major>`, with
35
35
  * `-` replaced by `_`).
36
36
  */
37
- export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "device_provider" | "object_store" | "context" | "push_provider" | "device_access" | "device_loopback_ports" | "migration_warnings";
37
+ export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "device_provider" | "object_store" | "context" | "push_provider" | "device_access" | "device_loopback_ports" | "device_site_access" | "migration_warnings";
38
38
  /** 权限清单里的一项(分组里的一项,或 `added` 里的一个权限键)。 */
39
39
  export interface PermissionItem {
40
40
  value: string;
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { pluginSchemaName } from "../ctx/create-ctx.js";
3
3
  import { isDestructiveSql, splitSqlStatements } from "../db/sql-statements.js";
4
- import { AGENTS_KEY, CLIENT_KEY, CONVERSATIONS_KEY, DEVICE_ACCESS_KEY_PREFIX, DEVICE_LOOPBACK_PORTS_KEY, DIAL_IN_KEY_PREFIX, INBOX_KEY, PEOPLE_KEY, permissionKeys, TRIGGERS_KEY_PREFIX, UI_COMPONENT_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "./permission-set.js";
4
+ import { AGENTS_KEY, CLIENT_KEY, CONVERSATIONS_KEY, DEVICE_ACCESS_KEY_PREFIX, DEVICE_LOOPBACK_PORTS_KEY, DEVICE_SITE_ACCESS_KEY, DIAL_IN_KEY_PREFIX, INBOX_KEY, PEOPLE_KEY, permissionKeys, TRIGGERS_KEY_PREFIX, UI_COMPONENT_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "./permission-set.js";
5
5
  /**
6
6
  * Review digest: the first 16 hex digits of `sha256(permissionKeys(set).join("\n"))`; with migration
7
7
  * warnings their digest (kind, file, line and statement) is folded in, without warnings it equals the
@@ -42,6 +42,7 @@ export const SENSITIVE_EXTENSION_POINTS = [
42
42
  const CLIENT_ITEM = "client code";
43
43
  /** The "deviceAccess" group's item of loopback port grants (`permissions.deviceAccess.loopbackPorts`). */
44
44
  const LOOPBACK_PORTS_ITEM = "local ports on the device (loopback)";
45
+ const SITE_ACCESS_ITEM = "profile-approved actions on websites";
45
46
  /** The one item of the "inbox" group (collaboration spec §4.9). */
46
47
  const INBOX_ITEM = "personal inbox items";
47
48
  /** The items of the read-only org fact groups. */
@@ -89,6 +90,8 @@ function itemReason(category, item) {
89
90
  }
90
91
  if (category === "deviceAccess" && item === LOOPBACK_PORTS_ITEM)
91
92
  return "device_loopback_ports";
93
+ if (category === "deviceAccess" && item === SITE_ACCESS_ITEM)
94
+ return "device_site_access";
92
95
  return ALWAYS_SENSITIVE.has(category) ? CATEGORY_REASON[category] : undefined;
93
96
  }
94
97
  /** Routes of the `http` group: member and admin (the kernel authenticates a person). */
@@ -109,6 +112,8 @@ function keyItem(key) {
109
112
  return { category: "inbox", item: INBOX_ITEM };
110
113
  if (key === DEVICE_LOOPBACK_PORTS_KEY)
111
114
  return { category: "deviceAccess", item: LOOPBACK_PORTS_ITEM };
115
+ if (key === DEVICE_SITE_ACCESS_KEY)
116
+ return { category: "deviceAccess", item: SITE_ACCESS_ITEM };
112
117
  if (key === AGENTS_KEY)
113
118
  return { category: "agents", item: AGENTS_ITEM };
114
119
  if (key === CONVERSATIONS_KEY)
@@ -214,6 +219,7 @@ export function permissionGroups(set) {
214
219
  items: [
215
220
  ...(p.deviceAccess?.services ?? []),
216
221
  ...(p.deviceAccess?.loopbackPorts === true ? [LOOPBACK_PORTS_ITEM] : []),
222
+ ...(p.deviceAccess?.siteAccess === true ? [SITE_ACCESS_ITEM] : []),
217
223
  ],
218
224
  },
219
225
  // the event types it emits for the orgs' event automations (not sensitive)
@@ -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(unreferenced(orgId))
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(unreferenced(orgId))
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(unreferenced(orgId)(eb)).as("referenced"))
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(unreferenced(orgId))
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
- source,
67
- name: f.name,
68
- size: f.size,
72
+ ...metadata,
69
73
  };
70
74
  }
71
- return { type: "file", mediaType: f.contentType, source, name: f.name, size: f.size };
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,3 @@
1
+ import { type RawBuilder } from "kysely";
2
+ /** The classified writes of one stored event. A malformed breakdown leaves every write unclassified. */
3
+ export declare function cacheWriteTierRows(payload: RawBuilder<unknown>): RawBuilder<unknown>;
@@ -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
+ }
@@ -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) })),
@@ -1,12 +1,9 @@
1
- import type { ModelUsage } from "@capybara-hq/plugin-sdk";
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
- /** 一次调用的估算成本;没有价格 → null。用量的四项互不重叠(见 plugin-sdk `ModelUsage`)。 */
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;