@capybara-hq/kernel 0.1.0-rc.116 → 0.1.0-rc.118

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) 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/catalog-content.d.ts +11 -0
  4. package/dist/catalog/catalog-content.js +1 -0
  5. package/dist/catalog/component-scope.service.js +2 -1
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/org-catalog.service.d.ts +1 -0
  8. package/dist/catalog/org-catalog.service.js +44 -2
  9. package/dist/catalog/plugin-install.d.ts +1 -0
  10. package/dist/catalog/plugin-install.js +11 -1
  11. package/dist/catalog/schema-path.d.ts +4 -6
  12. package/dist/catalog/schema-path.js +48 -21
  13. package/dist/channels/outbound.d.ts +5 -0
  14. package/dist/channels/outbound.js +6 -1
  15. package/dist/channels/supervisor.js +3 -0
  16. package/dist/conversations/conversations.controller.d.ts +1 -1
  17. package/dist/conversations/conversations.controller.js +1 -1
  18. package/dist/conversations/conversations.service.d.ts +4 -2
  19. package/dist/conversations/conversations.service.js +17 -3
  20. package/dist/conversations/events.d.ts +10 -1
  21. package/dist/conversations/events.js +8 -1
  22. package/dist/db/kernel-schema.d.ts +15 -1
  23. package/dist/devices/devices.controller.d.ts +5 -0
  24. package/dist/devices/devices.controller.js +20 -2
  25. package/dist/devices/devices.service.d.ts +11 -1
  26. package/dist/devices/devices.service.js +20 -0
  27. package/dist/evals/plan.d.ts +3 -1
  28. package/dist/evals/plan.js +25 -5
  29. package/dist/evals/runs.service.js +3 -2
  30. package/dist/evals/trajectory.js +1 -0
  31. package/dist/files/blob-references.d.ts +8 -0
  32. package/dist/files/blob-references.js +19 -0
  33. package/dist/files/blob-sweep.job.js +5 -23
  34. package/dist/files/library-files.service.js +8 -4
  35. package/dist/models/cache-write-usage.d.ts +3 -0
  36. package/dist/models/cache-write-usage.js +26 -0
  37. package/dist/models/images.js +5 -1
  38. package/dist/models/prices.d.ts +8 -6
  39. package/dist/models/prices.js +28 -3
  40. package/dist/orgs/settings.controller.d.ts +4 -17
  41. package/dist/orgs/settings.controller.js +5 -9
  42. package/dist/orgs/settings.service.d.ts +12 -0
  43. package/dist/orgs/settings.service.js +24 -0
  44. package/dist/platform/exclusions.js +11 -0
  45. package/dist/platform/ops/admin.ops.js +2 -2
  46. package/dist/platform/ops/conversations.ops.js +1 -1
  47. package/dist/platform/ops/devices.ops.js +21 -0
  48. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  49. package/dist/platform/ops/org-settings.ops.js +10 -10
  50. package/dist/runtime/context/build.d.ts +2 -0
  51. package/dist/runtime/context/build.js +9 -1
  52. package/dist/runtime/usage-report.js +3 -0
  53. package/dist/sandbox/legacy-retirement.d.ts +15 -0
  54. package/dist/sandbox/legacy-retirement.js +243 -3
  55. package/dist/sandbox/permission-instance-writes.d.ts +4 -1
  56. package/dist/sandbox/permission-instance-writes.js +55 -1
  57. package/dist/sandbox/providers.d.ts +6 -1
  58. package/dist/sandbox/providers.js +15 -1
  59. package/dist/sandbox/sandbox.service.d.ts +19 -3
  60. package/dist/sandbox/sandbox.service.js +167 -9
  61. package/dist/tools/builtins/sandbox/common.d.ts +2 -7
  62. package/dist/tools/builtins/sandbox/common.js +14 -8
  63. package/dist/tools/connector-tools-jobs.d.ts +3 -2
  64. package/dist/tools/connectors.service.d.ts +3 -1
  65. package/dist/tools/connectors.service.js +64 -12
  66. package/dist/tools/drift.d.ts +1 -1
  67. package/dist/tools/drift.js +13 -13
  68. package/dist/tools/pipeline.d.ts +4 -0
  69. package/dist/tools/pipeline.js +55 -16
  70. package/dist/ui/admin-ui.controller.d.ts +5 -2
  71. package/dist/ui/admin-ui.controller.js +14 -1
  72. package/dist/ui/ui.schemas.d.ts +9 -0
  73. package/dist/ui/ui.schemas.js +2 -0
  74. package/dist/ui/views.d.ts +1 -1
  75. package/dist/ui/views.js +4 -5
  76. package/package.json +3 -3
  77. package/src/migrations/0202_connector_endpoint_changed_at.sql +1 -0
  78. package/src/migrations/0203_model_cache_write_pricing.sql +5 -0
  79. 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;
@@ -73,6 +73,7 @@ export interface OrgCatalogTemplate {
73
73
  connector: string;
74
74
  endpoint: Record<string, unknown>;
75
75
  editableEndpoint: string[];
76
+ editableEndpointTitles?: Record<string, string>;
76
77
  auth: Record<string, unknown>;
77
78
  ownership: "org" | "personal" | null;
78
79
  /**
@@ -106,6 +107,13 @@ export interface OrgCatalogTemplate {
106
107
  */
107
108
  icon: string | null;
108
109
  }
110
+ /** A connector reference or described need for the org's plugin review. */
111
+ export type OrgCatalogAgentConnectorNeed = {
112
+ template: string;
113
+ } | {
114
+ label: string;
115
+ host?: string;
116
+ };
109
117
  /** `GET /orgs/:orgId/catalog/:itemId`: the item and what the install wizard needs (latest version). */
110
118
  export interface OrgCatalogDetail {
111
119
  item: OrgCatalogItem;
@@ -127,6 +135,8 @@ export interface OrgCatalogDetail {
127
135
  skills: string[];
128
136
  /** The agent template files (`agents/<name>.md`, sub-agents spec §16). */
129
137
  agents: string[];
138
+ /** Display details for agent templates with connector references, keyed by their paths in `agents`. */
139
+ agentConnectorNeeds?: Record<string, OrgCatalogAgentConnectorNeed[]>;
130
140
  }
131
141
  /**
132
142
  * A connector template as an org sees it (the install wizard and the upgrade preview's inputs):
@@ -137,6 +147,7 @@ export declare function orgTemplateView(id: string, file: ConnectorTemplateFile,
137
147
  on?: boolean;
138
148
  connected?: boolean;
139
149
  icon?: string | null;
150
+ editableEndpointTitles?: Record<string, string> | undefined;
140
151
  }): OrgCatalogTemplate;
141
152
  /** An item's icon (the latest version's plugin icon). */
142
153
  export interface CatalogIcon {
@@ -27,6 +27,7 @@ export function orgTemplateView(id, file, o = {}) {
27
27
  connector: t.connector,
28
28
  endpoint: t.endpoint,
29
29
  editableEndpoint: t.editableEndpoint ?? [],
30
+ ...(o.editableEndpointTitles && { editableEndpointTitles: o.editableEndpointTitles }),
30
31
  auth: t.auth,
31
32
  ownership: t.ownership ??
32
33
  (typeof t.auth.ownership === "string" ? t.auth.ownership : null),
@@ -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.91";
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;
@@ -66,6 +66,7 @@ export declare class OrgCatalogService {
66
66
  */
67
67
  /** The account is an admin (or owner) of the org. */
68
68
  private isOrgAdmin;
69
+ private endpointTitles;
69
70
  detail(orgId: string, accountId: string, itemId: string): Promise<OrgCatalogDetail>;
70
71
  /**
71
72
  * The item's icon; members don't see disabled items, nobody outside its list sees a hidden
@@ -22,17 +22,30 @@ import { OrgLock } from "../orgs/org-lock.js";
22
22
  import { can, roleAtLeast } from "../orgs/roles.js";
23
23
  import { packagePath } from "../packages/tgz.js";
24
24
  import { StorageService } from "../storage/storage.service.js";
25
- import { catalogHasIcon, findConnectorIn, orgTemplateView, readCatalogIcon, readCatalogTemplates, templatePluginProblem, } from "./catalog-content.js";
25
+ import { catalogHasIcon, findConnectorIn, orgTemplateView, readCatalogAgentTemplates, readCatalogIcon, readCatalogTemplates, templatePluginProblem, } from "./catalog-content.js";
26
26
  import { itemView, ownerOnlyFacts, versionUsable } from "./catalog-items.js";
27
27
  import { connectorTemplatesOn } from "./component-state.js";
28
28
  import { LIVE_INSTALL_STATUSES } from "./install-status.js";
29
29
  import { itemPendingError, ownerOf, ownersOf } from "./ownership.js";
30
30
  import { PluginInstaller, uninstallPreviewHash, upsertOrgSwitch, } from "./plugin-install.js";
31
+ import { schemaPathTitle } from "./schema-path.js";
31
32
  import { requestable, switchable, visibleTo, wantedOn } from "./scope.js";
32
33
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
33
34
  const itemNotFound = () => new ApiError("catalog.item_not_found", "Catalog item not found");
34
35
  const notOffered = () => new ApiError("catalog.approval_required", "This plugin is not offered to this organization; an org admin can request access");
35
36
  const pluginDisabled = () => new ApiError("plugin.disabled", "This plugin is disabled by the super admin and cannot be switched on");
37
+ function connectorNeedHost(endpoint) {
38
+ const url = URL.parse(endpoint);
39
+ if (!url?.hostname)
40
+ return undefined;
41
+ if (url.port)
42
+ return url.host;
43
+ // Parse the same authority with a different default port so an explicit default stays visible.
44
+ const scheme = url.protocol === "http:" || url.protocol === "ws:" ? "https" : "http";
45
+ const alternate = URL.parse(scheme + endpoint.slice(endpoint.indexOf(":")));
46
+ const port = alternate?.hostname === url.hostname ? alternate.port : undefined;
47
+ return port ? `${url.hostname}:${port}` : url.host;
48
+ }
36
49
  /**
37
50
  * Organizations see the platform catalog with the plugin scope rules applied (plugin and component
38
51
  * management spec §5): a plugin is `all` (on in every org unless an org admin switched it off,
@@ -258,6 +271,19 @@ let OrgCatalogService = class OrgCatalogService {
258
271
  .executeTakeFirst();
259
272
  return m !== undefined && roleAtLeast(m.role, "admin");
260
273
  }
274
+ endpointTitles(template) {
275
+ const paths = template.editableEndpoint;
276
+ if (!paths?.length)
277
+ return undefined;
278
+ const schema = findConnectorIn(this.registry, template.plugin, template.connector)?.endpointSchema;
279
+ if (!schema)
280
+ return undefined;
281
+ const entries = paths.flatMap((path) => {
282
+ const title = schemaPathTitle(schema, path.split("."));
283
+ return title ? [[path, title]] : [];
284
+ });
285
+ return entries.length ? Object.fromEntries(entries) : undefined;
286
+ }
261
287
  async detail(orgId, accountId, itemId) {
262
288
  if (!UUID_RE.test(itemId))
263
289
  throw itemNotFound();
@@ -273,7 +299,21 @@ let OrgCatalogService = class OrgCatalogService {
273
299
  if (!v)
274
300
  throw itemNotFound();
275
301
  const m = v.manifest;
276
- const templates = await readCatalogTemplates(this.storage, v);
302
+ const [templates, agentTemplates] = await Promise.all([
303
+ readCatalogTemplates(this.storage, v),
304
+ readCatalogAgentTemplates(this.storage, v),
305
+ ]);
306
+ const agentConnectorNeeds = {};
307
+ for (const { path, template } of agentTemplates) {
308
+ if (!template.connectors?.length)
309
+ continue;
310
+ agentConnectorNeeds[path] = template.connectors.map((connector) => {
311
+ if ("template" in connector)
312
+ return { template: connector.template };
313
+ const host = connectorNeedHost(connector.needs.endpoint);
314
+ return { label: connector.needs.label, ...(host && { host }) };
315
+ });
316
+ }
277
317
  // Which templates are on in this org now: the install makes connectors of those, a
278
318
  // default-off one an admin switched on included
279
319
  const on = await connectorTemplatesOn(this.db, orgId, itemId, templates.map((t) => t.id));
@@ -304,6 +344,7 @@ let OrgCatalogService = class OrgCatalogService {
304
344
  on: on.has(t.id),
305
345
  connected: connected.has(t.id),
306
346
  icon: iconOf(t.id),
347
+ editableEndpointTitles: this.endpointTitles(t.file.template),
307
348
  })),
308
349
  dependencies: [
309
350
  ...(m.dependencies ?? []).map((d) => ({ name: d.name, range: d.version })),
@@ -311,6 +352,7 @@ let OrgCatalogService = class OrgCatalogService {
311
352
  ],
312
353
  skills: (m.skills ?? []).map((s) => packagePath(s.path)),
313
354
  agents: (m.agents ?? []).map((a) => packagePath(a.path)),
355
+ ...(Object.keys(agentConnectorNeeds).length > 0 && { agentConnectorNeeds }),
314
356
  };
315
357
  }
316
358
  /**
@@ -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;
@@ -1,7 +1,5 @@
1
1
  import type { ZodTypeAny } from "zod";
2
- /**
3
- * zod schema(v4)里是否有点路径 `segs` 指向的字段(连接器模板的 `editableEndpoint` 用):对象按 shape(或非 never 的
4
- * catchall)、记录类型的任意键、union / 交叉的任一分支;包装(optional、default、pipe 的输入端等)剥掉再看。
5
- * 空路径即 schema 本身,恒为 true。叶子之下还有路径 → false。
6
- */
7
- export declare function schemaHasPath(schema: ZodTypeAny, segs: string[], depth?: number): boolean;
2
+ /** Whether the Zod schema admits the template's editable path. */
3
+ export declare function schemaHasPath(schema: ZodTypeAny, segs: string[]): boolean;
4
+ /** The title shared by the endpoint field's titled alternatives, when available. */
5
+ export declare function schemaPathTitle(schema: ZodTypeAny, segs: string[]): string | undefined;
@@ -10,9 +10,10 @@ const WRAPPERS = new Set([
10
10
  "success",
11
11
  ]);
12
12
  const defOf = (s) => s._zod.def;
13
- function unwrap(s, depth) {
13
+ function unwrap(s, depth, visit) {
14
14
  let node = s;
15
15
  for (let i = 0; i < 50; i++) {
16
+ visit?.(node);
16
17
  const d = defOf(node);
17
18
  if (WRAPPERS.has(d.type) && d.innerType)
18
19
  node = d.innerType;
@@ -25,39 +26,65 @@ function unwrap(s, depth) {
25
26
  }
26
27
  return undefined;
27
28
  }
28
- /**
29
- * zod schema(v4)里是否有点路径 `segs` 指向的字段(连接器模板的 `editableEndpoint` 用):对象按 shape(或非 never 的
30
- * catchall)、记录类型的任意键、union / 交叉的任一分支;包装(optional、default、pipe 的输入端等)剥掉再看。
31
- * 空路径即 schema 本身,恒为 true。叶子之下还有路径 → false。
32
- */
33
- export function schemaHasPath(schema, segs, depth = 0) {
29
+ /** Whether the Zod schema admits the template's editable path. */
30
+ export function schemaHasPath(schema, segs) {
31
+ return schemaFields(schema, segs, 0).next().done === false;
32
+ }
33
+ /** The title shared by the endpoint field's titled alternatives, when available. */
34
+ export function schemaPathTitle(schema, segs) {
35
+ let title;
36
+ for (const field of schemaFields(schema, segs, 0)) {
37
+ let name;
38
+ unwrap(field, 0, (node) => {
39
+ if (name)
40
+ return;
41
+ const metadata = node.meta()?.title;
42
+ if (typeof metadata === "string")
43
+ name = metadata.trim();
44
+ });
45
+ if (!name)
46
+ continue;
47
+ if (title !== undefined && title !== name)
48
+ return undefined;
49
+ title = name;
50
+ }
51
+ return title;
52
+ }
53
+ function* schemaFields(schema, segs, depth) {
34
54
  if (depth > 40)
35
- return false;
55
+ return;
36
56
  const node = unwrap(schema, depth);
37
57
  if (!node)
38
- return false;
39
- if (segs.length === 0)
40
- return true;
58
+ return;
59
+ if (segs.length === 0) {
60
+ yield schema;
61
+ return;
62
+ }
41
63
  const [head, ...rest] = segs;
42
64
  const d = defOf(node);
43
65
  switch (d.type) {
44
66
  case "object": {
45
67
  const child = d.shape && Object.hasOwn(d.shape, head) ? d.shape[head] : undefined;
46
68
  if (child)
47
- return schemaHasPath(child, rest, depth + 1);
48
- if (d.catchall && defOf(d.catchall).type !== "never") {
49
- return schemaHasPath(d.catchall, rest, depth + 1);
69
+ yield* schemaFields(child, rest, depth + 1);
70
+ else if (d.catchall && defOf(d.catchall).type !== "never") {
71
+ yield* schemaFields(d.catchall, rest, depth + 1);
50
72
  }
51
- return false;
73
+ break;
52
74
  }
53
75
  case "record":
54
- return d.valueType ? schemaHasPath(d.valueType, rest, depth + 1) : false;
76
+ if (d.valueType)
77
+ yield* schemaFields(d.valueType, rest, depth + 1);
78
+ break;
55
79
  case "union":
56
- return (d.options ?? []).some((o) => schemaHasPath(o, segs, depth + 1));
80
+ for (const option of d.options ?? [])
81
+ yield* schemaFields(option, segs, depth + 1);
82
+ break;
57
83
  case "intersection":
58
- return ((d.left !== undefined && schemaHasPath(d.left, segs, depth + 1)) ||
59
- (d.right !== undefined && schemaHasPath(d.right, segs, depth + 1)));
60
- default:
61
- return false;
84
+ if (d.left)
85
+ yield* schemaFields(d.left, segs, depth + 1);
86
+ if (d.right)
87
+ yield* schemaFields(d.right, segs, depth + 1);
88
+ break;
62
89
  }
63
90
  }
@@ -41,6 +41,11 @@ export declare const DRAFT_INTERVAL_MS = 1000;
41
41
  export declare const MILESTONE_INTERVAL_MS = 60000;
42
42
  /** 同一事件不可重试地失败这么多次后跳过它(Ruling A14)。 */
43
43
  export declare const POISON_FAILURES = 3;
44
+ /**
45
+ * How a delivery failure starts in a connection's `last_error`: the connection holding again does
46
+ * not clear it (the supervisor clears only the connect failures it recovered from).
47
+ */
48
+ export declare const DELIVERY_ERROR_PREFIX = "delivery failed: ";
44
49
  /**
45
50
  * The language of the kernel text a conversation's IM thread gets (cards, notices; maintainer
46
51
  * decision 2026-11-08: in IM, language is per person). The person who triggered the run speaks:
@@ -83,6 +83,11 @@ const BACKOFF_BASE_MS = 1000;
83
83
  const BACKOFF_MAX_MS = 60_000;
84
84
  /** 补读事件的分页大小。 */
85
85
  const PAGE = 200;
86
+ /**
87
+ * How a delivery failure starts in a connection's `last_error`: the connection holding again does
88
+ * not clear it (the supervisor clears only the connect failures it recovered from).
89
+ */
90
+ export const DELIVERY_ERROR_PREFIX = "delivery failed: ";
86
91
  /** `last_error` 的最大长度(同渠道选主)。 */
87
92
  const MAX_ERROR_CHARS = 1000;
88
93
  /** 可重试的投递失败:带已打码的说明与平台建议的等待时长,供退避策略与最后一次失败时记录。 */
@@ -396,7 +401,7 @@ let ChannelOutbound = class ChannelOutbound {
396
401
  }
397
402
  /** A non-retryable (or finally failed) send: the connection's `last_error` (already redacted). */
398
403
  async recordError(connectionId, message) {
399
- const text = `delivery failed: ${message}`.slice(0, MAX_ERROR_CHARS);
404
+ const text = `${DELIVERY_ERROR_PREFIX}${message}`.slice(0, MAX_ERROR_CHARS);
400
405
  this.log.warn("channel delivery failed", { connectionId, error: text });
401
406
  // org-filter: connectionId is the delivery's own connection (kernel-written job / row)
402
407
  await this.kdb
@@ -23,6 +23,7 @@ import { createRedactor } from "../log.js";
23
23
  import { CHANNEL_CHANGED_TOPIC, ChannelConnections, channelBackoffKey, channelFailsKey, } from "./connections.service.js";
24
24
  import { ChannelInbound } from "./inbound.js";
25
25
  import { GATEWAY_CHECK_JOB } from "./job-ids.js";
26
+ import { DELIVERY_ERROR_PREFIX } from "./outbound.js";
26
27
  /** 长连接租约键(内核锁):值为持有方的随机 token。 */
27
28
  export const channelLeaseKey = (connectionId) => `capk:channel-lease:${connectionId}`;
28
29
  /**
@@ -358,6 +359,8 @@ let ChannelSupervisor = class ChannelSupervisor {
358
359
  .set({ last_error: null })
359
360
  .where("id", "=", id)
360
361
  .where("last_error", "is not", null)
362
+ // a delivery failure is not a connect failure the connection recovered from
363
+ .where("last_error", "not like", `${DELIVERY_ERROR_PREFIX}%`)
361
364
  .execute();
362
365
  }
363
366
  catch (e) {
@@ -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. */
@@ -871,6 +875,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
871
875
  loopback: z.ZodOptional<z.ZodObject<{
872
876
  service: z.ZodString;
873
877
  port: z.ZodNumber;
878
+ readyRerunAttempt: z.ZodOptional<z.ZodNumber>;
874
879
  }, z.core.$strip>>;
875
880
  }, z.core.$strip>;
876
881
  }, z.core.$strip>, z.ZodObject<{
@@ -957,6 +962,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
957
962
  }, z.core.$strip>, unknown>;
958
963
  name: z.ZodOptional<z.ZodString>;
959
964
  size: z.ZodOptional<z.ZodNumber>;
965
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
960
966
  }, z.core.$strip>, z.ZodObject<{
961
967
  type: z.ZodLiteral<"file">;
962
968
  mediaType: z.ZodString;
@@ -966,6 +972,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
966
972
  }, z.core.$strip>, unknown>;
967
973
  name: z.ZodOptional<z.ZodString>;
968
974
  size: z.ZodOptional<z.ZodNumber>;
975
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
969
976
  }, z.core.$strip>], "type">>;
970
977
  attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
971
978
  appId: z.ZodString;
@@ -1285,6 +1292,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1285
1292
  }, z.core.$strip>, unknown>;
1286
1293
  name: z.ZodOptional<z.ZodString>;
1287
1294
  size: z.ZodOptional<z.ZodNumber>;
1295
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
1288
1296
  }, z.core.$strip>, z.ZodObject<{
1289
1297
  type: z.ZodLiteral<"file">;
1290
1298
  mediaType: z.ZodString;
@@ -1294,6 +1302,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1294
1302
  }, z.core.$strip>, unknown>;
1295
1303
  name: z.ZodOptional<z.ZodString>;
1296
1304
  size: z.ZodOptional<z.ZodNumber>;
1305
+ readByFileId: z.ZodOptional<z.ZodLiteral<true>>;
1297
1306
  }, z.core.$strip>], "type">>;
1298
1307
  stopReason: z.ZodEnum<{
1299
1308
  aborted: "aborted";