@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
@@ -89,6 +89,7 @@ let IdleReturn = class IdleReturn {
89
89
  if (now - finishedAt <= IDLE_RETURN_GAP_MS)
90
90
  return;
91
91
  // the previous run's last step usage (a side call's usage carries a `purpose`)
92
+ // org-filter: conv is the claimed run's conversation in its org scope
92
93
  const usageRow = await t
93
94
  .selectFrom("conversation_events")
94
95
  .select("payload")
@@ -102,6 +103,7 @@ let IdleReturn = class IdleReturn {
102
103
  const usage = usageRow?.payload;
103
104
  let lastCall = null;
104
105
  if (usage !== undefined) {
106
+ // org-filter: conv is the claimed run's conversation in its org scope
105
107
  const call = await t
106
108
  .selectFrom("conversation_events")
107
109
  .select("payload")
@@ -137,6 +139,7 @@ let IdleReturn = class IdleReturn {
137
139
  });
138
140
  if (facts === null)
139
141
  return;
142
+ // org-filter: conv is the claimed run's conversation in its org scope
140
143
  const summary = await t
141
144
  .selectFrom("conversation_events as e")
142
145
  .innerJoin("runs as r", "r.id", "e.run_id")
@@ -3,6 +3,7 @@ import type { Job, Worker } from "bullmq";
3
3
  import { EventCoalescer } from "../automations/events/coalesce.js";
4
4
  import { TriggerDispatcher } from "../automations/events/dispatcher.js";
5
5
  import { AutomationFirer } from "../automations/fire.js";
6
+ import { EventOrgBackfillJob } from "../conversations/event-org-backfill.js";
6
7
  import { ConversationNoticeDelivery } from "../device-access/conversation-notice-delivery.js";
7
8
  import { BlobObjects } from "../files/blob-objects.js";
8
9
  import { FileLibraryHashJob } from "../files/hash-job.js";
@@ -62,7 +63,8 @@ export declare class MaintenanceProcessor extends WorkerHost<Worker> {
62
63
  private readonly idleCompaction;
63
64
  private readonly db;
64
65
  private readonly loopback;
65
- constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, automations: Pick<AutomationFirer, "fire" | "settle">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke" | "settleResumeProof">, blobObjects: Pick<BlobObjects, "deleteBlob" | "deleteStaging" | "releaseFile">, hashing: Pick<FileLibraryHashJob, "dispatch" | "runOrgBatch">, platformIcons: Pick<PlatformIconObjects, "deleteObject">, notices: Pick<ConversationNoticeDelivery, "attempt">, triggers: Pick<TriggerDispatcher, "dispatch">, coalescer: Pick<EventCoalescer, "flush">, idleCompaction: Pick<IdleCompactionJob, "fire">, db: KernelDb, loopback: Pick<LoopbackGrants, "refresh">);
66
+ private readonly eventOrgBackfill;
67
+ constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, automations: Pick<AutomationFirer, "fire" | "settle">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke" | "settleResumeProof">, blobObjects: Pick<BlobObjects, "deleteBlob" | "deleteStaging" | "releaseFile">, hashing: Pick<FileLibraryHashJob, "dispatch" | "runOrgBatch">, platformIcons: Pick<PlatformIconObjects, "deleteObject">, notices: Pick<ConversationNoticeDelivery, "attempt">, triggers: Pick<TriggerDispatcher, "dispatch">, coalescer: Pick<EventCoalescer, "flush">, idleCompaction: Pick<IdleCompactionJob, "fire">, db: KernelDb, loopback: Pick<LoopbackGrants, "refresh">, eventOrgBackfill: Pick<EventOrgBackfillJob, "runBatch">);
66
68
  process(job: Job, token?: string): Promise<void>;
67
69
  /** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
68
70
  start(): void;
@@ -16,6 +16,8 @@ import { AUTOMATION_COALESCE_JOB, AUTOMATION_FIRE_JOB, AUTOMATION_SETTLE_JOB, TR
16
16
  import { BackgroundModule } from "../background/background.module.js";
17
17
  import { BG_WAKE_JOB } from "../background/wake-rules.js";
18
18
  import { EventLogModule } from "../conversations/event-log.js";
19
+ import { EVENT_ORG_BACKFILL_JOB, EventOrgBackfillJob, } from "../conversations/event-org-backfill.js";
20
+ import { EventOrgBackfillModule } from "../conversations/event-org-backfill.module.js";
19
21
  import { resolveConversationOrg, resolveRunOrg } from "../conversations/job-org.js";
20
22
  import { ConversationNoticeDelivery, ConversationNoticesModule, NOTICE_PROMPT_TIMEOUT_MS, } from "../device-access/conversation-notice-delivery.js";
21
23
  import { CONVERSATION_NOTICE_JOB, } from "../device-access/conversation-notices.js";
@@ -95,7 +97,8 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
95
97
  idleCompaction;
96
98
  db;
97
99
  loopback;
98
- constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, automations, scheduled, log, operations, blobObjects, hashing, platformIcons, notices, triggers, coalescer, idleCompaction, db, loopback) {
100
+ eventOrgBackfill;
101
+ constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, automations, scheduled, log, operations, blobObjects, hashing, platformIcons, notices, triggers, coalescer, idleCompaction, db, loopback, eventOrgBackfill) {
99
102
  super();
100
103
  this.permissionApprovals = permissionApprovals;
101
104
  this.waits = waits;
@@ -118,6 +121,7 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
118
121
  this.idleCompaction = idleCompaction;
119
122
  this.db = db;
120
123
  this.loopback = loopback;
124
+ this.eventOrgBackfill = eventOrgBackfill;
121
125
  }
122
126
  process(job, token) {
123
127
  return runJob(MAINTENANCE_QUEUE_NAME, job, () => this.dispatch(job, token), {
@@ -134,7 +138,7 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
134
138
  this.log.warn("maintenance job owner not found; skipped", { name: job.name, jobId: job.id });
135
139
  return;
136
140
  }
137
- await withOrgScope(orgId, handle);
141
+ await withOrgScope(orgId, () => handle(orgId));
138
142
  }
139
143
  async waitOwner({ kind, id, runId }) {
140
144
  if (kind === "subagents")
@@ -292,8 +296,14 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
292
296
  await this.loopback.refresh(job.data, AbortSignal.timeout(LOOPBACK_REFRESH_TIMEOUT_MS));
293
297
  return;
294
298
  // a large idle conversation's compaction before its prompt cache expires (idle compaction §4.3)
295
- case IDLE_COMPACTION_JOB:
296
- await this.idleCompaction.fire(job.data);
299
+ case IDLE_COMPACTION_JOB: {
300
+ const data = job.data;
301
+ await this.inOwnerScope(job, resolveRunOrg(this.db.db, data.runId, data.conversationId), (orgId) => this.idleCompaction.fire({ ...data, orgId }));
302
+ return;
303
+ }
304
+ // batched backfill of conversation_events.org_id from conversations (issue #1175)
305
+ case EVENT_ORG_BACKFILL_JOB:
306
+ await this.eventOrgBackfill.runBatch((job.data ?? { after: null }));
297
307
  return;
298
308
  default:
299
309
  if (await this.scheduled.runNow(job.name))
@@ -339,7 +349,8 @@ MaintenanceProcessor = __decorate([
339
349
  __param(17, Inject(EventCoalescer)),
340
350
  __param(18, Inject(IdleCompactionJob)),
341
351
  __param(19, Inject(KernelDb)),
342
- __param(20, Inject(LoopbackGrants))
352
+ __param(20, Inject(LoopbackGrants)),
353
+ __param(21, Inject(EventOrgBackfillJob))
343
354
  ], MaintenanceProcessor);
344
355
  export { MaintenanceProcessor };
345
356
  /**
@@ -370,6 +381,8 @@ MaintenanceModule = __decorate([
370
381
  BlobObjectsModule,
371
382
  // the file library's hashing
372
383
  FileLibraryJobsModule,
384
+ // batched conversation_events.org_id backfill
385
+ EventOrgBackfillModule,
373
386
  // the platform icon object deletion
374
387
  PlatformIconObjectsModule,
375
388
  // a deleted conversation's notice to its device's services
@@ -233,6 +233,7 @@ let PermissionContextRecorder = class PermissionContextRecorder {
233
233
  if (payload.rootConversationId !== subject.rootConversationId)
234
234
  throw new PermissionContextSubjectChanged();
235
235
  // the persisted log decides: the latest snapshot of this conversation, under its row lock
236
+ // org-filter: input.conversationId was verified in input.orgId by readRoot above
236
237
  const latest = await this.db
237
238
  .selectFrom("conversation_events")
238
239
  .select(["seq", "payload"])
@@ -165,6 +165,7 @@ let PluginContextService = class PluginContextService {
165
165
  .executeTakeFirst();
166
166
  if (await runEndedIn(t, input.runId))
167
167
  return "ended";
168
+ // org-filter: conversation row was locked with org_id = input.orgId above
168
169
  const rows = await t
169
170
  .selectFrom("conversation_events")
170
171
  .select(["seq", "payload"])
@@ -145,6 +145,7 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
145
145
  const rootId = input.rootConversationId;
146
146
  if (rootId === undefined || rootId === input.conversationId)
147
147
  return true;
148
+ // org-filter: rootId is the claimed sub-agent run's root conversation in input.orgId
148
149
  const latest = await this.db.db
149
150
  .selectFrom("conversation_events")
150
151
  .select("payload")
@@ -320,6 +321,7 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
320
321
  .executeTakeFirst();
321
322
  if (await runEndedIn(t, input.runId))
322
323
  return "ended";
324
+ // org-filter: conversation row was locked with org_id = input.orgId above
323
325
  const latest = await t
324
326
  .selectFrom("conversation_events")
325
327
  .select(["seq", "payload"])
@@ -114,6 +114,7 @@ let RunContextService = class RunContextService {
114
114
  // wake run has no message of its own). Messages record the zone and language used at send time
115
115
  // (IM-provided, account, browser, web language, org: message-context.ts); without a message,
116
116
  // the org's (§3.4).
117
+ // org-filter: input.conversationId is the claimed run's conversation in input.orgId
117
118
  const person = await t
118
119
  .selectFrom("conversation_events")
119
120
  .select([
@@ -191,6 +192,7 @@ export { RunContextService };
191
192
  * builtin's default zone.
192
193
  */
193
194
  export async function conversationTimeZone(t, orgId, conversationId) {
195
+ // org-filter: conversationId belongs to orgId (caller's running tool context)
194
196
  const row = await t
195
197
  .selectFrom("conversation_events")
196
198
  .select(sql `payload->>'timeZone'`.as("timeZone"))
@@ -206,6 +208,7 @@ export async function conversationTimeZone(t, orgId, conversationId) {
206
208
  return zone !== undefined && isTimeZone(zone) ? zone : "UTC";
207
209
  }
208
210
  /** The fold of a conversation's `run_context` events (read inside the caller's transaction). */
211
+ // org-filter: callers locked and verified conversationId in its org
209
212
  async function foldOf(t, conversationId) {
210
213
  const rows = await t
211
214
  .selectFrom("conversation_events")
@@ -230,6 +233,7 @@ async function parentDefinitionName(t, runId) {
230
233
  return row?.name ?? undefined;
231
234
  }
232
235
  /** The latest sender name in a conversation's log (the person the conversation works for). */
236
+ // org-filter: conversationId is the parent of a claimed sub-agent run in the same org
233
237
  async function latestSenderName(t, conversationId) {
234
238
  const row = await t
235
239
  .selectFrom("conversation_events")
@@ -17,6 +17,7 @@ export declare class RunDeletion {
17
17
  private readonly background;
18
18
  constructor(db: KernelDb, txHost: TransactionHost, outbox: OutboxService, finisher: RunFinish, background: BackgroundTaskStopper);
19
19
  stopOrg(data: StopDeletedOrgData): Promise<void>;
20
+ private stopOrgIn;
20
21
  /**
21
22
  * One page of the org's conversations that still have live work: an active run (queued, running
22
23
  * or waiting on an open wait) or a running background task (owned by its sandbox root). Idle
@@ -12,6 +12,7 @@ import { BackgroundTaskStopper } from "../background/stop.js";
12
12
  import { RUNNING_TASK_STATUS } from "../background/store.js";
13
13
  import { conversationTree } from "../conversations/tree.js";
14
14
  import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { withOrgScope } from "../infra/database/org-scope.js";
15
16
  import { TransactionHost } from "../infra/database/transaction-host.js";
16
17
  import { Transactional } from "../infra/database/transactional.decorator.js";
17
18
  import { OutboxService } from "../infra/outbox/outbox.service.js";
@@ -37,16 +38,19 @@ let RunDeletion = class RunDeletion {
37
38
  async stopOrg(data) {
38
39
  const org = await this.db
39
40
  .selectFrom("orgs")
40
- .select("deleted_at")
41
+ .select(["id", "deleted_at"])
41
42
  .where("id", "=", data.orgId)
42
43
  .executeTakeFirst();
43
44
  if (!org || isLive(org.deleted_at))
44
45
  return;
46
+ await withOrgScope(org.id, () => this.stopOrgIn(org.id, data.byAccountId));
47
+ }
48
+ async stopOrgIn(orgId, byAccountId) {
45
49
  let after = "";
46
50
  for (;;) {
47
- const rows = await this.liveConversationsIn(data.orgId, after);
51
+ const rows = await this.liveConversationsIn(orgId, after);
48
52
  for (const row of rows) {
49
- await this.stopConversationIn(row.id, data.byAccountId, "org_deleted");
53
+ await this.stopConversationIn(row.id, byAccountId, "org_deleted");
50
54
  await this.background.stopForDeletedConversation(row.id);
51
55
  }
52
56
  if (rows.length < 100)
@@ -565,6 +565,7 @@ let RunQueue = class RunQueue {
565
565
  * finished background task or delivery outside its wake window. Reads only: a wake inside its
566
566
  * window owes nothing here (the idle run's finish re-derives it).
567
567
  */
568
+ // org-filter: callers locked conversationId and resolved its org_id into conv
568
569
  async inputPendingIn(conversationId, conv) {
569
570
  const t = this.db;
570
571
  const message = await t
@@ -598,6 +599,7 @@ let RunQueue = class RunQueue {
598
599
  * worker that read it as queued re-checks it under the row locks before its `run_started`
599
600
  * ({@link abortQueuedIn}'s rule).
600
601
  */
602
+ // org-filter: called under the conversation row lock from ensureRunIn
601
603
  async endQueuedIdleIn(conversationId, active, st) {
602
604
  if (active.status !== "queued")
603
605
  return false;
@@ -758,6 +760,7 @@ let RunQueue = class RunQueue {
758
760
  * `aborted`): a message that reached it while running and then stopped is parked, and the next
759
761
  * run its parent starts absorbs it. Called under the sub-agent's row lock.
760
762
  */
763
+ // org-filter: called under the sub-agent conversation row lock in orgId
761
764
  async pendingMessageIn(conversationId, consumed, rootId, orgId) {
762
765
  const t = this.db;
763
766
  const message = await t
@@ -1202,6 +1202,7 @@ let RunWorker = class RunWorker {
1202
1202
  : current;
1203
1203
  // a wake run's boundary is a finished background task (background Bash §3) or a sub-agent's
1204
1204
  // delivery (agent map spec §5.3), not a message
1205
+ // org-filter: conversationId is the claimed run's conversation under its row lock
1205
1206
  const boundary = await t
1206
1207
  .selectFrom("conversation_events")
1207
1208
  .select(["type", "payload"])
@@ -13,6 +13,7 @@ import { CONVERSATION_CHANGES, conversationTopic, EventLog, } from "../conversat
13
13
  import { PROMPT_SUGGESTION_BUS_KIND, PromptSuggestionStore, } from "../conversations/prompt-suggestion-store.js";
14
14
  import { ApiError } from "../errors.js";
15
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
+ import { withOrgScope } from "../infra/database/org-scope.js";
16
17
  import { GracefulShutdown } from "../infra/lifecycle/graceful-shutdown.service.js";
17
18
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
18
19
  import { OrgSettingsService } from "../orgs/settings.service.js";
@@ -307,10 +308,10 @@ class Connection {
307
308
  }
308
309
  enqueue(fn) {
309
310
  this.chain = this.chain
310
- .then(async () => {
311
+ .then(() => withOrgScope(this.p.orgId, async () => {
311
312
  if (!this.closed)
312
313
  await fn();
313
- })
314
+ }))
314
315
  .catch((err) => {
315
316
  this.d.log.warn("conversation stream failed; closing", {
316
317
  conversationId: this.p.conversationId,
@@ -414,7 +415,7 @@ class Connection {
414
415
  return;
415
416
  this.rechecking = true;
416
417
  try {
417
- const denied = await authorize(this.d, this.p);
418
+ const denied = await withOrgScope(this.p.orgId, () => authorize(this.d, this.p));
418
419
  if (denied !== null)
419
420
  this.fail(denied);
420
421
  else {
@@ -201,6 +201,7 @@ let SubagentDeliveries = class SubagentDeliveries {
201
201
  return true;
202
202
  }
203
203
  /** Whether the child run handed back a report (`SubagentHandback`) before it finished. */
204
+ // org-filter: row is a kernel-written dispatch row processed inside its org scope
204
205
  async handedBack(row) {
205
206
  const hit = await this.db
206
207
  .selectFrom("conversation_events")
@@ -245,6 +245,7 @@ const isActiveStatus = (status) => ACTIVE_RUN_STATUSES.includes(status);
245
245
  * key), so the `deliver-to-parent` job never delivers it a second time. Null when the parent already
246
246
  * has a delivery for the run (it carries the result) or the run has no terminal event yet.
247
247
  */
248
+ // org-filter: row is a kernel-written dispatch row for the caller's org-scoped parent conversation
248
249
  async function rcFinishedResult(d, row) {
249
250
  const delivered = await d.db
250
251
  .selectFrom("conversation_events")
@@ -12,6 +12,7 @@ import { conversationAncestors } from "../../conversations/tree.js";
12
12
  */
13
13
  export async function publishSubagentProgress(d, s) {
14
14
  try {
15
+ // org-filter: s.conversationId and s.runId come from the claimed sub-agent run in its org scope
15
16
  const { rows } = await sql `
16
17
  SELECT count(*) AS n,
17
18
  (array_agg(e.payload->>'toolKey' ORDER BY e.seq DESC))[1] AS last
@@ -213,6 +213,7 @@ t, eventLog, runId) {
213
213
  return none;
214
214
  const conversationId = run.conversation_id;
215
215
  const seq = Number(run.trigger_seq);
216
+ // org-filter: conversationId comes from the kernel-resolved stopping run in its org scope
216
217
  const trigger = await t
217
218
  .selectFrom("conversation_events")
218
219
  .select(["type", "payload"])
@@ -224,6 +225,7 @@ t, eventLog, runId) {
224
225
  : undefined;
225
226
  if (skill?.mode !== "fork")
226
227
  return none;
228
+ // org-filter: conversationId comes from the kernel-resolved stopping run in its org scope
227
229
  const written = await t
228
230
  .selectFrom("conversation_events")
229
231
  .select("seq")
@@ -324,6 +324,7 @@ let UsageReporter = class UsageReporter {
324
324
  }
325
325
  }
326
326
  /** The payload of one usage event, read from the log; null when the event no longer exists. */
327
+ // org-filter: called inside withOrgScope(orgId) after resolveConversationOrg for the usage job
327
328
  async payloadOf(conversationId, seq) {
328
329
  const row = await this.db
329
330
  .selectFrom("conversation_events as e")
@@ -173,7 +173,7 @@ export declare class Waits implements OnApplicationShutdown {
173
173
  * or cancelled); `subagents`: the run's fork invocation child is no longer active.
174
174
  */
175
175
  private isSettled;
176
- /** 审批所在的步(`approval_requested` 事件里记的)。 */
176
+ /** Step recorded on the approval's `approval_requested` event. */
177
177
  private approvalStep;
178
178
  /**
179
179
  * 等待中被中止的运行:这些步里每个调用都补一条 `tool_result`(已有结果的按幂等键命中、不重复),
@@ -489,7 +489,8 @@ let Waits = class Waits {
489
489
  .executeTakeFirst();
490
490
  return row !== undefined && row.status !== "pending";
491
491
  }
492
- /** 审批所在的步(`approval_requested` 事件里记的)。 */
492
+ /** Step recorded on the approval's `approval_requested` event. */
493
+ // org-filter: conversationId is the run's conversation verified in its org by the wait caller
493
494
  async approvalStep(t, conversationId, approvalId) {
494
495
  const ev = await t
495
496
  .selectFrom("conversation_events")
@@ -504,6 +505,7 @@ let Waits = class Waits {
504
505
  * 等待中被中止的运行:这些步里每个调用都补一条 `tool_result`(已有结果的按幂等键命中、不重复),
505
506
  * 等待中的调用给取消说明,其余(排在等待调用之后、尚未执行的)给「未执行」说明。
506
507
  */
508
+ // org-filter: conversationId is the stopping run's conversation verified in its org
507
509
  async stoppedResults(t, conversationId, runId, steps, cancelled,
508
510
  /** Calls whose result the caller writes itself (open `Agent` calls). */
509
511
  skip = new Set()) {
@@ -331,6 +331,7 @@ let ManagedDeviceContextRecorder = class ManagedDeviceContextRecorder {
331
331
  workingRoot: held.workingRoot,
332
332
  });
333
333
  // the persisted log decides (old to marked appends even for identical roots; A to B to A too)
334
+ // org-filter: input.conversationId was verified in input.orgId under the run fence
334
335
  const latest = await this.db
335
336
  .selectFrom("conversation_events")
336
337
  .select(["seq", "payload"])
@@ -213,6 +213,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
213
213
  }
214
214
  async previewLocked(ctx, call, signal, crossing) {
215
215
  const snapshot = await this.snapshot(ctx, call, signal, undefined, crossing === undefined ? {} : { crossing });
216
+ // org-filter: snapshot verified ctx.holderConversationId in ctx.orgId above
216
217
  const messages = await this.db
217
218
  .selectFrom("conversation_events")
218
219
  .select("payload")
@@ -239,6 +240,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
239
240
  const f = await this.snapshot(ctx, call, signal, (grant) => {
240
241
  networkGrant = grant;
241
242
  });
243
+ // org-filter: snapshot verified ctx.holderConversationId in ctx.orgId above
242
244
  const started = await this.db
243
245
  .selectFrom("conversation_events")
244
246
  .select("payload")
@@ -148,6 +148,7 @@ let SandboxOperationIntents = class SandboxOperationIntents {
148
148
  run.trigger_account_id !== ctx.actor.accountId ||
149
149
  run.status !== "running")
150
150
  denied("The tool execution claim is no longer current");
151
+ // org-filter: c.conversationId is the fenced run's conversation in ctx.orgId
151
152
  const call = await this.db
152
153
  .selectFrom("conversation_events")
153
154
  .select("seq")
@@ -97,6 +97,7 @@ let PermissionCallGrants = class PermissionCallGrants {
97
97
  permissionScopeHash({ scopeRevision: view.scopeRevision, vector }) !==
98
98
  binding.authorityRevision)
99
99
  throw new ApiError("conflict", "Permissions changed or the call is unattended; review the current call again");
100
+ // org-filter: binding.conversationId was verified in binding.orgId under the run fence
100
101
  const messages = await this.db
101
102
  .selectFrom("conversation_events")
102
103
  .select("payload")
@@ -299,6 +300,7 @@ let PermissionCallGrants = class PermissionCallGrants {
299
300
  evidence = approval.detail?.permissionCandidate;
300
301
  }
301
302
  else {
303
+ // org-filter: b.conversationId was verified in b.orgId under the permission grant lock
302
304
  const event = await this.db
303
305
  .selectFrom("conversation_events")
304
306
  .selectAll()
@@ -358,6 +358,7 @@ let PermissionFacts = class PermissionFacts {
358
358
  .executeTakeFirst();
359
359
  if (conv?.project_path == null)
360
360
  return null;
361
+ // org-filter: rootConversationId was verified in orgId above
361
362
  const row = await this.db
362
363
  .selectFrom("conversation_events")
363
364
  .select([
@@ -376,6 +377,7 @@ let PermissionFacts = class PermissionFacts {
376
377
  return { root: row.root, unavailable: row.unavailable !== false };
377
378
  }
378
379
  /** The workspace root of a conversation's latest `device_paths` event, or null. */
380
+ // org-filter: callers verified conversationId in orgId before reading device paths
379
381
  async recordedWorkspace(conversationId) {
380
382
  const row = await this.db
381
383
  .selectFrom("conversation_events")
@@ -353,6 +353,7 @@ function textOfUserMessage(payload) {
353
353
  * bounded to `budget` estimated tokens (`sandbox.review.messageTokens`). The command review and the
354
354
  * tool review read the same messages.
355
355
  */
356
+ // org-filter: rootConversationId was resolved in its org by the review caller
356
357
  export async function readPersonMessages(db, rootConversationId, budget) {
357
358
  const rows = await db
358
359
  .selectFrom("conversation_events")
@@ -666,6 +666,7 @@ let CommandReviewService = class CommandReviewService {
666
666
  * whoever runs it (hardening spec R1).
667
667
  */
668
668
  async writtenInTree(orgId, rootConversationId, facts) {
669
+ // org-filter: tree CTE filters conversations by org_id = orgId
669
670
  const rows = await this.db
670
671
  .withRecursive("tree(id)", (db) => db
671
672
  .selectFrom("conversations")
@@ -203,6 +203,7 @@ projectSkills = false) {
203
203
  /** Whether `events` hold a person's skill invocation (a `user_message` with `skill`). */
204
204
  export const hasInvocation = (events) => events.some((e) => e.type === "user_message" && e.payload.skill !== undefined);
205
205
  /** {@link skillLoadOffered} for a conversation, read from the database. */
206
+ // org-filter: conversationId is the running conversation in its org scope
206
207
  export async function skillLoadOfferedIn(db, eventLog, conversationId) {
207
208
  if (await eventLog.latestOfType(conversationId, "skills_catalog"))
208
209
  return true;
@@ -108,6 +108,7 @@ export function projectSkillBlocked(p, name) {
108
108
  return projectInvocables(p).some((s) => s.name === name) ? null : "not_found";
109
109
  }
110
110
  /** The payload of the conversation's latest `project_root`, read with `db`. */
111
+ // org-filter: callers verified conversationId in orgId before calling
111
112
  async function latestProjectRoot(db, conversationId) {
112
113
  const row = await db
113
114
  .selectFrom("conversation_events")
@@ -128,6 +129,7 @@ const KNOWN_SNAPSHOT_CONVERSATIONS = 20;
128
129
  * that project; the device is never asked. Undefined when none is known.
129
130
  */
130
131
  export async function latestKnownProjectRoot(db, a) {
132
+ // org-filter: lateral subquery correlates to conversations filtered by c.org_id = a.orgId
131
133
  const rows = await db
132
134
  .selectFrom("conversations as c")
133
135
  .innerJoinLateral((eb) => eb
@@ -90,7 +90,7 @@ let AdminConnectors = class AdminConnectors {
90
90
  throw notFound();
91
91
  const tools = await this.db
92
92
  .selectFrom("connector_tools")
93
- .select(["name", "spec", "status", "default_policy", "declaration_policy"])
93
+ .select(["name", "spec", "status", "default_policy"])
94
94
  .where("connector_id", "=", connectorId)
95
95
  .orderBy("name")
96
96
  .execute();
@@ -105,7 +105,7 @@ let AdminConnectors = class AdminConnectors {
105
105
  name: t.name,
106
106
  title: typeof title === "string" ? title : null,
107
107
  status: t.status,
108
- defaultPolicy: t.declaration_policy ?? t.default_policy,
108
+ defaultPolicy: t.default_policy,
109
109
  };
110
110
  }),
111
111
  };
@@ -282,6 +282,7 @@ export { BuiltinTools };
282
282
  export async function chatModelSeesImages(db, providers, ctx) {
283
283
  if (ctx.runId === undefined)
284
284
  return false;
285
+ // org-filter: ctx.conversationId is the running tool call's conversation in ctx.orgId
285
286
  const row = await db.db
286
287
  .selectFrom("conversation_events")
287
288
  .select("payload")
@@ -340,6 +340,7 @@ async function invocationScope(db, ctx) {
340
340
  */
341
341
  async function invokedEntry(db, ctx, name) {
342
342
  // only the `skill` field: a message's content holds the rendered skill (up to 200k characters)
343
+ // org-filter: ctx.conversationId is the running tool call's conversation in ctx.orgId
343
344
  const rows = await db
344
345
  .selectFrom("conversation_events")
345
346
  .select(["seq", sql `payload -> 'skill'`.as("skill")])
@@ -383,6 +384,7 @@ async function invokedEntry(db, ctx, name) {
383
384
  * does not cover or re-renders as an opening message. `Skill` then copies the files and names
384
385
  * their directory without repeating the instructions. Read from the log, so a replay agrees.
385
386
  */
387
+ // org-filter: conversationId is the running Skill tool call's conversation in its org scope
386
388
  async function invokedInContext(db, conversationId, entry, args) {
387
389
  // only the `skill` field: a message's content holds the rendered skill (up to 200k characters)
388
390
  const rows = await db
@@ -61,7 +61,7 @@ let ConnectorAccountPolicies = class ConnectorAccountPolicies {
61
61
  const c = await this.connector(orgId, connectorId);
62
62
  const tools = await this.db
63
63
  .selectFrom("connector_tools")
64
- .select(["name", "spec", "status", "default_policy", "declaration_policy", "missing_since"])
64
+ .select(["name", "spec", "status", "default_policy", "missing_since"])
65
65
  .where("connector_id", "=", connectorId)
66
66
  .orderBy("name")
67
67
  .execute();
@@ -78,7 +78,7 @@ let ConnectorAccountPolicies = class ConnectorAccountPolicies {
78
78
  const key = connectorToolKey(c.slug, t.name);
79
79
  const locked = t.status !== "enabled" || t.missing_since !== null
80
80
  ? "disabled"
81
- : (t.declaration_policy ?? t.default_policy) === "deny" || orgRules.get(key) === "deny"
81
+ : t.default_policy === "deny" || orgRules.get(key) === "deny"
82
82
  ? "org_deny"
83
83
  : null;
84
84
  return {
@@ -86,7 +86,7 @@ let ConnectorAccountPolicies = class ConnectorAccountPolicies {
86
86
  key,
87
87
  title: typeof spec.title === "string" ? spec.title : null,
88
88
  description: spec.description,
89
- defaultPolicy: t.declaration_policy ?? t.default_policy,
89
+ defaultPolicy: t.default_policy,
90
90
  annotationPolicy: policyFromAnnotations(spec.annotations),
91
91
  policy: mine.get(t.name) ?? null,
92
92
  locked,