@capybara-hq/kernel 0.1.0-rc.113 → 0.1.0-rc.115

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 (96) hide show
  1. package/bootstrap.json +7 -7
  2. package/dist/admin/admin.schemas.d.ts +1 -0
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/channels/actions.js +2 -0
  5. package/dist/channels/cards.d.ts +4 -3
  6. package/dist/channels/cards.js +18 -3
  7. package/dist/channels/phrases.d.ts +15 -0
  8. package/dist/channels/phrases.js +9 -0
  9. package/dist/conversations/conversations.service.js +7 -0
  10. package/dist/conversations/events.d.ts +21 -0
  11. package/dist/conversations/events.js +35 -3
  12. package/dist/ctx/create-ctx.d.ts +1 -1
  13. package/dist/ctx/create-ctx.js +6 -1
  14. package/dist/db/kernel-schema.d.ts +29 -0
  15. package/dist/device-access/device-access.service.d.ts +74 -3
  16. package/dist/device-access/device-access.service.js +221 -7
  17. package/dist/devices/devices.service.js +3 -0
  18. package/dist/errors.d.ts +6 -0
  19. package/dist/errors.js +6 -0
  20. package/dist/extensions/permission-set.d.ts +11 -1
  21. package/dist/extensions/permission-set.js +15 -1
  22. package/dist/extensions/permission-view.d.ts +3 -2
  23. package/dist/extensions/permission-view.js +15 -2
  24. package/dist/identity/settings.d.ts +5 -0
  25. package/dist/identity/settings.js +4 -0
  26. package/dist/infra/outbox/registry.d.ts +14 -0
  27. package/dist/infra/outbox/registry.js +14 -0
  28. package/dist/models/purposes.js +5 -0
  29. package/dist/orgs/offboarding.js +5 -1
  30. package/dist/orgs/settings.service.d.ts +2 -0
  31. package/dist/platform/ops/org-settings.ops.js +1 -1
  32. package/dist/roles/worker.module.js +3 -0
  33. package/dist/runtime/compaction-model.d.ts +57 -0
  34. package/dist/runtime/compaction-model.js +87 -0
  35. package/dist/runtime/compaction.service.d.ts +23 -8
  36. package/dist/runtime/compaction.service.js +15 -10
  37. package/dist/runtime/context/compaction.d.ts +19 -2
  38. package/dist/runtime/context/compaction.js +23 -2
  39. package/dist/runtime/context/idle-compaction-rules.d.ts +17 -2
  40. package/dist/runtime/context/idle-compaction-rules.js +20 -5
  41. package/dist/runtime/idle-arm.d.ts +12 -2
  42. package/dist/runtime/idle-arm.js +66 -18
  43. package/dist/runtime/idle-compaction-jobs.d.ts +24 -3
  44. package/dist/runtime/idle-compaction.d.ts +11 -3
  45. package/dist/runtime/idle-compaction.js +61 -30
  46. package/dist/runtime/maintenance.d.ts +4 -2
  47. package/dist/runtime/maintenance.js +14 -4
  48. package/dist/runtime/model-call.d.ts +52 -16
  49. package/dist/runtime/model-call.js +71 -24
  50. package/dist/runtime/run-finish.d.ts +12 -3
  51. package/dist/runtime/run-finish.js +14 -7
  52. package/dist/runtime/run-queue.d.ts +5 -2
  53. package/dist/runtime/run-queue.js +7 -4
  54. package/dist/runtime/run-steps.d.ts +4 -1
  55. package/dist/runtime/run-steps.js +9 -2
  56. package/dist/runtime/run-worker.js +4 -2
  57. package/dist/runtime/runtime.module.js +3 -0
  58. package/dist/sandbox/device-sandbox.d.ts +12 -0
  59. package/dist/sandbox/device-sandbox.js +2 -0
  60. package/dist/sandbox/device-services.d.ts +42 -2
  61. package/dist/sandbox/device-services.js +74 -14
  62. package/dist/sandbox/loopback-expiry.job.d.ts +21 -0
  63. package/dist/sandbox/loopback-expiry.job.js +50 -0
  64. package/dist/sandbox/loopback-grant-records.d.ts +143 -0
  65. package/dist/sandbox/loopback-grant-records.js +239 -0
  66. package/dist/sandbox/loopback-grants.d.ts +119 -0
  67. package/dist/sandbox/loopback-grants.js +454 -0
  68. package/dist/sandbox/loopback-live-ports.d.ts +12 -0
  69. package/dist/sandbox/loopback-live-ports.js +43 -0
  70. package/dist/sandbox/permission-call-types.d.ts +3 -2
  71. package/dist/sandbox/permission-ceiling-writes.js +13 -1
  72. package/dist/sandbox/permission-facts.d.ts +4 -0
  73. package/dist/sandbox/permission-facts.js +4 -0
  74. package/dist/sandbox/review/classifier.d.ts +26 -4
  75. package/dist/sandbox/review/classifier.js +31 -4
  76. package/dist/sandbox/review/index.d.ts +3 -3
  77. package/dist/sandbox/review/index.js +2 -2
  78. package/dist/sandbox/review/permission-candidate.d.ts +5 -4
  79. package/dist/sandbox/review/permission-candidate.js +6 -5
  80. package/dist/sandbox/review/review.service.d.ts +69 -0
  81. package/dist/sandbox/review/review.service.js +117 -0
  82. package/dist/sandbox/sandbox.module.d.ts +1 -1
  83. package/dist/sandbox/sandbox.module.js +13 -2
  84. package/dist/tools/approvals.service.d.ts +82 -6
  85. package/dist/tools/approvals.service.js +233 -11
  86. package/dist/tools/call-scope.d.ts +9 -1
  87. package/dist/tools/loopback-asks.d.ts +52 -0
  88. package/dist/tools/loopback-asks.js +70 -0
  89. package/dist/tools/network-asks.d.ts +2 -1
  90. package/dist/tools/network-asks.js +10 -5
  91. package/dist/tools/pipeline.d.ts +59 -3
  92. package/dist/tools/pipeline.js +403 -40
  93. package/dist/tools/tools.module.js +3 -0
  94. package/package.json +2 -2
  95. package/src/migrations/0199_device_loopback_grants.sql +59 -0
  96. package/src/migrations/0200_runs_idle_mode.sql +4 -0
@@ -1,8 +1,15 @@
1
1
  import { type DeviceServiceSpec, type DeviceServiceStatus } from "@capybara-hq/plugin-sdk";
2
+ import { LockService } from "../infra/lock/lock.service.js";
3
+ import { LoopbackLivePorts } from "./loopback-live-ports.js";
4
+ import { PermissionFacts } from "./permission-facts.js";
2
5
  import { SandboxService } from "./sandbox.service.js";
3
6
  import type { SandboxUseContext } from "./use-context.js";
4
7
  /** The budget of the `ifRunning` ensure after a refresh applied new limits (a service restart). */
5
8
  export declare const POST_APPLY_ENSURE_TIMEOUT_MS = 30000;
9
+ /** The lifetime of the loopback set lock without renewal (renewed while an ensure runs). */
10
+ export declare const LOOPBACK_SET_LOCK_TTL_MS = 30000;
11
+ /** How long an ensure waits for another ensure of the same service to send its set. */
12
+ export declare const LOOPBACK_SET_LOCK_WAIT_MS = 60000;
6
13
  /**
7
14
  * Device services (browser use spec §5): one long-lived named process per device, started on an
8
15
  * extension's behalf in the device's own sandbox with its own state directory, reached by
@@ -13,10 +20,32 @@ export declare const POST_APPLY_ENSURE_TIMEOUT_MS = 30000;
13
20
  * launch and the extension's permission are the caller's (`ctx.deviceAccess`). Every name here is
14
21
  * a service id (`<extension>.<name>`, `DEVICE_SERVICE_ID_RE`): the caller namespaces the
15
22
  * extension's service names, so the provider never sees a bare name two extensions could share.
23
+ *
24
+ * Every ensure sends the provider the service's live loopback port grants (browser loopback port
25
+ * grants design §4: the whole sorted set), but only a non-empty set, and never while the device
26
+ * refuses loopback grants as far as is known ({@link knownLoopbackRefusal}: a ceiling keeps
27
+ * running outside the sandbox off, or a known support lacks `network.loopbackPorts`). Then
28
+ * `loopbackPorts` is left out, which closes every loopback port: a provider known to lack support
29
+ * never sees the key, and a ceiling switched off narrows on the next ensure, before the refresh
30
+ * job revokes the grants. A support not known (as while a device re-binds) keeps sending the set,
31
+ * as it keeps the grants; a provider without support ignores it.
32
+ * Reading the set and sending it are one step per (device, service) across replicas (a
33
+ * `LockService` lock taken outside any transaction): an ensure that read an older set can never
34
+ * reach the device after one that read a newer set.
16
35
  */
17
36
  export declare class DeviceServices {
18
37
  private readonly sandbox;
19
- constructor(sandbox: SandboxService);
38
+ private readonly loopback;
39
+ private readonly locks;
40
+ private readonly facts;
41
+ constructor(sandbox: SandboxService, loopback: Pick<LoopbackLivePorts, "livePorts">, locks: Pick<LockService, "run">, facts: Pick<PermissionFacts, "deviceSandboxFacts">);
42
+ /**
43
+ * Runs `send` with the service's live loopback ports under the (device, service) set lock: the
44
+ * set is read after the lock is taken and the send finishes before it is released, so the
45
+ * sends reach the device in the order their sets were read. A lost lock aborts the send. The
46
+ * opts carry `loopbackPorts` only for a non-empty set the device sandbox admits (see the class).
47
+ */
48
+ private withLoopbackSet;
20
49
  /**
21
50
  * Starts the service in the device, or finds it running (the provider keeps a running one).
22
51
  * With `ifRunning` it never starts one: a stopped service answers its `stopped` status, and the
@@ -39,7 +68,18 @@ export declare class DeviceServices {
39
68
  * without a running instance.
40
69
  */
41
70
  refresh(use: SandboxUseContext, name: string, signal: AbortSignal): Promise<DeviceServiceStatus | null>;
42
- /** An `ifRunning` ensure on the instance recorded now; null without a running instance. */
71
+ /**
72
+ * Sends the service's live loopback port set to the running service (a grant, a revoke, an
73
+ * expiry or a narrowing changed it): an `ifRunning` ensure only, no limits applied (the set is
74
+ * the service's own, not the device's). A provider restarts the service when its set changed and
75
+ * keeps it otherwise; a stopped service or instance needs nothing now (its next ensure sends the
76
+ * set). The status, or null without a running instance.
77
+ */
78
+ refreshLoopback(orgId: string, deviceId: string, name: string, signal: AbortSignal): Promise<DeviceServiceStatus | null>;
79
+ /**
80
+ * An `ifRunning` ensure on the instance recorded now, with the service's live loopback ports;
81
+ * null without a running instance.
82
+ */
43
83
  private ifRunningEnsure;
44
84
  /**
45
85
  * One request to the service's socket; resolves its answer (throws when it is not running).
@@ -9,9 +9,17 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { DEVICE_SERVICE_ID_RE, DeviceAccessError, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
+ import { LockService } from "../infra/lock/lock.service.js";
13
+ import { knownLoopbackRefusal } from "./loopback-grant-records.js";
14
+ import { LoopbackLivePorts } from "./loopback-live-ports.js";
15
+ import { PermissionFacts } from "./permission-facts.js";
12
16
  import { SandboxService } from "./sandbox.service.js";
13
17
  /** The budget of the `ifRunning` ensure after a refresh applied new limits (a service restart). */
14
18
  export const POST_APPLY_ENSURE_TIMEOUT_MS = 30_000;
19
+ /** The lifetime of the loopback set lock without renewal (renewed while an ensure runs). */
20
+ export const LOOPBACK_SET_LOCK_TTL_MS = 30_000;
21
+ /** How long an ensure waits for another ensure of the same service to send its set. */
22
+ export const LOOPBACK_SET_LOCK_WAIT_MS = 60_000;
15
23
  /**
16
24
  * Device services (browser use spec §5): one long-lived named process per device, started on an
17
25
  * extension's behalf in the device's own sandbox with its own state directory, reached by
@@ -22,11 +30,43 @@ export const POST_APPLY_ENSURE_TIMEOUT_MS = 30_000;
22
30
  * launch and the extension's permission are the caller's (`ctx.deviceAccess`). Every name here is
23
31
  * a service id (`<extension>.<name>`, `DEVICE_SERVICE_ID_RE`): the caller namespaces the
24
32
  * extension's service names, so the provider never sees a bare name two extensions could share.
33
+ *
34
+ * Every ensure sends the provider the service's live loopback port grants (browser loopback port
35
+ * grants design §4: the whole sorted set), but only a non-empty set, and never while the device
36
+ * refuses loopback grants as far as is known ({@link knownLoopbackRefusal}: a ceiling keeps
37
+ * running outside the sandbox off, or a known support lacks `network.loopbackPorts`). Then
38
+ * `loopbackPorts` is left out, which closes every loopback port: a provider known to lack support
39
+ * never sees the key, and a ceiling switched off narrows on the next ensure, before the refresh
40
+ * job revokes the grants. A support not known (as while a device re-binds) keeps sending the set,
41
+ * as it keeps the grants; a provider without support ignores it.
42
+ * Reading the set and sending it are one step per (device, service) across replicas (a
43
+ * `LockService` lock taken outside any transaction): an ensure that read an older set can never
44
+ * reach the device after one that read a newer set.
25
45
  */
26
46
  let DeviceServices = class DeviceServices {
27
47
  sandbox;
28
- constructor(sandbox) {
48
+ loopback;
49
+ locks;
50
+ facts;
51
+ constructor(sandbox, loopback, locks, facts) {
29
52
  this.sandbox = sandbox;
53
+ this.loopback = loopback;
54
+ this.locks = locks;
55
+ this.facts = facts;
56
+ }
57
+ /**
58
+ * Runs `send` with the service's live loopback ports under the (device, service) set lock: the
59
+ * set is read after the lock is taken and the send finishes before it is released, so the
60
+ * sends reach the device in the order their sets were read. A lost lock aborts the send. The
61
+ * opts carry `loopbackPorts` only for a non-empty set the device sandbox admits (see the class).
62
+ */
63
+ withLoopbackSet(orgId, deviceId, name, signal, send) {
64
+ return this.locks.run(`loopback-set-${deviceId}-${name}`, { ttlMs: LOOPBACK_SET_LOCK_TTL_MS, waitMs: LOOPBACK_SET_LOCK_WAIT_MS, signal }, async (held) => {
65
+ const ports = await this.loopback.livePorts(orgId, deviceId, name);
66
+ const admitted = ports.length > 0 &&
67
+ knownLoopbackRefusal(await this.facts.deviceSandboxFacts(orgId, deviceId)) === null;
68
+ return send(admitted ? { loopbackPorts: ports } : {}, AbortSignal.any([signal, held.lost]));
69
+ });
30
70
  }
31
71
  /**
32
72
  * Starts the service in the device, or finds it running (the provider keeps a running one).
@@ -36,11 +76,13 @@ let DeviceServices = class DeviceServices {
36
76
  */
37
77
  async ensure(use, spec, signal, opts = {}) {
38
78
  assertServiceSpec(spec);
39
- return this.sandbox.withDeviceServices(use, requireServices, (h, p, sig) => opts.ifRunning === true
40
- ? p.ensureService(h, nameOnlySpec(spec.name), sig, {
41
- ifRunning: true,
42
- })
43
- : p.ensureService(h, spec, sig), signal);
79
+ return this.sandbox.withDeviceServices(use, requireServices, (h, p, sig) => {
80
+ const ensure = p.ensureService;
81
+ // read under the use and the set lock, so a grant committed before it is in the set
82
+ return this.withLoopbackSet(use.orgId, use.deviceId, spec.name, sig, (loopback, s) => opts.ifRunning === true
83
+ ? ensure(h, nameOnlySpec(spec.name), s, { ifRunning: true, ...loopback })
84
+ : ensure(h, spec, s, loopback));
85
+ }, signal);
44
86
  }
45
87
  /**
46
88
  * Applies the device's current limits to the service when it runs (the device's allowlist
@@ -56,23 +98,38 @@ let DeviceServices = class DeviceServices {
56
98
  */
57
99
  async refresh(use, name, signal) {
58
100
  assertServiceName(name);
59
- const found = await this.ifRunningEnsure(use, name, signal);
101
+ const found = await this.ifRunningEnsure(use.orgId, use.deviceId, name, signal);
60
102
  if (found === null || found.state !== "running")
61
103
  return found;
62
104
  if ((await this.sandbox.applyLimitsIfRunning(use, signal)) !== "applied")
63
105
  return found;
64
106
  // its own budget, never what the wait left of the caller's: a provider restarts the service
65
107
  // on the new network here (device-local), so a spent caller signal must not skip it
66
- return this.ifRunningEnsure(use, name, AbortSignal.timeout(POST_APPLY_ENSURE_TIMEOUT_MS));
108
+ return this.ifRunningEnsure(use.orgId, use.deviceId, name, AbortSignal.timeout(POST_APPLY_ENSURE_TIMEOUT_MS));
67
109
  }
68
- /** An `ifRunning` ensure on the instance recorded now; null without a running instance. */
69
- async ifRunningEnsure(use, name, signal) {
70
- const current = await this.sandbox.currentInstance(use.deviceId);
110
+ /**
111
+ * Sends the service's live loopback port set to the running service (a grant, a revoke, an
112
+ * expiry or a narrowing changed it): an `ifRunning` ensure only, no limits applied (the set is
113
+ * the service's own, not the device's). A provider restarts the service when its set changed and
114
+ * keeps it otherwise; a stopped service or instance needs nothing now (its next ensure sends the
115
+ * set). The status, or null without a running instance.
116
+ */
117
+ async refreshLoopback(orgId, deviceId, name, signal) {
118
+ assertServiceName(name);
119
+ return this.ifRunningEnsure(orgId, deviceId, name, signal);
120
+ }
121
+ /**
122
+ * An `ifRunning` ensure on the instance recorded now, with the service's live loopback ports;
123
+ * null without a running instance.
124
+ */
125
+ async ifRunningEnsure(orgId, deviceId, name, signal) {
126
+ const current = await this.sandbox.currentInstance(deviceId);
71
127
  if (!current)
72
128
  return null;
73
- const r = await this.sandbox.ifRunning(use.deviceId, { createdAt: current.createdAt }, async (p, h, sig) => {
129
+ const r = await this.sandbox.ifRunning(deviceId, { createdAt: current.createdAt }, async (p, h, sig) => {
74
130
  requireServices(p);
75
- return p.ensureService(h, nameOnlySpec(name), sig, { ifRunning: true });
131
+ const ensure = p.ensureService;
132
+ return this.withLoopbackSet(orgId, deviceId, name, sig, (loopback, s) => ensure(h, nameOnlySpec(name), s, { ifRunning: true, ...loopback }));
76
133
  }, signal);
77
134
  return r.kind === "ran" ? r.value : null;
78
135
  }
@@ -145,7 +202,10 @@ let DeviceServices = class DeviceServices {
145
202
  };
146
203
  DeviceServices = __decorate([
147
204
  Injectable(),
148
- __param(0, Inject(SandboxService))
205
+ __param(0, Inject(SandboxService)),
206
+ __param(1, Inject(LoopbackLivePorts)),
207
+ __param(2, Inject(LockService)),
208
+ __param(3, Inject(PermissionFacts))
149
209
  ], DeviceServices);
150
210
  export { DeviceServices };
151
211
  /**
@@ -0,0 +1,21 @@
1
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
2
+ import { LockService } from "../infra/lock/lock.service.js";
3
+ import type { KernelLogger } from "../log.js";
4
+ import { LoopbackGrants } from "./loopback-grants.js";
5
+ /** The expiry pass of loopback port grants (`@LockedInterval`, every {@link LOOPBACK_EXPIRY_MS}). */
6
+ export declare const LOOPBACK_EXPIRY_JOB = "device-loopback-expiry";
7
+ /** The pass's period. */
8
+ export declare const LOOPBACK_EXPIRY_MS = 60000;
9
+ /**
10
+ * Ends the loopback port grants past their 24 hours (browser loopback port grants design §4) and
11
+ * owes the refresh of each service that held one: once per tick across replicas
12
+ * (`@LockedInterval`), provided only by the worker role (`WorkerModule`).
13
+ */
14
+ export declare class LoopbackExpiryJob {
15
+ private readonly grants;
16
+ readonly config: KernelConfigService;
17
+ readonly lockService: LockService;
18
+ readonly log: KernelLogger;
19
+ constructor(grants: Pick<LoopbackGrants, "expireDue">, config: KernelConfigService, lockService: LockService, log: KernelLogger);
20
+ expire(): Promise<void>;
21
+ }
@@ -0,0 +1,50 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
12
+ import { LockService } from "../infra/lock/lock.service.js";
13
+ import { LockedInterval } from "../infra/schedule/locked-interval.js";
14
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
15
+ import { LoopbackGrants } from "./loopback-grants.js";
16
+ /** The expiry pass of loopback port grants (`@LockedInterval`, every {@link LOOPBACK_EXPIRY_MS}). */
17
+ export const LOOPBACK_EXPIRY_JOB = "device-loopback-expiry";
18
+ /** The pass's period. */
19
+ export const LOOPBACK_EXPIRY_MS = 60_000;
20
+ /**
21
+ * Ends the loopback port grants past their 24 hours (browser loopback port grants design §4) and
22
+ * owes the refresh of each service that held one: once per tick across replicas
23
+ * (`@LockedInterval`), provided only by the worker role (`WorkerModule`).
24
+ */
25
+ let LoopbackExpiryJob = class LoopbackExpiryJob {
26
+ grants;
27
+ config;
28
+ lockService;
29
+ log;
30
+ constructor(grants, config, lockService, log) {
31
+ this.grants = grants;
32
+ this.config = config;
33
+ this.lockService = lockService;
34
+ this.log = log;
35
+ }
36
+ async expire() {
37
+ await this.grants.expireDue();
38
+ }
39
+ };
40
+ __decorate([
41
+ LockedInterval(LOOPBACK_EXPIRY_JOB, () => LOOPBACK_EXPIRY_MS)
42
+ ], LoopbackExpiryJob.prototype, "expire", null);
43
+ LoopbackExpiryJob = __decorate([
44
+ Injectable(),
45
+ __param(0, Inject(LoopbackGrants)),
46
+ __param(1, Inject(KernelConfigService)),
47
+ __param(2, Inject(LockService)),
48
+ __param(3, Inject(KERNEL_LOGGER))
49
+ ], LoopbackExpiryJob);
50
+ export { LoopbackExpiryJob };
@@ -0,0 +1,143 @@
1
+ import { DeviceAccessError, type LoopbackGrantSource, type SandboxPermissionSupport } from "@capybara-hq/plugin-sdk";
2
+ import { type Selectable } from "kysely";
3
+ import type { DeviceLoopbackGrantsTable, KernelSchemaDb } from "../db/kernel-schema.js";
4
+ import type { OutboxService } from "../infra/outbox/outbox.service.js";
5
+ import type { DeviceSandbox } from "./device-sandbox.js";
6
+ /**
7
+ * Loopback port grants (browser loopback port grants design §4, §6): one device service of a
8
+ * person's own device may reach one loopback port of that device for one conversation tree. The
9
+ * records in `device_loopback_grants` are the live set; every change to it (a grant, a revoke, an
10
+ * expiry, a conversation's deletion, a narrowing ceiling) owes a `device-loopback-refresh` job per
11
+ * affected (device, service), which sends the whole live set to an `ifRunning` ensure of the
12
+ * service. A ceiling narrows by revocation: the refresh job revokes (`outside-sandbox-off`) when
13
+ * the device refuses loopback grants now.
14
+ */
15
+ /** A grant's lifetime from issue. */
16
+ export declare const LOOPBACK_GRANT_TTL_HOURS = 24;
17
+ /** The refresh of one (device, service)'s live set (outbox job on the maintenance queue). */
18
+ export declare const LOOPBACK_REFRESH_JOB = "device-loopback-refresh";
19
+ /** The data of {@link LOOPBACK_REFRESH_JOB}: `orgId` gives the job its org scope (`runJob`). */
20
+ export interface LoopbackRefreshJobData {
21
+ orgId: string;
22
+ deviceId: string;
23
+ serviceId: string;
24
+ /** The change that owed it (the job id's last part), so a follow-up names its own id. */
25
+ change?: string;
26
+ /** The follow-up number after failed sends (absent for the first job). */
27
+ followUp?: number;
28
+ }
29
+ /**
30
+ * The most follow-ups one change owes after failed sends, about a day at
31
+ * {@link LOOPBACK_FOLLOW_UP_MAX_DELAY_MS}: a device the kernel records as running keeps getting
32
+ * the live set until one send lands, so a narrowing never stays on the machine because a send
33
+ * failed.
34
+ */
35
+ export declare const LOOPBACK_MAX_FOLLOW_UPS = 300;
36
+ /** The first follow-up's delay; it doubles up to {@link LOOPBACK_FOLLOW_UP_MAX_DELAY_MS}. */
37
+ export declare const LOOPBACK_FOLLOW_UP_DELAY_MS = 30000;
38
+ export declare const LOOPBACK_FOLLOW_UP_MAX_DELAY_MS = 300000;
39
+ /**
40
+ * Owes the follow-up of a refresh whose send failed (`-t<n>` after its change), delayed with a
41
+ * doubling backoff; false past {@link LOOPBACK_MAX_FOLLOW_UPS}.
42
+ */
43
+ export declare function oweLoopbackFollowUp(outbox: Pick<OutboxService, "add">, data: LoopbackRefreshJobData): Promise<boolean>;
44
+ /**
45
+ * The deterministic job id of a refresh (no `:`). `change` names what owed it: `g<grantId>` (a
46
+ * grant), `r<grantId>` (a revoke, an expiry or a deletion), `c<level>-<subjectId>-<epoch>` (a
47
+ * ceiling publication, the epoch after its bump).
48
+ */
49
+ export declare const loopbackRefreshJobId: (deviceId: string, serviceId: string, change: string) => string;
50
+ /** The budget of one refresh job's device calls. */
51
+ export declare const LOOPBACK_REFRESH_TIMEOUT_MS = 30000;
52
+ /** What names one grant: the root conversation holds it, sub-agents use their root's. */
53
+ export interface LoopbackGrantKey {
54
+ orgId: string;
55
+ deviceId: string;
56
+ /** `<extension>.<name>`. */
57
+ serviceId: string;
58
+ rootConversationId: string;
59
+ port: number;
60
+ }
61
+ /** One grant record as the kernel's callers read it. */
62
+ export interface LoopbackGrantRow {
63
+ id: string;
64
+ port: number;
65
+ source: LoopbackGrantSource;
66
+ /** ISO 8601. */
67
+ expiresAt: string;
68
+ runId: string | null;
69
+ callId: string | null;
70
+ attempt: number | null;
71
+ }
72
+ /** Why a grant ended (`device_loopback_grants.revoke_reason`). */
73
+ export type LoopbackRevokeReason = "revoked" | "expired" | "conversation-deleted" | "outside-sandbox-off";
74
+ /** A grant past {@link LOOPBACK_MAX_PORTS_PER_SERVICE} live ports of one (device, service). */
75
+ export declare class LoopbackLimitError extends DeviceAccessError {
76
+ constructor();
77
+ }
78
+ /**
79
+ * Why a loopback grant is refused on this device now, in the note's words; null when grantable.
80
+ * `escalationRefusal` is why a call could not run outside the sandbox here (the ceiling, an
81
+ * unattended run), null or undefined when it could.
82
+ */
83
+ export declare function loopbackRefusal(box: DeviceSandbox, support: SandboxPermissionSupport | null, escalationRefusal: string | null | undefined): string | null;
84
+ /**
85
+ * Whether the device refuses loopback grants now, as far as that is known: a ceiling layer keeps
86
+ * running outside the sandbox off (`ceiling`), or a known, usable support lacks loopback ports
87
+ * (`provider-support`: no `network.loopbackPorts`, an old capybara-device, or nothing run outside
88
+ * the sandbox). A support not known (none stored, a failed read, or a closed one naming an
89
+ * `unavailableReason`, as while a device re-binds) refuses nothing: grants are consents and are
90
+ * kept until the support is known again. Null when nothing known refuses.
91
+ */
92
+ export declare function knownLoopbackRefusal(facts: {
93
+ box: DeviceSandbox;
94
+ support: SandboxPermissionSupport | null;
95
+ }): "ceiling" | "provider-support" | null;
96
+ export declare const rowOf: (r: Selectable<DeviceLoopbackGrantsTable>) => LoopbackGrantRow;
97
+ export declare const isDatabasePort: (port: number) => boolean;
98
+ /** Owes the refresh of one (device, service). */
99
+ export declare function oweRefresh(outbox: Pick<OutboxService, "add">, target: LoopbackRefreshJobData, change: string): Promise<void>;
100
+ /**
101
+ * Owes one refresh per (device, service) with live grants under the subject, in the caller's
102
+ * transaction (a ceiling publication, `PermissionCeilingWrites.publishLocked`): every org at the
103
+ * platform level, the org's, the device's, or the root conversation's grants. Returns how many it
104
+ * owed. The job decides whether the ceiling now refuses and revokes then.
105
+ */
106
+ export declare function oweLoopbackRefreshes(db: KernelSchemaDb, outbox: Pick<OutboxService, "add">, under: {
107
+ level: "platform" | "org" | "device" | "root";
108
+ orgId?: string;
109
+ deviceId?: string;
110
+ rootConversationId?: string;
111
+ }, change: string): Promise<number>;
112
+ /**
113
+ * Revokes a deleted device's live grants (reason `revoked`, audited with `cause: "device-deleted"`)
114
+ * and owes their refreshes, in the caller's transaction (the device's deletion or its owner's
115
+ * offboarding).
116
+ */
117
+ export declare function revokeLoopbackGrantsOfDevice(db: KernelSchemaDb, outbox: Pick<OutboxService, "add">, target: {
118
+ orgId: string;
119
+ deviceId: string;
120
+ }): Promise<void>;
121
+ /**
122
+ * Revokes a deleted root's live grants (reason `conversation-deleted`, audited) and owes their
123
+ * refreshes, in the caller's transaction (the conversation's deletion). A sub-agent's
124
+ * conversation holds no grant, so its id finds none.
125
+ */
126
+ export declare function revokeLoopbackGrantsOfConversation(db: KernelSchemaDb, outbox: Pick<OutboxService, "add">, target: {
127
+ orgId: string;
128
+ rootConversationId: string;
129
+ }): Promise<void>;
130
+ /**
131
+ * Audits ended grants (`device.loopback_revoked`) and owes one refresh per (device, service),
132
+ * named by its first grant.
133
+ */
134
+ export declare function endedGrants(db: KernelSchemaDb, outbox: Pick<OutboxService, "add">, rows: readonly {
135
+ id: string;
136
+ org_id: string;
137
+ device_id: string;
138
+ service_id: string;
139
+ conversation_id: string;
140
+ port: number;
141
+ }[], reason: LoopbackRevokeReason, actorAccountId: string | null,
142
+ /** What ended them when the reason alone does not say (`device-deleted`, `provider-support`). */
143
+ cause?: string): Promise<void>;
@@ -0,0 +1,239 @@
1
+ import { DeviceAccessError, LOOPBACK_DATABASE_PORTS, LOOPBACK_MAX_PORTS_PER_SERVICE, } from "@capybara-hq/plugin-sdk";
2
+ import { sql } from "kysely";
3
+ import { audit } from "../identity/audit.js";
4
+ import { asPlatform } from "../infra/database/org-scope.js";
5
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
6
+ /**
7
+ * Loopback port grants (browser loopback port grants design §4, §6): one device service of a
8
+ * person's own device may reach one loopback port of that device for one conversation tree. The
9
+ * records in `device_loopback_grants` are the live set; every change to it (a grant, a revoke, an
10
+ * expiry, a conversation's deletion, a narrowing ceiling) owes a `device-loopback-refresh` job per
11
+ * affected (device, service), which sends the whole live set to an `ifRunning` ensure of the
12
+ * service. A ceiling narrows by revocation: the refresh job revokes (`outside-sandbox-off`) when
13
+ * the device refuses loopback grants now.
14
+ */
15
+ /** A grant's lifetime from issue. */
16
+ export const LOOPBACK_GRANT_TTL_HOURS = 24;
17
+ /** The refresh of one (device, service)'s live set (outbox job on the maintenance queue). */
18
+ export const LOOPBACK_REFRESH_JOB = "device-loopback-refresh";
19
+ /**
20
+ * The most follow-ups one change owes after failed sends, about a day at
21
+ * {@link LOOPBACK_FOLLOW_UP_MAX_DELAY_MS}: a device the kernel records as running keeps getting
22
+ * the live set until one send lands, so a narrowing never stays on the machine because a send
23
+ * failed.
24
+ */
25
+ export const LOOPBACK_MAX_FOLLOW_UPS = 300;
26
+ /** The first follow-up's delay; it doubles up to {@link LOOPBACK_FOLLOW_UP_MAX_DELAY_MS}. */
27
+ export const LOOPBACK_FOLLOW_UP_DELAY_MS = 30_000;
28
+ export const LOOPBACK_FOLLOW_UP_MAX_DELAY_MS = 300_000;
29
+ /**
30
+ * Owes the follow-up of a refresh whose send failed (`-t<n>` after its change), delayed with a
31
+ * doubling backoff; false past {@link LOOPBACK_MAX_FOLLOW_UPS}.
32
+ */
33
+ export async function oweLoopbackFollowUp(outbox, data) {
34
+ const n = (data.followUp ?? 0) + 1;
35
+ if (n > LOOPBACK_MAX_FOLLOW_UPS)
36
+ return false;
37
+ const change = data.change ?? "x";
38
+ const delay = Math.min(LOOPBACK_FOLLOW_UP_DELAY_MS * 2 ** (n - 1), LOOPBACK_FOLLOW_UP_MAX_DELAY_MS);
39
+ const next = {
40
+ orgId: data.orgId,
41
+ deviceId: data.deviceId,
42
+ serviceId: data.serviceId,
43
+ change,
44
+ followUp: n,
45
+ };
46
+ await outbox.add({
47
+ queue: MAINTENANCE_QUEUE_NAME,
48
+ name: LOOPBACK_REFRESH_JOB,
49
+ jobId: loopbackRefreshJobId(data.deviceId, data.serviceId, `${change}-t${n}`),
50
+ data: next,
51
+ runAt: new Date(Date.now() + delay),
52
+ orgId: data.orgId,
53
+ });
54
+ return true;
55
+ }
56
+ /**
57
+ * The deterministic job id of a refresh (no `:`). `change` names what owed it: `g<grantId>` (a
58
+ * grant), `r<grantId>` (a revoke, an expiry or a deletion), `c<level>-<subjectId>-<epoch>` (a
59
+ * ceiling publication, the epoch after its bump).
60
+ */
61
+ export const loopbackRefreshJobId = (deviceId, serviceId, change) => `dlr-${deviceId}-${serviceId}-${change}`;
62
+ /** The budget of one refresh job's device calls. */
63
+ export const LOOPBACK_REFRESH_TIMEOUT_MS = 30_000;
64
+ /** A grant past {@link LOOPBACK_MAX_PORTS_PER_SERVICE} live ports of one (device, service). */
65
+ export class LoopbackLimitError extends DeviceAccessError {
66
+ constructor() {
67
+ super("loopback_limit", `This device service already has ${LOOPBACK_MAX_PORTS_PER_SERVICE} local ports open; revoke one in the browser panel before granting another.`);
68
+ this.name = "LoopbackLimitError";
69
+ }
70
+ }
71
+ /**
72
+ * Why a loopback grant is refused on this device now, in the note's words; null when grantable.
73
+ * `escalationRefusal` is why a call could not run outside the sandbox here (the ceiling, an
74
+ * unattended run), null or undefined when it could.
75
+ */
76
+ export function loopbackRefusal(box, support, escalationRefusal) {
77
+ if (escalationRefusal !== null && escalationRefusal !== undefined)
78
+ return `running outside the sandbox is not possible here (${escalationRefusal})`;
79
+ if (support?.network.loopbackPorts !== true &&
80
+ support?.limitedBy?.loopbackPorts === "device-update")
81
+ return "capybara-device on this device is too old; update capybara-device to let the browser reach local ports";
82
+ if (support?.network.loopbackPorts !== true || !box.loopbackPorts)
83
+ return "this device's provider cannot open a local port to a device service";
84
+ return null;
85
+ }
86
+ /**
87
+ * Whether the device refuses loopback grants now, as far as that is known: a ceiling layer keeps
88
+ * running outside the sandbox off (`ceiling`), or a known, usable support lacks loopback ports
89
+ * (`provider-support`: no `network.loopbackPorts`, an old capybara-device, or nothing run outside
90
+ * the sandbox). A support not known (none stored, a failed read, or a closed one naming an
91
+ * `unavailableReason`, as while a device re-binds) refuses nothing: grants are consents and are
92
+ * kept until the support is known again. Null when nothing known refuses.
93
+ */
94
+ export function knownLoopbackRefusal(facts) {
95
+ const { box, support } = facts;
96
+ // no run here: only the device's ceiling decides whether a call could run outside now
97
+ if (!box.outsideSandbox && box.layer.outsideSandbox !== "provider")
98
+ return "ceiling";
99
+ if (support === null || support.unavailableReason !== undefined)
100
+ return null;
101
+ const refusal = loopbackRefusal(box, support, box.outsideSandbox ? null : "the provider runs nothing outside the sandbox");
102
+ return refusal === null ? null : "provider-support";
103
+ }
104
+ export const rowOf = (r) => ({
105
+ id: r.id,
106
+ port: r.port,
107
+ source: r.source,
108
+ expiresAt: new Date(r.expires_at).toISOString(),
109
+ runId: r.run_id,
110
+ callId: r.call_id,
111
+ attempt: r.attempt,
112
+ });
113
+ export const isDatabasePort = (port) => LOOPBACK_DATABASE_PORTS.includes(port);
114
+ /** Owes the refresh of one (device, service). */
115
+ export async function oweRefresh(outbox, target, change) {
116
+ const data = {
117
+ orgId: target.orgId,
118
+ deviceId: target.deviceId,
119
+ serviceId: target.serviceId,
120
+ change,
121
+ };
122
+ await outbox.add({
123
+ queue: MAINTENANCE_QUEUE_NAME,
124
+ name: LOOPBACK_REFRESH_JOB,
125
+ jobId: loopbackRefreshJobId(target.deviceId, target.serviceId, change),
126
+ data,
127
+ orgId: target.orgId,
128
+ });
129
+ }
130
+ /**
131
+ * Owes one refresh per (device, service) with live grants under the subject, in the caller's
132
+ * transaction (a ceiling publication, `PermissionCeilingWrites.publishLocked`): every org at the
133
+ * platform level, the org's, the device's, or the root conversation's grants. Returns how many it
134
+ * owed. The job decides whether the ceiling now refuses and revokes then.
135
+ */
136
+ export async function oweLoopbackRefreshes(db, outbox, under, change) {
137
+ const need = (v) => {
138
+ if (!v)
139
+ throw new Error(`A ${under.level} loopback refresh needs its subject`);
140
+ return v;
141
+ };
142
+ // RLS phase 5: the platform level reads every org's grants under asPlatform, but owes their
143
+ // outbox rows in the caller's scope; once RLS is enabled, those inserts must run under
144
+ // asPlatform too (or per row in its own org), or the policy refuses other orgs' rows
145
+ const rows = under.level === "platform"
146
+ ? await asPlatform("platform ceiling publication: loopback grants of every org", () => {
147
+ // org-filter: deployment-wide platform-level writer under the exclusive platform lock:
148
+ // the live grants it may narrow lie in every org; each refresh runs in its own org
149
+ return db
150
+ .selectFrom("device_loopback_grants")
151
+ .select(["org_id", "device_id", "service_id"])
152
+ .distinct()
153
+ .where("revoked_at", "is", null)
154
+ .orderBy("org_id")
155
+ .orderBy("device_id")
156
+ .orderBy("service_id")
157
+ .execute();
158
+ })
159
+ : await db
160
+ .selectFrom("device_loopback_grants")
161
+ .select(["org_id", "device_id", "service_id"])
162
+ .distinct()
163
+ .where("org_id", "=", need(under.orgId))
164
+ .where("revoked_at", "is", null)
165
+ .$if(under.level === "device", (q) => q.where("device_id", "=", need(under.deviceId)))
166
+ .$if(under.level === "root", (q) => q.where("conversation_id", "=", need(under.rootConversationId)))
167
+ .orderBy("device_id")
168
+ .orderBy("service_id")
169
+ .execute();
170
+ for (const r of rows)
171
+ await oweRefresh(outbox, { orgId: r.org_id, deviceId: r.device_id, serviceId: r.service_id }, change);
172
+ return rows.length;
173
+ }
174
+ /**
175
+ * Revokes a deleted device's live grants (reason `revoked`, audited with `cause: "device-deleted"`)
176
+ * and owes their refreshes, in the caller's transaction (the device's deletion or its owner's
177
+ * offboarding).
178
+ */
179
+ export async function revokeLoopbackGrantsOfDevice(db, outbox, target) {
180
+ const rows = await db
181
+ .updateTable("device_loopback_grants")
182
+ .set({ revoked_at: sql `now()`, revoke_reason: "revoked" })
183
+ .where("org_id", "=", target.orgId)
184
+ .where("device_id", "=", target.deviceId)
185
+ .where("revoked_at", "is", null)
186
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
187
+ .execute();
188
+ await endedGrants(db, outbox, rows, "revoked", null, "device-deleted");
189
+ }
190
+ /**
191
+ * Revokes a deleted root's live grants (reason `conversation-deleted`, audited) and owes their
192
+ * refreshes, in the caller's transaction (the conversation's deletion). A sub-agent's
193
+ * conversation holds no grant, so its id finds none.
194
+ */
195
+ export async function revokeLoopbackGrantsOfConversation(db, outbox, target) {
196
+ const rows = await db
197
+ .updateTable("device_loopback_grants")
198
+ .set({ revoked_at: sql `now()`, revoke_reason: "conversation-deleted" })
199
+ .where("org_id", "=", target.orgId)
200
+ .where("conversation_id", "=", target.rootConversationId)
201
+ .where("revoked_at", "is", null)
202
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
203
+ .execute();
204
+ await endedGrants(db, outbox, rows, "conversation-deleted", null);
205
+ }
206
+ /**
207
+ * Audits ended grants (`device.loopback_revoked`) and owes one refresh per (device, service),
208
+ * named by its first grant.
209
+ */
210
+ export async function endedGrants(db, outbox, rows, reason, actorAccountId,
211
+ /** What ended them when the reason alone does not say (`device-deleted`, `provider-support`). */
212
+ cause) {
213
+ const owed = new Map();
214
+ for (const r of [...rows].sort((a, b) => a.id.localeCompare(b.id))) {
215
+ await audit(db, {
216
+ actorAccountId,
217
+ orgId: r.org_id,
218
+ action: "device.loopback_revoked",
219
+ target: r.device_id,
220
+ detail: {
221
+ grantId: r.id,
222
+ deviceId: r.device_id,
223
+ serviceId: r.service_id,
224
+ conversationId: r.conversation_id,
225
+ port: r.port,
226
+ reason,
227
+ ...(cause !== undefined && { cause }),
228
+ },
229
+ });
230
+ const key = `${r.device_id}\n${r.service_id}`;
231
+ if (!owed.has(key))
232
+ owed.set(key, {
233
+ target: { orgId: r.org_id, deviceId: r.device_id, serviceId: r.service_id },
234
+ grantId: r.id,
235
+ });
236
+ }
237
+ for (const { target, grantId } of owed.values())
238
+ await oweRefresh(outbox, target, `r${grantId}`);
239
+ }