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

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 (173) 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/automations/events/trigger-events.service.d.ts +13 -1
  11. package/dist/automations/events/trigger-events.service.js +27 -14
  12. package/dist/catalog/catalog.service.d.ts +2 -0
  13. package/dist/catalog/catalog.service.js +28 -5
  14. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  15. package/dist/catalog/marketplace-fetch.js +15 -0
  16. package/dist/catalog/marketplaces.service.d.ts +4 -4
  17. package/dist/catalog/marketplaces.service.js +3 -2
  18. package/dist/catalog/owned-items.d.ts +2 -0
  19. package/dist/catalog/owned-items.js +30 -31
  20. package/dist/catalog/ownership.js +40 -38
  21. package/dist/catalog/plugin-import.d.ts +3 -4
  22. package/dist/catalog/plugin-import.js +50 -1
  23. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  24. package/dist/catalog/plugin-upgrade.js +95 -7
  25. package/dist/catalog/publisher-policy.d.ts +9 -0
  26. package/dist/catalog/publisher-policy.js +12 -0
  27. package/dist/catalog/unshare.js +66 -58
  28. package/dist/client/client-access.service.js +5 -3
  29. package/dist/config/schema.d.ts +1 -0
  30. package/dist/config/schema.js +8 -1
  31. package/dist/conversations/conversations.controller.js +4 -14
  32. package/dist/conversations/conversations.service.d.ts +14 -0
  33. package/dist/conversations/conversations.service.js +20 -2
  34. package/dist/ctx/create-ctx.d.ts +15 -2
  35. package/dist/ctx/create-ctx.js +195 -79
  36. package/dist/ctx/durable-cancellation.d.ts +3 -0
  37. package/dist/ctx/durable-cancellation.js +8 -0
  38. package/dist/ctx/durable-effects.service.d.ts +81 -0
  39. package/dist/ctx/durable-effects.service.js +316 -0
  40. package/dist/ctx/durable-envelope.d.ts +24 -0
  41. package/dist/ctx/durable-envelope.js +80 -0
  42. package/dist/ctx/durable-failure.d.ts +7 -0
  43. package/dist/ctx/durable-failure.js +32 -0
  44. package/dist/ctx/durable-job.d.ts +9 -0
  45. package/dist/ctx/durable-job.js +2 -0
  46. package/dist/ctx/durable-keys.d.ts +27 -0
  47. package/dist/ctx/durable-keys.js +138 -0
  48. package/dist/ctx/durable-relay.d.ts +29 -0
  49. package/dist/ctx/durable-relay.js +250 -0
  50. package/dist/ctx/queue.d.ts +2 -0
  51. package/dist/ctx/queue.js +25 -15
  52. package/dist/db/extension-db.js +2 -0
  53. package/dist/db/extension-handoff-schema.d.ts +6 -0
  54. package/dist/db/extension-handoff-schema.js +72 -0
  55. package/dist/db/extension-rls-predicate.d.ts +1 -0
  56. package/dist/db/extension-rls-predicate.js +8 -0
  57. package/dist/db/extension-schema-transfer.d.ts +1 -1
  58. package/dist/db/extension-schema-transfer.js +18 -6
  59. package/dist/db/kernel-schema.d.ts +64 -0
  60. package/dist/db/migrator.js +6 -13
  61. package/dist/db/pool.d.ts +2 -2
  62. package/dist/db/pool.js +2 -2
  63. package/dist/db/sql-statements.d.ts +3 -0
  64. package/dist/db/sql-statements.js +15 -5
  65. package/dist/device-access/device-access.module.js +12 -2
  66. package/dist/device-access/device-access.service.d.ts +30 -2
  67. package/dist/device-access/device-access.service.js +38 -4
  68. package/dist/device-access/host-gate.d.ts +45 -0
  69. package/dist/device-access/host-gate.js +92 -0
  70. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  71. package/dist/device-access/host-service-stop-sweep.js +112 -0
  72. package/dist/device-access/host-service-stop.d.ts +78 -0
  73. package/dist/device-access/host-service-stop.js +144 -0
  74. package/dist/device-access/host-services.d.ts +211 -0
  75. package/dist/device-access/host-services.js +803 -0
  76. package/dist/device-access/person-handles.d.ts +10 -0
  77. package/dist/device-access/person-handles.js +25 -0
  78. package/dist/device-access/service-events.d.ts +199 -0
  79. package/dist/device-access/service-events.js +704 -0
  80. package/dist/device-access/token.d.ts +5 -0
  81. package/dist/device-access/token.js +5 -0
  82. package/dist/devices/devices.service.js +3 -0
  83. package/dist/dial-in/access.d.ts +5 -5
  84. package/dist/dial-in/access.js +19 -12
  85. package/dist/dial-in/gateway.js +6 -2
  86. package/dist/dial-in/machines.d.ts +9 -2
  87. package/dist/dial-in/machines.js +27 -4
  88. package/dist/erasure/device-cleanup.js +12 -0
  89. package/dist/erasure/org-catalog.js +2 -2
  90. package/dist/erasure/org-rules.js +10 -0
  91. package/dist/errors.d.ts +2 -0
  92. package/dist/errors.js +2 -0
  93. package/dist/extensions/admin-ops.js +8 -2
  94. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  95. package/dist/extensions/deployed-snapshots.js +7 -2
  96. package/dist/extensions/extensions.module.js +10 -0
  97. package/dist/extensions/host.d.ts +12 -2
  98. package/dist/extensions/host.js +44 -22
  99. package/dist/extensions/instance.d.ts +5 -0
  100. package/dist/extensions/instance.js +10 -0
  101. package/dist/extensions/ledger.d.ts +1 -1
  102. package/dist/extensions/lifecycle-hooks.js +3 -3
  103. package/dist/extensions/org-config.js +6 -1
  104. package/dist/extensions/permission-set.d.ts +7 -0
  105. package/dist/extensions/permission-set.js +10 -0
  106. package/dist/extensions/permission-view.d.ts +1 -1
  107. package/dist/extensions/permission-view.js +10 -1
  108. package/dist/extensions/sources.d.ts +1 -0
  109. package/dist/extensions/sources.js +9 -0
  110. package/dist/git/tickets.js +32 -27
  111. package/dist/http/app.js +5 -3
  112. package/dist/identity/accounts.d.ts +6 -1
  113. package/dist/identity/accounts.js +11 -2
  114. package/dist/identity/api-tokens.js +7 -6
  115. package/dist/identity/settings.d.ts +9 -1
  116. package/dist/identity/settings.js +16 -1
  117. package/dist/inbox/inbox-items.service.d.ts +5 -0
  118. package/dist/inbox/inbox-items.service.js +57 -33
  119. package/dist/inbox/org-notices.js +3 -2
  120. package/dist/index.d.ts +1 -0
  121. package/dist/index.js +1 -0
  122. package/dist/infra/database/extension-effect-key-lock.d.ts +10 -0
  123. package/dist/infra/database/extension-effect-key-lock.js +69 -0
  124. package/dist/infra/database/extension-handoff.d.ts +27 -0
  125. package/dist/infra/database/extension-handoff.js +113 -0
  126. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  127. package/dist/infra/database/scoped-dialect.js +260 -72
  128. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  129. package/dist/infra/database/startup-activation-transaction.js +3 -2
  130. package/dist/infra/outbox/outbox.dispatcher.d.ts +6 -1
  131. package/dist/infra/outbox/outbox.dispatcher.js +64 -4
  132. package/dist/infra/outbox/outbox.module.js +2 -0
  133. package/dist/infra/outbox/registry.d.ts +40 -0
  134. package/dist/infra/outbox/registry.js +42 -0
  135. package/dist/infra/queue/queue-names.d.ts +1 -1
  136. package/dist/infra/queue/queue-names.js +1 -0
  137. package/dist/infra/queue/run-job.d.ts +4 -1
  138. package/dist/infra/queue/run-job.js +10 -2
  139. package/dist/kernel.js +1 -0
  140. package/dist/kernel.module.js +3 -0
  141. package/dist/orgs/offboarding.js +18 -9
  142. package/dist/orgs/orgs.service.js +16 -0
  143. package/dist/orgs/settings.service.js +3 -0
  144. package/dist/packages/npm-publish-keys.json +27 -0
  145. package/dist/packages/official-publisher.d.ts +19 -0
  146. package/dist/packages/official-publisher.js +152 -0
  147. package/dist/packages/provenance.d.ts +7 -0
  148. package/dist/packages/provenance.js +22 -19
  149. package/dist/packages/sigstore-trusted-root.json +126 -0
  150. package/dist/platform/ops/admin.ops.js +2 -1
  151. package/dist/platform/ops/orgs.ops.js +1 -0
  152. package/dist/roles/worker-role.d.ts +6 -3
  153. package/dist/roles/worker-role.js +12 -4
  154. package/dist/roles/worker.module.js +9 -0
  155. package/dist/runtime/maintenance.d.ts +5 -2
  156. package/dist/runtime/maintenance.js +18 -4
  157. package/dist/sandbox/device-reports.d.ts +4 -4
  158. package/dist/sandbox/device-reports.js +40 -30
  159. package/dist/sandbox/device-services.d.ts +2 -1
  160. package/dist/sandbox/device-services.js +5 -1
  161. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  162. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  163. package/dist/sandbox/permission-config-publication.js +5 -1
  164. package/dist/themes/theme-state.js +24 -13
  165. package/dist/tools/call-scope.d.ts +6 -0
  166. package/dist/tools/call-scope.js +22 -0
  167. package/dist/tools/registry.js +20 -2
  168. package/dist/ui/views.js +36 -8
  169. package/package.json +9 -4
  170. package/src/migrations/0222_device_host_services.sql +27 -0
  171. package/src/migrations/0223_device_service_events.sql +54 -0
  172. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
  173. package/src/migrations/0225_extension_effect_receipts.sql +25 -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 0225. 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 === "3693e0b7004dae3c5721abfadc80e1e8" ? 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"),
@@ -94,6 +100,7 @@ export const rowRules = [
94
100
  ];
95
101
  export const anonymousAccountRule = rule("org_anonymous_accounts", "org_id");
96
102
  export const lateRules = [
103
+ rule("extension_effect_receipts", "org_id, plugin, kind, effect_key"),
97
104
  rule("retention_coverage", "org_id"),
98
105
  rule("audit_events", "id"),
99
106
  rule("outbox", "id"),
@@ -165,9 +172,12 @@ export const childReferences = {
165
172
  ["automations", "child.device_id = parent.id"],
166
173
  ["device_conversation_notices", "child.device_id = parent.id"],
167
174
  ["device_defaults", "child.device_id = parent.id"],
175
+ ["device_host_services", "child.device_id = parent.id"],
168
176
  ["device_loopback_grants", "child.device_id = parent.id"],
169
177
  ["device_machines", "child.device_id = parent.id"],
170
178
  ["device_projects", "child.device_id = parent.id"],
179
+ ["device_service_event_cursors", "child.device_id = parent.id"],
180
+ ["device_service_events", "child.device_id = parent.id"],
171
181
  ["device_site_grants", "child.device_id = parent.id"],
172
182
  ],
173
183
  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));
@@ -5,9 +5,13 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
7
  import { Module } from "@nestjs/common";
8
+ import { TriggerEventsModule } from "../automations/events/events.module.js";
9
+ import { ExtensionEffects } from "../ctx/durable-effects.service.js";
10
+ import { ExtensionEffectKeys } from "../ctx/durable-keys.js";
8
11
  import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
9
12
  import { DialInRelayModule } from "../dial-in/relay.module.js";
10
13
  import { SuperAdminLockModule } from "../identity/super-admin.js";
14
+ import { InboxItemsModule } from "../inbox/inbox-items.service.js";
11
15
  import { ModelsModule } from "../models/models.module.js";
12
16
  import { OrgNetworkAllowancesModule } from "../orgs/network-allowances.service.js";
13
17
  import { OrgLockModule } from "../orgs/org-lock.js";
@@ -46,6 +50,8 @@ ExtensionsModule = __decorate([
46
50
  Module({
47
51
  imports: [
48
52
  ExtensionRegistryModule,
53
+ TriggerEventsModule,
54
+ InboxItemsModule,
49
55
  SuperAdminLockModule,
50
56
  OrgLockModule,
51
57
  StorageModule,
@@ -74,6 +80,8 @@ ExtensionsModule = __decorate([
74
80
  ReplicaStatusStore,
75
81
  ConfiguredExtensionDbIdentity,
76
82
  ExtensionHost,
83
+ ExtensionEffects,
84
+ ExtensionEffectKeys,
77
85
  ExtensionLifecycle,
78
86
  ExtensionAdmin,
79
87
  ExtensionAdminOps,
@@ -95,6 +103,8 @@ ExtensionsModule = __decorate([
95
103
  ReplicaStatusStore,
96
104
  ConfiguredExtensionDbIdentity,
97
105
  ExtensionHost,
106
+ ExtensionEffects,
107
+ ExtensionEffectKeys,
98
108
  ExtensionLifecycle,
99
109
  ExtensionAdmin,
100
110
  ExtensionAdminOps,
@@ -5,10 +5,12 @@ import type { KernelAppOptions } from "../app.js";
5
5
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
6
6
  import type { BusSubscriber } from "../ctx/bus.js";
7
7
  import { type DeviceAccessBackend, type InboxBackend, type PluginReadsBackend, type Route, type TriggersBackend } from "../ctx/create-ctx.js";
8
+ import { ExtensionEffects } from "../ctx/durable-effects.service.js";
8
9
  import { type ExtensionNetSeams } from "../ctx/net.js";
9
10
  import type { Keyring } from "../ctx/secrets.js";
10
11
  import { type ExtensionDbIdentity } from "../db/extension-db.js";
11
- import { DEVICE_ACCESS_BACKEND } from "../device-access/token.js";
12
+ import type { ServiceEventsBackend } from "../device-access/service-events.js";
13
+ import { DEVICE_ACCESS_BACKEND, SERVICE_EVENTS_BACKEND } from "../device-access/token.js";
12
14
  import { DialInAccess } from "../dial-in/access.js";
13
15
  import type { PluginRouteTable } from "../http/plugin-dispatch.js";
14
16
  import { INBOX_ITEMS_BACKEND } from "../inbox/token.js";
@@ -147,6 +149,7 @@ export declare class ExtensionHost {
147
149
  */
148
150
  static migrateOnly(specifiers: string[], opts: {
149
151
  dbUrl: string;
152
+ handoffRuntimeLogin?: string;
150
153
  extensionIdentity?: ExtensionDbIdentity;
151
154
  resolveFrom?: string;
152
155
  connectTimeoutMs?: number;
@@ -298,12 +301,19 @@ export declare class ExtensionHost {
298
301
  * Absent (a hand-built host) or not found (the CLI): `ctx.deviceAccess` calls are refused.
299
302
  * `TriggerEventsService` (`ctx.triggers`, {@link TRIGGER_EVENTS_BACKEND}) and
300
303
  * `InboxItemsService` (`ctx.inbox`, {@link INBOX_ITEMS_BACKEND}) and `PluginReadsService`
301
- * (`ctx.agents`, `ctx.conversations`, `ctx.people`, {@link PLUGIN_READS_BACKEND}) likewise.
304
+ * (`ctx.agents`, `ctx.conversations`, `ctx.people`, {@link PLUGIN_READS_BACKEND}) and
305
+ * `ServiceEvents` (`ctx.devices.serviceEvent`, {@link SERVICE_EVENTS_BACKEND}) likewise.
302
306
  */
303
307
  modules?: {
304
308
  get(token: typeof DEVICE_ACCESS_BACKEND, opts: {
305
309
  strict: false;
306
310
  }): DeviceAccessBackend;
311
+ get(token: typeof SERVICE_EVENTS_BACKEND, opts: {
312
+ strict: false;
313
+ }): ServiceEventsBackend;
314
+ get(token: typeof ExtensionEffects, opts: {
315
+ strict: false;
316
+ }): ExtensionEffects;
307
317
  get(token: typeof TRIGGER_EVENTS_BACKEND, opts: {
308
318
  strict: false;
309
319
  }): TriggersBackend;
@@ -17,13 +17,15 @@ import { ModuleRef } from "@nestjs/core";
17
17
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
18
18
  import { changedPaths, configFields, getPath, secretValues, unreachableSecrets, } from "../config/fields.js";
19
19
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
20
+ import { ExtensionEffects } from "../ctx/durable-effects.service.js";
20
21
  import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
21
22
  import { ConfiguredExtensionDbIdentity, extensionDbIdentity, extensionDbPool, } from "../db/extension-db.js";
23
+ import { ensureLocalExtensionHandoff } from "../db/extension-handoff-schema.js";
22
24
  import { transferKnownExtensionSchemas } from "../db/extension-schema-transfer.js";
23
25
  import { kernelDb } from "../db/kernel-schema.js";
24
26
  import { migrate } from "../db/migrator.js";
25
27
  import { createDb } from "../db/pool.js";
26
- import { DEVICE_ACCESS_BACKEND } from "../device-access/token.js";
28
+ import { DEVICE_ACCESS_BACKEND, SERVICE_EVENTS_BACKEND } from "../device-access/token.js";
27
29
  import { DialInAccess } from "../dial-in/access.js";
28
30
  import { INBOX_ITEMS_BACKEND } from "../inbox/token.js";
29
31
  import { waitWithin } from "../infra/close-within.js";
@@ -263,7 +265,7 @@ let ExtensionHost = class ExtensionHost {
263
265
  assertSecretsReachable(manifest);
264
266
  const identity = opts.extensionIdentity ?? extensionDbIdentity({ url: opts.dbUrl });
265
267
  if (opts.extensionIdentity) {
266
- await transferKnownExtensionSchemas(opts.dbUrl, identity, dirs.keys(), opts.connectTimeoutMs);
268
+ await transferKnownExtensionSchemas(opts.dbUrl, identity, dirs.keys(), opts.connectTimeoutMs, opts.handoffRuntimeLogin);
267
269
  }
268
270
  let toMigrate = ordered;
269
271
  if (!opts.autoApprove && ordered.length > 0) {
@@ -450,7 +452,8 @@ let ExtensionHost = class ExtensionHost {
450
452
  * Absent (a hand-built host) or not found (the CLI): `ctx.deviceAccess` calls are refused.
451
453
  * `TriggerEventsService` (`ctx.triggers`, {@link TRIGGER_EVENTS_BACKEND}) and
452
454
  * `InboxItemsService` (`ctx.inbox`, {@link INBOX_ITEMS_BACKEND}) and `PluginReadsService`
453
- * (`ctx.agents`, `ctx.conversations`, `ctx.people`, {@link PLUGIN_READS_BACKEND}) likewise.
455
+ * (`ctx.agents`, `ctx.conversations`, `ctx.people`, {@link PLUGIN_READS_BACKEND}) and
456
+ * `ServiceEvents` (`ctx.devices.serviceEvent`, {@link SERVICE_EVENTS_BACKEND}) likewise.
454
457
  */
455
458
  modules,
456
459
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
@@ -498,6 +501,22 @@ let ExtensionHost = class ExtensionHost {
498
501
  return undefined;
499
502
  }
500
503
  },
504
+ serviceEvents: () => {
505
+ try {
506
+ return modules?.get(SERVICE_EVENTS_BACKEND, { strict: false });
507
+ }
508
+ catch {
509
+ return undefined;
510
+ }
511
+ },
512
+ durableEffects: () => {
513
+ try {
514
+ return modules?.get(ExtensionEffects, { strict: false });
515
+ }
516
+ catch {
517
+ return undefined;
518
+ }
519
+ },
501
520
  triggers: () => {
502
521
  try {
503
522
  return modules?.get(TRIGGER_EVENTS_BACKEND, { strict: false });
@@ -1797,26 +1816,29 @@ let ExtensionHost = class ExtensionHost {
1797
1816
  let ctx;
1798
1817
  const name = spec.manifest.name;
1799
1818
  const identity = this.dbIdentity.resolve(name);
1800
- const extensionDb = identity.separate
1801
- ? extensionDbPool(identity, name, this.config.get().db, (err) => this.log.warn("extension database pool error", { plugin: name, err }))
1802
- : undefined;
1803
- const p = setupInstance(this.loadDeps, spec.manifest, {
1804
- entryUrl: spec.entryUrl,
1805
- source: spec.source,
1806
- sha256: spec.sha256,
1807
- config: spec.config,
1808
- configHash: spec.configHash,
1809
- permissions: spec.permissions,
1810
- ...(extensionDb && { extensionDb }),
1811
- onCtx: (c) => {
1812
- if (c)
1813
- ctx = c;
1814
- if (c || this.settingUp === ctx)
1815
- this.settingUp = c;
1816
- },
1817
- }).catch(async (error) => {
1819
+ const extensionDb = extensionDbPool(identity, name, this.config.get().db, (err) => this.log.warn("extension database pool error", { plugin: name, err }));
1820
+ const p = (async () => {
1821
+ if (!identity.separate) {
1822
+ await ensureLocalExtensionHandoff(this.deps.db, this.deps.dbUrl, pluginSchemaName(name), this.deps.connectTimeoutMs);
1823
+ }
1824
+ return setupInstance(this.loadDeps, spec.manifest, {
1825
+ entryUrl: spec.entryUrl,
1826
+ source: spec.source,
1827
+ sha256: spec.sha256,
1828
+ config: spec.config,
1829
+ configHash: spec.configHash,
1830
+ permissions: spec.permissions,
1831
+ extensionDb,
1832
+ onCtx: (c) => {
1833
+ if (c)
1834
+ ctx = c;
1835
+ if (c || this.settingUp === ctx)
1836
+ this.settingUp = c;
1837
+ },
1838
+ });
1839
+ })().catch(async (error) => {
1818
1840
  if (!ctx)
1819
- await extensionDb?.destroy();
1841
+ await extensionDb.destroy();
1820
1842
  throw error;
1821
1843
  });
1822
1844
  if (timeoutMs === undefined)