@capybara-hq/kernel 0.1.0-rc.132 → 0.1.0-rc.133

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 (135) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/admin.schemas.d.ts +4 -0
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/admin/setup.service.js +6 -1
  7. package/dist/agents/agents.controller.js +3 -2
  8. package/dist/agents/agents.service.d.ts +2 -0
  9. package/dist/agents/agents.service.js +7 -0
  10. package/dist/catalog/catalog.service.d.ts +2 -0
  11. package/dist/catalog/catalog.service.js +28 -5
  12. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  13. package/dist/catalog/marketplace-fetch.js +15 -0
  14. package/dist/catalog/marketplaces.service.d.ts +4 -4
  15. package/dist/catalog/marketplaces.service.js +3 -2
  16. package/dist/catalog/owned-items.d.ts +2 -0
  17. package/dist/catalog/owned-items.js +30 -31
  18. package/dist/catalog/ownership.js +40 -38
  19. package/dist/catalog/plugin-import.d.ts +3 -4
  20. package/dist/catalog/plugin-import.js +50 -1
  21. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  22. package/dist/catalog/plugin-upgrade.js +95 -7
  23. package/dist/catalog/publisher-policy.d.ts +9 -0
  24. package/dist/catalog/publisher-policy.js +12 -0
  25. package/dist/catalog/unshare.js +66 -58
  26. package/dist/client/client-access.service.js +5 -3
  27. package/dist/config/schema.js +1 -1
  28. package/dist/conversations/conversations.controller.js +4 -14
  29. package/dist/conversations/conversations.service.d.ts +14 -0
  30. package/dist/conversations/conversations.service.js +20 -2
  31. package/dist/ctx/create-ctx.d.ts +11 -2
  32. package/dist/ctx/create-ctx.js +121 -52
  33. package/dist/ctx/queue.js +7 -4
  34. package/dist/db/extension-rls-predicate.d.ts +1 -0
  35. package/dist/db/extension-rls-predicate.js +8 -0
  36. package/dist/db/kernel-schema.d.ts +48 -0
  37. package/dist/db/migrator.js +6 -13
  38. package/dist/db/pool.d.ts +2 -2
  39. package/dist/db/pool.js +2 -2
  40. package/dist/db/sql-statements.d.ts +3 -0
  41. package/dist/db/sql-statements.js +15 -5
  42. package/dist/device-access/device-access.module.js +12 -2
  43. package/dist/device-access/device-access.service.d.ts +30 -2
  44. package/dist/device-access/device-access.service.js +38 -4
  45. package/dist/device-access/host-gate.d.ts +45 -0
  46. package/dist/device-access/host-gate.js +92 -0
  47. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  48. package/dist/device-access/host-service-stop-sweep.js +112 -0
  49. package/dist/device-access/host-service-stop.d.ts +78 -0
  50. package/dist/device-access/host-service-stop.js +144 -0
  51. package/dist/device-access/host-services.d.ts +211 -0
  52. package/dist/device-access/host-services.js +803 -0
  53. package/dist/device-access/person-handles.d.ts +10 -0
  54. package/dist/device-access/person-handles.js +25 -0
  55. package/dist/device-access/service-events.d.ts +199 -0
  56. package/dist/device-access/service-events.js +704 -0
  57. package/dist/device-access/token.d.ts +5 -0
  58. package/dist/device-access/token.js +5 -0
  59. package/dist/devices/devices.service.js +3 -0
  60. package/dist/dial-in/access.d.ts +5 -5
  61. package/dist/dial-in/access.js +19 -12
  62. package/dist/dial-in/gateway.js +6 -2
  63. package/dist/dial-in/machines.d.ts +9 -2
  64. package/dist/dial-in/machines.js +27 -4
  65. package/dist/erasure/device-cleanup.js +12 -0
  66. package/dist/erasure/org-catalog.js +2 -2
  67. package/dist/erasure/org-rules.js +9 -0
  68. package/dist/errors.d.ts +2 -0
  69. package/dist/errors.js +2 -0
  70. package/dist/extensions/admin-ops.js +8 -2
  71. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  72. package/dist/extensions/deployed-snapshots.js +7 -2
  73. package/dist/extensions/host.d.ts +7 -2
  74. package/dist/extensions/host.js +11 -2
  75. package/dist/extensions/instance.d.ts +3 -0
  76. package/dist/extensions/instance.js +4 -0
  77. package/dist/extensions/ledger.d.ts +1 -1
  78. package/dist/extensions/lifecycle-hooks.js +3 -3
  79. package/dist/extensions/org-config.js +6 -1
  80. package/dist/extensions/permission-set.d.ts +7 -0
  81. package/dist/extensions/permission-set.js +10 -0
  82. package/dist/extensions/permission-view.d.ts +1 -1
  83. package/dist/extensions/permission-view.js +10 -1
  84. package/dist/git/tickets.js +32 -27
  85. package/dist/http/app.js +5 -3
  86. package/dist/identity/accounts.d.ts +6 -1
  87. package/dist/identity/accounts.js +11 -2
  88. package/dist/identity/api-tokens.js +7 -6
  89. package/dist/identity/settings.d.ts +9 -1
  90. package/dist/identity/settings.js +16 -1
  91. package/dist/inbox/org-notices.js +3 -2
  92. package/dist/index.d.ts +1 -0
  93. package/dist/index.js +1 -0
  94. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  95. package/dist/infra/database/scoped-dialect.js +260 -72
  96. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  97. package/dist/infra/database/startup-activation-transaction.js +3 -2
  98. package/dist/infra/outbox/registry.d.ts +28 -0
  99. package/dist/infra/outbox/registry.js +30 -0
  100. package/dist/infra/queue/queue-names.d.ts +1 -1
  101. package/dist/infra/queue/queue-names.js +1 -0
  102. package/dist/infra/queue/run-job.d.ts +4 -1
  103. package/dist/infra/queue/run-job.js +10 -2
  104. package/dist/kernel.module.js +3 -0
  105. package/dist/orgs/offboarding.js +18 -9
  106. package/dist/orgs/settings.service.js +3 -0
  107. package/dist/packages/npm-publish-keys.json +27 -0
  108. package/dist/packages/official-publisher.d.ts +19 -0
  109. package/dist/packages/official-publisher.js +152 -0
  110. package/dist/packages/provenance.d.ts +7 -0
  111. package/dist/packages/provenance.js +22 -19
  112. package/dist/packages/sigstore-trusted-root.json +126 -0
  113. package/dist/platform/ops/admin.ops.js +2 -1
  114. package/dist/platform/ops/orgs.ops.js +1 -0
  115. package/dist/roles/worker-role.d.ts +6 -3
  116. package/dist/roles/worker-role.js +12 -4
  117. package/dist/roles/worker.module.js +7 -0
  118. package/dist/runtime/maintenance.d.ts +5 -2
  119. package/dist/runtime/maintenance.js +18 -4
  120. package/dist/sandbox/device-reports.d.ts +4 -4
  121. package/dist/sandbox/device-reports.js +40 -30
  122. package/dist/sandbox/device-services.d.ts +2 -1
  123. package/dist/sandbox/device-services.js +5 -1
  124. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  125. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  126. package/dist/sandbox/permission-config-publication.js +5 -1
  127. package/dist/themes/theme-state.js +24 -13
  128. package/dist/tools/call-scope.d.ts +6 -0
  129. package/dist/tools/call-scope.js +22 -0
  130. package/dist/tools/registry.js +20 -2
  131. package/dist/ui/views.js +36 -8
  132. package/package.json +9 -4
  133. package/src/migrations/0222_device_host_services.sql +27 -0
  134. package/src/migrations/0223_device_service_events.sql +54 -0
  135. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
@@ -24,6 +24,8 @@ import { EventLogModule } from "../conversations/event-log.js";
24
24
  import { PromptSuggestionsModule } from "../conversations/prompt-suggestions.js";
25
25
  import { TitlesModule } from "../conversations/titles.js";
26
26
  import { ConversationNoticeSweepJob, ConversationNoticesModule, } from "../device-access/conversation-notice-delivery.js";
27
+ import { HostServiceStopSweepJob } from "../device-access/host-service-stop-sweep.js";
28
+ import { DeviceServiceEventWorkersModule } from "../device-access/service-events.js";
27
29
  import { DeviceSiteGrantsModule } from "../device-access/site-grants.module.js";
28
30
  import { ErasureModule } from "../erasure/erasure.module.js";
29
31
  import { ErasureSweep } from "../erasure/sweep.job.js";
@@ -102,6 +104,8 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
102
104
  // template connectors an org never had, owed by installs and extension switch-ons
103
105
  // (`cap-template-connectors`)
104
106
  TemplateConnectorsWorkersModule,
107
+ // device service event deliveries (`cap-device-service-events`) and their 5-minute sweep
108
+ DeviceServiceEventWorkersModule,
105
109
  // the domains the fixed-period jobs call
106
110
  RuntimeModule,
107
111
  RunJobsModule,
@@ -145,6 +149,9 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
145
149
  BackgroundTaskPollJob,
146
150
  // owed conversation notices to devices' services (close tabs on delete design §4.3)
147
151
  ConversationNoticeSweepJob,
152
+ // owed host service stops of connected machines and deleted devices (local agents spec,
153
+ // call 5)
154
+ HostServiceStopSweepJob,
148
155
  // loopback port grants past their 24 hours (browser loopback port grants design §4)
149
156
  LoopbackExpiryJob,
150
157
  ToolJobs,
@@ -4,6 +4,7 @@ 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
6
  import { ConversationNoticeDelivery } from "../device-access/conversation-notice-delivery.js";
7
+ import { HostServiceAccess } from "../device-access/host-services.js";
7
8
  import { ErasureWorker } from "../erasure/worker.js";
8
9
  import { BlobObjects } from "../files/blob-objects.js";
9
10
  import { FileLibraryHashJob } from "../files/hash-job.js";
@@ -36,7 +37,8 @@ export declare const MAINTENANCE_CONCURRENCY = 5;
36
37
  * {@link BlobObjects}, `file-library-hash`, `file-library-hash-org` → {@link FileLibraryHashJob},
37
38
  * `platform-icon-delete` →
38
39
  * {@link PlatformIconObjects}, `device-conversation-notice` → {@link ConversationNoticeDelivery},
39
- * `idle-compaction` → {@link IdleCompactionJob}, `device-loopback-refresh` → {@link LoopbackGrants}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
40
+ * `idle-compaction` → {@link IdleCompactionJob}, `device-loopback-refresh` → {@link LoopbackGrants}, `device-host-services-stop` →
41
+ * {@link HostServiceAccess}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
40
42
  * such as `sandbox-suspend-idle`) runs that job's body once ({@link ScheduledRuns.runNow}), as the
41
43
  * maintenance handlers did when those jobs were schedulers on this queue: an operator's or a
42
44
  * test's one-off run, not a second schedule (decision R23 of the Nest kernel spec). Any other
@@ -64,9 +66,10 @@ export declare class MaintenanceProcessor extends WorkerHost<Worker> {
64
66
  private readonly idleCompaction;
65
67
  private readonly db;
66
68
  private readonly loopback;
69
+ private readonly hostServices;
67
70
  private readonly retention;
68
71
  private readonly erasure;
69
- 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">, retention: Pick<RetentionWorker, "run">, erasure: Pick<ErasureWorker, "run">);
72
+ 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">, hostServices: Pick<HostServiceAccess, "deliverOwedStops">, retention: Pick<RetentionWorker, "run">, erasure: Pick<ErasureWorker, "run">);
70
73
  process(job: Job, token?: string): Promise<void>;
71
74
  /** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
72
75
  start(): void;
@@ -19,6 +19,9 @@ import { EventLogModule } from "../conversations/event-log.js";
19
19
  import { resolveConversationOrg, resolveRunOrg } from "../conversations/job-org.js";
20
20
  import { ConversationNoticeDelivery, ConversationNoticesModule, NOTICE_PROMPT_TIMEOUT_MS, } from "../device-access/conversation-notice-delivery.js";
21
21
  import { CONVERSATION_NOTICE_JOB, } from "../device-access/conversation-notices.js";
22
+ import { ExtensionDeviceAccessModule } from "../device-access/device-access.module.js";
23
+ import { HOST_SERVICES_STOP_JOB, } from "../device-access/host-service-stop.js";
24
+ import { HostServiceAccess } from "../device-access/host-services.js";
22
25
  import { DATA_ERASURE_JOB } from "../erasure/jobs.js";
23
26
  import { ErasureWorker, ErasureWorkerModule } from "../erasure/worker.js";
24
27
  import { BLOB_DELETE_JOB, BlobObjects, BlobObjectsModule, FILE_RELEASE_JOB, FILE_STAGING_DELETE_JOB, } from "../files/blob-objects.js";
@@ -71,7 +74,8 @@ export const MAINTENANCE_CONCURRENCY = 5;
71
74
  * {@link BlobObjects}, `file-library-hash`, `file-library-hash-org` → {@link FileLibraryHashJob},
72
75
  * `platform-icon-delete` →
73
76
  * {@link PlatformIconObjects}, `device-conversation-notice` → {@link ConversationNoticeDelivery},
74
- * `idle-compaction` → {@link IdleCompactionJob}, `device-loopback-refresh` → {@link LoopbackGrants}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
77
+ * `idle-compaction` → {@link IdleCompactionJob}, `device-loopback-refresh` → {@link LoopbackGrants}, `device-host-services-stop` →
78
+ * {@link HostServiceAccess}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
75
79
  * such as `sandbox-suspend-idle`) runs that job's body once ({@link ScheduledRuns.runNow}), as the
76
80
  * maintenance handlers did when those jobs were schedulers on this queue: an operator's or a
77
81
  * test's one-off run, not a second schedule (decision R23 of the Nest kernel spec). Any other
@@ -99,9 +103,10 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
99
103
  idleCompaction;
100
104
  db;
101
105
  loopback;
106
+ hostServices;
102
107
  retention;
103
108
  erasure;
104
- constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, automations, scheduled, log, operations, blobObjects, hashing, platformIcons, notices, triggers, coalescer, idleCompaction, db, loopback, retention, erasure) {
109
+ constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, automations, scheduled, log, operations, blobObjects, hashing, platformIcons, notices, triggers, coalescer, idleCompaction, db, loopback, hostServices, retention, erasure) {
105
110
  super();
106
111
  this.permissionApprovals = permissionApprovals;
107
112
  this.waits = waits;
@@ -124,6 +129,7 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
124
129
  this.idleCompaction = idleCompaction;
125
130
  this.db = db;
126
131
  this.loopback = loopback;
132
+ this.hostServices = hostServices;
127
133
  this.retention = retention;
128
134
  this.erasure = erasure;
129
135
  }
@@ -305,6 +311,11 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
305
311
  case LOOPBACK_REFRESH_JOB:
306
312
  await this.loopback.refresh(job.data, AbortSignal.timeout(LOOPBACK_REFRESH_TIMEOUT_MS));
307
313
  return;
314
+ // a switched-off extension's host services on the machines that run them (local agents
315
+ // spec, call 5)
316
+ case HOST_SERVICES_STOP_JOB:
317
+ await this.hostServices.deliverOwedStops(job.data);
318
+ return;
308
319
  // a large idle conversation's compaction before its prompt cache expires (idle compaction §4.3)
309
320
  case IDLE_COMPACTION_JOB: {
310
321
  const data = job.data;
@@ -356,8 +367,9 @@ MaintenanceProcessor = __decorate([
356
367
  __param(18, Inject(IdleCompactionJob)),
357
368
  __param(19, Inject(KernelDb)),
358
369
  __param(20, Inject(LoopbackGrants)),
359
- __param(21, Inject(RetentionWorker)),
360
- __param(22, Inject(ErasureWorker))
370
+ __param(21, Inject(HostServiceAccess)),
371
+ __param(22, Inject(RetentionWorker)),
372
+ __param(23, Inject(ErasureWorker))
361
373
  ], MaintenanceProcessor);
362
374
  export { MaintenanceProcessor };
363
375
  /**
@@ -394,6 +406,8 @@ MaintenanceModule = __decorate([
394
406
  PlatformIconObjectsModule,
395
407
  // a deleted conversation's notice to its device's services
396
408
  ConversationNoticesModule,
409
+ // a switched-off extension's host services stop
410
+ ExtensionDeviceAccessModule,
397
411
  QueueModule.registerQueue(MAINTENANCE_QUEUE_NAME),
398
412
  ],
399
413
  providers: [
@@ -68,10 +68,10 @@ export declare class DeviceReports {
68
68
  changed: boolean;
69
69
  }>;
70
70
  /**
71
- * `ctx.devices.reportChanged(deviceId)` of the extension `plugin`: `not-served` unless the
72
- * device is live and bound to `plugin` (the caller refuses it); otherwise reads the device's
73
- * report and permission support from `plugin` (its current instance's handle, if any) outside
74
- * any transaction and stores them as {@link refresh} does. Throws when the report cannot be read
71
+ * `ctx.devices.reportChanged(deviceId)` returns `not-served` unless the device is live, bound to
72
+ * `plugin`, and in the caller's org if the caller has an org scope. Reads the device's report and
73
+ * permission support from `plugin` (with its current instance's handle, if any) outside any
74
+ * transaction and stores them as {@link refresh} does. Throws when the report cannot be read
75
75
  * or does not pass, so the provider may tell again; a failed support read stores no support
76
76
  * (no crossing enforceable: revocation fails closed).
77
77
  */
@@ -11,6 +11,7 @@ import { parseDeviceReport, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { asPlatform, currentScope, withOrgScope } from "../infra/database/org-scope.js";
14
15
  import { runOutsideTransaction, TransactionHost } from "../infra/database/transaction-host.js";
15
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
16
17
  import { LockService } from "../infra/lock/lock.service.js";
@@ -132,42 +133,51 @@ let DeviceReports = class DeviceReports {
132
133
  }
133
134
  }
134
135
  /**
135
- * `ctx.devices.reportChanged(deviceId)` of the extension `plugin`: `not-served` unless the
136
- * device is live and bound to `plugin` (the caller refuses it); otherwise reads the device's
137
- * report and permission support from `plugin` (its current instance's handle, if any) outside
138
- * any transaction and stores them as {@link refresh} does. Throws when the report cannot be read
136
+ * `ctx.devices.reportChanged(deviceId)` returns `not-served` unless the device is live, bound to
137
+ * `plugin`, and in the caller's org if the caller has an org scope. Reads the device's report and
138
+ * permission support from `plugin` (with its current instance's handle, if any) outside any
139
+ * transaction and stores them as {@link refresh} does. Throws when the report cannot be read
139
140
  * or does not pass, so the provider may tell again; a failed support read stores no support
140
141
  * (no crossing enforceable: revocation fails closed).
141
142
  */
142
143
  async changed(plugin, deviceId, signal = new AbortController().signal) {
143
144
  return runOutsideTransaction(async () => {
144
- const device = await this.db
145
- .selectFrom("devices as d")
146
- .innerJoin("orgs as o", "o.id", "d.org_id")
147
- .select(["d.org_id", "d.provider"])
148
- .where("d.id", "=", deviceId)
149
- .where("d.deleted_at", "is", null)
150
- .where("o.deleted_at", "is", null)
151
- .executeTakeFirst();
152
- if (!device || device.provider !== plugin)
153
- return "not-served";
154
- const entry = this.providers.forDevice(plugin);
155
- if (!entry)
156
- throw new Error(`Device provider ${plugin} is not loaded on this replica`);
157
- const instance = await this.db
158
- .selectFrom("device_instances")
159
- .select("handle")
160
- .where("device_id", "=", deviceId)
161
- .where("org_id", "=", device.org_id)
162
- .where("provider", "=", plugin)
163
- .executeTakeFirst();
164
- const ref = {
165
- deviceId,
166
- orgId: device.org_id,
167
- handle: (instance?.handle ?? null),
145
+ const scope = currentScope();
146
+ const lookup = () => {
147
+ const query = this.db
148
+ .selectFrom("devices as d")
149
+ .innerJoin("orgs as o", "o.id", "d.org_id")
150
+ .select("d.org_id")
151
+ .where("d.id", "=", deviceId)
152
+ .where("d.provider", "=", plugin)
153
+ .where("d.deleted_at", "is", null)
154
+ .where("o.deleted_at", "is", null);
155
+ return (scope?.kind === "org" ? query.where("d.org_id", "=", scope.orgId) : query).executeTakeFirst();
168
156
  };
169
- const answer = await this.ask(entry, ref, signal, true);
170
- return (await this.store(plugin, ref, answer)).published ? "bumped" : "same";
157
+ const device = scope
158
+ ? await lookup()
159
+ : await asPlatform("resolve the org of a device served by the notifying provider", lookup);
160
+ if (!device)
161
+ return "not-served";
162
+ return withOrgScope(device.org_id, async () => {
163
+ const entry = this.providers.forDevice(plugin);
164
+ if (!entry)
165
+ throw new Error(`Device provider ${plugin} is not loaded on this replica`);
166
+ const instance = await this.db
167
+ .selectFrom("device_instances")
168
+ .select("handle")
169
+ .where("device_id", "=", deviceId)
170
+ .where("org_id", "=", device.org_id)
171
+ .where("provider", "=", plugin)
172
+ .executeTakeFirst();
173
+ const ref = {
174
+ deviceId,
175
+ orgId: device.org_id,
176
+ handle: (instance?.handle ?? null),
177
+ };
178
+ const answer = await this.ask(entry, ref, signal, true);
179
+ return (await this.store(plugin, ref, answer)).published ? "bumped" : "same";
180
+ });
171
181
  });
172
182
  }
173
183
  /**
@@ -64,7 +64,8 @@ export declare class DeviceServices {
64
64
  * Starts the service in the device, or finds it running (the provider keeps a running one).
65
65
  * With `ifRunning` it never starts one: a stopped service answers its `stopped` status, and the
66
66
  * provider gets only the name ({@link nameOnlySpec}), as with every ifRunning ensure. A spec
67
- * breaking {@link serviceSpecIssue} is refused before the device is touched.
67
+ * breaking {@link serviceSpecIssue}, or a host spec (`host` set: `host_not_declared`), is refused
68
+ * before the device is touched.
68
69
  */
69
70
  ensure(use: SandboxUseContext, spec: DeviceServiceSpec, signal: AbortSignal, opts?: {
70
71
  ifRunning?: boolean;
@@ -113,10 +113,14 @@ let DeviceServices = class DeviceServices {
113
113
  * Starts the service in the device, or finds it running (the provider keeps a running one).
114
114
  * With `ifRunning` it never starts one: a stopped service answers its `stopped` status, and the
115
115
  * provider gets only the name ({@link nameOnlySpec}), as with every ifRunning ensure. A spec
116
- * breaking {@link serviceSpecIssue} is refused before the device is touched.
116
+ * breaking {@link serviceSpecIssue}, or a host spec (`host` set: `host_not_declared`), is refused
117
+ * before the device is touched.
117
118
  */
118
119
  async ensure(use, spec, signal, opts = {}) {
119
120
  assertServiceSpec(spec);
121
+ // a host service starts only through its own admission (`HostServiceAccess`), never here
122
+ if (spec.host !== undefined)
123
+ throw new DeviceAccessError("host_not_declared", `The device service spec ${spec.name} sets host: a host service starts only through ensureHostService.`);
120
124
  return this.sandbox.withDeviceServices(use, requireServices, (h, p, sig) => {
121
125
  const ensure = p.ensureService;
122
126
  // read under the use and the set lock, so a grant committed before it is in the set
@@ -22,6 +22,14 @@ export declare class PermissionCeilingWrites {
22
22
  /** The platform writer excludes every descendant; only these environments changed Full reach. */
23
23
  invalidateDeviceConsentUnderPlatform(deviceIds: readonly string[], platformProfiles?: readonly PermissionProfile[]): Promise<void>;
24
24
  publishLocked(subject: AuthoritySubject, level: "platform" | "org" | "device" | "root", revoke?: boolean | ((scope: SandboxOperationScope | SandboxBrowseScope, row: Selectable<SandboxOperationIntentsTable>) => boolean), invalidateFullConsent?: boolean, refreshStartedServices?: boolean, platformProfiles?: readonly PermissionProfile[]): Promise<void>;
25
+ /**
26
+ * The host gate closed under the subject (local agents spec, call 1: a platform or org project
27
+ * reach cap narrowed below `machine`, or running outside the sandbox switched off there): every
28
+ * host service under it, a whole-machine escalation, is owed a stop in the writer's transaction,
29
+ * under the writer's exclusive lock of its level. The host gate refuses new ones once it
30
+ * commits, and its admission reads under the shared authority locks (`HostServiceGate.admit`).
31
+ */
32
+ oweHostServiceStopsLocked(subject: AuthoritySubject, level: "platform" | "org"): Promise<void>;
25
33
  /** Full access consent only grows where the org inherits the widened platform reach. */
26
34
  invalidateProjectReachWideningLocked(before: DeviceProjectReach, after: DeviceProjectReach, platformProfiles?: readonly PermissionProfile[]): Promise<void>;
27
35
  /** Selected profiles removed by an org or platform ceiling reset before the writer commits. */
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { narrowerProjectReach, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
+ import { oweHostServicesStop } from "../device-access/host-service-stop.js";
13
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
15
  import { KernelDb } from "../infra/database/kernel-db.js";
15
16
  import { asPlatform } from "../infra/database/org-scope.js";
@@ -122,6 +123,11 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
122
123
  rootConversationId: subject.rootConversationId,
123
124
  }),
124
125
  }, `c${level}-${id}-${epoch}`, refreshStartedServices);
126
+ // a project reach narrowed at the platform or the org (the writers pass it as
127
+ // `refreshStartedServices`) leaves it below `machine` for every device under the subject,
128
+ // which closes the host gate there
129
+ if (refreshStartedServices && (level === "platform" || level === "org"))
130
+ await this.oweHostServiceStopsLocked(subject, level);
125
131
  if (!revoke)
126
132
  return;
127
133
  // Acknowledged background starts stay revocable by every actual revoking writer (deletion is
@@ -170,6 +176,18 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
170
176
  });
171
177
  }
172
178
  }
179
+ /**
180
+ * The host gate closed under the subject (local agents spec, call 1: a platform or org project
181
+ * reach cap narrowed below `machine`, or running outside the sandbox switched off there): every
182
+ * host service under it, a whole-machine escalation, is owed a stop in the writer's transaction,
183
+ * under the writer's exclusive lock of its level. The host gate refuses new ones once it
184
+ * commits, and its admission reads under the shared authority locks (`HostServiceGate.admit`).
185
+ */
186
+ async oweHostServiceStopsLocked(subject, level) {
187
+ const orgId = level === "org" ? required(subject.orgId) : undefined;
188
+ this.locks.assertHeld(level, orgId ?? "platform", true);
189
+ await oweHostServicesStop(this.db.db, this.outbox, orgId === undefined ? {} : { orgId });
190
+ }
173
191
  /** Full access consent only grows where the org inherits the widened platform reach. */
174
192
  async invalidateProjectReachWideningLocked(before, after, platformProfiles) {
175
193
  if (narrowerProjectReach(before, after) === after)
@@ -293,6 +311,9 @@ __decorate([
293
311
  __decorate([
294
312
  Transactional({ propagation: "mandatory" })
295
313
  ], PermissionCeilingWrites.prototype, "publishLocked", null);
314
+ __decorate([
315
+ Transactional({ propagation: "mandatory" })
316
+ ], PermissionCeilingWrites.prototype, "oweHostServiceStopsLocked", null);
296
317
  __decorate([
297
318
  Transactional({ propagation: "mandatory" })
298
319
  ], PermissionCeilingWrites.prototype, "invalidateProjectReachWideningLocked", null);
@@ -159,10 +159,11 @@ let PermissionConfigPublication = class PermissionConfigPublication {
159
159
  const projection = permissionConfigProjection(this.config.get());
160
160
  const initialize = () => this.initializeLocked(projection, options.activation);
161
161
  if (options.startup) {
162
- const { url, connectTimeoutMs } = this.config.get().db;
162
+ const { url, connectTimeoutMs, rls } = this.config.get().db;
163
163
  return this.txHost.runStartupActivation(initialize, {
164
164
  connectionString: url,
165
165
  connectTimeoutMs,
166
+ rls,
166
167
  ...options.startup,
167
168
  });
168
169
  }
@@ -315,6 +316,9 @@ let PermissionConfigPublication = class PermissionConfigPublication {
315
316
  },
316
317
  // only a widening resets Full consent: a narrowing keeps what the consent covered
317
318
  (beforeMode === "off" && nextMode === "allowed") || networkWidened || hostsWidened, reachTightened, nextView.allowedProfiles.value);
319
+ // running outside the sandbox switched off closes the host gate on every device
320
+ if (beforeMode !== "off" && nextMode === "off")
321
+ await this.ceilings.oweHostServiceStopsLocked({}, "platform");
318
322
  if (beforeReach !== nextReach && !reachTightened)
319
323
  await this.ceilings.invalidateProjectReachWideningLocked(beforeReach, nextReach, nextView.allowedProfiles.value);
320
324
  return "activated";
@@ -3,8 +3,9 @@
3
3
  // transaction's connection when there is one): the settings writers (deployment, org, person) and
4
4
  // `ThemesService` decide with the same predicates.
5
5
  import { BUILTIN_AVATAR_PRESET_IDS, isThemeAssetPath, mergeThemeSchemes, } from "@capybara-hq/plugin-sdk";
6
- import { componentOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, switchOf, } from "../catalog/component-state.js";
6
+ import { componentOn, listedIn, loadComponents, loadScopeState, platformBuiltin, pluginFactsOf, switchOf, } from "../catalog/component-state.js";
7
7
  import { ApiError } from "../errors.js";
8
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
8
9
  import { packagePath } from "../packages/tgz.js";
9
10
  import { THEME_PRESET_KEY_RE } from "./avatar-preset-key.js";
10
11
  /** The schemes in the order they are listed. */
@@ -161,10 +162,9 @@ export async function themesOnIn(db, orgId) {
161
162
  * plugin live and not disabled, and its effective scope `all` (its own, or its plugin's when it
162
163
  * follows; a builtin plugin is `all`).
163
164
  */
164
- function platformDefaultEligible(st, c) {
165
+ function platformDefaultEligible(c, p) {
165
166
  if (c.ownerOrgId !== null || c.disabled)
166
167
  return false;
167
- const p = c.itemId === null ? undefined : st.plugins.get(c.itemId);
168
168
  if (c.itemId !== null && (p === undefined || p.disabled))
169
169
  return false;
170
170
  if (c.scopeMode === "own")
@@ -176,8 +176,17 @@ export async function eligiblePlatformDefault(db, id) {
176
176
  const [c] = await loadComponents(db, "theme", { ids: [id] });
177
177
  if (!c)
178
178
  return null;
179
- const st = await loadScopeState(db, "theme", [c]);
180
- return platformDefaultEligible(st, c) ? c : null;
179
+ // The public theme read needs only catalog metadata. Per-org availability is checked on writes.
180
+ const item = c.itemId === null
181
+ ? undefined
182
+ : await db
183
+ .selectFrom("catalog_items")
184
+ .select(["scope", "builtin", "disabled", "owner_org_id"])
185
+ .where("id", "=", c.itemId)
186
+ .where("deleted_at", "is", null)
187
+ .executeTakeFirst();
188
+ const plugin = item && { ...item, builtin: platformBuiltin(item) };
189
+ return platformDefaultEligible(c, plugin) ? c : null;
181
190
  }
182
191
  /**
183
192
  * 400 `theme.not_available`: theme `id` cannot be chosen where it was set; `orgs`: the live orgs
@@ -220,7 +229,8 @@ export async function lockThemeShared(db, id) {
220
229
  export async function assertPlatformDefaultEligible(db, id) {
221
230
  const [c] = await loadComponents(db, "theme", { ids: [id] });
222
231
  const st = c && (await loadScopeState(db, "theme", [c]));
223
- if (!c || !st || !platformDefaultEligible(st, c)) {
232
+ const plugin = c?.itemId == null ? undefined : st?.plugins.get(c.itemId);
233
+ if (!c || !st || !platformDefaultEligible(c, plugin)) {
224
234
  throw themeNotAvailable(id, "as the platform default (a platform theme whose scope is all)");
225
235
  }
226
236
  const orgs = await db
@@ -254,18 +264,19 @@ export async function themeOnIn(db, orgId, id) {
254
264
  }
255
265
  /** Whether theme `id` is on in at least one of the person's live orgs. */
256
266
  export async function themeOnForAccount(db, accountId, id) {
257
- const orgs = await db
267
+ // org-filter: deployment-wide lookup of the authenticated account's live memberships.
268
+ const orgs = await asPlatform("Resolve the account's orgs for a personal theme", () => db
258
269
  .selectFrom("memberships as m")
259
270
  .innerJoin("orgs as o", "o.id", "m.org_id")
260
271
  .select("m.org_id")
261
272
  .where("m.account_id", "=", accountId)
262
273
  .where("o.deleted_at", "is", null)
263
- .execute();
264
- const [c] = await loadComponents(db, "theme", { ids: [id] });
265
- if (!c || orgs.length === 0)
266
- return false;
267
- const st = await loadScopeState(db, "theme", [c]);
268
- return orgs.some((o) => onIn(st, c, o.org_id));
274
+ .execute());
275
+ for (const { org_id: orgId } of orgs) {
276
+ if (await withOrgScope(orgId, () => themeOnIn(db, orgId, id)))
277
+ return true;
278
+ }
279
+ return false;
269
280
  }
270
281
  /**
271
282
  * Refuses (400 `theme.not_available`) a person's pick that is on in none of their live orgs (the
@@ -92,6 +92,12 @@ export declare function attachCallScope(ctx: ToolCallContext, facts?: CallFacts,
92
92
  }): CallScope;
93
93
  /** The call's scope, or null for a context the pipeline did not make (no scope attached). */
94
94
  export declare function callScopeOf(ctx: ToolCallContext): CallScope | null;
95
+ /** Marks `ctx` live while the kernel runs its handler ({@link isLiveCall}). */
96
+ export declare function markCallLive(ctx: ToolCallContext): void;
97
+ /** Ends the live mark of `ctx`: its handler settled, or the kernel gave up on it. */
98
+ export declare function endCall(ctx: ToolCallContext): void;
99
+ /** Whether `ctx` is a call context the kernel issued and whose handler is running now. */
100
+ export declare function isLiveCall(ctx: unknown): boolean;
95
101
  /**
96
102
  * Runs `fn` as a device start of the call ({@link CallScope.starting}); a context without a scope
97
103
  * runs it as it is.
@@ -28,6 +28,28 @@ export function attachCallScope(ctx, facts, opts = {}) {
28
28
  export function callScopeOf(ctx) {
29
29
  return ctx[CALL_SCOPE] ?? null;
30
30
  }
31
+ /**
32
+ * The tool call contexts whose extension handler (or watcher) the kernel is running now: the tool
33
+ * registry marks the very object it passes to the extension before the call and ends the mark
34
+ * when the handler settles or the kernel gives up on it (its signal aborts); each watcher run of a
35
+ * watched wait gets its own mark the same way. A
36
+ * copy of a context (`{ ...call }`), one kept past its handler, or one built from strings is not
37
+ * live. Host device services admit a tool scope only for a live call. A `WeakSet` keyed by the
38
+ * object: per call and per process, like the scope itself.
39
+ */
40
+ const liveCalls = new WeakSet();
41
+ /** Marks `ctx` live while the kernel runs its handler ({@link isLiveCall}). */
42
+ export function markCallLive(ctx) {
43
+ liveCalls.add(ctx);
44
+ }
45
+ /** Ends the live mark of `ctx`: its handler settled, or the kernel gave up on it. */
46
+ export function endCall(ctx) {
47
+ liveCalls.delete(ctx);
48
+ }
49
+ /** Whether `ctx` is a call context the kernel issued and whose handler is running now. */
50
+ export function isLiveCall(ctx) {
51
+ return typeof ctx === "object" && ctx !== null && liveCalls.has(ctx);
52
+ }
31
53
  /**
32
54
  * Runs `fn` as a device start of the call ({@link CallScope.starting}); a context without a scope
33
55
  * runs it as it is.
@@ -24,6 +24,7 @@ import { resolveRoster } from "../runtime/subagents/roster.js";
24
24
  import { AGENT_BUILTIN_NAMES, AGENT_TOOL, BASH_COMPANION_TOOLS, BUILTIN, SEND_MESSAGE, SKILL_LOAD, SUBAGENT_HANDBACK, TOOL_SEARCH, } from "./builtin-names.js";
25
25
  import { agentToolSpec } from "./builtins/agent.js";
26
26
  import { BuiltinTools } from "./builtins/builtin-tools.js";
27
+ import { endCall, markCallLive } from "./call-scope.js";
27
28
  import { canonicalJson } from "./canonical-json.js";
28
29
  import { connectorSetups } from "./connector-setup.js";
29
30
  import { Credentials } from "./credentials.js";
@@ -201,7 +202,7 @@ let ToolRegistry = class ToolRegistry {
201
202
  .find((x) => x.plugin === source.plugin && x.spec.name === source.name);
202
203
  if (!t)
203
204
  return undefined;
204
- return (input, ctx) => t.inflight.run(ctx.signal, (signal) => t.handler(input, { ...ctx, signal }));
205
+ return (input, ctx) => t.inflight.run(ctx.signal, (signal) => whileLive({ ...ctx, signal }, (call) => t.handler(input, call)));
205
206
  }
206
207
  return undefined;
207
208
  }
@@ -219,7 +220,7 @@ let ToolRegistry = class ToolRegistry {
219
220
  const watch = t?.watch;
220
221
  if (t === undefined || watch === undefined)
221
222
  return undefined;
222
- return (ctx) => t.inflight.run(ctx.signal, (signal) => watch({ ...ctx, signal }));
223
+ return (ctx) => t.inflight.run(ctx.signal, (signal) => whileLive({ ...ctx, signal }, (call) => watch(call)));
223
224
  }
224
225
  /** The registered builtin tools' specs (display metadata for `tools/info.ts`). */
225
226
  builtinSpecs() {
@@ -688,3 +689,20 @@ export function filterSubagentTools(tools, filter) {
688
689
  const keep = (key) => !deny.has(key) && (allow === null || allow.has(key));
689
690
  return tools.filter((t) => (companions.has(t.key) ? keep(BUILTIN.Bash) : keep(t.key)));
690
691
  }
692
+ /**
693
+ * Runs an extension's handler (or watcher) with `call` live ({@link markCallLive}): the very
694
+ * object the extension receives, until the handler settles or the kernel gives up on it (its
695
+ * signal aborts, as on a timeout or a stop).
696
+ */
697
+ async function whileLive(call, fn) {
698
+ markCallLive(call);
699
+ const end = () => endCall(call);
700
+ call.signal.addEventListener("abort", end, { once: true });
701
+ try {
702
+ return await fn(call);
703
+ }
704
+ finally {
705
+ call.signal.removeEventListener("abort", end);
706
+ endCall(call);
707
+ }
708
+ }
package/dist/ui/views.js CHANGED
@@ -12,6 +12,7 @@ import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { isAgentVisibleIn } from "../agents/agent-lookup.js";
14
14
  import { ConversationsService } from "../conversations/conversations.service.js";
15
+ import { issuePersonHandle, revokePersonHandle } from "../device-access/person-handles.js";
15
16
  import { ApiError } from "../errors.js";
16
17
  import { EffectiveConfigs, NEEDS_CONFIG_REASON } from "../extensions/effective-config.js";
17
18
  import { ExtensionHost } from "../extensions/host.js";
@@ -446,13 +447,23 @@ let UiViews = class UiViews {
446
447
  throw new ApiError("validation_failed", `payload must be at most ${UI_LIMITS.payloadBytes} bytes as JSON`);
447
448
  }
448
449
  const action = entry.action;
449
- const r = await this.call(t, "action", (signal) => action({
450
- ...args,
451
- signal,
452
- actionId: input.actionId,
453
- ...(input.payload !== undefined && { payload: input.payload }),
454
- ...(input.answer !== undefined && { answer: input.answer }),
455
- }));
450
+ // an org action runs for its person: a kernel-issued handle, live only while it runs
451
+ const person = args.scope === "platform" ? undefined : issuePersonHandle(args.orgId, args.accountId);
452
+ let r;
453
+ try {
454
+ r = await this.call(t, "action", (signal) => action({
455
+ ...args,
456
+ signal,
457
+ actionId: input.actionId,
458
+ ...(person !== undefined && { person }),
459
+ ...(input.payload !== undefined && { payload: input.payload }),
460
+ ...(input.answer !== undefined && { answer: input.answer }),
461
+ }));
462
+ }
463
+ finally {
464
+ if (person !== undefined)
465
+ revokePersonHandle(person);
466
+ }
456
467
  const component = entry.contribution.kind === "component";
457
468
  this.check(t, "action", actionResultProblems(r, component));
458
469
  const res = r;
@@ -499,7 +510,24 @@ let UiViews = class UiViews {
499
510
  failCode: "ui.query_failed",
500
511
  timeoutCode: "ui.query_timeout",
501
512
  failMessage: `Plugin ${t.plugin} failed to answer query ${input.query} of ${t.id}`,
502
- fn: (signal) => handler({ ...resolved.args, query: input.query, params, signal }),
513
+ fn: async (signal) => {
514
+ const a = resolved.args;
515
+ // an org query runs for its person: a kernel-issued handle, live only while it runs
516
+ const person = a.scope === "platform" ? undefined : issuePersonHandle(a.orgId, a.accountId);
517
+ try {
518
+ return await handler({
519
+ ...a,
520
+ query: input.query,
521
+ params,
522
+ signal,
523
+ ...(person !== undefined && { person }),
524
+ });
525
+ }
526
+ finally {
527
+ if (person !== undefined)
528
+ revokePersonHandle(person);
529
+ }
530
+ },
503
531
  });
504
532
  let json;
505
533
  try {