@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
@@ -4,3 +4,8 @@
4
4
  * imports the host back).
5
5
  */
6
6
  export declare const DEVICE_ACCESS_BACKEND: unique symbol;
7
+ /**
8
+ * The token the extension host finds `ServiceEvents` by at the time of use (`ctx.devices.
9
+ * serviceEvent`), for the same reason: its module imports the extensions module.
10
+ */
11
+ export declare const SERVICE_EVENTS_BACKEND: unique symbol;
@@ -4,3 +4,8 @@
4
4
  * imports the host back).
5
5
  */
6
6
  export const DEVICE_ACCESS_BACKEND = Symbol("DEVICE_ACCESS_BACKEND");
7
+ /**
8
+ * The token the extension host finds `ServiceEvents` by at the time of use (`ctx.devices.
9
+ * serviceEvent`), for the same reason: its module imports the extensions module.
10
+ */
11
+ export const SERVICE_EVENTS_BACKEND = Symbol("SERVICE_EVENTS_BACKEND");
@@ -11,6 +11,7 @@ import { randomUUID } from "node:crypto";
11
11
  import { pluginDescription, validateAllowHost, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
+ import { oweHostServicesStopOnDevices } from "../device-access/host-service-stop.js";
14
15
  import { revokeSiteGrantsOfDevice } from "../device-access/site-grants.js";
15
16
  import { DialInHandlers } from "../dial-in/handlers.js";
16
17
  import { DialInMachines } from "../dial-in/machines.js";
@@ -785,6 +786,8 @@ let DevicesService = class DevicesService {
785
786
  // its loopback port grants end with it (browser loopback port grants design §4)
786
787
  await revokeLoopbackGrantsOfDevice(this.db.db, this.outbox, { orgId, deviceId: id });
787
788
  await revokeSiteGrantsOfDevice(this.db.db, { orgId, deviceId: id });
789
+ // its host services end with it (local agents spec, call 5): a removal and an erasure alike
790
+ await oweHostServicesStopOnDevices(this.db.db, this.outbox, { orgId, deviceIds: [id] });
788
791
  await oweDeviceDestroy(this.outbox, id, orgId);
789
792
  }
790
793
  /**
@@ -20,12 +20,12 @@ export declare class DialInAccess {
20
20
  private streams;
21
21
  constructor(kdb: KernelDb, relay: Pick<DialInRelay, "request" | "online" | "capacity" | "stop">);
22
22
  /**
23
- * Whether `deviceId` is a live device (in a live org) whose `devices.provider` is `plugin`, and
24
- * `plugin` is enabled in the device's org. Read from PG at every call. The full availability
25
- * check (valid org and effective config, `DeviceProviderSelection.isOnInOrg`) runs at the
26
- * machine's hello; this one stays below the extension host's module.
23
+ * The org of a live device served by this provider, if the provider is enabled there.
24
+ * An org-bound call can only find a device of its own org. Deployment callbacks resolve the
25
+ * owner from the registered device before entering its org. The full availability check
26
+ * (valid org and effective config) runs at the machine's hello.
27
27
  */
28
- serves(plugin: string, deviceId: string): Promise<boolean>;
28
+ servedOrg(plugin: string, deviceId: string): Promise<string | undefined>;
29
29
  /** {@link DialInRelay.request} with only the options an extension may pass. */
30
30
  request(deviceId: string, body: unknown, opts: Pick<DialInRequestOptions, "timeoutMs" | "signal">): Promise<unknown>;
31
31
  online(deviceId: string): Promise<boolean>;
@@ -11,6 +11,7 @@ import { DeviceOfflineError, DialInStreamElsewhereError, } from "@capybara-hq/pl
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { isExtensionEnabled } from "../extensions/enabled.js";
13
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { asPlatform, currentScope, withOrgScope } from "../infra/database/org-scope.js";
14
15
  import { DialInRelay } from "./relay.js";
15
16
  /**
16
17
  * What `ctx.dialIn` is built from (`ctx/create-ctx.ts`): the relay, and the check that a device is
@@ -30,23 +31,29 @@ let DialInAccess = class DialInAccess {
30
31
  this.relay = relay;
31
32
  }
32
33
  /**
33
- * Whether `deviceId` is a live device (in a live org) whose `devices.provider` is `plugin`, and
34
- * `plugin` is enabled in the device's org. Read from PG at every call. The full availability
35
- * check (valid org and effective config, `DeviceProviderSelection.isOnInOrg`) runs at the
36
- * machine's hello; this one stays below the extension host's module.
34
+ * The org of a live device served by this provider, if the provider is enabled there.
35
+ * An org-bound call can only find a device of its own org. Deployment callbacks resolve the
36
+ * owner from the registered device before entering its org. The full availability check
37
+ * (valid org and effective config) runs at the machine's hello.
37
38
  */
38
- async serves(plugin, deviceId) {
39
- const row = await this.kdb.db
39
+ async servedOrg(plugin, deviceId) {
40
+ const scope = currentScope();
41
+ const find = () => this.kdb.db
40
42
  .selectFrom("devices as d")
41
43
  .innerJoin("orgs as o", "o.id", "d.org_id")
42
- .select(["d.org_id", "d.provider"])
44
+ .select("d.org_id")
43
45
  .where("d.id", "=", deviceId)
46
+ .where("d.provider", "=", plugin)
44
47
  .where("d.deleted_at", "is", null)
45
- .where("o.deleted_at", "is", null)
46
- .executeTakeFirst();
47
- if (!row || row.provider !== plugin)
48
- return false;
49
- return isExtensionEnabled(this.kdb.db, row.org_id, plugin);
48
+ .where("o.deleted_at", "is", null);
49
+ const device = scope?.kind === "org"
50
+ ? await find().where("d.org_id", "=", scope.orgId).executeTakeFirst()
51
+ : await asPlatform("resolve the device served by a dial-in provider", () => find().executeTakeFirst());
52
+ if (device === undefined)
53
+ return undefined;
54
+ const orgId = device.org_id;
55
+ const enabled = await withOrgScope(orgId, () => isExtensionEnabled(this.kdb.db, orgId, plugin));
56
+ return enabled ? orgId : undefined;
50
57
  }
51
58
  /** {@link DialInRelay.request} with only the options an extension may pass. */
52
59
  request(deviceId, body, opts) {
@@ -479,7 +479,7 @@ class DeviceConnection {
479
479
  const signal = AbortSignal.any([this.ended.signal, AbortSignal.timeout(HELLO_TIMEOUT_MS)]);
480
480
  let timer;
481
481
  try {
482
- const answer = serving.handler.onHello(this.deviceId, body, signal, this.info());
482
+ const answer = this.inOrg(() => serving.handler.onHello(this.deviceId, body, signal, this.info()));
483
483
  const r = await Promise.race([
484
484
  answer,
485
485
  new Promise((_, reject) => {
@@ -842,7 +842,11 @@ class DeviceConnection {
842
842
  }
843
843
  /** The machine and connection a provider callback is about (a fresh object per call). */
844
844
  info() {
845
- return { machineId: this.identity.machineId, connectionId: this.connectionId };
845
+ return {
846
+ machineId: this.identity.machineId,
847
+ connectionId: this.connectionId,
848
+ orgId: this.identity.orgId,
849
+ };
846
850
  }
847
851
  /** The provider's `onClose`, after the lease is handed back; its failure is only logged. */
848
852
  tellClosed() {
@@ -1,6 +1,7 @@
1
1
  import type { ExtensionContext } from "@capybara-hq/plugin-sdk";
2
2
  import { KernelDb } from "../infra/database/kernel-db.js";
3
3
  import { TransactionHost } from "../infra/database/transaction-host.js";
4
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
4
5
  import type { KernelLogger } from "../log.js";
5
6
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
6
7
  import { DialInRelay } from "./relay.js";
@@ -56,7 +57,11 @@ export declare class DialInMachines {
56
57
  private readonly bus;
57
58
  private readonly log;
58
59
  private readonly ceilings;
59
- constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<DialInRelay, "stop">, bus: ExtensionContext["bus"], log: Pick<KernelLogger, "warn">, ceilings: PermissionCeilingWrites);
60
+ /** The delivery of host service stops owed to a machine that connects again. */
61
+ private readonly outbox;
62
+ constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<DialInRelay, "stop">, bus: ExtensionContext["bus"], log: Pick<KernelLogger, "warn">, ceilings: PermissionCeilingWrites,
63
+ /** The delivery of host service stops owed to a machine that connects again. */
64
+ outbox: Pick<OutboxService, "add">);
60
65
  /**
61
66
  * A new machine for the device and its credential (returned once). Revokes the
62
67
  * device's active machine first. Joins the caller's transaction (the device confirmation),
@@ -101,7 +106,9 @@ export declare class DialInMachines {
101
106
  * What a machine's hello envelope says about its program, recorded once the connection holds the
102
107
  * device's lease (before the provider's `onHello`): its version, OS and architecture, and the
103
108
  * host's boot identity (none clears the stored one). Marks the machine seen. A revoked machine
104
- * is left alone.
109
+ * is left alone. A device with host service stops still owed (its extension was switched off
110
+ * while the machine was away) owes their delivery now: requests to the machine wait for its
111
+ * `ready`, so the stop reaches it once this connection is up.
105
112
  */
106
113
  recordConnect(machineId: string, program: {
107
114
  version: string;
@@ -11,11 +11,13 @@ import { randomBytes } from "node:crypto";
11
11
  import { isDeviceBootId } from "@capybara-hq/plugin-sdk/device-protocol";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
+ import { latestMark, owedMarkMicros, oweHostServicesDelivery, } from "../device-access/host-service-stop.js";
14
15
  import { sha256Hex } from "../identity/hash.js";
15
16
  import { afterCommit } from "../infra/database/after-commit.js";
16
17
  import { KernelDb } from "../infra/database/kernel-db.js";
17
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
18
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
20
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
19
21
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
20
22
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
21
23
  import { deviceRevokedTopic } from "./keys.js";
@@ -41,13 +43,17 @@ let DialInMachines = class DialInMachines {
41
43
  bus;
42
44
  log;
43
45
  ceilings;
44
- constructor(db, txHost, relay, bus, log, ceilings) {
46
+ outbox;
47
+ constructor(db, txHost, relay, bus, log, ceilings,
48
+ /** The delivery of host service stops owed to a machine that connects again. */
49
+ outbox) {
45
50
  this.db = db;
46
51
  this.txHost = txHost;
47
52
  this.relay = relay;
48
53
  this.bus = bus;
49
54
  this.log = log;
50
55
  this.ceilings = ceilings;
56
+ this.outbox = outbox;
51
57
  }
52
58
  /**
53
59
  * A new machine for the device and its credential (returned once). Revokes the
@@ -165,11 +171,13 @@ let DialInMachines = class DialInMachines {
165
171
  * What a machine's hello envelope says about its program, recorded once the connection holds the
166
172
  * device's lease (before the provider's `onHello`): its version, OS and architecture, and the
167
173
  * host's boot identity (none clears the stored one). Marks the machine seen. A revoked machine
168
- * is left alone.
174
+ * is left alone. A device with host service stops still owed (its extension was switched off
175
+ * while the machine was away) owes their delivery now: requests to the machine wait for its
176
+ * `ready`, so the stop reaches it once this connection is up.
169
177
  */
170
178
  // org-filter: machineId is the connection's authenticated machine credential, not caller input
171
179
  async recordConnect(machineId, program) {
172
- await this.db
180
+ const machine = await this.db
173
181
  .updateTable("device_machines")
174
182
  .set({
175
183
  program_version: program.version,
@@ -180,7 +188,21 @@ let DialInMachines = class DialInMachines {
180
188
  })
181
189
  .where("id", "=", machineId)
182
190
  .where("revoked_at", "is", null)
191
+ .returning(["org_id", "device_id"])
192
+ .executeTakeFirst();
193
+ if (machine === undefined)
194
+ return;
195
+ const owed = await this.db
196
+ .selectFrom("device_host_services")
197
+ .select(owedMarkMicros.as("mark"))
198
+ .where("org_id", "=", machine.org_id)
199
+ .where("device_id", "=", machine.device_id)
200
+ .where("stop_owed_at", "is not", null)
183
201
  .execute();
202
+ // under the latest mark: reconnects with nothing newly owed stay one delivery
203
+ const mark = latestMark(owed);
204
+ if (mark !== null)
205
+ await oweHostServicesDelivery(this.outbox, { orgId: machine.org_id, deviceId: machine.device_id }, mark);
184
206
  }
185
207
  /** Marks the machine seen (a ping); writes at most once every 60 seconds. */
186
208
  // org-filter: machineId is the connection's authenticated machine credential, not caller input
@@ -328,7 +350,8 @@ DialInMachines = __decorate([
328
350
  __param(2, Inject(DialInRelay)),
329
351
  __param(3, Inject(KERNEL_BUS)),
330
352
  __param(4, Inject(KERNEL_LOGGER)),
331
- __param(5, Inject(PermissionCeilingWrites))
353
+ __param(5, Inject(PermissionCeilingWrites)),
354
+ __param(6, Inject(OutboxService))
332
355
  ], DialInMachines);
333
356
  export { DialInMachines };
334
357
  /** Two machine rows (or a login) name the same machine: same name, OS and arch. */
@@ -16,7 +16,13 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
16
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
17
17
  import { PURGE_BATCH_SIZE } from "../retention/purge-batch.js";
18
18
  import { orgCatalogDrift } from "./org-catalog.js";
19
+ // The device is deleted before these go: its owed host service stops are settled on the
20
+ // device-side guarantee (the deleted device's machine is closed or refused, and capybara-device
21
+ // stops every host service at that terminal end), as the stop delivery settles them.
19
22
  const dependents = [
23
+ ["device_service_events", "extension, service, seq"],
24
+ ["device_service_event_cursors", "extension, service"],
25
+ ["device_host_services", "extension, service"],
20
26
  ["device_defaults", "account_id"],
21
27
  ["device_machines", "id"],
22
28
  ["device_loopback_grants", "id"],
@@ -36,9 +42,12 @@ const scopedDeviceReferences = [
36
42
  "conversations",
37
43
  "device_conversation_notices",
38
44
  "device_defaults",
45
+ "device_host_services",
39
46
  "device_instances",
40
47
  "device_loopback_grants",
41
48
  "device_machines",
49
+ "device_service_event_cursors",
50
+ "device_service_events",
42
51
  "device_site_grants",
43
52
  "permission_call_grants",
44
53
  "sandbox_operation_intents",
@@ -114,6 +123,9 @@ let AccountDeviceCleanup = class AccountDeviceCleanup {
114
123
  UNION ALL SELECT FROM capybara.sandbox_operation_intents WHERE device_id=${device.id}
115
124
  UNION ALL SELECT FROM capybara.device_conversation_notices WHERE device_id=${device.id}
116
125
  UNION ALL SELECT FROM capybara.device_instances WHERE device_id=${device.id} AND org_id<>${orgId}
126
+ UNION ALL SELECT FROM capybara.device_host_services WHERE device_id=${device.id} AND org_id<>${orgId}
127
+ UNION ALL SELECT FROM capybara.device_service_events WHERE device_id=${device.id} AND org_id<>${orgId}
128
+ UNION ALL SELECT FROM capybara.device_service_event_cursors WHERE device_id=${device.id} AND org_id<>${orgId}
117
129
  UNION ALL SELECT FROM capybara.device_defaults WHERE device_id=${device.id}
118
130
  AND (org_id<>${orgId} OR account_id<>${accountId})
119
131
  UNION ALL SELECT FROM capybara.device_machines WHERE device_id=${device.id}
@@ -1,5 +1,5 @@
1
1
  import { sql } from "kysely";
2
- // PostgreSQL 17 after 0221. Re-review the ownership map before updating this fingerprint.
2
+ // PostgreSQL 17 after 0223. Re-review the ownership map before updating this fingerprint.
3
3
  // It includes relation/column identities and ordered PK, UNIQUE and inbound/outbound FK
4
4
  // columns and actions, including FKs from outside the kernel schema.
5
5
  export async function orgCatalogDrift(db) {
@@ -30,5 +30,5 @@ WITH catalog AS (
30
30
  )
31
31
  SELECT md5(string_agg(entry, chr(10) ORDER BY entry COLLATE "C")) AS fingerprint FROM catalog
32
32
  `.execute(db);
33
- return rows[0]?.fingerprint === "adf4514170b69e9a455891eacd3b9d03" ? undefined : "schema-drift";
33
+ return rows[0]?.fingerprint === "e1db306cfaad233fd8970147ed2ca6a4" ? undefined : "schema-drift";
34
34
  }
@@ -73,6 +73,12 @@ export const rowRules = [
73
73
  rule("sessions", "id", "current_org_id = (SELECT id FROM subject)"),
74
74
  epochRule,
75
75
  rule("device_defaults", "org_id, account_id"),
76
+ // A deleted device's owed host service stops are settled on the device-side guarantee: its
77
+ // revoked machine is closed (4003) or refused (401) and capybara-device stops every host
78
+ // service at that terminal end. The machine revocation is verified before these rows go.
79
+ rule("device_service_events", "device_id, extension, service, seq"),
80
+ rule("device_service_event_cursors", "device_id, extension, service"),
81
+ rule("device_host_services", "device_id, extension, service"),
76
82
  rule("device_generation_high_water", "device_id", "device_id::text IN (SELECT id FROM capybara.devices WHERE org_id = (SELECT id FROM subject))"),
77
83
  rule("device_instance_destructions", "device_id, provider, instance_generation", "device_id IN (SELECT id FROM capybara.devices WHERE org_id = (SELECT id FROM subject))"),
78
84
  rule("device_loopback_grants", "id"),
@@ -165,9 +171,12 @@ export const childReferences = {
165
171
  ["automations", "child.device_id = parent.id"],
166
172
  ["device_conversation_notices", "child.device_id = parent.id"],
167
173
  ["device_defaults", "child.device_id = parent.id"],
174
+ ["device_host_services", "child.device_id = parent.id"],
168
175
  ["device_loopback_grants", "child.device_id = parent.id"],
169
176
  ["device_machines", "child.device_id = parent.id"],
170
177
  ["device_projects", "child.device_id = parent.id"],
178
+ ["device_service_event_cursors", "child.device_id = parent.id"],
179
+ ["device_service_events", "child.device_id = parent.id"],
171
180
  ["device_site_grants", "child.device_id = parent.id"],
172
181
  ],
173
182
  agent_templates: [["agent_template_versions", "child.template_id = parent.id"]],
package/dist/errors.d.ts CHANGED
@@ -105,6 +105,7 @@ export declare const ERROR_CODES: {
105
105
  * Platform tool (only lowering and removing).
106
106
  */
107
107
  readonly "deployment.sharing_widen_not_allowed": 400;
108
+ readonly "deployment.publisher_policy_requires_session": 403;
108
109
  /** No live share with this code (unknown, revoked, expired, or its creator lost access). */
109
110
  readonly "share.not_found": 404;
110
111
  /** An internal share opened without a session: sign in as a member of its org. */
@@ -316,6 +317,7 @@ export declare const ERROR_CODES: {
316
317
  readonly "marketplace.fetch_failed": 502;
317
318
  readonly "marketplace.invalid": 502;
318
319
  readonly "marketplace.integrity_mismatch": 502;
320
+ readonly "marketplace.publisher_unverified": 502;
319
321
  readonly "marketplace.private_address": 422;
320
322
  readonly "marketplace.redirect": 422;
321
323
  readonly "marketplace.incompatible": 409;
package/dist/errors.js CHANGED
@@ -105,6 +105,7 @@ export const ERROR_CODES = {
105
105
  * Platform tool (only lowering and removing).
106
106
  */
107
107
  "deployment.sharing_widen_not_allowed": 400,
108
+ "deployment.publisher_policy_requires_session": 403,
108
109
  /** No live share with this code (unknown, revoked, expired, or its creator lost access). */
109
110
  "share.not_found": 404,
110
111
  /** An internal share opened without a session: sign in as a member of its org. */
@@ -316,6 +317,7 @@ export const ERROR_CODES = {
316
317
  "marketplace.fetch_failed": 502,
317
318
  "marketplace.invalid": 502,
318
319
  "marketplace.integrity_mismatch": 502,
320
+ "marketplace.publisher_unverified": 502,
319
321
  "marketplace.private_address": 422,
320
322
  "marketplace.redirect": 422,
321
323
  "marketplace.incompatible": 409,
@@ -15,6 +15,7 @@ import { itemRemovedError } from "../catalog/ownership.js";
15
15
  import { oweDeployedExtensionSync } from "../catalog/scope-jobs.js";
16
16
  import { pluginSchemaName } from "../ctx/create-ctx.js";
17
17
  import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
18
+ import { oweHostServicesStop } from "../device-access/host-service-stop.js";
18
19
  import { revokeSiteGrantsOfExtensionEverywhere } from "../device-access/site-grants.js";
19
20
  import { ApiError } from "../errors.js";
20
21
  import { audit } from "../identity/audit.js";
@@ -295,8 +296,10 @@ let ExtensionAdminOps = class ExtensionAdminOps {
295
296
  ...ownerDetail(opts.owner),
296
297
  });
297
298
  afterCommit(() => this.notify(name));
298
- if (leftDisabled !== undefined)
299
+ if (leftDisabled !== undefined) {
300
+ await oweHostServicesStop(db, this.outbox, { extension: name });
299
301
  return { changed: true, state: "disabled", leftDisabled };
302
+ }
300
303
  // A new version of an enabled extension is a deploy: it owes its plugin's scope sync
301
304
  if (row?.desired_state === "enabled")
302
305
  await oweDeployedExtensionSync(this.outbox, db, name);
@@ -409,8 +412,11 @@ let ExtensionAdminOps = class ExtensionAdminOps {
409
412
  })
410
413
  .where("name", "=", name)
411
414
  .execute();
412
- if (state === "disabled")
415
+ if (state === "disabled") {
413
416
  await revokeSiteGrantsOfExtensionEverywhere(db, name);
417
+ // its host services stop on every machine that runs one (local agents spec, call 5)
418
+ await oweHostServicesStop(db, this.outbox, { extension: name });
419
+ }
414
420
  await this.audit(actor, actorTokenId, state === "enabled" ? "extension.enabled" : "extension.disabled", name, row.version, row.sha256, { ...ownerDetail(owner), ...auditDetail });
415
421
  afterCommit(() => this.notify(name));
416
422
  // The enable is the deploy: it owes its plugin's scope sync, which installs it where its scope
@@ -3,7 +3,10 @@ import type { KernelDatabase, KernelSchemaDb } from "../db/kernel-schema.js";
3
3
  /**
4
4
  * The device service ids (`<extension>.<name>`, `deviceServiceId`) the deployment's approved
5
5
  * extensions declare in `permissions.deviceAccess.services`, by {@link deployedSnapshot} (the approved version is the one installed enabled or served),
6
- * whatever any org enabled. Sorted; a pair that is not a valid service id is left out.
6
+ * whatever any org enabled. Sorted; a pair that is not a valid service id is left out. A host
7
+ * service (also listed in `permissions.deviceAccess.hostServices`) is not counted: it runs on the
8
+ * person's machine outside any instance, no instance restores it, and the conversation-deleted
9
+ * notice is never sent to it.
7
10
  */
8
11
  export declare function queryDeclaredDeviceServices(db: KernelSchemaDb): Promise<string[]>;
9
12
  /**
@@ -3,7 +3,10 @@ import { sql } from "kysely";
3
3
  /**
4
4
  * The device service ids (`<extension>.<name>`, `deviceServiceId`) the deployment's approved
5
5
  * extensions declare in `permissions.deviceAccess.services`, by {@link deployedSnapshot} (the approved version is the one installed enabled or served),
6
- * whatever any org enabled. Sorted; a pair that is not a valid service id is left out.
6
+ * whatever any org enabled. Sorted; a pair that is not a valid service id is left out. A host
7
+ * service (also listed in `permissions.deviceAccess.hostServices`) is not counted: it runs on the
8
+ * person's machine outside any instance, no instance restores it, and the conversation-deleted
9
+ * notice is never sent to it.
7
10
  */
8
11
  export async function queryDeclaredDeviceServices(db) {
9
12
  const rows = await db
@@ -11,6 +14,7 @@ export async function queryDeclaredDeviceServices(db) {
11
14
  .select([
12
15
  "s.plugin",
13
16
  sql `s.permissions -> 'permissions' -> 'deviceAccess' -> 'services'`.as("services"),
17
+ sql `s.permissions -> 'permissions' -> 'deviceAccess' -> 'hostServices'`.as("hostServices"),
14
18
  ])
15
19
  .where(sql `jsonb_typeof(s.permissions -> 'permissions' -> 'deviceAccess' -> 'services') = 'array'`)
16
20
  .where(deployedSnapshot)
@@ -19,8 +23,9 @@ export async function queryDeclaredDeviceServices(db) {
19
23
  for (const r of rows) {
20
24
  if (!Array.isArray(r.services))
21
25
  continue;
26
+ const host = new Set(Array.isArray(r.hostServices) ? r.hostServices : []);
22
27
  for (const name of r.services) {
23
- if (typeof name !== "string")
28
+ if (typeof name !== "string" || host.has(name))
24
29
  continue;
25
30
  try {
26
31
  ids.add(deviceServiceId(r.plugin, name));
@@ -8,7 +8,8 @@ import { type DeviceAccessBackend, type InboxBackend, type PluginReadsBackend, t
8
8
  import { type ExtensionNetSeams } from "../ctx/net.js";
9
9
  import type { Keyring } from "../ctx/secrets.js";
10
10
  import { type ExtensionDbIdentity } from "../db/extension-db.js";
11
- import { DEVICE_ACCESS_BACKEND } from "../device-access/token.js";
11
+ import type { ServiceEventsBackend } from "../device-access/service-events.js";
12
+ import { DEVICE_ACCESS_BACKEND, SERVICE_EVENTS_BACKEND } from "../device-access/token.js";
12
13
  import { DialInAccess } from "../dial-in/access.js";
13
14
  import type { PluginRouteTable } from "../http/plugin-dispatch.js";
14
15
  import { INBOX_ITEMS_BACKEND } from "../inbox/token.js";
@@ -298,12 +299,16 @@ export declare class ExtensionHost {
298
299
  * Absent (a hand-built host) or not found (the CLI): `ctx.deviceAccess` calls are refused.
299
300
  * `TriggerEventsService` (`ctx.triggers`, {@link TRIGGER_EVENTS_BACKEND}) and
300
301
  * `InboxItemsService` (`ctx.inbox`, {@link INBOX_ITEMS_BACKEND}) and `PluginReadsService`
301
- * (`ctx.agents`, `ctx.conversations`, `ctx.people`, {@link PLUGIN_READS_BACKEND}) likewise.
302
+ * (`ctx.agents`, `ctx.conversations`, `ctx.people`, {@link PLUGIN_READS_BACKEND}) and
303
+ * `ServiceEvents` (`ctx.devices.serviceEvent`, {@link SERVICE_EVENTS_BACKEND}) likewise.
302
304
  */
303
305
  modules?: {
304
306
  get(token: typeof DEVICE_ACCESS_BACKEND, opts: {
305
307
  strict: false;
306
308
  }): DeviceAccessBackend;
309
+ get(token: typeof SERVICE_EVENTS_BACKEND, opts: {
310
+ strict: false;
311
+ }): ServiceEventsBackend;
307
312
  get(token: typeof TRIGGER_EVENTS_BACKEND, opts: {
308
313
  strict: false;
309
314
  }): TriggersBackend;
@@ -23,7 +23,7 @@ import { transferKnownExtensionSchemas } from "../db/extension-schema-transfer.j
23
23
  import { kernelDb } from "../db/kernel-schema.js";
24
24
  import { migrate } from "../db/migrator.js";
25
25
  import { createDb } from "../db/pool.js";
26
- import { DEVICE_ACCESS_BACKEND } from "../device-access/token.js";
26
+ import { DEVICE_ACCESS_BACKEND, SERVICE_EVENTS_BACKEND } from "../device-access/token.js";
27
27
  import { DialInAccess } from "../dial-in/access.js";
28
28
  import { INBOX_ITEMS_BACKEND } from "../inbox/token.js";
29
29
  import { waitWithin } from "../infra/close-within.js";
@@ -450,7 +450,8 @@ let ExtensionHost = class ExtensionHost {
450
450
  * Absent (a hand-built host) or not found (the CLI): `ctx.deviceAccess` calls are refused.
451
451
  * `TriggerEventsService` (`ctx.triggers`, {@link TRIGGER_EVENTS_BACKEND}) and
452
452
  * `InboxItemsService` (`ctx.inbox`, {@link INBOX_ITEMS_BACKEND}) and `PluginReadsService`
453
- * (`ctx.agents`, `ctx.conversations`, `ctx.people`, {@link PLUGIN_READS_BACKEND}) likewise.
453
+ * (`ctx.agents`, `ctx.conversations`, `ctx.people`, {@link PLUGIN_READS_BACKEND}) and
454
+ * `ServiceEvents` (`ctx.devices.serviceEvent`, {@link SERVICE_EVENTS_BACKEND}) likewise.
454
455
  */
455
456
  modules,
456
457
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
@@ -498,6 +499,14 @@ let ExtensionHost = class ExtensionHost {
498
499
  return undefined;
499
500
  }
500
501
  },
502
+ serviceEvents: () => {
503
+ try {
504
+ return modules?.get(SERVICE_EVENTS_BACKEND, { strict: false });
505
+ }
506
+ catch {
507
+ return undefined;
508
+ }
509
+ },
501
510
  triggers: () => {
502
511
  try {
503
512
  return modules?.get(TRIGGER_EVENTS_BACKEND, { strict: false });
@@ -1,6 +1,7 @@
1
1
  import { type DroppedUiContribution, type ExtensionManifest, type ExtensionPointRef, type ResolvedUiContribution, type StaticExtensionManifest } from "@capybara-hq/plugin-sdk";
2
2
  import { type ExtensionPointAccess, type KernelDeps, type KernelExtensionContext, LiveConfig, type RegisteredSetupCheck, type RegisteredTool, type Route } from "../ctx/create-ctx.js";
3
3
  import type { extensionDbPool } from "../db/extension-db.js";
4
+ import type { ServiceEventHandler } from "../device-access/service-events.js";
4
5
  import type { UiActionHandler, UiQueryHandler, UiRender } from "../ui/registry.js";
5
6
  import type { RegisteredHook } from "./hooks.js";
6
7
  import { InflightTracker } from "./inflight.js";
@@ -82,6 +83,8 @@ export declare class ExtensionInstance {
82
83
  get uiQueries(): ReadonlyMap<string, UiQueryHandler>;
83
84
  /** Setup checks registered through `ctx.setup.check` (empty after revocation). */
84
85
  get setupChecks(): ReadonlyMap<string, RegisteredSetupCheck>;
86
+ /** Handlers registered through `ctx.deviceAccess.onServiceEvent` (empty after revocation). */
87
+ get serviceEventHandlers(): ReadonlyMap<string, ServiceEventHandler>;
85
88
  /** The instance's `ctx.signal`: aborted when it is revoked or disposed. */
86
89
  get signal(): AbortSignal;
87
90
  /** 账上仍在的登记(撤销后为空)。 */
@@ -136,6 +136,10 @@ export class ExtensionInstance {
136
136
  get setupChecks() {
137
137
  return this.ctx.setupChecks;
138
138
  }
139
+ /** Handlers registered through `ctx.deviceAccess.onServiceEvent` (empty after revocation). */
140
+ get serviceEventHandlers() {
141
+ return this.ctx.serviceEventHandlers;
142
+ }
139
143
  /** The instance's `ctx.signal`: aborted when it is revoked or disposed. */
140
144
  get signal() {
141
145
  return this.ctx.signal;
@@ -1,5 +1,5 @@
1
1
  /** 插件经 ctx 做的一项登记的种类(C17)。 */
2
- export type RegistrationKind = "tool" | "route" | "queue" | "bus" | "lease" | "ui.view" | "ui.action" | "ui.query" | "provide" | "hook" | "setup.check";
2
+ export type RegistrationKind = "tool" | "route" | "queue" | "bus" | "lease" | "ui.view" | "ui.action" | "ui.query" | "provide" | "hook" | "setup.check" | "service.event";
3
3
  /** 账上的一项:撤销时调用 `dispose()`。 */
4
4
  export interface Registration {
5
5
  kind: RegistrationKind;
@@ -11,6 +11,7 @@ import { OnWorkerEvent, Processor, WorkerHost } from "@nestjs/bullmq";
11
11
  import { Inject, Injectable, Module } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { withOrgScope } from "../infra/database/org-scope.js";
14
15
  import { TransactionHost } from "../infra/database/transaction-host.js";
15
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
16
17
  import { OutboxService } from "../infra/outbox/outbox.service.js";
@@ -250,9 +251,8 @@ let LifecycleHooksProcessor = class LifecycleHooksProcessor extends WorkerHost {
250
251
  this.log = log;
251
252
  }
252
253
  process(job) {
253
- return runJob(LIFECYCLE_QUEUE, job, () => this.hooks.process(job.data, this.stopping.signal), {
254
- platform: "extension lifecycle hook (deployment-wide)",
255
- });
254
+ // The original job shape already carries the organization inside the durable payload.
255
+ return runJob(LIFECYCLE_QUEUE, job, () => withOrgScope(job.data.payload.orgId, () => this.hooks.process(job.data, this.stopping.signal)));
256
256
  }
257
257
  /** Starts consuming (worker role, after the extensions loaded). */
258
258
  start() {
@@ -11,6 +11,7 @@ import { EXTENSION_POINTS, parseExtensionPoint, } from "@capybara-hq/plugin-sdk"
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { assertItemInstallable, assertPluginSourcesInstallable, disabledPluginItems, pluginItemDisabled, } from "../catalog/request-rules.js";
13
13
  import { oweTemplateConnectors } from "../catalog/template-connector-jobs.js";
14
+ import { oweHostServicesStop } from "../device-access/host-service-stop.js";
14
15
  import { revokeSiteGrantsOfExtension } from "../device-access/site-grants.js";
15
16
  import { ApiError } from "../errors.js";
16
17
  import { audit } from "../identity/audit.js";
@@ -293,8 +294,11 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
293
294
  updated_at: new Date(),
294
295
  }))
295
296
  .execute();
296
- if (!enabled)
297
+ if (!enabled) {
297
298
  await revokeSiteGrantsOfExtension(t, { orgId, extensionName: plugin });
299
+ // its host services on the org's machines stop (local agents spec, call 5)
300
+ await oweHostServicesStop(t, this.outbox, { orgId, extension: plugin });
301
+ }
298
302
  // Switched on: it may provide the connector kind of a template whose plugin is installed in
299
303
  // the org without its connector; a worker creates the connectors it never had, once the
300
304
  // extension is loaded there (ruling R27)
@@ -414,6 +418,7 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
414
418
  if (!r)
415
419
  return false;
416
420
  await revokeSiteGrantsOfExtension(t, { orgId, extensionName: plugin });
421
+ await oweHostServicesStop(t, this.outbox, { orgId, extension: plugin });
417
422
  await audit(t, {
418
423
  actorAccountId,
419
424
  orgId,
@@ -81,6 +81,8 @@ export interface PermissionSet {
81
81
  services: string[];
82
82
  loopbackPorts?: true;
83
83
  siteAccess?: true;
84
+ /** Services that may run on the owner's machine outside the sandbox: one blocking key each. */
85
+ hostServices?: string[];
84
86
  };
85
87
  /**
86
88
  * The event types the extension may emit (`permissions.triggers.emit`, collaboration spec
@@ -188,6 +190,11 @@ export declare const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
188
190
  * upgrade without approval again. Recorded only when declared.
189
191
  */
190
192
  export declare const DEVICE_LOOPBACK_PORTS_KEY = "permissions.deviceaccess.loopbackports";
193
+ /**
194
+ * Key prefix of a host service (`permissions.deviceAccess.hostServices`): the service runs on the
195
+ * owner's machine outside the sandbox; sensitive and blocking like any device service key.
196
+ */
197
+ export declare const DEVICE_HOST_KEY_PREFIX = "permissions.deviceaccess.host:";
191
198
  /** Blocking permission for profile decisions on non-loopback site actions. */
192
199
  export declare const DEVICE_SITE_ACCESS_KEY = "permissions.deviceaccess.siteaccess";
193
200
  /**