@webpodjs/sdk 0.2.6 → 0.3.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.
Files changed (72) hide show
  1. package/README.md +93 -15
  2. package/dist/agent/backend.d.ts +18 -1
  3. package/dist/agent/backend.js +275 -76
  4. package/dist/agent/backend.js.map +1 -1
  5. package/dist/agent/fs.d.ts +2 -2
  6. package/dist/agent/fs.js +3 -2
  7. package/dist/agent/fs.js.map +1 -1
  8. package/dist/agent/protocol.d.ts +40 -1
  9. package/dist/agent/protocol.js +39 -3
  10. package/dist/agent/protocol.js.map +1 -1
  11. package/dist/errors.d.ts +1 -1
  12. package/dist/errors.js.map +1 -1
  13. package/dist/exec/client.js +21 -6
  14. package/dist/exec/client.js.map +1 -1
  15. package/dist/exec/frame.js +5 -0
  16. package/dist/exec/frame.js.map +1 -1
  17. package/dist/fs/tar.d.ts +1 -1
  18. package/dist/fs/tar.js +8 -2
  19. package/dist/fs/tar.js.map +1 -1
  20. package/dist/fs/workspace.js +61 -30
  21. package/dist/fs/workspace.js.map +1 -1
  22. package/dist/host/backend.d.ts +11 -0
  23. package/dist/host/backend.js +68 -12
  24. package/dist/host/backend.js.map +1 -1
  25. package/dist/host/controller.d.ts +2 -0
  26. package/dist/host/controller.js +11 -4
  27. package/dist/host/controller.js.map +1 -1
  28. package/dist/host/devices.d.ts +19 -2
  29. package/dist/host/devices.js +37 -3
  30. package/dist/host/devices.js.map +1 -1
  31. package/dist/host-exec/controller.d.ts +153 -4
  32. package/dist/host-exec/controller.js +974 -66
  33. package/dist/host-exec/controller.js.map +1 -1
  34. package/dist/host-exec/pipe.js +5 -1
  35. package/dist/host-exec/pipe.js.map +1 -1
  36. package/dist/host-exec/protocol.d.ts +330 -4
  37. package/dist/host-exec/protocol.js +34 -0
  38. package/dist/host-exec/protocol.js.map +1 -1
  39. package/dist/host-exec/route.js +74 -13
  40. package/dist/host-exec/route.js.map +1 -1
  41. package/dist/host-exec/shim.d.ts +2 -2
  42. package/dist/host-exec/shim.js +69 -12
  43. package/dist/host-exec/shim.js.map +1 -1
  44. package/dist/index.d.ts +3 -1
  45. package/dist/index.js +1 -0
  46. package/dist/index.js.map +1 -1
  47. package/dist/net/client.d.ts +5 -1
  48. package/dist/net/client.js +8 -4
  49. package/dist/net/client.js.map +1 -1
  50. package/dist/net/options.d.ts +14 -0
  51. package/dist/net/options.js +1 -1
  52. package/dist/net/options.js.map +1 -1
  53. package/dist/net/preview.d.ts +15 -1
  54. package/dist/net/preview.js +24 -4
  55. package/dist/net/preview.js.map +1 -1
  56. package/dist/output.d.ts +23 -0
  57. package/dist/output.js +161 -0
  58. package/dist/output.js.map +1 -0
  59. package/dist/pod.d.ts +21 -7
  60. package/dist/pod.js +165 -29
  61. package/dist/pod.js.map +1 -1
  62. package/dist/preview-relay.js +24 -7
  63. package/dist/preview-relay.js.map +1 -1
  64. package/dist/preview-serviceworker.js +71 -8
  65. package/dist/preview-serviceworker.js.map +1 -1
  66. package/dist/tools.d.ts +77 -0
  67. package/dist/tools.js +47 -0
  68. package/dist/tools.js.map +1 -0
  69. package/dist/types.d.ts +62 -2
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/package.json +1 -1
@@ -2,8 +2,9 @@ import { WebPodError } from "../errors.js";
2
2
  import { createFsRouter } from "../fs-router.js";
3
3
  import { SIGNAL_NUMBERS } from "../types.js";
4
4
  import { hiddenNote, progressTimeout, visibleDeadline, visibleTimeout } from "../timers.js";
5
+ import { ProcessOutput } from "../output.js";
5
6
  import { AgentFs, errnoError } from "./fs.js";
6
- import { DEFAULT_WINDOW, FrameDecoder, MAX_CHUNK, PROTOCOL_VERSION, decodeGuestMsg, encodeHostMsg, } from "./protocol.js";
7
+ import { DEFAULT_WINDOW, FrameDecoder, MAX_CHUNK, MAX_FRAME, PROTOCOL_VERSION, ProtocolError, ZeroLengthFrame, decodeGuestMsg, encodeHostMsg, } from "./protocol.js";
7
8
  /** The bytes of FsReplay / FsNotify parts: well within a frame (MAX_FRAME), a few round trips for a big batch. */
8
9
  const REPLAY_PART_BYTES = 256 * 1024;
9
10
  const pathBytes = new TextEncoder();
@@ -44,48 +45,6 @@ class Deferred {
44
45
  this.promise.catch(() => { });
45
46
  }
46
47
  }
47
- /** Output of one stream: chunks are acked to the agent only when the consumer reads them. */
48
- class OutputQueue {
49
- stream;
50
- #chunks = [];
51
- #ended = false;
52
- #error;
53
- #wake;
54
- constructor(ack) {
55
- this.stream = new ReadableStream({
56
- pull: async (controller) => {
57
- while (this.#chunks.length === 0 && !this.#ended)
58
- await new Promise((r) => (this.#wake = r));
59
- const chunk = this.#chunks.shift();
60
- if (chunk) {
61
- controller.enqueue(chunk);
62
- ack(chunk.length);
63
- }
64
- else if (this.#error !== undefined)
65
- controller.error(this.#error);
66
- else
67
- controller.close();
68
- },
69
- cancel: () => {
70
- // Keep the guest flowing when nobody reads: ack everything from now on.
71
- for (const c of this.#chunks)
72
- ack(c.length);
73
- this.#chunks = [];
74
- this.#ended = true;
75
- this.push = (c) => ack(c.length);
76
- },
77
- }, { highWaterMark: 0 });
78
- }
79
- push(chunk) {
80
- this.#chunks.push(chunk);
81
- this.#wake?.();
82
- }
83
- end(error) {
84
- this.#ended = true;
85
- this.#error = error;
86
- this.#wake?.();
87
- }
88
- }
89
48
  class AgentProcess {
90
49
  id;
91
50
  send;
@@ -94,7 +53,8 @@ class AgentProcess {
94
53
  stdout;
95
54
  stderr;
96
55
  exit;
97
- out;
56
+ /** Its output: each chunk acknowledged to the agent once it is read. */
57
+ out = [new ProcessOutput(), new ProcessOutput()];
98
58
  #pid = new Deferred();
99
59
  #exit = new Deferred();
100
60
  #unacked = 0;
@@ -105,11 +65,6 @@ class AgentProcess {
105
65
  this.send = send;
106
66
  this.pid = this.#pid.promise;
107
67
  this.exit = this.#exit.promise;
108
- const ack = (stream) => (bytes) => {
109
- if (!this.#done)
110
- void this.send({ type: "outputAck", id, stream, bytes }).catch(() => { });
111
- };
112
- this.out = [new OutputQueue(ack(1)), new OutputQueue(ack(2))];
113
68
  this.stdout = this.out[0].stream;
114
69
  this.stderr = this.out[1].stream;
115
70
  if (pty)
@@ -141,6 +96,10 @@ class AgentProcess {
141
96
  for (const w of this.#creditWaiters.splice(0))
142
97
  w();
143
98
  }
99
+ #ack(stream, bytes) {
100
+ if (!this.#done)
101
+ void this.send({ type: "outputAck", id: this.id, stream, bytes }).catch(() => { });
102
+ }
144
103
  handle(msg) {
145
104
  switch (msg.type) {
146
105
  case "spawned":
@@ -151,9 +110,11 @@ class AgentProcess {
151
110
  this.fail(err);
152
111
  break;
153
112
  }
154
- case "output":
155
- this.out[msg.stream - 1].push(msg.data);
113
+ case "output": {
114
+ const { stream, data } = msg;
115
+ this.out[stream - 1].push(data, () => this.#ack(stream, data.length));
156
116
  break;
117
+ }
157
118
  case "stdinAck":
158
119
  this.#unacked -= msg.bytes;
159
120
  this.#wakeWriters();
@@ -214,16 +175,18 @@ function helloWait(ms, downloads) {
214
175
  export async function createAgentBackend(options) {
215
176
  const writer = options.transport.writable.getWriter();
216
177
  const reader = options.transport.readable.getReader();
178
+ const log = options.onLog ?? ((level, text) => (level === "warn" ? console.warn : console.info)(`webpod-agent: ${text}`));
217
179
  const procs = new Map();
218
180
  const fsRequests = new Map();
219
181
  const caRequests = new Map();
220
182
  const opRequests = new Map();
221
183
  const listenRequests = new Map();
222
184
  const connectRequests = new Map();
185
+ const killRequests = new Map();
223
186
  const watches = new Map();
224
187
  let nextReq = 1;
225
188
  let nextWatch = 1;
226
- const decoder = new FrameDecoder();
189
+ let decoder = new FrameDecoder();
227
190
  let nextId = 1;
228
191
  let closed;
229
192
  let writes = Promise.resolve();
@@ -243,12 +206,8 @@ export async function createAgentBackend(options) {
243
206
  const hello = new Deferred();
244
207
  const ended = new Deferred();
245
208
  let hostListener = null;
246
- const shutdown = (error) => {
247
- if (closed !== undefined)
248
- return;
249
- closed = error;
250
- ended.resolve();
251
- hello.reject(error);
209
+ /** Fails what waits for an answer of the agent's session (it ended): processes, requests. */
210
+ const failPending = (error) => {
252
211
  for (const p of procs.values())
253
212
  p.fail(error);
254
213
  procs.clear();
@@ -264,22 +223,137 @@ export async function createAgentBackend(options) {
264
223
  for (const r of connectRequests.values())
265
224
  r.reject(error);
266
225
  connectRequests.clear();
226
+ for (const r of killRequests.values())
227
+ r.reject(error);
228
+ killRequests.clear();
267
229
  for (const r of caRequests.values()) {
268
230
  r.installed.reject(error);
269
231
  r.settled.reject(error);
270
232
  }
271
233
  caRequests.clear();
234
+ };
235
+ const shutdown = (error) => {
236
+ if (closed !== undefined)
237
+ return;
238
+ closed = error;
239
+ ended.resolve();
240
+ hello.reject(error);
241
+ failPending(error);
272
242
  watches.clear();
273
243
  };
244
+ // What the agent's next session gets again (T222): the pod CA, host mode's HostExecInfo, the ports host processes
245
+ // hold in the guest (by their requests), the guest watches.
246
+ let caPem;
247
+ let hostExecInfo;
248
+ const held = new Map();
249
+ const restartListeners = new Set();
250
+ const emitRestart = (e) => {
251
+ for (const l of [...restartListeners]) {
252
+ try {
253
+ l(e);
254
+ }
255
+ catch (err) {
256
+ log("warn", `agent-restart listener: ${err.message}`);
257
+ }
258
+ }
259
+ };
260
+ let agentName = "";
261
+ let session = 1;
262
+ const restarts = [];
263
+ const words = (agent) => agent.split(" ");
264
+ const has = (word) => words(agentName).includes(word);
265
+ const sessionOf = (agent) => words(agent).find((w) => w.startsWith("session="))?.slice(8) ?? "";
266
+ // The same agent but for its session and whether it answers a Resume.
267
+ const sameAgent = (a, b) => {
268
+ const strip = (s) => words(s).filter((w) => w !== "resumed" && !w.startsWith("session=")).join(" ");
269
+ return strip(a) === strip(b);
270
+ };
271
+ const answer = (agent) => has("rejoin") ? send({ type: "rejoin", version: PROTOCOL_VERSION, session: sessionOf(agent) }) : send({ type: "hello", version: PROTOCOL_VERSION });
272
+ /**
273
+ * A Hello after the first (but one answering a Resume) is a new session of the agent: its last one ended (killed, out
274
+ * of memory, a broken stream) and took the processes it ran with it, and its host-mode state (T208). What waits for
275
+ * the last session fails with AGENT_RESTARTED; with an agent that takes a Rejoin the pod goes on with the new one,
276
+ * which gets what the last one had (T222), else the connection is over.
277
+ */
278
+ const restart = (agent) => {
279
+ const now = performance.now();
280
+ restarts.push(now);
281
+ while (now - restarts[0] > 60000)
282
+ restarts.shift();
283
+ const ended = procs.size;
284
+ const reason = !has("rejoin")
285
+ ? "the guest agent restarted: the processes it ran have ended"
286
+ : !sameAgent(agent, agentName)
287
+ ? `the guest agent restarted as another agent (${agent}): the processes it ran have ended`
288
+ : restarts.length > (options.maxRestarts ?? 3)
289
+ ? `the guest agent keeps restarting (${restarts.length} times within a minute): the processes it ran have ended`
290
+ : undefined;
291
+ if (reason !== undefined) {
292
+ log("warn", reason);
293
+ shutdown(new WebPodError("AGENT_RESTARTED", reason));
294
+ emitRestart({ session: session + 1, ended, final: true, reason });
295
+ return;
296
+ }
297
+ session++;
298
+ agentName = agent;
299
+ const message = "the guest agent restarted: the processes it ran have ended";
300
+ failPending(new WebPodError("AGENT_RESTARTED", message));
301
+ // The new session drops what comes before its Rejoin: what was sent the last one, failed above.
302
+ void answer(agent).catch(() => { });
303
+ if (caPem !== undefined) {
304
+ installCa(caPem).then((r) => r.warnings.forEach((w) => log("warn", `CA: ${w}`)), (e) => log("warn", `CA: ${e.message}`));
305
+ }
306
+ if (hostExecInfo)
307
+ void send(hostExecInfo).catch(() => { });
308
+ for (const [req, l] of held) {
309
+ const pending = new Deferred();
310
+ listenRequests.set(req, pending);
311
+ void send({ type: "hostListen", req, ...l }).catch(() => { });
312
+ pending.promise.then((r) => {
313
+ if (!("errno" in r))
314
+ return;
315
+ held.delete(req);
316
+ log("warn", `port ${l.port} of a host process is not held in the guest any more (errno ${r.errno})`);
317
+ }, () => { });
318
+ }
319
+ for (const [watch, w] of watches) {
320
+ const req = nextReq++;
321
+ const pending = new Deferred();
322
+ fsRequests.set(req, pending);
323
+ void send({ type: "fs", req, op: { op: "watch", watch, path: w.path, recursive: w.recursive } }).catch(() => { });
324
+ pending.promise.catch((e) => log("warn", `watch of ${w.path}: ${e.message}`));
325
+ // What changed meanwhile was not seen: rescan.
326
+ w.listener([{ kind: 4, path: w.path }]);
327
+ }
328
+ log("warn", `the guest agent started a new session (${session}): ${ended} process(es) of the last ended`);
329
+ emitRestart({ session, ended, final: false, reason: message });
330
+ };
331
+ // After a Resume one more Hello may be its answer: it says so (`resumed`, agents with resume-hello), else it is the
332
+ // first after the Resume, before anything else (the agent's own new session said the first).
333
+ let greeted = false;
334
+ let resumeHello = options.resume === true;
274
335
  const dispatch = (msg) => {
275
336
  if (msg.type === "hello") {
276
337
  if (msg.version !== PROTOCOL_VERSION) {
277
338
  shutdown(new WebPodError("UNSUPPORTED", `agent speaks protocol ${msg.version}, SDK ${PROTOCOL_VERSION}`));
278
339
  return;
279
340
  }
280
- hello.resolve(msg.agent);
341
+ const resumed = words(msg.agent).includes("resumed");
342
+ if (!greeted) {
343
+ greeted = true;
344
+ agentName = msg.agent;
345
+ if (resumed)
346
+ resumeHello = false;
347
+ hello.resolve(msg.agent);
348
+ }
349
+ else if (resumeHello && (resumed || !has("resume-hello")))
350
+ resumeHello = false;
351
+ else
352
+ restart(msg.agent);
281
353
  return;
282
354
  }
355
+ if (!has("resume-hello"))
356
+ resumeHello = false;
283
357
  if (msg.type === "fsResult") {
284
358
  const pending = fsRequests.get(msg.req);
285
359
  fsRequests.delete(msg.req);
@@ -307,6 +381,11 @@ export async function createAgentBackend(options) {
307
381
  pending?.reject(errnoError(msg.errno, msg.message || `errno ${msg.errno}`));
308
382
  return;
309
383
  }
384
+ if (msg.type === "killed") {
385
+ killRequests.get(msg.req)?.resolve(msg.errno);
386
+ killRequests.delete(msg.req);
387
+ return;
388
+ }
310
389
  if (msg.type === "hostConnected") {
311
390
  const pending = connectRequests.get(msg.req);
312
391
  connectRequests.delete(msg.req);
@@ -325,11 +404,11 @@ export async function createAgentBackend(options) {
325
404
  return;
326
405
  }
327
406
  if (msg.type === "fsEvents") {
328
- watches.get(msg.watch)?.(msg.events);
407
+ watches.get(msg.watch)?.listener(msg.events);
329
408
  return;
330
409
  }
331
410
  if (msg.type === "error") {
332
- console.warn(`webpod-agent: ${msg.message}`);
411
+ log("warn", msg.message);
333
412
  return;
334
413
  }
335
414
  if (msg.type.startsWith("host")) {
@@ -357,6 +436,78 @@ export async function createAgentBackend(options) {
357
436
  }
358
437
  return -1;
359
438
  };
439
+ const concat = (a, b) => {
440
+ const out = new Uint8Array(a.length + b.length);
441
+ out.set(a);
442
+ out.set(b, a.length);
443
+ return out;
444
+ };
445
+ let resync = null;
446
+ const PREAMBLE = MAX_FRAME + 8;
447
+ const PREAMBLE_MAX = MAX_FRAME + 16;
448
+ const takeResync = () => {
449
+ const r = resync;
450
+ if (!r.confirmed) {
451
+ // After a frame that did not decode: the preamble's zero-length frame must follow.
452
+ if (r.buf.length < 4)
453
+ return false;
454
+ if (r.buf[0] || r.buf[1] || r.buf[2] || r.buf[3])
455
+ throw r.error;
456
+ r.confirmed = true;
457
+ }
458
+ const start = findHello(r.buf);
459
+ let zeros = 0;
460
+ while (zeros < r.buf.length && r.buf[zeros] === 0)
461
+ zeros++;
462
+ if (start < 0) {
463
+ // The Hello's frame starts right after the zeros, or up to 3 bytes before their end (its length's low bytes may
464
+ // be zeros too): its tag there, or not here yet.
465
+ const tagged = [0, 1, 2, 3].some((k) => zeros - k >= 0 && (zeros - k + 4 >= r.buf.length || r.buf[zeros - k + 4] === 0x81));
466
+ if ((zeros < r.buf.length && !tagged) || r.buf.length > PREAMBLE_MAX + 64)
467
+ throw new ProtocolError("a zero-length frame that is not the agent's preamble");
468
+ return false;
469
+ }
470
+ if (zeros < start || start > PREAMBLE_MAX)
471
+ throw new ProtocolError("a zero-length frame that is not the agent's preamble");
472
+ // The preamble is PREAMBLE zero bytes: those it lacks here completed a frame the dead agent process cut short.
473
+ const completed = PREAMBLE - start;
474
+ const cut = completed <= 0 ? "" : `a frame the last agent process cut short (${completed} zero bytes completed it; ${r.cut > 0 ? "it did not decode" : "what it carried went to the last session"}), then `;
475
+ log("warn", `the agent's stream resynced: ${cut}the preamble of the next agent process (${start} zero bytes) skipped`);
476
+ decoder = new FrameDecoder();
477
+ decoder.push(r.buf.subarray(start));
478
+ resync = null;
479
+ return true;
480
+ };
481
+ const resyncs = () => !greeted || has("resync");
482
+ const drain = () => {
483
+ for (;;) {
484
+ if (resync && !takeResync())
485
+ return;
486
+ let body;
487
+ try {
488
+ body = decoder.next();
489
+ }
490
+ catch (e) {
491
+ if (!(e instanceof ZeroLengthFrame) || !resyncs())
492
+ throw e;
493
+ resync = { cut: 0, buf: decoder.rest(), error: e, confirmed: true };
494
+ continue;
495
+ }
496
+ if (!body)
497
+ return;
498
+ let msg;
499
+ try {
500
+ msg = decodeGuestMsg(body);
501
+ }
502
+ catch (e) {
503
+ if (!resyncs())
504
+ throw e;
505
+ resync = { cut: body.length + 4, buf: decoder.rest(), error: e, confirmed: false };
506
+ continue;
507
+ }
508
+ dispatch(msg);
509
+ }
510
+ };
360
511
  void (async () => {
361
512
  try {
362
513
  for (;;) {
@@ -364,9 +515,7 @@ export async function createAgentBackend(options) {
364
515
  if (done)
365
516
  break;
366
517
  if (syncing) {
367
- const merged = new Uint8Array(pendingBytes.length + value.length);
368
- merged.set(pendingBytes);
369
- merged.set(value, pendingBytes.length);
518
+ const merged = concat(pendingBytes, value);
370
519
  const start = findHello(merged);
371
520
  if (start < 0) {
372
521
  pendingBytes = merged.slice(-64 * 1024);
@@ -375,10 +524,11 @@ export async function createAgentBackend(options) {
375
524
  syncing = false;
376
525
  decoder.push(merged.subarray(start));
377
526
  }
527
+ else if (resync)
528
+ resync.buf = concat(resync.buf, value);
378
529
  else
379
530
  decoder.push(value);
380
- for (let body = decoder.next(); body; body = decoder.next())
381
- dispatch(decodeGuestMsg(body));
531
+ drain();
382
532
  }
383
533
  shutdown(new WebPodError("DISPOSED", "agent connection closed"));
384
534
  }
@@ -393,7 +543,7 @@ export async function createAgentBackend(options) {
393
543
  void send({ type: "resume" }).catch(() => { });
394
544
  const helloDeadline = helloWait(options.helloTimeoutMs ?? 30000, options.helloDownloads);
395
545
  const agent = await Promise.race([hello.promise, helloDeadline.promise]).finally(helloDeadline.cancel);
396
- await send({ type: "hello", version: PROTOCOL_VERSION });
546
+ await answer(agent);
397
547
  const agentFs = new AgentFs({
398
548
  canSync: /(^|\s)fs-sync(\s|$)/.test(agent),
399
549
  request(op) {
@@ -406,16 +556,17 @@ export async function createAgentBackend(options) {
406
556
  });
407
557
  return pending.promise;
408
558
  },
409
- addWatch(listener) {
559
+ addWatch(listener, path, recursive) {
410
560
  const watch = nextWatch++;
411
- watches.set(watch, listener);
561
+ watches.set(watch, { listener, path, recursive });
412
562
  return watch;
413
563
  },
414
564
  removeWatch(watch) {
415
565
  watches.delete(watch);
416
566
  },
417
567
  });
418
- const installCa = (pem) => {
568
+ function installCa(pem) {
569
+ caPem = pem;
419
570
  const req = nextReq++;
420
571
  const pending = { installed: new Deferred(), settled: new Deferred() };
421
572
  caRequests.set(req, pending);
@@ -425,16 +576,16 @@ export async function createAgentBackend(options) {
425
576
  pending.settled.reject(e);
426
577
  });
427
578
  return pending.installed.promise;
428
- };
579
+ }
429
580
  let caSettled = null;
430
581
  if (options.caCertificate !== undefined) {
431
582
  const result = await installCa(options.caCertificate);
432
583
  if (result.bundle === null)
433
584
  throw new WebPodError("EINVAL", `CA not installed: ${result.warnings.join("; ")}`);
434
585
  for (const w of result.warnings)
435
- console.warn(`webpod-agent: CA: ${w}`);
586
+ log("warn", `CA: ${w}`);
436
587
  caSettled = result.settled;
437
- caSettled.then((ws) => ws.forEach((w) => console.warn(`webpod-agent: CA: ${w}`))).catch(() => { });
588
+ caSettled.then((ws) => ws.forEach((w) => log("warn", `CA: ${w}`))).catch(() => { });
438
589
  }
439
590
  const EVENT_KINDS = { create: 1, modify: 2, delete: 3, overflow: 4 };
440
591
  const replayAcks = /(^|\s)fs-replay(\s|$)/.test(agent);
@@ -454,6 +605,19 @@ export async function createAgentBackend(options) {
454
605
  });
455
606
  return pending.promise;
456
607
  };
608
+ // A part of the page's changes whose replay the agent's restart cut off goes to its next session: a replay can be
609
+ // done again, and settle() waits for it.
610
+ const replay = async (changes) => {
611
+ for (;;) {
612
+ try {
613
+ return await op((req) => ({ type: "fsReplay", req, changes }), 600000);
614
+ }
615
+ catch (e) {
616
+ if (!(e instanceof WebPodError && e.code === "AGENT_RESTARTED" && closed === undefined))
617
+ throw e;
618
+ }
619
+ }
620
+ };
457
621
  const hostListen = /(^|\s)host-listen(\s|$)/.test(agent)
458
622
  ? {
459
623
  listen(addr, port, uid) {
@@ -464,9 +628,15 @@ export async function createAgentBackend(options) {
464
628
  listenRequests.delete(req);
465
629
  pending.reject(e);
466
630
  });
631
+ // Held again in the agent's next session, under the same request.
632
+ void pending.promise.then((r) => {
633
+ if (!("errno" in r))
634
+ held.set(req, { addr, port: r.port, uid });
635
+ }, () => { });
467
636
  return pending.promise;
468
637
  },
469
638
  unlisten(req) {
639
+ held.delete(req);
470
640
  void send({ type: "hostUnlisten", req }).catch(() => { });
471
641
  },
472
642
  connect(port) {
@@ -481,17 +651,45 @@ export async function createAgentBackend(options) {
481
651
  },
482
652
  }
483
653
  : null;
654
+ const killPid = /(^|\s)kill(\s|$)/.test(agent)
655
+ ? (pid, signal, uid) => {
656
+ const req = nextReq++;
657
+ const pending = new Deferred();
658
+ killRequests.set(req, pending);
659
+ send({ type: "kill", req, pid, signal, uid }).catch((e) => {
660
+ killRequests.delete(req);
661
+ pending.reject(e);
662
+ });
663
+ return pending.promise;
664
+ }
665
+ : null;
666
+ const onAgentRestart = (listener) => {
667
+ restartListeners.add(listener);
668
+ return () => void restartListeners.delete(listener);
669
+ };
484
670
  const hostMode = /(^|\s)host-exec(\s|$)/.test(agent)
485
671
  ? {
486
- send: (msg) => send(msg),
672
+ send: (msg) => {
673
+ if (msg.type === "hostExecInfo")
674
+ hostExecInfo = msg;
675
+ return send(msg);
676
+ },
487
677
  listen: (listener) => void (hostListener = listener),
678
+ onSession: (listener) => onAgentRestart((e) => e.final || listener()),
488
679
  closed: ended.promise,
489
680
  }
490
681
  : null;
491
682
  return {
492
- agent,
683
+ get agent() {
684
+ return agentName;
685
+ },
686
+ get session() {
687
+ return session;
688
+ },
689
+ onAgentRestart,
493
690
  hostListen,
494
691
  hostMode,
692
+ killPid,
495
693
  installCa,
496
694
  caSettled,
497
695
  freeze: (paths, timeoutMs = 10000) => op((req) => ({ type: "freeze", req, paths, timeoutMs })),
@@ -504,7 +702,7 @@ export async function createAgentBackend(options) {
504
702
  if (!replayAcks)
505
703
  return parts.reduce((p, part) => p.then(() => send({ type: "fsNotify", changes: part })), Promise.resolve()).then(() => false);
506
704
  // Each answered once its part is replayed: behind a backlog of earlier ones, so no 30 s limit.
507
- return parts.reduce((p, part) => p.then(() => op((req) => ({ type: "fsReplay", req, changes: part }), 600000)), Promise.resolve()).then(() => true);
705
+ return parts.reduce((p, part) => p.then(() => replay(part)), Promise.resolve()).then(() => true);
508
706
  },
509
707
  fs: createFsRouter(agentFs, options.mounts),
510
708
  spawn(req) {
@@ -531,6 +729,7 @@ export async function createAgentBackend(options) {
531
729
  },
532
730
  async dispose() {
533
731
  shutdown(new WebPodError("DISPOSED", "pod has been disposed"));
732
+ restartListeners.clear();
534
733
  await writer.close().catch(() => { });
535
734
  await reader.cancel().catch(() => { });
536
735
  },