@capybara-hq/kernel 0.1.0-rc.117 → 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.
Files changed (61) hide show
  1. package/dist/admin/usage.service.d.ts +4 -2
  2. package/dist/admin/usage.service.js +35 -15
  3. package/dist/catalog/component-scope.service.js +2 -1
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/catalog/plugin-install.d.ts +1 -0
  6. package/dist/catalog/plugin-install.js +11 -1
  7. package/dist/conversations/conversations.controller.d.ts +1 -1
  8. package/dist/conversations/conversations.controller.js +1 -1
  9. package/dist/conversations/conversations.service.d.ts +4 -2
  10. package/dist/conversations/conversations.service.js +17 -3
  11. package/dist/conversations/events.d.ts +9 -1
  12. package/dist/conversations/events.js +2 -0
  13. package/dist/db/kernel-schema.d.ts +15 -1
  14. package/dist/devices/devices.controller.d.ts +5 -0
  15. package/dist/devices/devices.controller.js +20 -2
  16. package/dist/devices/devices.service.d.ts +3 -1
  17. package/dist/devices/devices.service.js +4 -0
  18. package/dist/evals/plan.d.ts +3 -1
  19. package/dist/evals/plan.js +25 -5
  20. package/dist/evals/runs.service.js +3 -2
  21. package/dist/evals/trajectory.js +1 -0
  22. package/dist/files/blob-references.d.ts +8 -0
  23. package/dist/files/blob-references.js +19 -0
  24. package/dist/files/blob-sweep.job.js +5 -23
  25. package/dist/files/library-files.service.js +8 -4
  26. package/dist/models/cache-write-usage.d.ts +3 -0
  27. package/dist/models/cache-write-usage.js +26 -0
  28. package/dist/models/images.js +5 -1
  29. package/dist/models/prices.d.ts +8 -6
  30. package/dist/models/prices.js +28 -3
  31. package/dist/orgs/settings.controller.d.ts +4 -17
  32. package/dist/orgs/settings.controller.js +5 -9
  33. package/dist/orgs/settings.service.d.ts +12 -0
  34. package/dist/orgs/settings.service.js +24 -0
  35. package/dist/platform/exclusions.js +6 -0
  36. package/dist/platform/ops/admin.ops.js +2 -2
  37. package/dist/platform/ops/conversations.ops.js +1 -1
  38. package/dist/platform/ops/devices.ops.js +7 -0
  39. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  40. package/dist/platform/ops/org-settings.ops.js +10 -10
  41. package/dist/runtime/context/build.d.ts +2 -0
  42. package/dist/runtime/context/build.js +9 -1
  43. package/dist/runtime/usage-report.js +3 -0
  44. package/dist/sandbox/legacy-retirement.d.ts +15 -0
  45. package/dist/sandbox/legacy-retirement.js +243 -3
  46. package/dist/sandbox/permission-instance-writes.d.ts +4 -1
  47. package/dist/sandbox/permission-instance-writes.js +55 -1
  48. package/dist/sandbox/providers.d.ts +6 -1
  49. package/dist/sandbox/providers.js +15 -1
  50. package/dist/sandbox/sandbox.service.d.ts +6 -3
  51. package/dist/sandbox/sandbox.service.js +116 -5
  52. package/dist/tools/builtins/sandbox/common.js +10 -6
  53. package/dist/tools/connector-tools-jobs.d.ts +3 -2
  54. package/dist/tools/connectors.service.d.ts +3 -1
  55. package/dist/tools/connectors.service.js +64 -12
  56. package/dist/tools/drift.d.ts +1 -1
  57. package/dist/tools/drift.js +13 -13
  58. package/package.json +2 -2
  59. package/src/migrations/0202_connector_endpoint_changed_at.sql +1 -0
  60. package/src/migrations/0203_model_cache_write_pricing.sql +5 -0
  61. package/src/migrations/0204_device_instance_retirement_identities.sql +46 -0
@@ -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;
@@ -7,6 +7,7 @@ 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 { validateCacheWriteByTtl, } from "@capybara-hq/plugin-sdk";
10
11
  import { Inject, Injectable } from "@nestjs/common";
11
12
  import { z } from "zod";
12
13
  import { ApiError } from "../errors.js";
@@ -17,20 +18,36 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
17
18
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
19
  /** 价格表的键。供应商名与模型 id 不含换行,拼接不会撞键。 */
19
20
  export const priceKey = (provider, model) => `${provider}\n${model}`;
20
- /** 一次调用的估算成本;没有价格 → null。用量的四项互不重叠(见 plugin-sdk `ModelUsage`)。 */
21
+ /** Estimates a call's cost from its validated write breakdown, or the generic rates. */
21
22
  export function costOf(usage, price) {
23
+ const classifiedWrites = validateCacheWriteByTtl(usage) === null ? usage.cacheWriteByTtl : undefined;
24
+ return costOfUsageTotals(usage, price, classifiedWrites);
25
+ }
26
+ /** Group totals can include both classified and unclassified writes. */
27
+ export function costOfUsageTotals(usage, price, classifiedWrites = []) {
22
28
  if (price === undefined)
23
29
  return null;
24
30
  const cacheRead = price.cacheReadPerMTok ?? price.inputPerMTok;
25
31
  const cacheWrite = price.cacheWritePerMTok ?? price.inputPerMTok;
32
+ let unclassified = usage.cacheWriteTokens;
33
+ let writeCost = 0;
34
+ for (const { ttl, tokens } of classifiedWrites) {
35
+ writeCost += tokens * (price.cacheWritePerMTokByTtl?.[ttl] ?? cacheWrite);
36
+ unclassified -= tokens;
37
+ }
26
38
  return ((usage.inputTokens * price.inputPerMTok +
27
39
  usage.outputTokens * price.outputPerMTok +
28
40
  usage.cacheReadTokens * cacheRead +
29
- usage.cacheWriteTokens * cacheWrite) /
41
+ writeCost +
42
+ unclassified * cacheWrite) /
30
43
  1_000_000);
31
44
  }
32
- /** 单价:≥ 0 且 ≤ 1e6(有限数)。 */
45
+ /** Price per million tokens, between zero and one million inclusive. */
33
46
  const PerMTok = z.number().min(0).max(1_000_000);
47
+ const TtlSeconds = z
48
+ .string()
49
+ .regex(/^[1-9][0-9]*$/)
50
+ .refine((key) => Number.isSafeInteger(Number(key)));
34
51
  const Name = z.string().min(1).max(200);
35
52
  /** `PUT /api/v1/admin/model-prices` 的 body:设一个价格,或 `price: null` 删除。 */
36
53
  export const MODEL_PRICE_PUT = z.union([
@@ -42,6 +59,7 @@ export const MODEL_PRICE_PUT = z.union([
42
59
  outputPerMTok: PerMTok,
43
60
  cacheReadPerMTok: PerMTok.nullable(),
44
61
  cacheWritePerMTok: PerMTok.nullable(),
62
+ cacheWritePerMTokByTtl: z.record(TtlSeconds, PerMTok).exactOptional(),
45
63
  })
46
64
  .strict(),
47
65
  z.object({ provider: Name, model: Name, price: z.null() }).strict(),
@@ -69,6 +87,7 @@ let PricesService = class PricesService {
69
87
  "output_per_mtok",
70
88
  "cache_read_per_mtok",
71
89
  "cache_write_per_mtok",
90
+ "cache_write_per_mtok_by_ttl",
72
91
  ])
73
92
  .orderBy("provider")
74
93
  .orderBy("model")
@@ -80,6 +99,9 @@ let PricesService = class PricesService {
80
99
  outputPerMTok: num(r.output_per_mtok),
81
100
  cacheReadPerMTok: numOrNull(r.cache_read_per_mtok),
82
101
  cacheWritePerMTok: numOrNull(r.cache_write_per_mtok),
102
+ ...(Object.keys(r.cache_write_per_mtok_by_ttl).length > 0 && {
103
+ cacheWritePerMTokByTtl: r.cache_write_per_mtok_by_ttl,
104
+ }),
83
105
  }));
84
106
  }
85
107
  /** 价格表(按 {@link priceKey} 查)。 */
@@ -123,6 +145,9 @@ let PricesService = class PricesService {
123
145
  output_per_mtok: v.outputPerMTok,
124
146
  cache_read_per_mtok: v.cacheReadPerMTok,
125
147
  cache_write_per_mtok: v.cacheWritePerMTok,
148
+ ...(v.cacheWritePerMTokByTtl !== undefined && {
149
+ cache_write_per_mtok_by_ttl: JSON.stringify(v.cacheWritePerMTokByTtl),
150
+ }),
126
151
  updated_by: actorAccountId,
127
152
  };
128
153
  await this.db
@@ -1,23 +1,10 @@
1
1
  import { type Principal } from "../identity/principal.js";
2
2
  import { type OrgContext } from "./org.guard.js";
3
- import { type OrgEffectiveNetwork, type OrgSandboxLimits, type OrgSettingsDeployment, type OrgSettingsPatch, OrgSettingsService, type OrgSettingsView } from "./settings.service.js";
4
- /**
5
- * 组织设置(`/api/v1/orgs/:orgId/settings`):成员可读,修改需 `org.update`(admin)。
6
- * 响应带 `deployment`(部署默认值,如沙箱出站),设置页据此展示「跟随部署」时的实际取值;
7
- * 以及只读的 `sandboxLimits`(组织实际生效的沙箱 cpu / 内存与来源,超级管理员在部署设置里覆盖,C19)。
8
- */
9
- type SettingsResponse = {
10
- /** `automations.forbiddenToolsUnreadable: true` when the stored list cannot be read. */
11
- settings: OrgSettingsView;
12
- deployment: OrgSettingsDeployment;
13
- /** The org's effective sandbox-mode network (org egress ceiling spec §D4). */
14
- effectiveNetwork: OrgEffectiveNetwork;
15
- sandboxLimits: OrgSandboxLimits;
16
- };
3
+ import { type OrgSettingsPatch, type OrgSettingsResponse, OrgSettingsService } from "./settings.service.js";
4
+ /** Organization settings, readable by members and writable by org admins. */
17
5
  export declare class OrgSettingsController {
18
6
  private readonly settings;
19
7
  constructor(settings: OrgSettingsService);
20
- get(org: OrgContext): Promise<SettingsResponse>;
21
- update(principal: Principal, org: OrgContext, body: OrgSettingsPatch): Promise<SettingsResponse>;
8
+ get(principal: Principal, org: OrgContext): Promise<OrgSettingsResponse>;
9
+ update(principal: Principal, org: OrgContext, body: OrgSettingsPatch): Promise<OrgSettingsResponse>;
22
10
  }
23
- export {};
@@ -15,19 +15,14 @@ import { CurrentOrg, OrgAction } from "./org.guard.js";
15
15
  import { OrgSettingsPatchSchema, OrgSettingsService, } from "./settings.service.js";
16
16
  class OrgSettingsPatchBody extends createZodDto(OrgSettingsPatchSchema, "OrgSettingsPatch") {
17
17
  }
18
+ /** Organization settings, readable by members and writable by org admins. */
18
19
  let OrgSettingsController = class OrgSettingsController {
19
20
  settings;
20
21
  constructor(settings) {
21
22
  this.settings = settings;
22
23
  }
23
- async get(org) {
24
- const settings = await this.settings.get(org.orgId);
25
- return {
26
- settings,
27
- deployment: await this.settings.deployment(),
28
- effectiveNetwork: this.settings.effectiveNetwork(settings),
29
- sandboxLimits: await this.settings.sandboxLimits(org.orgId),
30
- };
24
+ get(principal, org) {
25
+ return this.settings.view(org.orgId, principal.kind === "user" ? org.role : null);
31
26
  }
32
27
  async update(principal, org, body) {
33
28
  const p = requireUser(principal);
@@ -44,7 +39,8 @@ let OrgSettingsController = class OrgSettingsController {
44
39
  __decorate([
45
40
  Get(),
46
41
  OrgAction("org.read"),
47
- __param(0, CurrentOrg())
42
+ __param(0, CurrentPrincipal()),
43
+ __param(1, CurrentOrg())
48
44
  ], OrgSettingsController.prototype, "get", null);
49
45
  __decorate([
50
46
  Patch(),
@@ -14,6 +14,7 @@ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js
14
14
  import { type ExternalSharingView } from "../shares/settings.js";
15
15
  import { type DeviceNetworkSetting } from "./device-network-setting.js";
16
16
  import { OrgLock } from "./org-lock.js";
17
+ import { type OrgRole } from "./roles.js";
17
18
  /**
18
19
  * Org settings (`capybara.orgs.settings` jsonb). Read leniently: a missing or invalid field reads
19
20
  * as its default and unknown keys are kept (merged with the stored value on update), so a new
@@ -454,6 +455,15 @@ export interface OrgSettingsDeployment {
454
455
  /** The platform's prompt suggestions switch (off: the org's own switch has no effect). */
455
456
  promptSuggestions: "on" | "off";
456
457
  }
458
+ /** The settings read and the effective values displayed in the org's settings pages. */
459
+ export interface OrgSettingsResponse {
460
+ settings: OrgSettingsView;
461
+ deployment: OrgSettingsDeployment;
462
+ effectiveNetwork: OrgEffectiveNetwork;
463
+ sandboxLimits: OrgSandboxLimits;
464
+ /** Distinct ready blobs referenced by an org file or share, for user admins only. */
465
+ fileLibraryBytes?: number;
466
+ }
457
467
  /**
458
468
  * Parses the stored jsonb into settings (leniently, see {@link OrgSettingsSchema}).
459
469
  * `outsideSandbox` and `deviceNetwork` are read over the new and the old keys the permission
@@ -574,6 +584,8 @@ export declare class OrgSettingsService {
574
584
  effectiveNetwork(settings: Pick<OrgSettings, "deviceNetwork">): OrgEffectiveNetwork;
575
585
  /** 组织实际生效的沙箱 cpu / 内存(只读;由超级管理员在部署设置里覆盖)。 */
576
586
  sandboxLimits(orgId: string): Promise<OrgSandboxLimits>;
587
+ view(orgId: string, role: OrgRole | null): Promise<OrgSettingsResponse>;
588
+ private fileLibraryBytes;
577
589
  get(orgId: string): Promise<OrgSettingsView>;
578
590
  /**
579
591
  * The refusals of {@link update} that need no read of the org (the Platform tool's precheck):
@@ -14,6 +14,7 @@ import { z } from "zod";
14
14
  import { readPlatformAttribution, } from "../attribution/platform-attribution.js";
15
15
  import { DeviceProviderName } from "../devices/default-provider-setting.js";
16
16
  import { ApiError } from "../errors.js";
17
+ import { blobUnreferenced } from "../files/blob-references.js";
17
18
  import { audit } from "../identity/audit.js";
18
19
  import { COMPACTION_SETTINGS_PARTIAL, COMPACTION_SETTINGS_PATCH, PROMPT_CACHE_SETTINGS_PARTIAL, PROMPT_CACHE_SETTINGS_PATCH, readPlatformCompactionSettings, readPlatformPromptCacheSettings, readPromptSuggestions, readSandboxLimitOverride, } from "../identity/settings.js";
19
20
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -32,6 +33,7 @@ import { IanaTimeZone } from "../time-zone.js";
32
33
  import { mergeArrangement, OrgUiArrangementPatchSchema, UiArrangementSchema, } from "../ui/arrangement.js";
33
34
  import { DeviceNetworkSettingSchema, invalidDeviceNetwork, } from "./device-network-setting.js";
34
35
  import { OrgLock, OrgLockModule } from "./org-lock.js";
36
+ import { can } from "./roles.js";
35
37
  /**
36
38
  * Org settings (`capybara.orgs.settings` jsonb). Read leniently: a missing or invalid field reads
37
39
  * as its default and unknown keys are kept (merged with the stored value on update), so a new
@@ -602,6 +604,28 @@ let OrgSettingsService = class OrgSettingsService {
602
604
  source: override === undefined ? "deployment" : "override",
603
605
  };
604
606
  }
607
+ async view(orgId, role) {
608
+ const settings = await this.get(orgId);
609
+ return {
610
+ settings,
611
+ deployment: await this.deployment(),
612
+ effectiveNetwork: this.effectiveNetwork(settings),
613
+ sandboxLimits: await this.sandboxLimits(orgId),
614
+ ...(role !== null && can(role, "org.update")
615
+ ? { fileLibraryBytes: await this.fileLibraryBytes(orgId) }
616
+ : {}),
617
+ };
618
+ }
619
+ async fileLibraryBytes(orgId) {
620
+ const row = await this.db.db
621
+ .selectFrom("blobs")
622
+ .select(({ fn }) => fn.sum("size").as("bytes"))
623
+ .where("org_id", "=", orgId)
624
+ .where("status", "=", "ready")
625
+ .where((eb) => eb.not(blobUnreferenced(orgId)(eb)))
626
+ .executeTakeFirstOrThrow();
627
+ return Number(row.bytes ?? 0);
628
+ }
605
629
  async get(orgId) {
606
630
  const row = await this.db
607
631
  .selectFrom("orgs")
@@ -101,6 +101,12 @@ export const PLATFORM_EXCLUSIONS = [
101
101
  category: "transport",
102
102
  reason: "Redirects to the avatar image for <img>; no agent use",
103
103
  },
104
+ // devices
105
+ {
106
+ route: "POST /api/v1/orgs/:orgId/devices/:id/retirement/check",
107
+ category: "human-only",
108
+ reason: "An owner initiates the machine proof check from their authenticated device page",
109
+ },
104
110
  // background
105
111
  {
106
112
  route: "GET /api/v1/orgs/:orgId/conversations/:id/background-tasks/:taskId/output",
@@ -550,7 +550,7 @@ let AdminOperations = class AdminOperations {
550
550
  }),
551
551
  defineOperation({
552
552
  id: "models.prices",
553
- description: "The model price table (super admin): price per million tokens for input, output, cache read and cache write, by provider and model, in the deployment's currency. Pages by 50: pass the returned next as params.cursor.",
553
+ description: "The model price table (super admin): price per million tokens for input, output, cache read and cache write (including configured TTL tiers), by provider and model, in the deployment's currency. Pages by 50: pass the returned next as params.cursor.",
554
554
  input: z.object({ cursor: Cursor.optional() }).strict(),
555
555
  example: {},
556
556
  authz: { superAdmin: true },
@@ -564,7 +564,7 @@ let AdminOperations = class AdminOperations {
564
564
  }),
565
565
  defineOperation({
566
566
  id: "models.set-price",
567
- description: "Set the price of one model per million tokens (super admin): provider, model, inputPerMTok, outputPerMTok, cacheReadPerMTok and cacheWritePerMTok (null when the model has none); or provider, model and price: null to remove its price. Prices only estimate costs in the deployment's currency.",
567
+ description: "Set the price of one model per million tokens (super admin): provider, model, inputPerMTok, outputPerMTok, cacheReadPerMTok and cacheWritePerMTok (null to use the input price). Optional cacheWritePerMTokByTtl maps TTL seconds to prices; omit to keep saved tiers, or pass {} to clear them. Or pass provider, model and price: null to remove its price. Prices only estimate costs in the deployment's currency.",
568
568
  input: MODEL_PRICE_PUT,
569
569
  example: {
570
570
  provider: "model-fake",
@@ -257,7 +257,7 @@ let ConversationsOperations = class ConversationsOperations {
257
257
  }),
258
258
  defineOperation({
259
259
  id: "conversations.usage",
260
- description: "Read the token usage of one of your conversations, its sub-agents included: input, output, cache read and cache write tokens. Takes the id from conversations.list.",
260
+ description: "Read the token usage of one of your conversations, its sub-agents included: input, output, cache read and cache write tokens, with a breakdown of classified cache writes by TTL when available. Takes the id from conversations.list.",
261
261
  input: Id,
262
262
  example: { conversationId: "3f2b8a40-6c1d-4e0b-9a77-5d1e2c8b9f10" },
263
263
  authz: { orgAction: "agents.use" },
@@ -16,6 +16,7 @@ import { DeviceCreateBody, DeviceNameBody, DeviceNetworkBody, DeviceParams, Devi
16
16
  import { deviceLabel } from "../../devices/label.js";
17
17
  import { KernelDb } from "../../infra/database/kernel-db.js";
18
18
  import { rootConversationOf } from "../../runtime/subagents/child.js";
19
+ import { LOCAL_RETIREMENT_PROVIDER } from "../../sandbox/providers.js";
19
20
  import { defineOperation } from "../operation.js";
20
21
  import { PlatformOperations } from "../registry.js";
21
22
  import { precheckBy, viaAgent } from "./errors.js";
@@ -49,6 +50,12 @@ function stateOf(e) {
49
50
  };
50
51
  }
51
52
  if (e.retirement === "recreateRequired") {
53
+ if (e.provider === LOCAL_RETIREMENT_PROVIDER && e.dialIn)
54
+ return {
55
+ state: "recreate_required",
56
+ reason: "Earlier background work on the connected machine has not been confirmed stopped.",
57
+ next: "Ask the device owner to open the device page and choose Check again.",
58
+ };
52
59
  return {
53
60
  state: "recreate_required",
54
61
  reason: "Background work an earlier instance of it started may still run and can no longer be confirmed stopped; nothing runs on it.",
@@ -1,4 +1,5 @@
1
1
  import { type OnModuleInit } from "@nestjs/common";
2
+ import { KernelDb } from "../../infra/database/kernel-db.js";
2
3
  import { OrgSettingsService } from "../../orgs/settings.service.js";
3
4
  import { ThemesService } from "../../themes/themes.service.js";
4
5
  import { PlatformOperations } from "../registry.js";
@@ -13,6 +14,7 @@ export declare class OrgSettingsOperations implements OnModuleInit {
13
14
  private readonly registry;
14
15
  private readonly settings;
15
16
  private readonly themes;
16
- constructor(registry: PlatformOperations, settings: OrgSettingsService, themes: ThemesService);
17
+ private readonly db;
18
+ constructor(registry: PlatformOperations, settings: OrgSettingsService, themes: ThemesService, db: KernelDb);
17
19
  onModuleInit(): void;
18
20
  }
@@ -9,11 +9,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { z } from "zod";
12
+ import { KernelDb } from "../../infra/database/kernel-db.js";
12
13
  import { OrgSettingsPatchSchema, OrgSettingsService } from "../../orgs/settings.service.js";
13
14
  import { ThemesService } from "../../themes/themes.service.js";
14
15
  import { defineOperation } from "../operation.js";
15
16
  import { PlatformOperations } from "../registry.js";
16
17
  import { precheckBy, viaAgent } from "./errors.js";
18
+ import { roleOf } from "./role.js";
17
19
  const PLATFORM_TOOL_NOTE = {
18
20
  off: "The Platform tool is now off for this org: from the next call on, no Platform operation is available, including this one. An org admin can switch it back on in the organization settings on the web.",
19
21
  "read-only": "The Platform tool is now read-only for this org: from the next call on, writes are unavailable and only reads run. An org admin can change it in the organization settings on the web.",
@@ -30,29 +32,26 @@ let OrgSettingsOperations = class OrgSettingsOperations {
30
32
  registry;
31
33
  settings;
32
34
  themes;
33
- constructor(registry, settings, themes) {
35
+ db;
36
+ constructor(registry, settings, themes, db) {
34
37
  this.registry = registry;
35
38
  this.settings = settings;
36
39
  this.themes = themes;
40
+ this.db = db;
37
41
  }
38
42
  onModuleInit() {
39
43
  this.registry.register([
40
44
  defineOperation({
41
45
  id: "org-settings.get",
42
- description: "Read this org's settings: toolSearch, locale, sandboxToolPolicy, platformTool (on, read-only or off), outsideSandbox (allowed or off: whether the org's devices may be granted running a call outside their sandbox; absent follows the deployment, and the org may never exceed it), deviceNetwork (the org's device sandbox network: default, the network a device gets when its owner chooses none, and ceiling, the widest a device may choose, each open or allowlist and absent following the platform; base platform or none; extraHosts the org adds; excludedHosts platform hosts it drops; open means any public host, while loopback, private and cloud metadata addresses stay closed), wakeOnBackgroundTask (absent means it follows the deployment), theme (the org's default theme id, null or absent following the platform, and personal: allowed or locked), navigation (pluginPages: per plugin page contribution key <extension>/<contribution>, the section primary or more an org admin chose; at most 3 primary; absent means every page follows its own suggestion), uiArrangement (per list slot, the extension contributions the org hides and their order; per single slot, the contribution that replaces the built-in as use, null for the built-in; a slot not listed follows the platform), the deployment's outside-sandbox switch (outsideSandbox) and device network (deviceNetwork: its default and ceiling, its allowlist, orgHosts: extend lets the org go beyond the allowlist, within makes it the hosts' ceiling, and off for the platform kill switch), effectiveNetwork (the mode and hosts the org's devices really get), externalSharing (on or off, absent meaning off: whether members may share conversation files through public links; the deployment's externalSharing must be allow too) with the deployment's externalSharing and shareMaxExpiryDays, promptSuggestions (on or off, absent meaning on: whether the composer suggests the person's next message after a completed run; the deployment's promptSuggestions must be on too) with the deployment's promptSuggestions, and the sandbox cpu / memory limits in effect.",
46
+ description: "Read this org's settings: toolSearch, locale, sandboxToolPolicy, platformTool (on, read-only or off), outsideSandbox (allowed or off: whether the org's devices may be granted running a call outside their sandbox; absent follows the deployment, and the org may never exceed it), deviceNetwork (the org's device sandbox network: default, the network a device gets when its owner chooses none, and ceiling, the widest a device may choose, each open or allowlist and absent following the platform; base platform or none; extraHosts the org adds; excludedHosts platform hosts it drops; open means any public host, while loopback, private and cloud metadata addresses stay closed), wakeOnBackgroundTask (absent means it follows the deployment), theme (the org's default theme id, null or absent following the platform, and personal: allowed or locked), navigation (pluginPages: per plugin page contribution key <extension>/<contribution>, the section primary or more an org admin chose; at most 3 primary; absent means every page follows its own suggestion), uiArrangement (per list slot, the extension contributions the org hides and their order; per single slot, the contribution that replaces the built-in as use, null for the built-in; a slot not listed follows the platform), the deployment's outside-sandbox switch (outsideSandbox) and device network (deviceNetwork: its default and ceiling, its allowlist, orgHosts: extend lets the org go beyond the allowlist, within makes it the hosts' ceiling, and off for the platform kill switch), effectiveNetwork (the mode and hosts the org's devices really get), externalSharing (on or off, absent meaning off: whether members may share conversation files through public links; the deployment's externalSharing must be allow too) with the deployment's externalSharing and shareMaxExpiryDays, promptSuggestions (on or off, absent meaning on: whether the composer suggests the person's next message after a completed run; the deployment's promptSuggestions must be on too) with the deployment's promptSuggestions, the sandbox cpu / memory limits in effect, and fileLibraryBytes (the org-wide storage total for org admins).",
43
47
  input: z.object({}).strict(),
44
48
  example: {},
45
49
  authz: { orgAction: "org.read" },
46
50
  mirrors: ["GET /api/v1/orgs/:orgId/settings"],
47
51
  confirm: "read",
48
52
  run: async (_input, ctx) => {
49
- const settings = await this.settings.get(ctx.orgId);
50
- return {
51
- settings,
52
- deployment: await this.settings.deployment(),
53
- effectiveNetwork: this.settings.effectiveNetwork(settings),
54
- sandboxLimits: await this.settings.sandboxLimits(ctx.orgId),
55
- };
53
+ const role = await roleOf(this.db.db, ctx.orgId, ctx.actorAccountId);
54
+ return this.settings.view(ctx.orgId, role);
56
55
  },
57
56
  }),
58
57
  defineOperation({
@@ -151,6 +150,7 @@ OrgSettingsOperations = __decorate([
151
150
  Injectable(),
152
151
  __param(0, Inject(PlatformOperations)),
153
152
  __param(1, Inject(OrgSettingsService)),
154
- __param(2, Inject(ThemesService))
153
+ __param(2, Inject(ThemesService)),
154
+ __param(3, Inject(KernelDb))
155
155
  ], OrgSettingsOperations);
156
156
  export { OrgSettingsOperations };
@@ -297,6 +297,8 @@ export declare const attachmentReferenceText: (input: {
297
297
  uri: string;
298
298
  /** The content is text the model could read: it was not inlined because it is too long. */
299
299
  text?: boolean;
300
+ /** Set only for a text attachment whose log block carries the Read hint marker. */
301
+ readFileId?: string;
300
302
  }) => string;
301
303
  /** {@link resolveMedia} 的输入:行信息、字节与本次请求的媒体计划。 */
302
304
  export interface MediaContext {
@@ -347,7 +347,10 @@ export const attachmentReferenceText = (input) => {
347
347
  const why = input.text
348
348
  ? `${input.size} bytes of text; not sent inline. The file is available in the device on request.`
349
349
  : `${input.size} bytes — this model cannot read its content.`;
350
- return `[Attached file ${quoted(input.name)} (${input.mediaType}), ${why} Unsigned object reference: ${input.uri}. Use FetchAttachment with the file name or this reference to copy it into the device.]`;
350
+ const readHint = input.readFileId === undefined
351
+ ? ""
352
+ : ` If Read is available, use Read with file_id ${quoted(input.readFileId)} to read the text without a device.`;
353
+ return `[Attached file ${quoted(input.name)} (${input.mediaType}), ${why} Unsigned object reference: ${input.uri}. Use FetchAttachment with the file name or this reference to copy it into the device.${readHint}]`;
351
354
  };
352
355
  function placeholder(b, name) {
353
356
  if (b.type === "image") {
@@ -427,6 +430,11 @@ export function resolveMedia(content, model, ctx) {
427
430
  size: row.size,
428
431
  uri: row.uri,
429
432
  text: asText,
433
+ ...("readByFileId" in b &&
434
+ b.readByFileId === true &&
435
+ isText(b.mediaType) && {
436
+ readFileId: id,
437
+ }),
430
438
  });
431
439
  const mode = mediaMode(b, model);
432
440
  if (b.type === "file") {
@@ -253,6 +253,7 @@ let UsageReporter = class UsageReporter {
253
253
  "output_tokens",
254
254
  "cache_read_tokens",
255
255
  "cache_write_tokens",
256
+ "cache_write_by_ttl",
256
257
  "output_images",
257
258
  "occurred_at",
258
259
  ])
@@ -273,6 +274,7 @@ let UsageReporter = class UsageReporter {
273
274
  outputTokens: row.output_tokens,
274
275
  cacheReadTokens: row.cache_read_tokens,
275
276
  cacheWriteTokens: row.cache_write_tokens,
277
+ ...(row.cache_write_by_ttl !== null && { cacheWriteByTtl: row.cache_write_by_ttl }),
276
278
  ...(row.output_images > 0 && { outputImages: row.output_images }),
277
279
  },
278
280
  occurredAt: new Date(row.occurred_at).toISOString(),
@@ -359,6 +361,7 @@ let UsageReporter = class UsageReporter {
359
361
  outputTokens: p.outputTokens,
360
362
  cacheReadTokens: p.cacheReadTokens,
361
363
  cacheWriteTokens: p.cacheWriteTokens,
364
+ ...(p.cacheWriteByTtl !== undefined && { cacheWriteByTtl: p.cacheWriteByTtl }),
362
365
  ...(typeof p.outputImages === "number" && { outputImages: p.outputImages }),
363
366
  },
364
367
  occurredAt: new Date(row.created_at).toISOString(),