@capybara-hq/kernel 0.1.0-rc.84 → 0.1.0-rc.86

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 (157) hide show
  1. package/dist/admin/admin.module.js +5 -0
  2. package/dist/admin/health.service.d.ts +2 -2
  3. package/dist/admin/health.service.js +10 -2
  4. package/dist/catalog/admin-catalog.controller.d.ts +2 -1
  5. package/dist/catalog/admin-catalog.controller.js +2 -1
  6. package/dist/catalog/catalog-content.d.ts +5 -15
  7. package/dist/catalog/catalog-content.js +5 -56
  8. package/dist/catalog/catalog-scope.service.d.ts +3 -3
  9. package/dist/catalog/catalog-scope.service.js +4 -3
  10. package/dist/catalog/catalog.module.d.ts +3 -1
  11. package/dist/catalog/catalog.module.js +14 -1
  12. package/dist/catalog/component-scope.service.d.ts +6 -1
  13. package/dist/catalog/component-scope.service.js +16 -2
  14. package/dist/catalog/job-ids.d.ts +29 -0
  15. package/dist/catalog/job-ids.js +29 -0
  16. package/dist/catalog/jobs.d.ts +12 -3
  17. package/dist/catalog/jobs.js +28 -7
  18. package/dist/catalog/marketplaces.service.d.ts +1 -1
  19. package/dist/catalog/org-catalog.controller.d.ts +2 -30
  20. package/dist/catalog/org-catalog.controller.js +3 -29
  21. package/dist/catalog/org-catalog.schemas.d.ts +9 -46
  22. package/dist/catalog/org-catalog.schemas.js +9 -23
  23. package/dist/catalog/org-catalog.service.js +14 -23
  24. package/dist/catalog/plugin-import.d.ts +21 -0
  25. package/dist/catalog/plugin-import.js +33 -3
  26. package/dist/catalog/plugin-install.d.ts +69 -76
  27. package/dist/catalog/plugin-install.js +156 -234
  28. package/dist/catalog/plugin-upgrade.d.ts +71 -11
  29. package/dist/catalog/plugin-upgrade.js +222 -43
  30. package/dist/catalog/scope-sync.d.ts +22 -20
  31. package/dist/catalog/scope-sync.js +57 -42
  32. package/dist/catalog/template-connector-ensure.d.ts +100 -0
  33. package/dist/catalog/template-connector-ensure.js +285 -0
  34. package/dist/catalog/template-connector-jobs.d.ts +28 -0
  35. package/dist/catalog/template-connector-jobs.js +54 -0
  36. package/dist/catalog/template-connector-reconcile.d.ts +44 -0
  37. package/dist/catalog/template-connector-reconcile.js +114 -0
  38. package/dist/catalog/template-connectors.processor.d.ts +32 -0
  39. package/dist/catalog/template-connectors.processor.js +101 -0
  40. package/dist/channels/cards.d.ts +7 -3
  41. package/dist/channels/cards.js +9 -4
  42. package/dist/channels/phrases.d.ts +10 -0
  43. package/dist/channels/phrases.js +10 -0
  44. package/dist/config/docs.js +1 -1
  45. package/dist/config/schema.d.ts +3 -0
  46. package/dist/config/schema.js +18 -12
  47. package/dist/ctx/create-ctx.d.ts +10 -1
  48. package/dist/ctx/create-ctx.js +42 -2
  49. package/dist/db/kernel-schema.d.ts +2 -1
  50. package/dist/device-access/device-access.module.d.ts +7 -0
  51. package/dist/device-access/device-access.module.js +41 -0
  52. package/dist/device-access/device-access.service.d.ts +142 -0
  53. package/dist/device-access/device-access.service.js +464 -0
  54. package/dist/device-access/token.d.ts +6 -0
  55. package/dist/device-access/token.js +6 -0
  56. package/dist/device-access/viewer-routes.d.ts +45 -0
  57. package/dist/device-access/viewer-routes.js +81 -0
  58. package/dist/device-access/viewer.d.ts +244 -0
  59. package/dist/device-access/viewer.js +844 -0
  60. package/dist/dial-in/access.d.ts +19 -0
  61. package/dist/dial-in/access.js +23 -0
  62. package/dist/dial-in/gateway.d.ts +48 -6
  63. package/dist/dial-in/gateway.js +145 -10
  64. package/dist/dial-in/keys.d.ts +7 -0
  65. package/dist/dial-in/keys.js +7 -0
  66. package/dist/dial-in/routes.d.ts +11 -3
  67. package/dist/dial-in/routes.js +15 -4
  68. package/dist/dial-in/streams.d.ts +58 -0
  69. package/dist/dial-in/streams.js +283 -0
  70. package/dist/errors.d.ts +2 -0
  71. package/dist/errors.js +2 -0
  72. package/dist/extensions/host.d.ts +13 -1
  73. package/dist/extensions/host.js +20 -1
  74. package/dist/extensions/org-config.d.ts +6 -1
  75. package/dist/extensions/org-config.js +15 -2
  76. package/dist/extensions/permission-set.d.ts +15 -1
  77. package/dist/extensions/permission-set.js +13 -1
  78. package/dist/extensions/permission-view.d.ts +6 -4
  79. package/dist/extensions/permission-view.js +6 -1
  80. package/dist/git/gateway.js +3 -1
  81. package/dist/http/error.filter.js +2 -0
  82. package/dist/http/gateway-routes.d.ts +8 -4
  83. package/dist/http/gateway-routes.js +4 -3
  84. package/dist/infra/lock/lock.service.d.ts +5 -1
  85. package/dist/infra/lock/lock.service.js +10 -4
  86. package/dist/infra/outbox/registry.d.ts +28 -0
  87. package/dist/infra/outbox/registry.js +33 -0
  88. package/dist/infra/queue/queue-names.d.ts +1 -1
  89. package/dist/infra/queue/queue-names.js +2 -0
  90. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  91. package/dist/infra/throttler/named-throttlers.js +16 -0
  92. package/dist/kernel.module.js +3 -0
  93. package/dist/lifecycle/kernel-lifecycle.d.ts +8 -1
  94. package/dist/lifecycle/kernel-lifecycle.js +37 -11
  95. package/dist/orgs/org-owner.d.ts +7 -0
  96. package/dist/orgs/org-owner.js +16 -0
  97. package/dist/platform/operation.d.ts +3 -4
  98. package/dist/platform/ops/connectors.ops.js +8 -1
  99. package/dist/platform/ops/org-plugins.ops.d.ts +0 -9
  100. package/dist/platform/ops/org-plugins.ops.js +18 -235
  101. package/dist/platform/ops/plugins.ops.d.ts +0 -1
  102. package/dist/platform/ops/plugins.ops.js +3 -31
  103. package/dist/roles/gateway-role.d.ts +13 -6
  104. package/dist/roles/gateway-role.js +27 -9
  105. package/dist/roles/gateway.module.d.ts +2 -1
  106. package/dist/roles/gateway.module.js +13 -3
  107. package/dist/roles/worker-role.d.ts +9 -4
  108. package/dist/roles/worker-role.js +18 -5
  109. package/dist/roles/worker.module.d.ts +1 -1
  110. package/dist/roles/worker.module.js +8 -1
  111. package/dist/sandbox/device-services.d.ts +62 -0
  112. package/dist/sandbox/device-services.js +183 -0
  113. package/dist/sandbox/leases.d.ts +18 -1
  114. package/dist/sandbox/leases.js +75 -1
  115. package/dist/sandbox/network-grants.js +5 -2
  116. package/dist/sandbox/sandbox.module.d.ts +2 -1
  117. package/dist/sandbox/sandbox.module.js +5 -2
  118. package/dist/sandbox/sandbox.service.d.ts +44 -1
  119. package/dist/sandbox/sandbox.service.js +142 -5
  120. package/dist/setup/setup-guides.service.d.ts +9 -1
  121. package/dist/setup/setup-guides.service.js +38 -8
  122. package/dist/tools/admin-connectors.d.ts +3 -2
  123. package/dist/tools/admin-connectors.js +5 -4
  124. package/dist/tools/approvals.service.d.ts +45 -20
  125. package/dist/tools/approvals.service.js +19 -9
  126. package/dist/tools/call-scope.d.ts +60 -0
  127. package/dist/tools/call-scope.js +23 -0
  128. package/dist/tools/connector-setup.d.ts +28 -0
  129. package/dist/tools/connector-setup.js +33 -0
  130. package/dist/tools/connector-tools-jobs.d.ts +35 -0
  131. package/dist/tools/connector-tools-jobs.js +40 -0
  132. package/dist/tools/connector-tools.processor.d.ts +32 -0
  133. package/dist/tools/connector-tools.processor.js +97 -0
  134. package/dist/tools/connectors.controller.d.ts +1 -0
  135. package/dist/tools/connectors.schemas.d.ts +1 -0
  136. package/dist/tools/connectors.schemas.js +5 -0
  137. package/dist/tools/connectors.service.d.ts +138 -14
  138. package/dist/tools/connectors.service.js +410 -50
  139. package/dist/tools/credentials.d.ts +35 -0
  140. package/dist/tools/credentials.js +89 -1
  141. package/dist/tools/drift.d.ts +5 -0
  142. package/dist/tools/drift.js +21 -2
  143. package/dist/tools/editable-endpoint.d.ts +23 -0
  144. package/dist/tools/editable-endpoint.js +92 -0
  145. package/dist/tools/network-asks.d.ts +13 -0
  146. package/dist/tools/network-asks.js +26 -2
  147. package/dist/tools/oauth/flow.d.ts +1 -1
  148. package/dist/tools/oauth/flow.js +3 -2
  149. package/dist/tools/pipeline.d.ts +30 -1
  150. package/dist/tools/pipeline.js +299 -59
  151. package/dist/tools/questions.service.d.ts +24 -3
  152. package/dist/tools/questions.service.js +3 -1
  153. package/dist/tools/registry.d.ts +14 -2
  154. package/dist/tools/registry.js +27 -6
  155. package/dist/tools/tools.module.js +4 -0
  156. package/package.json +3 -3
  157. package/src/migrations/0183_connectors_created_by_nullable.sql +5 -0
@@ -1,5 +1,10 @@
1
+ import { type DeviceStream } from "@capybara-hq/plugin-sdk";
1
2
  import { KernelDb } from "../infra/database/kernel-db.js";
2
3
  import { DialInRelay, type DialInRequestOptions } from "./relay.js";
4
+ /** What opens streams on the machine sockets this process holds (`DialInGateway`). */
5
+ export interface DialInStreamOpener {
6
+ openStream(deviceId: string, body: unknown, signal: AbortSignal): Promise<DeviceStream>;
7
+ }
3
8
  /**
4
9
  * What `ctx.dialIn` is built from (`ctx/create-ctx.ts`): the relay, and the check that a device is
5
10
  * served by the calling extension. Kept below the extension host (its module imports nothing but
@@ -8,6 +13,11 @@ import { DialInRelay, type DialInRequestOptions } from "./relay.js";
8
13
  export declare class DialInAccess {
9
14
  private readonly kdb;
10
15
  private readonly relay;
16
+ /**
17
+ * The gateway of this process, when it runs the gateway role: it registers itself at
18
+ * construction (`DialInGateway` sits above this module, so it cannot be injected here).
19
+ */
20
+ private streams;
11
21
  constructor(kdb: KernelDb, relay: Pick<DialInRelay, "request" | "online" | "capacity" | "stop">);
12
22
  /**
13
23
  * Whether `deviceId` is a live device (in a live org) whose `devices.provider` is `plugin`, and
@@ -23,4 +33,13 @@ export declare class DialInAccess {
23
33
  maxFrameBytes: number;
24
34
  } | null>;
25
35
  stop(deviceId: string, reason: "drain" | "stop"): Promise<void>;
36
+ /** @internal the gateway of this process serves the streams of the sockets it holds. */
37
+ serveStreams(opener: DialInStreamOpener): void;
38
+ /**
39
+ * Opens a stream on the machine's socket, which only the gateway replica holding it can do
40
+ * (`DialInGateway.openStream`). A process without the gateway role throws
41
+ * `DialInStreamElsewhereError` when some replica holds the machine, `DeviceOfflineError` when
42
+ * none does.
43
+ */
44
+ openStream(deviceId: string, body: unknown, signal: AbortSignal): Promise<DeviceStream>;
26
45
  }
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
+ import { DeviceOfflineError, DialInStreamElsewhereError, } from "@capybara-hq/plugin-sdk";
10
11
  import { Inject, Injectable } from "@nestjs/common";
11
12
  import { isExtensionEnabled } from "../extensions/enabled.js";
12
13
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -19,6 +20,11 @@ import { DialInRelay } from "./relay.js";
19
20
  let DialInAccess = class DialInAccess {
20
21
  kdb;
21
22
  relay;
23
+ /**
24
+ * The gateway of this process, when it runs the gateway role: it registers itself at
25
+ * construction (`DialInGateway` sits above this module, so it cannot be injected here).
26
+ */
27
+ streams;
22
28
  constructor(kdb, relay) {
23
29
  this.kdb = kdb;
24
30
  this.relay = relay;
@@ -58,6 +64,23 @@ let DialInAccess = class DialInAccess {
58
64
  stop(deviceId, reason) {
59
65
  return this.relay.stop(deviceId, reason);
60
66
  }
67
+ /** @internal the gateway of this process serves the streams of the sockets it holds. */
68
+ serveStreams(opener) {
69
+ this.streams = opener;
70
+ }
71
+ /**
72
+ * Opens a stream on the machine's socket, which only the gateway replica holding it can do
73
+ * (`DialInGateway.openStream`). A process without the gateway role throws
74
+ * `DialInStreamElsewhereError` when some replica holds the machine, `DeviceOfflineError` when
75
+ * none does.
76
+ */
77
+ async openStream(deviceId, body, signal) {
78
+ if (this.streams)
79
+ return this.streams.openStream(deviceId, body, signal);
80
+ if (await this.relay.online(deviceId))
81
+ throw new DialInStreamElsewhereError(deviceId);
82
+ throw new DeviceOfflineError(deviceId);
83
+ }
61
84
  };
62
85
  DialInAccess = __decorate([
63
86
  Injectable(),
@@ -1,9 +1,10 @@
1
- import { type ExtensionContext } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceStream, type ExtensionContext } from "@capybara-hq/plugin-sdk";
2
2
  import type { WebSocket } from "@fastify/websocket";
3
3
  import type { Redis } from "ioredis";
4
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
5
  import { LockService } from "../infra/lock/lock.service.js";
6
6
  import type { KernelLogger } from "../log.js";
7
+ import { DialInAccess } from "./access.js";
7
8
  import { DialInHandlers, type DialInServing, type DialInUnavailable } from "./handlers.js";
8
9
  import { DialInMachines, type MachineIdentity } from "./machines.js";
9
10
  /** WebSocket close codes the gateway uses (the program reads 4002 and 4003). */
@@ -54,6 +55,8 @@ declare class DeviceConnection {
54
55
  private readonly credential;
55
56
  /** The protocol the route admitted (the serving provider's `permissions.dialIn.protocol`). */
56
57
  private readonly protocol;
58
+ /** The local port the socket arrived on (the holder address's default port when unset). */
59
+ private readonly localPort;
57
60
  readonly token: `${string}-${string}-${string}-${string}-${string}`;
58
61
  state: State;
59
62
  private lease;
@@ -79,7 +82,11 @@ declare class DeviceConnection {
79
82
  private closeReason;
80
83
  constructor(gw: DialInGateway, socket: WebSocket, identity: MachineIdentity, credential: string,
81
84
  /** The protocol the route admitted (the serving provider's `permissions.dialIn.protocol`). */
82
- protocol: string);
85
+ protocol: string,
86
+ /** The local port the socket arrived on (the holder address's default port when unset). */
87
+ localPort: number | undefined);
88
+ /** This connection's streams (the socket's own state, ended with it). */
89
+ private readonly streams;
83
90
  /**
84
91
  * The id a connection fences requests and results with (sent to the machine in `ready`).
85
92
  * Random and separate from the lease token, which stays internal to the kernel.
@@ -93,6 +100,15 @@ declare class DeviceConnection {
93
100
  /** Consecutive failed capacity publications on ping (this socket's own state). */
94
101
  private publishFailures;
95
102
  private publishCapacity;
103
+ /**
104
+ * Where other replicas hop a device stream to: the holder record `{ token, address }` next to
105
+ * the lease (written at the claim, refreshed with the capacity), read only under that token.
106
+ */
107
+ private writeAddress;
108
+ /** Whether this connection holds its device and sent `ready` (streams may open). */
109
+ get serving(): boolean;
110
+ /** Opens a stream to the machine on this socket ({@link DialInStreams.openStream}). */
111
+ openStream(body: unknown, signal: AbortSignal): Promise<DeviceStream>;
96
112
  get deviceId(): string;
97
113
  /**
98
114
  * Runs `fn` in the device's org (RLS spec §5.3: per-event work of a long connection enters the
@@ -175,8 +191,11 @@ export type DialInAdmission = {
175
191
  * request's deadline plus a margin). A `res` is accepted only for a request taken for the socket's
176
192
  * device: it is stored under `capk:device-res:<id>` for the rest of that TTL and published on
177
193
  * `device.res.<id>`. An `event` goes to the provider's `onFrame`; the close to its `onClose`.
178
- * `device.revoked.<deviceId>` closes the connection of that machine only (ruling R16). The
179
- * sockets are this process's own; everything other replicas need is in Redis.
194
+ * `device.revoked.<deviceId>` closes the connection of that machine only (ruling R16). Device
195
+ * streams ({@link DialInStreams}) run straight over the socket, so only the holder opens them; it
196
+ * writes its internal address under `capk:device-holder-addr:<deviceId>` next to the lease for
197
+ * the other replicas to hop to. The sockets are this process's own; everything other replicas
198
+ * need is in Redis.
180
199
  */
181
200
  export declare class DialInGateway {
182
201
  readonly machines: Pick<DialInMachines, "authenticate" | "isDeviceDeleted" | "recordConnect" | "touch">;
@@ -191,9 +210,32 @@ export declare class DialInGateway {
191
210
  private stopping;
192
211
  /** How often connections are pinged ({@link PING_INTERVAL_MS}; a test seam). */
193
212
  pingIntervalMs: number;
213
+ /** How long a machine has to answer a stream open ({@link STREAM_OPEN_TIMEOUT_MS}; test seam). */
214
+ streamOpenTimeoutMs: number;
194
215
  /** How often a held connection re-checks its credential ({@link REAUTH_EVERY_MS}; test seam). */
195
216
  reauthEveryMs: number;
196
- constructor(machines: Pick<DialInMachines, "authenticate" | "isDeviceDeleted" | "recordConnect" | "touch">, handlers: Pick<DialInHandlers, "forDevice">, locks: Pick<LockService, "hold">, bus: ExtensionContext["bus"], redis: Redis, config: KernelConfigService, log: Pick<KernelLogger, "info" | "warn">);
217
+ constructor(machines: Pick<DialInMachines, "authenticate" | "isDeviceDeleted" | "recordConnect" | "touch">, handlers: Pick<DialInHandlers, "forDevice">, locks: Pick<LockService, "hold">, bus: ExtensionContext["bus"], redis: Redis, config: KernelConfigService, log: Pick<KernelLogger, "info" | "warn">, access: Pick<DialInAccess, "serveStreams">);
218
+ /**
219
+ * This replica's internal origin for device stream hops: `gateway.internalUrl`, else
220
+ * `http://<hostname>:<http.port>` (with `http.port` 0, the port the connection arrived on).
221
+ */
222
+ internalAddress(localPort?: number): string;
223
+ /** The connection of `deviceId` this replica holds and serves, if any. */
224
+ private serving;
225
+ /** Whether this replica holds `deviceId`'s machine socket (past `ready`). */
226
+ holdsLocally(deviceId: string): boolean;
227
+ /**
228
+ * The internal address of the gateway replica holding `deviceId`'s machine
229
+ * (`capk:device-holder-addr:<deviceId>`, read under the current lease token), or null when no
230
+ * replica holds it or its holder has not recorded its address yet.
231
+ */
232
+ holderAddress(deviceId: string): Promise<string | null>;
233
+ /**
234
+ * Opens a stream to `deviceId`'s machine over the socket this replica holds
235
+ * ({@link DialInStreams}). Throws `DialInStreamElsewhereError` when another replica holds it
236
+ * (hop to {@link holderAddress}), `DeviceOfflineError` when none does.
237
+ */
238
+ openStream(deviceId: string, body: unknown, signal: AbortSignal): Promise<DeviceStream>;
197
239
  graceMs(): number;
198
240
  leaseTtlMs(): number;
199
241
  maxFrameBytes(): number;
@@ -209,7 +251,7 @@ export declare class DialInGateway {
209
251
  * so a credential revoked or a provider switched off since the upgrade check never gets a
210
252
  * connection.
211
253
  */
212
- accept(socket: WebSocket, credential: string, protocol: string): Promise<void>;
254
+ accept(socket: WebSocket, credential: string, protocol: string, localPort?: number): Promise<void>;
213
255
  /**
214
256
  * How many devices this process holds the connection of (replica presence reports it): only
215
257
  * sockets past the hello that hold their device's lease, so a socket still claiming or being
@@ -8,17 +8,20 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { DIAL_IN_PROTOCOL_RE, parseDialInMachineFrame, } from "@capybara-hq/plugin-sdk";
11
+ import { hostname } from "node:os";
12
+ import { DeviceOfflineError, DIAL_IN_PROTOCOL_RE, DialInStreamElsewhereError, parseDialInMachineFrame, } from "@capybara-hq/plugin-sdk";
12
13
  import { Inject, Injectable } from "@nestjs/common";
13
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
15
  import { asPlatform, withOrgScope, withoutOrgScope } from "../infra/database/org-scope.js";
15
16
  import { LockService } from "../infra/lock/lock.service.js";
16
17
  import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
18
+ import { DialInAccess } from "./access.js";
17
19
  import { storedResult, wireFrameOf } from "./envelope.js";
18
20
  import { DialInHandlers } from "./handlers.js";
19
- import { DEVICE_TAKEN_PREFIX, deviceLeaseKey, deviceReqKey, deviceReqTopic, deviceResKey, deviceResTopic, deviceRevokedTopic, deviceTakenKey, deviceTakeoverTopic, deviceTransportKey, } from "./keys.js";
21
+ import { DEVICE_TAKEN_PREFIX, deviceHolderAddrKey, deviceLeaseKey, deviceReqKey, deviceReqTopic, deviceResKey, deviceResTopic, deviceRevokedTopic, deviceTakenKey, deviceTakeoverTopic, deviceTransportKey, } from "./keys.js";
20
22
  import { DialInMachines } from "./machines.js";
21
23
  import { LIST_TTL_MARGIN_MS } from "./relay.js";
24
+ import { DialInStreams, isStreamFrame, STREAM_OPEN_TIMEOUT_MS } from "./streams.js";
22
25
  /** WebSocket close codes the gateway uses (the program reads 4002 and 4003). */
23
26
  export const DEVICE_CLOSE = {
24
27
  /** The kernel is shutting down: reconnect (another gateway replica takes over). */
@@ -108,6 +111,41 @@ redis.call('SET', KEYS[2], ARGV[2], 'PX', ttl)
108
111
  redis.call('DEL', KEYS[1])
109
112
  return 1
110
113
  `;
114
+ /**
115
+ * Writes the holder record `ARGV[2]` (`{ token, address }`) under `KEYS[2]` for `ARGV[3]` ms, only
116
+ * while the lease `KEYS[1]` is held by the token `ARGV[1]` (a connection that lost its lease never
117
+ * overwrites its successor's address). Returns 1 when written.
118
+ */
119
+ const WRITE_ADDR = `
120
+ if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end
121
+ redis.call('SET', KEYS[2], ARGV[2], 'PX', ARGV[3])
122
+ return 1
123
+ `;
124
+ /**
125
+ * Reads the lease `KEYS[1]` and the holder record `KEYS[2]` in one step: the record's address
126
+ * only when its token is the current lease's (an expired lease or a takeover whose holder has not
127
+ * written its address yet answers nothing, never a gone or replaced replica's address).
128
+ */
129
+ const READ_ADDR = `
130
+ local holder = redis.call('GET', KEYS[1])
131
+ if not holder then return false end
132
+ local raw = redis.call('GET', KEYS[2])
133
+ if not raw then return false end
134
+ local ok, rec = pcall(cjson.decode, raw)
135
+ if not ok or type(rec) ~= 'table' or rec.token ~= holder or type(rec.address) ~= 'string' then
136
+ return false
137
+ end
138
+ return rec.address
139
+ `;
140
+ /**
141
+ * Deletes the holder's address `KEYS[2]` once the lease `KEYS[1]` is free or still the token
142
+ * `ARGV[1]`'s: a successor that already claimed the lease keeps the address it writes.
143
+ */
144
+ const DELETE_ADDR = `
145
+ local holder = redis.call('GET', KEYS[1])
146
+ if holder and holder ~= ARGV[1] then return 0 end
147
+ return redis.call('DEL', KEYS[2])
148
+ `;
111
149
  const errMsg = (e) => (e instanceof Error ? e.message : String(e));
112
150
  /** A WebSocket close reason is at most 123 UTF-8 bytes. */
113
151
  const closeReason = (text) => {
@@ -126,6 +164,7 @@ class DeviceConnection {
126
164
  identity;
127
165
  credential;
128
166
  protocol;
167
+ localPort;
129
168
  token = randomUUID();
130
169
  state = "hello";
131
170
  lease;
@@ -151,13 +190,27 @@ class DeviceConnection {
151
190
  closeReason = "offline";
152
191
  constructor(gw, socket, identity, credential,
153
192
  /** The protocol the route admitted (the serving provider's `permissions.dialIn.protocol`). */
154
- protocol) {
193
+ protocol,
194
+ /** The local port the socket arrived on (the holder address's default port when unset). */
195
+ localPort) {
155
196
  this.gw = gw;
156
197
  this.socket = socket;
157
198
  this.identity = identity;
158
199
  this.credential = credential;
159
200
  this.protocol = protocol;
201
+ this.localPort = localPort;
202
+ this.streams = new DialInStreams(identity.deviceId, {
203
+ send: (text) => {
204
+ if (this.state === "closed" || this.socket.readyState !== this.socket.OPEN)
205
+ return false;
206
+ this.socket.send(text);
207
+ return true;
208
+ },
209
+ maxFrameBytes: () => this.effectiveCap ?? 0,
210
+ }, () => this.gw.streamOpenTimeoutMs);
160
211
  }
212
+ /** This connection's streams (the socket's own state, ended with it). */
213
+ streams;
161
214
  /**
162
215
  * The id a connection fences requests and results with (sent to the machine in `ready`).
163
216
  * Random and separate from the lease token, which stays internal to the kernel.
@@ -177,11 +230,30 @@ class DeviceConnection {
177
230
  await this.close(DEVICE_CLOSE.protocol, "Frame capacity changed; reconnect");
178
231
  return;
179
232
  }
233
+ const ttl = Math.max(this.gw.leaseTtlMs(), this.gw.pingIntervalMs * 3);
180
234
  await this.gw.redis.set(deviceTransportKey(this.deviceId, this.token), JSON.stringify({
181
235
  connectionId: this.connectionId,
182
236
  maxFrameBytes: this.effectiveCap,
183
237
  ...(this.programRunId !== undefined && { programRunId: this.programRunId }),
184
- }), "PX", Math.max(this.gw.leaseTtlMs(), this.gw.pingIntervalMs * 3));
238
+ }), "PX", ttl);
239
+ await this.writeAddress();
240
+ }
241
+ /**
242
+ * Where other replicas hop a device stream to: the holder record `{ token, address }` next to
243
+ * the lease (written at the claim, refreshed with the capacity), read only under that token.
244
+ */
245
+ async writeAddress() {
246
+ await this.gw.redis.eval(WRITE_ADDR, 2, deviceLeaseKey(this.deviceId), deviceHolderAddrKey(this.deviceId), this.token, JSON.stringify({ token: this.token, address: this.gw.internalAddress(this.localPort) }), String(Math.max(this.gw.leaseTtlMs(), this.gw.pingIntervalMs * 3)));
247
+ }
248
+ /** Whether this connection holds its device and sent `ready` (streams may open). */
249
+ get serving() {
250
+ return this.state === "holding" && this.ready;
251
+ }
252
+ /** Opens a stream to the machine on this socket ({@link DialInStreams.openStream}). */
253
+ openStream(body, signal) {
254
+ if (!this.serving)
255
+ return Promise.reject(new DeviceOfflineError(this.deviceId));
256
+ return this.streams.openStream(body, signal);
185
257
  }
186
258
  get deviceId() {
187
259
  return this.identity.deviceId;
@@ -296,6 +368,11 @@ class DeviceConnection {
296
368
  this.close(DEVICE_CLOSE.protocol, "hello expected");
297
369
  return;
298
370
  }
371
+ // stream frames go to this socket's stream table, never through shared state
372
+ if (isStreamFrame(frame)) {
373
+ this.streams.onFrame(frame);
374
+ return;
375
+ }
299
376
  // results are stored in any state after ready: the program sends those it kept while
300
377
  // disconnected right after its ready
301
378
  await this.store(frame);
@@ -481,6 +558,7 @@ class DeviceConnection {
481
558
  return false;
482
559
  }
483
560
  lease.lost.addEventListener("abort", onLost, { once: true });
561
+ await this.writeAddress();
484
562
  await this.subscribe(deviceReqTopic(env), () => this.drain());
485
563
  await this.subscribe(deviceRevokedTopic(env), (p) => {
486
564
  const message = p;
@@ -690,6 +768,7 @@ class DeviceConnection {
690
768
  this.state = "closed";
691
769
  this.ready = false;
692
770
  this.ended.abort();
771
+ this.streams.closeAll();
693
772
  clearTimeout(this.helloTimer);
694
773
  clearTimeout(this.pingTimer);
695
774
  const lease = this.lease;
@@ -701,6 +780,7 @@ class DeviceConnection {
701
780
  lease.abandon();
702
781
  else
703
782
  await lease.release();
783
+ await this.gw.redis.eval(DELETE_ADDR, 2, deviceLeaseKey(this.deviceId), deviceHolderAddrKey(this.deviceId), this.token);
704
784
  }
705
785
  }
706
786
  catch (e) {
@@ -760,8 +840,11 @@ class DeviceConnection {
760
840
  * request's deadline plus a margin). A `res` is accepted only for a request taken for the socket's
761
841
  * device: it is stored under `capk:device-res:<id>` for the rest of that TTL and published on
762
842
  * `device.res.<id>`. An `event` goes to the provider's `onFrame`; the close to its `onClose`.
763
- * `device.revoked.<deviceId>` closes the connection of that machine only (ruling R16). The
764
- * sockets are this process's own; everything other replicas need is in Redis.
843
+ * `device.revoked.<deviceId>` closes the connection of that machine only (ruling R16). Device
844
+ * streams ({@link DialInStreams}) run straight over the socket, so only the holder opens them; it
845
+ * writes its internal address under `capk:device-holder-addr:<deviceId>` next to the lease for
846
+ * the other replicas to hop to. The sockets are this process's own; everything other replicas
847
+ * need is in Redis.
765
848
  */
766
849
  let DialInGateway = class DialInGateway {
767
850
  machines;
@@ -776,9 +859,11 @@ let DialInGateway = class DialInGateway {
776
859
  stopping = false;
777
860
  /** How often connections are pinged ({@link PING_INTERVAL_MS}; a test seam). */
778
861
  pingIntervalMs = PING_INTERVAL_MS;
862
+ /** How long a machine has to answer a stream open ({@link STREAM_OPEN_TIMEOUT_MS}; test seam). */
863
+ streamOpenTimeoutMs = STREAM_OPEN_TIMEOUT_MS;
779
864
  /** How often a held connection re-checks its credential ({@link REAUTH_EVERY_MS}; test seam). */
780
865
  reauthEveryMs = REAUTH_EVERY_MS;
781
- constructor(machines, handlers, locks, bus, redis, config, log) {
866
+ constructor(machines, handlers, locks, bus, redis, config, log, access) {
782
867
  this.machines = machines;
783
868
  this.handlers = handlers;
784
869
  this.locks = locks;
@@ -786,6 +871,55 @@ let DialInGateway = class DialInGateway {
786
871
  this.redis = redis;
787
872
  this.config = config;
788
873
  this.log = log;
874
+ // ctx.dialIn.openStream on this process reaches the sockets this gateway holds
875
+ access.serveStreams(this);
876
+ }
877
+ /**
878
+ * This replica's internal origin for device stream hops: `gateway.internalUrl`, else
879
+ * `http://<hostname>:<http.port>` (with `http.port` 0, the port the connection arrived on).
880
+ */
881
+ internalAddress(localPort) {
882
+ const c = this.config.get();
883
+ if (c.gateway.internalUrl !== undefined)
884
+ return c.gateway.internalUrl.replace(/\/+$/, "");
885
+ const port = c.http.port !== 0 ? c.http.port : (localPort ?? 0);
886
+ return `http://${hostname()}:${port}`;
887
+ }
888
+ /** The connection of `deviceId` this replica holds and serves, if any. */
889
+ serving(deviceId) {
890
+ for (const c of this.connections)
891
+ if (c.deviceId === deviceId && c.serving)
892
+ return c;
893
+ return undefined;
894
+ }
895
+ /** Whether this replica holds `deviceId`'s machine socket (past `ready`). */
896
+ holdsLocally(deviceId) {
897
+ return this.serving(deviceId) !== undefined;
898
+ }
899
+ /**
900
+ * The internal address of the gateway replica holding `deviceId`'s machine
901
+ * (`capk:device-holder-addr:<deviceId>`, read under the current lease token), or null when no
902
+ * replica holds it or its holder has not recorded its address yet.
903
+ */
904
+ async holderAddress(deviceId) {
905
+ const r = await this.redis.eval(READ_ADDR, 2, deviceLeaseKey(deviceId), deviceHolderAddrKey(deviceId));
906
+ return typeof r === "string" ? r : null;
907
+ }
908
+ /**
909
+ * Opens a stream to `deviceId`'s machine over the socket this replica holds
910
+ * ({@link DialInStreams}). Throws `DialInStreamElsewhereError` when another replica holds it
911
+ * (hop to {@link holderAddress}), `DeviceOfflineError` when none does.
912
+ */
913
+ async openStream(deviceId, body, signal) {
914
+ const conn = this.serving(deviceId);
915
+ if (conn !== undefined)
916
+ return conn.openStream(body, signal);
917
+ const holder = await this.redis.get(deviceLeaseKey(deviceId));
918
+ // a connection of this replica still claiming or before ready is not elsewhere
919
+ const mine = [...this.connections].some((c) => c.token === holder);
920
+ if (holder !== null && !mine)
921
+ throw new DialInStreamElsewhereError(deviceId);
922
+ throw new DeviceOfflineError(deviceId);
789
923
  }
790
924
  graceMs() {
791
925
  return this.config.get().devices.dialIn.reconnectGraceSeconds * 1000;
@@ -819,7 +953,7 @@ let DialInGateway = class DialInGateway {
819
953
  * so a credential revoked or a provider switched off since the upgrade check never gets a
820
954
  * connection.
821
955
  */
822
- async accept(socket, credential, protocol) {
956
+ async accept(socket, credential, protocol, localPort) {
823
957
  socket.pause();
824
958
  try {
825
959
  if (this.stopping) {
@@ -843,7 +977,7 @@ let DialInGateway = class DialInGateway {
843
977
  socket.close(DEVICE_CLOSE.protocol, "the device's provider is unavailable");
844
978
  return;
845
979
  }
846
- const conn = new DeviceConnection(this, socket, admission.identity, credential, protocol);
980
+ const conn = new DeviceConnection(this, socket, admission.identity, credential, protocol, localPort);
847
981
  this.connections.add(conn);
848
982
  conn.start();
849
983
  }
@@ -885,6 +1019,7 @@ DialInGateway = __decorate([
885
1019
  __param(3, Inject(KERNEL_BUS)),
886
1020
  __param(4, Inject(REDIS)),
887
1021
  __param(5, Inject(KernelConfigService)),
888
- __param(6, Inject(KERNEL_LOGGER))
1022
+ __param(6, Inject(KERNEL_LOGGER)),
1023
+ __param(7, Inject(DialInAccess))
889
1024
  ], DialInGateway);
890
1025
  export { DialInGateway };
@@ -4,6 +4,13 @@
4
4
  */
5
5
  /** The lease of the replica holding the machine's connection: `capk:device-lease:<deviceId>`. */
6
6
  export declare const deviceLeaseKey: (deviceId: string) => string;
7
+ /**
8
+ * The internal address (`gateway.internalUrl`, or `http://<hostname>:<port>`) of the gateway
9
+ * replica holding the machine's connection, as `{ token, address }` with the holder's lease token:
10
+ * `capk:device-holder-addr:<deviceId>`. Written by the holder next to its lease, with a TTL, and
11
+ * read only while the lease still has that token; another replica hops a device stream there.
12
+ */
13
+ export declare const deviceHolderAddrKey: (deviceId: string) => string;
7
14
  /** The list of requests waiting for the machine: `capk:device-req:<deviceId>`. */
8
15
  export declare const deviceReqKey: (deviceId: string) => string;
9
16
  /** The result of one request: `capk:device-res:<requestId>`. */
@@ -4,6 +4,13 @@
4
4
  */
5
5
  /** The lease of the replica holding the machine's connection: `capk:device-lease:<deviceId>`. */
6
6
  export const deviceLeaseKey = (deviceId) => `capk:device-lease:${deviceId}`;
7
+ /**
8
+ * The internal address (`gateway.internalUrl`, or `http://<hostname>:<port>`) of the gateway
9
+ * replica holding the machine's connection, as `{ token, address }` with the holder's lease token:
10
+ * `capk:device-holder-addr:<deviceId>`. Written by the holder next to its lease, with a TTL, and
11
+ * read only while the lease still has that token; another replica hops a device stream there.
12
+ */
13
+ export const deviceHolderAddrKey = (deviceId) => `capk:device-holder-addr:${deviceId}`;
7
14
  /** The list of requests waiting for the machine: `capk:device-req:<deviceId>`. */
8
15
  export const deviceReqKey = (deviceId) => `capk:device-req:${deviceId}`;
9
16
  /** The result of one request: `capk:device-res:<requestId>`. */
@@ -1,5 +1,6 @@
1
1
  import { type WebSocket } from "@fastify/websocket";
2
2
  import type { FastifyInstance, FastifyRequest } from "fastify";
3
+ import { type DeviceStreamRoutesOptions } from "../device-access/viewer-routes.js";
3
4
  import type { DialInAdmission } from "./gateway.js";
4
5
  /** The device connection route (environments spec §13.4). */
5
6
  export declare const DEVICE_CONNECT_ROUTE = "/device/connect";
@@ -10,12 +11,17 @@ export interface DeviceRoutesGateway {
10
11
  /** Who the credential stands for and the provider serving its device; null when unknown. */
11
12
  admit(credential: string): Promise<DialInAdmission>;
12
13
  /** Serves the upgraded socket (re-checks the credential with the socket paused). */
13
- accept(socket: WebSocket, credential: string, protocol: string): Promise<void>;
14
+ accept(socket: WebSocket, credential: string, protocol: string, localPort?: number): Promise<void>;
14
15
  }
15
16
  export interface DeviceRoutesOptions {
16
17
  gateway: DeviceRoutesGateway;
17
18
  /** `devices.dialIn.maxFrameBytes`: a larger incoming frame closes the socket (1009). */
18
19
  maxFrameBytes: number;
20
+ /**
21
+ * The device stream viewer routes (`GET /device/stream`, the hop route), registered in the same
22
+ * WebSocket scope when given (`@fastify/websocket` serves one upgrade listener per server).
23
+ */
24
+ streams?: DeviceStreamRoutesOptions;
19
25
  }
20
26
  /**
21
27
  * A WebSocket upgrade: `Upgrade` lists `websocket` and `Connection` lists `upgrade` (both
@@ -30,7 +36,8 @@ export declare function isWebSocketUpgrade(req: FastifyRequest): boolean;
30
36
  */
31
37
  export declare function protocolMismatchMessage(plugin: string, expected: string, spoken: unknown): string;
32
38
  /**
33
- * Registers `GET /device/connect` (the gateway role only) in its own encapsulated scope with
39
+ * Registers `GET /device/connect` (the gateway role only), and with `opts.streams` the device
40
+ * stream viewer routes (`device-access/viewer-routes.ts`), in its own encapsulated scope with
34
41
  * `@fastify/websocket`: a raw Fastify route outside Nest, so neither the API's `AuthGuard` nor its
35
42
  * CSRF check applies. Before the upgrade the route checks the machine credential (401
36
43
  * `device.credential_invalid`), then the device's provider: off in the org, not loaded or not a
@@ -40,7 +47,8 @@ export declare function protocolMismatchMessage(plugin: string, expected: string
40
47
  * Must be called before Nest `app.init()`, on the root instance.
41
48
  *
42
49
  * `@fastify/websocket` sends every upgrade request of the server through the Fastify router; the
43
- * root hooks below keep that from reaching any other route: a WebSocket upgrade to another path
50
+ * root hooks below keep that from reaching any other route: a WebSocket upgrade to a path not in
51
+ * {@link UPGRADE_ROUTES}
44
52
  * is answered 404 and its socket closed once answered (Node would have dropped it without a
45
53
  * listener). Other upgrades (`h2c`) reach their route as ordinary requests; their socket, which
46
54
  * no HTTP connection owns any more, is closed once answered as well (the upgrade is declined).
@@ -1,9 +1,16 @@
1
1
  import websocket, {} from "@fastify/websocket";
2
+ import { DEVICE_STREAM_HOP_ROUTE, DEVICE_STREAM_ROUTE, registerDeviceStreamRoutes, } from "../device-access/viewer-routes.js";
2
3
  import { errorBody } from "../errors.js";
3
4
  /** The device connection route (environments spec §13.4). */
4
5
  export const DEVICE_CONNECT_ROUTE = "/device/connect";
5
6
  /** The header carrying the dial-in protocol the program speaks (`<name>/<major>`). */
6
7
  export const DEVICE_PROTOCOL_HEADER = "x-capybara-device-protocol";
8
+ /** The routes of the gateway role that accept a WebSocket upgrade. */
9
+ const UPGRADE_ROUTES = new Set([
10
+ DEVICE_CONNECT_ROUTE,
11
+ DEVICE_STREAM_ROUTE,
12
+ DEVICE_STREAM_HOP_ROUTE,
13
+ ]);
7
14
  /** The comma-separated tokens of a header, lowercased. */
8
15
  function tokens(v) {
9
16
  return [v ?? []]
@@ -54,7 +61,8 @@ export function protocolMismatchMessage(plugin, expected, spoken) {
54
61
  return `This device is served by ${plugin}, which speaks ${expected}; ${said}. ${fix}`;
55
62
  }
56
63
  /**
57
- * Registers `GET /device/connect` (the gateway role only) in its own encapsulated scope with
64
+ * Registers `GET /device/connect` (the gateway role only), and with `opts.streams` the device
65
+ * stream viewer routes (`device-access/viewer-routes.ts`), in its own encapsulated scope with
58
66
  * `@fastify/websocket`: a raw Fastify route outside Nest, so neither the API's `AuthGuard` nor its
59
67
  * CSRF check applies. Before the upgrade the route checks the machine credential (401
60
68
  * `device.credential_invalid`), then the device's provider: off in the org, not loaded or not a
@@ -64,14 +72,15 @@ export function protocolMismatchMessage(plugin, expected, spoken) {
64
72
  * Must be called before Nest `app.init()`, on the root instance.
65
73
  *
66
74
  * `@fastify/websocket` sends every upgrade request of the server through the Fastify router; the
67
- * root hooks below keep that from reaching any other route: a WebSocket upgrade to another path
75
+ * root hooks below keep that from reaching any other route: a WebSocket upgrade to a path not in
76
+ * {@link UPGRADE_ROUTES}
68
77
  * is answered 404 and its socket closed once answered (Node would have dropped it without a
69
78
  * listener). Other upgrades (`h2c`) reach their route as ordinary requests; their socket, which
70
79
  * no HTTP connection owns any more, is closed once answered as well (the upgrade is declined).
71
80
  */
72
81
  export async function registerDeviceConnectRoute(fastify, opts) {
73
82
  fastify.addHook("onRequest", async (req, reply) => {
74
- if (!isWebSocketUpgrade(req) || req.routeOptions.url === DEVICE_CONNECT_ROUTE)
83
+ if (!isWebSocketUpgrade(req) || UPGRADE_ROUTES.has(req.routeOptions.url ?? ""))
75
84
  return;
76
85
  return reply
77
86
  .code(404)
@@ -116,7 +125,9 @@ export async function registerDeviceConnectRoute(fastify, opts) {
116
125
  socket.close(4400, "not authenticated");
117
126
  return;
118
127
  }
119
- void opts.gateway.accept(socket, a.credential, a.protocol);
128
+ void opts.gateway.accept(socket, a.credential, a.protocol, req.socket.localPort);
120
129
  });
130
+ if (opts.streams)
131
+ await registerDeviceStreamRoutes(scope, opts.streams);
121
132
  });
122
133
  }
@@ -0,0 +1,58 @@
1
+ import { type DeviceStream, type DialInMachineFrame } from "@capybara-hq/plugin-sdk";
2
+ /**
3
+ * The `code` of the error a stream's `send` rejects with when a message does not fit one frame
4
+ * once base64-encoded (the viewer endpoint answers it with 1009).
5
+ */
6
+ export declare const DEVICE_STREAM_MESSAGE_TOO_BIG = "device.stream_message_too_big";
7
+ /** The stream frames a machine sends ({@link DialInStreams.onFrame}). */
8
+ export type DialInMachineStreamFrame = Extract<DialInMachineFrame, {
9
+ type: "stream-opened" | "stream-data" | "stream-credit" | "stream-close";
10
+ }>;
11
+ /** Whether a machine frame belongs to a stream (routed to {@link DialInStreams.onFrame}). */
12
+ export declare function isStreamFrame(frame: DialInMachineFrame): frame is DialInMachineStreamFrame;
13
+ /** What a connection's stream table needs from its socket. */
14
+ export interface DialInStreamTransport {
15
+ /** Sends one frame's text on the socket; false when the socket is no longer open. */
16
+ send(text: string): boolean;
17
+ /** The connection's negotiated frame capacity in UTF-8 bytes. */
18
+ maxFrameBytes(): number;
19
+ }
20
+ /** The reason every stream of a connection ends with when its socket closes. */
21
+ export declare const STREAM_OFFLINE_REASON = "device-offline";
22
+ /** How long the machine has to answer `stream-open` ({@link DialInStreams.openStream}). */
23
+ export declare const STREAM_OPEN_TIMEOUT_MS = 15000;
24
+ /**
25
+ * The streams of one machine connection on the gateway replica holding its socket (browser use
26
+ * spec §6.1): opened with `stream-open`, carried as `stream-data` frames straight over the socket
27
+ * (never through Redis or PG), each side sending only while it holds credit
28
+ * ({@link DIAL_IN_STREAM_INITIAL_CREDIT} at the open, one more per message the other side
29
+ * consumed). A data frame carries one whole message in base64; a message that does not fit the
30
+ * connection's frame capacity is refused, never split. The table is the connection's own state and
31
+ * lives exactly as long as the socket: its close ends every stream with
32
+ * {@link STREAM_OFFLINE_REASON}.
33
+ */
34
+ export declare class DialInStreams {
35
+ private readonly deviceId;
36
+ private readonly transport;
37
+ /** How long the machine has to answer an open ({@link STREAM_OPEN_TIMEOUT_MS}). */
38
+ private readonly openTimeoutMs;
39
+ private readonly open;
40
+ /** Streams sent `stream-open` and not answered yet. */
41
+ private readonly opening;
42
+ private ended;
43
+ constructor(deviceId: string, transport: DialInStreamTransport,
44
+ /** How long the machine has to answer an open ({@link STREAM_OPEN_TIMEOUT_MS}). */
45
+ openTimeoutMs?: () => number);
46
+ /**
47
+ * Opens a stream: sends `stream-open` with `body` and resolves once the machine answered
48
+ * `stream-opened` ok. A refusal rejects with the machine's error; `signal` bounds the opening
49
+ * only (an abort sends `stream-close` and rejects with the signal's reason), and so does the
50
+ * kernel's own deadline ({@link STREAM_OPEN_TIMEOUT_MS}: `stream-close` and a clear error); the
51
+ * socket's close rejects with `DeviceOfflineError`.
52
+ */
53
+ openStream(body: unknown, signal: AbortSignal): Promise<DeviceStream>;
54
+ /** A stream frame from the machine; a frame of a stream that is not open is dropped. */
55
+ onFrame(frame: DialInMachineStreamFrame): void;
56
+ /** The socket closed: every stream ends, every opening fails. */
57
+ closeAll(): void;
58
+ }