@capybara-hq/kernel 0.1.0-rc.129 → 0.1.0-rc.130

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 (101) hide show
  1. package/dist/admin/usage.service.d.ts +20 -37
  2. package/dist/admin/usage.service.js +99 -122
  3. package/dist/automations/unattended.js +2 -0
  4. package/dist/background/wake-rules.js +1 -0
  5. package/dist/channels/outbound.js +2 -0
  6. package/dist/config/schema.d.ts +2 -0
  7. package/dist/config/schema.js +17 -1
  8. package/dist/conversations/conversations.service.js +5 -0
  9. package/dist/conversations/event-log.d.ts +6 -2
  10. package/dist/conversations/event-log.js +23 -10
  11. package/dist/conversations/event-org-backfill.d.ts +111 -0
  12. package/dist/conversations/event-org-backfill.js +264 -0
  13. package/dist/conversations/event-org-backfill.module.d.ts +3 -0
  14. package/dist/conversations/event-org-backfill.module.js +18 -0
  15. package/dist/conversations/events.d.ts +14 -0
  16. package/dist/conversations/events.js +2 -0
  17. package/dist/conversations/files.js +1 -0
  18. package/dist/conversations/leak-check.js +1 -0
  19. package/dist/conversations/prompt-suggestion-store.js +1 -0
  20. package/dist/conversations/prompt-suggestions.js +1 -0
  21. package/dist/conversations/queue.js +1 -0
  22. package/dist/conversations/selection.js +1 -0
  23. package/dist/conversations/titles.js +1 -0
  24. package/dist/db/kernel-schema.d.ts +8 -15
  25. package/dist/db/migrator.d.ts +6 -0
  26. package/dist/db/migrator.js +58 -6
  27. package/dist/evals/run-replay.js +4 -2
  28. package/dist/evals/sets.service.d.ts +1 -7
  29. package/dist/evals/sets.service.js +6 -15
  30. package/dist/evals/snapshot.js +2 -0
  31. package/dist/evals/trajectory.d.ts +7 -10
  32. package/dist/evals/trajectory.js +31 -23
  33. package/dist/evals/trajectory.service.d.ts +1 -7
  34. package/dist/evals/trajectory.service.js +10 -19
  35. package/dist/evals/worker.d.ts +2 -0
  36. package/dist/evals/worker.js +15 -2
  37. package/dist/identity/settings.d.ts +1 -0
  38. package/dist/identity/settings.js +3 -3
  39. package/dist/index.d.ts +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/infra/outbox/registry.d.ts +14 -0
  42. package/dist/infra/outbox/registry.js +15 -0
  43. package/dist/kernel.d.ts +6 -0
  44. package/dist/kernel.js +31 -2
  45. package/dist/lifecycle/kernel-lifecycle.js +2 -3
  46. package/dist/models/embeddings.d.ts +1 -0
  47. package/dist/models/embeddings.js +8 -0
  48. package/dist/models/images.d.ts +1 -0
  49. package/dist/models/images.js +7 -0
  50. package/dist/models/price-snapshot.d.ts +43 -0
  51. package/dist/models/price-snapshot.js +145 -0
  52. package/dist/platform/ops/admin.ops.js +1 -1
  53. package/dist/push/recipients.js +9 -8
  54. package/dist/roles/worker.module.js +6 -0
  55. package/dist/runtime/idle-arm.js +3 -0
  56. package/dist/runtime/idle-compaction.d.ts +1 -1
  57. package/dist/runtime/idle-compaction.js +6 -2
  58. package/dist/runtime/idle-return.js +3 -0
  59. package/dist/runtime/maintenance.d.ts +3 -1
  60. package/dist/runtime/maintenance.js +18 -5
  61. package/dist/runtime/permission-context.service.js +1 -0
  62. package/dist/runtime/plugin-context.service.js +1 -0
  63. package/dist/runtime/project/knowledge.service.js +2 -0
  64. package/dist/runtime/run-context.service.js +4 -0
  65. package/dist/runtime/run-deletion.d.ts +1 -0
  66. package/dist/runtime/run-deletion.js +7 -3
  67. package/dist/runtime/run-queue.js +3 -0
  68. package/dist/runtime/run-worker.js +1 -0
  69. package/dist/runtime/stream.js +4 -3
  70. package/dist/runtime/subagents/deliveries.js +1 -0
  71. package/dist/runtime/subagents/dispatch.js +1 -0
  72. package/dist/runtime/subagents/progress.js +1 -0
  73. package/dist/runtime/subagents/skill-fork.js +2 -0
  74. package/dist/runtime/usage-report.js +1 -0
  75. package/dist/runtime/waits.d.ts +1 -1
  76. package/dist/runtime/waits.js +3 -1
  77. package/dist/sandbox/managed-device-context.js +1 -0
  78. package/dist/sandbox/operation-authority.js +2 -0
  79. package/dist/sandbox/operation-intents.js +1 -0
  80. package/dist/sandbox/permission-call-grants.js +2 -0
  81. package/dist/sandbox/permission-facts.js +2 -0
  82. package/dist/sandbox/review/classifier.js +1 -0
  83. package/dist/sandbox/review/review.service.js +1 -0
  84. package/dist/skills/catalog.js +1 -0
  85. package/dist/skills/invoke.js +2 -0
  86. package/dist/tools/admin-connectors.js +2 -2
  87. package/dist/tools/builtins/builtin-tools.js +1 -0
  88. package/dist/tools/builtins/skill-load.js +2 -0
  89. package/dist/tools/connector-account-policies.js +3 -3
  90. package/dist/tools/connectors.service.js +13 -25
  91. package/dist/tools/drift.js +8 -14
  92. package/dist/tools/policy.js +2 -2
  93. package/dist/tools/registry.js +1 -2
  94. package/dist/tools/tool-watch.processor.d.ts +1 -1
  95. package/dist/tools/tool-watch.processor.js +1 -1
  96. package/dist/tools/tool-watch.service.js +22 -7
  97. package/dist/ui/views.js +1 -0
  98. package/package.json +1 -1
  99. package/src/migrations/0213_contract_org_security_policy.sql +43 -0
  100. package/src/migrations/0214_model_usage_price_snapshot.sql +2 -0
  101. package/src/migrations/0215_conversation_events_org_id.sql +48 -0
@@ -1,9 +1,7 @@
1
- import type { CacheWriteByTtl } from "@capybara-hq/plugin-sdk";
2
- import { SettingsService } from "../identity/settings.js";
3
1
  import { CacheService } from "../infra/cache/cache.service.js";
4
2
  import { KernelDb } from "../infra/database/kernel-db.js";
5
3
  import { TransactionHost } from "../infra/database/transaction-host.js";
6
- import { PricesService } from "../models/prices.js";
4
+ import { type GroupedCacheWrite, type UsageCost } from "../models/price-snapshot.js";
7
5
  /** Seam token of the kernel's own tests: a shorter statement timeout and a fixed clock. */
8
6
  export declare const ADMIN_USAGE_TIMINGS: unique symbol;
9
7
  export interface AdminUsageTimings {
@@ -34,11 +32,9 @@ export interface UsageDay {
34
32
  /** Runs created that day (every run: sub-agent and eval replay runs included, D6). */
35
33
  runs: number;
36
34
  tokens: UsageTokens;
37
- /**
38
- * Estimated cost in `currency` of the priced tokens; null when the day used tokens and none of
39
- * them had a price (0 for a day with no tokens).
40
- */
41
- cost: number | null;
35
+ images: number;
36
+ /** Exact subtotals by recorded currency and token counts for missing prices. */
37
+ cost: UsageCost;
42
38
  }
43
39
  /** One org's week: totals only (never per account, agent or conversation; spec §9). */
44
40
  export interface UsageOrg {
@@ -48,8 +44,8 @@ export interface UsageOrg {
48
44
  runs: number;
49
45
  /** Every token kind summed, embeddings included. */
50
46
  tokens: number;
51
- /** As {@link UsageDay.cost}, over the org's week. */
52
- cost: number | null;
47
+ images: number /** As {@link UsageDay.cost}, over the org's week. */;
48
+ cost: UsageCost;
53
49
  }
54
50
  /**
55
51
  * `AdminUsageService.week(tz)` (admin overview spec §4.3, §5.2): the platform's runs, tokens and
@@ -62,12 +58,10 @@ export interface AdminUsageWeek {
62
58
  /** End of today in `tz`, exclusive (ISO 8601, UTC). */
63
59
  to: string;
64
60
  tz: string;
65
- /** The deployment setting `priceCurrency`. */
66
- currency: string;
67
61
  /** Exactly 7 days, oldest first, today last; days without usage are zeros. */
68
62
  days: UsageDay[];
69
- /** Some tokens of the week had no price: the costs count only the priced ones. */
70
- costPartial: boolean;
63
+ /** Nominal currency subtotals over the whole week. */
64
+ cost: UsageCost;
71
65
  /** At most 10, by total tokens descending (then runs, then id). */
72
66
  orgs: UsageOrg[];
73
67
  /** The orgs with usage outside the top 10, summed; `count` 0 when there are none. */
@@ -75,7 +69,8 @@ export interface AdminUsageWeek {
75
69
  count: number;
76
70
  runs: number;
77
71
  tokens: number;
78
- cost: number | null;
72
+ images: number;
73
+ cost: UsageCost;
79
74
  };
80
75
  }
81
76
  /** `YYYY-MM-DD` of `at` in `tz`. */
@@ -85,43 +80,33 @@ export declare function addDays(date: string, days: number): string;
85
80
  interface TokenRow {
86
81
  day: string;
87
82
  org_id: string;
88
- provider: string;
89
- model: string;
83
+ price_snapshot: unknown;
84
+ kind: "conversation" | "embedding" | "image_generation";
85
+ images: string;
90
86
  input: string;
91
87
  output: string;
92
88
  cache_read: string;
93
89
  cache_write: string;
94
- cache_write_by_ttl: CacheWriteByTtl[] | null;
90
+ cache_write_by_ttl: GroupedCacheWrite[] | null;
95
91
  }
96
92
  interface RunRow {
97
93
  day: string;
98
94
  org_id: string;
99
95
  runs: string;
100
96
  }
101
- interface EmbeddingRow {
102
- day: string;
103
- org_id: string;
104
- provider: string;
105
- model: string;
106
- input: string;
107
- }
108
97
  /**
109
98
  * The admin overview's usage block (spec §4.3, §5.2, §5.4). Three grouped queries over a bounded
110
99
  * window (`conversation_events_usage_idx`, `runs_created_idx`, `model_usage_time_idx`) in one
111
- * read-only transaction with a statement timeout; priced here with the model price table. The
112
- * answer is cached in Redis for 300 s per time zone and first day, so every replica serves the
113
- * same answer and a zone is recomputed at most once per 5 minutes (prices or currency changed in
114
- * between show after the TTL). Aggregates only: no account, agent or conversation, no content.
100
+ * read-only transaction with a statement timeout. Usage is priced from recorded snapshots. The
101
+ * answer is cached in Redis for 300 s per time zone and first day. Only org totals are exposed.
115
102
  */
116
103
  export declare class AdminUsageService {
117
104
  private readonly db;
118
105
  readonly txHost: TransactionHost;
119
106
  readonly cacheService: CacheService;
120
- private readonly prices;
121
- private readonly settings;
122
107
  private readonly statementTimeoutMs;
123
108
  private readonly now;
124
- constructor(db: KernelDb, txHost: TransactionHost, cacheService: CacheService, prices: Pick<PricesService, "table">, settings: Pick<SettingsService, "get">, timings?: Partial<AdminUsageTimings>);
109
+ constructor(db: KernelDb, txHost: TransactionHost, cacheService: CacheService, timings?: Partial<AdminUsageTimings>);
125
110
  /**
126
111
  * The week ending today in `tz` (an IANA zone the caller validated, `IanaTimeZone`; normalized to
127
112
  * its canonical spelling, which the answer echoes and the cache key holds). Throws
@@ -138,14 +123,12 @@ export declare class AdminUsageService {
138
123
  protected aggregate(tz: string, firstDay: string): Promise<AdminUsageWeek>;
139
124
  }
140
125
  /**
141
- * The three grouped queries over `[from, to)` (spec §5.4), each on its time index:
142
- * `conversation_events_usage_idx`, `runs_created_idx`, `model_usage_time_idx`. Rows are bounded by
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).
126
+ * The three queries take bounded time ranges on the usage and run indexes. Grouping by the price
127
+ * snapshot keeps differently priced calls separate until their subtotals have been calculated.
145
128
  */
146
129
  export declare function usageQueries(tz: string, from: Date, to: Date): {
147
130
  tokens: import("kysely").RawBuilder<TokenRow>;
148
131
  runs: import("kysely").RawBuilder<RunRow>;
149
- embeddings: import("kysely").RawBuilder<EmbeddingRow>;
132
+ modelUsage: import("kysely").RawBuilder<TokenRow>;
150
133
  };
151
134
  export {};
@@ -10,14 +10,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable, Optional } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { ApiError } from "../errors.js";
13
- import { SettingsService } from "../identity/settings.js";
14
13
  import { CacheService } from "../infra/cache/cache.service.js";
15
14
  import { Cacheable } from "../infra/cache/cacheable.decorator.js";
16
15
  import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { asPlatform } from "../infra/database/org-scope.js";
17
17
  import { runOutsideTransaction, TransactionHost } from "../infra/database/transaction-host.js";
18
18
  import { Transactional } from "../infra/database/transactional.decorator.js";
19
19
  import { cacheWriteTierRows } from "../models/cache-write-usage.js";
20
- import { costOf, costOfUsageTotals, PricesService, priceKey, } from "../models/prices.js";
20
+ import { addUsageCost, emptyUsageCost, groupedSnapshotCost, } from "../models/price-snapshot.js";
21
21
  /** Seam token of the kernel's own tests: a shorter statement timeout and a fixed clock. */
22
22
  export const ADMIN_USAGE_TIMINGS = Symbol("ADMIN_USAGE_TIMINGS");
23
23
  /** Days in the window: today and the 6 days before. */
@@ -48,40 +48,22 @@ export function addDays(date, days) {
48
48
  const [y, m, d] = date.split("-").map(Number);
49
49
  return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
50
50
  }
51
- const newCost = () => ({ priced: 0, anyPriced: false, unpriced: false });
52
- const addCost = (acc, cost, tokens) => {
53
- if (cost !== null) {
54
- acc.priced += cost;
55
- acc.anyPriced = true;
56
- }
57
- else if (tokens > 0) {
58
- acc.unpriced = true;
59
- }
60
- };
61
- /** Rounded to 1e-6 (float noise); null when tokens were used and none was priced. */
62
- const costValue = (acc) => !acc.anyPriced && acc.unpriced ? null : Math.round(acc.priced * 1e6) / 1e6;
63
51
  /**
64
52
  * The admin overview's usage block (spec §4.3, §5.2, §5.4). Three grouped queries over a bounded
65
53
  * window (`conversation_events_usage_idx`, `runs_created_idx`, `model_usage_time_idx`) in one
66
- * read-only transaction with a statement timeout; priced here with the model price table. The
67
- * answer is cached in Redis for 300 s per time zone and first day, so every replica serves the
68
- * same answer and a zone is recomputed at most once per 5 minutes (prices or currency changed in
69
- * between show after the TTL). Aggregates only: no account, agent or conversation, no content.
54
+ * read-only transaction with a statement timeout. Usage is priced from recorded snapshots. The
55
+ * answer is cached in Redis for 300 s per time zone and first day. Only org totals are exposed.
70
56
  */
71
57
  let AdminUsageService = class AdminUsageService {
72
58
  db;
73
59
  txHost;
74
60
  cacheService;
75
- prices;
76
- settings;
77
61
  statementTimeoutMs;
78
62
  now;
79
- constructor(db, txHost, cacheService, prices, settings, timings = {}) {
63
+ constructor(db, txHost, cacheService, timings = {}) {
80
64
  this.db = db;
81
65
  this.txHost = txHost;
82
66
  this.cacheService = cacheService;
83
- this.prices = prices;
84
- this.settings = settings;
85
67
  this.statementTimeoutMs = timings.statementTimeoutMs ?? DEFAULT_STATEMENT_TIMEOUT_MS;
86
68
  this.now = timings.now ?? Date.now;
87
69
  }
@@ -97,7 +79,8 @@ let AdminUsageService = class AdminUsageService {
97
79
  async week(tz) {
98
80
  const zone = new Intl.DateTimeFormat("en-US", { timeZone: tz }).resolvedOptions().timeZone;
99
81
  const firstDay = addDays(dateIn(zone, this.now()), -(USAGE_WINDOW_DAYS - 1));
100
- return runOutsideTransaction(() => this.cachedWeek(zone, firstDay));
82
+ // org-filter: deployment-wide usage and run totals for the super admin overview
83
+ return runOutsideTransaction(() => asPlatform("admin usage across organizations", () => this.cachedWeek(zone, firstDay)));
101
84
  }
102
85
  /** The cache key holds the zone and the first day: a new day starts a new entry. */
103
86
  async cachedWeek(tz, firstDay) {
@@ -131,14 +114,11 @@ let AdminUsageService = class AdminUsageService {
131
114
  const q = usageQueries(tz, from, to);
132
115
  const tokens = await q.tokens.execute(db);
133
116
  const runs = await q.runs.execute(db);
134
- const embeddings = await q.embeddings.execute(db);
135
- const [prices, settings] = await Promise.all([this.prices.table(), this.settings.get()]);
117
+ const modelUsage = await q.modelUsage.execute(db);
136
118
  const result = summarize({
137
119
  firstDay,
138
- tokens: tokens.rows,
120
+ tokens: [...tokens.rows, ...modelUsage.rows],
139
121
  runs: runs.rows,
140
- embeddings: embeddings.rows,
141
- prices,
142
122
  });
143
123
  const orgIds = result.top.map((o) => o.orgId);
144
124
  const names = orgIds.length === 0
@@ -153,16 +133,15 @@ let AdminUsageService = class AdminUsageService {
153
133
  from: from.toISOString(),
154
134
  to: to.toISOString(),
155
135
  tz,
156
- currency: settings.priceCurrency,
157
136
  days: result.days,
158
- costPartial: result.costPartial,
137
+ cost: result.cost,
159
138
  orgs: result.top.map((o) => ({ ...o, name: nameOf.get(o.orgId) ?? o.orgId })),
160
139
  otherOrgs: result.otherOrgs,
161
140
  };
162
141
  }
163
142
  };
164
143
  __decorate([
165
- Cacheable({ key: "admin-usage:#{0}:#{1}", ttl: USAGE_CACHE_TTL })
144
+ Cacheable({ key: "admin-usage-price-coverage:#{0}:#{1}", ttl: USAGE_CACHE_TTL })
166
145
  ], AdminUsageService.prototype, "cachedWeek", null);
167
146
  __decorate([
168
147
  Transactional({ propagation: "requires_new", accessMode: "read only" })
@@ -172,59 +151,57 @@ AdminUsageService = __decorate([
172
151
  __param(0, Inject(KernelDb)),
173
152
  __param(1, Inject(TransactionHost)),
174
153
  __param(2, Inject(CacheService)),
175
- __param(3, Inject(PricesService)),
176
- __param(4, Inject(SettingsService)),
177
- __param(5, Optional()),
178
- __param(5, Inject(ADMIN_USAGE_TIMINGS))
154
+ __param(3, Optional()),
155
+ __param(3, Inject(ADMIN_USAGE_TIMINGS))
179
156
  ], AdminUsageService);
180
157
  export { AdminUsageService };
181
158
  /**
182
- * The three grouped queries over `[from, to)` (spec §5.4), each on its time index:
183
- * `conversation_events_usage_idx`, `runs_created_idx`, `model_usage_time_idx`. Rows are bounded by
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).
159
+ * The three queries take bounded time ranges on the usage and run indexes. Grouping by the price
160
+ * snapshot keeps differently priced calls separate until their subtotals have been calculated.
186
161
  */
187
162
  export function usageQueries(tz, from, to) {
188
- // a malformed payload value (a string, null) counts 0 and a fraction is rounded, so one bad
189
- // event cannot fail the aggregate for its 7 days
163
+ const day = (col) => sql `to_char((${sql.ref(col)} AT TIME ZONE ${tz})::date, 'YYYY-MM-DD')`;
190
164
  const tokenSum = (field) => sql `coalesce(sum(CASE WHEN jsonb_typeof(e.payload->${sql.lit(field)}) = 'number'
191
165
  THEN round((e.payload->>${sql.lit(field)})::numeric) END), 0)`;
192
- const day = (col) => sql `to_char((${sql.ref(col)} AT TIME ZONE ${tz})::date, 'YYYY-MM-DD')`;
166
+ const group = (source) => sql `
167
+ WITH usage_rows AS NOT MATERIALIZED (${source}), write_tiers AS (
168
+ SELECT e.day, e.org_id, e.kind, e.price_snapshot, t.ttl, sum(t.tokens) AS tokens
169
+ FROM usage_rows e
170
+ CROSS JOIN LATERAL (${cacheWriteTierRows(sql `e.payload`)}) t
171
+ WHERE e.payload ? 'cacheWriteByTtl'
172
+ GROUP BY 1, 2, 3, 4, 5
173
+ ), breakdowns AS (
174
+ SELECT day, org_id, kind, price_snapshot,
175
+ jsonb_agg(jsonb_build_object('ttl', ttl, 'tokens', trunc(tokens)::text) ORDER BY ttl) AS tiers
176
+ FROM write_tiers
177
+ GROUP BY 1, 2, 3, 4
178
+ ), totals AS (
179
+ SELECT e.day, e.org_id, e.kind, e.price_snapshot,
180
+ ${tokenSum("inputTokens")} AS input,
181
+ ${tokenSum("outputTokens")} AS output,
182
+ ${tokenSum("cacheReadTokens")} AS cache_read,
183
+ ${tokenSum("cacheWriteTokens")} AS cache_write,
184
+ ${tokenSum("outputImages")} AS images
185
+ FROM usage_rows e
186
+ GROUP BY 1, 2, 3, 4
187
+ )
188
+ SELECT totals.*, breakdowns.tiers AS cache_write_by_ttl
189
+ FROM totals LEFT JOIN breakdowns USING (day, org_id, kind, price_snapshot)
190
+ `;
191
+ // Usage copied from a source case retains its original run ID. Only usage belonging to the
192
+ // replay conversation's own run reflects a new provider call.
193
193
  return {
194
- // chat tokens: every `usage` event (steps, compaction, titles, web fetch), by day × org × model
195
- tokens: sql `
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)
226
- `,
227
- // runs: every run (sub-agent and eval replay runs included, D6), by day × org
194
+ tokens: group(sql `
195
+ SELECT ${day("e.created_at")} AS day, c.org_id, 'conversation'::text AS kind,
196
+ coalesce(e.payload->'priceSnapshot', 'null'::jsonb) AS price_snapshot, e.payload
197
+ FROM capybara.conversation_events e
198
+ JOIN capybara.conversations c ON c.id = e.conversation_id
199
+ WHERE e.type = 'usage' AND e.created_at >= ${from} AND e.created_at < ${to}
200
+ AND (c.kind <> 'eval' OR EXISTS (
201
+ SELECT 1 FROM capybara.runs replay_run
202
+ WHERE replay_run.id = e.run_id AND replay_run.conversation_id = c.id
203
+ ))
204
+ `),
228
205
  runs: sql `
229
206
  SELECT ${day("r.created_at")} AS day, c.org_id, count(*) AS runs
230
207
  FROM capybara.runs r
@@ -232,17 +209,20 @@ export function usageQueries(tz, from, to) {
232
209
  WHERE r.created_at >= ${from} AND r.created_at < ${to}
233
210
  GROUP BY 1, 2
234
211
  `,
235
- // embeddings (`ctx.models.embed`), by day × org × model
236
- embeddings: sql `
237
- SELECT ${day("u.occurred_at")} AS day, u.org_id, u.provider, u.model,
238
- coalesce(sum(u.input_tokens), 0) AS input
212
+ modelUsage: group(sql `
213
+ SELECT ${day("u.occurred_at")} AS day, u.org_id, u.kind,
214
+ coalesce(u.price_snapshot, 'null'::jsonb) AS price_snapshot,
215
+ jsonb_build_object(
216
+ 'inputTokens', u.input_tokens, 'outputTokens', u.output_tokens,
217
+ 'cacheReadTokens', u.cache_read_tokens, 'cacheWriteTokens', u.cache_write_tokens,
218
+ 'cacheWriteByTtl', u.cache_write_by_ttl, 'outputImages', u.output_images
219
+ ) AS payload
239
220
  FROM capybara.model_usage u
240
221
  WHERE u.occurred_at >= ${from} AND u.occurred_at < ${to}
241
- GROUP BY 1, 2, 3, 4
242
- `,
222
+ `),
243
223
  };
244
224
  }
245
- /** Folds the grouped rows into days and orgs, pricing each (provider, model) group. */
225
+ /** Fold grouped usage into day, week and org totals. */
246
226
  function summarize(input) {
247
227
  const days = new Map();
248
228
  for (let i = 0; i < USAGE_WINDOW_DAYS; i++) {
@@ -251,26 +231,26 @@ function summarize(input) {
251
231
  day: {
252
232
  date,
253
233
  runs: 0,
234
+ images: 0,
254
235
  tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, embedding: 0 },
255
236
  },
256
- cost: newCost(),
237
+ cost: emptyUsageCost(),
257
238
  });
258
239
  }
259
240
  const orgs = new Map();
260
241
  const org = (orgId) => {
261
242
  let o = orgs.get(orgId);
262
243
  if (!o) {
263
- o = { orgId, runs: 0, tokens: 0, cost: newCost() };
244
+ o = { orgId, runs: 0, tokens: 0, images: 0, cost: emptyUsageCost() };
264
245
  orgs.set(orgId, o);
265
246
  }
266
247
  return o;
267
248
  };
268
- let costPartial = false;
269
- const price = (provider, model) => input.prices.get(priceKey(provider, model));
249
+ const weekCost = emptyUsageCost();
270
250
  for (const r of input.tokens) {
271
251
  const d = days.get(r.day);
272
252
  if (!d)
273
- continue; // outside the window (cannot happen: bounded by the same midnights)
253
+ continue;
274
254
  const usage = {
275
255
  inputTokens: Number(r.input),
276
256
  outputTokens: Number(r.output),
@@ -278,31 +258,29 @@ function summarize(input) {
278
258
  cacheWriteTokens: Number(r.cache_write),
279
259
  };
280
260
  const total = usage.inputTokens + usage.outputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
281
- const cost = costOfUsageTotals(usage, price(r.provider, r.model), r.cache_write_by_ttl ?? undefined);
282
- if (cost === null && total > 0)
283
- costPartial = true;
284
- d.day.tokens.input += usage.inputTokens;
285
- d.day.tokens.output += usage.outputTokens;
286
- d.day.tokens.cacheRead += usage.cacheReadTokens;
287
- d.day.tokens.cacheWrite += usage.cacheWriteTokens;
288
- addCost(d.cost, cost, total);
261
+ const cost = groupedSnapshotCost(r.price_snapshot, {
262
+ inputTokens: r.input,
263
+ outputTokens: r.output,
264
+ cacheReadTokens: r.cache_read,
265
+ cacheWriteTokens: r.cache_write,
266
+ }, r.cache_write_by_ttl ?? []);
267
+ if (r.kind === "embedding") {
268
+ d.day.tokens.embedding += usage.inputTokens;
269
+ }
270
+ else {
271
+ d.day.tokens.input += usage.inputTokens;
272
+ d.day.tokens.output += usage.outputTokens;
273
+ d.day.tokens.cacheRead += usage.cacheReadTokens;
274
+ d.day.tokens.cacheWrite += usage.cacheWriteTokens;
275
+ }
276
+ const images = Number(r.images);
277
+ d.day.images += images;
278
+ addUsageCost(d.cost, cost);
279
+ addUsageCost(weekCost, cost);
289
280
  const o = org(r.org_id);
290
281
  o.tokens += total;
291
- addCost(o.cost, cost, total);
292
- }
293
- for (const r of input.embeddings) {
294
- const d = days.get(r.day);
295
- if (!d)
296
- continue;
297
- const n = Number(r.input);
298
- const cost = costOf({ inputTokens: n, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }, price(r.provider, r.model));
299
- if (cost === null && n > 0)
300
- costPartial = true;
301
- d.day.tokens.embedding += n;
302
- addCost(d.cost, cost, n);
303
- const o = org(r.org_id);
304
- o.tokens += n;
305
- addCost(o.cost, cost, n);
282
+ o.images += images;
283
+ addUsageCost(o.cost, cost);
306
284
  }
307
285
  for (const r of input.runs) {
308
286
  const d = days.get(r.day);
@@ -316,26 +294,25 @@ function summarize(input) {
316
294
  b.runs - a.runs ||
317
295
  (a.orgId < b.orgId ? -1 : a.orgId > b.orgId ? 1 : 0));
318
296
  const rest = ranked.slice(USAGE_TOP_ORGS);
319
- const restCost = newCost();
320
- for (const o of rest) {
321
- restCost.priced += o.cost.priced;
322
- restCost.anyPriced ||= o.cost.anyPriced;
323
- restCost.unpriced ||= o.cost.unpriced;
324
- }
297
+ const restCost = emptyUsageCost();
298
+ for (const o of rest)
299
+ addUsageCost(restCost, o.cost);
325
300
  return {
326
- days: [...days.values()].map((d) => ({ ...d.day, cost: costValue(d.cost) })),
327
- costPartial,
301
+ days: [...days.values()].map((d) => ({ ...d.day, cost: d.cost })),
302
+ cost: weekCost,
328
303
  top: ranked.slice(0, USAGE_TOP_ORGS).map((o) => ({
329
304
  orgId: o.orgId,
330
305
  runs: o.runs,
331
306
  tokens: o.tokens,
332
- cost: costValue(o.cost),
307
+ images: o.images,
308
+ cost: o.cost,
333
309
  })),
334
310
  otherOrgs: {
335
311
  count: rest.length,
336
312
  runs: rest.reduce((s, o) => s + o.runs, 0),
337
313
  tokens: rest.reduce((s, o) => s + o.tokens, 0),
338
- cost: costValue(restCost),
314
+ images: rest.reduce((s, o) => s + o.images, 0),
315
+ cost: restCost,
339
316
  },
340
317
  };
341
318
  }
@@ -28,6 +28,7 @@ const NO_LINEAGE = { automationRunId: null, triggerEventId: null };
28
28
  * - anything else, or no such event: neither.
29
29
  */
30
30
  export async function automationRunAt(t, conversationId, seq) {
31
+ // org-filter: caller holds the conversation row lock in its org
31
32
  const ev = await t
32
33
  .selectFrom("conversation_events")
33
34
  .select(["type", "payload"])
@@ -123,6 +124,7 @@ export const unattendedFails = (u) => unattendedRules(u) && u.unattendedAsk ===
123
124
  * task posted into) does not make it attended: the task's grants are the creator's, and only the
124
125
  * creator is the one asked.
125
126
  */
127
+ // org-filter: runId is the claimed run's id; events are correlated by r.conversation_id
126
128
  async function personJoined(db, runId) {
127
129
  const row = await db
128
130
  .selectFrom("runs as r")
@@ -49,6 +49,7 @@ const WAKE_EVENT_TYPES = ["background_task_finished", "subagent_delivery"];
49
49
  * - no other wake of this conversation started in the last {@link WAKE_WINDOW_MS} (else `later`).
50
50
  * The boundary is the newest event whose trigger account can send.
51
51
  */
52
+ // org-filter: conv was locked and resolved in its org by the caller (RunQueue)
52
53
  export async function wakeDecisionIn(t, conv, consumed, deploymentOn, canSend) {
53
54
  const finishes = await t
54
55
  .selectFrom("conversation_events as e")
@@ -132,6 +132,7 @@ function isBusMessage(m) {
132
132
  * Read from PG, so any replica derives the same value.
133
133
  */
134
134
  export async function conversationLocale(db, orgId, conversationId, uptoSeq) {
135
+ // org-filter: conversationId was resolved in orgId by the channel delivery or caller
135
136
  const m = await db
136
137
  .selectFrom("conversation_events")
137
138
  .select([
@@ -1832,6 +1833,7 @@ class Delivery {
1832
1833
  * card. The handoff links an answer took along count as sent.
1833
1834
  */
1834
1835
  async rebuildProgress(runId, final) {
1836
+ // org-filter: this.conversationId is the channel delivery job's org-scoped conversation
1835
1837
  const start = await this.d.db
1836
1838
  .selectFrom("conversation_events")
1837
1839
  .select("seq")
@@ -67,6 +67,8 @@ export declare const KernelConfigSchema: z.ZodObject<{
67
67
  }, z.core.$strict>>;
68
68
  db: z.ZodPrefault<z.ZodObject<{
69
69
  url: z.ZodString;
70
+ migrationUrl: z.ZodOptional<z.ZodString>;
71
+ extensionsUrl: z.ZodOptional<z.ZodString>;
70
72
  poolMax: z.ZodDefault<z.ZodNumber>;
71
73
  connectTimeoutMs: z.ZodDefault<z.ZodNumber>;
72
74
  idleTimeoutMs: z.ZodDefault<z.ZodNumber>;
@@ -327,7 +327,23 @@ export const KernelConfigSchema = z.strictObject({
327
327
  url: z
328
328
  .string()
329
329
  .min(1)
330
- .meta(meta({ secret: true, description: "PostgreSQL connection URL" })),
330
+ .meta(meta({ secret: true, description: "PostgreSQL runtime connection URL" })),
331
+ migrationUrl: z
332
+ .string()
333
+ .min(1)
334
+ .optional()
335
+ .meta(meta({
336
+ secret: true,
337
+ description: "PostgreSQL owner connection URL for capybara migrate only",
338
+ })),
339
+ extensionsUrl: z
340
+ .string()
341
+ .min(1)
342
+ .optional()
343
+ .meta(meta({
344
+ secret: true,
345
+ description: "PostgreSQL connection URL for the shared extension login",
346
+ })),
331
347
  poolMax: z
332
348
  .number()
333
349
  .int()
@@ -61,6 +61,7 @@ import { conversationTree } from "./tree.js";
61
61
  * SQL for the {@link ProjectState} of the conversation row aliased/named `ref` (a correlated
62
62
  * subquery on the latest `project_root` event, served by `conversation_events_project_root_idx`).
63
63
  */
64
+ // org-filter: correlated subquery over an outer conversations query filtered by org_id
64
65
  function projectStateSql(ref) {
65
66
  const id = sql.ref(`${ref}.id`);
66
67
  return sql `(
@@ -226,6 +227,7 @@ function storedSubject(s) {
226
227
  : JSON.stringify({ source: s.source, kind: s.kind, id: s.id, title: s.title });
227
228
  }
228
229
  /** The sums of the `usage` events matching `where` (over `conversation_events e`), one row. */
230
+ // org-filter: callers scope `where` to conversations already filtered by org_id
229
231
  const usageSums = (where) => sql `
230
232
  WITH usage_events AS (
231
233
  SELECT e.payload
@@ -1598,6 +1600,7 @@ let ConversationsService = class ConversationsService {
1598
1600
  }
1599
1601
  // the latest summary (conversation_events_compaction_summary_idx), then the newest messages
1600
1602
  // after what it covers
1603
+ // org-filter: conversation id was verified in orgId above
1601
1604
  const summary = await this.db
1602
1605
  .selectFrom("conversation_events")
1603
1606
  .select(["seq", sql `payload`.as("payload")])
@@ -1607,6 +1610,7 @@ let ConversationsService = class ConversationsService {
1607
1610
  .limit(1)
1608
1611
  .executeTakeFirst();
1609
1612
  const summaryPayload = summary?.payload;
1613
+ // org-filter: conversation id was verified in orgId above
1610
1614
  const rows = await this.db
1611
1615
  .selectFrom("conversation_events")
1612
1616
  .select(["seq", "type", sql `payload`.as("payload")])
@@ -1622,6 +1626,7 @@ let ConversationsService = class ConversationsService {
1622
1626
  // fill the newest rows, and a files-only message has no text, so the log is asked when they
1623
1627
  // hold none)
1624
1628
  if (summary === undefined && !rows.some((r) => r.type === "user_message")) {
1629
+ // org-filter: conversation id was verified in orgId above
1625
1630
  const anyUser = await this.db
1626
1631
  .selectFrom("conversation_events")
1627
1632
  .select("seq")
@@ -157,7 +157,9 @@ export declare class EventLog {
157
157
  */
158
158
  publishChanged(conversationId: string, what: ConversationChange): Promise<void>;
159
159
  /** 读 `afterSeq` 之后的事件,按 seq 升序,最多 `limit` 条。 */
160
- readAfter(conversationId: string, afterSeq: number, limit?: number): Promise<ConversationEvent[]>;
160
+ readAfter(conversationId: string, afterSeq: number, limit?: number, options?: {
161
+ includeUsagePricing?: boolean;
162
+ }): Promise<ConversationEvent[]>;
161
163
  /**
162
164
  * The page of the log that ends right before `beforeSeq` (`null`: the log's end), in ascending
163
165
  * seq: the last `limit` events before it, extended back so the first event is the log's first or
@@ -175,7 +177,9 @@ export declare class EventLog {
175
177
  * `runIds` 为空时返回空数组。走部分索引 `conversation_events_run_idx (conversation_id, run_id, seq)`(0027):
176
178
  * 往前翻页读较早的运行时不扫更晚运行的事件。
177
179
  */
178
- readRunsAfter(conversationId: string, runIds: readonly string[], afterSeq: number, limit?: number): Promise<ConversationEvent[]>;
180
+ readRunsAfter(conversationId: string, runIds: readonly string[], afterSeq: number, limit?: number, options?: {
181
+ includeUsagePricing?: boolean;
182
+ }): Promise<ConversationEvent[]>;
179
183
  /**
180
184
  * The delivery scope of `runId` in the conversation (truthful delivery spec §2 step 2): the run's
181
185
  * `run_started` seq `S` through the run index (0 when the run has none), then one range read of