@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 { 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;
@@ -74,6 +74,8 @@ export interface UnattendedRun {
74
74
  export declare const unattendedRules: (u: UnattendedRun | null | undefined) => u is UnattendedRun;
75
75
  /** In `fail` mode, an unattended run never waits for a person (§7). */
76
76
  export declare const unattendedFails: (u: UnattendedRun | null | undefined) => boolean;
77
+ /** An automation invocation with no person present, regardless of grant eligibility. */
78
+ export declare function hasUnattendedTaskRun(db: KernelSchemaDb, runId: string): Promise<boolean>;
77
79
  /**
78
80
  * The automation context of a run's tool calls (`PolicyContext.unattended`), or null when the
79
81
  * run is attended: it serves no task run, or a person's message joined it ({@link personJoined}).
@@ -150,6 +150,15 @@ async function personJoined(db, runId) {
150
150
  .executeTakeFirst();
151
151
  return row?.joined === true;
152
152
  }
153
+ async function taskRunWithAttendance(db, runId) {
154
+ const run = await unattendedTaskRunOf(db, runId);
155
+ return run !== null && !run.trial && (await personJoined(db, runId)) ? null : run;
156
+ }
157
+ /** An automation invocation with no person present, regardless of grant eligibility. */
158
+ export async function hasUnattendedTaskRun(db, runId) {
159
+ const run = await taskRunWithAttendance(db, runId);
160
+ return run !== null && !run.trial;
161
+ }
153
162
  /**
154
163
  * The automation context of a run's tool calls (`PolicyContext.unattended`), or null when the
155
164
  * run is attended: it serves no task run, or a person's message joined it ({@link personJoined}).
@@ -158,11 +167,9 @@ async function personJoined(db, runId) {
158
167
  * else the org's default.
159
168
  */
160
169
  export async function unattendedRunOf(db, config, orgId, runId) {
161
- const run = await unattendedTaskRunOf(db, runId);
170
+ const run = await taskRunWithAttendance(db, runId);
162
171
  if (run === null)
163
172
  return null;
164
- if (!run.trial && (await personJoined(db, runId)))
165
- return null;
166
173
  const s = await readAutomationSettings(db, config, orgId);
167
174
  // org-filter: the task id is read from the kernel run's own automation_run_id, never input
168
175
  const own = await db
@@ -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.94";
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;
@@ -97,10 +97,8 @@ export declare function commandCardText(detail: Pick<CommandAskDetail, "kind" |
97
97
  workingRoot?: string;
98
98
  }, scopes: readonly string[], locale: ChannelLocale, redact?: (s: string) => string): NetworkCardText;
99
99
  /**
100
- * The `bind` card of a secure input request (or an approval whose Platform call needs the person
101
- * to type secrets): the values pass only through the web, never an IM vendor, so IM gets a link to
102
- * the conversation instead of an approval card. Undefined when the approval does not exist or has
103
- * no person fields.
100
+ * The web handoff for approvals with person fields and for site approvals. The channel gets a
101
+ * link to the conversation and the sensitive request stays on the web.
104
102
  */
105
103
  export declare function personFieldsCard(d: CardDeps, approvalId: string, base: string, locale: ChannelLocale): Promise<Extract<ChannelCard, {
106
104
  kind: "bind";
@@ -325,13 +325,18 @@ export function commandCardText(detail, scopes, locale, redact = (s) => s) {
325
325
  };
326
326
  }
327
327
  /**
328
- * The `bind` card of a secure input request (or an approval whose Platform call needs the person
329
- * to type secrets): the values pass only through the web, never an IM vendor, so IM gets a link to
330
- * the conversation instead of an approval card. Undefined when the approval does not exist or has
331
- * no person fields.
328
+ * The web handoff for approvals with person fields and for site approvals. The channel gets a
329
+ * link to the conversation and the sensitive request stays on the web.
332
330
  */
333
331
  export async function personFieldsCard(d, approvalId, base, locale) {
334
332
  const v = await d.approvals.describe(approvalId);
333
+ if (v?.kind === "network" && v.detail?.kind === "site") {
334
+ return {
335
+ kind: "bind",
336
+ text: phrase("siteApprovalOnWeb", locale),
337
+ url: `${base}${v.conversationPath}`,
338
+ };
339
+ }
335
340
  const n = v?.personFields?.length ?? 0;
336
341
  if (!v || n === 0)
337
342
  return undefined;
@@ -352,8 +357,8 @@ export async function personFieldsCard(d, approvalId, base, locale) {
352
357
  */
353
358
  export async function approvalCard(d, approvalId, base, locale, redact) {
354
359
  const v = await d.approvals.describe(approvalId);
355
- // a secure input is web-only: never an approval card, only the bind link (personFieldsCard)
356
- if (!v || v.kind === "secure_input")
360
+ // Web-only approvals use the bind link from personFieldsCard.
361
+ if (!v || v.kind === "secure_input" || v.detail?.kind === "site")
357
362
  return undefined;
358
363
  const decidedBy = await displayName(d.db, v.decidedBy);
359
364
  // a network, git or command ask names what it asks about instead of a tool call (same shape)
@@ -92,6 +92,10 @@ export declare const CHANNEL_PHRASES: {
92
92
  readonly zh: "需要你的批准";
93
93
  readonly en: "Approval required";
94
94
  };
95
+ readonly siteApprovalOnWeb: {
96
+ readonly zh: "请在网页上审批此网站操作";
97
+ readonly en: "Review this site action on the web";
98
+ };
95
99
  /** A network ask's card title for one host (`{host}`; network ask-to-allow spec §6.5). */
96
100
  readonly networkTitleOne: {
97
101
  readonly zh: "智能体想访问 {host},允许吗?";
@@ -78,6 +78,7 @@ export const CHANNEL_PHRASES = {
78
78
  },
79
79
  /** 审批卡片的标题与随附文本。 */
80
80
  approvalTitle: { zh: "需要你的批准", en: "Approval required" },
81
+ siteApprovalOnWeb: { zh: "请在网页上审批此网站操作", en: "Review this site action on the web" },
81
82
  /** A network ask's card title for one host (`{host}`; network ask-to-allow spec §6.5). */
82
83
  networkTitleOne: {
83
84
  zh: "智能体想访问 {host},允许吗?",
@@ -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
@@ -14,6 +14,7 @@ import { AgentLookup, visibleTo } from "../agents/agent-lookup.js";
14
14
  import { avatarView } from "../agents/avatar-view.js";
15
15
  import { unbindConversation } from "../channels/threads.js";
16
16
  import { oweConversationDeletedNotice } from "../device-access/conversation-notices.js";
17
+ import { revokeSiteGrantsOfConversation } from "../device-access/site-grants.js";
17
18
  import { ConversationDevices, } from "../devices/conversation-devices.js";
18
19
  import { DeviceProjectFilesService } from "../devices/device-project-files.service.js";
19
20
  import { DeviceProjectsService } from "../devices/device-projects.service.js";
@@ -28,6 +29,7 @@ import { TransactionHost, withTransactionFencePrelude, } from "../infra/database
28
29
  import { Transactional } from "../infra/database/transactional.decorator.js";
29
30
  import { KernelEvents } from "../infra/events/kernel-events.js";
30
31
  import { OutboxService } from "../infra/outbox/outbox.service.js";
32
+ import { cacheWriteTierRows } from "../models/cache-write-usage.js";
31
33
  import { projectSkillOf } from "../runtime/context/project-root.js";
32
34
  import { ProviderRegistry } from "../runtime/providers.js";
33
35
  import { RunControl as RunControlService } from "../runtime/run-control.js";
@@ -225,19 +227,31 @@ function storedSubject(s) {
225
227
  }
226
228
  /** The sums of the `usage` events matching `where` (over `conversation_events e`), one row. */
227
229
  const usageSums = (where) => sql `
230
+ WITH usage_events AS (
231
+ SELECT e.payload
232
+ FROM capybara.conversation_events e
233
+ WHERE e.type = 'usage' AND ${where}
234
+ ), write_tiers AS (
235
+ SELECT tier.ttl, sum(tier.tokens) AS tokens
236
+ FROM usage_events e
237
+ CROSS JOIN LATERAL (${cacheWriteTierRows(sql `e.payload`)}) tier
238
+ GROUP BY tier.ttl
239
+ )
228
240
  SELECT
229
241
  coalesce(sum((e.payload->>'inputTokens')::bigint), 0) AS input_tokens,
230
242
  coalesce(sum((e.payload->>'outputTokens')::bigint), 0) AS output_tokens,
231
243
  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}
244
+ coalesce(sum((e.payload->>'cacheWriteTokens')::bigint), 0) AS cache_write_tokens,
245
+ (SELECT jsonb_agg(jsonb_build_object('ttl', ttl, 'tokens', tokens) ORDER BY ttl)
246
+ FROM write_tiers) AS cache_write_by_ttl
247
+ FROM usage_events e
235
248
  `;
236
249
  const toUsage = (r) => ({
237
250
  inputTokens: Number(r.input_tokens),
238
251
  outputTokens: Number(r.output_tokens),
239
252
  cacheReadTokens: Number(r.cache_read_tokens),
240
253
  cacheWriteTokens: Number(r.cache_write_tokens),
254
+ ...(r.cache_write_by_ttl !== null && { cacheWriteByTtl: r.cache_write_by_ttl }),
241
255
  });
242
256
  /**
243
257
  * 会话:只有所有者可见;每次访问都实时复核 agent 对所有者仍可用(spec 3.6 R5),
@@ -656,6 +670,7 @@ let ConversationsService = class ConversationsService {
656
670
  orgId,
657
671
  rootConversationId: conversationId,
658
672
  });
673
+ await revokeSiteGrantsOfConversation(this.db.db, { orgId, rootConversationId: conversationId });
659
674
  }
660
675
  /** 读会话:非所有者、或 agent 已对所有者不可用 → `conversation.not_found`。 */
661
676
  async get(orgId, conversationId, viewerAccountId) {
@@ -926,6 +941,7 @@ let ConversationsService = class ConversationsService {
926
941
  WHERE e.conversation_id = c.id AND e.run_id = r.id AND e.type = 'tool_result'
927
942
  ) AS tool_calls,
928
943
  u.input_tokens, u.output_tokens, u.cache_read_tokens, u.cache_write_tokens,
944
+ u.cache_write_by_ttl,
929
945
  ARRAY(SELECT a.id FROM capybara.approvals a
930
946
  WHERE a.conversation_id = c.id AND a.status = 'pending' AND a.expires_at > now()
931
947
  ORDER BY a.created_at, a.id) AS approval_ids,
@@ -367,6 +367,7 @@ export declare const ReviewRecordSchema: z.ZodObject<{
367
367
  "loopback-port": "loopback-port";
368
368
  "outside-sandbox": "outside-sandbox";
369
369
  sensitive: "sensitive";
370
+ "site-access": "site-access";
370
371
  }>>;
371
372
  }, z.core.$strict>;
372
373
  /** The display-only `approval_requested.command` facts of a `command` ask (auto mode spec §5.4). */
@@ -475,6 +476,7 @@ export declare const ContentBlockSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
475
476
  }, z.core.$strip>, unknown>;
476
477
  name: z.ZodOptional<z.ZodString>;
477
478
  size: z.ZodOptional<z.ZodNumber>;
479
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
478
480
  }, z.core.$strip>, z.ZodObject<{
479
481
  type: z.ZodLiteral<"file">;
480
482
  mediaType: z.ZodString;
@@ -484,6 +486,7 @@ export declare const ContentBlockSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
484
486
  }, z.core.$strip>, unknown>;
485
487
  name: z.ZodOptional<z.ZodString>;
486
488
  size: z.ZodOptional<z.ZodNumber>;
489
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
487
490
  }, z.core.$strip>], "type">;
488
491
  type MediaBlock = Extract<ContentBlock, {
489
492
  type: "image" | "document" | "file";
@@ -496,7 +499,9 @@ export type LogContentBlock = Exclude<ContentBlock, MediaBlock> | (MediaBlock ex
496
499
  source: Extract<MediaSource, {
497
500
  kind: "ref";
498
501
  }>;
499
- } : never : never);
502
+ } & (B["type"] extends "image" ? unknown : {
503
+ readByFileId?: true;
504
+ }) : never : never);
500
505
  /** The longest handoff card title (`ToolViewSchema` kind `handoff`), per language. */
501
506
  export declare const HANDOFF_TITLE_MAX_CHARS = 200;
502
507
  /** The longest secure input target name (`approval_requested.secureInput.target`), per language. */
@@ -843,6 +848,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
843
848
  "directories-and-hosts": "directories-and-hosts";
844
849
  "loopback-port": "loopback-port";
845
850
  "sandbox-escalation": "sandbox-escalation";
851
+ "site-access": "site-access";
846
852
  }>;
847
853
  escalation: z.ZodOptional<z.ZodObject<{
848
854
  justification: z.ZodString;
@@ -866,8 +872,21 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
866
872
  host: "host";
867
873
  "loopback-port": "loopback-port";
868
874
  "outside-sandbox": "outside-sandbox";
875
+ "site-access": "site-access";
869
876
  }>>;
870
877
  sensitive: z.ZodOptional<z.ZodArray<z.ZodString>>;
878
+ site: z.ZodOptional<z.ZodObject<{
879
+ service: z.ZodString;
880
+ action: z.ZodEnum<{
881
+ evaluate: "evaluate";
882
+ "permission-grant": "permission-grant";
883
+ "storage-clear": "storage-clear";
884
+ "storage-read": "storage-read";
885
+ }>;
886
+ origin: z.ZodString;
887
+ detailSha256: z.ZodString;
888
+ attempt: z.ZodNumber;
889
+ }, z.core.$strip>>;
871
890
  loopback: z.ZodOptional<z.ZodObject<{
872
891
  service: z.ZodString;
873
892
  port: z.ZodNumber;
@@ -958,6 +977,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
958
977
  }, z.core.$strip>, unknown>;
959
978
  name: z.ZodOptional<z.ZodString>;
960
979
  size: z.ZodOptional<z.ZodNumber>;
980
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
961
981
  }, z.core.$strip>, z.ZodObject<{
962
982
  type: z.ZodLiteral<"file">;
963
983
  mediaType: z.ZodString;
@@ -967,6 +987,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
967
987
  }, z.core.$strip>, unknown>;
968
988
  name: z.ZodOptional<z.ZodString>;
969
989
  size: z.ZodOptional<z.ZodNumber>;
990
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
970
991
  }, z.core.$strip>], "type">>;
971
992
  attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
972
993
  appId: z.ZodString;
@@ -1286,6 +1307,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1286
1307
  }, z.core.$strip>, unknown>;
1287
1308
  name: z.ZodOptional<z.ZodString>;
1288
1309
  size: z.ZodOptional<z.ZodNumber>;
1310
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
1289
1311
  }, z.core.$strip>, z.ZodObject<{
1290
1312
  type: z.ZodLiteral<"file">;
1291
1313
  mediaType: z.ZodString;
@@ -1295,6 +1317,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1295
1317
  }, z.core.$strip>, unknown>;
1296
1318
  name: z.ZodOptional<z.ZodString>;
1297
1319
  size: z.ZodOptional<z.ZodNumber>;
1320
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
1298
1321
  }, z.core.$strip>], "type">>;
1299
1322
  stopReason: z.ZodEnum<{
1300
1323
  aborted: "aborted";
@@ -1519,6 +1542,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1519
1542
  "loopback-port": "loopback-port";
1520
1543
  "outside-sandbox": "outside-sandbox";
1521
1544
  sensitive: "sensitive";
1545
+ "site-access": "site-access";
1522
1546
  }>>;
1523
1547
  }, z.core.$strict>>;
1524
1548
  loadedTools: z.ZodOptional<z.ZodArray<z.ZodString>>;
@@ -1688,6 +1712,16 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1688
1712
  sandbox: "sandbox";
1689
1713
  }>;
1690
1714
  }, z.core.$strict>>;
1715
+ site: z.ZodOptional<z.ZodObject<{
1716
+ service: z.ZodString;
1717
+ action: z.ZodEnum<{
1718
+ evaluate: "evaluate";
1719
+ "permission-grant": "permission-grant";
1720
+ "storage-clear": "storage-clear";
1721
+ "storage-read": "storage-read";
1722
+ }>;
1723
+ origin: z.ZodString;
1724
+ }, z.core.$strip>>;
1691
1725
  loopback: z.ZodOptional<z.ZodObject<{
1692
1726
  service: z.ZodString;
1693
1727
  port: z.ZodNumber;
@@ -1,5 +1,5 @@
1
1
  import { posix } from "node:path";
2
- import { CARD_BADGE_MAX, CARD_TEXT_MAX, CONTEXT_LIMITS, DOCUMENT_MEDIA_TYPES, hasControlChars, IMAGE_MEDIA_TYPES, isAttachmentId, isFileId, isSkillName, MEDIA_NAME_MAX_CHARS, validateAllowHost, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
2
+ import { CARD_BADGE_MAX, CARD_TEXT_MAX, CONTEXT_LIMITS, DOCUMENT_MEDIA_TYPES, hasControlChars, IMAGE_MEDIA_TYPES, isAttachmentId, isFileId, isSkillName, MEDIA_NAME_MAX_CHARS, SITE_ACCESS_ACTIONS, validateAllowHost, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
3
3
  import { z } from "zod";
4
4
  import { AgentDefinitionSchema, DisabledSkillRef, DisabledToolRef, ModelRef, } from "../agents/definition.js";
5
5
  import { ORG_ROLES } from "../orgs/roles.js";
@@ -456,7 +456,7 @@ export const ReviewRecordSchema = z
456
456
  * Not model-visible, so it needs no DriftReason.
457
457
  */
458
458
  crossing: z
459
- .enum(["directory", "host", "outside-sandbox", "sensitive", "loopback-port"])
459
+ .enum(["directory", "host", "outside-sandbox", "sensitive", "loopback-port", "site-access"])
460
460
  .optional(),
461
461
  })
462
462
  .strict();
@@ -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"];
@@ -850,7 +852,12 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
850
852
  binding: PermissionCallBindingSchema,
851
853
  permissionScope: PermissionExpansionSchema,
852
854
  targetPath: z.string().max(4096).optional(),
853
- scopeKind: z.enum(["directories-and-hosts", "sandbox-escalation", "loopback-port"]),
855
+ scopeKind: z.enum([
856
+ "directories-and-hosts",
857
+ "sandbox-escalation",
858
+ "loopback-port",
859
+ "site-access",
860
+ ]),
854
861
  /** A per-call sandbox escalation: the model's justification (its scope is empty). */
855
862
  escalation: PermissionEscalationSchema.optional(),
856
863
  candidateHash: z.string(),
@@ -862,13 +869,24 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
862
869
  */
863
870
  decisionSource: z.enum(["review-model", "rule", "full-access"]),
864
871
  /** The crossing reviewed (approval-only profiles design); not model-visible. */
865
- crossing: z.enum(["directory", "host", "outside-sandbox", "loopback-port"]).optional(),
872
+ crossing: z
873
+ .enum(["directory", "host", "outside-sandbox", "loopback-port", "site-access"])
874
+ .optional(),
866
875
  /** The sensitive-command consents (rule ids) a Full access auto-grant skipped; not model-visible. */
867
876
  sensitive: z.array(z.string()).optional(),
868
877
  /**
869
878
  * A loopback port grant's review (`scopeKind: "loopback-port"`): the device service and the
870
879
  * port it asked to reach on the person's own device. Not model-visible.
871
880
  */
881
+ site: z
882
+ .object({
883
+ service: z.string(),
884
+ action: z.enum(SITE_ACCESS_ACTIONS),
885
+ origin: z.string().max(300),
886
+ detailSha256: z.string().regex(/^[a-f0-9]{64}$/),
887
+ attempt: z.number().int().positive(),
888
+ })
889
+ .optional(),
872
890
  loopback: z
873
891
  .object({
874
892
  service: z.string(),
@@ -1544,6 +1562,13 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1544
1562
  * to reach on the person's own device and whether it is a well-known database port. Display
1545
1563
  * only, never model-visible, as `network`.
1546
1564
  */
1565
+ site: z
1566
+ .object({
1567
+ service: z.string(),
1568
+ action: z.enum(SITE_ACCESS_ACTIONS),
1569
+ origin: z.string().max(300),
1570
+ })
1571
+ .optional(),
1547
1572
  loopback: z
1548
1573
  .object({
1549
1574
  service: z.string(),
@@ -103,7 +103,7 @@ export interface KernelDeps {
103
103
  };
104
104
  }
105
105
  /** What `ctx.deviceAccess` calls through (`DeviceAccessService`). */
106
- export type DeviceAccessBackend = Pick<DeviceAccessService, "ensureService" | "request" | "reportBlockedHosts" | "streamTicket" | "addNetworkHosts" | "answerHandoff" | "grantLoopbackPort" | "revokeLoopbackPort" | "loopbackPorts">;
106
+ export type DeviceAccessBackend = Pick<DeviceAccessService, "ensureService" | "request" | "reportBlockedHosts" | "requestSiteAccess" | "siteGrants" | "revokeSiteGrant" | "streamTicket" | "addNetworkHosts" | "answerHandoff" | "grantLoopbackPort" | "revokeLoopbackPort" | "loopbackPorts">;
107
107
  /** What `ctx.triggers` calls through (`TriggerEventsService`). */
108
108
  export type TriggersBackend = Pick<TriggerEventsService, "emit" | "causeOf">;
109
109
  /** What `ctx.inbox` calls through (`InboxItemsService`). */
@@ -420,6 +420,7 @@ identity = { sha256: null }) {
420
420
  superseded: () => disposing || lifecycle.signal.aborted,
421
421
  // read from the approved manifest: an upgrade adding it waits for approval again
422
422
  loopbackPorts: perms.deviceAccess?.loopbackPorts === true,
423
+ siteAccess: perms.deviceAccess?.siteAccess === true,
423
424
  };
424
425
  const backend = () => {
425
426
  const b = deps.deviceAccess?.();
@@ -437,6 +438,9 @@ identity = { sha256: null }) {
437
438
  grantLoopbackPort: async (scope) => backend().grantLoopbackPort(caller, scope),
438
439
  revokeLoopbackPort: async (scope) => backend().revokeLoopbackPort(caller, scope),
439
440
  loopbackPorts: async (scope) => backend().loopbackPorts(caller, scope),
441
+ requestSiteAccess: (call, ask) => backend().requestSiteAccess(caller, call, ask),
442
+ siteGrants: async (scope) => backend().siteGrants(caller, scope),
443
+ revokeSiteGrant: async (scope) => backend().revokeSiteGrant(caller, scope),
440
444
  };
441
445
  })()
442
446
  : undefined;