@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
@@ -16,6 +16,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
16
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
17
17
  import { OutboxService } from "../infra/outbox/outbox.service.js";
18
18
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
19
+ import { readPriceSnapshots } from "../models/price-snapshot.js";
19
20
  import { PushOwed, PushOwedModule } from "../push/push-owed.js";
20
21
  import { ConversationEventSchema, } from "./events.js";
21
22
  /**
@@ -54,13 +55,18 @@ export const CONVERSATION_CHANGES = [
54
55
  "background",
55
56
  ];
56
57
  const notFound = () => new ApiError("conversation.not_found", "Conversation not found");
57
- function toEvent(r) {
58
+ function toEvent(r, withUsagePricing = false) {
59
+ let payload = r.payload;
60
+ if (r.type === "usage" && !withUsagePricing && payload && typeof payload === "object") {
61
+ const { priceSnapshot: _priceSnapshot, ...usage } = payload;
62
+ payload = usage;
63
+ }
58
64
  return {
59
65
  conversationId: r.conversation_id,
60
66
  seq: Number(r.seq),
61
67
  type: r.type,
62
68
  runId: r.run_id,
63
- payload: r.payload,
69
+ payload,
64
70
  createdAt: r.created_at,
65
71
  };
66
72
  }
@@ -82,6 +88,7 @@ const EVENT_COLUMNS = [
82
88
  * §8.1); a conversation without one writes nothing more. A push trigger event (an approval, a
83
89
  * run's end, ...: `push/triggers.ts`) owes its push fanout in the same transaction (`PushOwed`).
84
90
  */
91
+ // org-filter: EventLog is keyed by conversation id; callers resolve the conversation in its org
85
92
  let EventLog = class EventLog {
86
93
  db;
87
94
  bus;
@@ -167,7 +174,7 @@ let EventLog = class EventLog {
167
174
  }
168
175
  }
169
176
  /** 读 `afterSeq` 之后的事件,按 seq 升序,最多 `limit` 条。 */
170
- async readAfter(conversationId, afterSeq, limit = 500) {
177
+ async readAfter(conversationId, afterSeq, limit = 500, options) {
171
178
  const rows = await this.db
172
179
  .selectFrom("conversation_events")
173
180
  .select(EVENT_COLUMNS)
@@ -176,7 +183,7 @@ let EventLog = class EventLog {
176
183
  .orderBy("seq")
177
184
  .limit(limit)
178
185
  .execute();
179
- return rows.map(toEvent);
186
+ return rows.map((row) => toEvent(row, options?.includeUsagePricing));
180
187
  }
181
188
  /**
182
189
  * The page of the log that ends right before `beforeSeq` (`null`: the log's end), in ascending
@@ -234,7 +241,7 @@ let EventLog = class EventLog {
234
241
  .executeTakeFirst()
235
242
  : undefined;
236
243
  return {
237
- events: [...head, ...rows].map(toEvent),
244
+ events: [...head, ...rows].map((row) => toEvent(row)),
238
245
  turnsBefore: Number(turns?.n ?? 0),
239
246
  };
240
247
  }
@@ -243,7 +250,7 @@ let EventLog = class EventLog {
243
250
  * `runIds` 为空时返回空数组。走部分索引 `conversation_events_run_idx (conversation_id, run_id, seq)`(0027):
244
251
  * 往前翻页读较早的运行时不扫更晚运行的事件。
245
252
  */
246
- async readRunsAfter(conversationId, runIds, afterSeq, limit = 500) {
253
+ async readRunsAfter(conversationId, runIds, afterSeq, limit = 500, options) {
247
254
  if (runIds.length === 0)
248
255
  return [];
249
256
  const rows = await this.db
@@ -255,7 +262,7 @@ let EventLog = class EventLog {
255
262
  .orderBy("seq")
256
263
  .limit(limit)
257
264
  .execute();
258
- return rows.map(toEvent);
265
+ return rows.map((row) => toEvent(row, options?.includeUsagePricing));
259
266
  }
260
267
  /**
261
268
  * The delivery scope of `runId` in the conversation (truthful delivery spec §2 step 2): the run's
@@ -403,8 +410,6 @@ let EventLog = class EventLog {
403
410
  return r.data;
404
411
  }
405
412
  /** The append itself, in the context's transaction (both callers open or join one). */
406
- // org-filter: the log writer is keyed by conversation id only; every append path resolved the
407
- // conversation in its org first (access check, run claim, channel binding)
408
413
  async write(conversationId, events, bodies) {
409
414
  const t = this.db;
410
415
  // 先锁会话行:之后的幂等查询与 seq 分配都在这把锁内,并发 append 依次执行。The same statement
@@ -490,6 +495,11 @@ let EventLog = class EventLog {
490
495
  .executeTakeFirstOrThrow();
491
496
  const toSeq = Number(last_seq);
492
497
  const base = toSeq - n;
498
+ const usageModels = fresh.flatMap((i) => {
499
+ const body = bodies[i];
500
+ return body?.type === "usage" ? [body.payload] : [];
501
+ });
502
+ const priceOf = usageModels.length > 0 ? await readPriceSnapshots(t.db, usageModels) : undefined;
493
503
  const inserted = await t
494
504
  .insertInto("conversation_events")
495
505
  .values(fresh.map((i, j) => {
@@ -497,11 +507,14 @@ let EventLog = class EventLog {
497
507
  const body = bodies[i];
498
508
  return {
499
509
  conversation_id: conversationId,
510
+ org_id: conv.org_id,
500
511
  seq: base + j + 1,
501
512
  type: body.type,
502
513
  run_id: e.runId ?? null,
503
514
  idem_key: e.idemKey ?? null,
504
- payload: payloadJson(body.payload),
515
+ payload: payloadJson(body.type === "usage"
516
+ ? { ...body.payload, priceSnapshot: priceOf?.(body.payload) }
517
+ : body.payload),
505
518
  };
506
519
  }))
507
520
  .returning(EVENT_COLUMNS)
@@ -0,0 +1,111 @@
1
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { TransactionHost } from "../infra/database/transaction-host.js";
4
+ import { LockService } from "../infra/lock/lock.service.js";
5
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
6
+ import type { KernelLogger } from "../log.js";
7
+ /** The maintenance job name for one batched backfill step (no `:`). */
8
+ export declare const EVENT_ORG_BACKFILL_JOB = "conversation-events-org-backfill";
9
+ /** The periodic kickoff's name (scheduler key and lock; no `:`). */
10
+ export declare const EVENT_ORG_BACKFILL_KICKOFF_JOB = "conversation-events-org-backfill-kickoff";
11
+ /** How often the worker kickoff checks for remaining NULL `org_id` rows during rolling deploys. */
12
+ export declare const EVENT_ORG_BACKFILL_KICKOFF_PERIOD_MS: number;
13
+ /** Rows committed per short backfill transaction. */
14
+ export declare const EVENT_ORG_BACKFILL_BATCH = 5000;
15
+ /** Keyset cursor in primary-key `(conversation_id, seq)` order. */
16
+ export interface EventOrgBackfillCursor {
17
+ conversationId: string;
18
+ /** `bigint` serialized as decimal string to stay lossless in JSON job payloads. */
19
+ seq: string;
20
+ }
21
+ /** Payload of one {@link EVENT_ORG_BACKFILL_JOB} batch. */
22
+ export interface EventOrgBackfillData {
23
+ /** Exclusive keyset cursor; `null` starts from the beginning of `(conversation_id, seq)`. */
24
+ after: EventOrgBackfillCursor | null;
25
+ /** Optional batch size override (clamped to `1..EVENT_ORG_BACKFILL_BATCH`); tests use small values. */
26
+ batchSize?: number;
27
+ }
28
+ /** Counts produced by the post-backfill parent and ownership integrity check. */
29
+ export interface EventOrgIntegrity {
30
+ /** Events whose `conversation_id` has no matching row in `conversations`. */
31
+ missingParents: number;
32
+ /** Events whose non-null `org_id` disagrees with their parent conversation's `org_id`. */
33
+ mismatchedOrgs: number;
34
+ /** Events whose `org_id` is still `NULL`. */
35
+ remainingNulls: number;
36
+ }
37
+ /** Outcome of one committed backfill batch. */
38
+ export interface EventOrgBackfillBatchResult {
39
+ /** Rows whose `org_id` was filled in this transaction. */
40
+ updated: number;
41
+ /** Last `(conversation_id, seq)` key locked in this batch, or `null` if none matched. */
42
+ last: EventOrgBackfillCursor | null;
43
+ /** Cursor of the next batch owed via the outbox, or `null` when this pass reached the end. */
44
+ next: EventOrgBackfillCursor | null;
45
+ /** True when the pass reached the end and verified zero remaining `NULL` rows. */
46
+ done: boolean;
47
+ /** Populated when the pass finished with no remaining `NULL` rows. */
48
+ integrity?: EventOrgIntegrity;
49
+ }
50
+ /**
51
+ * Deterministic BullMQ / outbox job id for a backfill batch cursor (no `:`).
52
+ * The first batch uses a fixed id so repeated kickoffs deduplicate cleanly; subsequent batches
53
+ * hash the `(conversationId, seq)` key so arbitrary conversation ids never introduce `:`.
54
+ */
55
+ export declare function eventOrgBackfillJobId(after: EventOrgBackfillCursor | null): string;
56
+ /**
57
+ * Worker-only batched backfill of `conversation_events.org_id` from `conversations` (issue #1175):
58
+ *
59
+ * - Migration 0215 adds the nullable `org_id` column and `NOT VALID` composite FK with short locks
60
+ * only; this job fills existing and rolling-window NULL rows outside migration transactions.
61
+ * - Each invocation commits one short `@Transactional()` batch of up to
62
+ * {@link EVENT_ORG_BACKFILL_BATCH} (5,000) rows ordered by `(conversation_id, seq)` using
63
+ * `FOR UPDATE OF e SKIP LOCKED`, so concurrent appends and two concurrent workers never block or
64
+ * deadlock on each other.
65
+ * - When a full batch is processed, the next resumable cursor job is owed atomically in the same
66
+ * transaction through `OutboxService.add` under a deterministic job id without `:`.
67
+ * - When no `NULL` rows remain, the job verifies that zero events lack a parent conversation and
68
+ * zero events carry a mismatched `org_id`, then stops.
69
+ */
70
+ export declare class EventOrgBackfillJob {
71
+ private readonly db;
72
+ readonly txHost: TransactionHost;
73
+ private readonly outbox;
74
+ private readonly log;
75
+ constructor(db: KernelDb, txHost: TransactionHost, outbox: Pick<OutboxService, "add">, log: Pick<KernelLogger, "info" | "warn">);
76
+ /** Whether any `conversation_events` row still has `org_id IS NULL`. */
77
+ anyNullOrg(): Promise<boolean>;
78
+ /**
79
+ * Deployment-wide ownership check: counts orphan events (no parent in `conversations`),
80
+ * mismatched non-null `org_id` rows, and remaining `NULL` rows.
81
+ */
82
+ verifyIntegrity(): Promise<EventOrgIntegrity>;
83
+ /** Owes the first backfill batch via the transactional outbox (deduplicated by fixed job id). */
84
+ oweFirst(opts?: {
85
+ batchSize?: number;
86
+ }): Promise<boolean>;
87
+ /**
88
+ * Executes one committed batch starting strictly after `data.after`, owes the next batch if the
89
+ * batch was full, and verifies integrity once no `NULL` rows remain.
90
+ */
91
+ runBatch(data?: EventOrgBackfillData): Promise<EventOrgBackfillBatchResult>;
92
+ private commitBatch;
93
+ }
94
+ /**
95
+ * Periodic worker-only kickoff for {@link EventOrgBackfillJob} (`@LockedInterval`, once per tick
96
+ * across replicas and once on worker start; provided only under `WorkerModule`). While any
97
+ * `conversation_events` row has `org_id IS NULL`, it owes the first batch under its deterministic
98
+ * job id; once zero `NULL` rows remain, it is a no-op.
99
+ */
100
+ export declare class EventOrgBackfillKickoffJob {
101
+ private readonly backfill;
102
+ readonly config: KernelConfigService;
103
+ readonly lockService: LockService;
104
+ readonly log: KernelLogger;
105
+ constructor(backfill: Pick<EventOrgBackfillJob, "anyNullOrg" | "oweFirst">, config: KernelConfigService, lockService: LockService, log: KernelLogger);
106
+ tick(): Promise<void>;
107
+ /** One kickoff check without the tick lock (the interval body; tests call it directly). */
108
+ runOnce(opts?: {
109
+ batchSize?: number;
110
+ }): Promise<boolean>;
111
+ }
@@ -0,0 +1,264 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { createHash } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
+ import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { asPlatform } from "../infra/database/org-scope.js";
16
+ import { TransactionHost } from "../infra/database/transaction-host.js";
17
+ import { Transactional } from "../infra/database/transactional.decorator.js";
18
+ import { LockService } from "../infra/lock/lock.service.js";
19
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
20
+ import { LockedInterval } from "../infra/schedule/locked-interval.js";
21
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
22
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
23
+ /** The maintenance job name for one batched backfill step (no `:`). */
24
+ export const EVENT_ORG_BACKFILL_JOB = "conversation-events-org-backfill";
25
+ /** The periodic kickoff's name (scheduler key and lock; no `:`). */
26
+ export const EVENT_ORG_BACKFILL_KICKOFF_JOB = "conversation-events-org-backfill-kickoff";
27
+ /** How often the worker kickoff checks for remaining NULL `org_id` rows during rolling deploys. */
28
+ export const EVENT_ORG_BACKFILL_KICKOFF_PERIOD_MS = 15 * 60_000;
29
+ /** Rows committed per short backfill transaction. */
30
+ export const EVENT_ORG_BACKFILL_BATCH = 5_000;
31
+ /**
32
+ * Deterministic BullMQ / outbox job id for a backfill batch cursor (no `:`).
33
+ * The first batch uses a fixed id so repeated kickoffs deduplicate cleanly; subsequent batches
34
+ * hash the `(conversationId, seq)` key so arbitrary conversation ids never introduce `:`.
35
+ */
36
+ export function eventOrgBackfillJobId(after) {
37
+ if (after === null)
38
+ return `${EVENT_ORG_BACKFILL_JOB}-first`;
39
+ const digest = createHash("sha256")
40
+ .update(`${after.conversationId}\0${after.seq}`)
41
+ .digest("hex")
42
+ .slice(0, 16);
43
+ return `${EVENT_ORG_BACKFILL_JOB}-${digest}`;
44
+ }
45
+ /**
46
+ * Worker-only batched backfill of `conversation_events.org_id` from `conversations` (issue #1175):
47
+ *
48
+ * - Migration 0215 adds the nullable `org_id` column and `NOT VALID` composite FK with short locks
49
+ * only; this job fills existing and rolling-window NULL rows outside migration transactions.
50
+ * - Each invocation commits one short `@Transactional()` batch of up to
51
+ * {@link EVENT_ORG_BACKFILL_BATCH} (5,000) rows ordered by `(conversation_id, seq)` using
52
+ * `FOR UPDATE OF e SKIP LOCKED`, so concurrent appends and two concurrent workers never block or
53
+ * deadlock on each other.
54
+ * - When a full batch is processed, the next resumable cursor job is owed atomically in the same
55
+ * transaction through `OutboxService.add` under a deterministic job id without `:`.
56
+ * - When no `NULL` rows remain, the job verifies that zero events lack a parent conversation and
57
+ * zero events carry a mismatched `org_id`, then stops.
58
+ */
59
+ let EventOrgBackfillJob = class EventOrgBackfillJob {
60
+ db;
61
+ txHost;
62
+ outbox;
63
+ log;
64
+ constructor(db, txHost, outbox, log) {
65
+ this.db = db;
66
+ this.txHost = txHost;
67
+ this.outbox = outbox;
68
+ this.log = log;
69
+ }
70
+ /** Whether any `conversation_events` row still has `org_id IS NULL`. */
71
+ anyNullOrg() {
72
+ // org-filter: deployment-wide existence check for unbackfilled conversation_events rows
73
+ return asPlatform("conversation_events org_id backfill: check for remaining NULL rows", async () => {
74
+ const row = await this.db
75
+ .selectFrom("conversation_events")
76
+ .select("conversation_id")
77
+ .where("org_id", "is", null)
78
+ .limit(1)
79
+ .executeTakeFirst();
80
+ return row !== undefined;
81
+ });
82
+ }
83
+ /**
84
+ * Deployment-wide ownership check: counts orphan events (no parent in `conversations`),
85
+ * mismatched non-null `org_id` rows, and remaining `NULL` rows.
86
+ */
87
+ verifyIntegrity() {
88
+ // org-filter: deployment-wide integrity check across all conversation_events and conversations
89
+ return asPlatform("conversation_events org_id backfill: verify parent and org ownership integrity", async () => {
90
+ const res = await sql `
91
+ SELECT
92
+ count(*) FILTER (WHERE c.id IS NULL)::int AS missing_parents,
93
+ count(*) FILTER (
94
+ WHERE c.id IS NOT NULL AND e.org_id IS NOT NULL AND e.org_id <> c.org_id
95
+ )::int AS mismatched_orgs,
96
+ count(*) FILTER (WHERE e.org_id IS NULL)::int AS remaining_nulls
97
+ FROM capybara.conversation_events e
98
+ LEFT JOIN capybara.conversations c ON c.id = e.conversation_id
99
+ `.execute(this.db.db);
100
+ const row = res.rows[0];
101
+ return {
102
+ missingParents: row?.missing_parents ?? 0,
103
+ mismatchedOrgs: row?.mismatched_orgs ?? 0,
104
+ remainingNulls: row?.remaining_nulls ?? 0,
105
+ };
106
+ });
107
+ }
108
+ /** Owes the first backfill batch via the transactional outbox (deduplicated by fixed job id). */
109
+ async oweFirst(opts = {}) {
110
+ const data = opts.batchSize === undefined ? { after: null } : { after: null, batchSize: opts.batchSize };
111
+ return this.outbox.add({
112
+ queue: MAINTENANCE_QUEUE_NAME,
113
+ name: EVENT_ORG_BACKFILL_JOB,
114
+ jobId: eventOrgBackfillJobId(null),
115
+ data,
116
+ });
117
+ }
118
+ /**
119
+ * Executes one committed batch starting strictly after `data.after`, owes the next batch if the
120
+ * batch was full, and verifies integrity once no `NULL` rows remain.
121
+ */
122
+ async runBatch(data = { after: null }) {
123
+ const rawSize = data.batchSize ?? EVENT_ORG_BACKFILL_BATCH;
124
+ const batchSize = Math.max(1, Math.min(EVENT_ORG_BACKFILL_BATCH, Math.floor(rawSize)));
125
+ // org-filter: deployment-wide batched backfill of conversation_events.org_id from conversations
126
+ const batch = await asPlatform("conversation_events org_id backfill batch", () => this.commitBatch(data.after ?? null, batchSize, data.batchSize));
127
+ if (batch.next !== null) {
128
+ return { ...batch, done: false };
129
+ }
130
+ if (await this.anyNullOrg()) {
131
+ // Either a concurrent worker still holds uncommitted NULL rows or an old replica inserted a
132
+ // NULL row behind our cursor; the next kickoff or sibling worker finishes it.
133
+ return { ...batch, done: false };
134
+ }
135
+ const integrity = await this.verifyIntegrity();
136
+ if (integrity.missingParents > 0 || integrity.mismatchedOrgs > 0) {
137
+ throw new Error(`conversation_events org_id integrity check failed: missingParents=${integrity.missingParents}, mismatchedOrgs=${integrity.mismatchedOrgs}`);
138
+ }
139
+ if (batch.updated > 0) {
140
+ this.log.info("conversation_events org_id backfill pass finished", { ...integrity });
141
+ }
142
+ return {
143
+ ...batch,
144
+ done: integrity.remainingNulls === 0,
145
+ integrity,
146
+ };
147
+ }
148
+ async commitBatch(after, batchSize, explicitBatchSize) {
149
+ // Split the cursor branch so Postgres uses a pure index range scan on conversation_events_pkey
150
+ // when resuming after a cursor instead of falling back to an OR scan from the start.
151
+ const cursorClause = after === null
152
+ ? sql ``
153
+ : sql `AND (e.conversation_id, e.seq) > (${after.conversationId}, ${after.seq}::bigint)`;
154
+ const res = await sql `
155
+ WITH batch AS (
156
+ SELECT e.conversation_id, e.seq, c.id AS parent_id, c.org_id
157
+ FROM capybara.conversation_events e
158
+ LEFT JOIN capybara.conversations c ON c.id = e.conversation_id
159
+ WHERE e.org_id IS NULL
160
+ ${cursorClause}
161
+ ORDER BY e.conversation_id, e.seq
162
+ LIMIT ${batchSize}
163
+ FOR UPDATE OF e SKIP LOCKED
164
+ ),
165
+ updated AS (
166
+ UPDATE capybara.conversation_events e
167
+ SET org_id = batch.org_id
168
+ FROM batch
169
+ WHERE batch.parent_id IS NOT NULL
170
+ AND e.conversation_id = batch.conversation_id
171
+ AND e.seq = batch.seq
172
+ AND e.org_id IS NULL
173
+ RETURNING e.conversation_id, e.seq
174
+ )
175
+ SELECT
176
+ (SELECT count(*)::int FROM batch) AS fetched_count,
177
+ (SELECT count(*)::int FROM batch WHERE parent_id IS NULL) AS missing_parents,
178
+ (SELECT count(*)::int FROM updated) AS updated_count,
179
+ (SELECT conversation_id FROM batch ORDER BY conversation_id DESC, seq DESC LIMIT 1) AS last_conv,
180
+ (SELECT seq::text FROM batch ORDER BY conversation_id DESC, seq DESC LIMIT 1) AS last_seq
181
+ `.execute(this.db.db);
182
+ const row = res.rows[0];
183
+ const fetched = row?.fetched_count ?? 0;
184
+ const missingParents = row?.missing_parents ?? 0;
185
+ if (missingParents > 0) {
186
+ throw new Error(`conversation_events org_id backfill found ${missingParents} event(s) without a parent conversation`);
187
+ }
188
+ const updated = row?.updated_count ?? 0;
189
+ const last = row?.last_conv !== null &&
190
+ row?.last_conv !== undefined &&
191
+ row?.last_seq !== null &&
192
+ row?.last_seq !== undefined
193
+ ? { conversationId: row.last_conv, seq: row.last_seq }
194
+ : null;
195
+ const next = fetched >= batchSize && last !== null ? last : null;
196
+ if (next !== null) {
197
+ const nextData = explicitBatchSize === undefined
198
+ ? { after: next }
199
+ : { after: next, batchSize: explicitBatchSize };
200
+ await this.outbox.add({
201
+ queue: MAINTENANCE_QUEUE_NAME,
202
+ name: EVENT_ORG_BACKFILL_JOB,
203
+ jobId: eventOrgBackfillJobId(next),
204
+ data: nextData,
205
+ });
206
+ }
207
+ return { updated, last, next };
208
+ }
209
+ };
210
+ __decorate([
211
+ Transactional()
212
+ ], EventOrgBackfillJob.prototype, "oweFirst", null);
213
+ __decorate([
214
+ Transactional()
215
+ ], EventOrgBackfillJob.prototype, "commitBatch", null);
216
+ EventOrgBackfillJob = __decorate([
217
+ Injectable(),
218
+ __param(0, Inject(KernelDb)),
219
+ __param(1, Inject(TransactionHost)),
220
+ __param(2, Inject(OutboxService)),
221
+ __param(3, Inject(KERNEL_LOGGER))
222
+ ], EventOrgBackfillJob);
223
+ export { EventOrgBackfillJob };
224
+ /**
225
+ * Periodic worker-only kickoff for {@link EventOrgBackfillJob} (`@LockedInterval`, once per tick
226
+ * across replicas and once on worker start; provided only under `WorkerModule`). While any
227
+ * `conversation_events` row has `org_id IS NULL`, it owes the first batch under its deterministic
228
+ * job id; once zero `NULL` rows remain, it is a no-op.
229
+ */
230
+ let EventOrgBackfillKickoffJob = class EventOrgBackfillKickoffJob {
231
+ backfill;
232
+ config;
233
+ lockService;
234
+ log;
235
+ constructor(backfill, config, lockService, log) {
236
+ this.backfill = backfill;
237
+ this.config = config;
238
+ this.lockService = lockService;
239
+ this.log = log;
240
+ }
241
+ async tick() {
242
+ if (await this.runOnce())
243
+ this.log.info("conversation_events org_id backfill owed");
244
+ }
245
+ /** One kickoff check without the tick lock (the interval body; tests call it directly). */
246
+ async runOnce(opts) {
247
+ if (!(await this.backfill.anyNullOrg()))
248
+ return false;
249
+ return this.backfill.oweFirst(opts);
250
+ }
251
+ };
252
+ __decorate([
253
+ LockedInterval(EVENT_ORG_BACKFILL_KICKOFF_JOB, () => EVENT_ORG_BACKFILL_KICKOFF_PERIOD_MS, {
254
+ runOnStart: true,
255
+ })
256
+ ], EventOrgBackfillKickoffJob.prototype, "tick", null);
257
+ EventOrgBackfillKickoffJob = __decorate([
258
+ Injectable(),
259
+ __param(0, Inject(EventOrgBackfillJob)),
260
+ __param(1, Inject(KernelConfigService)),
261
+ __param(2, Inject(LockService)),
262
+ __param(3, Inject(KERNEL_LOGGER))
263
+ ], EventOrgBackfillKickoffJob);
264
+ export { EventOrgBackfillKickoffJob };
@@ -0,0 +1,3 @@
1
+ /** Batched `conversation_events.org_id` backfill ({@link EventOrgBackfillJob}), worker-only. */
2
+ export declare class EventOrgBackfillModule {
3
+ }
@@ -0,0 +1,18 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Module } from "@nestjs/common";
8
+ import { EventOrgBackfillJob } from "./event-org-backfill.js";
9
+ /** Batched `conversation_events.org_id` backfill ({@link EventOrgBackfillJob}), worker-only. */
10
+ let EventOrgBackfillModule = class EventOrgBackfillModule {
11
+ };
12
+ EventOrgBackfillModule = __decorate([
13
+ Module({
14
+ providers: [EventOrgBackfillJob],
15
+ exports: [EventOrgBackfillJob],
16
+ })
17
+ ], EventOrgBackfillModule);
18
+ export { EventOrgBackfillModule };
@@ -1266,6 +1266,20 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1266
1266
  step: z.ZodNumber;
1267
1267
  provider: z.ZodString;
1268
1268
  model: z.ZodString;
1269
+ priceSnapshot: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
1270
+ version: z.ZodLiteral<1>;
1271
+ currency: z.ZodString;
1272
+ status: z.ZodLiteral<"priced">;
1273
+ inputPerMTok: z.ZodString;
1274
+ outputPerMTok: z.ZodString;
1275
+ cacheReadPerMTok: z.ZodNullable<z.ZodString>;
1276
+ cacheWritePerMTok: z.ZodNullable<z.ZodString>;
1277
+ cacheWritePerMTokByTtl: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
1278
+ }, z.core.$strip>, z.ZodObject<{
1279
+ version: z.ZodLiteral<1>;
1280
+ currency: z.ZodString;
1281
+ status: z.ZodLiteral<"unpriced">;
1282
+ }, z.core.$strip>], "status">>;
1269
1283
  purpose: z.ZodOptional<z.ZodEnum<{
1270
1284
  compaction: "compaction";
1271
1285
  image: "image";
@@ -2,6 +2,7 @@ import { posix } from "node:path";
2
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
+ import { PriceSnapshotSchema } from "../models/price-snapshot.js";
5
6
  import { ORG_ROLES } from "../orgs/roles.js";
6
7
  import { coversHost } from "../sandbox/modes.js";
7
8
  import { TOOL_VIEW_DIFF_MAX_LINES, TOOL_VIEW_LINE_MAX_CHARS, TOOL_VIEW_PATH_MAX_CHARS, } from "../tools/view.js";
@@ -1245,6 +1246,7 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1245
1246
  provider: z.string(),
1246
1247
  model: z.string(),
1247
1248
  ...ModelUsageShape,
1249
+ priceSnapshot: PriceSnapshotSchema.optional(),
1248
1250
  purpose: z
1249
1251
  .enum(["compaction", "title", "web_fetch", "review", "image", "vision", "suggestion"])
1250
1252
  .optional(),
@@ -147,6 +147,7 @@ let ConversationFiles = class ConversationFiles {
147
147
  return f;
148
148
  }
149
149
  /** The tool call of each delivery logged in the conversation, by artifact (= file) id. */
150
+ // org-filter: callers verify access to conversationId in orgId before calling
150
151
  async callIds(conversationId) {
151
152
  const rows = await this.db
152
153
  .selectFrom("conversation_events")
@@ -40,6 +40,7 @@ let ConversationLeakCheck = class ConversationLeakCheck {
40
40
  for (const [path, value] of candidates) {
41
41
  // the payload is stored as JSON text, so a value is searched in its JSON-escaped form
42
42
  const needle = JSON.stringify(value).slice(1, -1);
43
+ // org-filter: ids come from the org-scoped approval's conversation tree
43
44
  const r = await sql `
44
45
  SELECT EXISTS (
45
46
  SELECT 1 FROM capybara.conversation_events
@@ -111,6 +111,7 @@ let PromptSuggestionStore = class PromptSuggestionStore {
111
111
  return false;
112
112
  if (latest.status !== "completed")
113
113
  return false;
114
+ // org-filter: conversationId was resolved in its org by the caller or job
114
115
  const newer = await db
115
116
  .selectFrom("conversation_events")
116
117
  .select(sql `1`.as("one"))
@@ -75,6 +75,7 @@ const UNBILLED_KINDS = new Set([
75
75
  /** The usage event's idempotency key: one suggestion usage per run. */
76
76
  const usageIdemKey = (runId) => `usage_suggestion:${runId}`;
77
77
  /** Whether the run's suggestion usage event exists (its call was made: a rerun is a no-op). */
78
+ // org-filter: conversationId is the finished run's conversation, scoped to its org by the job
78
79
  async function suggestionUsageExists(db, conversationId, runId) {
79
80
  const row = await db
80
81
  .selectFrom("conversation_events")
@@ -226,6 +226,7 @@ export async function pauseQueueWith(t, conversationId, reason) {
226
226
  .execute();
227
227
  }
228
228
  /** Whether a user_message with this client id is already in the log (inside `t`). */
229
+ // org-filter: the caller locked this conversation row in its own (org-checked or kernel) path
229
230
  export async function alreadySent(t, conversationId, clientMessageId) {
230
231
  const row = await t
231
232
  .selectFrom("conversation_events")
@@ -57,6 +57,7 @@ export function effectiveDefinition(def, sel) {
57
57
  * The selection from the log: the latest `model_switched` (before `beforeSeq` when given). Pass a
58
58
  * transaction that holds the conversation row lock to read it consistently with an append.
59
59
  */
60
+ // org-filter: callers resolve and lock conversationId in its org before reading its selection
60
61
  export async function readSelection(db, conversationId, beforeSeq) {
61
62
  let q = db
62
63
  .selectFrom("conversation_events")
@@ -123,6 +123,7 @@ const typedText = (content) => {
123
123
  return first?.type === "text" ? first.text : "";
124
124
  };
125
125
  /** The attempt number to enqueue for this conversation, or null when no title job is due. */
126
+ // org-filter: EXISTS subquery is correlated to conversations filtered by c.org_id = orgId
126
127
  export async function titleAttemptDue(db, orgId, conversationId) {
127
128
  const row = await db
128
129
  .selectFrom("conversations as c")