@capybara-hq/kernel 0.1.0-rc.123 → 0.1.0-rc.124

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/bootstrap.json +31 -31
  2. package/dist/admin/admin.controller.d.ts +2 -2
  3. package/dist/admin/admin.controller.js +1 -1
  4. package/dist/admin/health.service.js +5 -5
  5. package/dist/admin/overview.service.d.ts +2 -2
  6. package/dist/admin/overview.service.js +1 -1
  7. package/dist/agents/agents.module.js +4 -0
  8. package/dist/agents/agents.schemas.js +1 -0
  9. package/dist/agents/models.controller.d.ts +2 -2
  10. package/dist/agents/onboarding-checklist.d.ts +30 -0
  11. package/dist/agents/onboarding-checklist.js +176 -0
  12. package/dist/agents/readiness.controller.d.ts +1 -0
  13. package/dist/agents/readiness.controller.js +12 -2
  14. package/dist/agents/readiness.service.d.ts +5 -2
  15. package/dist/agents/readiness.service.js +14 -3
  16. package/dist/automations/automations.service.js +7 -21
  17. package/dist/automations/events/acceptance.d.ts +2 -0
  18. package/dist/automations/events/acceptance.js +14 -3
  19. package/dist/automations/events/sweep.job.d.ts +3 -36
  20. package/dist/automations/events/sweep.job.js +5 -127
  21. package/dist/automations/fire.d.ts +3 -0
  22. package/dist/automations/fire.js +18 -1
  23. package/dist/automations/grant-rules.d.ts +0 -14
  24. package/dist/automations/grant-rules.js +0 -18
  25. package/dist/automations/scan.job.js +22 -16
  26. package/dist/catalog/catalog.module.d.ts +4 -7
  27. package/dist/catalog/catalog.module.js +4 -10
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/catalog/plugin-import.js +2 -1
  30. package/dist/catalog/plugin-install.d.ts +2 -2
  31. package/dist/catalog/plugin-install.js +2 -2
  32. package/dist/catalog/template-connector-ensure.d.ts +4 -7
  33. package/dist/catalog/template-connector-ensure.js +11 -15
  34. package/dist/channels/supervisor.js +34 -23
  35. package/dist/channels/webhook.d.ts +1 -0
  36. package/dist/channels/webhook.js +10 -5
  37. package/dist/conversations/job-org.d.ts +2 -0
  38. package/dist/conversations/job-org.js +12 -0
  39. package/dist/ctx/create-ctx.js +2 -1
  40. package/dist/db/kernel-schema.d.ts +1 -0
  41. package/dist/dial-in/auth.controller.js +3 -2
  42. package/dist/dial-in/auth.service.js +3 -2
  43. package/dist/dial-in/gateway.d.ts +0 -1
  44. package/dist/dial-in/gateway.js +6 -9
  45. package/dist/extensions/host.d.ts +2 -2
  46. package/dist/extensions/host.js +22 -13
  47. package/dist/extensions/installs.d.ts +1 -0
  48. package/dist/extensions/installs.js +2 -0
  49. package/dist/html/html-document.controller.js +3 -0
  50. package/dist/html/html-document.service.js +2 -0
  51. package/dist/http/plugin-route-access.js +7 -2
  52. package/dist/identity/account-avatar.controller.js +4 -2
  53. package/dist/identity/accounts.js +19 -32
  54. package/dist/identity/api-tokens.d.ts +2 -0
  55. package/dist/identity/api-tokens.js +14 -10
  56. package/dist/identity/audit.js +10 -5
  57. package/dist/identity/binding.d.ts +1 -1
  58. package/dist/identity/binding.js +19 -10
  59. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -8
  60. package/dist/lifecycle/kernel-lifecycle.js +11 -37
  61. package/dist/models/purposes.d.ts +24 -3
  62. package/dist/models/purposes.js +131 -14
  63. package/dist/orgs/directory-sync.js +6 -4
  64. package/dist/orgs/roles.d.ts +1 -1
  65. package/dist/orgs/roles.js +1 -0
  66. package/dist/platform/exclusions.js +5 -0
  67. package/dist/platform/ops/admin.ops.js +1 -1
  68. package/dist/platform/ops/agents.ops.js +1 -1
  69. package/dist/platform/ops/models.ops.js +3 -3
  70. package/dist/push/fanout.d.ts +1 -0
  71. package/dist/push/fanout.js +11 -4
  72. package/dist/push/recipients.d.ts +3 -1
  73. package/dist/push/recipients.js +29 -22
  74. package/dist/runtime/maintenance.d.ts +5 -1
  75. package/dist/runtime/maintenance.js +50 -11
  76. package/dist/runtime/providers.d.ts +12 -9
  77. package/dist/runtime/providers.js +2 -23
  78. package/dist/runtime/run-orphan-check.job.d.ts +1 -0
  79. package/dist/runtime/run-orphan-check.job.js +23 -21
  80. package/dist/runtime/usage-report.d.ts +2 -1
  81. package/dist/runtime/usage-report.js +26 -4
  82. package/dist/sandbox/providers.d.ts +2 -0
  83. package/dist/sandbox/providers.js +2 -0
  84. package/dist/shares/liveness.d.ts +3 -2
  85. package/dist/shares/liveness.js +26 -11
  86. package/dist/shares/share-open.service.js +2 -0
  87. package/dist/skills/usable.d.ts +2 -0
  88. package/dist/skills/usable.js +56 -0
  89. package/dist/tools/builtins/platform.js +17 -12
  90. package/dist/tools/connector-setup.d.ts +5 -1
  91. package/dist/tools/connector-setup.js +14 -0
  92. package/dist/tools/credentials.d.ts +5 -0
  93. package/dist/tools/credentials.js +10 -0
  94. package/dist/tools/oauth/flow.d.ts +1 -0
  95. package/dist/tools/oauth/flow.js +8 -3
  96. package/dist/tools/registry.d.ts +2 -0
  97. package/dist/tools/registry.js +6 -0
  98. package/package.json +3 -3
  99. package/src/migrations/0209_onboarding_checklist.sql +5 -0
  100. package/dist/catalog/template-connector-reconcile.d.ts +0 -44
  101. package/dist/catalog/template-connector-reconcile.js +0 -114
@@ -16,11 +16,14 @@ 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 { resolveConversationOrg, resolveRunOrg } from "../conversations/job-org.js";
19
20
  import { ConversationNoticeDelivery, ConversationNoticesModule, NOTICE_PROMPT_TIMEOUT_MS, } from "../device-access/conversation-notice-delivery.js";
20
21
  import { CONVERSATION_NOTICE_JOB, } from "../device-access/conversation-notices.js";
21
22
  import { BLOB_DELETE_JOB, BlobObjects, BlobObjectsModule, FILE_RELEASE_JOB, FILE_STAGING_DELETE_JOB, } from "../files/blob-objects.js";
22
23
  import { FILE_LIBRARY_HASH_JOB, FILE_LIBRARY_HASH_ORG_JOB, FileLibraryHashJob, } from "../files/hash-job.js";
23
24
  import { FileLibraryJobsModule } from "../files/library-jobs.module.js";
25
+ import { KernelDb } from "../infra/database/kernel-db.js";
26
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
24
27
  import { configuredProcessor } from "../infra/queue/configured-processor.js";
25
28
  import { QueueModule } from "../infra/queue/queue.module.js";
26
29
  import { runJob } from "../infra/queue/run-job.js";
@@ -90,8 +93,9 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
90
93
  triggers;
91
94
  coalescer;
92
95
  idleCompaction;
96
+ db;
93
97
  loopback;
94
- constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, automations, scheduled, log, operations, blobObjects, hashing, platformIcons, notices, triggers, coalescer, idleCompaction, loopback) {
98
+ constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, automations, scheduled, log, operations, blobObjects, hashing, platformIcons, notices, triggers, coalescer, idleCompaction, db, loopback) {
95
99
  super();
96
100
  this.permissionApprovals = permissionApprovals;
97
101
  this.waits = waits;
@@ -112,6 +116,7 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
112
116
  this.triggers = triggers;
113
117
  this.coalescer = coalescer;
114
118
  this.idleCompaction = idleCompaction;
119
+ this.db = db;
115
120
  this.loopback = loopback;
116
121
  }
117
122
  process(job, token) {
@@ -123,6 +128,25 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
123
128
  start() {
124
129
  void this.worker.run().catch((err) => this.error(err));
125
130
  }
131
+ async inOwnerScope(job, lookup, handle) {
132
+ const orgId = await lookup;
133
+ if (orgId === undefined) {
134
+ this.log.warn("maintenance job owner not found; skipped", { name: job.name, jobId: job.id });
135
+ return;
136
+ }
137
+ await withOrgScope(orgId, handle);
138
+ }
139
+ async waitOwner({ kind, id, runId }) {
140
+ if (kind === "subagents")
141
+ return runId === undefined ? undefined : resolveRunOrg(this.db.db, runId);
142
+ // org-filter: deployment-wide lookup of the owner of a queued approval or question timeout
143
+ const row = await asPlatform("resolve the org of a queued wait timeout", () => this.db
144
+ .selectFrom(kind === "approval" ? "approvals" : "questions")
145
+ .select("org_id")
146
+ .where("id", "=", id)
147
+ .executeTakeFirst());
148
+ return row?.org_id;
149
+ }
126
150
  async dispatch(job, token) {
127
151
  switch (job.name) {
128
152
  case PERMISSION_APPROVAL_RECHECK:
@@ -149,7 +173,7 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
149
173
  await this.deletion.stopOrg(job.data);
150
174
  return;
151
175
  case WAIT_TIMEOUT_JOB:
152
- await this.waits.processTimeout(job, token);
176
+ await this.inOwnerScope(job, this.waitOwner(job.data), () => this.waits.processTimeout(job, token));
153
177
  return;
154
178
  case SANDBOX_DESTROY_FOR_JOB:
155
179
  await runSandboxDestroyFor(this.sandbox, this.log, job);
@@ -168,7 +192,12 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
168
192
  // a departed member's run stop, owed by the offboarding (transactional outbox spec §8.1)
169
193
  case RUN_STOP_JOB:
170
194
  try {
171
- await this.offboarding.stopRun(job.data);
195
+ const data = job.data;
196
+ // A deleted run may already be purged. Its cancellation is a Redis signal only.
197
+ if (data.deleted)
198
+ await this.offboarding.stopRun(data);
199
+ else
200
+ await this.inOwnerScope(job, resolveRunOrg(this.db.db, data.runId, data.conversationId), () => this.offboarding.stopRun(data));
172
201
  }
173
202
  catch (err) {
174
203
  // nothing stops the run after its last attempt: say so (the failed job is kept)
@@ -186,21 +215,30 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
186
215
  case BG_WAKE_JOB: {
187
216
  // fired before the window ended (clock skew): it reschedules under its next retry id
188
217
  const { conversationId, retry } = job.data;
189
- await this.runs.ensureRun(conversationId, { wakeRetry: (retry ?? 0) + 1 });
218
+ await this.inOwnerScope(job, resolveConversationOrg(this.db.db, conversationId), () => this.runs.ensureRun(conversationId, { wakeRetry: (retry ?? 0) + 1 }));
190
219
  return;
191
220
  }
192
221
  // the ensure-run backstop of a message, wake or run end (transactional outbox spec §6)
193
- case ENSURE_RUN_JOB:
194
- await this.runs.ensureRun(job.data.conversationId);
222
+ case ENSURE_RUN_JOB: {
223
+ const { conversationId } = job.data;
224
+ await this.inOwnerScope(job, resolveConversationOrg(this.db.db, conversationId), () => this.runs.ensureRun(conversationId));
195
225
  return;
226
+ }
196
227
  // the stops a run's end or a root's delete owes its sub-agent tree (outbox spec §6)
197
- case STOP_TREE_JOB:
198
- await processStopTree(this.waits, job.data, this.deletion);
228
+ case STOP_TREE_JOB: {
229
+ const data = job.data;
230
+ const owner = "runId" in data
231
+ ? resolveRunOrg(this.db.db, data.runId)
232
+ : resolveConversationOrg(this.db.db, data.conversationId);
233
+ await this.inOwnerScope(job, owner, () => processStopTree(this.waits, data, this.deletion));
199
234
  return;
235
+ }
200
236
  // a finished sub-agent run's delivery to its parent (transactional outbox spec §6)
201
- case DELIVER_TO_PARENT_JOB:
202
- await processDeliverToParent(this.waits, job.data);
237
+ case DELIVER_TO_PARENT_JOB: {
238
+ const data = job.data;
239
+ await this.inOwnerScope(job, resolveRunOrg(this.db.db, data.childRunId), () => processDeliverToParent(this.waits, data));
203
240
  return;
241
+ }
204
242
  // one task run of an automation (scheduled tasks spec §6)
205
243
  case AUTOMATION_FIRE_JOB:
206
244
  await this.automations.fire(job.data.taskRunId);
@@ -300,7 +338,8 @@ MaintenanceProcessor = __decorate([
300
338
  __param(16, Inject(TriggerDispatcher)),
301
339
  __param(17, Inject(EventCoalescer)),
302
340
  __param(18, Inject(IdleCompactionJob)),
303
- __param(19, Inject(LoopbackGrants))
341
+ __param(19, Inject(KernelDb)),
342
+ __param(20, Inject(LoopbackGrants))
304
343
  ], MaintenanceProcessor);
305
344
  export { MaintenanceProcessor };
306
345
  /**
@@ -103,17 +103,19 @@ export declare function supportsEmbedding(provider: BoundProvider): boolean;
103
103
  /** Authorizes all input texts before the caller splits them into provider batches. */
104
104
  export declare function prepareEmbedding(provider: BoundProvider, payload: EmbeddingRequestHookPayload, hooks: HookRunner | undefined, signal: AbortSignal): Promise<NonNullable<BoundProvider["embed"]>>;
105
105
  export declare function prepareImageGeneration(provider: BoundProvider, payload: () => ImageRequestHookPayload, hooks: HookRunner | undefined, signal: AbortSignal, ref: ModelRef): Promise<NonNullable<BoundProvider["generateImage"]>>;
106
+ export type PlatformProviderState = "ok" | "error" | "org_configured";
107
+ export type OrgProviderState = "ok" | "error" | "needs_config";
106
108
  /**
107
- * 一个供应商在后台的视图:供应商名即插件名;`status: "error"` 时 `models` 为空、`error` 为内核的说明。
108
- * `org_configured` (the platform view only): the platform config leaves a required overridable
109
- * field empty, so each org configures the provider itself; no list.
109
+ * A provider's model listing. Configuration states have no models or failure detail:
110
+ * `org_configured` is the platform view of an org-managed connection and `needs_config` means
111
+ * the organization's effective configuration is incomplete.
110
112
  */
111
- export interface ProviderStatus {
113
+ export interface ProviderStatus<State extends PlatformProviderState | OrgProviderState = PlatformProviderState | OrgProviderState> {
112
114
  provider: string;
113
115
  plugin: string;
114
- status: "ok" | "error" | "org_configured";
116
+ status: State;
117
+ /** The kernel's diagnostic for a failed list. */
115
118
  error?: string;
116
- /** With `error` from a failed list (not a provider that needs configuration): why it failed. */
117
119
  errorKind?: ListErrorKind;
118
120
  models: ListedModelInfo[];
119
121
  }
@@ -222,7 +224,7 @@ export declare class ProviderRegistry {
222
224
  * {@link listWithStatus} for the org, with every model the platform left on, each carrying
223
225
  * `disabled` for the org's own list. Reads the same cached lists (no extra provider call).
224
226
  */
225
- catalog(orgId: string): Promise<ProviderStatus[]>;
227
+ catalog(orgId: string): Promise<ProviderStatus<OrgProviderState>[]>;
226
228
  /**
227
229
  * Whether each provider gives an agent a model to pick in `orgId` (org readiness): the same
228
230
  * cached lists, time limit and failure markers as {@link catalog}, and the same rule as the
@@ -237,13 +239,14 @@ export declare class ProviderRegistry {
237
239
  * from the platform's list only).
238
240
  * See {@link statuses} for the statuses.
239
241
  */
240
- listWithStatus(orgId?: string): Promise<ProviderStatus[]>;
242
+ listWithStatus(): Promise<ProviderStatus<PlatformProviderState>[]>;
243
+ listWithStatus(orgId: string): Promise<ProviderStatus<OrgProviderState>[]>;
241
244
  /**
242
245
  * Every installed provider's full list and status, for `orgId` or the platform: a provider whose
243
246
  * model listing fails (including passing `models.listTimeoutMs`) gets `error` with empty
244
247
  * `models` without affecting the others, and is not asked again for
245
248
  * {@link LIST_FAILURE_TTL_SECONDS} seconds. For an org only the providers it enabled are
246
- * listed (one it did not enable is absent); one that needs configuration there gets `error`. The
249
+ * listed (one it did not enable is absent); one that needs configuration there gets `needs_config`. The
247
250
  * platform view of a provider whose platform config leaves a required overridable field empty
248
251
  * gets `org_configured`. `error` is only the kernel's own English message (the upstream error
249
252
  * text is never exposed; it goes to a warn log). No disabled list applied.
@@ -442,7 +442,6 @@ let ProviderRegistry = class ProviderRegistry {
442
442
  const out = [];
443
443
  for (const p of await this.catalog(orgId)) {
444
444
  if (p.status === "error") {
445
- // a provider that needs configuration here is not past the gate
446
445
  if (p.errorKind !== undefined) {
447
446
  out.push({ provider: p.provider, state: "list_failed", errorKind: p.errorKind });
448
447
  }
@@ -457,12 +456,6 @@ let ProviderRegistry = class ProviderRegistry {
457
456
  }
458
457
  return out;
459
458
  }
460
- /**
461
- * Every installed provider with its status (in plugin load order), for `orgId` (the providers it enabled, their enabled
462
- * models only), or the platform view when undefined (`/admin/models`: every model, `disabled`
463
- * from the platform's list only).
464
- * See {@link statuses} for the statuses.
465
- */
466
459
  async listWithStatus(orgId) {
467
460
  const [statuses, platform, org] = await Promise.all([
468
461
  this.statuses(orgId),
@@ -479,16 +472,6 @@ let ProviderRegistry = class ProviderRegistry {
479
472
  }),
480
473
  }));
481
474
  }
482
- /**
483
- * Every installed provider's full list and status, for `orgId` or the platform: a provider whose
484
- * model listing fails (including passing `models.listTimeoutMs`) gets `error` with empty
485
- * `models` without affecting the others, and is not asked again for
486
- * {@link LIST_FAILURE_TTL_SECONDS} seconds. For an org only the providers it enabled are
487
- * listed (one it did not enable is absent); one that needs configuration there gets `error`. The
488
- * platform view of a provider whose platform config leaves a required overridable field empty
489
- * gets `org_configured`. `error` is only the kernel's own English message (the upstream error
490
- * text is never exposed; it goes to a warn log). No disabled list applied.
491
- */
492
475
  async statuses(orgId) {
493
476
  const on = orgId === undefined ? new Set() : await this.enablement.enabledIn(orgId);
494
477
  const providers = this.providers().filter((p) => orgId === undefined || on.has(p.plugin));
@@ -521,12 +504,8 @@ let ProviderRegistry = class ProviderRegistry {
521
504
  return settled.map((r, i) => {
522
505
  const provider = providers[i].plugin;
523
506
  if (r.status === "fulfilled") {
524
- if (r.value === "org_configured") {
525
- return { provider, plugin: provider, status: "org_configured", models: [] };
526
- }
527
- if (r.value === "needs_config") {
528
- const error = `Model provider ${provider} needs configuration in this organization`;
529
- return { provider, plugin: provider, status: "error", error, models: [] };
507
+ if (typeof r.value === "string") {
508
+ return { provider, plugin: provider, status: r.value, models: [] };
530
509
  }
531
510
  return { provider, plugin: provider, status: "ok", models: r.value };
532
511
  }
@@ -119,6 +119,7 @@ export declare class RunOrphanCheck {
119
119
  run(): Promise<void>;
120
120
  /** One pass: repairs the orphans it finds (each on its own; a failure is logged). */
121
121
  check(): Promise<RunOrphanCheckResult>;
122
+ private repair;
122
123
  private saveCursorIn;
123
124
  private hasDeadDelivery;
124
125
  /**
@@ -12,7 +12,7 @@ import { sql } from "kysely";
12
12
  import { EventLog } from "../conversations/event-log.js";
13
13
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
14
  import { KernelDb } from "../infra/database/kernel-db.js";
15
- import { asPlatform } from "../infra/database/org-scope.js";
15
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
16
16
  import { TransactionHost } from "../infra/database/transaction-host.js";
17
17
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
18
  import { KernelEvents } from "../infra/events/kernel-events.js";
@@ -223,23 +223,11 @@ let RunOrphanCheck = class RunOrphanCheck {
223
223
  inspected++;
224
224
  for (const c of page) {
225
225
  try {
226
- if (c.deleted) {
227
- await this.deletion.stopDeletedConversation(c.conversationId, null);
228
- continue;
229
- }
230
- if (!(await this.withoutJobOrHolder(c)))
231
- continue;
232
- if (c.status === "running") {
233
- if (await this.failRunning(c))
234
- out.runningRepaired++;
235
- }
236
- else if (await this.hasDeadDelivery(c)) {
237
- await this.failRunning(c, true);
238
- }
239
- else if (await this.oweAgainIn(c)) {
240
- out.queuedReadded++;
226
+ const repaired = await withOrgScope(c.orgId, () => this.repair(c));
227
+ if (repaired)
228
+ out[repaired]++;
229
+ if (repaired === "queuedReadded")
241
230
  lost.push(c);
242
- }
243
231
  }
244
232
  catch (err) {
245
233
  this.log.error("run-orphan-check: cannot repair a run", { runId: c.runId, err });
@@ -260,6 +248,21 @@ let RunOrphanCheck = class RunOrphanCheck {
260
248
  }
261
249
  return out;
262
250
  }
251
+ async repair(c) {
252
+ if (c.deleted) {
253
+ await this.deletion.stopDeletedConversation(c.conversationId, null);
254
+ return;
255
+ }
256
+ if (!(await this.withoutJobOrHolder(c)))
257
+ return;
258
+ if (c.status === "running")
259
+ return (await this.failRunning(c)) ? "runningRepaired" : undefined;
260
+ if (await this.hasDeadDelivery(c)) {
261
+ await this.failRunning(c, true);
262
+ return;
263
+ }
264
+ return (await this.oweAgainIn(c)) ? "queuedReadded" : undefined;
265
+ }
263
266
  async saveCursorIn(cursor) {
264
267
  const values = {
265
268
  since: cursor === null ? null : sql `${cursor.since}::timestamptz`,
@@ -330,9 +333,8 @@ let RunOrphanCheck = class RunOrphanCheck {
330
333
  if (deliveryFailed) {
331
334
  // Lock dead rows against admin retry. A pending retry always takes precedence over a
332
335
  // historical dead copy. Producers of replacement jobs also hold this conversation lock.
333
- // org-filter: outbox rows by queue and deterministic kernel job id (unique across the
334
- // deployment); outbox.org_id is nullable
335
- const deliveries = await this.db
336
+ // org-filter: deployment-wide outbox rows by deterministic job id, including older unowned rows
337
+ const deliveries = await asPlatform("lock the orphan's outbox deliveries by job id", () => this.db
336
338
  .selectFrom("outbox")
337
339
  .select("dead_at")
338
340
  .where("queue", "=", c.queue)
@@ -342,7 +344,7 @@ let RunOrphanCheck = class RunOrphanCheck {
342
344
  eb("dead_at", ">=", sql `${c.since}::timestamptz`),
343
345
  ]))
344
346
  .forUpdate()
345
- .execute();
347
+ .execute());
346
348
  if (deliveries.length === 0 || deliveries.some((row) => row.dead_at === null))
347
349
  return null;
348
350
  }
@@ -123,7 +123,7 @@ export declare class UsageReporter {
123
123
  * itself closes with the application.
124
124
  */
125
125
  stop(): Promise<void>;
126
- /** The payload of a job: a `usage` event's or a `model_usage` row's; null when it is gone. */
126
+ private modelUsageOrg;
127
127
  private payloadOfJob;
128
128
  /**
129
129
  * The payload of one `model_usage` row (spec B §5.4, image generation spec §9): purpose `image`
@@ -146,6 +146,7 @@ export declare class UsageReporter {
146
146
  private writePending;
147
147
  /** One delivery job (the `@Processor` of {@link USAGE_REPORT_QUEUE} calls it). */
148
148
  process(j: Job<UsageReportJob>, token: string | undefined): Promise<void>;
149
+ private deliver;
149
150
  /** {@link unservable}; a lookup failure counts as "unknown" (keep retrying). */
150
151
  private unservableOrNone;
151
152
  /** Logs a warning at most once per plugin and kind per minute (Redis key with a TTL). */
@@ -11,6 +11,7 @@ import { getQueueToken } from "@nestjs/bullmq";
11
11
  import { Inject, Injectable, Module } from "@nestjs/common";
12
12
  import { DelayedError, Job, UnrecoverableError } from "bullmq";
13
13
  import { sql } from "kysely";
14
+ import { resolveConversationOrg } from "../conversations/job-org.js";
14
15
  import { ExtensionsModule } from "../extensions/extensions.module.js";
15
16
  import { deepFreeze, errMsg, HookNeedsConfigError, } from "../extensions/hooks.js";
16
17
  import { ExtensionHost } from "../extensions/host.js";
@@ -18,6 +19,7 @@ import { STALE_RECONCILE_PERIODS } from "../extensions/lifecycle-topics.js";
18
19
  import { queryUsageSubscribers } from "../extensions/usage-subscribers.js";
19
20
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
20
21
  import { KernelDb } from "../infra/database/kernel-db.js";
22
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
21
23
  import { LockService } from "../infra/lock/lock.service.js";
22
24
  import { QueueModule } from "../infra/queue/queue.module.js";
23
25
  import { KERNEL_LOGGER } from "../infra/tokens.js";
@@ -226,7 +228,15 @@ let UsageReporter = class UsageReporter {
226
228
  this.worker = undefined;
227
229
  await w?.close().catch(() => { });
228
230
  }
229
- /** The payload of a job: a `usage` event's or a `model_usage` row's; null when it is gone. */
231
+ async modelUsageOrg(usageId) {
232
+ // org-filter: deployment-wide lookup of the owner of a queued model usage id
233
+ const row = await asPlatform("resolve the org of a queued model usage report", () => this.db
234
+ .selectFrom("model_usage")
235
+ .select("org_id")
236
+ .where("id", "=", usageId)
237
+ .executeTakeFirst());
238
+ return row?.org_id;
239
+ }
230
240
  payloadOfJob(data) {
231
241
  return data.usageId !== undefined
232
242
  ? this.payloadOfUsage(data.usageId)
@@ -298,12 +308,16 @@ let UsageReporter = class UsageReporter {
298
308
  if (data.usageId === undefined)
299
309
  return;
300
310
  try {
301
- await this.db
311
+ const usageId = data.usageId;
312
+ const orgId = await this.modelUsageOrg(usageId);
313
+ if (orgId === undefined)
314
+ return;
315
+ await withOrgScope(orgId, () => this.db
302
316
  .updateTable("model_usage")
303
317
  .set({ report_failed_at: sql `now()` })
304
- .where("id", "=", data.usageId)
318
+ .where("id", "=", usageId)
305
319
  .where("reported_at", "is", null)
306
- .execute();
320
+ .execute());
307
321
  }
308
322
  catch (err) {
309
323
  this.log.warn("cannot mark a model usage report as given up", { usageId: data.usageId, err });
@@ -389,6 +403,14 @@ let UsageReporter = class UsageReporter {
389
403
  }
390
404
  /** One delivery job (the `@Processor` of {@link USAGE_REPORT_QUEUE} calls it). */
391
405
  async process(j, token) {
406
+ const orgId = j.data.usageId === undefined
407
+ ? await resolveConversationOrg(this.db, j.data.conversationId)
408
+ : await this.modelUsageOrg(j.data.usageId);
409
+ if (orgId === undefined)
410
+ return;
411
+ return withOrgScope(orgId, () => this.deliver(j, token));
412
+ }
413
+ async deliver(j, token) {
392
414
  const payload = await this.payloadOfJob(j.data);
393
415
  // conversation deleted meanwhile: nothing to report
394
416
  if (payload === null)
@@ -5,6 +5,8 @@ import { ExtensionRegistry } from "../extensions/registry.js";
5
5
  * (`EXTENSION_NAME_RE`), so it never collides with a loaded `device-provider@1` plugin.
6
6
  */
7
7
  export declare const isInProcessName: (name: string) => boolean;
8
+ /** The provider for personal computers connected to the platform. */
9
+ export declare const LOCAL_DEVICE_PROVIDER = "device-local";
8
10
  /**
9
11
  * Whether a provider serves its devices over the dial-in channel: it implements
10
12
  * `DeviceProvider.dialIn` (an extension may only when it declares `permissions.dialIn`, checked
@@ -16,6 +16,8 @@ import { guardProviderConnection } from "./unreachable.js";
16
16
  * (`EXTENSION_NAME_RE`), so it never collides with a loaded `device-provider@1` plugin.
17
17
  */
18
18
  export const isInProcessName = (name) => name.startsWith("@");
19
+ /** The provider for personal computers connected to the platform. */
20
+ export const LOCAL_DEVICE_PROVIDER = "device-local";
19
21
  /**
20
22
  * Whether a provider serves its devices over the dial-in channel: it implements
21
23
  * `DeviceProvider.dialIn` (an extension may only when it declares `permissions.dialIn`, checked
@@ -46,8 +46,8 @@ export declare const shareSourceOk: (eb: ExpressionBuilder<KernelDatabase, "file
46
46
  * `ConversationAccess.isAccessible`'s predicates: active account, still a member, the conversation
47
47
  * and its tree root not deleted, the agent not deleted and still visible to the creator; for a
48
48
  * library share: active account, still a member), and for an external share the effective external
49
- * sharing switch allows it now. One query (plus the platform switch for an external share, read live), no
50
- * cache: a cause going away (the switch back on) makes a share not expired live again.
49
+ * sharing switch allows it now. The public code or id first resolves its org. Liveness is checked in
50
+ * that org on every open, so turning sharing back on can restore access to an unexpired share.
51
51
  */
52
52
  export declare class ShareLiveness {
53
53
  private readonly db;
@@ -58,6 +58,7 @@ export declare class ShareLiveness {
58
58
  byCode(code: string): Promise<LiveShare | null>;
59
59
  /** The live share with this id (and generation, when given), or null. */
60
60
  byId(shareId: string, generation?: number): Promise<LiveShare | null>;
61
+ private findPublic;
61
62
  /**
62
63
  * Whether a share-scoped embed token (file sharing spec §7) still holds, checked on every use:
63
64
  * the share is live at the token's generation, in the token's org, and `plugin` is enabled in
@@ -13,6 +13,7 @@ import { accessibleTo } from "../conversations/access.js";
13
13
  import { enabledExtensionsQuery } from "../extensions/enabled.js";
14
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
15
  import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
16
17
  import { KERNEL_LOGGER } from "../infra/tokens.js";
17
18
  import { parseOrgSettings } from "../orgs/settings.service.js";
18
19
  import { UUID_RE } from "../ui/registry.js";
@@ -82,8 +83,8 @@ export const shareSourceOk = (eb) => eb.and([
82
83
  * `ConversationAccess.isAccessible`'s predicates: active account, still a member, the conversation
83
84
  * and its tree root not deleted, the agent not deleted and still visible to the creator; for a
84
85
  * library share: active account, still a member), and for an external share the effective external
85
- * sharing switch allows it now. One query (plus the platform switch for an external share, read live), no
86
- * cache: a cause going away (the switch back on) makes a share not expired live again.
86
+ * sharing switch allows it now. The public code or id first resolves its org. Liveness is checked in
87
+ * that org on every open, so turning sharing back on can restore access to an unexpired share.
87
88
  */
88
89
  let ShareLiveness = class ShareLiveness {
89
90
  db;
@@ -98,13 +99,29 @@ let ShareLiveness = class ShareLiveness {
98
99
  async byCode(code) {
99
100
  if (!SHARE_CODE_RE.test(code))
100
101
  return null;
101
- return this.find({ code });
102
+ return this.findPublic("code", code);
102
103
  }
103
104
  /** The live share with this id (and generation, when given), or null. */
104
105
  async byId(shareId, generation) {
105
106
  if (!UUID_RE.test(shareId))
106
107
  return null;
107
- return this.find({ id: shareId, ...(generation !== undefined && { generation }) });
108
+ return this.findPublic("id", shareId, generation);
109
+ }
110
+ async findPublic(column, value, generation) {
111
+ // org-filter: deployment-wide lookup of a public share by its unique code or signed id
112
+ const owner = await asPlatform("resolve the org of a public share link", () => this.db
113
+ .selectFrom("file_shares")
114
+ .select(["id", "org_id"])
115
+ .where(column, "=", value)
116
+ .executeTakeFirst());
117
+ if (!owner)
118
+ return null;
119
+ return withOrgScope(owner.org_id, () => this.find({
120
+ id: owner.id,
121
+ orgId: owner.org_id,
122
+ ...(column === "code" && { code: value }),
123
+ ...(generation !== undefined && { generation }),
124
+ }));
108
125
  }
109
126
  /**
110
127
  * Whether a share-scoped embed token (file sharing spec §7) still holds, checked on every use:
@@ -115,12 +132,12 @@ let ShareLiveness = class ShareLiveness {
115
132
  async embedLive(plugin, c) {
116
133
  if (!UUID_RE.test(c.shareId) || !UUID_RE.test(c.orgId))
117
134
  return false;
118
- const share = await this.find({
135
+ const share = await withOrgScope(c.orgId, () => this.find({
119
136
  id: c.shareId,
120
137
  generation: c.generation,
121
138
  orgId: c.orgId,
122
139
  plugin,
123
- });
140
+ }));
124
141
  return share !== null;
125
142
  }
126
143
  async find(by) {
@@ -160,14 +177,12 @@ let ShareLiveness = class ShareLiveness {
160
177
  .where((eb) => shareSourceOk(eb));
161
178
  if (by.code !== undefined)
162
179
  q = q.where("file_shares.code", "=", by.code);
163
- if (by.id !== undefined)
164
- q = q.where("file_shares.id", "=", by.id);
180
+ q = q.where("file_shares.id", "=", by.id);
165
181
  if (by.generation !== undefined)
166
182
  q = q.where("file_shares.generation", "=", by.generation);
167
- if (by.orgId !== undefined)
168
- q = q.where("file_shares.org_id", "=", by.orgId);
183
+ q = q.where("file_shares.org_id", "=", by.orgId);
169
184
  const { orgId, plugin } = by;
170
- if (orgId !== undefined && plugin !== undefined) {
185
+ if (plugin !== undefined) {
171
186
  q = q.where((eb) => eb.exists(eb
172
187
  .selectFrom(enabledExtensionsQuery(this.db.db, orgId).as("en"))
173
188
  .select("en.plugin")
@@ -21,6 +21,7 @@ import { HTML_TOKEN_TTL_SECONDS, HtmlTokens } from "../html/html-token.js";
21
21
  import { isHtmlType } from "../html/html-type.js";
22
22
  import { audit } from "../identity/audit.js";
23
23
  import { KernelDb } from "../infra/database/kernel-db.js";
24
+ import { bindRequestScope } from "../infra/database/org-scope.js";
24
25
  import { TransactionHost } from "../infra/database/transaction-host.js";
25
26
  import { Transactional } from "../infra/database/transactional.decorator.js";
26
27
  import { LockService } from "../infra/lock/lock.service.js";
@@ -101,6 +102,7 @@ let ShareOpenService = class ShareOpenService {
101
102
  const share = await this.liveness.byCode(code);
102
103
  if (share === null)
103
104
  throw shareNotFound();
105
+ bindRequestScope({ kind: "org", orgId: share.orgId });
104
106
  const p = req.principal;
105
107
  const sessionAccount = p?.kind === "user" && p.via === "session" && !p.account.mustChangePassword
106
108
  ? p.account.id
@@ -81,6 +81,8 @@ export declare function builtinSkillIds(db: KernelSchemaDb, orgId: string): Prom
81
81
  * skills are always on, and an agent cannot turn them off (skills default-on spec §3).
82
82
  */
83
83
  export declare function builtinSkillPlugins(db: KernelSchemaDb): Promise<Set<string>>;
84
+ /** Whether the effective library has a skill besides those shipped by builtin plugins. */
85
+ export declare function hasNonBuiltinSkill(db: KernelSchemaDb, orgId: string): Promise<boolean>;
84
86
  /**
85
87
  * The ids of the skills an agent always has, whatever its `disabledSkills` say: its own skills
86
88
  * (`scope = 'agent'`) and the org skills it shared (`origin_agent_id`: the agent keeps a shared
@@ -348,6 +348,62 @@ export async function builtinSkillPlugins(db) {
348
348
  .execute();
349
349
  return new Set(rows.map((r) => r.name));
350
350
  }
351
+ /** Whether the effective library has a skill besides those shipped by builtin plugins. */
352
+ export async function hasNonBuiltinSkill(db, orgId) {
353
+ // A standalone skill and a pinned copy whose source was removed both serve their own version.
354
+ const own = await db
355
+ .selectFrom("skills as s")
356
+ .innerJoin("skill_versions as v", (j) => j.onRef("v.skill_id", "=", "s.id").onRef("v.version", "=", "s.current_version"))
357
+ .select("s.id")
358
+ .where("s.org_id", "=", orgId)
359
+ .where("s.scope", "=", "org")
360
+ .where("s.deleted_at", "is", null)
361
+ .where((eb) => eb.or([
362
+ eb("s.platform_skill_id", "is", null),
363
+ eb.and([
364
+ eb("s.pinned_version", "is not", null),
365
+ eb.exists(eb
366
+ .selectFrom("platform_skills as removed")
367
+ .select("removed.id")
368
+ .whereRef("removed.id", "=", "s.platform_skill_id")
369
+ .where("removed.deleted_at", "is not", null)),
370
+ ]),
371
+ ]))
372
+ .limit(1)
373
+ .executeTakeFirst();
374
+ if (own)
375
+ return true;
376
+ // Skip resolving the library when it has no candidate besides live builtin components.
377
+ const candidate = await db
378
+ .selectFrom("platform_skills as p")
379
+ .leftJoin("catalog_items as c", "c.id", "p.catalog_item_id")
380
+ .select("p.id")
381
+ .where("p.deleted_at", "is", null)
382
+ .where("p.disabled", "=", false)
383
+ .where((eb) => eb.or([
384
+ eb("p.catalog_item_id", "is", null),
385
+ eb.and([
386
+ eb("c.deleted_at", "is", null),
387
+ eb("c.disabled", "=", false),
388
+ eb.or([
389
+ eb("c.builtin", "=", false),
390
+ eb("c.owner_org_id", "is not", null),
391
+ eb("p.owner_org_id", "is not", null),
392
+ ]),
393
+ ]),
394
+ ]))
395
+ .limit(1)
396
+ .executeTakeFirst();
397
+ if (!candidate)
398
+ return false;
399
+ // Scope, switches, name clashes, pins and promotions are resolved as in the org's library.
400
+ const [skills, builtin] = await Promise.all([
401
+ usableSkills(db, orgId),
402
+ builtinSkillIds(db, orgId),
403
+ ]);
404
+ const ids = new Set(builtin);
405
+ return skills.some((skill) => !ids.has(skill.id));
406
+ }
351
407
  /**
352
408
  * The ids of the skills an agent always has, whatever its `disabledSkills` say: its own skills
353
409
  * (`scope = 'agent'`) and the org skills it shared (`origin_agent_id`: the agent keeps a shared