@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
@@ -1,3 +1,4 @@
1
+ import type { CacheWriteByTtl } from "@capybara-hq/plugin-sdk";
1
2
  import { SettingsService } from "../identity/settings.js";
2
3
  import { CacheService } from "../infra/cache/cache.service.js";
3
4
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -90,6 +91,7 @@ interface TokenRow {
90
91
  output: string;
91
92
  cache_read: string;
92
93
  cache_write: string;
94
+ cache_write_by_ttl: CacheWriteByTtl[] | null;
93
95
  }
94
96
  interface RunRow {
95
97
  day: string;
@@ -138,8 +140,8 @@ export declare class AdminUsageService {
138
140
  /**
139
141
  * The three grouped queries over `[from, to)` (spec §5.4), each on its time index:
140
142
  * `conversation_events_usage_idx`, `runs_created_idx`, `model_usage_time_idx`. Rows are bounded by
141
- * days × orgs (× models), not by events. Days are calendar days in `tz` (`YYYY-MM-DD` text, so no
142
- * driver turns them into local-time dates).
143
+ * days × orgs (× models), with cache writes grouped by tier within each row. Days are calendar
144
+ * days in `tz` (`YYYY-MM-DD` text, so no driver turns them into local-time dates).
143
145
  */
144
146
  export declare function usageQueries(tz: string, from: Date, to: Date): {
145
147
  tokens: import("kysely").RawBuilder<TokenRow>;
@@ -16,7 +16,8 @@ import { Cacheable } from "../infra/cache/cacheable.decorator.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
17
  import { runOutsideTransaction, TransactionHost } from "../infra/database/transaction-host.js";
18
18
  import { Transactional } from "../infra/database/transactional.decorator.js";
19
- import { costOf, PricesService, priceKey } from "../models/prices.js";
19
+ import { cacheWriteTierRows } from "../models/cache-write-usage.js";
20
+ import { costOf, costOfUsageTotals, PricesService, priceKey, } from "../models/prices.js";
20
21
  /** Seam token of the kernel's own tests: a shorter statement timeout and a fixed clock. */
21
22
  export const ADMIN_USAGE_TIMINGS = Symbol("ADMIN_USAGE_TIMINGS");
22
23
  /** Days in the window: today and the 6 days before. */
@@ -180,8 +181,8 @@ export { AdminUsageService };
180
181
  /**
181
182
  * The three grouped queries over `[from, to)` (spec §5.4), each on its time index:
182
183
  * `conversation_events_usage_idx`, `runs_created_idx`, `model_usage_time_idx`. Rows are bounded by
183
- * days × orgs (× models), not by events. Days are calendar days in `tz` (`YYYY-MM-DD` text, so no
184
- * driver turns them into local-time dates).
184
+ * days × orgs (× models), with cache writes grouped by tier within each row. Days are calendar
185
+ * days in `tz` (`YYYY-MM-DD` text, so no driver turns them into local-time dates).
185
186
  */
186
187
  export function usageQueries(tz, from, to) {
187
188
  // a malformed payload value (a string, null) counts 0 and a fraction is rounded, so one bad
@@ -192,17 +193,36 @@ export function usageQueries(tz, from, to) {
192
193
  return {
193
194
  // chat tokens: every `usage` event (steps, compaction, titles, web fetch), by day × org × model
194
195
  tokens: sql `
195
- SELECT ${day("e.created_at")} AS day, c.org_id,
196
- coalesce(e.payload->>'provider', '') AS provider,
197
- coalesce(e.payload->>'model', '') AS model,
198
- ${tokenSum("inputTokens")} AS input,
199
- ${tokenSum("outputTokens")} AS output,
200
- ${tokenSum("cacheReadTokens")} AS cache_read,
201
- ${tokenSum("cacheWriteTokens")} AS cache_write
202
- FROM capybara.conversation_events e
203
- JOIN capybara.conversations c ON c.id = e.conversation_id
204
- WHERE e.type = 'usage' AND e.created_at >= ${from} AND e.created_at < ${to}
205
- GROUP BY 1, 2, 3, 4
196
+ WITH usage_events AS NOT MATERIALIZED (
197
+ SELECT ${day("e.created_at")} AS day, c.org_id,
198
+ coalesce(e.payload->>'provider', '') AS provider,
199
+ coalesce(e.payload->>'model', '') AS model,
200
+ e.payload
201
+ FROM capybara.conversation_events e
202
+ JOIN capybara.conversations c ON c.id = e.conversation_id
203
+ WHERE e.type = 'usage' AND e.created_at >= ${from} AND e.created_at < ${to}
204
+ ), write_tiers AS (
205
+ SELECT e.day, e.org_id, e.provider, e.model, tier.ttl, sum(tier.tokens) AS tokens
206
+ FROM usage_events e
207
+ CROSS JOIN LATERAL (${cacheWriteTierRows(sql `e.payload`)}) tier
208
+ WHERE e.payload ? 'cacheWriteByTtl'
209
+ GROUP BY 1, 2, 3, 4, 5
210
+ ), breakdowns AS (
211
+ SELECT day, org_id, provider, model,
212
+ jsonb_agg(jsonb_build_object('ttl', ttl, 'tokens', tokens) ORDER BY ttl) AS tiers
213
+ FROM write_tiers
214
+ GROUP BY 1, 2, 3, 4
215
+ ), totals AS (
216
+ SELECT day, org_id, provider, model,
217
+ ${tokenSum("inputTokens")} AS input,
218
+ ${tokenSum("outputTokens")} AS output,
219
+ ${tokenSum("cacheReadTokens")} AS cache_read,
220
+ ${tokenSum("cacheWriteTokens")} AS cache_write
221
+ FROM usage_events e
222
+ GROUP BY 1, 2, 3, 4
223
+ )
224
+ SELECT totals.*, breakdowns.tiers AS cache_write_by_ttl
225
+ FROM totals LEFT JOIN breakdowns USING (day, org_id, provider, model)
206
226
  `,
207
227
  // runs: every run (sub-agent and eval replay runs included, D6), by day × org
208
228
  runs: sql `
@@ -258,7 +278,7 @@ function summarize(input) {
258
278
  cacheWriteTokens: Number(r.cache_write),
259
279
  };
260
280
  const total = usage.inputTokens + usage.outputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
261
- const cost = costOf(usage, price(r.provider, r.model));
281
+ const cost = costOfUsageTotals(usage, price(r.provider, r.model), r.cache_write_by_ttl ?? undefined);
262
282
  if (cost === null && total > 0)
263
283
  costPartial = true;
264
284
  d.day.tokens.input += usage.inputTokens;
@@ -597,9 +597,10 @@ let ComponentScopeService = class ComponentScopeService {
597
597
  });
598
598
  }
599
599
  // A connector template switched on where its plugin is installed: its connector now, as an
600
- // install would make it (plugin pages spec §5.2.2), in this transaction
600
+ // install would make it (plugin pages spec §5.2.2), or an ensure once its provider is available
601
601
  if (kind === "connector_template" && body.enabled && componentOn(c, p, listed, true)) {
602
602
  await this.installer.createSwitchedOnTemplateConnectorIn(orgId, actor, c.id, {
603
+ deferUnavailable: true,
603
604
  ...(actorTokenId !== undefined && { actorTokenId }),
604
605
  ...(auditDetail !== undefined && { auditDetail }),
605
606
  });
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.92";
211
+ readonly sdk: "0.1.0-rc.93";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -579,6 +579,7 @@ export declare class PluginInstaller {
579
579
  createSwitchedOnTemplateConnectorIn(orgId: string, actor: string | null, platformTemplateId: string, opts?: {
580
580
  actorTokenId?: string;
581
581
  auditDetail?: AuditDetail;
582
+ deferUnavailable?: boolean;
582
583
  }): Promise<string | undefined>;
583
584
  /**
584
585
  * Records a connector made from one of the item's connector templates on the org's install of
@@ -1762,7 +1762,17 @@ let PluginInstaller = class PluginInstaller {
1762
1762
  return undefined;
1763
1763
  }
1764
1764
  const ct = { id: row.template_id, file: row.file };
1765
- const ci = this.planConnector(actor, { itemId, version: row.version }, ct, "", undefined);
1765
+ const { plugin, connector } = ct.file.template;
1766
+ // Only a missing provider prevents validation. A loaded one still checks the preset
1767
+ // and version before an org switch can defer creation.
1768
+ const ci = opts.deferUnavailable && !findConnectorIn(this.registry, plugin, connector)
1769
+ ? undefined
1770
+ : this.planConnector(actor, { itemId, version: row.version }, ct, "", undefined);
1771
+ if (ci === undefined ||
1772
+ (opts.deferUnavailable && !(await this.connectors.kindAvailable(orgId, connector)))) {
1773
+ await oweTemplateConnectors(this.outbox, this.db, orgId);
1774
+ return undefined;
1775
+ }
1766
1776
  const connectorId = await this.connectors.createDeferredIn(orgId, actor, ci, opts);
1767
1777
  await this.recordTemplateConnectorIn(orgId, itemId, connectorId, ct.id, ["installed"]);
1768
1778
  return connectorId;
@@ -258,7 +258,7 @@ export declare class ConversationsController {
258
258
  }>;
259
259
  /**
260
260
  * The conversation's token usage, its sub-agents' included (sub-agents spec §8.3):
261
- * `{ usage: { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens } }`. Owner only.
261
+ * Includes the cache write breakdown by TTL when available. Owner only.
262
262
  */
263
263
  usage(principal: Principal, org: OrgContext, id: string): Promise<{
264
264
  usage: UsageTotals;
@@ -397,7 +397,7 @@ let ConversationsController = class ConversationsController {
397
397
  }
398
398
  /**
399
399
  * The conversation's token usage, its sub-agents' included (sub-agents spec §8.3):
400
- * `{ usage: { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens } }`. Owner only.
400
+ * Includes the cache write breakdown by TTL when available. Owner only.
401
401
  */
402
402
  async usage(principal, org, id) {
403
403
  const p = requireUser(principal);
@@ -1,4 +1,4 @@
1
- import type { ConversationSource, TriggerSubject } from "@capybara-hq/plugin-sdk";
1
+ import type { CacheWriteByTtl, ConversationSource, TriggerSubject } from "@capybara-hq/plugin-sdk";
2
2
  import { AgentLookup } from "../agents/agent-lookup.js";
3
3
  import type { AgentDefinition, ModelRef } from "../agents/definition.js";
4
4
  import type { AgentAvatarView } from "../agents/profile.js";
@@ -122,12 +122,14 @@ export interface ConversationGroup {
122
122
  /** The group has more than `perGroup` conversations. */
123
123
  more: boolean;
124
124
  }
125
- /** Token usage, the four fields of a `usage` event. */
125
+ /** Token usage summed across conversation events. */
126
126
  export interface UsageTotals {
127
127
  inputTokens: number;
128
128
  outputTokens: number;
129
129
  cacheReadTokens: number;
130
130
  cacheWriteTokens: number;
131
+ /** Classified writes only, sorted by TTL. Older events can contribute to the total alone. */
132
+ cacheWriteByTtl?: CacheWriteByTtl[];
131
133
  }
132
134
  /**
133
135
  * One sub-agent of a conversation (sub-agents spec §14.3). `status`, `toolCalls`, `startedAt` and
@@ -28,6 +28,7 @@ import { TransactionHost, withTransactionFencePrelude, } from "../infra/database
28
28
  import { Transactional } from "../infra/database/transactional.decorator.js";
29
29
  import { KernelEvents } from "../infra/events/kernel-events.js";
30
30
  import { OutboxService } from "../infra/outbox/outbox.service.js";
31
+ import { cacheWriteTierRows } from "../models/cache-write-usage.js";
31
32
  import { projectSkillOf } from "../runtime/context/project-root.js";
32
33
  import { ProviderRegistry } from "../runtime/providers.js";
33
34
  import { RunControl as RunControlService } from "../runtime/run-control.js";
@@ -225,19 +226,31 @@ function storedSubject(s) {
225
226
  }
226
227
  /** The sums of the `usage` events matching `where` (over `conversation_events e`), one row. */
227
228
  const usageSums = (where) => sql `
229
+ WITH usage_events AS (
230
+ SELECT e.payload
231
+ FROM capybara.conversation_events e
232
+ WHERE e.type = 'usage' AND ${where}
233
+ ), write_tiers AS (
234
+ SELECT tier.ttl, sum(tier.tokens) AS tokens
235
+ FROM usage_events e
236
+ CROSS JOIN LATERAL (${cacheWriteTierRows(sql `e.payload`)}) tier
237
+ GROUP BY tier.ttl
238
+ )
228
239
  SELECT
229
240
  coalesce(sum((e.payload->>'inputTokens')::bigint), 0) AS input_tokens,
230
241
  coalesce(sum((e.payload->>'outputTokens')::bigint), 0) AS output_tokens,
231
242
  coalesce(sum((e.payload->>'cacheReadTokens')::bigint), 0) AS cache_read_tokens,
232
- coalesce(sum((e.payload->>'cacheWriteTokens')::bigint), 0) AS cache_write_tokens
233
- FROM capybara.conversation_events e
234
- WHERE e.type = 'usage' AND ${where}
243
+ coalesce(sum((e.payload->>'cacheWriteTokens')::bigint), 0) AS cache_write_tokens,
244
+ (SELECT jsonb_agg(jsonb_build_object('ttl', ttl, 'tokens', tokens) ORDER BY ttl)
245
+ FROM write_tiers) AS cache_write_by_ttl
246
+ FROM usage_events e
235
247
  `;
236
248
  const toUsage = (r) => ({
237
249
  inputTokens: Number(r.input_tokens),
238
250
  outputTokens: Number(r.output_tokens),
239
251
  cacheReadTokens: Number(r.cache_read_tokens),
240
252
  cacheWriteTokens: Number(r.cache_write_tokens),
253
+ ...(r.cache_write_by_ttl !== null && { cacheWriteByTtl: r.cache_write_by_ttl }),
241
254
  });
242
255
  /**
243
256
  * 会话:只有所有者可见;每次访问都实时复核 agent 对所有者仍可用(spec 3.6 R5),
@@ -926,6 +939,7 @@ let ConversationsService = class ConversationsService {
926
939
  WHERE e.conversation_id = c.id AND e.run_id = r.id AND e.type = 'tool_result'
927
940
  ) AS tool_calls,
928
941
  u.input_tokens, u.output_tokens, u.cache_read_tokens, u.cache_write_tokens,
942
+ u.cache_write_by_ttl,
929
943
  ARRAY(SELECT a.id FROM capybara.approvals a
930
944
  WHERE a.conversation_id = c.id AND a.status = 'pending' AND a.expires_at > now()
931
945
  ORDER BY a.created_at, a.id) AS approval_ids,
@@ -475,6 +475,7 @@ export declare const ContentBlockSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
475
475
  }, z.core.$strip>, unknown>;
476
476
  name: z.ZodOptional<z.ZodString>;
477
477
  size: z.ZodOptional<z.ZodNumber>;
478
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
478
479
  }, z.core.$strip>, z.ZodObject<{
479
480
  type: z.ZodLiteral<"file">;
480
481
  mediaType: z.ZodString;
@@ -484,6 +485,7 @@ export declare const ContentBlockSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
484
485
  }, z.core.$strip>, unknown>;
485
486
  name: z.ZodOptional<z.ZodString>;
486
487
  size: z.ZodOptional<z.ZodNumber>;
488
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
487
489
  }, z.core.$strip>], "type">;
488
490
  type MediaBlock = Extract<ContentBlock, {
489
491
  type: "image" | "document" | "file";
@@ -496,7 +498,9 @@ export type LogContentBlock = Exclude<ContentBlock, MediaBlock> | (MediaBlock ex
496
498
  source: Extract<MediaSource, {
497
499
  kind: "ref";
498
500
  }>;
499
- } : never : never);
501
+ } & (B["type"] extends "image" ? unknown : {
502
+ readByFileId?: true;
503
+ }) : never : never);
500
504
  /** The longest handoff card title (`ToolViewSchema` kind `handoff`), per language. */
501
505
  export declare const HANDOFF_TITLE_MAX_CHARS = 200;
502
506
  /** The longest secure input target name (`approval_requested.secureInput.target`), per language. */
@@ -958,6 +962,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
958
962
  }, z.core.$strip>, unknown>;
959
963
  name: z.ZodOptional<z.ZodString>;
960
964
  size: z.ZodOptional<z.ZodNumber>;
965
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
961
966
  }, z.core.$strip>, z.ZodObject<{
962
967
  type: z.ZodLiteral<"file">;
963
968
  mediaType: z.ZodString;
@@ -967,6 +972,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
967
972
  }, z.core.$strip>, unknown>;
968
973
  name: z.ZodOptional<z.ZodString>;
969
974
  size: z.ZodOptional<z.ZodNumber>;
975
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
970
976
  }, z.core.$strip>], "type">>;
971
977
  attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
972
978
  appId: z.ZodString;
@@ -1286,6 +1292,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1286
1292
  }, z.core.$strip>, unknown>;
1287
1293
  name: z.ZodOptional<z.ZodString>;
1288
1294
  size: z.ZodOptional<z.ZodNumber>;
1295
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
1289
1296
  }, z.core.$strip>, z.ZodObject<{
1290
1297
  type: z.ZodLiteral<"file">;
1291
1298
  mediaType: z.ZodString;
@@ -1295,6 +1302,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1295
1302
  }, z.core.$strip>, unknown>;
1296
1303
  name: z.ZodOptional<z.ZodString>;
1297
1304
  size: z.ZodOptional<z.ZodNumber>;
1305
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
1298
1306
  }, z.core.$strip>], "type">>;
1299
1307
  stopReason: z.ZodEnum<{
1300
1308
  aborted: "aborted";
@@ -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"];
@@ -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 { 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
@@ -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
@@ -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` 的运行(排队时就被中止 /
@@ -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
+ }