@braedonsaunders/appkit-desk 0.5.1 → 0.7.0

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.
package/README.md CHANGED
@@ -112,6 +112,12 @@ stops, the disk persists, applications cold-start on `resume`. Keep-alive jobs
112
112
  die with the lease, and their termination is recorded as `job_exit` so no
113
113
  process ever runs where an operator cannot see it.
114
114
 
115
+ `host.shutdown(deskId)` is a restart, not a destroy: a resident desk is synced
116
+ and shut down instead of parked, a parked desk's memory snapshot is discarded,
117
+ and the overlay stays, so the next `start` or `resume` cold boots from disk.
118
+ Use it when a desk must come back fresh — new memory or vCPU settings, or a
119
+ guest wedged in a way a resume would bring straight back.
120
+
115
121
  Residency is bounded by a hard capacity cap. Starts beyond the cap queue FIFO
116
122
  rather than overcommitting host memory. `host.stats()` reports
117
123
  `{ resident, queued, capacity, suspended, lastStartedAt, lastSuspendedAt,
@@ -179,7 +185,8 @@ append-only record that cannot be edited afterward.
179
185
 
180
186
  `onEvent` receives a closed union — `shell_command`, `app_launch`, `click`,
181
187
  `type`, `key`, `scroll`, `drag`, `window_focus`, `screen_open`,
182
- `screen_close`, `handover_begin`, `handover_end`, `job_start`, `job_exit` —
188
+ `screen_close`, `handover_begin`, `handover_end`, `job_start`, `job_exit`,
189
+ `snapshot_cpu_fallback` —
183
190
  each stamped with `deskId` and an ISO timestamp. The union is defined here so
184
191
  the consumer's ledger and this package agree on the taxonomy; persistence is
185
192
  entirely the consumer's concern.
@@ -231,3 +238,23 @@ masking boundary changes.
231
238
  Do not fall back to unconfined execution when this package reports an
232
239
  unsupported host. A deployment without KVM loses the desk ability entirely —
233
240
  the same fail-closed posture as the rest of AppKit.
241
+
242
+ ## Routed guest networking and TCP services
243
+
244
+ `deskNetworkIdentity(index)` returns a deterministic TAP name and MAC address. `createDeskNetwork({ gateway, dns, egress, chainPrefix?, allowHostPorts?, prefixLength?, runner?, enableForwarding? })` provides routed point-to-point TAP setup. Set `egress: { mode: 'open' }` to masquerade guest-originated IPv4 traffic for arbitrary TCP and UDP; IPv6 traffic on the TAP is blocked with `ip6tables` so it cannot bypass host isolation; new inbound forwarded connections are dropped. Set `egress: { mode: 'proxied', httpProxyPort, httpsProxyPort }` to transparently redirect HTTP and HTTPS to proxy listeners, pin DNS to the supplied resolver, and drop other guest egress. The proxy supplies destination policy. Both modes drop new connections to host services, except TCP and UDP ports explicitly listed in `allowHostPorts` on the gateway address; proxied mode also permits its proxy listeners. Established replies to host-initiated guest connections are accepted.
245
+
246
+ The default iptables chain prefix is `desk`. Existing deployments using the `bh` chains must supply `chainPrefix: 'bh'` to retain those names during a rolling upgrade and avoid orphaning the old rules. `ensure({ tap, guest })` must finish before boot; `teardown({ tap, guest })` removes its rules and TAP after the VM stops. Configure Linux IPv4 forwarding, NET_ADMIN, `ip`, and `iptables` in the host namespace; open mode also requires `ip6tables`. When changing egress modes, tear down the old mode before installing the new one. `configureGuest(desk, { tap, guest })` configures the guest interface, route, and resolver through exec. `syncDeskGuestClock(desk, now?)` sets the guest clock after wake. Failures are reported to the caller. Operations on one TAP are serialized within the network instance; use one instance per namespace. Rule replacement uses multiple iptables commands and is not atomic: call `ensure` before the VM starts, and do not refresh rules on a live TAP.
247
+
248
+ Supply `network: { tapDevice, macAddress, guestAddress }` to `host.start`, then `await desk.connect(port)` returns a Node `Duplex` TCP stream to the guest. The caller owns the stream; suspension closes it. A service must listen on the guest interface, and its protocol and authentication remain the application's responsibility. `connectGuest` on host options injects a dialer for testing.
249
+
250
+ With `parkWithMemory`, new snapshots carry a host CPU signature. A changed signature skips restore and cold boots; Cloud Hypervisor's specific incompatible-CPUID restore error also triggers a cold boot. These outcomes increment `stats().snapshotCpuFallbacks`, set `lastSnapshotCpuFallback`, and emit `snapshot_cpu_fallback`, rather than setting `lastError`. Existing snapshots without a signature are attempted normally. Signatures are conservative CPU identity and feature fingerprints, not a guarantee of CPUID compatibility; a cold boot loses the parked process state. Keep snapshots and their overlays together.
251
+
252
+ For a disposable real-host check, provide a guest image with the desk agent and Python 3, Cloud Hypervisor, KVM, and a free TAP name and IP pair. Run from the repository root in the target network namespace with privileges to manage TAP and iptables:
253
+
254
+ ```sh
255
+ DESK_CHECK_TAP=dsk9001 DESK_CHECK_GUEST=172.30.0.2 DESK_CHECK_GATEWAY=172.30.0.1 \
256
+ DESK_CHECK_IMAGE_ROOT=/data/desk-image DESK_CHECK_BASE_IMAGE=/data/desk-image/base.img \
257
+ DESK_CHECK_TMPDIR=/data/tmp pnpm --filter @braedonsaunders/appkit-desk exec tsx scripts/check-kvm.mts
258
+ ```
259
+
260
+ Set `DESK_CHECK_KERNEL_CMDLINE` for images that require a custom root device. The check creates and removes a disposable VM, overlay, snapshot, TAP and firewall rules. It verifies a guest HTTP stream before and after memory restore; it does not verify the proxy or cross-CPU migration. Choose addresses that do not overlap existing routes.
package/backend.d.ts CHANGED
@@ -90,9 +90,40 @@ export interface DeskMachine {
90
90
  onConnectionChange?(listener: (change: DeskConnectionChange) => void): () => void;
91
91
  /** Stop the VM. Idempotent; resolves once the VMM process has exited. */
92
92
  shutdown(): Promise<void>;
93
+ /**
94
+ * Park the VM with its memory, so resuming continues the process tree.
95
+ *
96
+ * Optional: a backend with no snapshot facility simply does not offer it, and
97
+ * the host falls back to `shutdown()`. Pauses the guest, writes a snapshot to
98
+ * `snapshotDir`, then stops the VMM — and resolves only once all three have
99
+ * happened, because a caller that believed a snapshot exists when it does not
100
+ * would later refuse to boot the desk at all.
101
+ *
102
+ * The caller is responsible for quiescing the guest filesystem first. A paused
103
+ * guest still holds dirty pages that exist only in the snapshot, so a disk
104
+ * parked without a prior `sync` is consistent only *with that snapshot* —
105
+ * which matters the moment the snapshot is discarded.
106
+ */
107
+ park?(snapshotDir: string): Promise<void>;
108
+ }
109
+ export interface DeskBootHooks {
110
+ /**
111
+ * Called on a restore, after the snapshot has been read back and before the
112
+ * guest is allowed to run.
113
+ *
114
+ * This is the window in which the snapshot must be destroyed. A memory image
115
+ * is valid only against the disk it was taken with, so once the guest resumes
116
+ * and writes, any surviving snapshot describes a past that no longer matches —
117
+ * and replaying it later would corrupt the desk. Restoring paused and
118
+ * invalidating here is what makes that impossible rather than unlikely.
119
+ *
120
+ * Throwing aborts the restore: the VM is stopped and the caller is free to
121
+ * cold boot, which is safe because a paused guest has written nothing.
122
+ */
123
+ onRestored?: () => Promise<void>;
93
124
  }
94
125
  export interface DeskBackend {
95
- boot(plan: DeskLaunchPlan): Promise<DeskMachine>;
126
+ boot(plan: DeskLaunchPlan, hooks?: DeskBootHooks): Promise<DeskMachine>;
96
127
  }
97
128
  export type DeskProcessLauncher = (command: string, args: readonly string[], options: {
98
129
  identity?: DeskLauncherIdentity;
@@ -134,6 +165,17 @@ export interface CloudHypervisorBackendOptions {
134
165
  guestAgentPort?: number;
135
166
  }
136
167
  export declare function createCloudHypervisorBackend(options?: CloudHypervisorBackendOptions): DeskBackend;
168
+ /**
169
+ * Cloud Hypervisor's control plane: HTTP/1.1 over the `--api-socket` Unix
170
+ * socket. The plan has always created that socket; until now nothing spoke to
171
+ * it, because stopping a VM needed nothing more than killing the process.
172
+ *
173
+ * Pausing and snapshotting do need it, and `ch-remote` — the tool that usually
174
+ * does this — is not in the runner image. Writing the two requests by hand is a
175
+ * smaller change than adding a binary to the image, and keeps the whole
176
+ * lifecycle inside one process that already owns the socket path.
177
+ */
178
+ export type VmmApiCall = (socketPath: string, path: string, body?: Record<string, unknown>, method?: 'PUT' | 'GET') => Promise<void>;
137
179
  /** The default backend: real Cloud Hypervisor over a real vsock socket. */
138
180
  export declare const cloudHypervisorBackend: DeskBackend;
139
181
  //# sourceMappingURL=backend.d.ts.map
package/backend.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"backend.d.ts","sourceRoot":"","sources":["../src/backend.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAS,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAI7D,OAAO,KAAK,EAAE,MAAM,EA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GAC1C,WAAW,CA0Gb;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,UAAU,GAAG,CACvB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,MAAM,CAAC,EAAE,KAAK,GAAG,KAAK,KACnB,OAAO,CAAC,IAAI,CAAC,CAAA;AAqElB,2EAA2E;AAC3E,eAAO,MAAM,sBAAsB,EAAE,WAA4C,CAAA"}
package/backend.js CHANGED
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import { spawn } from 'node:child_process';
13
13
  import { randomUUID } from 'node:crypto';
14
+ import { request as httpRequest } from 'node:http';
14
15
  import { createConnection } from 'node:net';
15
16
  import { Buffer } from 'node:buffer';
16
17
  import { DeskError } from './plan.js';
@@ -58,7 +59,7 @@ export function createCloudHypervisorBackend(options = {}) {
58
59
  const reconnectRetryDelayMs = options.reconnectRetryDelayMs ?? DEFAULT_RECONNECT_RETRY_DELAY_MS;
59
60
  const killGraceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
60
61
  const guestAgentPort = options.guestAgentPort ?? GUEST_AGENT_VSOCK_PORT;
61
- async function boot(plan) {
62
+ async function boot(plan, hooks) {
62
63
  if (platform !== 'linux') {
63
64
  throw new DeskError(`The AppKit desk requires Linux; received ${platform}.`);
64
65
  }
@@ -70,6 +71,23 @@ export function createCloudHypervisorBackend(options = {}) {
70
71
  const child = launcher(plan.vmm.command, plan.vmm.args, { identity: plan.launcherIdentity });
71
72
  const log = drainOutput(child);
72
73
  const exit = watchExit(child);
74
+ // A restored guest comes back PAUSED (see the `resume=false` reasoning in
75
+ // the plan). Three things have to happen in this order and nowhere else:
76
+ // prove the restore finished, let the caller destroy the snapshot while the
77
+ // guest still cannot write, then start it.
78
+ if (plan.snapshot.restoring) {
79
+ try {
80
+ await waitForVmm(vmmApi, plan.api.socketPath, { now, exited: exit, timeoutMs: connectTimeoutMs });
81
+ await hooks?.onRestored?.();
82
+ await vmmApi(plan.api.socketPath, '/api/v1/vm.resume');
83
+ }
84
+ catch (error) {
85
+ await terminate(child, exit, killGraceMs);
86
+ const said = log.tail();
87
+ const detail = said === '' ? '' : ` The VMM said: ${said}`;
88
+ throw new DeskError(`Desk ${plan.deskId} could not be restored from ${plan.snapshot.dir}: ${errorMessage(error)}${detail}`);
89
+ }
90
+ }
73
91
  let stream;
74
92
  try {
75
93
  stream = await connectWithRetry({
@@ -117,10 +135,73 @@ export function createCloudHypervisorBackend(options = {}) {
117
135
  idFactory,
118
136
  requestTimeoutMs,
119
137
  killGraceMs,
138
+ apiSocketPath: plan.api.socketPath,
139
+ vmmApi,
120
140
  });
121
141
  }
122
142
  return { boot };
123
143
  }
144
+ const vmmApi = async (socketPath, path, body, method = 'PUT') => {
145
+ const payload = body === undefined ? undefined : Buffer.from(JSON.stringify(body), 'utf8');
146
+ await new Promise((resolve, reject) => {
147
+ const request = httpRequest({
148
+ socketPath,
149
+ path,
150
+ method,
151
+ headers: {
152
+ ...(payload ? { 'content-type': 'application/json', 'content-length': String(payload.length) } : {}),
153
+ },
154
+ }, (response) => {
155
+ // CH answers 204 with no body on success. Drain regardless: an unread
156
+ // response keeps the socket open and the next call queues behind it.
157
+ const chunks = [];
158
+ response.on('data', (chunk) => chunks.push(chunk));
159
+ response.on('end', () => {
160
+ const status = response.statusCode ?? 0;
161
+ if (status >= 200 && status < 300) {
162
+ resolve();
163
+ return;
164
+ }
165
+ const said = Buffer.concat(chunks).toString('utf8').trim().slice(0, 400);
166
+ reject(new DeskError(`${path} returned ${status}${said === '' ? '' : `: ${said}`}`));
167
+ });
168
+ });
169
+ request.on('error', (error) => reject(new DeskError(`${path} failed: ${errorMessage(error)}`)));
170
+ if (payload)
171
+ request.write(payload);
172
+ request.end();
173
+ });
174
+ };
175
+ /**
176
+ * Wait until the VMM answers its control socket.
177
+ *
178
+ * On a restore this is also the only honest signal that the snapshot was read
179
+ * back: Cloud Hypervisor creates the API socket early but does not serve
180
+ * `vm.info` until it holds a VM, so a successful call means the restore
181
+ * completed rather than merely that the process started. A VMM that exits
182
+ * instead — a corrupt snapshot, a config the host can no longer satisfy — stops
183
+ * the wait immediately rather than burning the whole timeout.
184
+ */
185
+ async function waitForVmm(call, socketPath, options) {
186
+ const deadline = options.now() + options.timeoutMs;
187
+ const retryDelayMs = options.retryDelayMs ?? 50;
188
+ let lastFailure = 'it never answered';
189
+ for (;;) {
190
+ if (options.exited.done)
191
+ throw new DeskError(`the VMM exited before it served its control socket`);
192
+ try {
193
+ await call(socketPath, '/api/v1/vm.info', undefined, 'GET');
194
+ return;
195
+ }
196
+ catch (error) {
197
+ lastFailure = errorMessage(error);
198
+ }
199
+ if (options.now() >= deadline) {
200
+ throw new DeskError(`the VMM did not answer ${socketPath} in ${options.timeoutMs}ms: ${lastFailure}`);
201
+ }
202
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
203
+ }
204
+ }
124
205
  /** The default backend: real Cloud Hypervisor over a real vsock socket. */
125
206
  export const cloudHypervisorBackend = createCloudHypervisorBackend();
126
207
  /**
@@ -323,6 +404,34 @@ function createMachine(options) {
323
404
  close(new DeskError(`Desk ${deskId} is shutting down.`), true);
324
405
  await terminate(child, exit, killGraceMs);
325
406
  },
407
+ async park(snapshotDir) {
408
+ // Close the guest channel FIRST. Pausing a VM strands whatever was in
409
+ // flight on the vsock, and a reconnect attempt against a paused guest
410
+ // would burn the whole reconnect window before giving up — so the channel
411
+ // is made terminal before the VM stops answering, exactly as shutdown
412
+ // does it.
413
+ close(new DeskError(`Desk ${deskId} is being parked.`), true);
414
+ try {
415
+ await options.vmmApi(options.apiSocketPath, '/api/v1/vm.pause');
416
+ await options.vmmApi(options.apiSocketPath, '/api/v1/vm.snapshot', {
417
+ // Three slashes: `file://` plus an absolute path. CH rejects a
418
+ // destination_url it cannot parse, and the directory must already
419
+ // exist — it writes the config and memory files into it.
420
+ destination_url: `file://${snapshotDir}`,
421
+ });
422
+ }
423
+ catch (error) {
424
+ // The VM is paused and there is no usable snapshot, which is the one
425
+ // state nothing downstream can interpret. Stop the VMM so the desk is
426
+ // plainly off, and say why — the caller falls back to a cold boot, and
427
+ // the disk is still consistent because the guest was synced before this.
428
+ await terminate(child, exit, killGraceMs);
429
+ throw error instanceof DeskError
430
+ ? new DeskError(`Desk ${deskId} could not be parked with its memory: ${error.message}`)
431
+ : new DeskError(`Desk ${deskId} could not be parked with its memory: ${errorMessage(error)}`);
432
+ }
433
+ await terminate(child, exit, killGraceMs);
434
+ },
326
435
  };
327
436
  }
328
437
  /**
package/backend.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"backend.js","sourceRoot":"","sources":["../src/backend.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAA;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEpC,OAAO,EAAE,SAAS,EAAkD,MAAM,QAAQ,CAAA;AAClF,OAAO,EACL,WAAW,EACX,YAAY,EACZ,sBAAsB,EACtB,qBAAqB,GAItB,MAAM,YAAY,CAAA;AAEnB;;;;;;;;;;GAUG;AACH,MAAM,OAAO,2BAA4B,SAAQ,SAAS;IACtC,IAAI,GAAW,6BAA6B,CAAA;CAC/D;AAmHD,MAAM,0BAA0B,GAAG,MAAM,CAAA;AACzC,MAAM,0BAA0B,GAAG,MAAM,CAAA;AACzC,MAAM,8BAA8B,GAAG,GAAG,CAAA;AAC1C,MAAM,4BAA4B,GAAG,KAAK,CAAA;AAC1C,MAAM,2BAA2B,GAAG,MAAM,CAAA;AAC1C,MAAM,gCAAgC,GAAG,GAAG,CAAA;AAC5C;;;;;GAKG;AACH,MAAM,yBAAyB,GAAG,CAAC,CAAA;AACnC,MAAM,qBAAqB,G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AAE,OAAO,CAAC,QAAQ,EAAE,GAAG;QAC1B,GAAG,EAAE,OAAO,CAAC,QAAQ,EAAE,GAAG;KAC3B,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,UAAkB;IACxC,OAAO,gBAAgB,CAAC,UAAU,CAAC,CAAA;AACrC,CAAC;AAED,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAO,CAAC,cAAc,EAAE,EAAE;QAC1C,MAAM,KAAK,GAAG,UAAU,CAAC,cAAc,EAAE,EAAE,CAAC,CAAA;QAC5C,KAAK,CAAC,KAAK,EAAE,CAAA;IACf,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC/D,CAAC","sourcesContent":["/**\n * The backend port and its default Cloud Hypervisor implementation.\n *\n * `DeskBackend` is the seam that keeps the package testable without a\n * hypervisor: the host asks a backend to boot a `DeskLaunchPlan` and gets a\n * `DeskMachine` — a request/response channel to the in-guest agent plus an\n * event subscription. CI and non-KVM developer machines inject an in-memory\n * fake; production uses `cloudHypervisorBackend`, whose process-spawning glue\n * is deliberately thin because everything that can be pure lives in the plan\n * builder and the protocol module.\n */\nimport { spawn, type ChildProcess } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { createConnection } from 'node:net'\nimport { Buffer } from 'node:buffer'\nimport type { Duplex } from 'node:stream'\nimport { DeskError, type DeskLaunchPlan, type DeskLauncherIdentity } from './plan'\nimport {\n encodeFrame,\n FrameDecoder,\n GUEST_AGENT_VSOCK_PORT,\n parseHostBoundMessage,\n type GuestCommand,\n type GuestEventMessage,\n type HostBoundMessage,\n} from './protocol'\n\n/**\n * A request that was in flight when the guest connection dropped.\n *\n * Distinct from a plain `DeskError` because the caller's next move is\n * different: this request may ALREADY HAVE RUN. The frame reached the guest,\n * and whether the guest executed it before the channel went away is not\n * knowable from the host. An `exec` may have sent mail; a `click` may have\n * landed. So the transport refuses to guess — it names the ambiguity and lets\n * the caller decide whether the operation is safe to repeat. Anything that\n * rejects with a plain `DeskError` instead never reached the guest at all.\n */\nexport class DeskRequestFateUnknownError extends DeskError {\n override readonly name: string = 'DeskRequestFateUnknownError'\n}\n\n/**\n * What happened to the transport underneath a machine.\n *\n * `reconnected` means the host lost the guest channel mid-lease and got it\n * back; the desk is usable again. It is NOT a promise that the guest is\n * unchanged — see the note on `onConnectionChange`. `lost` means it will not\n * come back on this VM and the desk needs a fresh boot.\n */\nexport type DeskConnectionChange =\n | {\n state: 'reconnected'\n deskId: string\n /** How the previous connection went away. */\n reason: string\n /** Wall-clock time the desk spent with no channel to its guest. */\n downtimeMs: number\n /** Reconnects this machine has survived, including this one. */\n reconnects: number\n }\n | {\n state: 'lost'\n deskId: string\n /** Why it is gone for good: the VMM exited, or the window ran out. */\n reason: string\n }\n\n/** A booted microVM as the host sees it: one desk, one guest-agent channel. */\nexport interface DeskMachine {\n readonly deskId: string\n /**\n * Send one request to the in-guest agent and await its correlated result.\n *\n * Rejects with `DeskError` when the guest reports an error, the request\n * times out, or the connection is gone for good — in that last case the\n * request never left the host, so repeating it is safe.\n *\n * A connection lost mid-lease is re-established rather than fatal: a call\n * that arrives while that is happening WAITS for it instead of failing.\n * A call that was already in flight when the channel dropped rejects with\n * `DeskRequestFateUnknownError`, because the host cannot tell whether the\n * guest ran it.\n */\n request(command: GuestCommand, options?: { timeoutMs?: number }): Promise<unknown>\n /**\n * Subscribe to unsolicited guest events (job exits, frames, focus changes).\n *\n * Subscriptions belong to the machine, not to the socket under it, so they\n * survive a reconnect. What does NOT survive is the guest's own capture\n * state: a guest agent that restarted has no screen, no frame encoder and\n * no video encoder, and a subscriber will simply stop receiving. Watch\n * `onConnectionChange` to notice.\n */\n subscribe(listener: (event: GuestEventMessage) => void): () => void\n /**\n * Watch the transport under this machine.\n *\n * Optional: a backend whose channel cannot drop has nothing to report. The\n * default backend reports every reconnect, because a reconnect that leaves\n * no trace turns a guest agent restarting every few minutes into a desk that\n * misbehaves for reasons nobody can find.\n */\n onConnectionChange?(listener: (change: DeskConnectionChange) => void): () => void\n /** Stop the VM. Idempotent; resolves once the VMM process has exited. */\n shutdown(): Promise<void>\n}\n\nexport interface DeskBackend {\n boot(plan: DeskLaunchPlan): Promise<DeskMachine>\n}\n\nexport type DeskProcessLauncher = (\n command: string,\n args: readonly string[],\n options: { identity?: DeskLauncherIdentity },\n) => ChildProcess\n\nexport interface CloudHypervisorBackendOptions {\n /** Spawns the VMM and image tooling; injectable for tests. */\n launcher?: DeskProcessLauncher\n /** Opens the host side of the vsock Unix socket; injectable for tests. */\n connect?: (socketPath: string) => Duplex\n platform?: NodeJS.Platform\n /**\n * Clock behind every connect and reconnect deadline. Injectable for the same\n * reason `DeskHostOptions.now` is: a test drives a window to its end by\n * moving the clock, rather than sleeping for it and hoping the machine it\n * runs on is fast enough.\n */\n now?: () => number\n idFactory?: () => string\n requestTimeoutMs?: number\n connectTimeoutMs?: number\n connectRetryDelayMs?: number\n /** Bound on a single handshake attempt; see attemptHandshake. */\n handshakeTimeoutMs?: number\n /**\n * How long a machine keeps trying to get its guest channel back after an\n * unexpected drop before declaring the desk lost. Bounded on purpose: the\n * VMM is still alive so a reconnect is cheap and usually fast, but retrying\n * forever against a guest that is never coming back is worse than failing.\n */\n reconnectWindowMs?: number\n /**\n * First delay between reconnect attempts. It doubles toward a ceiling, so\n * this is the fast first poll rather than the steady rate. Separate from\n * `connectRetryDelayMs`, which is sized for a guest that is still cold\n * booting; here the guest was up a moment ago.\n */\n reconnectRetryDelayMs?: number\n killGraceMs?: number\n guestAgentPort?: number\n}\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000\nconst DEFAULT_CONNECT_TIMEOUT_MS = 20_000\nconst DEFAULT_CONNECT_RETRY_DELAY_MS = 100\nconst DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000\nconst DEFAULT_RECONNECT_WINDOW_MS = 30_000\nconst DEFAULT_RECONNECT_RETRY_DELAY_MS = 250\n/**\n * How far the reconnect delay is allowed to double. A guest agent that systemd\n * is restarting is not helped by being hammered four times a second for the\n * whole window, and an unbounded doubling would spend most of the window\n * asleep after two failures.\n */\nconst RECONNECT_BACKOFF_CEILING = 8\nconst DEFAULT_KILL_GRACE_MS = 2_000\nconst HANDSHAKE_LINE_LIMIT = 128\n\nexport function createCloudHypervisorBackend(\n options: CloudHypervisorBackendOptions = {},\n): DeskBackend {\n const launcher = options.launcher ?? defaultLauncher\n const connect = options.connect ?? defaultConnect\n const platform = options.platform ?? process.platform\n const now = options.now ?? Date.now\n const idFactory = options.idFactory ?? randomUUID\n const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS\n const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS\n const connectRetryDelayMs = options.connectRetryDelayMs ?? DEFAULT_CONNECT_RETRY_DELAY_MS\n const handshakeTimeoutMs = options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS\n const reconnectWindowMs = options.reconnectWindowMs ?? DEFAULT_RECONNECT_WINDOW_MS\n const reconnectRetryDelayMs = options.reconnectRetryDelayMs ?? DEFAULT_RECONNECT_RETRY_DELAY_MS\n const killGraceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS\n const guestAgentPort = options.guestAgentPort ?? GUEST_AGENT_VSOCK_PORT\n\n async function boot(plan: DeskLaunchPlan): Promise<DeskMachine> {\n if (platform !== 'linux') {\n throw new DeskError(`The AppKit desk requires Linux; received ${platform}.`)\n }\n if (plan.overlay.create) {\n await runToCompletion(\n launcher(plan.overlay.create.command, plan.overlay.create.args, {\n identity: plan.launcherIdentity,\n }),\n `overlay creation for desk ${plan.deskId}`,\n )\n }\n\n const child = launcher(plan.vmm.command, plan.vmm.args, { identity: plan.launcherIdentity })\n const log = drainOutput(child)\n const exit = watchExit(child)\n let stream: Duplex\n try {\n stream = await connectWithRetry({\n connect,\n now,\n socketPath: plan.vsock.socketPath,\n port: guestAgentPort,\n timeoutMs: connectTimeoutMs,\n retryDelayMs: connectRetryDelayMs,\n attemptTimeoutMs: handshakeTimeoutMs,\n exited: exit,\n })\n } catch (error) {\n await terminate(child, exit, killGraceMs)\n const said = log.tail()\n const detail = said === '' ? '' : ` The VMM said: ${said}`\n throw error instanceof DeskError\n ? new DeskError(`${error.message}${detail}`)\n : new DeskError(\n `Could not reach the guest agent for desk ${plan.deskId}: ${errorMessage(error)}${detail}`,\n )\n }\n return createMachine({\n deskId: plan.deskId,\n child,\n exit,\n stream,\n // The same path the first connection took, deliberately: a reconnect\n // that skipped confirmGuest would adopt the very hollow handshake the\n // boot path learned not to trust.\n reconnect: (abandoned) =>\n connectWithRetry({\n connect,\n now,\n socketPath: plan.vsock.socketPath,\n port: guestAgentPort,\n timeoutMs: reconnectWindowMs,\n retryDelayMs: reconnectRetryDelayMs,\n maxRetryDelayMs: reconnectRetryDelayMs * RECONNECT_BACKOFF_CEILING,\n attemptTimeoutMs: handshakeTimeoutMs,\n exited: exit,\n exitedMessage: `the VMM for desk ${plan.deskId} exited.`,\n abandoned,\n }),\n reconnectWindowMs,\n now,\n idFactory,\n requestTimeoutMs,\n killGraceMs,\n })\n }\n\n return { boot }\n}\n\n/** The default backend: real Cloud Hypervisor over a real vsock socket. */\nexport const cloudHypervisorBackend: DeskBackend = createCloudHypervisorBackend()\n\n/**\n * The machine, and the small state machine that keeps it connected.\n *\n * A vsock channel is not a fact the host learns once at boot — the transport\n * can lie about being connected, and it can go away mid-lease for reasons that\n * have nothing to do with the desk being unusable: the guest agent restarts,\n * the socat bridge drops, a transient vsock error, the guest wedges for a\n * moment. Treating any of those as terminal stranded the desk for the rest of\n * its lease with a perfectly healthy guest behind it, answering every call\n * with \"no longer connected\". So a live connection is something this machine\n * RE-ESTABLISHES:\n *\n * live ──unexpected drop──▶ reconnecting ──confirmed guest──▶ live\n * │ │\n * │ └──window exhausted / VMM exited──▶ closed\n * └──shutdown(), VMM already exited, protocol violation───────────▶ closed\n *\n * `closed` is terminal. Nothing reconnects out of it, which is what makes\n * `shutdown()` and a dead VMM final rather than the start of a retry loop.\n */\nfunction createMachine(options: {\n deskId: string\n child: ChildProcess\n exit: ExitWatcher\n stream: Duplex\n /** Re-establishes the channel; resolves only once a guest has answered. */\n reconnect: (abandoned: () => boolean) => Promise<Duplex>\n reconnectWindowMs: number\n now: () => number\n idFactory: () => string\n requestTimeoutMs: number\n killGraceMs: number\n}): DeskMachine {\n const { deskId, child, exit, now, idFactory, requestTimeoutMs, killGraceMs, reconnectWindowMs } =\n options\n const pending = new Map<\n string,\n { resolve: (result: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }\n >()\n // Listeners live on the machine rather than on the socket, so a reconnect\n // re-points the data path at the new stream and every subscriber keeps\n // working without re-registering.\n const listeners = new Set<(event: GuestEventMessage) => void>()\n const watchers = new Set<(change: DeskConnectionChange) => void>()\n let stream = options.stream\n let state: 'live' | 'reconnecting' | 'closed' = 'live'\n let reconnects = 0\n let reconnecting: Promise<void> | null = null\n\n function failAll(error: Error): void {\n for (const entry of pending.values()) {\n clearTimeout(entry.timer)\n entry.reject(error)\n }\n pending.clear()\n }\n\n function announce(change: DeskConnectionChange): void {\n for (const watcher of [...watchers]) watcher(change)\n }\n\n function close(error: DeskError, intentional: boolean): void {\n if (state === 'closed') return\n state = 'closed'\n failAll(error)\n stream.destroy()\n // A desk the consumer asked to stop is not news; one that stopped on its\n // own is the thing an operator needs to be told about.\n if (!intentional) announce({ state: 'lost', deskId, reason: error.message })\n }\n\n function attach(next: Duplex): void {\n stream = next\n // Each connection decodes with its OWN decoder: a frame the drop cut in\n // half must never be completed by the first bytes of its replacement.\n const decoder = new FrameDecoder()\n const current = () => stream === next && state !== 'closed'\n const onData = (chunk: Buffer): void => {\n if (!current()) return\n let values: unknown[]\n try {\n values = decoder.push(chunk)\n } catch (error) {\n close(\n new DeskError(`Guest agent protocol violation on desk ${deskId}: ${errorMessage(error)}`),\n false,\n )\n return\n }\n for (const value of values) {\n let message: HostBoundMessage\n try {\n message = parseHostBoundMessage(value)\n } catch (error) {\n close(\n new DeskError(`Guest agent sent a malformed message on desk ${deskId}: ${errorMessage(error)}`),\n false,\n )\n return\n }\n if ('id' in message) {\n const entry = pending.get(message.id)\n if (!entry) continue\n pending.delete(message.id)\n clearTimeout(entry.timer)\n if (message.ok) entry.resolve(message.result)\n else entry.reject(new DeskError(`Guest agent error on desk ${deskId}: ${message.error}`))\n } else {\n for (const listener of [...listeners]) listener(message)\n }\n }\n }\n next.on('data', onData)\n next.once('close', () => {\n drop(next, `the guest agent connection closed on desk ${deskId}`)\n })\n next.once('error', (error: Error) => {\n drop(next, `the guest agent connection failed on desk ${deskId}: ${error.message}`)\n })\n }\n\n function drop(from: Duplex, reason: string): void {\n if (state !== 'live' || from !== stream) return\n from.destroy()\n if (exit.done) {\n // A dead VMM is not a connection problem. There is no guest to get back\n // to, and retrying against it forever only delays the fresh boot the\n // desk actually needs.\n close(new DeskError(`Desk ${deskId} is no longer connected: the VMM exited (${reason}).`), false)\n return\n }\n state = 'reconnecting'\n const lostAt = now()\n // In-flight requests CANNOT be silently retried. Each of their frames\n // already reached the guest, and whether the guest ran it before the\n // channel went away is not knowable from here: an `exec` may have sent\n // mail, a `click` may have landed. Replaying a side-effecting operation to\n // paper over a blip is the wrong kind of resilience, so every one of them\n // is told its fate is unknown and the caller decides.\n failAll(\n new DeskRequestFateUnknownError(\n `Desk ${deskId} lost its guest agent connection while this request was in flight `\n + `(${reason}); the guest may or may not have run it.`,\n ),\n )\n reconnecting = restore(reason, lostAt)\n }\n\n /** Always resolves: callers await it to learn the outcome, not to be thrown at. */\n async function restore(reason: string, lostAt: number): Promise<void> {\n let next: Duplex\n try {\n next = await options.reconnect(() => state !== 'reconnecting')\n } catch (error) {\n close(\n new DeskError(\n `Desk ${deskId} lost its guest agent connection and could not get it back: ${errorMessage(error)}`,\n ),\n false,\n )\n return\n }\n if (state !== 'reconnecting') {\n // shutdown() won the race while the replacement socket was coming up.\n next.destroy()\n return\n }\n attach(next)\n state = 'live'\n reconnects += 1\n announce({ state: 'reconnected', deskId, reason, downtimeMs: now() - lostAt, reconnects })\n }\n\n attach(options.stream)\n\n return {\n deskId,\n async request(command, requestOptions = {}) {\n // A call that lands mid-reconnect waits for it rather than failing on\n // the spot: the guest is usually back within seconds, and telling a\n // caller a desk is gone when it is about to be fine is the bug this\n // machine exists to end. The wait is bounded by the same window the\n // reconnect itself is.\n const waitUntil = now() + reconnectWindowMs\n while (state === 'reconnecting') {\n const attempt = reconnecting\n if (!attempt || now() >= waitUntil) break\n await attempt\n }\n if (state !== 'live') {\n // This one never left the host, so — unlike a request that was in\n // flight when the channel dropped — repeating it is safe.\n throw new DeskError(`Desk ${deskId} is no longer connected.`)\n }\n const id = idFactory()\n const timeoutMs = requestOptions.timeoutMs ?? requestTimeoutMs\n const target = stream\n return await new Promise<unknown>((resolvePromise, rejectPromise) => {\n const timer = setTimeout(() => {\n pending.delete(id)\n rejectPromise(new DeskError(`Guest request ${command.op} timed out on desk ${deskId}.`))\n }, timeoutMs)\n timer.unref()\n pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer })\n target.write(encodeFrame({ ...command, id }))\n })\n },\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n onConnectionChange(listener) {\n watchers.add(listener)\n return () => {\n watchers.delete(listener)\n }\n },\n async shutdown() {\n // Terminal by construction: `closed` is the state the reconnect loop\n // checks, so an explicit shutdown can never be followed by a reconnect.\n close(new DeskError(`Desk ${deskId} is shutting down.`), true)\n await terminate(child, exit, killGraceMs)\n },\n }\n}\n\ninterface ExitWatcher {\n done: boolean\n promise: Promise<void>\n}\n\n/**\n * Read the VMM's stdout and stderr, and keep only the last few kilobytes.\n *\n * This is not for logging — it is load-bearing. The child is spawned with\n * both streams as PIPES, and a pipe nobody reads fills after about 64KB, at\n * which point the VMM BLOCKS on its next write. Cloud Hypervisor logs while\n * it runs, so an unread pipe freezes the guest partway through boot: the\n * process is alive, the disk is untouched, and the guest agent never reaches\n * vsock. Every symptom points at the image and none of them are its fault.\n *\n * Draining costs nothing and buys the tail of what the VMM said, which is the\n * difference between \"the VMM exited\" and knowing why.\n */\nfunction drainOutput(child: ChildProcess, limit = 8 * 1024): { tail: () => string } {\n let buffered = ''\n const absorb = (chunk: unknown) => {\n buffered += String(chunk)\n if (buffered.length > limit) buffered = buffered.slice(buffered.length - limit)\n }\n child.stdout?.on('data', absorb)\n child.stderr?.on('data', absorb)\n // A pipe that errors must not take the process down with it.\n child.stdout?.on('error', () => undefined)\n child.stderr?.on('error', () => undefined)\n return { tail: () => buffered.trim() }\n}\n\nfunction watchExit(child: ChildProcess): ExitWatcher {\n const watcher: ExitWatcher = { done: false, promise: Promise.resolve() }\n watcher.promise = new Promise<void>((resolvePromise) => {\n const settle = () => {\n watcher.done = true\n resolvePromise()\n }\n child.once('exit', settle)\n child.once('error', settle)\n })\n return watcher\n}\n\nasync function terminate(child: ChildProcess, exit: ExitWatcher, killGraceMs: number): Promise<void> {\n if (exit.done) return\n child.kill('SIGTERM')\n const forceKill = setTimeout(() => {\n if (!exit.done) child.kill('SIGKILL')\n }, killGraceMs)\n forceKill.unref()\n await exit.promise\n clearTimeout(forceKill)\n}\n\nfunction runToCompletion(child: ChildProcess, label: string): Promise<void> {\n return new Promise<void>((resolvePromise, rejectPromise) => {\n let stderr = ''\n child.stderr?.on('data', (chunk) => {\n stderr += String(chunk)\n })\n child.once('error', (error) => {\n rejectPromise(new DeskError(`${label} failed to start: ${error.message}`))\n })\n child.once('exit', (code, signal) => {\n if (code === 0) {\n resolvePromise()\n return\n }\n const detail = stderr.trim()\n rejectPromise(\n new DeskError(\n `${label} exited with code ${code ?? 'unknown'}`\n + `${signal ? ` (${signal})` : ''}${detail ? `: ${detail}` : '.'}`,\n ),\n )\n })\n })\n}\n\n/**\n * Cloud Hypervisor exposes guest vsock ports through a host Unix socket with\n * a line-oriented preamble: the client writes `CONNECT <port>\\n` and the VMM\n * answers `OK <assigned>\\n` before the byte stream becomes the guest\n * connection. The VMM creates the socket during boot, so connection attempts\n * retry until the deadline.\n *\n * The same loop serves the first connection and every later reconnect, so a\n * reconnect gets `confirmGuest` too — a mid-lease reconnect that trusted the\n * banner would re-adopt exactly the hollow stream the boot path learned not to.\n */\nasync function connectWithRetry(options: {\n connect: (socketPath: string) => Duplex\n now: () => number\n socketPath: string\n port: number\n timeoutMs: number\n retryDelayMs: number\n /** Ceiling the delay doubles toward; omitted keeps the delay constant. */\n maxRetryDelayMs?: number\n attemptTimeoutMs: number\n exited: ExitWatcher\n /** A dead VMM means something different at boot than it does mid-lease. */\n exitedMessage?: string\n /** Stops the loop early when the caller no longer wants the connection. */\n abandoned?: () => boolean\n}): Promise<Duplex> {\n const deadline = options.now() + options.timeoutMs\n let lastFailure = 'the guest agent never answered'\n let retryDelayMs = options.retryDelayMs\n while (options.now() <= deadline) {\n if (options.exited.done) {\n throw new DeskError(options.exitedMessage ?? 'The VMM exited before the guest agent came up.')\n }\n if (options.abandoned?.() === true) {\n throw new DeskError('the connection attempt was abandoned.')\n }\n try {\n const stream = await attemptHandshake(\n options.connect,\n options.socketPath,\n options.port,\n options.attemptTimeoutMs,\n )\n try {\n await confirmGuest(stream, options.attemptTimeoutMs)\n } catch (error) {\n stream.destroy()\n throw error\n }\n return stream\n } catch (error) {\n lastFailure = errorMessage(error)\n }\n await delay(retryDelayMs)\n if (options.maxRetryDelayMs !== undefined) {\n retryDelayMs = Math.min(retryDelayMs * 2, options.maxRetryDelayMs)\n }\n }\n throw new DeskError(\n `Timed out connecting to the guest agent at ${options.socketPath}: ${lastFailure}`,\n )\n}\n\n/**\n * One handshake attempt, which MUST settle.\n *\n * Cloud Hypervisor accepts a connection on the vsock socket whether or not\n * anything in the guest is listening on the port, and when nothing is it may\n * answer nothing at all: no reply, no error, no close. Without a deadline of\n * its own this promise then never settles — and because the caller awaits it\n * inside the retry loop, the loop stops iterating, the overall deadline is\n * never re-checked, and the boot hangs forever rather than failing. That is\n * indistinguishable from a wedged host and it is why every attempt is bounded\n * here as well as in aggregate.\n */\n/**\n * Prove a guest is behind the handshake by asking it something.\n *\n * Cloud Hypervisor answers `CONNECT <port>` with `OK` whether or not anything\n * in the guest is listening on that port, and only closes the socket a moment\n * later when it finds nobody there. A caller that trusts the banner therefore\n * \"connects\" to a guest that is still booting, gets a closed stream seconds\n * later, and — because a closed machine is not retried — leaves the desk dead\n * for as long as it is leased, with a healthy guest sitting behind it. So the\n * handshake is not the test; a reply is.\n */\nasync function confirmGuest(stream: Duplex, timeoutMs: number): Promise<void> {\n const decoder = new FrameDecoder()\n await new Promise<void>((resolvePromise, rejectPromise) => {\n let settled = false\n const finish = (error?: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n stream.off('data', onData)\n stream.off('close', onClose)\n stream.off('error', finish)\n if (error) rejectPromise(error)\n else resolvePromise()\n }\n const timer = setTimeout(\n () => finish(new DeskError('the guest agent did not answer the first request.')),\n timeoutMs,\n )\n timer.unref?.()\n const onClose = () =>\n finish(new DeskError('the connection closed before the guest agent answered.'))\n const onData = (chunk: Buffer) => {\n let values: unknown[]\n try {\n values = decoder.push(chunk)\n } catch (error) {\n finish(error instanceof Error ? error : new Error(String(error)))\n return\n }\n for (const value of values) {\n // Anything at all proves a guest is there; the reply is parsed for\n // real by the machine once it owns the stream.\n if (value && typeof value === 'object') {\n finish()\n return\n }\n }\n }\n stream.on('data', onData)\n stream.once('close', onClose)\n stream.once('error', finish)\n stream.write(encodeFrame({ id: 'hello', op: 'ping' }))\n })\n}\n\nfunction attemptHandshake(\n connect: (socketPath: string) => Duplex,\n socketPath: string,\n port: number,\n attemptTimeoutMs: number,\n): Promise<Duplex> {\n return new Promise<Duplex>((resolvePromise, rejectPromise) => {\n let stream: Duplex\n try {\n stream = connect(socketPath)\n } catch (error) {\n rejectPromise(error instanceof Error ? error : new Error(String(error)))\n return\n }\n let banner = ''\n let settled = false\n const timer = setTimeout(() => {\n fail(new DeskError('vsock handshake went unanswered.'))\n }, attemptTimeoutMs)\n // An unref'd timer must not hold the process open on its own.\n timer.unref?.()\n const fail = (error: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n stream.destroy()\n rejectPromise(error)\n }\n const onData = (chunk: Buffer) => {\n banner += chunk.toString('latin1')\n const newline = banner.indexOf('\\n')\n if (newline === -1) {\n if (banner.length > HANDSHAKE_LINE_LIMIT) {\n fail(new DeskError('vsock handshake reply exceeded the line limit.'))\n }\n return\n }\n const line = banner.slice(0, newline)\n const rest = banner.slice(newline + 1)\n stream.off('data', onData)\n stream.off('error', fail)\n if (!line.startsWith('OK ')) {\n fail(new DeskError(`vsock handshake was refused: ${line}`))\n return\n }\n settled = true\n clearTimeout(timer)\n if (rest.length > 0) stream.unshift(Buffer.from(rest, 'latin1'))\n resolvePromise(stream)\n }\n stream.on('data', onData)\n stream.once('error', fail)\n // A close before the banner is a refusal, not a hang.\n stream.once('close', () => fail(new DeskError('vsock handshake closed before a reply.')))\n stream.write(`CONNECT ${port}\\n`)\n })\n}\n\nfunction defaultLauncher(\n command: string,\n args: readonly string[],\n options: { identity?: DeskLauncherIdentity },\n): ChildProcess {\n return spawn(command, [...args], {\n stdio: ['ignore', 'pipe', 'pipe'],\n uid: options.identity?.uid,\n gid: options.identity?.gid,\n })\n}\n\nfunction defaultConnect(socketPath: string): Duplex {\n return createConnection(socketPath)\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise<void>((resolvePromise) => {\n const timer = setTimeout(resolvePromise, ms)\n timer.unref()\n })\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n"]}
1
+ {"version":3,"file":"backend.js","sourceRoot":"","sources":["../src/backend.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,KAAK,EAAqB,MAA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OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,SAAS,CAAC,wCAAwC,CAAC,CAAC,CAAC,CAAA;QACzF,MAAM,CAAC,KAAK,CAAC,WAAW,IAAI,IAAI,CAAC,CAAA;IACnC,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,eAAe,CACtB,OAAe,EACf,IAAuB,EACvB,OAA4C;IAE5C,OAAO,KAAK,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE;QAC/B,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC;QACjC,GAAG,EAAE,OAAO,CAAC,QAAQ,EAAE,GAAG;QAC1B,GAAG,EAAE,OAAO,CAAC,QAAQ,EAAE,GAAG;KAC3B,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,UAAkB;IACxC,OAAO,gBAAgB,CAAC,UAAU,CAAC,CAAA;AACrC,CAAC;AAED,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAO,CAAC,cAAc,EAAE,EAAE;QAC1C,MAAM,KAAK,GAAG,UAAU,CAAC,cAAc,EAAE,EAAE,CAAC,CAAA;QAC5C,KAAK,CAAC,KAAK,EAAE,CAAA;IACf,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC/D,CAAC","sourcesContent":["/**\n * The backend port and its default Cloud Hypervisor implementation.\n *\n * `DeskBackend` is the seam that keeps the package testable without a\n * hypervisor: the host asks a backend to boot a `DeskLaunchPlan` and gets a\n * `DeskMachine` — a request/response channel to the in-guest agent plus an\n * event subscription. CI and non-KVM developer machines inject an in-memory\n * fake; production uses `cloudHypervisorBackend`, whose process-spawning glue\n * is deliberately thin because everything that can be pure lives in the plan\n * builder and the protocol module.\n */\nimport { spawn, type ChildProcess } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { request as httpRequest } from 'node:http'\nimport { createConnection } from 'node:net'\nimport { Buffer } from 'node:buffer'\nimport type { Duplex } from 'node:stream'\nimport { DeskError, type DeskLaunchPlan, type DeskLauncherIdentity } from './plan'\nimport {\n encodeFrame,\n FrameDecoder,\n GUEST_AGENT_VSOCK_PORT,\n parseHostBoundMessage,\n type GuestCommand,\n type GuestEventMessage,\n type HostBoundMessage,\n} from './protocol'\n\n/**\n * A request that was in flight when the guest connection dropped.\n *\n * Distinct from a plain `DeskError` because the caller's next move is\n * different: this request may ALREADY HAVE RUN. The frame reached the guest,\n * and whether the guest executed it before the channel went away is not\n * knowable from the host. An `exec` may have sent mail; a `click` may have\n * landed. So the transport refuses to guess — it names the ambiguity and lets\n * the caller decide whether the operation is safe to repeat. Anything that\n * rejects with a plain `DeskError` instead never reached the guest at all.\n */\nexport class DeskRequestFateUnknownError extends DeskError {\n override readonly name: string = 'DeskRequestFateUnknownError'\n}\n\n/**\n * What happened to the transport underneath a machine.\n *\n * `reconnected` means the host lost the guest channel mid-lease and got it\n * back; the desk is usable again. It is NOT a promise that the guest is\n * unchanged — see the note on `onConnectionChange`. `lost` means it will not\n * come back on this VM and the desk needs a fresh boot.\n */\nexport type DeskConnectionChange =\n | {\n state: 'reconnected'\n deskId: string\n /** How the previous connection went away. */\n reason: string\n /** Wall-clock time the desk spent with no channel to its guest. */\n downtimeMs: number\n /** Reconnects this machine has survived, including this one. */\n reconnects: number\n }\n | {\n state: 'lost'\n deskId: string\n /** Why it is gone for good: the VMM exited, or the window ran out. */\n reason: string\n }\n\n/** A booted microVM as the host sees it: one desk, one guest-agent channel. */\nexport interface DeskMachine {\n readonly deskId: string\n /**\n * Send one request to the in-guest agent and await its correlated result.\n *\n * Rejects with `DeskError` when the guest reports an error, the request\n * times out, or the connection is gone for good — in that last case the\n * request never left the host, so repeating it is safe.\n *\n * A connection lost mid-lease is re-established rather than fatal: a call\n * that arrives while that is happening WAITS for it instead of failing.\n * A call that was already in flight when the channel dropped rejects with\n * `DeskRequestFateUnknownError`, because the host cannot tell whether the\n * guest ran it.\n */\n request(command: GuestCommand, options?: { timeoutMs?: number }): Promise<unknown>\n /**\n * Subscribe to unsolicited guest events (job exits, frames, focus changes).\n *\n * Subscriptions belong to the machine, not to the socket under it, so they\n * survive a reconnect. What does NOT survive is the guest's own capture\n * state: a guest agent that restarted has no screen, no frame encoder and\n * no video encoder, and a subscriber will simply stop receiving. Watch\n * `onConnectionChange` to notice.\n */\n subscribe(listener: (event: GuestEventMessage) => void): () => void\n /**\n * Watch the transport under this machine.\n *\n * Optional: a backend whose channel cannot drop has nothing to report. The\n * default backend reports every reconnect, because a reconnect that leaves\n * no trace turns a guest agent restarting every few minutes into a desk that\n * misbehaves for reasons nobody can find.\n */\n onConnectionChange?(listener: (change: DeskConnectionChange) => void): () => void\n /** Stop the VM. Idempotent; resolves once the VMM process has exited. */\n shutdown(): Promise<void>\n /**\n * Park the VM with its memory, so resuming continues the process tree.\n *\n * Optional: a backend with no snapshot facility simply does not offer it, and\n * the host falls back to `shutdown()`. Pauses the guest, writes a snapshot to\n * `snapshotDir`, then stops the VMM — and resolves only once all three have\n * happened, because a caller that believed a snapshot exists when it does not\n * would later refuse to boot the desk at all.\n *\n * The caller is responsible for quiescing the guest filesystem first. A paused\n * guest still holds dirty pages that exist only in the snapshot, so a disk\n * parked without a prior `sync` is consistent only *with that snapshot* —\n * which matters the moment the snapshot is discarded.\n */\n park?(snapshotDir: string): Promise<void>\n}\n\nexport interface DeskBootHooks {\n /**\n * Called on a restore, after the snapshot has been read back and before the\n * guest is allowed to run.\n *\n * This is the window in which the snapshot must be destroyed. A memory image\n * is valid only against the disk it was taken with, so once the guest resumes\n * and writes, any surviving snapshot describes a past that no longer matches —\n * and replaying it later would corrupt the desk. Restoring paused and\n * invalidating here is what makes that impossible rather than unlikely.\n *\n * Throwing aborts the restore: the VM is stopped and the caller is free to\n * cold boot, which is safe because a paused guest has written nothing.\n */\n onRestored?: () => Promise<void>\n}\n\nexport interface DeskBackend {\n boot(plan: DeskLaunchPlan, hooks?: DeskBootHooks): Promise<DeskMachine>\n}\n\nexport type DeskProcessLauncher = (\n command: string,\n args: readonly string[],\n options: { identity?: DeskLauncherIdentity },\n) => ChildProcess\n\nexport interface CloudHypervisorBackendOptions {\n /** Spawns the VMM and image tooling; injectable for tests. */\n launcher?: DeskProcessLauncher\n /** Opens the host side of the vsock Unix socket; injectable for tests. */\n connect?: (socketPath: string) => Duplex\n platform?: NodeJS.Platform\n /**\n * Clock behind every connect and reconnect deadline. Injectable for the same\n * reason `DeskHostOptions.now` is: a test drives a window to its end by\n * moving the clock, rather than sleeping for it and hoping the machine it\n * runs on is fast enough.\n */\n now?: () => number\n idFactory?: () => string\n requestTimeoutMs?: number\n connectTimeoutMs?: number\n connectRetryDelayMs?: number\n /** Bound on a single handshake attempt; see attemptHandshake. */\n handshakeTimeoutMs?: number\n /**\n * How long a machine keeps trying to get its guest channel back after an\n * unexpected drop before declaring the desk lost. Bounded on purpose: the\n * VMM is still alive so a reconnect is cheap and usually fast, but retrying\n * forever against a guest that is never coming back is worse than failing.\n */\n reconnectWindowMs?: number\n /**\n * First delay between reconnect attempts. It doubles toward a ceiling, so\n * this is the fast first poll rather than the steady rate. Separate from\n * `connectRetryDelayMs`, which is sized for a guest that is still cold\n * booting; here the guest was up a moment ago.\n */\n reconnectRetryDelayMs?: number\n killGraceMs?: number\n guestAgentPort?: number\n}\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000\nconst DEFAULT_CONNECT_TIMEOUT_MS = 20_000\nconst DEFAULT_CONNECT_RETRY_DELAY_MS = 100\nconst DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000\nconst DEFAULT_RECONNECT_WINDOW_MS = 30_000\nconst DEFAULT_RECONNECT_RETRY_DELAY_MS = 250\n/**\n * How far the reconnect delay is allowed to double. A guest agent that systemd\n * is restarting is not helped by being hammered four times a second for the\n * whole window, and an unbounded doubling would spend most of the window\n * asleep after two failures.\n */\nconst RECONNECT_BACKOFF_CEILING = 8\nconst DEFAULT_KILL_GRACE_MS = 2_000\nconst HANDSHAKE_LINE_LIMIT = 128\n\nexport function createCloudHypervisorBackend(\n options: CloudHypervisorBackendOptions = {},\n): DeskBackend {\n const launcher = options.launcher ?? defaultLauncher\n const connect = options.connect ?? defaultConnect\n const platform = options.platform ?? process.platform\n const now = options.now ?? Date.now\n const idFactory = options.idFactory ?? randomUUID\n const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS\n const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS\n const connectRetryDelayMs = options.connectRetryDelayMs ?? DEFAULT_CONNECT_RETRY_DELAY_MS\n const handshakeTimeoutMs = options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS\n const reconnectWindowMs = options.reconnectWindowMs ?? DEFAULT_RECONNECT_WINDOW_MS\n const reconnectRetryDelayMs = options.reconnectRetryDelayMs ?? DEFAULT_RECONNECT_RETRY_DELAY_MS\n const killGraceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS\n const guestAgentPort = options.guestAgentPort ?? GUEST_AGENT_VSOCK_PORT\n\n async function boot(plan: DeskLaunchPlan, hooks?: DeskBootHooks): Promise<DeskMachine> {\n if (platform !== 'linux') {\n throw new DeskError(`The AppKit desk requires Linux; received ${platform}.`)\n }\n if (plan.overlay.create) {\n await runToCompletion(\n launcher(plan.overlay.create.command, plan.overlay.create.args, {\n identity: plan.launcherIdentity,\n }),\n `overlay creation for desk ${plan.deskId}`,\n )\n }\n\n const child = launcher(plan.vmm.command, plan.vmm.args, { identity: plan.launcherIdentity })\n const log = drainOutput(child)\n const exit = watchExit(child)\n\n // A restored guest comes back PAUSED (see the `resume=false` reasoning in\n // the plan). Three things have to happen in this order and nowhere else:\n // prove the restore finished, let the caller destroy the snapshot while the\n // guest still cannot write, then start it.\n if (plan.snapshot.restoring) {\n try {\n await waitForVmm(vmmApi, plan.api.socketPath, { now, exited: exit, timeoutMs: connectTimeoutMs })\n await hooks?.onRestored?.()\n await vmmApi(plan.api.socketPath, '/api/v1/vm.resume')\n } catch (error) {\n await terminate(child, exit, killGraceMs)\n const said = log.tail()\n const detail = said === '' ? '' : ` The VMM said: ${said}`\n throw new DeskError(\n `Desk ${plan.deskId} could not be restored from ${plan.snapshot.dir}: ${errorMessage(error)}${detail}`,\n )\n }\n }\n\n let stream: Duplex\n try {\n stream = await connectWithRetry({\n connect,\n now,\n socketPath: plan.vsock.socketPath,\n port: guestAgentPort,\n timeoutMs: connectTimeoutMs,\n retryDelayMs: connectRetryDelayMs,\n attemptTimeoutMs: handshakeTimeoutMs,\n exited: exit,\n })\n } catch (error) {\n await terminate(child, exit, killGraceMs)\n const said = log.tail()\n const detail = said === '' ? '' : ` The VMM said: ${said}`\n throw error instanceof DeskError\n ? new DeskError(`${error.message}${detail}`)\n : new DeskError(\n `Could not reach the guest agent for desk ${plan.deskId}: ${errorMessage(error)}${detail}`,\n )\n }\n return createMachine({\n deskId: plan.deskId,\n child,\n exit,\n stream,\n // The same path the first connection took, deliberately: a reconnect\n // that skipped confirmGuest would adopt the very hollow handshake the\n // boot path learned not to trust.\n reconnect: (abandoned) =>\n connectWithRetry({\n connect,\n now,\n socketPath: plan.vsock.socketPath,\n port: guestAgentPort,\n timeoutMs: reconnectWindowMs,\n retryDelayMs: reconnectRetryDelayMs,\n maxRetryDelayMs: reconnectRetryDelayMs * RECONNECT_BACKOFF_CEILING,\n attemptTimeoutMs: handshakeTimeoutMs,\n exited: exit,\n exitedMessage: `the VMM for desk ${plan.deskId} exited.`,\n abandoned,\n }),\n reconnectWindowMs,\n now,\n idFactory,\n requestTimeoutMs,\n killGraceMs,\n apiSocketPath: plan.api.socketPath,\n vmmApi,\n })\n }\n\n return { boot }\n}\n\n/**\n * Cloud Hypervisor's control plane: HTTP/1.1 over the `--api-socket` Unix\n * socket. The plan has always created that socket; until now nothing spoke to\n * it, because stopping a VM needed nothing more than killing the process.\n *\n * Pausing and snapshotting do need it, and `ch-remote` — the tool that usually\n * does this — is not in the runner image. Writing the two requests by hand is a\n * smaller change than adding a binary to the image, and keeps the whole\n * lifecycle inside one process that already owns the socket path.\n */\nexport type VmmApiCall = (\n socketPath: string,\n path: string,\n body?: Record<string, unknown>,\n method?: 'PUT' | 'GET',\n) => Promise<void>\n\nconst vmmApi: VmmApiCall = async (socketPath, path, body, method = 'PUT') => {\n const payload = body === undefined ? undefined : Buffer.from(JSON.stringify(body), 'utf8')\n await new Promise<void>((resolve, reject) => {\n const request = httpRequest(\n {\n socketPath,\n path,\n method,\n headers: {\n ...(payload ? { 'content-type': 'application/json', 'content-length': String(payload.length) } : {}),\n },\n },\n (response) => {\n // CH answers 204 with no body on success. Drain regardless: an unread\n // response keeps the socket open and the next call queues behind it.\n const chunks: Buffer[] = []\n response.on('data', (chunk: Buffer) => chunks.push(chunk))\n response.on('end', () => {\n const status = response.statusCode ?? 0\n if (status >= 200 && status < 300) {\n resolve()\n return\n }\n const said = Buffer.concat(chunks).toString('utf8').trim().slice(0, 400)\n reject(new DeskError(`${path} returned ${status}${said === '' ? '' : `: ${said}`}`))\n })\n },\n )\n request.on('error', (error) => reject(new DeskError(`${path} failed: ${errorMessage(error)}`)))\n if (payload) request.write(payload)\n request.end()\n })\n}\n\n/**\n * Wait until the VMM answers its control socket.\n *\n * On a restore this is also the only honest signal that the snapshot was read\n * back: Cloud Hypervisor creates the API socket early but does not serve\n * `vm.info` until it holds a VM, so a successful call means the restore\n * completed rather than merely that the process started. A VMM that exits\n * instead — a corrupt snapshot, a config the host can no longer satisfy — stops\n * the wait immediately rather than burning the whole timeout.\n */\nasync function waitForVmm(\n call: VmmApiCall,\n socketPath: string,\n options: { now: () => number; exited: ExitWatcher; timeoutMs: number; retryDelayMs?: number },\n): Promise<void> {\n const deadline = options.now() + options.timeoutMs\n const retryDelayMs = options.retryDelayMs ?? 50\n let lastFailure = 'it never answered'\n for (;;) {\n if (options.exited.done) throw new DeskError(`the VMM exited before it served its control socket`)\n try {\n await call(socketPath, '/api/v1/vm.info', undefined, 'GET')\n return\n } catch (error) {\n lastFailure = errorMessage(error)\n }\n if (options.now() >= deadline) {\n throw new DeskError(`the VMM did not answer ${socketPath} in ${options.timeoutMs}ms: ${lastFailure}`)\n }\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs))\n }\n}\n\n/** The default backend: real Cloud Hypervisor over a real vsock socket. */\nexport const cloudHypervisorBackend: DeskBackend = createCloudHypervisorBackend()\n\n/**\n * The machine, and the small state machine that keeps it connected.\n *\n * A vsock channel is not a fact the host learns once at boot — the transport\n * can lie about being connected, and it can go away mid-lease for reasons that\n * have nothing to do with the desk being unusable: the guest agent restarts,\n * the socat bridge drops, a transient vsock error, the guest wedges for a\n * moment. Treating any of those as terminal stranded the desk for the rest of\n * its lease with a perfectly healthy guest behind it, answering every call\n * with \"no longer connected\". So a live connection is something this machine\n * RE-ESTABLISHES:\n *\n * live ──unexpected drop──▶ reconnecting ──confirmed guest──▶ live\n * │ │\n * │ └──window exhausted / VMM exited──▶ closed\n * └──shutdown(), VMM already exited, protocol violation───────────▶ closed\n *\n * `closed` is terminal. Nothing reconnects out of it, which is what makes\n * `shutdown()` and a dead VMM final rather than the start of a retry loop.\n */\nfunction createMachine(options: {\n deskId: string\n child: ChildProcess\n exit: ExitWatcher\n stream: Duplex\n /** Re-establishes the channel; resolves only once a guest has answered. */\n reconnect: (abandoned: () => boolean) => Promise<Duplex>\n reconnectWindowMs: number\n now: () => number\n idFactory: () => string\n requestTimeoutMs: number\n killGraceMs: number\n /** Cloud Hypervisor's control socket, for pause and snapshot. */\n apiSocketPath: string\n vmmApi: VmmApiCall\n}): DeskMachine {\n const { deskId, child, exit, now, idFactory, requestTimeoutMs, killGraceMs, reconnectWindowMs } =\n options\n const pending = new Map<\n string,\n { resolve: (result: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }\n >()\n // Listeners live on the machine rather than on the socket, so a reconnect\n // re-points the data path at the new stream and every subscriber keeps\n // working without re-registering.\n const listeners = new Set<(event: GuestEventMessage) => void>()\n const watchers = new Set<(change: DeskConnectionChange) => void>()\n let stream = options.stream\n let state: 'live' | 'reconnecting' | 'closed' = 'live'\n let reconnects = 0\n let reconnecting: Promise<void> | null = null\n\n function failAll(error: Error): void {\n for (const entry of pending.values()) {\n clearTimeout(entry.timer)\n entry.reject(error)\n }\n pending.clear()\n }\n\n function announce(change: DeskConnectionChange): void {\n for (const watcher of [...watchers]) watcher(change)\n }\n\n function close(error: DeskError, intentional: boolean): void {\n if (state === 'closed') return\n state = 'closed'\n failAll(error)\n stream.destroy()\n // A desk the consumer asked to stop is not news; one that stopped on its\n // own is the thing an operator needs to be told about.\n if (!intentional) announce({ state: 'lost', deskId, reason: error.message })\n }\n\n function attach(next: Duplex): void {\n stream = next\n // Each connection decodes with its OWN decoder: a frame the drop cut in\n // half must never be completed by the first bytes of its replacement.\n const decoder = new FrameDecoder()\n const current = () => stream === next && state !== 'closed'\n const onData = (chunk: Buffer): void => {\n if (!current()) return\n let values: unknown[]\n try {\n values = decoder.push(chunk)\n } catch (error) {\n close(\n new DeskError(`Guest agent protocol violation on desk ${deskId}: ${errorMessage(error)}`),\n false,\n )\n return\n }\n for (const value of values) {\n let message: HostBoundMessage\n try {\n message = parseHostBoundMessage(value)\n } catch (error) {\n close(\n new DeskError(`Guest agent sent a malformed message on desk ${deskId}: ${errorMessage(error)}`),\n false,\n )\n return\n }\n if ('id' in message) {\n const entry = pending.get(message.id)\n if (!entry) continue\n pending.delete(message.id)\n clearTimeout(entry.timer)\n if (message.ok) entry.resolve(message.result)\n else entry.reject(new DeskError(`Guest agent error on desk ${deskId}: ${message.error}`))\n } else {\n for (const listener of [...listeners]) listener(message)\n }\n }\n }\n next.on('data', onData)\n next.once('close', () => {\n drop(next, `the guest agent connection closed on desk ${deskId}`)\n })\n next.once('error', (error: Error) => {\n drop(next, `the guest agent connection failed on desk ${deskId}: ${error.message}`)\n })\n }\n\n function drop(from: Duplex, reason: string): void {\n if (state !== 'live' || from !== stream) return\n from.destroy()\n if (exit.done) {\n // A dead VMM is not a connection problem. There is no guest to get back\n // to, and retrying against it forever only delays the fresh boot the\n // desk actually needs.\n close(new DeskError(`Desk ${deskId} is no longer connected: the VMM exited (${reason}).`), false)\n return\n }\n state = 'reconnecting'\n const lostAt = now()\n // In-flight requests CANNOT be silently retried. Each of their frames\n // already reached the guest, and whether the guest ran it before the\n // channel went away is not knowable from here: an `exec` may have sent\n // mail, a `click` may have landed. Replaying a side-effecting operation to\n // paper over a blip is the wrong kind of resilience, so every one of them\n // is told its fate is unknown and the caller decides.\n failAll(\n new DeskRequestFateUnknownError(\n `Desk ${deskId} lost its guest agent connection while this request was in flight `\n + `(${reason}); the guest may or may not have run it.`,\n ),\n )\n reconnecting = restore(reason, lostAt)\n }\n\n /** Always resolves: callers await it to learn the outcome, not to be thrown at. */\n async function restore(reason: string, lostAt: number): Promise<void> {\n let next: Duplex\n try {\n next = await options.reconnect(() => state !== 'reconnecting')\n } catch (error) {\n close(\n new DeskError(\n `Desk ${deskId} lost its guest agent connection and could not get it back: ${errorMessage(error)}`,\n ),\n false,\n )\n return\n }\n if (state !== 'reconnecting') {\n // shutdown() won the race while the replacement socket was coming up.\n next.destroy()\n return\n }\n attach(next)\n state = 'live'\n reconnects += 1\n announce({ state: 'reconnected', deskId, reason, downtimeMs: now() - lostAt, reconnects })\n }\n\n attach(options.stream)\n\n return {\n deskId,\n async request(command, requestOptions = {}) {\n // A call that lands mid-reconnect waits for it rather than failing on\n // the spot: the guest is usually back within seconds, and telling a\n // caller a desk is gone when it is about to be fine is the bug this\n // machine exists to end. The wait is bounded by the same window the\n // reconnect itself is.\n const waitUntil = now() + reconnectWindowMs\n while (state === 'reconnecting') {\n const attempt = reconnecting\n if (!attempt || now() >= waitUntil) break\n await attempt\n }\n if (state !== 'live') {\n // This one never left the host, so — unlike a request that was in\n // flight when the channel dropped — repeating it is safe.\n throw new DeskError(`Desk ${deskId} is no longer connected.`)\n }\n const id = idFactory()\n const timeoutMs = requestOptions.timeoutMs ?? requestTimeoutMs\n const target = stream\n return await new Promise<unknown>((resolvePromise, rejectPromise) => {\n const timer = setTimeout(() => {\n pending.delete(id)\n rejectPromise(new DeskError(`Guest request ${command.op} timed out on desk ${deskId}.`))\n }, timeoutMs)\n timer.unref()\n pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer })\n target.write(encodeFrame({ ...command, id }))\n })\n },\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n onConnectionChange(listener) {\n watchers.add(listener)\n return () => {\n watchers.delete(listener)\n }\n },\n async shutdown() {\n // Terminal by construction: `closed` is the state the reconnect loop\n // checks, so an explicit shutdown can never be followed by a reconnect.\n close(new DeskError(`Desk ${deskId} is shutting down.`), true)\n await terminate(child, exit, killGraceMs)\n },\n async park(snapshotDir: string) {\n // Close the guest channel FIRST. Pausing a VM strands whatever was in\n // flight on the vsock, and a reconnect attempt against a paused guest\n // would burn the whole reconnect window before giving up — so the channel\n // is made terminal before the VM stops answering, exactly as shutdown\n // does it.\n close(new DeskError(`Desk ${deskId} is being parked.`), true)\n try {\n await options.vmmApi(options.apiSocketPath, '/api/v1/vm.pause')\n await options.vmmApi(options.apiSocketPath, '/api/v1/vm.snapshot', {\n // Three slashes: `file://` plus an absolute path. CH rejects a\n // destination_url it cannot parse, and the directory must already\n // exist — it writes the config and memory files into it.\n destination_url: `file://${snapshotDir}`,\n })\n } catch (error) {\n // The VM is paused and there is no usable snapshot, which is the one\n // state nothing downstream can interpret. Stop the VMM so the desk is\n // plainly off, and say why — the caller falls back to a cold boot, and\n // the disk is still consistent because the guest was synced before this.\n await terminate(child, exit, killGraceMs)\n throw error instanceof DeskError\n ? new DeskError(`Desk ${deskId} could not be parked with its memory: ${error.message}`)\n : new DeskError(`Desk ${deskId} could not be parked with its memory: ${errorMessage(error)}`)\n }\n await terminate(child, exit, killGraceMs)\n },\n }\n}\n\ninterface ExitWatcher {\n done: boolean\n promise: Promise<void>\n}\n\n/**\n * Read the VMM's stdout and stderr, and keep only the last few kilobytes.\n *\n * This is not for logging — it is load-bearing. The child is spawned with\n * both streams as PIPES, and a pipe nobody reads fills after about 64KB, at\n * which point the VMM BLOCKS on its next write. Cloud Hypervisor logs while\n * it runs, so an unread pipe freezes the guest partway through boot: the\n * process is alive, the disk is untouched, and the guest agent never reaches\n * vsock. Every symptom points at the image and none of them are its fault.\n *\n * Draining costs nothing and buys the tail of what the VMM said, which is the\n * difference between \"the VMM exited\" and knowing why.\n */\nfunction drainOutput(child: ChildProcess, limit = 8 * 1024): { tail: () => string } {\n let buffered = ''\n const absorb = (chunk: unknown) => {\n buffered += String(chunk)\n if (buffered.length > limit) buffered = buffered.slice(buffered.length - limit)\n }\n child.stdout?.on('data', absorb)\n child.stderr?.on('data', absorb)\n // A pipe that errors must not take the process down with it.\n child.stdout?.on('error', () => undefined)\n child.stderr?.on('error', () => undefined)\n return { tail: () => buffered.trim() }\n}\n\nfunction watchExit(child: ChildProcess): ExitWatcher {\n const watcher: ExitWatcher = { done: false, promise: Promise.resolve() }\n watcher.promise = new Promise<void>((resolvePromise) => {\n const settle = () => {\n watcher.done = true\n resolvePromise()\n }\n child.once('exit', settle)\n child.once('error', settle)\n })\n return watcher\n}\n\nasync function terminate(child: ChildProcess, exit: ExitWatcher, killGraceMs: number): Promise<void> {\n if (exit.done) return\n child.kill('SIGTERM')\n const forceKill = setTimeout(() => {\n if (!exit.done) child.kill('SIGKILL')\n }, killGraceMs)\n forceKill.unref()\n await exit.promise\n clearTimeout(forceKill)\n}\n\nfunction runToCompletion(child: ChildProcess, label: string): Promise<void> {\n return new Promise<void>((resolvePromise, rejectPromise) => {\n let stderr = ''\n child.stderr?.on('data', (chunk) => {\n stderr += String(chunk)\n })\n child.once('error', (error) => {\n rejectPromise(new DeskError(`${label} failed to start: ${error.message}`))\n })\n child.once('exit', (code, signal) => {\n if (code === 0) {\n resolvePromise()\n return\n }\n const detail = stderr.trim()\n rejectPromise(\n new DeskError(\n `${label} exited with code ${code ?? 'unknown'}`\n + `${signal ? ` (${signal})` : ''}${detail ? `: ${detail}` : '.'}`,\n ),\n )\n })\n })\n}\n\n/**\n * Cloud Hypervisor exposes guest vsock ports through a host Unix socket with\n * a line-oriented preamble: the client writes `CONNECT <port>\\n` and the VMM\n * answers `OK <assigned>\\n` before the byte stream becomes the guest\n * connection. The VMM creates the socket during boot, so connection attempts\n * retry until the deadline.\n *\n * The same loop serves the first connection and every later reconnect, so a\n * reconnect gets `confirmGuest` too — a mid-lease reconnect that trusted the\n * banner would re-adopt exactly the hollow stream the boot path learned not to.\n */\nasync function connectWithRetry(options: {\n connect: (socketPath: string) => Duplex\n now: () => number\n socketPath: string\n port: number\n timeoutMs: number\n retryDelayMs: number\n /** Ceiling the delay doubles toward; omitted keeps the delay constant. */\n maxRetryDelayMs?: number\n attemptTimeoutMs: number\n exited: ExitWatcher\n /** A dead VMM means something different at boot than it does mid-lease. */\n exitedMessage?: string\n /** Stops the loop early when the caller no longer wants the connection. */\n abandoned?: () => boolean\n}): Promise<Duplex> {\n const deadline = options.now() + options.timeoutMs\n let lastFailure = 'the guest agent never answered'\n let retryDelayMs = options.retryDelayMs\n while (options.now() <= deadline) {\n if (options.exited.done) {\n throw new DeskError(options.exitedMessage ?? 'The VMM exited before the guest agent came up.')\n }\n if (options.abandoned?.() === true) {\n throw new DeskError('the connection attempt was abandoned.')\n }\n try {\n const stream = await attemptHandshake(\n options.connect,\n options.socketPath,\n options.port,\n options.attemptTimeoutMs,\n )\n try {\n await confirmGuest(stream, options.attemptTimeoutMs)\n } catch (error) {\n stream.destroy()\n throw error\n }\n return stream\n } catch (error) {\n lastFailure = errorMessage(error)\n }\n await delay(retryDelayMs)\n if (options.maxRetryDelayMs !== undefined) {\n retryDelayMs = Math.min(retryDelayMs * 2, options.maxRetryDelayMs)\n }\n }\n throw new DeskError(\n `Timed out connecting to the guest agent at ${options.socketPath}: ${lastFailure}`,\n )\n}\n\n/**\n * One handshake attempt, which MUST settle.\n *\n * Cloud Hypervisor accepts a connection on the vsock socket whether or not\n * anything in the guest is listening on the port, and when nothing is it may\n * answer nothing at all: no reply, no error, no close. Without a deadline of\n * its own this promise then never settles — and because the caller awaits it\n * inside the retry loop, the loop stops iterating, the overall deadline is\n * never re-checked, and the boot hangs forever rather than failing. That is\n * indistinguishable from a wedged host and it is why every attempt is bounded\n * here as well as in aggregate.\n */\n/**\n * Prove a guest is behind the handshake by asking it something.\n *\n * Cloud Hypervisor answers `CONNECT <port>` with `OK` whether or not anything\n * in the guest is listening on that port, and only closes the socket a moment\n * later when it finds nobody there. A caller that trusts the banner therefore\n * \"connects\" to a guest that is still booting, gets a closed stream seconds\n * later, and — because a closed machine is not retried — leaves the desk dead\n * for as long as it is leased, with a healthy guest sitting behind it. So the\n * handshake is not the test; a reply is.\n */\nasync function confirmGuest(stream: Duplex, timeoutMs: number): Promise<void> {\n const decoder = new FrameDecoder()\n await new Promise<void>((resolvePromise, rejectPromise) => {\n let settled = false\n const finish = (error?: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n stream.off('data', onData)\n stream.off('close', onClose)\n stream.off('error', finish)\n if (error) rejectPromise(error)\n else resolvePromise()\n }\n const timer = setTimeout(\n () => finish(new DeskError('the guest agent did not answer the first request.')),\n timeoutMs,\n )\n timer.unref?.()\n const onClose = () =>\n finish(new DeskError('the connection closed before the guest agent answered.'))\n const onData = (chunk: Buffer) => {\n let values: unknown[]\n try {\n values = decoder.push(chunk)\n } catch (error) {\n finish(error instanceof Error ? error : new Error(String(error)))\n return\n }\n for (const value of values) {\n // Anything at all proves a guest is there; the reply is parsed for\n // real by the machine once it owns the stream.\n if (value && typeof value === 'object') {\n finish()\n return\n }\n }\n }\n stream.on('data', onData)\n stream.once('close', onClose)\n stream.once('error', finish)\n stream.write(encodeFrame({ id: 'hello', op: 'ping' }))\n })\n}\n\nfunction attemptHandshake(\n connect: (socketPath: string) => Duplex,\n socketPath: string,\n port: number,\n attemptTimeoutMs: number,\n): Promise<Duplex> {\n return new Promise<Duplex>((resolvePromise, rejectPromise) => {\n let stream: Duplex\n try {\n stream = connect(socketPath)\n } catch (error) {\n rejectPromise(error instanceof Error ? error : new Error(String(error)))\n return\n }\n let banner = ''\n let settled = false\n const timer = setTimeout(() => {\n fail(new DeskError('vsock handshake went unanswered.'))\n }, attemptTimeoutMs)\n // An unref'd timer must not hold the process open on its own.\n timer.unref?.()\n const fail = (error: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n stream.destroy()\n rejectPromise(error)\n }\n const onData = (chunk: Buffer) => {\n banner += chunk.toString('latin1')\n const newline = banner.indexOf('\\n')\n if (newline === -1) {\n if (banner.length > HANDSHAKE_LINE_LIMIT) {\n fail(new DeskError('vsock handshake reply exceeded the line limit.'))\n }\n return\n }\n const line = banner.slice(0, newline)\n const rest = banner.slice(newline + 1)\n stream.off('data', onData)\n stream.off('error', fail)\n if (!line.startsWith('OK ')) {\n fail(new DeskError(`vsock handshake was refused: ${line}`))\n return\n }\n settled = true\n clearTimeout(timer)\n if (rest.length > 0) stream.unshift(Buffer.from(rest, 'latin1'))\n resolvePromise(stream)\n }\n stream.on('data', onData)\n stream.once('error', fail)\n // A close before the banner is a refusal, not a hang.\n stream.once('close', () => fail(new DeskError('vsock handshake closed before a reply.')))\n stream.write(`CONNECT ${port}\\n`)\n })\n}\n\nfunction defaultLauncher(\n command: string,\n args: readonly string[],\n options: { identity?: DeskLauncherIdentity },\n): ChildProcess {\n return spawn(command, [...args], {\n stdio: ['ignore', 'pipe', 'pipe'],\n uid: options.identity?.uid,\n gid: options.identity?.gid,\n })\n}\n\nfunction defaultConnect(socketPath: string): Duplex {\n return createConnection(socketPath)\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise<void>((resolvePromise) => {\n const timer = setTimeout(resolvePromise, ms)\n timer.unref()\n })\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n"]}
package/events.d.ts CHANGED
@@ -104,6 +104,9 @@ export type DeskEventDetail = {
104
104
  kind: 'screen_open';
105
105
  width: number;
106
106
  height: number;
107
+ } | {
108
+ kind: 'snapshot_cpu_fallback';
109
+ reason: 'signature_mismatch' | 'incompatible_cpuid';
107
110
  } | {
108
111
  kind: 'screen_close';
109
112
  } | {
package/events.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,CAAA;AAE3D,MAAM,WAAW,SAAS;IACxB,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;CACV;AAED,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CACrB;AAED;;;;GAIG;AACH,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;IACnB,OAAO,EAAE,SAAS,MAAM,EAAE,CAAA;IAC1B,MAAM,EAAE;QAAE,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAA;IACtE,QAAQ,EAAE,SAAS,QAAQ,EAAE,CAAA;CAC9B;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,eAAe,GAAG,KAAK,GAAG,MAAM,CAAA;AAE5C;;;;;;;;GAQG;AACH,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,OAAO,CAAA;AAEjD,MAA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SAAS,KAAK,IAAI,CAAA;IACnC,KAAK,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAA;CACvC"}
package/events.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG","sourcesContent":["/**\n * The typed desk event stream and the ports a consumer supplies.\n *\n * AppKit owns the mechanism of running a desk; the consumer owns the record.\n * Every governed thing that happens on a desk is delivered to `onEvent` as one\n * member of a closed union so the consumer's append-only ledger can persist it\n * without inventing its own taxonomy. Handover boundaries additionally reach\n * the `audit` port — and, while a handover is active, they are the *only*\n * thing that reaches any port. See the masking contract on `DeskPorts`.\n */\n\nexport type DeskPointerButton = 'left' | 'middle' | 'right'\n\nexport interface DeskPoint {\n x: number\n y: number\n}\n\nexport interface WindowInfo {\n id: string\n title: string\n appId: string | null\n}\n\n/**\n * One node of the focused application's AT-SPI accessibility tree, when the\n * application exposes one. Perception is pixels-primary; the tree is\n * opportunistic and may be `null` at any time.\n */\nexport interface A11yNode {\n id: string\n role: string\n name: string | null\n actions: readonly string[]\n bounds: { x: number; y: number; width: number; height: number } | null\n children: readonly A11yNode[]\n}\n\n/**\n * How the pixels of a live frame are encoded on the wire.\n *\n * Two jobs, two formats. `observe()` is always lossless PNG because it feeds a\n * model's vision and anchors coordinates, and it is asked for rarely. The\n * `frames()` stream feeds a human driving the screen: there the scarce\n * resource is bytes on the transport, not fidelity, so a lossy `jpeg` is\n * roughly an order of magnitude smaller per frame and is what makes a live\n * view feel like a remote desktop rather than a slideshow.\n */\nexport type DeskFrameFormat = 'png' | 'jpeg'\n\n/**\n * The two kinds of unit a video stream is made of.\n *\n * `init` is the header a decoder needs before it can make sense of anything —\n * for fragmented MP4, `ftyp` plus `moov`. It arrives once per encoder start and\n * a consumer that never receives it decodes nothing at all, silently. `media`\n * is one fragment of pictures. Ordering is load-bearing: init first, then media\n * from a keyframe onwards.\n */\nexport type DeskVideoChunkKind = 'init' | 'media'\n\nexport type DeskHandoverScope = 'view' | 'control'\n\nexport type DeskHandoverEndReason = 'ended' | 'expired' | 'revoked'\n\n/**\n * The closed union of recordable desk activity. The consumer's ledger stores\n * these rows; the union is defined here so the mechanism and the record agree\n * on the taxonomy without the package ever touching a database.\n */\nexport type DeskEventDetail =\n | {\n kind: 'shell_command'\n command: string\n args: readonly string[]\n cwd: string | null\n exitCode: number | null\n signal: string | null\n }\n | { kind: 'app_launch'; appId: string; args: readonly string[] }\n | { kind: 'click'; x: number; y: number; button: DeskPointerButton; clicks: 1 | 2 }\n | { kind: 'type'; text: string }\n | { kind: 'key'; combo: string }\n | { kind: 'scroll'; x: number; y: number; dx: number; dy: number }\n | { kind: 'drag'; from: DeskPoint; to: DeskPoint }\n | { kind: 'window_focus'; window: WindowInfo }\n | { kind: 'screen_open'; width: number; height: number }\n | { kind: 'screen_close' }\n | { kind: 'handover_begin'; actor: string | null; scope: DeskHandoverScope }\n | { kind: 'handover_end'; actor: string | null; durationMs: number }\n | { kind: 'job_start'; jobId: string; command: string; args: readonly string[] }\n | { kind: 'job_exit'; jobId: string; exitCode: number | null; signal: string | null }\n\nexport type DeskEventKind = DeskEventDetail['kind']\n\nexport type DeskEvent = DeskEventDetail & { deskId: string; at: string }\n\n/**\n * Handover boundaries as the audit port sees them: who took over, under what\n * scope, and for how long — never what they typed.\n */\nexport type DeskAuditEntry =\n | {\n kind: 'handover_begin'\n deskId: string\n actor: string | null\n scope: DeskHandoverScope\n ttlMs: number\n at: string\n }\n | {\n kind: 'handover_end'\n deskId: string\n actor: string | null\n durationMs: number\n reason: DeskHandoverEndReason\n at: string\n }\n\n/**\n * Consumer-supplied policy. Absent hooks allow: the package is mechanism, and\n * a deployment that wants governance supplies it here. A hook returning\n * `false` makes the corresponding call throw before anything reaches the\n * guest.\n */\nexport interface DeskPolicyPort {\n allowExec?(request: {\n deskId: string\n command: string\n args: readonly string[]\n keepAlive: boolean\n }): boolean\n allowScreen?(request: { deskId: string; width: number; height: number }): boolean\n allowHandover?(request: {\n deskId: string\n scope: DeskHandoverScope\n ttlMs: number\n }): boolean\n}\n\n/**\n * The ports a consumer supplies to `createDeskHost`.\n *\n * Masking contract (load-bearing): while a handover is active, input events —\n * `click`, `type`, `key`, `scroll`, `drag` — and the screen-derived events\n * `window_focus` and `app_launch` never reach `onEvent`, and frames are never\n * emitted to `frames()` consumers. Only `handover_begin` and `handover_end`\n * cross the boundary, carrying actor and duration. Getting this wrong leaks\n * credentials into an append-only record.\n */\nexport interface DeskPorts {\n policy?: DeskPolicyPort\n onEvent: (event: DeskEvent) => void\n audit: (entry: DeskAuditEntry) => void\n}\n"]}
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG","sourcesContent":["/**\n * The typed desk event stream and the ports a consumer supplies.\n *\n * AppKit owns the mechanism of running a desk; the consumer owns the record.\n * Every governed thing that happens on a desk is delivered to `onEvent` as one\n * member of a closed union so the consumer's append-only ledger can persist it\n * without inventing its own taxonomy. Handover boundaries additionally reach\n * the `audit` port — and, while a handover is active, they are the *only*\n * thing that reaches any port. See the masking contract on `DeskPorts`.\n */\n\nexport type DeskPointerButton = 'left' | 'middle' | 'right'\n\nexport interface DeskPoint {\n x: number\n y: number\n}\n\nexport interface WindowInfo {\n id: string\n title: string\n appId: string | null\n}\n\n/**\n * One node of the focused application's AT-SPI accessibility tree, when the\n * application exposes one. Perception is pixels-primary; the tree is\n * opportunistic and may be `null` at any time.\n */\nexport interface A11yNode {\n id: string\n role: string\n name: string | null\n actions: readonly string[]\n bounds: { x: number; y: number; width: number; height: number } | null\n children: readonly A11yNode[]\n}\n\n/**\n * How the pixels of a live frame are encoded on the wire.\n *\n * Two jobs, two formats. `observe()` is always lossless PNG because it feeds a\n * model's vision and anchors coordinates, and it is asked for rarely. The\n * `frames()` stream feeds a human driving the screen: there the scarce\n * resource is bytes on the transport, not fidelity, so a lossy `jpeg` is\n * roughly an order of magnitude smaller per frame and is what makes a live\n * view feel like a remote desktop rather than a slideshow.\n */\nexport type DeskFrameFormat = 'png' | 'jpeg'\n\n/**\n * The two kinds of unit a video stream is made of.\n *\n * `init` is the header a decoder needs before it can make sense of anything —\n * for fragmented MP4, `ftyp` plus `moov`. It arrives once per encoder start and\n * a consumer that never receives it decodes nothing at all, silently. `media`\n * is one fragment of pictures. Ordering is load-bearing: init first, then media\n * from a keyframe onwards.\n */\nexport type DeskVideoChunkKind = 'init' | 'media'\n\nexport type DeskHandoverScope = 'view' | 'control'\n\nexport type DeskHandoverEndReason = 'ended' | 'expired' | 'revoked'\n\n/**\n * The closed union of recordable desk activity. The consumer's ledger stores\n * these rows; the union is defined here so the mechanism and the record agree\n * on the taxonomy without the package ever touching a database.\n */\nexport type DeskEventDetail =\n | {\n kind: 'shell_command'\n command: string\n args: readonly string[]\n cwd: string | null\n exitCode: number | null\n signal: string | null\n }\n | { kind: 'app_launch'; appId: string; args: readonly string[] }\n | { kind: 'click'; x: number; y: number; button: DeskPointerButton; clicks: 1 | 2 }\n | { kind: 'type'; text: string }\n | { kind: 'key'; combo: string }\n | { kind: 'scroll'; x: number; y: number; dx: number; dy: number }\n | { kind: 'drag'; from: DeskPoint; to: DeskPoint }\n | { kind: 'window_focus'; window: WindowInfo }\n | { kind: 'screen_open'; width: number; height: number }\n | { kind: 'snapshot_cpu_fallback'; reason: 'signature_mismatch' | 'incompatible_cpuid' }\n | { kind: 'screen_close' }\n | { kind: 'handover_begin'; actor: string | null; scope: DeskHandoverScope }\n | { kind: 'handover_end'; actor: string | null; durationMs: number }\n | { kind: 'job_start'; jobId: string; command: string; args: readonly string[] }\n | { kind: 'job_exit'; jobId: string; exitCode: number | null; signal: string | null }\n\nexport type DeskEventKind = DeskEventDetail['kind']\n\nexport type DeskEvent = DeskEventDetail & { deskId: string; at: string }\n\n/**\n * Handover boundaries as the audit port sees them: who took over, under what\n * scope, and for how long — never what they typed.\n */\nexport type DeskAuditEntry =\n | {\n kind: 'handover_begin'\n deskId: string\n actor: string | null\n scope: DeskHandoverScope\n ttlMs: number\n at: string\n }\n | {\n kind: 'handover_end'\n deskId: string\n actor: string | null\n durationMs: number\n reason: DeskHandoverEndReason\n at: string\n }\n\n/**\n * Consumer-supplied policy. Absent hooks allow: the package is mechanism, and\n * a deployment that wants governance supplies it here. A hook returning\n * `false` makes the corresponding call throw before anything reaches the\n * guest.\n */\nexport interface DeskPolicyPort {\n allowExec?(request: {\n deskId: string\n command: string\n args: readonly string[]\n keepAlive: boolean\n }): boolean\n allowScreen?(request: { deskId: string; width: number; height: number }): boolean\n allowHandover?(request: {\n deskId: string\n scope: DeskHandoverScope\n ttlMs: number\n }): boolean\n}\n\n/**\n * The ports a consumer supplies to `createDeskHost`.\n *\n * Masking contract (load-bearing): while a handover is active, input events —\n * `click`, `type`, `key`, `scroll`, `drag` — and the screen-derived events\n * `window_focus` and `app_launch` never reach `onEvent`, and frames are never\n * emitted to `frames()` consumers. Only `handover_begin` and `handover_end`\n * cross the boundary, carrying actor and duration. Getting this wrong leaks\n * credentials into an append-only record.\n */\nexport interface DeskPorts {\n policy?: DeskPolicyPort\n onEvent: (event: DeskEvent) => void\n audit: (entry: DeskAuditEntry) => void\n}\n"]}