@ai-ecoverse/slicc-kernel 1.182.0 → 1.184.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 (78) hide show
  1. package/README.md +150 -5
  2. package/dist/async-process.js +14060 -0
  3. package/dist/async-process.js.map +7 -0
  4. package/dist/cloudflare-sources.js +2 -0
  5. package/dist/cloudflare.js +42562 -0
  6. package/dist/cloudflare.js.map +7 -0
  7. package/dist/driver-worker.js +290 -90
  8. package/dist/driver-worker.js.map +4 -4
  9. package/dist/index.js +328 -102
  10. package/dist/index.js.map +4 -4
  11. package/dist/kernel-worker.js +1837 -732
  12. package/dist/kernel-worker.js.map +4 -4
  13. package/dist/node-driver-worker.js +298 -98
  14. package/dist/node-driver-worker.js.map +4 -4
  15. package/dist/node-process-worker.cjs +4719 -652
  16. package/dist/node-process-worker.cjs.map +4 -4
  17. package/dist/node-process-worker.js +4719 -652
  18. package/dist/node-process-worker.js.map +4 -4
  19. package/dist/node.js +3341 -924
  20. package/dist/node.js.map +4 -4
  21. package/dist/process-worker.js +4625 -558
  22. package/dist/process-worker.js.map +4 -4
  23. package/dist/types/async/header-hook.d.ts +3 -0
  24. package/dist/types/async/link.d.ts +14 -0
  25. package/dist/types/async/message-link.d.ts +15 -0
  26. package/dist/types/async/node-host.d.ts +16 -0
  27. package/dist/types/async/remote-worker.d.ts +12 -0
  28. package/dist/types/async/snapshots.d.ts +13 -0
  29. package/dist/types/async/transport.d.ts +28 -0
  30. package/dist/types/async/wire.d.ts +113 -0
  31. package/dist/types/cdp/port.d.ts +2 -1
  32. package/dist/types/client/attach.d.ts +2 -0
  33. package/dist/types/client/protocol.d.ts +1 -0
  34. package/dist/types/client/serve-client.d.ts +1 -0
  35. package/dist/types/cloudflare/clock-skew.d.ts +2 -0
  36. package/dist/types/cloudflare/computer-driver.d.ts +65 -0
  37. package/dist/types/cloudflare/computer.d.ts +105 -0
  38. package/dist/types/cloudflare/fork-tokens.d.ts +17 -0
  39. package/dist/types/cloudflare/images.d.ts +20 -0
  40. package/dist/types/cloudflare/isolates.d.ts +17 -0
  41. package/dist/types/cloudflare/kernel-end.d.ts +45 -0
  42. package/dist/types/cloudflare/loader.d.ts +54 -0
  43. package/dist/types/cloudflare/options.d.ts +81 -0
  44. package/dist/types/cloudflare/placement.d.ts +61 -0
  45. package/dist/types/cloudflare/rpc-link.d.ts +49 -0
  46. package/dist/types/cloudflare/rpc-pack.d.ts +7 -0
  47. package/dist/types/cloudflare/sqlite-meta.d.ts +4 -0
  48. package/dist/types/cloudflare/sqlite-root.d.ts +5 -0
  49. package/dist/types/cloudflare/sqlite-store.d.ts +73 -0
  50. package/dist/types/cloudflare.d.ts +16 -0
  51. package/dist/types/devices-relay.d.ts +74 -0
  52. package/dist/types/facade/port.d.ts +2 -1
  53. package/dist/types/index.d.ts +14 -0
  54. package/dist/types/kernel/devices.d.ts +155 -0
  55. package/dist/types/kernel/embedder.d.ts +2 -0
  56. package/dist/types/kernel/fd-table.d.ts +3 -1
  57. package/dist/types/kernel/host.d.ts +3 -0
  58. package/dist/types/kernel/process.d.ts +22 -0
  59. package/dist/types/kernel/protocol.d.ts +1 -0
  60. package/dist/types/kernel/serial-ioctl.d.ts +73 -0
  61. package/dist/types/launcher.d.ts +20 -0
  62. package/dist/types/mount/hostfs.d.ts +2 -1
  63. package/dist/types/mount/in-process.d.ts +15 -0
  64. package/dist/types/node.d.ts +20 -2
  65. package/dist/types/ports.d.ts +7 -0
  66. package/dist/types/process/js/js-dev.d.ts +24 -0
  67. package/dist/types/process/kernel-streams.d.ts +11 -1
  68. package/dist/types/process/process-pty.d.ts +1 -0
  69. package/dist/types/process/wasi/wasi-fds.d.ts +1 -0
  70. package/dist/types/process/wasi/wasi-files.d.ts +1 -0
  71. package/dist/types/process/wasi/wasi-host.d.ts +3 -2
  72. package/dist/types/process/wasi/wasi-module.d.ts +2 -0
  73. package/dist/types/process/wasi/wasi-sigmask.d.ts +2 -1
  74. package/dist/types/process/wasi/wasi-termios.d.ts +1 -0
  75. package/dist/types/process/wasi/wasm-reentry.d.ts +1 -0
  76. package/dist/types/realm/sync-sab-bridge.d.ts +1 -0
  77. package/dist/types/serve.d.ts +14 -1
  78. package/package.json +11 -5
@@ -652,8 +652,8 @@ function dirsChannel(metadata) {
652
652
  function noticeOf(data) {
653
653
  if (Array.isArray(data)) return { paths: data.filter((p) => typeof p === "string"), trees: [] };
654
654
  const notice = data ?? {};
655
- const strings2 = (list) => Array.isArray(list) ? list.filter((p) => typeof p === "string") : [];
656
- return { paths: strings2(notice.paths), trees: strings2(notice.trees), outside: true };
655
+ const strings3 = (list) => Array.isArray(list) ? list.filter((p) => typeof p === "string") : [];
656
+ return { paths: strings3(notice.paths), trees: strings3(notice.trees), outside: true };
657
657
  }
658
658
 
659
659
  // src/fs/types.ts
@@ -1427,15 +1427,15 @@ var RemoteWatch = class {
1427
1427
  this.channel.postMessage({ ack: seq2, from: this.tab, to: from });
1428
1428
  }
1429
1429
  hold(add, drop, wait2) {
1430
- const fresh3 = add.filter(
1430
+ const fresh4 = add.filter(
1431
1431
  ([path, fid]) => !this.myHolds.has(path) || this.myHolds.get(path) !== fid
1432
1432
  );
1433
1433
  const gone = drop.filter((path) => this.myHolds.has(path));
1434
1434
  for (const path of gone) this.myHolds.delete(path);
1435
- for (const [path, fid] of fresh3) this.myHolds.set(path, fid);
1436
- if (fresh3.length === 0 && gone.length === 0 || this.peers.size === 0)
1435
+ for (const [path, fid] of fresh4) this.myHolds.set(path, fid);
1436
+ if (fresh4.length === 0 && gone.length === 0 || this.peers.size === 0)
1437
1437
  return Promise.resolve();
1438
- const seq2 = this.sendHolds(fresh3, gone);
1438
+ const seq2 = this.sendHolds(fresh4, gone);
1439
1439
  if (!wait2) return Promise.resolve();
1440
1440
  const heard = new Set(
1441
1441
  [...this.peers].filter((peer) => this.holders.has(peer) && !this.silent.has(peer))
@@ -2121,7 +2121,7 @@ var OpfsFs = class {
2121
2121
  const parent = entries.at(-1);
2122
2122
  const setgid = ((parent?.mode ?? 0) & S_ISGID2) !== 0;
2123
2123
  const parentGid = (ownOf(parent) ?? inherit(entries.slice(0, -1))).gid;
2124
- const want = { uid: owner.uid, gid: setgid ? parentGid : owner.gid };
2124
+ const want2 = { uid: owner.uid, gid: setgid ? parentGid : owner.gid };
2125
2125
  let mode = owner.mode === void 0 ? void 0 : owner.mode & PERM_MASK;
2126
2126
  if (directory && setgid) mode = (mode ?? 493) | S_ISGID2;
2127
2127
  const fields = {};
@@ -2129,7 +2129,7 @@ var OpfsFs = class {
2129
2129
  fields.mode = mode;
2130
2130
  }
2131
2131
  if (self) fields.heir = void 0;
2132
- if (ownOf(self) || !sameOwner(want, inherit(entries))) Object.assign(fields, want);
2132
+ if (ownOf(self) || !sameOwner(want2, inherit(entries))) Object.assign(fields, want2);
2133
2133
  return Object.keys(fields).length > 0 ? fields : void 0;
2134
2134
  }
2135
2135
  async stampNew(path, owner, directory) {
@@ -2366,9 +2366,9 @@ var OpfsFs = class {
2366
2366
  this.lookups++;
2367
2367
  if (split(path).length === 0) return this.root;
2368
2368
  const cached = this.files.get(path);
2369
- const fresh3 = cached && performance.now() - (this.found.get(cached) ?? -CHECK_MS) < CHECK_MS;
2370
- if (cached && !fresh3) this.files.delete(path);
2371
- if (cached && fresh3) {
2369
+ const fresh4 = cached && performance.now() - (this.found.get(cached) ?? -CHECK_MS) < CHECK_MS;
2370
+ if (cached && !fresh4) this.files.delete(path);
2371
+ if (cached && fresh4) {
2372
2372
  if (this.glanced(cached)) return this.remember(path, cached);
2373
2373
  try {
2374
2374
  await this.glance(cached);
@@ -2586,8 +2586,8 @@ var OpfsFs = class {
2586
2586
  glanced(handle) {
2587
2587
  if (this.exact > 0) return void 0;
2588
2588
  const seen = this.glances.get(handle);
2589
- const fresh3 = seen && seen.changes === this.changes && this.recent(seen, GLANCE_LOOKUPS);
2590
- return fresh3 ? seen.file : void 0;
2589
+ const fresh4 = seen && seen.changes === this.changes && this.recent(seen, GLANCE_LOOKUPS);
2590
+ return fresh4 ? seen.file : void 0;
2591
2591
  }
2592
2592
  async glance(handle) {
2593
2593
  const at = performance.now();
@@ -2789,13 +2789,13 @@ var OpfsFs = class {
2789
2789
  async keptFor(path) {
2790
2790
  const at = normalizePath(path);
2791
2791
  const cached = this.files.get(at);
2792
- const fresh3 = cached && performance.now() - (this.found.get(cached) ?? -CHECK_MS) < CHECK_MS;
2793
- const [target, existed] = fresh3 ? [at, true] : await this.writeTarget(path);
2792
+ const fresh4 = cached && performance.now() - (this.found.get(cached) ?? -CHECK_MS) < CHECK_MS;
2793
+ const [target, existed] = fresh4 ? [at, true] : await this.writeTarget(path);
2794
2794
  if (!existed) return [void 0, target, false];
2795
2795
  this.refuse(target);
2796
2796
  const [entry] = await this.meta.get([target]);
2797
2797
  if (entry?.fifo || entry?.socket) throw fsError("ENXIO", path);
2798
- const kept = fresh3 ? cached : this.files.get(target);
2798
+ const kept = fresh4 ? cached : this.files.get(target);
2799
2799
  const usable3 = kept && performance.now() - (this.found.get(kept) ?? -CHECK_MS) < CHECK_MS;
2800
2800
  return [usable3 ? kept : void 0, target, true];
2801
2801
  }
@@ -4342,21 +4342,21 @@ function latin1Bytes(text) {
4342
4342
  return out;
4343
4343
  }
4344
4344
  function parseRequestHead(bytes) {
4345
- const lines2 = latin1(bytes).split(/\r?\n/);
4346
- while (lines2.length > 0 && lines2[0] === "") lines2.shift();
4347
- const match = /^([!#$%&'*+\-.^_`|~0-9A-Za-z]+) (\S+) HTTP\/(\d)\.(\d)$/.exec(lines2.shift() ?? "");
4345
+ const lines3 = latin1(bytes).split(/\r?\n/);
4346
+ while (lines3.length > 0 && lines3[0] === "") lines3.shift();
4347
+ const match = /^([!#$%&'*+\-.^_`|~0-9A-Za-z]+) (\S+) HTTP\/(\d)\.(\d)$/.exec(lines3.shift() ?? "");
4348
4348
  if (!match) throw new HttpError(400, "malformed request line");
4349
4349
  if (match[3] !== "1") throw new HttpError(505, `HTTP/${match[3]}.${match[4]} is not supported`);
4350
4350
  return {
4351
4351
  method: match[1],
4352
4352
  target: match[2],
4353
4353
  minor: Number(match[4]),
4354
- headers: parseFields(lines2)
4354
+ headers: parseFields(lines3)
4355
4355
  };
4356
4356
  }
4357
- function parseFields(lines2) {
4357
+ function parseFields(lines3) {
4358
4358
  const headers = [];
4359
- for (const line of lines2) {
4359
+ for (const line of lines3) {
4360
4360
  if (line === "") continue;
4361
4361
  if (line.startsWith(" ") || line.startsWith(" ")) {
4362
4362
  throw new HttpError(400, "obsolete line folding");
@@ -4841,10 +4841,10 @@ var CdpFacade = class {
4841
4841
  reject(new HttpError(502, `the CDP host closed: ${reason ?? "no reason"}`));
4842
4842
  };
4843
4843
  conn.onmessage = (message3) => {
4844
- const parsed2 = JSON.parse(message3);
4845
- if (parsed2.id !== 1) return;
4844
+ const parsed3 = JSON.parse(message3);
4845
+ if (parsed3.id !== 1) return;
4846
4846
  clearTimeout(timer);
4847
- resolve2(parsed2);
4847
+ resolve2(parsed3);
4848
4848
  };
4849
4849
  conn.send(JSON.stringify({ id: 1, method: "Target.getTargets" }));
4850
4850
  }
@@ -5032,10 +5032,13 @@ function fresh(bytes, start2 = 0, end = bytes.length) {
5032
5032
  return new Uint8Array(bytes.subarray(start2, end));
5033
5033
  }
5034
5034
 
5035
+ // src/ports.ts
5036
+ var messageChannel = () => new MessageChannel();
5037
+
5035
5038
  // src/cdp/port.ts
5036
- function portCdpHook(ask, gone) {
5039
+ function portCdpHook(ask, gone, ports = messageChannel) {
5037
5040
  return (request3) => new Promise((resolve2, reject) => {
5038
- const { port1, port2 } = new MessageChannel();
5041
+ const { port1, port2 } = ports();
5039
5042
  let closed = false;
5040
5043
  const conn = {
5041
5044
  send: (m) => {
@@ -5075,10 +5078,129 @@ function portCdpHook(ask, gone) {
5075
5078
  });
5076
5079
  }
5077
5080
 
5078
- // src/embedder-relay.ts
5081
+ // src/devices-relay.ts
5082
+ function quiet() {
5083
+ return void 0;
5084
+ }
5085
+ function raised(failure2) {
5086
+ return Object.assign(new Error(failure2.message), { name: failure2.name });
5087
+ }
5079
5088
  function fresh2(bytes) {
5080
5089
  return bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
5081
5090
  }
5091
+ function devicesAsker(port) {
5092
+ const remotes2 = /* @__PURE__ */ new Map();
5093
+ let next3 = 0;
5094
+ const post = (message3, transfer = []) => port.postMessage({ devices: message3 }, transfer);
5095
+ const push = (remote, item) => {
5096
+ remote.chunks.push(item);
5097
+ remote.wake?.();
5098
+ };
5099
+ const streams = (id2, remote) => ({
5100
+ readable: new ReadableStream(
5101
+ {
5102
+ pull: async (controller) => {
5103
+ if (remote.chunks.length === 0) {
5104
+ post({ id: id2, pull: true });
5105
+ await new Promise((resolve2) => {
5106
+ remote.wake = resolve2;
5107
+ });
5108
+ }
5109
+ const item = remote.chunks.shift();
5110
+ if (item instanceof Uint8Array) controller.enqueue(item);
5111
+ else if (item === null || item === void 0) controller.close();
5112
+ else controller.error(raised(item));
5113
+ },
5114
+ cancel: (reason) => {
5115
+ post({ id: id2, cancel: String(reason ?? "closed") });
5116
+ }
5117
+ },
5118
+ { highWaterMark: 0 }
5119
+ ),
5120
+ writable: new WritableStream({
5121
+ write: (chunk2) => {
5122
+ const seq2 = ++remote.seq;
5123
+ const done5 = Promise.withResolvers();
5124
+ remote.writes.set(seq2, done5);
5125
+ const bytes = fresh2(chunk2);
5126
+ post({ id: id2, write: bytes, seq: seq2 }, [bytes.buffer]);
5127
+ return done5.promise;
5128
+ },
5129
+ abort: (reason) => {
5130
+ post({ id: id2, cancel: String(reason ?? "closed") });
5131
+ }
5132
+ }),
5133
+ control: (op, args) => {
5134
+ const seq2 = ++remote.seq;
5135
+ const done5 = Promise.withResolvers();
5136
+ remote.controls.set(seq2, done5);
5137
+ post({ id: id2, control: { seq: seq2, op, ...args ? { args } : {} } });
5138
+ if (op === "close") void done5.promise.finally(() => remotes2.delete(id2)).catch(quiet);
5139
+ return done5.promise;
5140
+ }
5141
+ });
5142
+ const hookFor = (client) => ({
5143
+ open: async (request3) => {
5144
+ const id2 = ++next3;
5145
+ const remote = {
5146
+ opened: Promise.withResolvers(),
5147
+ chunks: [],
5148
+ wake: void 0,
5149
+ writes: /* @__PURE__ */ new Map(),
5150
+ controls: /* @__PURE__ */ new Map(),
5151
+ seq: 0
5152
+ };
5153
+ remotes2.set(id2, remote);
5154
+ const abort = () => {
5155
+ remotes2.delete(id2);
5156
+ post({ id: id2, cancel: "interrupted" });
5157
+ remote.opened.reject(request3.signal.reason);
5158
+ };
5159
+ request3.signal.addEventListener("abort", abort, { once: true });
5160
+ const { path, flags: flags2, stamp } = request3;
5161
+ post({ id: id2, open: { client, path, flags: flags2, stamp } });
5162
+ try {
5163
+ await remote.opened.promise;
5164
+ } finally {
5165
+ request3.signal.removeEventListener("abort", abort);
5166
+ }
5167
+ return streams(id2, remote);
5168
+ }
5169
+ });
5170
+ const answer2 = (message3) => {
5171
+ const remote = remotes2.get(message3.id);
5172
+ if (!remote) return;
5173
+ if ("opened" in message3) remote.opened.resolve();
5174
+ else if ("failed" in message3) {
5175
+ remotes2.delete(message3.id);
5176
+ remote.opened.reject(raised(message3.failed));
5177
+ } else if ("chunk" in message3) push(remote, message3.chunk);
5178
+ else if ("done" in message3) push(remote, null);
5179
+ else if ("readError" in message3) push(remote, message3.readError);
5180
+ else if ("wrote" in message3) {
5181
+ remote.writes.get(message3.wrote)?.resolve();
5182
+ remote.writes.delete(message3.wrote);
5183
+ } else if ("writeError" in message3) {
5184
+ remote.writes.get(message3.seq)?.reject(raised(message3.writeError));
5185
+ remote.writes.delete(message3.seq);
5186
+ } else if ("answered" in message3) {
5187
+ remote.controls.get(message3.answered)?.resolve(message3.value);
5188
+ remote.controls.delete(message3.answered);
5189
+ } else {
5190
+ remote.controls.get(message3.refused)?.reject(raised(message3.error));
5191
+ remote.controls.delete(message3.refused);
5192
+ }
5193
+ };
5194
+ return { hookFor, answer: answer2 };
5195
+ }
5196
+ function devicesReplyOf(data) {
5197
+ return data?.devicesReply;
5198
+ }
5199
+
5200
+ // src/embedder-relay.ts
5201
+ function fresh3(bytes) {
5202
+ return bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
5203
+ }
5082
5204
  function embedderAsker(port) {
5083
5205
  const asks = /* @__PURE__ */ new Map();
5084
5206
  let next3 = 0;
@@ -5117,7 +5239,7 @@ function embedderAsker(port) {
5117
5239
  const got = await asked.body.read().catch(() => ({ done: true, value: void 0 }));
5118
5240
  if (got.done) post({ id: id2, bodyEnd: true });
5119
5241
  else {
5120
- const bytes = fresh2(got.value);
5242
+ const bytes = fresh3(got.value);
5121
5243
  post({ id: id2, body: bytes }, [bytes.buffer]);
5122
5244
  }
5123
5245
  };
@@ -5174,9 +5296,9 @@ function embedderReplyOf(data) {
5174
5296
 
5175
5297
  // src/facade/port.ts
5176
5298
  var FACADE_GONE = "the facade host is gone";
5177
- function portFacadeHook(ask, gone) {
5299
+ function portFacadeHook(ask, gone, ports = messageChannel) {
5178
5300
  return (stamp, { name: name2 }) => new Promise((resolve2, reject) => {
5179
- const { port1, port2 } = new MessageChannel();
5301
+ const { port1, port2 } = ports();
5180
5302
  let closed = false;
5181
5303
  const shut = () => {
5182
5304
  closed = true;
@@ -5288,11 +5410,11 @@ function permOf(st, link2) {
5288
5410
  ...link2 !== void 0 ? { link: link2 } : {}
5289
5411
  };
5290
5412
  }
5291
- function permits(cred, perm, want, directory = true) {
5413
+ function permits(cred, perm, want2, directory = true) {
5292
5414
  const mode = perm.mode ?? (directory ? 493 : 420);
5293
- if (cred.euid === 0) return (want & X_OK) === 0 || directory || (mode & 73) !== 0;
5415
+ if (cred.euid === 0) return (want2 & X_OK) === 0 || directory || (mode & 73) !== 0;
5294
5416
  const shift = cred.euid === perm.uid ? 6 : inGroup(cred, perm.gid) ? 3 : 0;
5295
- return (mode >> shift & want) === want;
5417
+ return (mode >> shift & want2) === want2;
5296
5418
  }
5297
5419
  function sticky(cred, dir, entry) {
5298
5420
  if (cred.euid === 0 || ((dir.mode ?? 0) & S_ISVTX) === 0) return true;
@@ -5367,27 +5489,27 @@ async function present(fs, path, directory) {
5367
5489
  const st = await fs.lstat(path).catch(() => void 0);
5368
5490
  return st !== void 0 && (!directory || st.isDirectory);
5369
5491
  }
5370
- async function finalOf(fs, walked, want, options) {
5492
+ async function finalOf(fs, walked, want2, options) {
5371
5493
  const perm = walked.perm;
5372
5494
  if (options.follow === false && perm.link !== void 0) {
5373
5495
  return [{ ...perm, mode: 511 }, false];
5374
5496
  }
5375
- if ((want & X_OK) === 0 || options.directory !== void 0) {
5497
+ if ((want2 & X_OK) === 0 || options.directory !== void 0) {
5376
5498
  return [perm, options.directory !== false];
5377
5499
  }
5378
5500
  const look = options.follow === false ? fs.lstat : fs.stat;
5379
5501
  const st = await look.call(fs, walked.path).catch(() => void 0);
5380
5502
  return st ? [permOf(st), st.isDirectory] : [perm, false];
5381
5503
  }
5382
- async function access(fs, cred, path, want, options = {}) {
5504
+ async function access(fs, cred, path, want2, options = {}) {
5383
5505
  const walked = await walk(fs, cred, path, options.follow !== false, options.links);
5384
5506
  if (walked.denied !== void 0) {
5385
5507
  if (walked.link || await present(fs, walked.denied, true)) return walked;
5386
5508
  return { path, perm: void 0, missing: true };
5387
5509
  }
5388
5510
  if (!walked.perm) return { ...walked, missing: true };
5389
- const [perm, directory] = await finalOf(fs, walked, want, options);
5390
- if (want === 0 || permits(cred, perm, want, directory)) return walked;
5511
+ const [perm, directory] = await finalOf(fs, walked, want2, options);
5512
+ if (want2 === 0 || permits(cred, perm, want2, directory)) return walked;
5391
5513
  if (await present(fs, walked.path, false)) return { ...walked, denied: walked.path };
5392
5514
  return { ...walked, missing: true };
5393
5515
  }
@@ -5493,11 +5615,11 @@ function ttyOpenable(g, tty) {
5493
5615
  if (!g || !tty.owner || permits(g.cred, tty.owner, R_OK | W_OK, false)) return;
5494
5616
  deny(g, "open", tty.name ?? "/dev/tty");
5495
5617
  }
5496
- async function need(g, op, path, want, options = {}, shown2 = path) {
5497
- if (want & W_OK && shown2 === path) await fence(g, op, path);
5498
- const walked = await access(g.fs, g.cred, path, want, linked(g, options));
5618
+ async function need(g, op, path, want2, options = {}, shown2 = path) {
5619
+ if (want2 & W_OK && shown2 === path) await fence(g, op, path);
5620
+ const walked = await access(g.fs, g.cred, path, want2, linked(g, options));
5499
5621
  if (walked.denied !== void 0) deny(g, op, walked.link ? walked.denied : shown2);
5500
- else if (want & R_OK && g.fs.commandTarget) await readsAs(g, op, walked.path, shown2);
5622
+ else if (want2 & R_OK && g.fs.commandTarget) await readsAs(g, op, walked.path, shown2);
5501
5623
  return walked;
5502
5624
  }
5503
5625
  async function readsAs(g, op, path, shown2) {
@@ -5646,10 +5768,10 @@ async function creatable(g, op, path) {
5646
5768
  const target = await need(g, op, path, 0);
5647
5769
  if (target.denied === void 0) await need(g, op, parentOf5(target.path), W_OK | X_OK, DIR, path);
5648
5770
  }
5649
- async function openable(g, op, path, want, create) {
5771
+ async function openable(g, op, path, want2, create) {
5650
5772
  const st = create ? await g.fs.stat(path).catch(() => void 0) : void 0;
5651
5773
  if (create && !st) return creatable(g, op, path);
5652
- await need(g, op, path, want, { directory: st?.isDirectory ?? false });
5774
+ await need(g, op, path, want2, { directory: st?.isDirectory ?? false });
5653
5775
  }
5654
5776
 
5655
5777
  // src/kernel/cred.ts
@@ -6090,8 +6212,8 @@ var FdTable = class _FdTable {
6090
6212
  }
6091
6213
  stdioTerminal() {
6092
6214
  for (const fd of [0, 1, 2]) {
6093
- const tty = this.fds.get(fd)?.file.tty;
6094
- if (tty) return tty;
6215
+ const file = this.fds.get(fd)?.file;
6216
+ if (file?.tty && !file.device) return file.tty;
6095
6217
  }
6096
6218
  return void 0;
6097
6219
  }
@@ -6392,13 +6514,13 @@ function addressBits(host) {
6392
6514
  function parsePrefix(text) {
6393
6515
  const parts2 = text.trim().split("/");
6394
6516
  if (parts2.length > 2) return void 0;
6395
- const [address = "", size] = parts2;
6396
- const parsed2 = addressBits(address);
6397
- if (!parsed2) return void 0;
6398
- const max = parsed2.v6 ? 128 : 32;
6517
+ const [address2 = "", size] = parts2;
6518
+ const parsed3 = addressBits(address2);
6519
+ if (!parsed3) return void 0;
6520
+ const max = parsed3.v6 ? 128 : 32;
6399
6521
  const length2 = size === void 0 ? max : /^\d{1,3}$/.test(size) ? Number(size) : -1;
6400
6522
  if (length2 < 0 || length2 > max) return void 0;
6401
- return { ...parsed2, length: length2 };
6523
+ return { ...parsed3, length: length2 };
6402
6524
  }
6403
6525
  function within4(prefix, addr) {
6404
6526
  if (prefix.v6 !== addr.v6) return false;
@@ -6424,10 +6546,10 @@ var Routes = class {
6424
6546
  this.ipv6 = ipv62;
6425
6547
  }
6426
6548
  set(table) {
6427
- const parsed2 = (table.prefixes ?? []).map(parsePrefix);
6428
- const bad = (table.prefixes ?? []).find((_, i) => !parsed2[i]);
6549
+ const parsed3 = (table.prefixes ?? []).map(parsePrefix);
6550
+ const bad = (table.prefixes ?? []).find((_, i) => !parsed3[i]);
6429
6551
  if (bad !== void 0) throw new Error(`not an address prefix: ${bad}`);
6430
- this.table = parsed2;
6552
+ this.table = parsed3;
6431
6553
  this.exit = table.exit === true;
6432
6554
  }
6433
6555
  classify(host) {
@@ -6963,10 +7085,10 @@ var KernelSocket = class _KernelSocket {
6963
7085
  }
6964
7086
  };
6965
7087
  let made2;
6966
- const abandon = () => {
7088
+ const abandon2 = () => {
6967
7089
  if (!keeps(signal.reason)) view2.close();
6968
7090
  };
6969
- signal.addEventListener("abort", abandon, { once: true });
7091
+ signal.addEventListener("abort", abandon2, { once: true });
6970
7092
  try {
6971
7093
  made2 = await make(view2);
6972
7094
  } catch (err) {
@@ -6979,7 +7101,7 @@ var KernelSocket = class _KernelSocket {
6979
7101
  throw signal.aborted ? signal.reason : err;
6980
7102
  } finally {
6981
7103
  handshaking = false;
6982
- signal.removeEventListener("abort", abandon);
7104
+ signal.removeEventListener("abort", abandon2);
6983
7105
  }
6984
7106
  const plain3 = uplinkLink(made2.conn, (err) => {
6985
7107
  this.reset = err instanceof KernelError && err.code === "EPROTO" ? err : new KernelError("ECONNRESET");
@@ -8128,7 +8250,7 @@ var UserDb = class {
8128
8250
  joined(name2, extra);
8129
8251
  group.push({ name: name2, gid: uid, members: [] });
8130
8252
  passwd.push(row);
8131
- const fresh3 = !await this.fs.exists(home);
8253
+ const fresh4 = !await this.fs.exists(home);
8132
8254
  await this.fs.mkdir(home, { recursive: true });
8133
8255
  try {
8134
8256
  await this.provision(row, this.umaskFor(options), shared2);
@@ -8136,7 +8258,7 @@ var UserDb = class {
8136
8258
  await this.fs.mkdir("/etc", { recursive: true });
8137
8259
  await this.commit(formatPasswd(passwd), formatGroup(group));
8138
8260
  } catch (err) {
8139
- if (fresh3) await this.fs.rm(home, { recursive: true, force: true });
8261
+ if (fresh4) await this.fs.rm(home, { recursive: true, force: true });
8140
8262
  throw err;
8141
8263
  }
8142
8264
  remember();
@@ -8220,7 +8342,7 @@ var UserDb = class {
8220
8342
  };
8221
8343
 
8222
8344
  // src/client/protocol.ts
8223
- var PROTOCOL = [1, 17];
8345
+ var PROTOCOL = [1, 18];
8224
8346
  var FS_METHODS = [
8225
8347
  "readFile",
8226
8348
  "writeFile",
@@ -8349,7 +8471,7 @@ function signalOf(host) {
8349
8471
  }
8350
8472
  function dialFor(l, req, open2) {
8351
8473
  const socket = dialSocket(l.net, req.port, req.host);
8352
- const { port1, port2 } = new MessageChannel();
8474
+ const { port1, port2 } = l.ports();
8353
8475
  open2.set(
8354
8476
  req.id,
8355
8477
  serveSocket(socket, port1, () => open2.delete(req.id))
@@ -8442,7 +8564,8 @@ function cdpRegistry(send2, gone) {
8442
8564
  (request3, cdp) => send2({ cdpOpen: { ...request3, registration: req.id }, port: cdp }, [
8443
8565
  cdp
8444
8566
  ]),
8445
- gone
8567
+ gone,
8568
+ l.ports
8446
8569
  );
8447
8570
  registered.set(req.id, l.cdp.register(hook, req.runtime));
8448
8571
  return req.id;
@@ -8465,7 +8588,8 @@ function facadeRegistry(send2, gone) {
8465
8588
  (request3, facade) => send2({ facadeOpen: { ...request3, registration: req.id }, port: facade }, [
8466
8589
  facade
8467
8590
  ]),
8468
- gone
8591
+ gone,
8592
+ l.ports
8469
8593
  );
8470
8594
  registered.set(req.id, l.facades.register(req.name, hook));
8471
8595
  return req.id;
@@ -8480,8 +8604,10 @@ function hostRegistries(send2, gone, port) {
8480
8604
  const cdps = cdpRegistry(send2, gone);
8481
8605
  const facades = facadeRegistry(send2, gone);
8482
8606
  const requests = requestBinding(send2, port);
8607
+ const devices = deviceBinding(send2, port);
8483
8608
  return {
8484
8609
  requests,
8610
+ devices,
8485
8611
  answer(l, req) {
8486
8612
  if (req.op === "serve-cdp") return cdps.serve(l, req);
8487
8613
  if (req.op === "unserve-cdp") return cdps.drop(req.registration);
@@ -8490,6 +8616,7 @@ function hostRegistries(send2, gone, port) {
8490
8616
  },
8491
8617
  close() {
8492
8618
  requests.close();
8619
+ devices.close();
8493
8620
  cdps.close();
8494
8621
  facades.close();
8495
8622
  }
@@ -8603,6 +8730,28 @@ function answered(pending, req, reply, detach) {
8603
8730
  }
8604
8731
  );
8605
8732
  }
8733
+ async function helloRefused(host, hosts, message3) {
8734
+ return versionError(message3.protocol) ?? await hosts.requests.accept(host, message3) ?? await hosts.devices.accept(host, message3);
8735
+ }
8736
+ function deviceBinding(send2, port) {
8737
+ const asker = devicesAsker({ postMessage: (m, t) => send2(m, t) });
8738
+ let unbind;
8739
+ port.addEventListener("message", (event) => {
8740
+ const reply = devicesReplyOf(event.data);
8741
+ if (reply) asker.answer(reply);
8742
+ });
8743
+ return {
8744
+ async accept(host, hello) {
8745
+ if (!hello.devices) return void 0;
8746
+ if (!host.attachDevices || host.session === void 0)
8747
+ return "EPERM: this port may not answer device opens";
8748
+ const launcher = await host.launcher();
8749
+ unbind = launcher.devices.register(host.session, asker.hookFor(host.session));
8750
+ return void 0;
8751
+ },
8752
+ close: () => unbind?.()
8753
+ };
8754
+ }
8606
8755
  function serveClient(port, host) {
8607
8756
  let state = "new";
8608
8757
  let self;
@@ -8636,9 +8785,9 @@ function serveClient(port, host) {
8636
8785
  ended.resolve();
8637
8786
  }
8638
8787
  async function hello(message3) {
8639
- const refused4 = versionError(message3.protocol) ?? await hosts.requests.accept(host, message3);
8640
- if (refused4) {
8641
- send2({ hello: { protocol: PROTOCOL, error: refused4 } });
8788
+ const refused5 = await helloRefused(host, hosts, message3);
8789
+ if (refused5) {
8790
+ send2({ hello: { protocol: PROTOCOL, error: refused5 } });
8642
8791
  detach();
8643
8792
  return;
8644
8793
  }
@@ -8922,7 +9071,7 @@ function satisfies(version, range2) {
8922
9071
  }
8923
9072
 
8924
9073
  // src/version.ts
8925
- var KERNEL_VERSION = true ? "1.182.0" : "0.0.0-dev";
9074
+ var KERNEL_VERSION = true ? "1.184.0" : "0.0.0-dev";
8926
9075
  var OS_RELEASE = "6.0.0-slicc";
8927
9076
  function procVersion() {
8928
9077
  return `Linux version ${OS_RELEASE} (slicc-kernel ${KERNEL_VERSION}) #1 SMP PREEMPT_DYNAMIC
@@ -9214,10 +9363,10 @@ async function tierPackages(fs, physical, roots, bins, kernel, global) {
9214
9363
  const own = commandsOf(pkg, manifest);
9215
9364
  const named = new Set(own.map((command) => command.name));
9216
9365
  const extra = bins ? await binCommandsOf(physical, pkg, manifest, named) : [];
9217
- const refused4 = engineRefusal(manifest, kernel);
9366
+ const refused5 = engineRefusal(manifest, kernel);
9218
9367
  const name2 = pkg.slice(root.length + 1);
9219
9368
  const dependency = direct?.has(name2) === false;
9220
- const marks = { ...refused4 ? { refused: refused4 } : {}, ...dependency ? { dependency } : {} };
9369
+ const marks = { ...refused5 ? { refused: refused5 } : {}, ...dependency ? { dependency } : {} };
9221
9370
  out.push({
9222
9371
  name: name2,
9223
9372
  pkg,
@@ -9249,7 +9398,7 @@ function winners(tier) {
9249
9398
  }
9250
9399
  return out;
9251
9400
  }
9252
- async function scanCommands(fs, modules, binsFrom = Number.POSITIVE_INFINITY, kernel = KERNEL_VERSION, refused4, global = /* @__PURE__ */ new Set()) {
9401
+ async function scanCommands(fs, modules, binsFrom = Number.POSITIVE_INFINITY, kernel = KERNEL_VERSION, refused5, global = /* @__PURE__ */ new Set()) {
9253
9402
  const found = /* @__PURE__ */ new Map();
9254
9403
  const physical = physicalResolver(fs);
9255
9404
  const tiers = (typeof modules === "string" ? [modules] : modules).map(
@@ -9263,7 +9412,7 @@ async function scanCommands(fs, modules, binsFrom = Number.POSITIVE_INFINITY, ke
9263
9412
  const dependencies = [];
9264
9413
  for (const [index, roots] of tiers.entries()) {
9265
9414
  const tier = await tierPackages(fs, physical, roots, index >= binsFrom, kernel, global);
9266
- if (refused4) refused4.push(...tier.flatMap((entry) => entry.commands.filter((c) => c.refused)));
9415
+ if (refused5) refused5.push(...tier.flatMap((entry) => entry.commands.filter((c) => c.refused)));
9267
9416
  await take(tier.filter((entry) => !entry.dependency));
9268
9417
  dependencies.push(tier.filter((entry) => entry.dependency));
9269
9418
  }
@@ -9867,9 +10016,9 @@ var TAGS_VERSION = 1;
9867
10016
  async function readTags(fs) {
9868
10017
  const text = await fs.readFile(TAGS_PATH).catch(() => "");
9869
10018
  try {
9870
- const parsed2 = JSON.parse(text);
9871
- if (!parsed2 || typeof parsed2 !== "object") return {};
9872
- const { v: _, ...tables } = parsed2;
10019
+ const parsed3 = JSON.parse(text);
10020
+ if (!parsed3 || typeof parsed3 !== "object") return {};
10021
+ const { v: _, ...tables } = parsed3;
9873
10022
  return tables;
9874
10023
  } catch {
9875
10024
  return {};
@@ -9939,27 +10088,27 @@ var Crontabs = class {
9939
10088
  const json5 = JSON.stringify({ v: TAGS_VERSION, ...kept });
9940
10089
  if (json5 === await fs.readFile(TAGS_PATH).catch(() => "")) return;
9941
10090
  const owner = owners ? { uid: 0, gid: 0, mode: 384 } : void 0;
9942
- const fresh3 = `${TAGS_PATH}.${crypto.randomUUID()}.new`;
9943
- await fs.writeFile(fresh3, json5, owner);
9944
- await fs.rename(fresh3, TAGS_PATH);
10091
+ const fresh4 = `${TAGS_PATH}.${crypto.randomUUID()}.new`;
10092
+ await fs.writeFile(fresh4, json5, owner);
10093
+ await fs.rename(fresh4, TAGS_PATH);
9945
10094
  }
9946
10095
  async install(path, target, text, caller) {
9947
10096
  if (text.length > CRONTAB_MAX) return { error: "crontab: the table is too long" };
9948
10097
  const { errors } = parseCrontab(text, path);
9949
10098
  if (errors.length > 0) {
9950
- const lines2 = errors.map(({ line, message: message3 }) => `"-":${line}: ${message3}`);
9951
- return { error: ["crontab: errors in crontab file, cannot install", ...lines2].join("\n") };
10099
+ const lines3 = errors.map(({ line, message: message3 }) => `"-":${line}: ${message3}`);
10100
+ return { error: ["crontab: errors in crontab file, cannot install", ...lines3].join("\n") };
9952
10101
  }
9953
10102
  const { fs, owners } = this.o;
9954
10103
  if (!await fs.exists(SPOOL_DIR)) {
9955
10104
  await fs.mkdir(SPOOL_DIR, { recursive: true });
9956
10105
  if (owners) await fs.chown?.(SPOOL_DIR, { uid: 0, gid: 0, mode: 448, follow: false });
9957
10106
  }
9958
- const fresh3 = `${SPOOL_DIR}/.${target.name}.${crypto.randomUUID()}.new`;
10107
+ const fresh4 = `${SPOOL_DIR}/.${target.name}.${crypto.randomUUID()}.new`;
9959
10108
  const owner = owners ? { uid: target.uid, gid: target.gid, mode: 384 } : void 0;
9960
10109
  await this.retag(path, text, caller);
9961
- await fs.writeFile(fresh3, text, owner);
9962
- await fs.rename(fresh3, path);
10110
+ await fs.writeFile(fresh4, text, owner);
10111
+ await fs.rename(fresh4, path);
9963
10112
  return { text: "" };
9964
10113
  }
9965
10114
  };
@@ -10280,15 +10429,15 @@ var UnlinkedKeeper = class {
10280
10429
  const releases = [];
10281
10430
  const take = async () => {
10282
10431
  for (; ; ) {
10283
- const fresh3 = [...this.heldWithin(target).keys()].filter((path) => !paths.includes(path));
10284
- if (fresh3.length === 0) return;
10285
- fresh3.sort();
10286
- if (paths.some((path) => path > fresh3[0])) {
10432
+ const fresh4 = [...this.heldWithin(target).keys()].filter((path) => !paths.includes(path));
10433
+ if (fresh4.length === 0) return;
10434
+ fresh4.sort();
10435
+ if (paths.some((path) => path > fresh4[0])) {
10287
10436
  for (const release of releases.splice(0)) release();
10288
- fresh3.push(...paths.splice(0));
10289
- fresh3.sort();
10437
+ fresh4.push(...paths.splice(0));
10438
+ fresh4.sort();
10290
10439
  }
10291
- for (const path of fresh3) {
10440
+ for (const path of fresh4) {
10292
10441
  paths.push(path);
10293
10442
  releases.push(await this.gate.acquire(path));
10294
10443
  }
@@ -10684,10 +10833,10 @@ var Output = class {
10684
10833
  };
10685
10834
  function readStamp(text) {
10686
10835
  try {
10687
- const parsed2 = JSON.parse(text ?? "");
10688
- const jobs = parsed2.jobs && typeof parsed2.jobs === "object" ? parsed2.jobs : {};
10689
- const reboot = parsed2.reboot && typeof parsed2.reboot === "object" ? parsed2.reboot : {};
10690
- const when = parsed2.when && typeof parsed2.when === "object" ? parsed2.when : {};
10836
+ const parsed3 = JSON.parse(text ?? "");
10837
+ const jobs = parsed3.jobs && typeof parsed3.jobs === "object" ? parsed3.jobs : {};
10838
+ const reboot = parsed3.reboot && typeof parsed3.reboot === "object" ? parsed3.reboot : {};
10839
+ const when = parsed3.when && typeof parsed3.when === "object" ? parsed3.when : {};
10691
10840
  return { jobs: { ...jobs }, reboot: { ...reboot }, when: { ...when } };
10692
10841
  } catch {
10693
10842
  return { jobs: {}, reboot: {}, when: {} };
@@ -10807,10 +10956,10 @@ var CronService = class {
10807
10956
  const text = JSON.stringify(stamp);
10808
10957
  const old = await fs.readFile(STAMP_PATH).catch(() => void 0);
10809
10958
  if (old === text || old === void 0 && text === EMPTY_STAMP) return;
10810
- const fresh3 = `${STAMP_PATH}.new`;
10959
+ const fresh4 = `${STAMP_PATH}.new`;
10811
10960
  const owner = owners ? { uid: 0, gid: 0, mode: 384 } : void 0;
10812
- await fs.writeFile(fresh3, text, owner);
10813
- await fs.rename(fresh3, STAMP_PATH);
10961
+ await fs.writeFile(fresh4, text, owner);
10962
+ await fs.rename(fresh4, STAMP_PATH);
10814
10963
  }
10815
10964
  async load() {
10816
10965
  const { fs } = this.host;
@@ -10863,10 +11012,10 @@ var CronService = class {
10863
11012
  await this.once(path, text, errors);
10864
11013
  return table;
10865
11014
  }
10866
- async once(path, version, lines2) {
11015
+ async once(path, version, lines3) {
10867
11016
  if (this.reported.get(path) === version) return;
10868
11017
  this.reported.set(path, version);
10869
- for (const line of lines2) await this.error(line);
11018
+ for (const line of lines3) await this.error(line);
10870
11019
  }
10871
11020
  async error(line) {
10872
11021
  if (this.stopping.signal.aborted) return;
@@ -11100,8 +11249,8 @@ function canonicalHost2(host) {
11100
11249
  function localV4(a, b) {
11101
11250
  return a === 127 || a === 0 || a === 169 && b === 254;
11102
11251
  }
11103
- function hextets(address) {
11104
- const [head, tail2, extra] = address.split("::");
11252
+ function hextets(address2) {
11253
+ const [head, tail2, extra] = address2.split("::");
11105
11254
  if (extra !== void 0) return void 0;
11106
11255
  const part = (text) => text ? text.split(":").map((h) => Number.parseInt(h, 16)) : [];
11107
11256
  const front = part(head);
@@ -11109,8 +11258,8 @@ function hextets(address) {
11109
11258
  const groups = tail2 === void 0 ? front : [...front, ...new Array(8 - front.length - back.length).fill(0), ...back];
11110
11259
  return groups.length === 8 && groups.every((g) => g >= 0 && g <= 65535) ? groups : void 0;
11111
11260
  }
11112
- function localV6(address) {
11113
- const g = hextets(address);
11261
+ function localV6(address2) {
11262
+ const g = hextets(address2);
11114
11263
  if (!g) return true;
11115
11264
  if ((g[0] & 65472) === 65152) return true;
11116
11265
  const zeroPrefix = g.slice(0, 5).every((x) => x === 0);
@@ -11483,8 +11632,8 @@ var RealmProxy = class {
11483
11632
  }
11484
11633
  async connect(conn, incoming, req, idle2) {
11485
11634
  const target = tunnelTarget(req);
11486
- const refused4 = target.port === 443 ? await this.tunnelReady(target) : void 0;
11487
- if (refused4) throw refused4;
11635
+ const refused5 = target.port === 443 ? await this.tunnelReady(target) : void 0;
11636
+ if (refused5) throw refused5;
11488
11637
  await conn.write(latin1Bytes("HTTP/1.1 200 Connection Established\r\n\r\n"), this.stop.signal);
11489
11638
  try {
11490
11639
  const first = await incoming.peek(this.stop.signal);
@@ -11928,15 +12077,15 @@ async function followLinks(fs, path) {
11928
12077
  }
11929
12078
  var NOBODY = { ruid: -1, euid: -1, suid: -1, rgid: -1, egid: -1, sgid: -1, groups: [] };
11930
12079
  var EMPTY2 = new Uint8Array(0);
11931
- function quiet(promise) {
12080
+ function quiet2(promise) {
11932
12081
  return promise.catch(() => void 0);
11933
12082
  }
11934
12083
  async function readsAs2(fs, cred, target) {
11935
- const walked = await quiet(access(fs, cred, target, R_OK, { directory: false }));
12084
+ const walked = await quiet2(access(fs, cred, target, R_OK, { directory: false }));
11936
12085
  return walked !== void 0 && walked.denied === void 0 && !walked.missing;
11937
12086
  }
11938
12087
  async function shownTarget(fs, target) {
11939
- const st = await quiet(fs.stat(target));
12088
+ const st = await quiet2(fs.stat(target));
11940
12089
  return st?.isFile && await readsAs2(fs, NOBODY, target) ? st : void 0;
11941
12090
  }
11942
12091
  async function madeFor(owner, virtual) {
@@ -12259,10 +12408,10 @@ var FreshModules = class {
12259
12408
  this.fresh.set(key, { umask: mask, pid, added: 0, setup: mask !== DEFAULT_UMASK });
12260
12409
  }
12261
12410
  forget(pid) {
12262
- for (const [path, fresh3] of this.fresh) if (fresh3.pid === pid) this.fresh.delete(path);
12411
+ for (const [path, fresh4] of this.fresh) if (fresh4.pid === pid) this.fresh.delete(path);
12263
12412
  }
12264
- drop(fresh3) {
12265
- for (const [key, note] of [...this.fresh]) if (note === fresh3) this.fresh.delete(key);
12413
+ drop(fresh4) {
12414
+ for (const [key, note] of [...this.fresh]) if (note === fresh4) this.fresh.delete(key);
12266
12415
  }
12267
12416
  moved(from, to) {
12268
12417
  const source = normalizePath(from);
@@ -12271,10 +12420,10 @@ var FreshModules = class {
12271
12420
  for (const key of [...this.fresh.keys()]) {
12272
12421
  if (key === target || within6(key, target)) this.fresh.delete(key);
12273
12422
  }
12274
- for (const [key, fresh3] of [...this.fresh]) {
12423
+ for (const [key, fresh4] of [...this.fresh]) {
12275
12424
  if (key !== source && !within6(key, source)) continue;
12276
12425
  this.fresh.delete(key);
12277
- this.fresh.set(target + key.slice(source.length), fresh3);
12426
+ this.fresh.set(target + key.slice(source.length), fresh4);
12278
12427
  }
12279
12428
  }
12280
12429
  wrap(fs) {
@@ -12284,15 +12433,15 @@ var FreshModules = class {
12284
12433
  };
12285
12434
  const decide = async (given, known) => {
12286
12435
  const path = normalizePath(given);
12287
- const fresh3 = this.fresh.get(path);
12288
- if (!fresh3) return;
12436
+ const fresh4 = this.fresh.get(path);
12437
+ if (!fresh4) return;
12289
12438
  const bytes = known && known.length >= MAGIC.length ? known : await head(path);
12290
- const want = isModule(bytes) ? 73 & ~fresh3.umask : 0;
12291
- fresh3.setup = false;
12292
- if (want === fresh3.added) return;
12439
+ const want2 = isModule(bytes) ? 73 & ~fresh4.umask : 0;
12440
+ fresh4.setup = false;
12441
+ if (want2 === fresh4.added) return;
12293
12442
  const mode = (await fs.stat(path)).mode & 4095;
12294
- await fs.chmod(path, mode & ~fresh3.added | want);
12295
- fresh3.added = want;
12443
+ await fs.chmod(path, mode & ~fresh4.added | want2);
12444
+ fresh4.added = want2;
12296
12445
  };
12297
12446
  const overrides = {
12298
12447
  writeFile: async (path, content, owner) => {
@@ -12305,9 +12454,9 @@ var FreshModules = class {
12305
12454
  }
12306
12455
  },
12307
12456
  chmod: async (path, mode) => {
12308
- const fresh3 = this.fresh.get(normalizePath(path));
12309
- if (fresh3?.setup && (mode & 4095) === (438 & ~fresh3.umask)) fresh3.setup = false;
12310
- else if (fresh3) this.drop(fresh3);
12457
+ const fresh4 = this.fresh.get(normalizePath(path));
12458
+ if (fresh4?.setup && (mode & 4095) === (438 & ~fresh4.umask)) fresh4.setup = false;
12459
+ else if (fresh4) this.drop(fresh4);
12311
12460
  await fs.chmod(path, mode);
12312
12461
  },
12313
12462
  rm: async (path, options) => {
@@ -12324,16 +12473,16 @@ var FreshModules = class {
12324
12473
  link: async (from, to, follow2) => {
12325
12474
  await fs.link(from, to, follow2);
12326
12475
  const source = follow2 && fs.realpath ? await fs.realpath(from, true).catch(() => from) : from;
12327
- const fresh3 = this.fresh.get(normalizePath(source));
12328
- if (fresh3) this.fresh.set(normalizePath(to), fresh3);
12476
+ const fresh4 = this.fresh.get(normalizePath(source));
12477
+ if (fresh4) this.fresh.set(normalizePath(to), fresh4);
12329
12478
  }
12330
12479
  };
12331
12480
  const { append } = fs;
12332
12481
  if (append) {
12333
12482
  overrides.append = async (path, bytes, options) => {
12334
- const fresh3 = this.fresh.has(normalizePath(path));
12483
+ const fresh4 = this.fresh.has(normalizePath(path));
12335
12484
  const end = await append.call(fs, path, bytes, options);
12336
- if (fresh3 && end - bytes.length < MAGIC.length) await decide(path);
12485
+ if (fresh4 && end - bytes.length < MAGIC.length) await decide(path);
12337
12486
  return end;
12338
12487
  };
12339
12488
  }
@@ -12660,7 +12809,7 @@ var FsWatchers = class {
12660
12809
  };
12661
12810
  const content = (run2, types) => async (...args) => {
12662
12811
  const at = normalizePath(args[0]);
12663
- const fresh3 = this.covers(at) && !await fs.exists(at).catch(() => true);
12812
+ const fresh4 = this.covers(at) && !await fs.exists(at).catch(() => true);
12664
12813
  let done5 = false;
12665
12814
  try {
12666
12815
  await run2(...args);
@@ -12669,11 +12818,11 @@ var FsWatchers = class {
12669
12818
  const real = await realOf(at);
12670
12819
  const paths = real === at ? [at] : [at, real];
12671
12820
  this.report(paths);
12672
- if (done5) for (const type of types(fresh3, args)) this.emit(type, paths);
12821
+ if (done5) for (const type of types(fresh4, args)) this.emit(type, paths);
12673
12822
  }
12674
12823
  };
12675
- const written2 = (fresh3) => fresh3 ? ["rename", "change"] : ["change"];
12676
- const overwritten = (fresh3, args) => fresh3 || args[1].length === 0 ? written2(fresh3) : ["change", "change"];
12824
+ const written2 = (fresh4) => fresh4 ? ["rename", "change"] : ["change"];
12825
+ const overwritten = (fresh4, args) => fresh4 || args[1].length === 0 ? written2(fresh4) : ["change", "change"];
12677
12826
  const reshaping = (run2) => async (...args) => {
12678
12827
  this.reshaped();
12679
12828
  try {
@@ -12706,14 +12855,14 @@ var FsWatchers = class {
12706
12855
  if (created4.length > 0 || !await fs.exists(ancestor)) created4.push(ancestor);
12707
12856
  }
12708
12857
  }
12709
- const fresh3 = !options?.recursive || this.typed.size > 0 && !await fs.exists(path);
12858
+ const fresh4 = !options?.recursive || this.typed.size > 0 && !await fs.exists(path);
12710
12859
  let done5 = false;
12711
12860
  try {
12712
12861
  await fs.mkdir(path, options);
12713
12862
  done5 = true;
12714
12863
  } finally {
12715
12864
  this.report([...created4, path]);
12716
- if (done5) this.emit("rename", fresh3 ? [...created4, path] : created4);
12865
+ if (done5) this.emit("rename", fresh4 ? [...created4, path] : created4);
12717
12866
  }
12718
12867
  },
12719
12868
  rm: reshaping(async (path, options) => {
@@ -12977,12 +13126,12 @@ var ChildTable = class {
12977
13126
  async nextChange(candidates, flags2, interrupt) {
12978
13127
  let wake;
12979
13128
  const stateChange = new Promise((resolve2) => wake = resolve2);
12980
- const watching = flags2.untraced || flags2.continued;
12981
- if (watching && wake) this.stateChanged.push(wake);
13129
+ const watching2 = flags2.untraced || flags2.continued;
13130
+ if (watching2 && wake) this.stateChanged.push(wake);
12982
13131
  try {
12983
13132
  await Promise.race([
12984
13133
  ...candidates.map(([, child]) => child.exited),
12985
- ...watching ? [stateChange] : [],
13134
+ ...watching2 ? [stateChange] : [],
12986
13135
  interrupt
12987
13136
  ]);
12988
13137
  } finally {
@@ -13223,15 +13372,15 @@ function embedderFailure(err) {
13223
13372
  return new KernelError(ERRNOS[String(name2)] ?? "EIO", lineOf2(err));
13224
13373
  }
13225
13374
  function headerOf(bytes) {
13226
- let parsed2;
13375
+ let parsed3;
13227
13376
  try {
13228
- parsed2 = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
13377
+ parsed3 = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
13229
13378
  } catch {
13230
13379
  throw new KernelError("EINVAL", "the request header is not JSON");
13231
13380
  }
13232
- if (typeof parsed2 !== "object" || parsed2 === null || Array.isArray(parsed2))
13381
+ if (typeof parsed3 !== "object" || parsed3 === null || Array.isArray(parsed3))
13233
13382
  throw new KernelError("EINVAL", "the request header is not an object");
13234
- const { kind, ...options } = parsed2;
13383
+ const { kind, ...options } = parsed3;
13235
13384
  if (typeof kind !== "string" || kind.length > 64 || !KIND.test(kind))
13236
13385
  throw new KernelError("EINVAL", "the request has no valid kind");
13237
13386
  return { kind, options };
@@ -13658,6 +13807,966 @@ var EmbedderBroker = class {
13658
13807
  }
13659
13808
  };
13660
13809
 
13810
+ // src/kernel/serial-ioctl.ts
13811
+ var IOCTL = {
13812
+ TCGETS: 21505,
13813
+ TCSETS: 21506,
13814
+ TCSETSW: 21507,
13815
+ TCSETSF: 21508,
13816
+ TCSBRK: 21513,
13817
+ TCFLSH: 21515,
13818
+ TIOCEXCL: 21516,
13819
+ TIOCNXCL: 21517,
13820
+ TIOCSCTTY: 21518,
13821
+ TIOCGPGRP: 21519,
13822
+ TIOCSPGRP: 21520,
13823
+ TIOCOUTQ: 21521,
13824
+ TIOCGWINSZ: 21523,
13825
+ TIOCSWINSZ: 21524,
13826
+ TIOCMGET: 21525,
13827
+ TIOCMBIS: 21526,
13828
+ TIOCMBIC: 21527,
13829
+ TIOCMSET: 21528,
13830
+ FIONREAD: 21531,
13831
+ TIOCNOTTY: 21538,
13832
+ TCSBRKP: 21541,
13833
+ TIOCSBRK: 21543,
13834
+ TIOCCBRK: 21544,
13835
+ TCGETS2: 2150388778,
13836
+ TCSETS2: 1076646955,
13837
+ TCSETSW2: 1076646956,
13838
+ TCSETSF2: 1076646957
13839
+ };
13840
+ var TERMIOS_GETS = /* @__PURE__ */ new Set([IOCTL.TCGETS, IOCTL.TCGETS2]);
13841
+ var TERMIOS_SETS = /* @__PURE__ */ new Set([
13842
+ IOCTL.TCSETS,
13843
+ IOCTL.TCSETSW,
13844
+ IOCTL.TCSETSF,
13845
+ IOCTL.TCSETS2,
13846
+ IOCTL.TCSETSW2,
13847
+ IOCTL.TCSETSF2
13848
+ ]);
13849
+ var INT_OUT = /* @__PURE__ */ new Set([
13850
+ IOCTL.TIOCMGET,
13851
+ IOCTL.FIONREAD,
13852
+ IOCTL.TIOCOUTQ
13853
+ ]);
13854
+ var INT_IN = /* @__PURE__ */ new Set([
13855
+ IOCTL.TIOCMBIS,
13856
+ IOCTL.TIOCMBIC,
13857
+ IOCTL.TIOCMSET
13858
+ ]);
13859
+ var INT_ARG = /* @__PURE__ */ new Set([IOCTL.TCSBRK, IOCTL.TCSBRKP, IOCTL.TCFLSH]);
13860
+ var TIOCM = {
13861
+ DTR: 2,
13862
+ RTS: 4,
13863
+ CTS: 32,
13864
+ CD: 64,
13865
+ RI: 128,
13866
+ DSR: 256
13867
+ };
13868
+ var CBAUD = 4111;
13869
+ var BOTHER = 4096;
13870
+ var IBSHIFT = 16;
13871
+ var CSIZE = 48;
13872
+ var CSTOPB = 64;
13873
+ var PARENB = 256;
13874
+ var PARODD = 512;
13875
+ var CRTSCTS = 2147483648;
13876
+ var SPEEDS = [
13877
+ 0,
13878
+ 50,
13879
+ 75,
13880
+ 110,
13881
+ 134,
13882
+ 150,
13883
+ 200,
13884
+ 300,
13885
+ 600,
13886
+ 1200,
13887
+ 1800,
13888
+ 2400,
13889
+ 4800,
13890
+ 9600,
13891
+ 19200,
13892
+ 38400
13893
+ ];
13894
+ var FAST = [
13895
+ 0,
13896
+ 57600,
13897
+ 115200,
13898
+ 230400,
13899
+ 460800,
13900
+ 5e5,
13901
+ 576e3,
13902
+ 921600,
13903
+ 1e6,
13904
+ 1152e3,
13905
+ 15e5,
13906
+ 2e6,
13907
+ 25e5,
13908
+ 3e6,
13909
+ 35e5,
13910
+ 4e6
13911
+ ];
13912
+ function speedOf(code) {
13913
+ if (code === BOTHER) return void 0;
13914
+ return code & BOTHER ? FAST[code & 15] : SPEEDS[code & 15];
13915
+ }
13916
+ function speedsOf(termios, current, extended) {
13917
+ const out = termios.c_cflag & CBAUD;
13918
+ const ospeed = speedOf(out) ?? (extended ? (termios.c_ospeed ?? current.ospeed) >>> 0 : current.ospeed);
13919
+ const inCode = termios.c_cflag >>> IBSHIFT & CBAUD;
13920
+ if (inCode === 0) return { ispeed: ospeed, ospeed };
13921
+ const ispeed = speedOf(inCode) ?? (extended ? (termios.c_ispeed ?? current.ispeed) >>> 0 : current.ispeed);
13922
+ return { ispeed, ospeed };
13923
+ }
13924
+ function settingsOf(cflag, baudRate) {
13925
+ return {
13926
+ baudRate,
13927
+ dataBits: 5 + ((cflag & CSIZE) >> 4),
13928
+ parity: cflag & PARENB ? cflag & PARODD ? "odd" : "even" : "none",
13929
+ stopBits: cflag & CSTOPB ? 2 : 1,
13930
+ flowControl: cflag & CRTSCTS ? "hardware" : "none"
13931
+ };
13932
+ }
13933
+ function sameSettings(a, b) {
13934
+ return a.baudRate === b.baudRate && a.dataBits === b.dataBits && a.parity === b.parity && a.stopBits === b.stopBits && a.flowControl === b.flowControl;
13935
+ }
13936
+ var SERIAL_CFLAG = 13 | 48 | 128 | 1024 | 2048;
13937
+ var SERIAL_LFLAG = 16 | 32 | 512 | 2048;
13938
+ var SERIAL_OFLAG = 4;
13939
+
13940
+ // src/kernel/tty.ts
13941
+ var ICRNL = 256;
13942
+ var IUTF8 = 16384;
13943
+ var OPOST = 1;
13944
+ var ONLCR = 4;
13945
+ var ISIG = 1;
13946
+ var ICANON = 2;
13947
+ var ECHO = 8;
13948
+ var ECHOE = 16;
13949
+ var ECHOCTL = 512;
13950
+ var NOFLSH = 128;
13951
+ var IEXTEN = 32768;
13952
+ var VINTR = 0;
13953
+ var VQUIT = 1;
13954
+ var VERASE = 2;
13955
+ var VKILL = 3;
13956
+ var VEOF = 4;
13957
+ var VSUSP = 10;
13958
+ var VWERASE = 14;
13959
+ function defaultTermios() {
13960
+ const cCc = new Array(32).fill(0);
13961
+ Object.assign(cCc, { [VINTR]: 3, [VQUIT]: 28, [VERASE]: 127, [VKILL]: 21 });
13962
+ Object.assign(cCc, { [VEOF]: 4, 6: 1, 8: 17, 9: 19, [VSUSP]: 26 });
13963
+ Object.assign(cCc, { 12: 18, 13: 15, [VWERASE]: 23, 15: 22 });
13964
+ return {
13965
+ c_iflag: ICRNL | 1024 | 8192 | IUTF8,
13966
+ c_oflag: OPOST | ONLCR,
13967
+ c_cflag: 15 | 48 | 128,
13968
+ c_lflag: ISIG | ICANON | ECHO | ECHOE | 32 | ECHOCTL | 2048 | IEXTEN,
13969
+ c_cc: cCc
13970
+ };
13971
+ }
13972
+ var encoder3 = new TextEncoder();
13973
+ function isContinuation(byte) {
13974
+ return (byte & 192) === 128;
13975
+ }
13976
+ var KernelTty = class {
13977
+ termios = defaultTermios();
13978
+ cols = 80;
13979
+ rows = 24;
13980
+ readable = [];
13981
+ line = [];
13982
+ waiters = [];
13983
+ hungUp = false;
13984
+ name;
13985
+ owner;
13986
+ onRead;
13987
+ readers = 0;
13988
+ screen;
13989
+ signal;
13990
+ constructor(screen, signal) {
13991
+ this.screen = screen;
13992
+ this.signal = signal;
13993
+ }
13994
+ receive(bytes) {
13995
+ const { c_iflag, c_lflag } = this.termios;
13996
+ if (!(c_iflag & ICRNL) && !(c_lflag & (ISIG | ICANON | ECHO))) {
13997
+ if (bytes.length > 0) this.readable.push(bytes.slice());
13998
+ } else for (const byte of bytes) this.key(byte);
13999
+ this.wake();
14000
+ }
14001
+ resize(cols, rows) {
14002
+ if (cols === this.cols && rows === this.rows) return;
14003
+ this.setSize(cols, rows);
14004
+ this.signal(SIG.WINCH);
14005
+ }
14006
+ hangup() {
14007
+ this.hungUp = true;
14008
+ this.wake();
14009
+ }
14010
+ signalHangup() {
14011
+ this.signal(SIG.HUP);
14012
+ }
14013
+ setSize(cols, rows) {
14014
+ this.cols = cols;
14015
+ this.rows = rows;
14016
+ }
14017
+ tcgets() {
14018
+ return { ...this.termios, c_cc: [...this.termios.c_cc] };
14019
+ }
14020
+ tcsets(termios, flush = false) {
14021
+ const wasCanonical = this.canonical;
14022
+ this.termios = { ...termios, c_cc: [...termios.c_cc] };
14023
+ if (flush) {
14024
+ this.line = [];
14025
+ this.readable = [];
14026
+ }
14027
+ if (wasCanonical && !this.canonical && this.line.length > 0) {
14028
+ this.readable.push(Uint8Array.from(this.line));
14029
+ this.line = [];
14030
+ this.wake();
14031
+ }
14032
+ }
14033
+ winsize() {
14034
+ return [this.rows, this.cols];
14035
+ }
14036
+ file() {
14037
+ return new OpenFile({
14038
+ read: (max, signal) => this.read(max, signal),
14039
+ write: async (bytes) => {
14040
+ if (this.hungUp) throw new KernelError("EIO");
14041
+ this.output(bytes);
14042
+ return bytes.length;
14043
+ },
14044
+ poll: () => ({
14045
+ readable: this.readable.length > 0 || this.hungUp,
14046
+ writable: true,
14047
+ hangup: this.hungUp,
14048
+ nread: this.readable.reduce((n, chunk2) => n + (chunk2?.length ?? 0), 0)
14049
+ }),
14050
+ changed: (signal) => this.changed(signal),
14051
+ close: () => {
14052
+ },
14053
+ tty: this
14054
+ });
14055
+ }
14056
+ get canonical() {
14057
+ return (this.termios.c_lflag & ICANON) !== 0;
14058
+ }
14059
+ cc(slot2) {
14060
+ return this.termios.c_cc[slot2] ?? 0;
14061
+ }
14062
+ key(input) {
14063
+ const { c_iflag, c_lflag } = this.termios;
14064
+ const byte = input === 13 && c_iflag & ICRNL ? 10 : input;
14065
+ if (c_lflag & ISIG && this.signalKey(byte)) return;
14066
+ if (!this.canonical) {
14067
+ this.readable.push(Uint8Array.of(byte));
14068
+ if (c_lflag & ECHO) this.echo(byte);
14069
+ return;
14070
+ }
14071
+ this.edit(byte);
14072
+ }
14073
+ signalKey(byte) {
14074
+ const sig = byte === this.cc(VINTR) ? SIG.INT : byte === this.cc(VQUIT) ? SIG.QUIT : byte === this.cc(VSUSP) ? SIG.TSTP : 0;
14075
+ if (!sig || byte === 0) return false;
14076
+ if (this.termios.c_lflag & ECHO) this.echo(byte);
14077
+ if (!(this.termios.c_lflag & NOFLSH)) {
14078
+ this.line = [];
14079
+ this.readable = [];
14080
+ }
14081
+ this.signal(sig);
14082
+ return true;
14083
+ }
14084
+ edit(byte) {
14085
+ const echo = (this.termios.c_lflag & ECHO) !== 0;
14086
+ if (byte === this.cc(VERASE) || byte === 8) {
14087
+ this.rubOut(this.lastCharLength());
14088
+ } else if (byte === this.cc(VKILL)) {
14089
+ this.rubOut(this.line.length);
14090
+ } else if (byte === this.cc(VWERASE)) {
14091
+ this.rubOut(this.lastWordLength());
14092
+ } else if (byte === this.cc(VEOF)) {
14093
+ this.readable.push(this.line.length > 0 ? Uint8Array.from(this.line) : null);
14094
+ this.line = [];
14095
+ } else if (byte === 10) {
14096
+ this.line.push(byte);
14097
+ this.readable.push(Uint8Array.from(this.line));
14098
+ this.line = [];
14099
+ if (echo) this.output(encoder3.encode("\n"));
14100
+ } else {
14101
+ this.line.push(byte);
14102
+ if (echo) this.echo(byte);
14103
+ }
14104
+ }
14105
+ lastWordLength() {
14106
+ let end = this.line.length;
14107
+ while (end > 0 && this.line[end - 1] === 32) end--;
14108
+ while (end > 0 && this.line[end - 1] !== 32) end--;
14109
+ return this.line.length - end;
14110
+ }
14111
+ lastCharLength() {
14112
+ const { line } = this;
14113
+ let n = Math.min(1, line.length);
14114
+ if (this.termios.c_iflag & IUTF8) {
14115
+ while (n < line.length && isContinuation(line[line.length - n] ?? 0)) n++;
14116
+ }
14117
+ return n;
14118
+ }
14119
+ rubOut(n) {
14120
+ const dropped2 = this.line.splice(this.line.length - n, n);
14121
+ const utf83 = (this.termios.c_iflag & IUTF8) !== 0;
14122
+ const cells = utf83 ? dropped2.filter((b) => !isContinuation(b)).length : dropped2.length;
14123
+ if (cells > 0 && this.termios.c_lflag & ECHO) {
14124
+ this.output(encoder3.encode("\b \b".repeat(cells)), false);
14125
+ }
14126
+ }
14127
+ echo(byte) {
14128
+ if (byte < 32 && byte !== 10 && byte !== 9 && this.termios.c_lflag & ECHOCTL) {
14129
+ this.output(Uint8Array.of(94, byte + 64), false);
14130
+ return;
14131
+ }
14132
+ this.output(Uint8Array.of(byte));
14133
+ }
14134
+ output(bytes, translate2 = true) {
14135
+ const { c_oflag } = this.termios;
14136
+ if (!translate2 || !(c_oflag & OPOST && c_oflag & ONLCR) || !bytes.includes(10)) {
14137
+ this.screen.write(bytes);
14138
+ return;
14139
+ }
14140
+ const out = [];
14141
+ for (const byte of bytes) {
14142
+ if (byte === 10) out.push(13);
14143
+ out.push(byte);
14144
+ }
14145
+ this.screen.write(Uint8Array.from(out));
14146
+ }
14147
+ get reading() {
14148
+ return this.readers > 0;
14149
+ }
14150
+ async read(max, signal) {
14151
+ this.onRead?.();
14152
+ this.readers++;
14153
+ try {
14154
+ return await this.take(max, signal);
14155
+ } finally {
14156
+ this.readers--;
14157
+ }
14158
+ }
14159
+ async take(max, signal) {
14160
+ while (this.readable.length === 0) {
14161
+ if (this.hungUp) return new Uint8Array(0);
14162
+ await this.changed(signal);
14163
+ }
14164
+ const head = this.readable[0];
14165
+ if (head === null) {
14166
+ this.readable.shift();
14167
+ return new Uint8Array(0);
14168
+ }
14169
+ if (head === void 0) return new Uint8Array(0);
14170
+ const chunks = [];
14171
+ let n = 0;
14172
+ while (this.readable.length > 0 && n < max) {
14173
+ const next3 = this.readable[0];
14174
+ if (next3 === null || next3 === void 0) break;
14175
+ const take = next3.subarray(0, max - n);
14176
+ chunks.push(take);
14177
+ n += take.length;
14178
+ if (take.length < next3.length) this.readable[0] = next3.subarray(take.length);
14179
+ else this.readable.shift();
14180
+ if (this.canonical) break;
14181
+ }
14182
+ const out = new Uint8Array(n);
14183
+ let at = 0;
14184
+ for (const chunk2 of chunks) {
14185
+ out.set(chunk2, at);
14186
+ at += chunk2.length;
14187
+ }
14188
+ return out;
14189
+ }
14190
+ changed(signal) {
14191
+ if (signal?.aborted) return Promise.reject(new KernelError("EINTR"));
14192
+ return new Promise((resolve2, reject) => {
14193
+ const onAbort = () => {
14194
+ this.waiters = this.waiters.filter((w) => w !== waiter);
14195
+ reject(new KernelError("EINTR"));
14196
+ };
14197
+ const waiter = () => {
14198
+ signal?.removeEventListener("abort", onAbort);
14199
+ resolve2();
14200
+ };
14201
+ this.waiters.push(waiter);
14202
+ signal?.addEventListener("abort", onAbort, { once: true });
14203
+ });
14204
+ }
14205
+ wake() {
14206
+ const waiters = this.waiters;
14207
+ this.waiters = [];
14208
+ for (const resolve2 of waiters) resolve2();
14209
+ }
14210
+ };
14211
+
14212
+ // src/kernel/devices.ts
14213
+ var DEVICE_NAME = /^tty(USB|ACM)(\d{1,3})$/;
14214
+ var BY_ID = "/dev/serial/by-id";
14215
+ var LINK_NAME = /^[A-Za-z0-9._:+@=,-]{1,255}$/;
14216
+ var MAJORS = { USB: 188, ACM: 166 };
14217
+ var HIGH_WATER = 64 * 1024;
14218
+ var CLOSING_WAIT_MS = 3e4;
14219
+ var BREAK_MS = 250;
14220
+ var MAX_ID2 = 4294967294;
14221
+ var DEFAULT_SETTINGS = settingsOf(SERIAL_CFLAG, 9600);
14222
+ function refused2(code, text) {
14223
+ return Object.assign(new Error(`${code}: ${text}`), { code });
14224
+ }
14225
+ function invalid(what) {
14226
+ return refused2("EINVAL", what);
14227
+ }
14228
+ function nodePath(path) {
14229
+ if (typeof path !== "string") throw invalid("path must be a string");
14230
+ const name2 = path.startsWith("/dev/") ? path.slice(5) : path;
14231
+ const m = DEVICE_NAME.exec(name2);
14232
+ const minor = Number(m?.[2]);
14233
+ if (!m || minor > 255) throw invalid(`not a serial device name: ${path}`);
14234
+ return { path: `/dev/${name2}`, major: MAJORS[m[1]], minor };
14235
+ }
14236
+ function linkPath(link2) {
14237
+ if (typeof link2 !== "string") throw invalid("a link must be a string");
14238
+ const name2 = link2.startsWith(`${BY_ID}/`) ? link2.slice(BY_ID.length + 1) : link2;
14239
+ if (!LINK_NAME.test(name2) || name2 === "." || name2 === "..")
14240
+ throw invalid(`not a link name: ${link2}`);
14241
+ return `${BY_ID}/${name2}`;
14242
+ }
14243
+ function modeOf(mode) {
14244
+ if (mode === void 0) return 384;
14245
+ if (!Number.isInteger(mode) || mode < 0 || mode > 4095)
14246
+ throw invalid("mode must be permission bits");
14247
+ return mode;
14248
+ }
14249
+ async function idOf(value2, find) {
14250
+ if (value2 === void 0) return 0;
14251
+ if (typeof value2 === "number") {
14252
+ if (!Number.isInteger(value2) || value2 < 0 || value2 > MAX_ID2) throw invalid(`bad id ${value2}`);
14253
+ return value2;
14254
+ }
14255
+ const id2 = typeof value2 === "string" ? await find(value2) : void 0;
14256
+ if (id2 === void 0) throw invalid(`unknown owner or group ${String(value2)}`);
14257
+ return id2;
14258
+ }
14259
+ function quiet3() {
14260
+ return void 0;
14261
+ }
14262
+ function want(access2) {
14263
+ return access2 === "read" ? R_OK : access2 === "write" ? W_OK : R_OK | W_OK;
14264
+ }
14265
+ function checkMeta(node, change, uid, gid, guard2) {
14266
+ const { cred } = guard2;
14267
+ const owner = cred.euid === 0 || cred.euid === node.uid;
14268
+ const member = cred.egid === gid || cred.groups.includes(gid);
14269
+ const chown2 = uid !== node.uid || gid !== node.gid;
14270
+ const times = (change.atimeMs ?? change.mtimeMs ?? null) !== null;
14271
+ if (change.mode !== void 0 && !owner) deny(guard2, "chmod", node.path, "EPERM");
14272
+ if (chown2 && cred.euid !== 0 && (uid !== node.uid || !owner || !member))
14273
+ deny(guard2, "chown", node.path, "EPERM");
14274
+ if (times && !owner && !(change.now && permits(cred, node, W_OK, false)))
14275
+ deny(guard2, "utimes", node.path, change.now ? "EACCES" : "EPERM");
14276
+ }
14277
+ var DeviceNodes = class {
14278
+ hooks = /* @__PURE__ */ new Map();
14279
+ nodes = /* @__PURE__ */ new Map();
14280
+ links = /* @__PURE__ */ new Map();
14281
+ lookup;
14282
+ users;
14283
+ next = 0;
14284
+ constructor(users, lookup2) {
14285
+ this.users = users;
14286
+ this.lookup = lookup2;
14287
+ }
14288
+ register(client, hook) {
14289
+ this.hooks.set(client, hook);
14290
+ return () => {
14291
+ if (this.hooks.get(client) !== hook) return;
14292
+ this.hooks.delete(client);
14293
+ for (const node of [...this.nodes.values()]) if (node.client === client) this.drop(node);
14294
+ };
14295
+ }
14296
+ async add(spec, client) {
14297
+ if (typeof spec !== "object" || spec === null) throw invalid("add needs a spec");
14298
+ const { path, major, minor } = nodePath(spec.path);
14299
+ const mode = modeOf(spec.mode);
14300
+ if (spec.links !== void 0 && !Array.isArray(spec.links))
14301
+ throw invalid("links must be a list");
14302
+ const links = (spec.links ?? []).map(linkPath);
14303
+ const uid = await idOf(spec.owner, (name2) => this.lookup.userId(name2));
14304
+ const gid = await idOf(spec.group, (name2) => this.lookup.groupId(name2));
14305
+ if (!this.hooks.has(client)) throw refused2("ENOTSUP", "this client has no devices hook");
14306
+ if (this.nodes.has(path)) throw refused2("EEXIST", `${path} exists`);
14307
+ const taken = links.find((l, i) => this.links.has(l) || links.indexOf(l) !== i);
14308
+ if (taken !== void 0) throw refused2("EEXIST", `${taken} exists`);
14309
+ const node = {
14310
+ id: ++this.next,
14311
+ client,
14312
+ path,
14313
+ uid,
14314
+ gid,
14315
+ mode,
14316
+ major,
14317
+ minor,
14318
+ links,
14319
+ opening: false,
14320
+ atimeMs: Date.now(),
14321
+ mtimeMs: Date.now(),
14322
+ ctimeMs: Date.now()
14323
+ };
14324
+ this.nodes.set(path, node);
14325
+ for (const link2 of links) this.links.set(link2, node);
14326
+ return node.id;
14327
+ }
14328
+ remove(id2) {
14329
+ const node = [...this.nodes.values()].find((n) => n.id === id2);
14330
+ if (!node) return false;
14331
+ this.drop(node);
14332
+ return true;
14333
+ }
14334
+ drop(node) {
14335
+ this.nodes.delete(node.path);
14336
+ for (const link2 of node.links) this.links.delete(link2);
14337
+ node.channel?.lost(new KernelError("EIO", `${node.path} was removed`));
14338
+ }
14339
+ list() {
14340
+ return [...this.nodes.values()].sort((a, b) => a.path < b.path ? -1 : 1).map(({ path, uid, gid, mode, major, minor, links, atimeMs, mtimeMs, ctimeMs }) => ({
14341
+ path,
14342
+ uid,
14343
+ gid,
14344
+ mode,
14345
+ major,
14346
+ minor,
14347
+ links: [...links],
14348
+ atimeMs,
14349
+ mtimeMs,
14350
+ ctimeMs
14351
+ }));
14352
+ }
14353
+ meta(path, change, guard2) {
14354
+ const node = this.find(path);
14355
+ if (!node) throw new KernelError("ENOENT");
14356
+ const uid = change.uid === void 0 || change.uid === -1 ? node.uid : change.uid >>> 0;
14357
+ const gid = change.gid === void 0 || change.gid === -1 ? node.gid : change.gid >>> 0;
14358
+ if (guard2) checkMeta(node, change, uid, gid, guard2);
14359
+ const now = Date.now();
14360
+ if (change.mode !== void 0) node.mode = change.mode & 4095;
14361
+ node.uid = uid;
14362
+ node.gid = gid;
14363
+ const at = (ms, kept) => ms === void 0 || ms === null ? kept : change.now ? now : ms;
14364
+ node.atimeMs = at(change.atimeMs, node.atimeMs);
14365
+ node.mtimeMs = at(change.mtimeMs, node.mtimeMs);
14366
+ node.ctimeMs = now;
14367
+ if (node.channel) node.channel.tty.owner = { uid: node.uid, gid: node.gid, mode: node.mode };
14368
+ }
14369
+ find(path) {
14370
+ return this.nodes.get(path) ?? this.links.get(path);
14371
+ }
14372
+ openTty(path) {
14373
+ return this.nodes.get(path)?.channel?.tty;
14374
+ }
14375
+ async open(path, flags2, opener) {
14376
+ const node = this.find(path);
14377
+ if (!node) throw new KernelError("ENOENT");
14378
+ const access2 = (flags2 & 3) === 0 ? "read" : (flags2 & 3) === 1 ? "write" : "both";
14379
+ if (opener.guard && !permits(opener.guard.cred, node, want(access2), false))
14380
+ deny(opener.guard, "open", node.path);
14381
+ if (node.channel || node.opening) throw new KernelError("EBUSY");
14382
+ const hook = this.hooks.get(node.client);
14383
+ node.opening = true;
14384
+ const asked = Promise.resolve().then(
14385
+ () => hook.open({ path: node.path, flags: flags2 & 3, stamp: opener.stamp, signal: opener.signal })
14386
+ );
14387
+ let streams;
14388
+ try {
14389
+ streams = await interruptible2(asked, opener.signal);
14390
+ } catch (err) {
14391
+ if (err instanceof KernelError && err.code === "EINTR") {
14392
+ void asked.then(abandon, quiet3).finally(() => node.opening = false);
14393
+ } else node.opening = false;
14394
+ throw embedderFailure(err);
14395
+ }
14396
+ node.opening = false;
14397
+ if (!isStreams(streams)) throw new KernelError("EIO", "the devices hook gave no streams");
14398
+ if (this.nodes.get(node.path) !== node) {
14399
+ void abandon(streams);
14400
+ throw new KernelError("ENOENT");
14401
+ }
14402
+ const channel = new DeviceChannel(node.path, streams, node.saved, (saved) => {
14403
+ node.saved = saved;
14404
+ if (node.channel === channel) delete node.channel;
14405
+ });
14406
+ channel.tty.owner = { uid: node.uid, gid: node.gid, mode: node.mode };
14407
+ node.channel = channel;
14408
+ try {
14409
+ await channel.restore();
14410
+ } catch (err) {
14411
+ await channel.close();
14412
+ throw err;
14413
+ }
14414
+ return channel.file(access2);
14415
+ }
14416
+ };
14417
+ function isStreams(value2) {
14418
+ const s = value2;
14419
+ return !!s && s.readable instanceof ReadableStream && s.writable instanceof WritableStream && typeof s.control === "function";
14420
+ }
14421
+ async function abandon(streams) {
14422
+ if (!isStreams(streams)) return;
14423
+ await streams.readable.cancel("closed").catch(quiet3);
14424
+ await streams.writable.abort("closed").catch(quiet3);
14425
+ await Promise.resolve().then(() => streams.control("close")).catch(quiet3);
14426
+ }
14427
+ function serialTermios() {
14428
+ const base = defaultTermios();
14429
+ return {
14430
+ c_iflag: 0,
14431
+ c_oflag: SERIAL_OFLAG,
14432
+ c_cflag: SERIAL_CFLAG,
14433
+ c_lflag: SERIAL_LFLAG,
14434
+ c_cc: base.c_cc
14435
+ };
14436
+ }
14437
+ function sleep(ms, signal) {
14438
+ return interruptible2(new Promise((resolve2) => setTimeout(resolve2, ms)), signal);
14439
+ }
14440
+ var DeviceChannel = class {
14441
+ tty;
14442
+ path;
14443
+ inner;
14444
+ reader;
14445
+ writer;
14446
+ streams;
14447
+ onClosed;
14448
+ gone = Promise.withResolvers();
14449
+ failure;
14450
+ pending = /* @__PURE__ */ new Set();
14451
+ queued = 0;
14452
+ resume;
14453
+ waiters = [];
14454
+ closed = false;
14455
+ ispeed = 9600;
14456
+ ospeed = 9600;
14457
+ dtr = true;
14458
+ rts = true;
14459
+ constructor(path, streams, saved, onClosed) {
14460
+ this.path = path;
14461
+ this.streams = streams;
14462
+ this.onClosed = onClosed;
14463
+ this.gone.promise.catch(quiet3);
14464
+ this.tty = new KernelTty({ write: (bytes) => this.send(bytes) }, quiet3);
14465
+ this.tty.name = path;
14466
+ this.tty.setSize(0, 0);
14467
+ this.tty.tcsets(saved?.termios ?? serialTermios());
14468
+ if (saved) {
14469
+ this.ispeed = saved.ispeed;
14470
+ this.ospeed = saved.ospeed;
14471
+ this.dtr = this.rts = saved.ospeed !== 0;
14472
+ }
14473
+ this.inner = this.tty.file();
14474
+ this.reader = streams.readable.getReader();
14475
+ this.writer = streams.writable.getWriter();
14476
+ void this.pump();
14477
+ }
14478
+ file(access2) {
14479
+ return new OpenFile({
14480
+ ...access2 === "write" ? {} : { read: (max, signal) => this.read(max, signal) },
14481
+ ...access2 === "read" ? {} : { write: (bytes, signal) => this.write(bytes, signal) },
14482
+ poll: () => this.poll(),
14483
+ changed: (signal) => this.changed(signal),
14484
+ close: () => this.close(),
14485
+ tty: this.tty,
14486
+ device: this
14487
+ });
14488
+ }
14489
+ lost(err) {
14490
+ if (this.failure) return;
14491
+ this.failure = err;
14492
+ this.gone.reject(err);
14493
+ this.tty.hangup();
14494
+ this.wake();
14495
+ }
14496
+ control(op, args) {
14497
+ return Promise.resolve().then(() => this.streams.control(op, args));
14498
+ }
14499
+ buffered() {
14500
+ return this.inner.file.poll?.().nread ?? 0;
14501
+ }
14502
+ async pump() {
14503
+ for (; ; ) {
14504
+ while (this.buffered() >= HIGH_WATER && !this.closed && !this.failure) {
14505
+ await new Promise((resolve2) => {
14506
+ this.resume = resolve2;
14507
+ });
14508
+ }
14509
+ if (this.closed || this.failure) return;
14510
+ let got;
14511
+ try {
14512
+ got = await this.reader.read();
14513
+ } catch (err) {
14514
+ if (!this.closed) this.lost(new KernelError("EIO", lineOf2(err)));
14515
+ return;
14516
+ }
14517
+ if (got.done) {
14518
+ this.tty.hangup();
14519
+ this.wake();
14520
+ return;
14521
+ }
14522
+ this.tty.receive(got.value);
14523
+ this.wake();
14524
+ }
14525
+ }
14526
+ send(bytes) {
14527
+ if (this.closed || this.failure) return;
14528
+ const n = bytes.length;
14529
+ this.queued += n;
14530
+ const sent = this.writer.write(bytes.slice()).catch((err) => {
14531
+ this.lost(new KernelError("EIO", lineOf2(err)));
14532
+ });
14533
+ const tracked = sent.finally(() => {
14534
+ this.queued -= n;
14535
+ this.pending.delete(tracked);
14536
+ this.wake();
14537
+ });
14538
+ this.pending.add(tracked);
14539
+ }
14540
+ check() {
14541
+ if (this.failure) throw this.failure;
14542
+ }
14543
+ async read(max, signal) {
14544
+ this.check();
14545
+ const read = this.inner.file.read;
14546
+ const got = await read(max, signal);
14547
+ this.resume?.();
14548
+ this.resume = void 0;
14549
+ if (got.length === 0) this.check();
14550
+ return got;
14551
+ }
14552
+ async ready(signal) {
14553
+ this.check();
14554
+ try {
14555
+ await interruptible2(Promise.race([this.writer.ready, this.gone.promise]), signal);
14556
+ } catch (err) {
14557
+ if (err instanceof KernelError) throw err;
14558
+ throw new KernelError("EIO", lineOf2(err));
14559
+ }
14560
+ }
14561
+ async write(bytes, signal) {
14562
+ this.check();
14563
+ if (!((this.writer.desiredSize ?? 0) > 0)) await this.ready(signal);
14564
+ const write = this.inner.file.write;
14565
+ return write(bytes, signal);
14566
+ }
14567
+ poll() {
14568
+ if (this.failure)
14569
+ return { readable: true, writable: true, hangup: true, error: true, nread: 0 };
14570
+ const inner = this.inner.file.poll?.();
14571
+ const writable3 = (this.writer.desiredSize ?? 0) > 0;
14572
+ return { ...inner, writable: writable3 };
14573
+ }
14574
+ changed(signal) {
14575
+ const mine = new Promise((resolve2) => this.waiters.push(resolve2));
14576
+ const theirs = this.inner.file.changed?.(signal);
14577
+ return interruptible2(Promise.race([mine, theirs]), signal);
14578
+ }
14579
+ wake() {
14580
+ const waiters = this.waiters;
14581
+ this.waiters = [];
14582
+ for (const resolve2 of waiters) resolve2();
14583
+ }
14584
+ async drain(signal) {
14585
+ while (this.pending.size > 0) {
14586
+ this.check();
14587
+ await interruptible2(
14588
+ Promise.race([Promise.all([...this.pending]), this.gone.promise]),
14589
+ signal
14590
+ );
14591
+ }
14592
+ this.check();
14593
+ }
14594
+ async restore() {
14595
+ const settings = this.settings();
14596
+ if (settings.baudRate === 0)
14597
+ return this.signals({ dataTerminalReady: false, requestToSend: false });
14598
+ if (sameSettings(settings, DEFAULT_SETTINGS)) return;
14599
+ try {
14600
+ await this.control("configure", settings);
14601
+ } catch (err) {
14602
+ throw embedderFailure(err);
14603
+ }
14604
+ }
14605
+ settings() {
14606
+ return settingsOf(this.tty.tcgets().c_cflag, this.ospeed);
14607
+ }
14608
+ termios() {
14609
+ return { ...this.tty.tcgets(), c_ispeed: this.ispeed, c_ospeed: this.ospeed };
14610
+ }
14611
+ async setTermios(termios, how, signal) {
14612
+ this.check();
14613
+ if (how.drain) await this.drain(signal);
14614
+ const before = this.settings();
14615
+ const old = { termios: this.tty.tcgets(), ispeed: this.ispeed, ospeed: this.ospeed };
14616
+ const speeds = speedsOf(termios, this, how.extended === true);
14617
+ this.tty.tcsets(termios, how.flush === true);
14618
+ this.ispeed = speeds.ispeed;
14619
+ this.ospeed = speeds.ospeed;
14620
+ try {
14621
+ if (speeds.ospeed === 0) await this.setModem(this.bits() & ~(TIOCM.DTR | TIOCM.RTS));
14622
+ else {
14623
+ if (!sameSettings(before, this.settings()))
14624
+ await this.control("configure", this.settings());
14625
+ if (old.ospeed === 0) await this.setModem(this.bits() | TIOCM.DTR | TIOCM.RTS);
14626
+ }
14627
+ if (how.flush) await this.control("flush", { input: true, output: false });
14628
+ } catch (err) {
14629
+ this.tty.tcsets(old.termios);
14630
+ this.ispeed = old.ispeed;
14631
+ this.ospeed = old.ospeed;
14632
+ throw embedderFailure(err);
14633
+ }
14634
+ }
14635
+ bits() {
14636
+ return (this.dtr ? TIOCM.DTR : 0) | (this.rts ? TIOCM.RTS : 0);
14637
+ }
14638
+ async modem() {
14639
+ this.check();
14640
+ const s = await this.control("signals").catch((err) => {
14641
+ throw embedderFailure(err);
14642
+ });
14643
+ return this.bits() | (s?.clearToSend ? TIOCM.CTS : 0) | (s?.dataSetReady ? TIOCM.DSR : 0) | (s?.dataCarrierDetect ? TIOCM.CD : 0) | (s?.ringIndicator ? TIOCM.RI : 0);
14644
+ }
14645
+ async setModem(bits2) {
14646
+ this.check();
14647
+ const dataTerminalReady = (bits2 & TIOCM.DTR) !== 0;
14648
+ const requestToSend = (bits2 & TIOCM.RTS) !== 0;
14649
+ await this.signals({ dataTerminalReady, requestToSend });
14650
+ this.dtr = dataTerminalReady;
14651
+ this.rts = requestToSend;
14652
+ }
14653
+ async signals(args) {
14654
+ try {
14655
+ await this.control("setSignals", args);
14656
+ } catch (err) {
14657
+ throw embedderFailure(err);
14658
+ }
14659
+ }
14660
+ async sendBreak(ms, signal) {
14661
+ await this.drain(signal);
14662
+ await this.signals({ break: true });
14663
+ try {
14664
+ await sleep(ms, signal);
14665
+ } finally {
14666
+ await this.signals({ break: false });
14667
+ }
14668
+ }
14669
+ async flush(input, output) {
14670
+ this.check();
14671
+ if (input) this.tty.tcsets(this.tty.tcgets(), true);
14672
+ try {
14673
+ await this.control("flush", { input, output });
14674
+ } catch (err) {
14675
+ throw embedderFailure(err);
14676
+ }
14677
+ }
14678
+ async ioctl(request3, arg, signal) {
14679
+ this.check();
14680
+ switch (request3) {
14681
+ case IOCTL.TCGETS:
14682
+ case IOCTL.TCGETS2:
14683
+ return this.termios();
14684
+ case IOCTL.TCSETS:
14685
+ case IOCTL.TCSETSW:
14686
+ case IOCTL.TCSETSF:
14687
+ case IOCTL.TCSETS2:
14688
+ case IOCTL.TCSETSW2:
14689
+ case IOCTL.TCSETSF2: {
14690
+ const extended = request3 > 65535;
14691
+ const kind = (request3 & 255) - (extended ? 43 : 2);
14692
+ await this.setTermios(
14693
+ arg,
14694
+ { drain: kind > 0, flush: kind === 2, extended },
14695
+ signal
14696
+ );
14697
+ return null;
14698
+ }
14699
+ case IOCTL.TIOCMGET:
14700
+ return this.modem();
14701
+ case IOCTL.TIOCMSET:
14702
+ await this.setModem(Number(arg));
14703
+ return null;
14704
+ case IOCTL.TIOCMBIS:
14705
+ await this.setModem(this.bits() | Number(arg));
14706
+ return null;
14707
+ case IOCTL.TIOCMBIC:
14708
+ await this.setModem(this.bits() & ~Number(arg));
14709
+ return null;
14710
+ case IOCTL.TIOCSBRK:
14711
+ case IOCTL.TIOCCBRK:
14712
+ await this.signals({ break: request3 === IOCTL.TIOCSBRK });
14713
+ return null;
14714
+ case IOCTL.TCSBRK:
14715
+ if (Number(arg) === 0) await this.sendBreak(BREAK_MS, signal);
14716
+ else await this.drain(signal);
14717
+ return null;
14718
+ case IOCTL.TCSBRKP:
14719
+ await this.sendBreak(Number(arg) > 0 ? Number(arg) * 100 : BREAK_MS, signal);
14720
+ return null;
14721
+ case IOCTL.TCFLSH: {
14722
+ const queue = Number(arg);
14723
+ if (queue < 0 || queue > 2) throw new KernelError("EINVAL");
14724
+ await this.flush(queue !== 1, queue !== 0);
14725
+ return null;
14726
+ }
14727
+ case IOCTL.FIONREAD:
14728
+ return this.buffered();
14729
+ case IOCTL.TIOCOUTQ:
14730
+ return this.queued;
14731
+ case IOCTL.TIOCEXCL:
14732
+ case IOCTL.TIOCNXCL:
14733
+ return null;
14734
+ case IOCTL.TIOCGWINSZ: {
14735
+ const [rows, cols] = this.tty.winsize();
14736
+ return { rows, cols };
14737
+ }
14738
+ case IOCTL.TIOCSWINSZ: {
14739
+ const size = arg;
14740
+ this.tty.setSize(Number(size?.cols) & 65535, Number(size?.rows) & 65535);
14741
+ return null;
14742
+ }
14743
+ case IOCTL.TIOCSCTTY:
14744
+ throw new KernelError("EPERM");
14745
+ default:
14746
+ throw new KernelError("ENOTTY");
14747
+ }
14748
+ }
14749
+ async close() {
14750
+ if (this.closed) return;
14751
+ try {
14752
+ if (!this.failure) {
14753
+ await interruptible2(this.drain(), AbortSignal.timeout(CLOSING_WAIT_MS)).catch(quiet3);
14754
+ }
14755
+ this.closed = true;
14756
+ this.resume?.();
14757
+ this.wake();
14758
+ await this.reader.cancel("closed").catch(quiet3);
14759
+ this.reader.releaseLock();
14760
+ await this.writer.abort("closed").catch(quiet3);
14761
+ this.writer.releaseLock();
14762
+ await this.control("close").catch(quiet3);
14763
+ } finally {
14764
+ this.closed = true;
14765
+ this.onClosed({ termios: this.tty.tcgets(), ispeed: this.ispeed, ospeed: this.ospeed });
14766
+ }
14767
+ }
14768
+ };
14769
+
13661
14770
  // src/kernel/exec-ticket.ts
13662
14771
  var TICKET_ENV = "SLICC_SEALED_TICKET";
13663
14772
  var TICKET_TTL_MS = 3e4;
@@ -13934,6 +15043,14 @@ function inheritedCwd(chdir, parent) {
13934
15043
  return chdir ? void 0 : parent;
13935
15044
  }
13936
15045
 
15046
+ // src/async/header-hook.ts
15047
+ var watchers = /* @__PURE__ */ new WeakMap();
15048
+ var watching = 0;
15049
+ function headerNotified(header4, index, bits2 = 0) {
15050
+ if (watching === 0) return;
15051
+ watchers.get(header4.buffer)?.(index, bits2);
15052
+ }
15053
+
13937
15054
  // src/fs/copy.ts
13938
15055
  async function present2(fs, path) {
13939
15056
  return fs.lstat(path).then(
@@ -14030,8 +15147,8 @@ var DriverConnection = class _DriverConnection {
14030
15147
  } finally {
14031
15148
  clearTimeout(timer);
14032
15149
  }
14033
- const refused4 = driverVersionError(hello.protocol);
14034
- if (refused4) throw errnoError("EPROTO", refused4);
15150
+ const refused5 = driverVersionError(hello.protocol);
15151
+ if (refused5) throw errnoError("EPROTO", refused5);
14035
15152
  if (hello.error) throw errnoError(hello.errno ?? "EIO", hello.error);
14036
15153
  return new _DriverConnection(port, hello.capabilities ?? {}, waiting, timeoutMs, options);
14037
15154
  }
@@ -14077,7 +15194,7 @@ var DriverConnection = class _DriverConnection {
14077
15194
  var S_ISGID4 = 1024;
14078
15195
  var ID = /^\d{1,10}$/;
14079
15196
  var MASK = /^0*[0-7]{1,4}$/;
14080
- var MAX_ID2 = 4294967294;
15197
+ var MAX_ID3 = 4294967294;
14081
15198
  function idOption(value2) {
14082
15199
  return value2 === void 0 ? 0 : Number(value2);
14083
15200
  }
@@ -14089,7 +15206,7 @@ function checkIds(options) {
14089
15206
  for (const key of ["uid", "gid"]) {
14090
15207
  const value2 = options[key];
14091
15208
  if (value2 === void 0) continue;
14092
- if (!ID.test(value2) || Number(value2) > MAX_ID2) throw errnoError("EINVAL", `${key}=${value2}`);
15209
+ if (!ID.test(value2) || Number(value2) > MAX_ID3) throw errnoError("EINVAL", `${key}=${value2}`);
14093
15210
  }
14094
15211
  }
14095
15212
  function checkMasks(options) {
@@ -14101,7 +15218,7 @@ function checkMasks(options) {
14101
15218
  }
14102
15219
  }
14103
15220
  }
14104
- function modeOf(attr2, mount) {
15221
+ function modeOf2(attr2, mount) {
14105
15222
  const type = attr2.kind === "directory" ? 16384 : attr2.kind === "symlink" ? 40960 : attr2.kind === "fifo" ? 4096 : 32768;
14106
15223
  const fallback = type | (attr2.kind === "directory" ? 493 : attr2.kind === "symlink" ? 511 : 420);
14107
15224
  if (mount.caps.owners) return attr2.mode ?? fallback;
@@ -14262,9 +15379,9 @@ var HeldPaths = class extends Map {
14262
15379
  this.unlinked.set(path, file);
14263
15380
  }
14264
15381
  keep(path, file) {
14265
- const fresh3 = this.handlesAt(path).filter((id2) => !this.keptHandles.has(id2));
14266
- for (const id2 of fresh3) this.keptHandles.set(id2, file);
14267
- this.uses.set(file, Math.max(fresh3.length, 1));
15382
+ const fresh4 = this.handlesAt(path).filter((id2) => !this.keptHandles.has(id2));
15383
+ for (const id2 of fresh4) this.keptHandles.set(id2, file);
15384
+ this.uses.set(file, Math.max(fresh4.length, 1));
14268
15385
  this.unlinked.set(path, file);
14269
15386
  }
14270
15387
  unkeep(path, file) {
@@ -14385,7 +15502,7 @@ function statOf2(attr2, path, mount) {
14385
15502
  isSymbolicLink: attr2.kind === "symlink",
14386
15503
  ...attr2.kind === "fifo" ? { isFifo: true } : {},
14387
15504
  size: attr2.size,
14388
- mode: modeOf(attr2, mount),
15505
+ mode: modeOf2(attr2, mount),
14389
15506
  mtime,
14390
15507
  atime: attr2.atime === void 0 ? mtime : new Date(attr2.atime),
14391
15508
  ctime: mtime,
@@ -15476,8 +16593,8 @@ var MountFs = class _MountFs {
15476
16593
  }
15477
16594
  this.writable(mount, real);
15478
16595
  const { uid, gid, mode } = change;
15479
- const fresh3 = change.kind === "new" && { uid, gid, mode };
15480
- const set3 = fresh3 ? await this.driverOwner(found, real, fresh3, false) : change;
16596
+ const fresh4 = change.kind === "new" && { uid, gid, mode };
16597
+ const set3 = fresh4 ? await this.driverOwner(found, real, fresh4, false) : change;
15481
16598
  this.table.forget(mount, real);
15482
16599
  const attrs = Object.entries({ uid: set3.uid, gid: set3.gid, mode: set3.mode });
15483
16600
  await mount.conn.call({
@@ -15754,10 +16871,10 @@ async function runMkdir(entry, path, req) {
15754
16871
  const plain3 = plainDirMode(entry, req.mode);
15755
16872
  const parentsMode = !req.exclusive ? plainParentsMode(entry) : void 0;
15756
16873
  const fixParents = parentsMode !== void 0 ? await missingParents(fs, path, parentsMode) : void 0;
15757
- const fresh3 = plain3 !== void 0 && !await fs.exists(path);
16874
+ const fresh4 = plain3 !== void 0 && !await fs.exists(path);
15758
16875
  await (req.exclusive ? mkdirExclusive(entry, path, req.mode) : fs.mkdir(path, mkdirOptions(entry, req.mode)));
15759
16876
  await fixParents?.();
15760
- if (fresh3) await fs.chmod(path, plain3);
16877
+ if (fresh4) await fs.chmod(path, plain3);
15761
16878
  return done2;
15762
16879
  }
15763
16880
  async function shownAs(entry, path, st) {
@@ -15969,10 +17086,10 @@ async function guard(g, path, req, cwd) {
15969
17086
  }
15970
17087
  async function opening(entry, path, mode) {
15971
17088
  const g = guardOf(entry);
15972
- const want = (mode & HOLD_READ ? R_OK : 0) | (mode & HOLD_WRITE ? W_OK : 0);
17089
+ const want2 = (mode & HOLD_READ ? R_OK : 0) | (mode & HOLD_WRITE ? W_OK : 0);
15973
17090
  const created4 = (mode & HOLD_CREATED) !== 0 && entry.created?.take(path) === true;
15974
- if (g && want !== 0 && !created4) {
15975
- await need(g, "open", path, want, { directory: false });
17091
+ if (g && want2 !== 0 && !created4) {
17092
+ await need(g, "open", path, want2, { directory: false });
15976
17093
  }
15977
17094
  }
15978
17095
  async function stillThere(entry, path, req) {
@@ -15996,7 +17113,7 @@ async function holdOp(entry, path, req) {
15996
17113
  await entry.source?.open(path, real);
15997
17114
  await stillThere(entry, path, req);
15998
17115
  if (req.nofollow && !await ownEntry(entry, path, real ?? path)) continue;
15999
- const fid = req.ino === void 0 ? void 0 : await idOf(entry, real ?? path);
17116
+ const fid = req.ino === void 0 ? void 0 : await idOf2(entry, real ?? path);
16000
17117
  if (!r || !r.missed(path) && !r.changedSince(path, gen) && !r.inFlight?.(path))
16001
17118
  return json2(await heldOpen(entry, path, real, req, fid));
16002
17119
  }
@@ -16010,7 +17127,7 @@ async function heldOpen(entry, path, real, req, fid) {
16010
17127
  await entry.announceHold?.(real ?? path, fid, ((req.mode ?? 0) & HOLD_CREATED) !== 0);
16011
17128
  return real !== void 0 && real !== path ? { handle, real } : handle;
16012
17129
  }
16013
- async function idOf(entry, path) {
17130
+ async function idOf2(entry, path) {
16014
17131
  return await entry.fileId?.(path)?.catch(() => void 0) ?? void 0;
16015
17132
  }
16016
17133
  async function ownEntry(entry, path, real) {
@@ -16082,8 +17199,8 @@ async function guarded(entry, path, req) {
16082
17199
  return { paths };
16083
17200
  } catch (err) {
16084
17201
  const refusal2 = err.code === "EACCES";
16085
- const refused4 = req.op === "exists" && refusal2 ? json2(false) : toErrno(err);
16086
- return { refused: refused4 };
17202
+ const refused5 = req.op === "exists" && refusal2 ? json2(false) : toErrno(err);
17203
+ return { refused: refused5 };
16087
17204
  }
16088
17205
  }
16089
17206
  async function copyOp(entry, path, req) {
@@ -16184,7 +17301,7 @@ async function bound(entry, path, handle) {
16184
17301
  const now = await entry.fs.stat(path).catch(() => void 0);
16185
17302
  if (now === void 0 && bound3.fid !== void 0 && !await entry.fs.lstat(path).catch(() => void 0))
16186
17303
  throw syncError("ENOENT", path);
16187
- const same3 = bound3.fid === void 0 ? now?.ino === bound3.ino : now?.fid === bound3.fid || await idOf(entry, path) === bound3.fid;
17304
+ const same3 = bound3.fid === void 0 ? now?.ino === bound3.ino : now?.fid === bound3.fid || await idOf2(entry, path) === bound3.fid;
16188
17305
  if (same3) {
16189
17306
  entry.trust?.(handle, bound3.doubt);
16190
17307
  return;
@@ -16279,13 +17396,13 @@ async function created2(entry, req) {
16279
17396
  return seen === void 0 ? looked : json2({ ...looked.json, seen });
16280
17397
  }
16281
17398
  var DENIED = /* @__PURE__ */ new Set(["EACCES", "EPERM"]);
16282
- async function rmPermitted(entry, path, req, refused4) {
17399
+ async function rmPermitted(entry, path, req, refused5) {
16283
17400
  const st = await entry.fs.lstat(path).catch(() => void 0);
16284
- if (!st?.isDirectory) return refused4;
17401
+ if (!st?.isDirectory) return refused5;
16285
17402
  const unlisted = await guarded(entry, path, { ...req, op: "readdir" });
16286
17403
  if ("refused" in unlisted) return unlisted.refused;
16287
17404
  const names2 = await entry.fs.readdir(path).catch(() => void 0);
16288
- if (!names2) return refused4;
17405
+ if (!names2) return refused5;
16289
17406
  let first;
16290
17407
  for (const name2 of names2) {
16291
17408
  const child = await dispatchOne(entry, {
@@ -16336,14 +17453,14 @@ async function newDevName(entry, path, req) {
16336
17453
  const named = NAMING.has(req.op);
16337
17454
  if (!named && !CREATIONS.has(req.op)) return void 0;
16338
17455
  const target = named ? entry.fs.resolvePath(entry.cwd, req.arg2 ?? "") : path;
16339
- const refused4 = devCreation(target, entry.cred?.());
16340
- if (!refused4) return void 0;
17456
+ const refused5 = devCreation(target, entry.cred?.());
17457
+ if (!refused5) return void 0;
16341
17458
  const there = await entry.fs.lstat(target).then(
16342
17459
  () => true,
16343
17460
  () => false
16344
17461
  );
16345
17462
  if (there) return void 0;
16346
- return { ok: false, errno: refused4, message: `${target}: no new names in /dev or /proc` };
17463
+ return { ok: false, errno: refused5, message: `${target}: no new names in /dev or /proc` };
16347
17464
  }
16348
17465
  var MISS_OPS = /* @__PURE__ */ new Set(["stat", "lstat"]);
16349
17466
  async function linkFree(fs, path) {
@@ -16454,13 +17571,13 @@ var SAB_DEFAULT_WINDOW_BYTES = 1024 * 1024;
16454
17571
  var SAB_MIN_BYTES = SAB_HEADER_BYTES + 4096;
16455
17572
  var SYNC_SAB_REQ_MSG = "sync-sab-req";
16456
17573
  var SYNC_SAB_NEXT_MSG = "sync-sab-next";
16457
- var encoder3 = new TextEncoder();
17574
+ var encoder4 = new TextEncoder();
16458
17575
  var decoder2 = new TextDecoder();
16459
17576
  function encodeSabResult(result) {
16460
17577
  if (!result.ok) {
16461
17578
  return {
16462
17579
  status: SAB_STATUS_ERRNO,
16463
- payload: encoder3.encode(
17580
+ payload: encoder4.encode(
16464
17581
  JSON.stringify({
16465
17582
  errno: result.errno,
16466
17583
  message: result.message,
@@ -16475,7 +17592,7 @@ function encodeSabResult(result) {
16475
17592
  case "bytes":
16476
17593
  return { status: SAB_STATUS_BYTES, payload: result.bytes };
16477
17594
  case "json":
16478
- return { status: SAB_STATUS_JSON, payload: encoder3.encode(JSON.stringify(result.json)) };
17595
+ return { status: SAB_STATUS_JSON, payload: encoder4.encode(JSON.stringify(result.json)) };
16479
17596
  default:
16480
17597
  return { status: SAB_STATUS_VOID, payload: new Uint8Array(0) };
16481
17598
  }
@@ -16519,6 +17636,7 @@ function attachSyncSabResponder(port, sab, token, opts) {
16519
17636
  Atomics.store(header4, SAB_I_STATE, SAB_STATE_READY);
16520
17637
  Atomics.add(header4, SAB_I_PUB, 1);
16521
17638
  Atomics.notify(header4, SAB_I_PUB);
17639
+ headerNotified(header4, SAB_I_PUB);
16522
17640
  if (offset + chunk2 >= entry.payload.byteLength) drop(id2);
16523
17641
  else if (entry.timer) {
16524
17642
  clearTimeout(entry.timer);
@@ -16802,9 +17920,9 @@ var Pages = class {
16802
17920
  const page = (start2 + at) / PAGE;
16803
17921
  if (this.pages.has(page)) continue;
16804
17922
  const part = bytes.subarray(at, Math.min(at + PAGE, bytes.length));
16805
- const fresh3 = this.take(part.length);
16806
- fresh3.set(part);
16807
- this.pages.set(page, fresh3);
17923
+ const fresh4 = this.take(part.length);
17924
+ fresh4.set(part);
17925
+ this.pages.set(page, fresh4);
16808
17926
  }
16809
17927
  }
16810
17928
  read(at, length2) {
@@ -17015,16 +18133,16 @@ var pinnedRoot;
17015
18133
  var rootKind = () => globalThis.navigator?.storage ? "opfs" : "memory";
17016
18134
  function mountTable(mounts = []) {
17017
18135
  const root = pinnedRoot ?? rootKind();
17018
- const lines2 = [`${root} / ${root} rw 0 0`, "devfs /dev devfs rw 0 0", "proc /proc proc rw 0 0"];
18136
+ const lines3 = [`${root} / ${root} rw 0 0`, "devfs /dev devfs rw 0 0", "proc /proc proc rw 0 0"];
17019
18137
  for (const m of mounts) {
17020
18138
  const options = Object.entries(m.options).map(([k, v]) => v === "" ? k : `${k}=${v}`);
17021
18139
  if (m.state !== "ok") options.push(m.state);
17022
18140
  const access2 = options.includes("ro") ? [] : ["rw"];
17023
- lines2.push(
18141
+ lines3.push(
17024
18142
  `${field3(m.source)} ${field3(m.target)} ${m.type} ${[...access2, ...options].join(",")} 0 0`
17025
18143
  );
17026
18144
  }
17027
- return `${lines2.join("\n")}
18145
+ return `${lines3.join("\n")}
17028
18146
  `;
17029
18147
  }
17030
18148
 
@@ -18059,7 +19177,7 @@ function recordRefusal(opening2) {
18059
19177
  const found = headerClass(opening2);
18060
19178
  return found && new KernelError("EPROTO", `${found[0]}: ${found[1]}`);
18061
19179
  }
18062
- function refused2(engine, session, err, opening2) {
19180
+ function refused3(engine, session, err, opening2) {
18063
19181
  const flags2 = session.verifyResult;
18064
19182
  const code = verifyCode(flags2);
18065
19183
  if (code && flags2 !== -1)
@@ -18080,7 +19198,7 @@ async function handshake(conn, o, session, inbox) {
18080
19198
  done5 = session.handshake();
18081
19199
  } catch (err) {
18082
19200
  await send(conn, session).catch(() => void 0);
18083
- throw refused2(o.engine, session, err, inbox.opening);
19201
+ throw refused3(o.engine, session, err, inbox.opening);
18084
19202
  }
18085
19203
  await send(conn, session);
18086
19204
  if (done5) return;
@@ -18531,10 +19649,10 @@ async function anchorFor(engine, chain2, host, found) {
18531
19649
  var FRAGMENT = 16;
18532
19650
  var MIN_VALUE = 8;
18533
19651
  var MIN_BASE64 = 8;
18534
- var encoder4 = new TextEncoder();
19652
+ var encoder5 = new TextEncoder();
18535
19653
  var STD = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
18536
19654
  function utf8(text) {
18537
- return encoder4.encode(text);
19655
+ return encoder5.encode(text);
18538
19656
  }
18539
19657
  function base64(bytes, padded = true) {
18540
19658
  let out = "";
@@ -18608,14 +19726,73 @@ function encodings(bytes) {
18608
19726
  }
18609
19727
  return [...standard, ...standard.map(urlSafe)];
18610
19728
  }
18611
- function shapes(value2) {
19729
+ function windows(length2) {
19730
+ const out = [];
19731
+ for (let offset = 0; offset + FRAGMENT <= length2; offset++) out.push(offset);
19732
+ return out;
19733
+ }
19734
+ function strings(document) {
19735
+ const out = [];
19736
+ const stack = [document];
19737
+ while (stack.length > 0) {
19738
+ const item = stack.pop();
19739
+ if (typeof item === "string") out.push(item);
19740
+ if (typeof item !== "object" || item === null) continue;
19741
+ for (const child of Object.values(item)) stack.push(child);
19742
+ }
19743
+ return out;
19744
+ }
19745
+ var DOMAIN = "(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z]{2,63}";
19746
+ var HOST = new RegExp(`^${DOMAIN}$`);
19747
+ var EMAIL = new RegExp(`^[^\\s@]+@${DOMAIN}$`);
19748
+ var URL_SHAPE = new RegExp(`^https?://${DOMAIN}(?::[0-9]{1,5})?((?:/[^/?#\\s]*)*)$`);
19749
+ var ARMOR = /^-----(?:BEGIN|END) [A-Z0-9 ]+-----$/;
19750
+ function unescaped(segment) {
19751
+ try {
19752
+ return decodeURIComponent(segment);
19753
+ } catch {
19754
+ return segment;
19755
+ }
19756
+ }
19757
+ function address(leaf) {
19758
+ if (HOST.test(leaf) || EMAIL.test(leaf)) return true;
19759
+ const url = URL_SHAPE.exec(leaf);
19760
+ if (!url) return false;
19761
+ return url[1].split("/").every((segment) => utf8(segment).length < FRAGMENT || EMAIL.test(unescaped(segment)));
19762
+ }
19763
+ function lines2(leaf) {
19764
+ if (address(leaf)) return [];
19765
+ return leaf.split(/[\r\n"\\]/).filter((line) => utf8(line).length >= FRAGMENT && !ARMOR.test(line));
19766
+ }
19767
+ function parsed2(value2) {
19768
+ try {
19769
+ const document = JSON.parse(value2);
19770
+ return typeof document === "object" && document !== null ? document : null;
19771
+ } catch {
19772
+ return null;
19773
+ }
19774
+ }
19775
+ function fragments(value2) {
19776
+ const raw2 = utf8(value2);
19777
+ const document = parsed2(value2);
19778
+ if (!document) return { pieces: [raw2], whole: true };
19779
+ return { pieces: [...new Set(strings(document).flatMap(lines2))].map(utf8), whole: false };
19780
+ }
19781
+ function shapes(value2, split3 = fragments(value2)) {
18612
19782
  const raw2 = utf8(value2);
18613
19783
  const seen = /* @__PURE__ */ new Set([value2]);
18614
19784
  const out = [];
18615
- if (raw2.length < FRAGMENT) out.push({ bytes: raw2, form: "raw" });
18616
- for (let offset = 0; raw2.length >= FRAGMENT && offset + FRAGMENT <= raw2.length; offset++) {
18617
- out.push({ bytes: raw2.subarray(offset, offset + FRAGMENT), form: "fragment", offset });
18618
- }
19785
+ if (raw2.length < FRAGMENT || !split3.whole) out.push({ bytes: raw2, form: "raw" });
19786
+ split3.pieces.forEach((bytes, piece) => {
19787
+ for (const offset of windows(bytes.length)) {
19788
+ out.push({
19789
+ bytes: bytes.subarray(offset, offset + FRAGMENT),
19790
+ form: "fragment",
19791
+ offset,
19792
+ piece
19793
+ });
19794
+ }
19795
+ });
18619
19796
  const add = (text, form) => {
18620
19797
  if (seen.has(text)) return;
18621
19798
  seen.add(text);
@@ -18748,12 +19925,19 @@ function prepare(secrets, sameLength) {
18748
19925
  const ids = /* @__PURE__ */ new Map();
18749
19926
  const wrapIds = /* @__PURE__ */ new Map();
18750
19927
  const values = secrets.map((secret) => utf8(secret.value));
19928
+ const splits = [];
18751
19929
  secrets.forEach((secret, index) => {
18752
19930
  if (typeof secret.value !== "string" || values[index].length < MIN_VALUE) {
18753
19931
  throw new RangeError(`the value of ${secret.name} is shorter than ${MIN_VALUE} bytes`);
18754
19932
  }
18755
- for (const shape of shapes(secret.value)) {
18756
- const source = { secret: index, form: shape.form, offset: shape.offset };
19933
+ splits.push(fragments(secret.value));
19934
+ for (const shape of shapes(secret.value, splits[index])) {
19935
+ const source = {
19936
+ secret: index,
19937
+ form: shape.form,
19938
+ offset: shape.offset,
19939
+ piece: shape.piece
19940
+ };
18757
19941
  register(main, sources, ids, shape.bytes, source);
18758
19942
  if (wrappable(shape.form)) register(wrap, wrapSources, wrapIds, shape.bytes, source);
18759
19943
  }
@@ -18764,7 +19948,16 @@ function prepare(secrets, sameLength) {
18764
19948
  utf8(secret.placeholder),
18765
19949
  utf8(`[redacted:${secret.name}]`)
18766
19950
  ]);
18767
- return { secrets, values, main, wrap, sources, wrapSources, replacements, sameLength };
19951
+ return {
19952
+ secrets,
19953
+ splits,
19954
+ main,
19955
+ wrap,
19956
+ sources,
19957
+ wrapSources,
19958
+ replacements,
19959
+ sameLength
19960
+ };
18768
19961
  }
18769
19962
  function filled(input, start2, end) {
18770
19963
  const out = new Uint8Array(end - start2);
@@ -18795,14 +19988,16 @@ function resolve(c, input, start2, end, source) {
18795
19988
  growing: false
18796
19989
  };
18797
19990
  }
18798
- const value2 = c.values[source.secret];
19991
+ const split3 = c.splits[source.secret];
19992
+ const value2 = split3.pieces[source.piece];
18799
19993
  let stop = end;
18800
19994
  let at = source.offset + FRAGMENT;
18801
19995
  while (stop < input.length && at < value2.length && input[stop] === value2[at]) {
18802
19996
  stop++;
18803
19997
  at++;
18804
19998
  }
18805
- const form = source.offset === 0 && at === value2.length ? "raw" : "fragment";
19999
+ const whole = split3.whole && source.offset === 0 && at === value2.length;
20000
+ const form = whole ? "raw" : "fragment";
18806
20001
  const growing = stop === input.length && at < value2.length;
18807
20002
  return { start: start2, end: stop, secret: source.secret, form, rank: RANK[form], growing };
18808
20003
  }
@@ -18956,9 +20151,9 @@ function compile(secrets, options = {}) {
18956
20151
  // src/kernel/scrub-file.ts
18957
20152
  var SCRUB_IDLE_MS = 50;
18958
20153
  var SCRUB_NONBLOCK_MAX = 64 * 1024;
18959
- var encoder5 = new TextEncoder();
20154
+ var encoder6 = new TextEncoder();
18960
20155
  function scrubberOf(secrets, sameLength = false) {
18961
- const usable3 = secrets.filter((s) => encoder5.encode(s.value).length >= MIN_VALUE);
20156
+ const usable3 = secrets.filter((s) => encoder6.encode(s.value).length >= MIN_VALUE);
18962
20157
  return usable3.length > 0 ? compile(usable3, { idleMs: SCRUB_IDLE_MS, sameLength }) : void 0;
18963
20158
  }
18964
20159
  async function writeAll2(file, bytes) {
@@ -18982,7 +20177,7 @@ function scrubbed(inner, scrubber, idleMs = SCRUB_IDLE_MS) {
18982
20177
  let timer;
18983
20178
  let failed4;
18984
20179
  const waiters = /* @__PURE__ */ new Set();
18985
- const quiet2 = () => !busy && pending === 0;
20180
+ const quiet4 = () => !busy && pending === 0;
18986
20181
  const wake = () => {
18987
20182
  for (const waiter of [...waiters]) waiter();
18988
20183
  };
@@ -18999,7 +20194,7 @@ function scrubbed(inner, scrubber, idleMs = SCRUB_IDLE_MS) {
18999
20194
  if (failed4 === void 0) failed4 = err;
19000
20195
  }).finally(() => {
19001
20196
  pending -= 1;
19002
- if (quiet2()) wake();
20197
+ if (quiet4()) wake();
19003
20198
  });
19004
20199
  };
19005
20200
  const settling = (signal) => new Promise((resolve2, reject) => {
@@ -19017,7 +20212,7 @@ function scrubbed(inner, scrubber, idleMs = SCRUB_IDLE_MS) {
19017
20212
  signal?.addEventListener("abort", stop, { once: true });
19018
20213
  });
19019
20214
  const settled = async () => {
19020
- while (!quiet2()) await settling();
20215
+ while (!quiet4()) await settling();
19021
20216
  };
19022
20217
  const changed = async (signal) => {
19023
20218
  const round = new AbortController();
@@ -19033,7 +20228,7 @@ function scrubbed(inner, scrubber, idleMs = SCRUB_IDLE_MS) {
19033
20228
  };
19034
20229
  const turn = async (signal) => {
19035
20230
  for (let waited = false; ; waited = true) {
19036
- if (quiet2() && (pollFile(file).writable || !file.changed)) {
20231
+ if (quiet4() && (pollFile(file).writable || !file.changed)) {
19037
20232
  busy = true;
19038
20233
  return;
19039
20234
  }
@@ -19062,13 +20257,14 @@ function scrubbed(inner, scrubber, idleMs = SCRUB_IDLE_MS) {
19062
20257
  ...bound2(file, "stat"),
19063
20258
  poll: () => {
19064
20259
  const state = pollFile(file);
19065
- return quiet2() ? state : { ...state, writable: false };
20260
+ return quiet4() ? state : { ...state, writable: false };
19066
20261
  },
19067
20262
  changed,
19068
20263
  ...file.tty ? { tty: file.tty } : {},
19069
20264
  identity: file.identity ?? file,
19070
20265
  ...file.clipboard ? { clipboard: file.clipboard } : {},
19071
20266
  ...file.embedder ? { embedder: file.embedder } : {},
20267
+ ...file.device ? { device: file.device } : {},
19072
20268
  ...file.write ? {
19073
20269
  write: async (bytes, signal) => {
19074
20270
  await turn(signal);
@@ -19080,7 +20276,7 @@ function scrubbed(inner, scrubber, idleMs = SCRUB_IDLE_MS) {
19080
20276
  await send2(stream.push(taken), signal);
19081
20277
  } finally {
19082
20278
  busy = false;
19083
- if (quiet2()) wake();
20279
+ if (quiet4()) wake();
19084
20280
  }
19085
20281
  timer = setTimeout(release, idleMs);
19086
20282
  return taken.length;
@@ -19139,9 +20335,9 @@ function scrubStdio(fds, scrubber) {
19139
20335
  // src/kernel/net/sealed-scrubs.ts
19140
20336
  function addTo(tree2, host, secrets) {
19141
20337
  const entry = tree2.get(host) ?? { secrets: [], version: 0, scrubber: void 0 };
19142
- const fresh3 = secrets.filter((s) => !entry.secrets.some((e) => e.value === s.value));
19143
- if (fresh3.length === 0) return;
19144
- entry.secrets = [...entry.secrets, ...fresh3];
20338
+ const fresh4 = secrets.filter((s) => !entry.secrets.some((e) => e.value === s.value));
20339
+ if (fresh4.length === 0) return;
20340
+ entry.secrets = [...entry.secrets, ...fresh4];
19145
20341
  entry.version += 1;
19146
20342
  entry.scrubber = void 0;
19147
20343
  tree2.set(host, entry);
@@ -19304,7 +20500,7 @@ var HEADER = new RegExp(`^header:${TOKEN3}$`);
19304
20500
  var METHOD = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
19305
20501
  var TARGET = /^[\x21-\x7e]+$/;
19306
20502
  var SESSION_EXIT = /^(tailscale|device:[A-Za-z0-9._:-]+)$/;
19307
- var HOST = /^[a-z0-9.:-]+$/;
20503
+ var HOST2 = /^[a-z0-9.:-]+$/;
19308
20504
  var UNSAFE = /[\r\n\0]/;
19309
20505
  var ANCHOR_ID = /^[A-Za-z0-9+/]{43}=$/;
19310
20506
  function verifiedByOk(f) {
@@ -19358,7 +20554,7 @@ function scramOk(f) {
19358
20554
  return texts.every((t) => typeof t === "string" && SCRAM_TEXT.test(t));
19359
20555
  }
19360
20556
  function hostOk(host) {
19361
- return typeof host === "string" && HOST.test(host) && boundHost(host) === host;
20557
+ return typeof host === "string" && HOST2.test(host) && boundHost(host) === host;
19362
20558
  }
19363
20559
  function sessionAskable(f, now) {
19364
20560
  if (!Object.hasOwn(POSITIONS, f.protocol) || typeof f.position !== "string") return false;
@@ -19448,20 +20644,20 @@ var ASK_FIELDS = /* @__PURE__ */ new Set([
19448
20644
  "caller",
19449
20645
  "requester"
19450
20646
  ]);
19451
- var encoder6 = new TextEncoder();
20647
+ var encoder7 = new TextEncoder();
19452
20648
  var decoder3 = new TextDecoder("utf-8", { fatal: true });
19453
20649
  function parseSealed(bytes) {
19454
20650
  try {
19455
20651
  if (bytes.length > SEALED_MAX_BYTES) throw new KernelError("EMSGSIZE");
19456
- let parsed2;
20652
+ let parsed3;
19457
20653
  try {
19458
- parsed2 = JSON.parse(decoder3.decode(bytes));
20654
+ parsed3 = JSON.parse(decoder3.decode(bytes));
19459
20655
  } catch {
19460
20656
  throw new KernelError("EINVAL");
19461
20657
  }
19462
- if (typeof parsed2 !== "object" || parsed2 === null || Array.isArray(parsed2))
20658
+ if (typeof parsed3 !== "object" || parsed3 === null || Array.isArray(parsed3))
19463
20659
  throw new KernelError("EINVAL");
19464
- const req = parsed2;
20660
+ const req = parsed3;
19465
20661
  if (req.v !== 1 || typeof req.op !== "string" || !SEALED_OPS.has(req.op))
19466
20662
  throw new KernelError("EINVAL");
19467
20663
  if (req.op === "materialize" && !materializable(req)) throw new KernelError("EINVAL");
@@ -19557,7 +20753,7 @@ var SealedChannel = class {
19557
20753
  await this.broker.tickets.record(req, reply, caller.pid);
19558
20754
  if (this.inflight !== flight) return;
19559
20755
  this.inflight = void 0;
19560
- if (reply) this.reply = encoder6.encode(serialized(reply));
20756
+ if (reply) this.reply = encoder7.encode(serialized(reply));
19561
20757
  });
19562
20758
  this.inflight = flight;
19563
20759
  return length2;
@@ -19833,7 +21029,7 @@ function shown(text) {
19833
21029
  const chars = [...safe];
19834
21030
  return `'${chars.length > SHOWN_MAX ? `${chars.slice(0, SHOWN_MAX - 1).join("")}\u2026` : safe}'`;
19835
21031
  }
19836
- function unescaped(double) {
21032
+ function unescaped2(double) {
19837
21033
  return double.replace(/\\(["\\$`])/g, "$1");
19838
21034
  }
19839
21035
  function splitWords(text) {
@@ -19849,7 +21045,7 @@ function splitWords(text) {
19849
21045
  word = void 0;
19850
21046
  continue;
19851
21047
  }
19852
- word = (word ?? "") + (single ?? (double !== void 0 ? unescaped(double) : escaped ?? plain3));
21048
+ word = (word ?? "") + (single ?? (double !== void 0 ? unescaped2(double) : escaped ?? plain3));
19853
21049
  }
19854
21050
  if (word !== void 0) words3.push(word);
19855
21051
  return words3;
@@ -19886,7 +21082,7 @@ function splitPatterns(text) {
19886
21082
  }
19887
21083
  word ??= [];
19888
21084
  if (plain3 !== void 0) addPlain(word, plain3);
19889
- else addPart(word, single ?? (double !== void 0 ? unescaped(double) : escaped));
21085
+ else addPart(word, single ?? (double !== void 0 ? unescaped2(double) : escaped));
19890
21086
  }
19891
21087
  if (word !== void 0) words3.push(word);
19892
21088
  return words3;
@@ -19937,13 +21133,13 @@ function commandMatches(cmnd, argv) {
19937
21133
  if (cmnd === "*") return true;
19938
21134
  const [path, ...args] = argv;
19939
21135
  if (path !== cmnd.path) return false;
19940
- const want = cmnd.args;
19941
- if (want === void 0) return true;
21136
+ const want2 = cmnd.args;
21137
+ if (want2 === void 0) return true;
19942
21138
  return globMatch(
19943
- want.length,
21139
+ want2.length,
19944
21140
  args.length,
19945
- (i) => isAny(want[i]),
19946
- (i, j) => wordMatch(want[i], args[j])
21141
+ (i) => isAny(want2[i]),
21142
+ (i, j) => wordMatch(want2[i], args[j])
19947
21143
  );
19948
21144
  }
19949
21145
  function commandText(cmnd) {
@@ -20240,11 +21436,11 @@ function parsePolicy(text, file) {
20240
21436
  const defaults2 = [];
20241
21437
  const errors = [];
20242
21438
  for (const [n, line] of text.split("\n").entries()) {
20243
- const parsed2 = parseLine(line, file);
20244
- if (parsed2 === null) continue;
20245
- if ("error" in parsed2) errors.push({ line: n + 1, message: parsed2.error });
20246
- else if ("defaults" in parsed2) defaults2.push(parsed2.defaults);
20247
- else rules.push(...parsed2.rules);
21439
+ const parsed3 = parseLine(line, file);
21440
+ if (parsed3 === null) continue;
21441
+ if ("error" in parsed3) errors.push({ line: n + 1, message: parsed3.error });
21442
+ else if ("defaults" in parsed3) defaults2.push(parsed3.defaults);
21443
+ else rules.push(...parsed3.rules);
20248
21444
  }
20249
21445
  return { rules, defaults: defaults2, errors };
20250
21446
  }
@@ -20297,11 +21493,11 @@ var REPLAY_TAGS_MAX = 64;
20297
21493
  var REPLAY_ARGV_MAX = 4096;
20298
21494
  var REPLAY_BYTES_MAX = 1024 * 1024;
20299
21495
  var NOT_A_REQUEST = "sudo: that isn't a sudo request this kernel can run";
20300
- function strings(value2, max) {
21496
+ function strings2(value2, max) {
20301
21497
  return Array.isArray(value2) && value2.length <= max && value2.every((s) => typeof s === "string");
20302
21498
  }
20303
21499
  function words(value2) {
20304
- if (!strings(value2, REPLAY_ARGV_MAX) || value2.length === 0) return false;
21500
+ if (!strings2(value2, REPLAY_ARGV_MAX) || value2.length === 0) return false;
20305
21501
  const bytes = value2.reduce((n, s) => n + s.length + 1, 0);
20306
21502
  return bytes <= REPLAY_BYTES_MAX && !value2.some((s) => s.includes("\0"));
20307
21503
  }
@@ -20336,7 +21532,7 @@ function replayOf(value2) {
20336
21532
  const bound3 = filesOf(r.userWritable);
20337
21533
  const named = (s) => typeof s === "string" && s !== "";
20338
21534
  const absolute2 = (s) => typeof s === "string" && s.startsWith("/") && s.length <= PATH_MAX && !s.includes("\0");
20339
- const valid = typeof id2 === "string" && REPLAY_ID.test(id2) && named(user) && named(target) && Number.isInteger(uid) && uid >= 0 && words(argv) && absolute2(path) && absolute2(cwd) && (stdin === "tty" || stdin === "none") && (tag === void 0 || typeof tag === "string") && (tags === void 0 || strings(tags, REPLAY_TAGS_MAX)) && rootOnly2 !== void 0 && bound3 !== void 0;
21535
+ const valid = typeof id2 === "string" && REPLAY_ID.test(id2) && named(user) && named(target) && Number.isInteger(uid) && uid >= 0 && words(argv) && absolute2(path) && absolute2(cwd) && (stdin === "tty" || stdin === "none") && (tag === void 0 || typeof tag === "string") && (tags === void 0 || strings2(tags, REPLAY_TAGS_MAX)) && rootOnly2 !== void 0 && bound3 !== void 0;
20340
21536
  if (!valid) return failed2("EINVAL", NOT_A_REQUEST);
20341
21537
  const all = tags ?? (tag === void 0 ? [] : [tag]);
20342
21538
  return {
@@ -20428,28 +21624,28 @@ function recordedCommand(argv) {
20428
21624
  const [path = "", ...args] = argv;
20429
21625
  return commandText({ path, args: args.map((a) => [a]) });
20430
21626
  }
20431
- function flags(parsed2, arg, next3) {
21627
+ function flags(parsed3, arg, next3) {
20432
21628
  for (let j = 1; j < arg.length; j++) {
20433
21629
  const flag = arg[j];
20434
- if (flag === "n") parsed2.nonInteractive = true;
20435
- else if (flag === "l") parsed2.list = true;
20436
- else if (flag === "v") parsed2.validate = true;
20437
- else if (flag === "k") parsed2.reset = true;
20438
- else if (flag === "K") parsed2.removeAll = true;
21630
+ if (flag === "n") parsed3.nonInteractive = true;
21631
+ else if (flag === "l") parsed3.list = true;
21632
+ else if (flag === "v") parsed3.validate = true;
21633
+ else if (flag === "k") parsed3.reset = true;
21634
+ else if (flag === "K") parsed3.removeAll = true;
20439
21635
  else if (flag !== "u") return `sudo: invalid option -- '${flag}'
20440
21636
  ${USAGE}`;
20441
21637
  else {
20442
21638
  const user = arg.slice(j + 1) || next3;
20443
21639
  if (!user) return `sudo: option requires an argument -- 'u'
20444
21640
  ${USAGE}`;
20445
- parsed2.user = user;
21641
+ parsed3.user = user;
20446
21642
  return arg.slice(j + 1) ? 0 : 1;
20447
21643
  }
20448
21644
  }
20449
21645
  return 0;
20450
21646
  }
20451
21647
  function parseArgs(args) {
20452
- const parsed2 = {
21648
+ const parsed3 = {
20453
21649
  list: false,
20454
21650
  nonInteractive: false,
20455
21651
  validate: false,
@@ -20466,19 +21662,19 @@ function parseArgs(args) {
20466
21662
  break;
20467
21663
  }
20468
21664
  if (!arg.startsWith("-") || arg === "-") break;
20469
- const used2 = flags(parsed2, arg, args[i + 1]);
21665
+ const used2 = flags(parsed3, arg, args[i + 1]);
20470
21666
  if (typeof used2 === "string") return used2;
20471
21667
  i += used2;
20472
21668
  }
20473
- parsed2.command = args.slice(i);
20474
- return usable(parsed2) ? parsed2 : USAGE;
21669
+ parsed3.command = args.slice(i);
21670
+ return usable(parsed3) ? parsed3 : USAGE;
20475
21671
  }
20476
- function usable(parsed2) {
20477
- const command = parsed2.command.length > 0;
20478
- const modes = [parsed2.list, parsed2.validate, parsed2.removeAll].filter(Boolean).length;
20479
- if (modes > 1 || parsed2.removeAll && parsed2.reset) return false;
21672
+ function usable(parsed3) {
21673
+ const command = parsed3.command.length > 0;
21674
+ const modes = [parsed3.list, parsed3.validate, parsed3.removeAll].filter(Boolean).length;
21675
+ if (modes > 1 || parsed3.removeAll && parsed3.reset) return false;
20480
21676
  if (modes === 1) return !command;
20481
- return command || parsed2.reset;
21677
+ return command || parsed3.reset;
20482
21678
  }
20483
21679
  function policyOf(settings) {
20484
21680
  return { type: settings.timestampType, minutes: settings.timestampTimeout };
@@ -20622,28 +21818,28 @@ var Sudo = class {
20622
21818
  };
20623
21819
  }
20624
21820
  async check(cred, call) {
20625
- const lines2 = [];
21821
+ const lines3 = [];
20626
21822
  let ok4 = true;
20627
21823
  const report = ({ path, problems, ok: read }) => {
20628
21824
  for (const problem of problems) {
20629
21825
  const where = problem.line === void 0 ? `${path}: sudo skips it:` : `${path}:${problem.line}:`;
20630
- lines2.push([2, `visudo: ${where} ${problem.message}`]);
21826
+ lines3.push([2, `visudo: ${where} ${problem.message}`]);
20631
21827
  }
20632
- if (read && problems.length === 0) lines2.push([1, `${path}: parsed OK`]);
21828
+ if (read && problems.length === 0) lines3.push([1, `${path}: parsed OK`]);
20633
21829
  if (problems.length > 0) ok4 = false;
20634
21830
  };
20635
21831
  const values = (defaults2) => {
20636
- for (const line of defaultsText(defaults2)) lines2.push([1, line]);
21832
+ for (const line of defaultsText(defaults2)) lines3.push([1, line]);
20637
21833
  };
20638
21834
  if (call.files !== void 0) {
20639
21835
  const defaults2 = [];
20640
21836
  for (const { name: name2, text } of call.files) {
20641
- const parsed2 = parsePolicy(text);
20642
- defaults2.push(...parsed2.defaults);
20643
- report({ path: name2, rules: [], problems: parsed2.errors, ok: true });
21837
+ const parsed3 = parsePolicy(text);
21838
+ defaults2.push(...parsed3.defaults);
21839
+ report({ path: name2, rules: [], problems: parsed3.errors, ok: true });
20644
21840
  }
20645
21841
  if (defaults2.length > 0) values(defaults2);
20646
- return { lines: lines2, ok: ok4 };
21842
+ return { lines: lines3, ok: ok4 };
20647
21843
  }
20648
21844
  if (this.o.mode === "enforce" && cred.euid !== 0) {
20649
21845
  const hint = "check the policy as root (sudo visudo -c), or a file with visudo -c -f <file>";
@@ -20652,7 +21848,7 @@ var Sudo = class {
20652
21848
  const files = await this.policy();
20653
21849
  for (const file of files) report(file);
20654
21850
  values(files.flatMap((f) => f.defaults ?? []));
20655
- return { lines: lines2, ok: ok4 };
21851
+ return { lines: lines3, ok: ok4 };
20656
21852
  }
20657
21853
  async groupIds() {
20658
21854
  return new Map((await this.o.users.groups()).map((g) => [g.name, g.gid]));
@@ -20717,13 +21913,13 @@ var Sudo = class {
20717
21913
  return void 0;
20718
21914
  }
20719
21915
  async request(caller, call, signal) {
20720
- const parsed2 = parseArgs(call.args);
20721
- if (typeof parsed2 === "string") return failed2("EINVAL", parsed2);
21916
+ const parsed3 = parseArgs(call.args);
21917
+ if (typeof parsed3 === "string") return failed2("EINVAL", parsed3);
20722
21918
  if (this.o.mode !== "enforce") {
20723
21919
  const mode = this.o.mode;
20724
- if (parsed2.list) return { list: `sudo: users are '${mode}': commands run as the caller
21920
+ if (parsed3.list) return { list: `sudo: users are '${mode}': commands run as the caller
20725
21921
  ` };
20726
- return parsed2.command.length > 0 ? { run: parsed2.command } : DONE;
21922
+ return parsed3.command.length > 0 ? { run: parsed3.command } : DONE;
20727
21923
  }
20728
21924
  const { cred } = caller;
20729
21925
  const policy = await this.policyRules(caller);
@@ -20736,22 +21932,22 @@ var Sudo = class {
20736
21932
  };
20737
21933
  const applies = await this.applies(self, cred);
20738
21934
  const settings = resolveDefaults(policy.defaults, applies);
20739
- if (parsed2.removeAll) {
21935
+ if (parsed3.removeAll) {
20740
21936
  this.timestamps.remove(owner.uid);
20741
21937
  return DONE;
20742
21938
  }
20743
- if (parsed2.reset && !parsed2.validate && !parsed2.list && parsed2.command.length === 0) {
21939
+ if (parsed3.reset && !parsed3.validate && !parsed3.list && parsed3.command.length === 0) {
20744
21940
  this.timestamps.invalidate(owner, settings.timestampType);
20745
21941
  return DONE;
20746
21942
  }
20747
- const target = await this.lookup(parsed2.user);
20748
- if (!target) return failed2("ENOENT", `sudo: unknown user ${parsed2.user}`);
21943
+ const target = await this.lookup(parsed3.user);
21944
+ if (!target) return failed2("ENOENT", `sudo: unknown user ${parsed3.user}`);
20749
21945
  const root = cred.euid === 0;
20750
21946
  const rules = root ? [] : policy.rules;
20751
21947
  const mine = rules.filter((rule) => applies(rule.who));
20752
- if (parsed2.list) return await this.listed(self, root, mine, settings.matching);
20753
- const session = { caller, self, target, owner, policy: policyOf(settings), parsed: parsed2, signal };
20754
- if (parsed2.validate) return this.validate(session, root, mine, call.cwd);
21948
+ if (parsed3.list) return await this.listed(self, root, mine, settings.matching);
21949
+ const session = { caller, self, target, owner, policy: policyOf(settings), parsed: parsed3, signal };
21950
+ if (parsed3.validate) return this.validate(session, root, mine, call.cwd);
20755
21951
  return this.command(session, root, mine, call);
20756
21952
  }
20757
21953
  async replay(value2) {
@@ -20810,9 +22006,9 @@ var Sudo = class {
20810
22006
  );
20811
22007
  }
20812
22008
  async command(s, root, mine, call) {
20813
- const { caller, self, target, parsed: parsed2 } = s;
22009
+ const { caller, self, target, parsed: parsed3 } = s;
20814
22010
  const { cred } = caller;
20815
- const [word = "", ...args] = parsed2.command;
22011
+ const [word = "", ...args] = parsed3.command;
20816
22012
  const cwd = await this.canonical(call.cwd);
20817
22013
  if (cwd === void 0 || !await this.reachable(cred, cwd)) {
20818
22014
  return failed2(
@@ -20827,7 +22023,7 @@ var Sudo = class {
20827
22023
  const matching = mine.filter(
20828
22024
  (rule) => (rule.target === "ALL" || rule.target === target.name) && (rule.cwd === void 0 || rule.cwd === cwd) && stdinMatches(rule, caller.stdin) && commandMatches(rule.cmnd, argv) && pinned(rule, bound3)
20829
22025
  );
20830
- const grant = () => this.grant(self, target, cred, parsed2.command, path, cwd, call.term, bound3);
22026
+ const grant = () => this.grant(self, target, cred, parsed3.command, path, cwd, call.term, bound3);
20831
22027
  if (root || matching.some((rule) => rule.nopasswd)) return grant();
20832
22028
  const quoted = argv.map(quoteWord).join(" ");
20833
22029
  if (matching.length === 0) {
@@ -20836,38 +22032,38 @@ var Sudo = class {
20836
22032
  `sudo: ${self.name} is not allowed to run ${quoted} as ${target.name}`
20837
22033
  );
20838
22034
  }
20839
- if (!parsed2.reset && this.timestamps.current(s.owner, s.policy, bound3)) {
22035
+ if (!parsed3.reset && this.timestamps.current(s.owner, s.policy, bound3)) {
20840
22036
  this.timestamps.stamp(s.owner, s.policy, bound3);
20841
22037
  this.logged(s, cwd, argv);
20842
22038
  return grant();
20843
22039
  }
20844
- if (parsed2.nonInteractive) return failed2("EPERM", "sudo: a password is required");
22040
+ if (parsed3.nonInteractive) return failed2("EPERM", "sudo: a password is required");
20845
22041
  return this.pendingFor(cred.ruid, async () => {
20846
- const answer2 = await this.ask(s, { argv: parsed2.command, path, cwd, bound: bound3 });
22042
+ const answer2 = await this.ask(s, { argv: parsed3.command, path, cwd, bound: bound3 });
20847
22043
  if ("error" in answer2) return answer2;
20848
22044
  if (await this.canonical(call.cwd) !== cwd || !await this.reachable(cred, cwd)) {
20849
22045
  return failed2("EACCES", `sudo: ${call.cwd} changed while the request waited`);
20850
22046
  }
20851
22047
  const now = await this.bound(path, cwd);
20852
22048
  if (!now) return failed2("ENOENT", `sudo: ${word}: command not found`);
20853
- const shown2 = recordable(cwd, [...parsed2.command, ...Object.keys(bound3)]);
22049
+ const shown2 = recordable(cwd, [...parsed3.command, ...Object.keys(bound3)]);
20854
22050
  const result = answer2.answer === "once" ? grant() : await this.always(self, target, { cwd, argv, bound: bound3 }, now, shown2, grant);
20855
22051
  if (!("error" in result)) this.stamped(s, answer2, bound3);
20856
22052
  return result;
20857
22053
  });
20858
22054
  }
20859
22055
  async validate(s, root, mine, dir) {
20860
- const { self, parsed: parsed2 } = s;
22056
+ const { self, parsed: parsed3 } = s;
20861
22057
  if (root) return DONE;
20862
22058
  if (mine.length === 0) {
20863
22059
  return failed2("EPERM", `Sorry, user ${self.name} may not run sudo on ${this.o.hostname}.`);
20864
22060
  }
20865
22061
  if (mine.every((rule) => rule.nopasswd)) return DONE;
20866
- if (!parsed2.reset && this.timestamps.current(s.owner, s.policy)) {
22062
+ if (!parsed3.reset && this.timestamps.current(s.owner, s.policy)) {
20867
22063
  this.timestamps.stamp(s.owner, s.policy);
20868
22064
  return DONE;
20869
22065
  }
20870
- if (parsed2.nonInteractive) return failed2("EPERM", "sudo: a password is required");
22066
+ if (parsed3.nonInteractive) return failed2("EPERM", "sudo: a password is required");
20871
22067
  const cwd = await this.canonical(dir) ?? normalizePath(dir);
20872
22068
  return this.pendingFor(s.caller.cred.ruid, async () => {
20873
22069
  const answer2 = await this.ask(s, { argv: [], path: "", cwd, bound: {}, validate: true });
@@ -20922,7 +22118,7 @@ var Sudo = class {
20922
22118
  }
20923
22119
  const shown2 = [];
20924
22120
  for (const rule of rules) shown2.push(described(rule, await this.writable(rule)));
20925
- const lines2 = shown2.join("\n");
22121
+ const lines3 = shown2.join("\n");
20926
22122
  const params = defaults2.flatMap((d) => d.params).join(", ");
20927
22123
  const matching = params === "" ? "" : `Matching Defaults entries for ${self.name} on ${host}:
20928
22124
  ${params}
@@ -20930,7 +22126,7 @@ var Sudo = class {
20930
22126
  `;
20931
22127
  return {
20932
22128
  list: `${matching}User ${self.name} may run the following commands on ${host}:
20933
- ${lines2}
22129
+ ${lines3}
20934
22130
  `
20935
22131
  };
20936
22132
  }
@@ -21347,7 +22543,7 @@ async function epollSyscall(req, proc) {
21347
22543
 
21348
22544
  // src/kernel/locks.ts
21349
22545
  var overlaps = (a, b) => a.start < b.end && b.start < a.end;
21350
- var clashes = (lock, owner, want) => lock.owner !== owner && overlaps(lock, want) && (lock.kind === "write" || want.kind === "write");
22546
+ var clashes = (lock, owner, want2) => lock.owner !== owner && overlaps(lock, want2) && (lock.kind === "write" || want2.kind === "write");
21351
22547
  function lockRange(start2, len) {
21352
22548
  if (!Number.isSafeInteger(start2) || !Number.isSafeInteger(len)) throw new KernelError("EINVAL");
21353
22549
  const from = len < 0 ? start2 + len : start2;
@@ -21433,8 +22629,8 @@ var LockTable = class {
21433
22629
  blocked = /* @__PURE__ */ new Map();
21434
22630
  wakers = /* @__PURE__ */ new Map();
21435
22631
  held = /* @__PURE__ */ new Map();
21436
- holder(key, owner, want) {
21437
- return this.records.get(key)?.find((lock) => clashes(lock, owner, want));
22632
+ holder(key, owner, want2) {
22633
+ return this.records.get(key)?.find((lock) => clashes(lock, owner, want2));
21438
22634
  }
21439
22635
  set(key, owner, kind, start2, end) {
21440
22636
  if (kind !== "unlock" && this.holder(key, owner, { key, kind, start: start2, end })) return false;
@@ -21453,10 +22649,10 @@ var LockTable = class {
21453
22649
  return true;
21454
22650
  }
21455
22651
  async wait(key, owner, kind, range2, blocking) {
21456
- const want = { key, kind, ...range2 };
22652
+ const want2 = { key, kind, ...range2 };
21457
22653
  let signal;
21458
22654
  for (; ; ) {
21459
- const holder = this.holder(key, owner, want);
22655
+ const holder = this.holder(key, owner, want2);
21460
22656
  if (!holder) {
21461
22657
  this.set(key, owner, kind, range2.start, range2.end);
21462
22658
  return;
@@ -21464,7 +22660,7 @@ var LockTable = class {
21464
22660
  if (this.waitsOn(holder.owner, owner)) throw new KernelError("EDEADLK");
21465
22661
  signal ??= blocking();
21466
22662
  if (signal.aborted) throw new KernelError("EINTR");
21467
- this.blocked.set(owner, want);
22663
+ this.blocked.set(owner, want2);
21468
22664
  try {
21469
22665
  await this.changed(key, signal);
21470
22666
  } finally {
@@ -21476,9 +22672,9 @@ var LockTable = class {
21476
22672
  const seen = /* @__PURE__ */ new Set();
21477
22673
  for (let at = from; at !== void 0 && !seen.has(at); ) {
21478
22674
  seen.add(at);
21479
- const want = this.blocked.get(at);
21480
- if (!want) return false;
21481
- const holder = this.holder(want.key, at, want);
22675
+ const want2 = this.blocked.get(at);
22676
+ if (!want2) return false;
22677
+ const holder = this.holder(want2.key, at, want2);
21482
22678
  if (!holder) return false;
21483
22679
  if (holder.owner === target) return true;
21484
22680
  at = holder.owner;
@@ -21843,24 +23039,24 @@ function errno2(code, message3) {
21843
23039
  }
21844
23040
  function requestHead(method, url, headers, extra, first = []) {
21845
23041
  if (!TOKEN4.test(method)) throw errno2("EINVAL", `method ${method}`);
21846
- const lines2 = [`${method} ${url.pathname}${url.search} HTTP/1.1`, `host: ${url.host}`];
21847
- for (const [name2, value2] of first) lines2.push(`${name2}: ${value2}`);
23042
+ const lines3 = [`${method} ${url.pathname}${url.search} HTTP/1.1`, `host: ${url.host}`];
23043
+ for (const [name2, value2] of first) lines3.push(`${name2}: ${value2}`);
21848
23044
  for (const [name2, value2] of headers) {
21849
23045
  if (OWN_HEADERS.has(name2.toLowerCase())) continue;
21850
23046
  if (!TOKEN4.test(name2) || !SAFE_VALUE.test(value2)) throw errno2("EINVAL", `header ${name2}`);
21851
- lines2.push(`${name2}: ${value2}`);
23047
+ lines3.push(`${name2}: ${value2}`);
21852
23048
  }
21853
- for (const [name2, value2] of extra) lines2.push(`${name2}: ${value2}`);
21854
- return latin1Bytes(`${lines2.join("\r\n")}\r
23049
+ for (const [name2, value2] of extra) lines3.push(`${name2}: ${value2}`);
23050
+ return latin1Bytes(`${lines3.join("\r\n")}\r
21855
23051
  \r
21856
23052
  `);
21857
23053
  }
21858
23054
  function parseHead(bytes) {
21859
- const [statusLine = "", ...lines2] = latin1(bytes).split(/\r?\n/);
23055
+ const [statusLine = "", ...lines3] = latin1(bytes).split(/\r?\n/);
21860
23056
  const match = /^HTTP\/1\.[01] (\d{3})(?: (.*))?$/.exec(statusLine);
21861
23057
  if (!match) throw errno2("EPROTO", `not an HTTP/1.x response: ${statusLine.slice(0, 80)}`);
21862
23058
  const headers = [];
21863
- for (const line of lines2) {
23059
+ for (const line of lines3) {
21864
23060
  const colon = line.indexOf(":");
21865
23061
  if (colon > 0) headers.push([line.slice(0, colon).trim(), line.slice(colon + 1).trim()]);
21866
23062
  }
@@ -21950,8 +23146,8 @@ var KernelLoopback = class {
21950
23146
  );
21951
23147
  } catch (err) {
21952
23148
  socket.close();
21953
- const refused4 = err instanceof KernelError && err.code === "ECONNREFUSED";
21954
- throw refused4 ? errno2("ECONNREFUSED", `nothing listens on the kernel's port ${port}`) : err;
23149
+ const refused5 = err instanceof KernelError && err.code === "ECONNREFUSED";
23150
+ throw refused5 ? errno2("ECONNREFUSED", `nothing listens on the kernel's port ${port}`) : err;
21955
23151
  }
21956
23152
  signal.addEventListener("abort", () => socket.close(), { once: true });
21957
23153
  return socket;
@@ -22340,9 +23536,9 @@ function pem(der2) {
22340
23536
  for (let i = 0; i < der2.length; i += 32768) {
22341
23537
  b642 += String.fromCharCode(...der2.subarray(i, i + 32768));
22342
23538
  }
22343
- const lines2 = btoa(b642).match(/.{1,64}/g) ?? [];
23539
+ const lines3 = btoa(b642).match(/.{1,64}/g) ?? [];
22344
23540
  return `-----BEGIN CERTIFICATE-----
22345
- ${lines2.join("\n")}
23541
+ ${lines3.join("\n")}
22346
23542
  -----END CERTIFICATE-----
22347
23543
  `;
22348
23544
  }
@@ -23126,13 +24322,13 @@ var HOSTS_PATH = "/etc/hosts";
23126
24322
  function parseHosts(text) {
23127
24323
  const table = /* @__PURE__ */ new Map();
23128
24324
  for (const raw2 of text.split("\n")) {
23129
- const [address, ...names2] = raw2.replace(/#.*/, "").trim().split(/\s+/);
23130
- if (!address || names2.length === 0) continue;
23131
- if (ipv4Bytes(address) === void 0 && ipv6Groups(address) === void 0) continue;
24325
+ const [address2, ...names2] = raw2.replace(/#.*/, "").trim().split(/\s+/);
24326
+ if (!address2 || names2.length === 0) continue;
24327
+ if (ipv4Bytes(address2) === void 0 && ipv6Groups(address2) === void 0) continue;
23132
24328
  for (const name2 of names2) {
23133
24329
  const key = name2.toLowerCase().replace(/\.$/, "");
23134
24330
  const known = table.get(key) ?? [];
23135
- if (!known.includes(address)) known.push(address);
24331
+ if (!known.includes(address2)) known.push(address2);
23136
24332
  table.set(key, known);
23137
24333
  }
23138
24334
  }
@@ -23332,14 +24528,14 @@ var Resolver = class {
23332
24528
  if (hostsEntry(key, this.own) !== void 0) return true;
23333
24529
  return ((await this.hosts?.().catch(() => void 0))?.get(key)?.length ?? 0) > 0;
23334
24530
  }
23335
- async reverse(address) {
23336
- const v6 = ipv6Groups(address)?.join(":");
23337
- const same3 = (a) => a === address || v6 !== void 0 && ipv6Groups(a)?.join(":") === v6;
24531
+ async reverse(address2) {
24532
+ const v6 = ipv6Groups(address2)?.join(":");
24533
+ const same3 = (a) => a === address2 || v6 !== void 0 && ipv6Groups(a)?.join(":") === v6;
23338
24534
  const file = await this.hosts?.().catch(() => void 0);
23339
24535
  for (const table of [file, this.builtin]) {
23340
24536
  for (const [name2, addresses] of table ?? []) if (addresses.some(same3)) return name2;
23341
24537
  }
23342
- if (ipv4Bytes(address)?.[0] === 127) return "localhost";
24538
+ if (ipv4Bytes(address2)?.[0] === 127) return "localhost";
23343
24539
  return void 0;
23344
24540
  }
23345
24541
  async resolve(name2, family, blocking) {
@@ -23393,13 +24589,13 @@ var Resolver = class {
23393
24589
  if (addresses.length > 0) this.remember(id2, addresses, answer2.ttl);
23394
24590
  return addresses;
23395
24591
  }
23396
- usable(name2, address, family) {
23397
- const v4 = ipv4Bytes(address) !== void 0;
23398
- if (!v4 && (family === 4 || !ipv6Groups(address))) return false;
24592
+ usable(name2, address2, family) {
24593
+ const v4 = ipv4Bytes(address2) !== void 0;
24594
+ if (!v4 && (family === 4 || !ipv6Groups(address2))) return false;
23399
24595
  if (v4 && family === 6) return false;
23400
- const kind = this.routes.classify(address);
24596
+ const kind = this.routes.classify(address2);
23401
24597
  if (kind !== "loopback" && kind !== "host" && kind !== "reserved") return true;
23402
- this.log(`slicc-kernel: dropped the uplink's answer ${address} for ${name2}: it is ${kind}`);
24598
+ this.log(`slicc-kernel: dropped the uplink's answer ${address2} for ${name2}: it is ${kind}`);
23403
24599
  return false;
23404
24600
  }
23405
24601
  remember(id2, addresses, ttl) {
@@ -23433,275 +24629,6 @@ function waitFor(lookup2, signal) {
23433
24629
  });
23434
24630
  }
23435
24631
 
23436
- // src/kernel/tty.ts
23437
- var ICRNL = 256;
23438
- var IUTF8 = 16384;
23439
- var OPOST = 1;
23440
- var ONLCR = 4;
23441
- var ISIG = 1;
23442
- var ICANON = 2;
23443
- var ECHO = 8;
23444
- var ECHOE = 16;
23445
- var ECHOCTL = 512;
23446
- var NOFLSH = 128;
23447
- var IEXTEN = 32768;
23448
- var VINTR = 0;
23449
- var VQUIT = 1;
23450
- var VERASE = 2;
23451
- var VKILL = 3;
23452
- var VEOF = 4;
23453
- var VSUSP = 10;
23454
- var VWERASE = 14;
23455
- function defaultTermios() {
23456
- const cCc = new Array(32).fill(0);
23457
- Object.assign(cCc, { [VINTR]: 3, [VQUIT]: 28, [VERASE]: 127, [VKILL]: 21 });
23458
- Object.assign(cCc, { [VEOF]: 4, 6: 1, 8: 17, 9: 19, [VSUSP]: 26 });
23459
- Object.assign(cCc, { 12: 18, 13: 15, [VWERASE]: 23, 15: 22 });
23460
- return {
23461
- c_iflag: ICRNL | 1024 | 8192 | IUTF8,
23462
- c_oflag: OPOST | ONLCR,
23463
- c_cflag: 15 | 48 | 128,
23464
- c_lflag: ISIG | ICANON | ECHO | ECHOE | 32 | ECHOCTL | 2048 | IEXTEN,
23465
- c_cc: cCc
23466
- };
23467
- }
23468
- var encoder7 = new TextEncoder();
23469
- function isContinuation(byte) {
23470
- return (byte & 192) === 128;
23471
- }
23472
- var KernelTty = class {
23473
- termios = defaultTermios();
23474
- cols = 80;
23475
- rows = 24;
23476
- readable = [];
23477
- line = [];
23478
- waiters = [];
23479
- hungUp = false;
23480
- name;
23481
- owner;
23482
- onRead;
23483
- readers = 0;
23484
- screen;
23485
- signal;
23486
- constructor(screen, signal) {
23487
- this.screen = screen;
23488
- this.signal = signal;
23489
- }
23490
- receive(bytes) {
23491
- for (const byte of bytes) this.key(byte);
23492
- this.wake();
23493
- }
23494
- resize(cols, rows) {
23495
- if (cols === this.cols && rows === this.rows) return;
23496
- this.setSize(cols, rows);
23497
- this.signal(SIG.WINCH);
23498
- }
23499
- hangup() {
23500
- this.hungUp = true;
23501
- this.wake();
23502
- }
23503
- signalHangup() {
23504
- this.signal(SIG.HUP);
23505
- }
23506
- setSize(cols, rows) {
23507
- this.cols = cols;
23508
- this.rows = rows;
23509
- }
23510
- tcgets() {
23511
- return { ...this.termios, c_cc: [...this.termios.c_cc] };
23512
- }
23513
- tcsets(termios, flush = false) {
23514
- const wasCanonical = this.canonical;
23515
- this.termios = { ...termios, c_cc: [...termios.c_cc] };
23516
- if (flush) {
23517
- this.line = [];
23518
- this.readable = [];
23519
- }
23520
- if (wasCanonical && !this.canonical && this.line.length > 0) {
23521
- this.readable.push(Uint8Array.from(this.line));
23522
- this.line = [];
23523
- this.wake();
23524
- }
23525
- }
23526
- winsize() {
23527
- return [this.rows, this.cols];
23528
- }
23529
- file() {
23530
- return new OpenFile({
23531
- read: (max, signal) => this.read(max, signal),
23532
- write: async (bytes) => {
23533
- if (this.hungUp) throw new KernelError("EIO");
23534
- this.output(bytes);
23535
- return bytes.length;
23536
- },
23537
- poll: () => ({
23538
- readable: this.readable.length > 0 || this.hungUp,
23539
- writable: true,
23540
- hangup: this.hungUp,
23541
- nread: this.readable.reduce((n, chunk2) => n + (chunk2?.length ?? 0), 0)
23542
- }),
23543
- changed: (signal) => this.changed(signal),
23544
- close: () => {
23545
- },
23546
- tty: this
23547
- });
23548
- }
23549
- get canonical() {
23550
- return (this.termios.c_lflag & ICANON) !== 0;
23551
- }
23552
- cc(slot2) {
23553
- return this.termios.c_cc[slot2] ?? 0;
23554
- }
23555
- key(input) {
23556
- const { c_iflag, c_lflag } = this.termios;
23557
- const byte = input === 13 && c_iflag & ICRNL ? 10 : input;
23558
- if (c_lflag & ISIG && this.signalKey(byte)) return;
23559
- if (!this.canonical) {
23560
- this.readable.push(Uint8Array.of(byte));
23561
- if (c_lflag & ECHO) this.echo(byte);
23562
- return;
23563
- }
23564
- this.edit(byte);
23565
- }
23566
- signalKey(byte) {
23567
- const sig = byte === this.cc(VINTR) ? SIG.INT : byte === this.cc(VQUIT) ? SIG.QUIT : byte === this.cc(VSUSP) ? SIG.TSTP : 0;
23568
- if (!sig || byte === 0) return false;
23569
- if (this.termios.c_lflag & ECHO) this.echo(byte);
23570
- if (!(this.termios.c_lflag & NOFLSH)) {
23571
- this.line = [];
23572
- this.readable = [];
23573
- }
23574
- this.signal(sig);
23575
- return true;
23576
- }
23577
- edit(byte) {
23578
- const echo = (this.termios.c_lflag & ECHO) !== 0;
23579
- if (byte === this.cc(VERASE) || byte === 8) {
23580
- this.rubOut(this.lastCharLength());
23581
- } else if (byte === this.cc(VKILL)) {
23582
- this.rubOut(this.line.length);
23583
- } else if (byte === this.cc(VWERASE)) {
23584
- this.rubOut(this.lastWordLength());
23585
- } else if (byte === this.cc(VEOF)) {
23586
- this.readable.push(this.line.length > 0 ? Uint8Array.from(this.line) : null);
23587
- this.line = [];
23588
- } else if (byte === 10) {
23589
- this.line.push(byte);
23590
- this.readable.push(Uint8Array.from(this.line));
23591
- this.line = [];
23592
- if (echo) this.output(encoder7.encode("\n"));
23593
- } else {
23594
- this.line.push(byte);
23595
- if (echo) this.echo(byte);
23596
- }
23597
- }
23598
- lastWordLength() {
23599
- let end = this.line.length;
23600
- while (end > 0 && this.line[end - 1] === 32) end--;
23601
- while (end > 0 && this.line[end - 1] !== 32) end--;
23602
- return this.line.length - end;
23603
- }
23604
- lastCharLength() {
23605
- const { line } = this;
23606
- let n = Math.min(1, line.length);
23607
- if (this.termios.c_iflag & IUTF8) {
23608
- while (n < line.length && isContinuation(line[line.length - n] ?? 0)) n++;
23609
- }
23610
- return n;
23611
- }
23612
- rubOut(n) {
23613
- const dropped2 = this.line.splice(this.line.length - n, n);
23614
- const utf83 = (this.termios.c_iflag & IUTF8) !== 0;
23615
- const cells = utf83 ? dropped2.filter((b) => !isContinuation(b)).length : dropped2.length;
23616
- if (cells > 0 && this.termios.c_lflag & ECHO) {
23617
- this.output(encoder7.encode("\b \b".repeat(cells)), false);
23618
- }
23619
- }
23620
- echo(byte) {
23621
- if (byte < 32 && byte !== 10 && byte !== 9 && this.termios.c_lflag & ECHOCTL) {
23622
- this.output(Uint8Array.of(94, byte + 64), false);
23623
- return;
23624
- }
23625
- this.output(Uint8Array.of(byte));
23626
- }
23627
- output(bytes, translate2 = true) {
23628
- const { c_oflag } = this.termios;
23629
- if (!translate2 || !(c_oflag & OPOST && c_oflag & ONLCR) || !bytes.includes(10)) {
23630
- this.screen.write(bytes);
23631
- return;
23632
- }
23633
- const out = [];
23634
- for (const byte of bytes) {
23635
- if (byte === 10) out.push(13);
23636
- out.push(byte);
23637
- }
23638
- this.screen.write(Uint8Array.from(out));
23639
- }
23640
- get reading() {
23641
- return this.readers > 0;
23642
- }
23643
- async read(max, signal) {
23644
- this.onRead?.();
23645
- this.readers++;
23646
- try {
23647
- return await this.take(max, signal);
23648
- } finally {
23649
- this.readers--;
23650
- }
23651
- }
23652
- async take(max, signal) {
23653
- while (this.readable.length === 0) {
23654
- if (this.hungUp) return new Uint8Array(0);
23655
- await this.changed(signal);
23656
- }
23657
- const head = this.readable[0];
23658
- if (head === null) {
23659
- this.readable.shift();
23660
- return new Uint8Array(0);
23661
- }
23662
- if (head === void 0) return new Uint8Array(0);
23663
- const chunks = [];
23664
- let n = 0;
23665
- while (this.readable.length > 0 && n < max) {
23666
- const next3 = this.readable[0];
23667
- if (next3 === null || next3 === void 0) break;
23668
- const take = next3.subarray(0, max - n);
23669
- chunks.push(take);
23670
- n += take.length;
23671
- if (take.length < next3.length) this.readable[0] = next3.subarray(take.length);
23672
- else this.readable.shift();
23673
- if (this.canonical) break;
23674
- }
23675
- const out = new Uint8Array(n);
23676
- let at = 0;
23677
- for (const chunk2 of chunks) {
23678
- out.set(chunk2, at);
23679
- at += chunk2.length;
23680
- }
23681
- return out;
23682
- }
23683
- changed(signal) {
23684
- if (signal?.aborted) return Promise.reject(new KernelError("EINTR"));
23685
- return new Promise((resolve2, reject) => {
23686
- const onAbort = () => {
23687
- this.waiters = this.waiters.filter((w) => w !== waiter);
23688
- reject(new KernelError("EINTR"));
23689
- };
23690
- const waiter = () => {
23691
- signal?.removeEventListener("abort", onAbort);
23692
- resolve2();
23693
- };
23694
- this.waiters.push(waiter);
23695
- signal?.addEventListener("abort", onAbort, { once: true });
23696
- });
23697
- }
23698
- wake() {
23699
- const waiters = this.waiters;
23700
- this.waiters = [];
23701
- for (const resolve2 of waiters) resolve2();
23702
- }
23703
- };
23704
-
23705
24632
  // src/kernel/pty.ts
23706
24633
  var PtyPair = class {
23707
24634
  slave;
@@ -23894,6 +24821,7 @@ function ptySyscall(req, ctx) {
23894
24821
  return done4;
23895
24822
  case "pty-ctty": {
23896
24823
  const tty = terminalOf(ctx, req.fd);
24824
+ if (ctx.fds.get(req.fd).file.device) throw new KernelError("EPERM");
23897
24825
  const leader = ctx.jobs?.getsid(ctx.pid, 0) === ctx.pid;
23898
24826
  if (leader && ctx.jobs?.controllingTerminal(ctx.pid) === tty) return done4;
23899
24827
  if (!ctx.jobs?.acquireTerminal(ctx.pid, tty)) throw new KernelError("EPERM");
@@ -24675,10 +25603,10 @@ function basicOf(value2) {
24675
25603
  function placeholdersIn(text) {
24676
25604
  return [...new Set(text.match(ANY_PLACEHOLDER) ?? [])];
24677
25605
  }
24678
- function scan(lines2) {
25606
+ function scan(lines3) {
24679
25607
  const found = [];
24680
- for (let i = 1; i < lines2.length; i++) {
24681
- const m = HEADER_LINE.exec(lines2[i]);
25608
+ for (let i = 1; i < lines3.length; i++) {
25609
+ const m = HEADER_LINE.exec(lines3[i]);
24682
25610
  if (!m) return void 0;
24683
25611
  const value2 = m[2];
24684
25612
  const basic = basicOf(value2);
@@ -24701,10 +25629,10 @@ function usable2(values) {
24701
25629
  }
24702
25630
  async function substituteHead(head, ask) {
24703
25631
  if (!head.endsWith("\r\n\r\n")) return void 0;
24704
- const lines2 = head.slice(0, -4).split("\r\n");
24705
- if (lines2.some((l) => l.includes("\n") || l.includes("\r"))) return void 0;
24706
- const request3 = REQUEST_LINE2.exec(lines2[0]);
24707
- const found = request3 ? scan(lines2) : void 0;
25632
+ const lines3 = head.slice(0, -4).split("\r\n");
25633
+ if (lines3.some((l) => l.includes("\n") || l.includes("\r"))) return void 0;
25634
+ const request3 = REQUEST_LINE2.exec(lines3[0]);
25635
+ const found = request3 ? scan(lines3) : void 0;
24708
25636
  if (!request3 || !found || found.length !== 1) return void 0;
24709
25637
  const at = found[0];
24710
25638
  if (at.placeholders.length > SESSION_PLACEHOLDERS) return void 0;
@@ -24716,8 +25644,8 @@ async function substituteHead(head, ask) {
24716
25644
  );
24717
25645
  if (Object.keys(values).length === 0) return void 0;
24718
25646
  const value2 = at.basic ? `${at.basic.scheme}${btoa(replaced(at.basic.decoded, values))}` : replaced(at.value, values);
24719
- const out = [...lines2];
24720
- out[at.line] = `${lines2[at.line].split(":")[0]}: ${value2}`;
25647
+ const out = [...lines3];
25648
+ out[at.line] = `${lines3[at.line].split(":")[0]}: ${value2}`;
24721
25649
  return { head: `${out.join("\r\n")}\r
24722
25650
  \r
24723
25651
  `, values };
@@ -25040,9 +25968,9 @@ function serverHeader(header4, server) {
25040
25968
  return server.plus && server.binding ? END_POINT : "n,,";
25041
25969
  }
25042
25970
  function rewritten(first, header4) {
25043
- const parsed2 = clientFirstOf(first.data);
25044
- if (!parsed2 || parsed2.header === header4) return first;
25045
- return { mechanism: header4 === END_POINT ? PLUS : PLAIN3, data: `${header4}${parsed2.bare}` };
25971
+ const parsed3 = clientFirstOf(first.data);
25972
+ if (!parsed3 || parsed3.header === header4) return first;
25973
+ return { mechanism: header4 === END_POINT ? PLUS : PLAIN3, data: `${header4}${parsed3.bare}` };
25046
25974
  }
25047
25975
  var PgClient = class {
25048
25976
  clientFirst;
@@ -25062,10 +25990,10 @@ var PgClient = class {
25062
25990
  }
25063
25991
  if (server.sasl && this.clientFirst === void 0) {
25064
25992
  const first = initial(message3);
25065
- const parsed2 = first && clientFirstOf(first.data);
25066
- if (!first || !parsed2) return { bytes: message3, done: true };
25993
+ const parsed3 = first && clientFirstOf(first.data);
25994
+ if (!first || !parsed3) return { bytes: message3, done: true };
25067
25995
  this.clientFirst = first.data;
25068
- this.header = serverHeader(parsed2.header, server);
25996
+ this.header = serverHeader(parsed3.header, server);
25069
25997
  const sent = rewritten(first, this.header);
25070
25998
  if (sent === first) return { bytes: message3, done: false };
25071
25999
  return {
@@ -25230,7 +26158,7 @@ function headEnd2(bytes) {
25230
26158
  }
25231
26159
  return -1;
25232
26160
  }
25233
- function modeOf2(start2) {
26161
+ function modeOf3(start2) {
25234
26162
  const sniffs = [
25235
26163
  ["http1", sniffHttp1(start2)],
25236
26164
  ["smtp", sniffSmtp(start2)],
@@ -25339,7 +26267,7 @@ var SessionWriter = class {
25339
26267
  joined5.set(bytes, this.buffer.length);
25340
26268
  this.buffer.fill(0);
25341
26269
  this.buffer = joined5;
25342
- if (this.mode === "sniff") this.mode = modeOf2(latin12(joined5.subarray(0, 8))) ?? "sniff";
26270
+ if (this.mode === "sniff") this.mode = modeOf3(latin12(joined5.subarray(0, 8))) ?? "sniff";
25343
26271
  if (this.mode === "pg" && !this.sawPg) {
25344
26272
  this.sawPg = true;
25345
26273
  if (!this.s.verified) void this.proof("pg");
@@ -25826,12 +26754,12 @@ function secure(prepared, seal) {
25826
26754
  prepared.own?.release();
25827
26755
  }
25828
26756
  };
25829
- const abandon = () => {
26757
+ const abandon2 = () => {
25830
26758
  if (ran) return;
25831
26759
  prepared.options.session.free();
25832
26760
  prepared.own?.release();
25833
26761
  };
25834
- return { make, abandon };
26762
+ return { make, abandon: abandon2 };
25835
26763
  }
25836
26764
  function supportOf(net) {
25837
26765
  const support = net.tlsClient;
@@ -25848,19 +26776,19 @@ async function uplinkAddress(proc, host) {
25848
26776
  async function connectSecure(proc, socket, host, port, req) {
25849
26777
  const servername = serverName(req.servername || host);
25850
26778
  if (isLoopbackHost(servername) || isLoopbackHost(host)) throw new KernelError("ENOTSUP");
25851
- const address = await uplinkAddress(proc, host);
25852
- const route2 = proc.net.uplinkFor(address);
26779
+ const address2 = await uplinkAddress(proc, host);
26780
+ const route2 = proc.net.uplinkFor(address2);
25853
26781
  if (!route2)
25854
26782
  throw new KernelError("ENOTSUP", "TLS in the kernel needs a destination the uplink routes");
25855
26783
  const support = supportOf(proc.net);
25856
26784
  let info;
25857
- const { make, abandon } = secure(await prepare2(support, req, servername), { proc, port });
26785
+ const { make, abandon: abandon2 } = secure(await prepare2(support, req, servername), { proc, port });
25858
26786
  try {
25859
- await socket.connectSecure({ family: "inet", host: address, port }, route2, async (conn) => {
26787
+ await socket.connectSecure({ family: "inet", host: address2, port }, route2, async (conn) => {
25860
26788
  info = await conn.upgrade(make);
25861
26789
  });
25862
26790
  } finally {
25863
- abandon();
26791
+ abandon2();
25864
26792
  }
25865
26793
  return sessionOf(info, servername);
25866
26794
  }
@@ -25893,14 +26821,14 @@ async function upgradeSecure(proc, socket, req) {
25893
26821
  const host = req.servername || (peer?.family === "inet" ? peer.host : "");
25894
26822
  const servername = serverName(host);
25895
26823
  const port = peer?.family === "inet" ? peer.port : 0;
25896
- const { make, abandon } = secure(await prepare2(supportOf(proc.net), req, servername), {
26824
+ const { make, abandon: abandon2 } = secure(await prepare2(supportOf(proc.net), req, servername), {
25897
26825
  proc,
25898
26826
  port
25899
26827
  });
25900
26828
  try {
25901
26829
  return sessionOf(await socket.upgradeSecure(make), servername);
25902
26830
  } finally {
25903
- abandon();
26831
+ abandon2();
25904
26832
  }
25905
26833
  }
25906
26834
 
@@ -27824,6 +28752,10 @@ var SYSCALL_OPS = /* @__PURE__ */ new Set([
27824
28752
  "fd-open-clipboard",
27825
28753
  "fd-clipboard-abort",
27826
28754
  "fd-open-embedder",
28755
+ "fd-dev-nodes",
28756
+ "fd-open-dev",
28757
+ "fd-dev-ioctl",
28758
+ "fd-dev-meta",
27827
28759
  "tty-get",
27828
28760
  "tty-set",
27829
28761
  "tty-winsz",
@@ -28200,7 +29132,7 @@ var WasmProcess = class {
28200
29132
  async dispatch(req, cancelled) {
28201
29133
  try {
28202
29134
  if (isFdSyscall(req)) return await this.fdSyscall(req, cancelled);
28203
- if (isTtySyscall(req)) return this.ttySyscall(req);
29135
+ if (isTtySyscall(req)) return await this.ttySyscall(req, cancelled);
28204
29136
  if (isJobSyscall(req)) return this.jobSyscall(req);
28205
29137
  if (isSocketSyscall(req)) return await this.socketSyscall(req, cancelled);
28206
29138
  if (isSemSyscall(req)) return await this.semSyscall(req, cancelled);
@@ -28264,7 +29196,7 @@ var WasmProcess = class {
28264
29196
  return owner;
28265
29197
  }
28266
29198
  pathKeys = /* @__PURE__ */ new Map();
28267
- async lockPath(target, want) {
29199
+ async lockPath(target, want2) {
28268
29200
  if (target.fd !== void 0) {
28269
29201
  const st = await this.fds.get(target.fd).file.stat?.();
28270
29202
  if (!st) throw new KernelError("EBADF");
@@ -28274,9 +29206,9 @@ var WasmProcess = class {
28274
29206
  if (!target.path.startsWith("/")) throw new KernelError("EINVAL");
28275
29207
  const path = target.path;
28276
29208
  const g = this.guarded();
28277
- const checked = `${want}:${path}`;
28278
- if (g && want !== 0 && !this.lockChecked.has(checked)) {
28279
- await openable(g, "lock", path, want, false);
29209
+ const checked = `${want2}:${path}`;
29210
+ if (g && want2 !== 0 && !this.lockChecked.has(checked)) {
29211
+ await openable(g, "lock", path, want2, false);
28280
29212
  this.lockChecked.add(checked);
28281
29213
  }
28282
29214
  return path;
@@ -28289,8 +29221,8 @@ var WasmProcess = class {
28289
29221
  const known = file ? fileKeys.get(file) : this.pathKeys.get(target.path ?? "");
28290
29222
  if (kind === "close" && !file && target.path !== void 0) this.pathKeys.delete(target.path);
28291
29223
  if (access2 && !access2.stat) return objectKey(access2);
28292
- const want = kind === "read" ? R_OK : kind === "write" ? W_OK : 0;
28293
- const path = await this.lockPath(target, want);
29224
+ const want2 = kind === "read" ? R_OK : kind === "write" ? W_OK : 0;
29225
+ const path = await this.lockPath(target, want2);
28294
29226
  if (known !== void 0) return known;
28295
29227
  const st = await this.options.fs.stat?.(path).catch((err) => {
28296
29228
  if (!file) throw err;
@@ -28376,7 +29308,7 @@ var WasmProcess = class {
28376
29308
  const file = this.fds.get(req.fd).file;
28377
29309
  const read = req.peek ? file.peek : file.read;
28378
29310
  if (!read) throw new KernelError(req.peek && file.read ? "EOPNOTSUPP" : "EBADF");
28379
- if (file.tty) this.checkForeground(file.tty);
29311
+ if (file.tty && !file.device) this.checkForeground(file.tty);
28380
29312
  if (file.clipboard) return this.readClipboard(file.clipboard, req, cancelled);
28381
29313
  if (file.embedder) return this.readEmbedder(file, req, cancelled);
28382
29314
  if (file instanceof EventFd && req.max < EventFd.SIZE) throw new KernelError("EINVAL");
@@ -28473,6 +29405,46 @@ var WasmProcess = class {
28473
29405
  throw err;
28474
29406
  });
28475
29407
  }
29408
+ async openDev(path, flags2, cancelled) {
29409
+ const devices = this.options.devices;
29410
+ if (!devices) throw new KernelError("ENOENT");
29411
+ const shown2 = await this.options.identity?.();
29412
+ const tags = this.options.embedder?.tagsOf(this.pid);
29413
+ const stamp = {
29414
+ pid: shown2?.pid ?? this.pid,
29415
+ uid: this.cred.euid,
29416
+ gid: this.cred.egid,
29417
+ groups: [...this.cred.groups],
29418
+ users: devices.users,
29419
+ ...tags?.length ? { tag: tags[0], tags: [...tags] } : {}
29420
+ };
29421
+ const guard2 = this.guarded();
29422
+ const file = await devices.open(path, flags2, {
29423
+ stamp,
29424
+ ...guard2 ? { guard: guard2 } : {},
29425
+ signal: this.blockingSignal(cancelled)
29426
+ });
29427
+ return this.fds.install(this.options.outputFilter?.(file) ?? file, 3);
29428
+ }
29429
+ devMeta(path, change) {
29430
+ const devices = this.options.devices;
29431
+ if (!devices) throw new KernelError("ENOENT");
29432
+ devices.meta(path, change, this.guarded());
29433
+ return { ok: true, kind: "void" };
29434
+ }
29435
+ async devIoctl(req, cancelled) {
29436
+ const file = this.fds.get(req.fd).file;
29437
+ if (!file.device) {
29438
+ if (req.request >>> 0 === 21531) return pollFile(file).nread ?? 0;
29439
+ throw new KernelError("ENOTTY");
29440
+ }
29441
+ const result = await file.device.ioctl(
29442
+ req.request >>> 0,
29443
+ req.arg,
29444
+ this.blockingSignal(cancelled)
29445
+ );
29446
+ return result ?? null;
29447
+ }
28476
29448
  async openEmbedder(flags2) {
28477
29449
  const broker = this.options.embedder;
28478
29450
  if (!broker) throw new KernelError("ENOENT");
@@ -28560,11 +29532,11 @@ var WasmProcess = class {
28560
29532
  } else if (req.create) {
28561
29533
  await nodes.onEntry(path, async () => {
28562
29534
  const marks = this.options.owners || plain3 !== void 0;
28563
- const fresh3 = marks && !await present3(fs, path, true);
29535
+ const fresh4 = marks && !await present3(fs, path, true);
28564
29536
  this.fds.installAt(fd, this.openVfsFile(open2, await nodes.identify(path), fs));
28565
29537
  await this.fds.get(fd).file.stat?.();
28566
- if (fresh3 && plain3 !== void 0) await fs.chmod?.(path, plain3);
28567
- else if (fresh3) {
29538
+ if (fresh4 && plain3 !== void 0) await fs.chmod?.(path, plain3);
29539
+ else if (fresh4) {
28568
29540
  await fs.chown?.(path, { ...this.newOwner(req.mode), kind: "new" });
28569
29541
  }
28570
29542
  });
@@ -28663,8 +29635,8 @@ var WasmProcess = class {
28663
29635
  if (req.exclusive) return inParent(g, "open", req.path);
28664
29636
  if (req.created && guard2.created?.take(req.path)) return;
28665
29637
  const access2 = req.flags & WRITE_ACCESS;
28666
- const want = (access2 === 1 ? 0 : R_OK) | (access2 !== 0 || req.truncate ? W_OK : 0);
28667
- await openable(g, "open", req.path, want, req.create === true);
29638
+ const want2 = (access2 === 1 ? 0 : R_OK) | (access2 !== 0 || req.truncate ? W_OK : 0);
29639
+ await openable(g, "open", req.path, want2, req.create === true);
28668
29640
  }
28669
29641
  openTty(name2) {
28670
29642
  const tty = name2 === void 0 ? this.controllingTerminal() : this.options.jobs?.terminalNamed(name2);
@@ -28728,7 +29700,7 @@ var WasmProcess = class {
28728
29700
  }
28729
29701
  terminalByName(name2) {
28730
29702
  const n = ptsNumber(name2);
28731
- const tty = n === void 0 ? this.options.jobs?.terminalNamed(name2) : this.options.ptys?.get(n).slave;
29703
+ const tty = n === void 0 ? this.options.jobs?.terminalNamed(name2) ?? this.options.devices?.openTty(name2) : this.options.ptys?.get(n).slave;
28732
29704
  if (!tty) throw new KernelError("ENOENT");
28733
29705
  return tty;
28734
29706
  }
@@ -28850,6 +29822,16 @@ var WasmProcess = class {
28850
29822
  return { ok: true, kind: "json", json: await this.openClipboard(req.flags) };
28851
29823
  case "fd-open-embedder":
28852
29824
  return { ok: true, kind: "json", json: await this.openEmbedder(req.flags) };
29825
+ case "fd-dev-nodes":
29826
+ return { ok: true, kind: "json", json: this.options.devices?.list() ?? [] };
29827
+ case "fd-open-dev":
29828
+ return { ok: true, kind: "json", json: await this.openDev(req.path, req.flags, cancelled) };
29829
+ case "fd-dev-ioctl":
29830
+ return { ok: true, kind: "json", json: await this.devIoctl(req, cancelled) };
29831
+ case "fd-dev-meta": {
29832
+ const { op: _, path, ...change } = req;
29833
+ return this.devMeta(path, change);
29834
+ }
28853
29835
  case "fd-clipboard-abort": {
28854
29836
  const file = this.fds.get(req.fd);
28855
29837
  file.file.clipboard?.abort();
@@ -28876,6 +29858,7 @@ var WasmProcess = class {
28876
29858
  case "fd-flush": {
28877
29859
  const file = this.fds.get(req.fd).file;
28878
29860
  if (file.flush) await file.flush();
29861
+ await this.options.durable?.();
28879
29862
  return { ok: true, kind: "void" };
28880
29863
  }
28881
29864
  }
@@ -28885,6 +29868,7 @@ var WasmProcess = class {
28885
29868
  const nodes = this.nodes;
28886
29869
  if (req.op === "fd-path-flush") {
28887
29870
  await nodes.flush(await nodes.targetKey(req.path).catch(() => req.path));
29871
+ if (req.durable) await this.options.durable?.();
28888
29872
  } else if (req.op === "fd-path-unlinking")
28889
29873
  await nodes.unlinking(await nodes.entryKey(req.path));
28890
29874
  else if (req.op === "fd-path-unlinked") nodes.unlinked(await nodes.entryKey(req.path));
@@ -28894,6 +29878,11 @@ var WasmProcess = class {
28894
29878
  return { ok: true, kind: "void" };
28895
29879
  }
28896
29880
  const file = this.fds.get(req.fd).file;
29881
+ const device = file.device;
29882
+ if (device && (req.op === "fd-chmod" || req.op === "fd-chown" || req.op === "fd-utimes")) {
29883
+ const { op: _, fd: __, ...change } = req;
29884
+ return this.devMeta(device.path, change);
29885
+ }
28897
29886
  if (!file.pread || !file.pwrite || !file.resize || !file.stat) throw new KernelError("ESPIPE");
28898
29887
  switch (req.op) {
28899
29888
  case "fd-pread":
@@ -29063,14 +30052,19 @@ var WasmProcess = class {
29063
30052
  ...file.fifo !== void 0 ? { fifo: file.fifo } : {}
29064
30053
  };
29065
30054
  }
29066
- ttySyscall(req) {
30055
+ async ttySyscall(req, cancelled) {
29067
30056
  const tty = this.tty(req.fd);
29068
30057
  const jobs = this.options.jobs;
30058
+ const device = this.fds.get(req.fd).file.device;
30059
+ if (device && req.op.startsWith("tty-pgrp")) throw new KernelError("ENOTTY");
29069
30060
  switch (req.op) {
29070
30061
  case "tty-get":
29071
30062
  return { ok: true, kind: "json", json: tty.tcgets() };
29072
30063
  case "tty-set":
29073
- tty.tcsets(req.termios, req.flush === true);
30064
+ if (device) {
30065
+ const how = { flush: req.flush === true, drain: req.drain === true };
30066
+ await device.setTermios(req.termios, how, this.blockingSignal(cancelled));
30067
+ } else tty.tcsets(req.termios, req.flush === true);
29074
30068
  return { ok: true, kind: "void" };
29075
30069
  case "tty-winsz": {
29076
30070
  const size = tty.winsize();
@@ -29758,6 +30752,7 @@ var Dying = class {
29758
30752
  this.hard = setTimeout(finish, KILL_HARD_MS);
29759
30753
  this.arm();
29760
30754
  Atomics.store(header4, SAB_I_KILLED, code);
30755
+ headerNotified(header4, SAB_I_KILLED);
29761
30756
  process.die();
29762
30757
  }
29763
30758
  serve(req, work) {
@@ -29822,11 +30817,13 @@ function notifiers(header4) {
29822
30817
  onPending(sig) {
29823
30818
  Atomics.or(header4, SAB_I_SIGNALS, sigbit(sig));
29824
30819
  Atomics.notify(header4, SAB_I_SIGNALS);
30820
+ headerNotified(header4, SAB_I_SIGNALS, sigbit(sig));
29825
30821
  },
29826
30822
  onAsync() {
29827
30823
  for (const at of [header4, ...asyncFanout.get(header4) ?? []]) {
29828
30824
  Atomics.add(at, SAB_I_ASYNC, 1);
29829
30825
  Atomics.notify(at, SAB_I_ASYNC);
30826
+ headerNotified(at, SAB_I_ASYNC);
29830
30827
  }
29831
30828
  }
29832
30829
  };
@@ -29835,6 +30832,7 @@ function publishStops(process, header4) {
29835
30832
  process.onState((state) => {
29836
30833
  Atomics.store(header4, SAB_I_STOP, state === "stopped" ? 1 : 0);
29837
30834
  Atomics.notify(header4, SAB_I_STOP);
30835
+ headerNotified(header4, SAB_I_STOP);
29838
30836
  });
29839
30837
  }
29840
30838
  function transferOf(opts, lane) {
@@ -29951,12 +30949,14 @@ function processOptions(opts, header4, hooks, created4) {
29951
30949
  ...opts.outputFilter ? { outputFilter: opts.outputFilter } : {},
29952
30950
  ...opts.clipboard ? { clipboard: opts.clipboard, ...clipboardName(opts) } : {},
29953
30951
  ...embedderOptions(opts),
30952
+ devices: opts.devices,
29954
30953
  ...opts.readonlyAt ? { readonlyAt: opts.readonlyAt } : {},
29955
30954
  ...opts.source ? { source: opts.source } : {},
29956
30955
  noLinks: opts.noLinks,
29957
30956
  ...opts.dac ? { guard: { dac: opts.dac, fs: opts.fs, created: created4, ...linksOf(opts) } } : {},
29958
30957
  ...opts.identity ? { identity: opts.identity } : {},
29959
30958
  ...opts.onSyscall ? { onSyscall: opts.onSyscall } : {},
30959
+ ...opts.durable ? { durable: opts.durable } : {},
29960
30960
  ...opts.settling ? { settling: opts.settling } : {},
29961
30961
  ...heldHooks(opts),
29962
30962
  spawner: opts.spawner,
@@ -29985,7 +30985,10 @@ function processOptions(opts, header4, hooks, created4) {
29985
30985
  onReap: opts.onReap,
29986
30986
  resolver: opts.resolver,
29987
30987
  ...notifiers(header4),
29988
- onTimer: (which) => void Atomics.or(header4, SAB_I_TIMERS, 1 << which),
30988
+ onTimer: (which) => {
30989
+ Atomics.or(header4, SAB_I_TIMERS, 1 << which);
30990
+ headerNotified(header4, SAB_I_TIMERS, 1 << which);
30991
+ },
29989
30992
  hasPending: () => unblocked(header4) !== 0 || Atomics.load(header4, SAB_I_TIMERS) !== 0,
29990
30993
  raise: hooks.raise,
29991
30994
  threadKill: hooks.threadKill,
@@ -30702,14 +31705,14 @@ var LockService = class {
30702
31705
  );
30703
31706
  });
30704
31707
  }
30705
- async holder(key, owner, want) {
31708
+ async holder(key, owner, want2) {
30706
31709
  return await this.ask({
30707
31710
  op: "holder",
30708
31711
  key,
30709
31712
  owner,
30710
- kind: want.kind,
30711
- start: want.start,
30712
- end: want.end
31713
+ kind: want2.kind,
31714
+ start: want2.start,
31715
+ end: want2.end
30713
31716
  }) ?? void 0;
30714
31717
  }
30715
31718
  async set(key, owner, kind, start2, end) {
@@ -30988,9 +31991,9 @@ function local(name2) {
30988
31991
  function literal2(name2) {
30989
31992
  return ipv4Bytes(name2) !== void 0 || ipv6Groups(name2) !== void 0;
30990
31993
  }
30991
- function addressData(address, type) {
30992
- if (type === TYPE_A) return ipv4Bytes(address);
30993
- const groups = type === TYPE_AAAA ? ipv6Groups(address) : void 0;
31994
+ function addressData(address2, type) {
31995
+ if (type === TYPE_A) return ipv4Bytes(address2);
31996
+ const groups = type === TYPE_AAAA ? ipv6Groups(address2) : void 0;
30994
31997
  return groups?.flatMap((g) => [g >> 8, g & 255]);
30995
31998
  }
30996
31999
  var DnsStub = class {
@@ -31003,10 +32006,10 @@ var DnsStub = class {
31003
32006
  this.timeoutMs = options.timeoutMs ?? DNS_FORWARD_TIMEOUT_MS;
31004
32007
  }
31005
32008
  async answer(query, udp) {
31006
- const parsed2 = parseQuery(query);
31007
- if (!parsed2) return void 0;
31008
- if (!parsed2.ok) return errorReply2(parsed2.id, parsed2.flags, parsed2.rcode);
31009
- const q = parsed2.question;
32009
+ const parsed3 = parseQuery(query);
32010
+ if (!parsed3) return void 0;
32011
+ if (!parsed3.ok) return errorReply2(parsed3.id, parsed3.flags, parsed3.rcode);
32012
+ const q = parsed3.question;
31010
32013
  const reply = await this.reply(query, q).catch(
31011
32014
  () => answerReply(query, q, SERVFAIL, [], false)
31012
32015
  );
@@ -31015,8 +32018,8 @@ var DnsStub = class {
31015
32018
  async reply(query, q) {
31016
32019
  if (q.klass !== CLASS_IN || literal2(q.name)) return this.forward(query, q);
31017
32020
  if (q.type === TYPE_PTR) {
31018
- const address = reverseAddress(q.name);
31019
- const name2 = address !== void 0 ? await this.reverse(address) : void 0;
32021
+ const address2 = reverseAddress(q.name);
32022
+ const name2 = address2 !== void 0 ? await this.reverse(address2) : void 0;
31020
32023
  if (name2 !== void 0)
31021
32024
  return answerReply(query, q, NOERROR, [record2(TYPE_PTR, encodeName(name2))], true);
31022
32025
  return this.forward(query, q);
@@ -31046,8 +32049,8 @@ var DnsStub = class {
31046
32049
  known(name2) {
31047
32050
  return this.resolver.known(name2).catch(() => false);
31048
32051
  }
31049
- reverse(address) {
31050
- return this.resolver.reverse(address).catch(() => void 0);
32052
+ reverse(address2) {
32053
+ return this.resolver.reverse(address2).catch(() => void 0);
31051
32054
  }
31052
32055
  async forward(query, q) {
31053
32056
  if (!this.forwarder) return answerReply(query, q, SERVFAIL, [], false);
@@ -31226,7 +32229,7 @@ function honors(traits, redirect) {
31226
32229
  const raw2 = traits.manualRedirects === true && (hops === void 0 || hops === false);
31227
32230
  return redirect === "manual" && raw2;
31228
32231
  }
31229
- function refused3(message3) {
32232
+ function refused4(message3) {
31230
32233
  return new TransportError(message3, 502, void 0, "transport");
31231
32234
  }
31232
32235
  var RemoteTransport = class {
@@ -31317,7 +32320,7 @@ var RemoteTransport = class {
31317
32320
  const { signal, redirect } = request3;
31318
32321
  signal.throwIfAborted();
31319
32322
  if (unfollowed2(redirect) && !honors(this.traits, redirect)) {
31320
- throw refused3(`this transport cannot honor redirect: ${redirect}`);
32323
+ throw refused4(`this transport cannot honor redirect: ${redirect}`);
31321
32324
  }
31322
32325
  let finished = false;
31323
32326
  const abort = () => {
@@ -31368,7 +32371,7 @@ var RemoteTransport = class {
31368
32371
  };
31369
32372
  if (unfollowed2(redirect) && (redirected2 || redirects?.length)) {
31370
32373
  await cancel();
31371
- throw refused3(`this transport followed a redirect despite redirect: ${redirect}`);
32374
+ throw refused4(`this transport followed a redirect despite redirect: ${redirect}`);
31372
32375
  }
31373
32376
  return {
31374
32377
  ...url !== void 0 ? { url } : {},
@@ -31858,6 +32861,7 @@ var SETUP_OPS = /* @__PURE__ */ new Set([
31858
32861
  "proc-list",
31859
32862
  "proc-identity",
31860
32863
  "fd-info",
32864
+ "fd-dev-nodes",
31861
32865
  "sig-mask",
31862
32866
  "sig-inherited",
31863
32867
  "proc-setpgid",
@@ -31954,8 +32958,8 @@ var WasmMemories = class {
31954
32958
  const learned = this.learned;
31955
32959
  if (!learned) return this.base;
31956
32960
  const steps = Math.floor((this.now() - learned.at) / DECAY_MS);
31957
- const raised = learned.ceiling + steps * DECAY_STEP;
31958
- if (raised < (this.base ?? DEFAULT_CEILING)) return raised;
32961
+ const raised2 = learned.ceiling + steps * DECAY_STEP;
32962
+ if (raised2 < (this.base ?? DEFAULT_CEILING)) return raised2;
31959
32963
  this.learned = void 0;
31960
32964
  return this.base;
31961
32965
  }
@@ -32098,9 +33102,9 @@ function serveFilesystem(port, handlers, capabilities = {}, options = {}) {
32098
33102
  let open2 = false;
32099
33103
  const reply = (message3, transfer = []) => port.postMessage(message3, transfer);
32100
33104
  async function hello(message3) {
32101
- const refused4 = driverVersionError(message3.protocol);
32102
- if (refused4) {
32103
- reply({ hello: { protocol: DRIVER_PROTOCOL, error: refused4, errno: "EPROTO" } });
33105
+ const refused5 = driverVersionError(message3.protocol);
33106
+ if (refused5) {
33107
+ reply({ hello: { protocol: DRIVER_PROTOCOL, error: refused5, errno: "EPROTO" } });
32104
33108
  return;
32105
33109
  }
32106
33110
  try {
@@ -32406,7 +33410,7 @@ function unescape(field4) {
32406
33410
  );
32407
33411
  }
32408
33412
  function parseFstab(text) {
32409
- const lines2 = [];
33413
+ const lines3 = [];
32410
33414
  text.split("\n").forEach((raw2, index) => {
32411
33415
  const content = raw2.replace(/#.*$/, "").trim();
32412
33416
  if (!content) return;
@@ -32415,12 +33419,12 @@ function parseFstab(text) {
32415
33419
  if (options.split(",").includes("noauto")) return;
32416
33420
  const spec = { source, target, type, options: {} };
32417
33421
  try {
32418
- lines2.push({ line: index + 1, spec: { ...spec, options: parseMountOptions(options) } });
33422
+ lines3.push({ line: index + 1, spec: { ...spec, options: parseMountOptions(options) } });
32419
33423
  } catch (err) {
32420
- lines2.push({ line: index + 1, spec, invalid: err });
33424
+ lines3.push({ line: index + 1, spec, invalid: err });
32421
33425
  }
32422
33426
  });
32423
- return lines2;
33427
+ return lines3;
32424
33428
  }
32425
33429
  function codeOf6(err) {
32426
33430
  const code = err?.code;
@@ -32438,20 +33442,20 @@ function wait(ms, signal) {
32438
33442
  signal.addEventListener("abort", done5, { once: true });
32439
33443
  });
32440
33444
  }
32441
- async function mountFstab(lines2, mount, signal, retries = FSTAB_RETRIES, discard = () => {
33445
+ async function mountFstab(lines3, mount, signal, retries = FSTAB_RETRIES, discard = () => {
32442
33446
  }, settled = () => {
32443
33447
  }) {
32444
33448
  return Promise.all(
32445
- lines2.map(async (each) => {
33449
+ lines3.map(async (each) => {
32446
33450
  const result = await mountLine(each, mount, signal, retries, discard);
32447
33451
  settled(each, result);
32448
33452
  return result;
32449
33453
  })
32450
33454
  );
32451
33455
  }
32452
- async function mountLine({ line, spec, invalid }, mount, signal, retries, discard) {
32453
- let failed4 = invalid;
32454
- for (let attempt = 0; !invalid && attempt <= retries.length && !signal.aborted; attempt++) {
33456
+ async function mountLine({ line, spec, invalid: invalid2 }, mount, signal, retries, discard) {
33457
+ let failed4 = invalid2;
33458
+ for (let attempt = 0; !invalid2 && attempt <= retries.length && !signal.aborted; attempt++) {
32455
33459
  try {
32456
33460
  const entry = await mount(spec);
32457
33461
  if (!signal.aborted) return { line, target: spec.target, entry };
@@ -32619,14 +33623,14 @@ var RESTORE_AGAIN_MS = 3e4;
32619
33623
  function hostfsHandlers(current, againMs = RESTORE_AGAIN_MS) {
32620
33624
  const handles = /* @__PURE__ */ new Map();
32621
33625
  let nextFh = 0;
32622
- const fresh3 = (remote) => {
33626
+ const fresh4 = (remote) => {
32623
33627
  if (remote.client.token === remote.token && !remote.client.gone) return remote;
32624
33628
  throw fsError2("ESTALE", "the folder was granted again, so this open file is gone");
32625
33629
  };
32626
33630
  const live2 = (fh) => {
32627
33631
  const remote = handles.get(fh);
32628
33632
  if (!remote) throw fsError2("EBADF", `handle ${fh}`);
32629
- return fresh3(remote);
33633
+ return fresh4(remote);
32630
33634
  };
32631
33635
  const call = (op, body = {}) => current().call(op, body);
32632
33636
  const same3 = (was, mode, seen) => seen?.mode === (mode | 128) && (was.ino !== void 0 && seen.ino !== void 0 ? seen.ino === was.ino : seen.size === was.size && seen.mtime === was.mtime);
@@ -32708,7 +33712,7 @@ function hostfsHandlers(current, againMs = RESTORE_AGAIN_MS) {
32708
33712
  if (!remote) throw fsError2("EBADF", `handle ${fh}`);
32709
33713
  handles.delete(fh);
32710
33714
  try {
32711
- await fresh3(remote).client.call("release", { fh: remote.fh }, true);
33715
+ await fresh4(remote).client.call("release", { fh: remote.fh }, true);
32712
33716
  } finally {
32713
33717
  if (remote.restore) await settle3(current(), remote.restore);
32714
33718
  }
@@ -32758,7 +33762,7 @@ async function resize(h, path, size) {
32758
33762
  await h.release(fh);
32759
33763
  }
32760
33764
  }
32761
- function sleep(ms, signal) {
33765
+ function sleep2(ms, signal) {
32762
33766
  return new Promise((resolve2) => {
32763
33767
  const done5 = () => {
32764
33768
  clearTimeout(timer);
@@ -32786,22 +33790,22 @@ function keepWatching(loop, signal) {
32786
33790
  const stop = () => session2.abort();
32787
33791
  signal.addEventListener("abort", stop);
32788
33792
  let timer;
32789
- const quiet2 = () => {
33793
+ const quiet4 = () => {
32790
33794
  clearTimeout(timer);
32791
33795
  timer = setTimeout(stop, silenceMs);
32792
33796
  };
32793
33797
  let opened2 = false;
32794
33798
  try {
32795
33799
  const client = await loop.connect();
32796
- quiet2();
33800
+ quiet4();
32797
33801
  await client.watch(
32798
33802
  session2.signal,
32799
33803
  (event) => {
32800
- quiet2();
33804
+ quiet4();
32801
33805
  if (!event.ping) loop.event(event);
32802
33806
  },
32803
33807
  () => {
32804
- quiet2();
33808
+ quiet4();
32805
33809
  opened2 = true;
32806
33810
  up = true;
32807
33811
  loop.up(client);
@@ -32830,7 +33834,7 @@ function keepWatching(loop, signal) {
32830
33834
  loop.down();
32831
33835
  }
32832
33836
  ready2.resolve();
32833
- await sleep(wait2, signal);
33837
+ await sleep2(wait2, signal);
32834
33838
  wait2 = Math.min(wait2 * 2, most);
32835
33839
  }
32836
33840
  })();
@@ -33085,12 +34089,12 @@ function grantConnect(hook, fetch2, liveness = {}) {
33085
34089
  return new HostfsClient(first, grant, fetch2);
33086
34090
  };
33087
34091
  }
33088
- async function openHostfs(spec, connect2, timing = {}) {
34092
+ async function openHostfs(spec, connect2, timing = {}, ports = messageChannel) {
33089
34093
  const readonly2 = spec.options?.ro !== void 0;
33090
- const { port1, port2 } = new MessageChannel();
34094
+ const { port1, port2 } = ports();
33091
34095
  const slot2 = mediumSlot(
33092
34096
  async (err) => unreachable(err),
33093
- () => watching.kick()
34097
+ () => watching2.kick()
33094
34098
  );
33095
34099
  const stop = new AbortController();
33096
34100
  let active;
@@ -33110,7 +34114,7 @@ async function openHostfs(spec, connect2, timing = {}) {
33110
34114
  ...readonly2 ? { readonly: true } : {}
33111
34115
  }
33112
34116
  );
33113
- const watching = keepWatching(
34117
+ const watching2 = keepWatching(
33114
34118
  {
33115
34119
  connect: () => connect2(spec.source, { readonly: readonly2 }),
33116
34120
  up(client) {
@@ -33127,7 +34131,7 @@ async function openHostfs(spec, connect2, timing = {}) {
33127
34131
  },
33128
34132
  stop.signal
33129
34133
  );
33130
- await watching.ready;
34134
+ await watching2.ready;
33131
34135
  return {
33132
34136
  port: port1,
33133
34137
  present: slot2.present,
@@ -33139,6 +34143,26 @@ async function openHostfs(spec, connect2, timing = {}) {
33139
34143
  };
33140
34144
  }
33141
34145
 
34146
+ // src/mount/in-process.ts
34147
+ var IN_PROCESS_DRIVER = /* @__PURE__ */ Symbol.for(
34148
+ "slicc-kernel.mount.in-process"
34149
+ );
34150
+ function openInProcess(spec, ports = messageChannel) {
34151
+ const driver = spec[IN_PROCESS_DRIVER];
34152
+ if (!driver) return void 0;
34153
+ const { port1, port2 } = ports();
34154
+ driver.served?.(
34155
+ serveFilesystem(port2, driver.handlers, driver.capabilities ?? {}, { owned: true })
34156
+ );
34157
+ return {
34158
+ port: port1,
34159
+ dispose: () => {
34160
+ port1.close();
34161
+ port2.close();
34162
+ }
34163
+ };
34164
+ }
34165
+
33142
34166
  // src/mount/media.ts
33143
34167
  var MEDIA_STORE = "handles";
33144
34168
  function memoryMedia() {
@@ -33598,13 +34622,29 @@ function foreignImports(bytes) {
33598
34622
  return {};
33599
34623
  }
33600
34624
  var LIBC_MARK = /^wasix-sysroot \d{4}\.\d+\.\d+-(\d+)/;
33601
- function libcVersion(module) {
33602
- for (const section of WebAssembly.Module.customSections(module, "slicc.libc")) {
34625
+ function libcOf(sections) {
34626
+ for (const section of sections) {
33603
34627
  const found = LIBC_MARK.exec(new TextDecoder().decode(section));
33604
34628
  if (found) return Number(found[1]);
33605
34629
  }
33606
34630
  return void 0;
33607
34631
  }
34632
+ function customSectionsOf(bytes, wanted) {
34633
+ const found = [];
34634
+ const r = new Reader(bytes);
34635
+ r.at = 8;
34636
+ while (r.at < bytes.length) {
34637
+ const id2 = r.byte();
34638
+ const size = r.u32();
34639
+ const end = r.at + size;
34640
+ if (id2 === 0 && r.name() === wanted) found.push(bytes.subarray(r.at, end));
34641
+ r.at = end;
34642
+ }
34643
+ return found;
34644
+ }
34645
+ function libcVersionOf(bytes) {
34646
+ return libcOf(customSectionsOf(bytes, "slicc.libc"));
34647
+ }
33608
34648
 
33609
34649
  // src/refused-command.ts
33610
34650
  var REFUSED_PATH = "/usr/lib/slicc/refused";
@@ -34035,8 +35075,8 @@ function cronPath(path) {
34035
35075
  );
34036
35076
  }
34037
35077
  var ETC_HOSTNAME_LIBC = 42;
34038
- function readsEtcHostname(program) {
34039
- return program.abi === "wasi" && (libcVersion(program.module) ?? 0) >= ETC_HOSTNAME_LIBC;
35078
+ function readsEtcHostname(program, libc) {
35079
+ return program.abi === "wasi" && (libc ?? 0) >= ETC_HOSTNAME_LIBC;
34040
35080
  }
34041
35081
  function setOrDrop(env, key, value2) {
34042
35082
  if (value2 === void 0) delete env[key];
@@ -34194,6 +35234,8 @@ function addTimes(into, pid, t) {
34194
35234
  into.set(pid, { utime: at.utime + t.utime, stime: at.stime + t.stime });
34195
35235
  }
34196
35236
  var Launcher = class {
35237
+ emscripten;
35238
+ admit;
34197
35239
  fs;
34198
35240
  processFs;
34199
35241
  noLinksFs;
@@ -34204,8 +35246,10 @@ var Launcher = class {
34204
35246
  unguardedRoot;
34205
35247
  writers;
34206
35248
  unlinkOwnerOption;
35249
+ durable;
34207
35250
  base;
34208
35251
  createWorker;
35252
+ compile;
34209
35253
  moduleUrl;
34210
35254
  moduleUrls = /* @__PURE__ */ new Map();
34211
35255
  urlsInUse = /* @__PURE__ */ new Map();
@@ -34220,6 +35264,7 @@ var Launcher = class {
34220
35264
  unwatchScopes = () => void 0;
34221
35265
  warned = /* @__PURE__ */ new Set();
34222
35266
  compiled = /* @__PURE__ */ new Map();
35267
+ libcs = /* @__PURE__ */ new WeakMap();
34223
35268
  texts = /* @__PURE__ */ new Map();
34224
35269
  revocations = 0;
34225
35270
  integrity;
@@ -34288,6 +35333,9 @@ var Launcher = class {
34288
35333
  onMountPending;
34289
35334
  removable = /* @__PURE__ */ new Map();
34290
35335
  hostfs;
35336
+ get ports() {
35337
+ return this.hostfs.ports ?? messageChannel;
35338
+ }
34291
35339
  fstabRetries;
34292
35340
  inserted = /* @__PURE__ */ new Map();
34293
35341
  openFiles = /* @__PURE__ */ new Set();
@@ -34314,6 +35362,7 @@ var Launcher = class {
34314
35362
  scrubs = /* @__PURE__ */ new Map();
34315
35363
  clipboard;
34316
35364
  embedder;
35365
+ devices;
34317
35366
  rootFs;
34318
35367
  fileWatches;
34319
35368
  nextPid = 1e3;
@@ -34338,6 +35387,7 @@ var Launcher = class {
34338
35387
  );
34339
35388
  this.embedder = this.embedderBroker(options.embedder);
34340
35389
  this.embedder.denied = options.onDenial;
35390
+ this.devices = this.deviceNodes(options.devices);
34341
35391
  this.sealed = new SealedBroker(
34342
35392
  options.sealed,
34343
35393
  this.usersMode,
@@ -34369,8 +35419,8 @@ var Launcher = class {
34369
35419
  this.mounted = this.mounts.wrap(options.fs);
34370
35420
  this.base = this.rooted(this.mounted);
34371
35421
  this.createWorker = options.createWorker;
34372
- this.moduleUrl = options.moduleUrl;
34373
- this.createDriverWorker = options.createDriverWorker;
35422
+ ({ compile: this.compile, emscripten: this.emscripten, admit: this.admit } = options);
35423
+ ({ moduleUrl: this.moduleUrl, createDriverWorker: this.createDriverWorker } = options);
34374
35424
  this.media = options.media ?? memoryMedia();
34375
35425
  this.onMountPending = options.onMountPending;
34376
35426
  this.hostfs = options;
@@ -34443,7 +35493,7 @@ var Launcher = class {
34443
35493
  );
34444
35494
  this.fs = this.processChain(fs, this.nodes, this.unlinked);
34445
35495
  this.writerTags = writerTags(options.protect);
34446
- this.unlinkOwnerOption = options.unlinkOwner;
35496
+ ({ unlinkOwner: this.unlinkOwnerOption, durable: this.durable } = options);
34447
35497
  if (this.writerTags.size > 0 && options.fs.protect && !options.fs.unguarded) {
34448
35498
  throw new TypeError("protect.writers needs a root file system with an unguarded view");
34449
35499
  }
@@ -34553,16 +35603,16 @@ var Launcher = class {
34553
35603
  if (!found) {
34554
35604
  found = this.swaps.settled().then(() => this.trustedAppended()).then(async (appended2) => {
34555
35605
  const tiers = await this.tiers(scope, appended2);
34556
- const refused4 = [];
35606
+ const refused5 = [];
34557
35607
  const commands = await scanCommands(
34558
35608
  this.scanned,
34559
35609
  tiers,
34560
35610
  tiers.length - appended2.length,
34561
35611
  void 0,
34562
- refused4,
35612
+ refused5,
34563
35613
  await this.globalRoots(scope)
34564
35614
  );
34565
- this.refusedOf.set(commands, refused4.map(refusing));
35615
+ this.refusedOf.set(commands, refused5.map(refusing));
34566
35616
  return commands;
34567
35617
  }).then(
34568
35618
  (commands) => this.refusals(commands).set(SUDO_COMMAND.name, SUDO_COMMAND).set(VISUDO_COMMAND.name, VISUDO_COMMAND).set(CRONTAB_COMMAND.name, CRONTAB_COMMAND).set(SEALED_COMMAND.name, SEALED_COMMAND)
@@ -34769,14 +35819,14 @@ var Launcher = class {
34769
35819
  return await this.commandAt(path, scope) ?? await this.refusedAt(path, name2, scope);
34770
35820
  }
34771
35821
  async refusedAt(path, name2, scope) {
34772
- const refused4 = this.refusedOf.get(await this.commands(scope)) ?? [];
34773
- if (refused4.length === 0) return void 0;
35822
+ const refused5 = this.refusedOf.get(await this.commands(scope)) ?? [];
35823
+ if (refused5.length === 0) return void 0;
34774
35824
  const st = await this.base.stat(path).catch(() => void 0);
34775
35825
  if (!st?.isFile) return void 0;
34776
35826
  const real = await physicalPathAsync(this.base, path).catch(() => path);
34777
35827
  const same3 = async (own) => own === path || await physicalPathAsync(this.base, own).catch(() => own) === real;
34778
35828
  const owners = [];
34779
- for (const c of refused4) {
35829
+ for (const c of refused5) {
34780
35830
  const origin = c.origin;
34781
35831
  for (const own of [origin.glue, origin.wasm, ...origin.variants ?? []]) {
34782
35832
  if (!await same3(own)) continue;
@@ -34786,11 +35836,11 @@ var Launcher = class {
34786
35836
  }
34787
35837
  const stem = name2.replace(/\.wasm$/, "");
34788
35838
  const named = owners.find((c) => c.name === name2) ?? owners.find((c) => c.name === stem);
34789
- return named ?? owners[0] ?? await this.refusedCopy(real, name2, refused4);
35839
+ return named ?? owners[0] ?? await this.refusedCopy(real, name2, refused5);
34790
35840
  }
34791
- async refusedCopy(real, name2, refused4) {
35841
+ async refusedCopy(real, name2, refused5) {
34792
35842
  const dir = real.slice(0, real.lastIndexOf("/"));
34793
- for (const c of refused4) {
35843
+ for (const c of refused5) {
34794
35844
  const origin = c.origin;
34795
35845
  if (origin.abi !== "emscripten" || origin.script || c.name !== name2) continue;
34796
35846
  const own = await physicalPathAsync(this.base, origin.glue).catch(() => origin.glue);
@@ -34957,8 +36007,8 @@ var Launcher = class {
34957
36007
  const via = planned?.via ?? [];
34958
36008
  for (const [i, file] of via.entries()) {
34959
36009
  if (!byPath(file)) continue;
34960
- const want = i < via.length - 1 ? R_OK | X_OK : X_OK;
34961
- await need(g, "exec", this.fs.resolvePath(req.cwd, file), want);
36010
+ const want2 = i < via.length - 1 ? R_OK | X_OK : X_OK;
36011
+ await need(g, "exec", this.fs.resolvePath(req.cwd, file), want2);
34962
36012
  }
34963
36013
  for (const bin of planned?.bins ?? []) await need(g, "exec", bin, R_OK | X_OK);
34964
36014
  if (planned?.target.copy) await need(g, "exec", planned.target.copy, R_OK | X_OK);
@@ -34998,12 +36048,12 @@ var Launcher = class {
34998
36048
  return void 0;
34999
36049
  }
35000
36050
  async planOne(req, { ppid, cred, scope }, catalogOnly = false) {
35001
- const refused4 = (err) => {
36051
+ const refused5 = (err) => {
35002
36052
  throw codeOf8(err) === "EACCES" ? new SpawnError("EACCES") : err;
35003
36053
  };
35004
- const file = await this.execFile(req.file, req.cwd, this.execGuard(cred, ppid)).catch(refused4);
36054
+ const file = await this.execFile(req.file, req.cwd, this.execGuard(cred, ppid)).catch(refused5);
35005
36055
  const planned = await this.plan(file, req.argv, req.cwd, scope, req.argv0, catalogOnly);
35006
- await this.mayExec(cred, { ...req, file, pid: ppid }, planned).catch(refused4);
36056
+ await this.mayExec(cred, { ...req, file, pid: ppid }, planned).catch(refused5);
35007
36057
  if (planned) return planned;
35008
36058
  throw new SpawnError(catalogOnly ? "ENOENT" : await this.unrunnable(file, req.cwd, scope));
35009
36059
  }
@@ -35229,9 +36279,12 @@ var Launcher = class {
35229
36279
  const bytes = sum === void 0 ? read : await this.pinnedBytes(pin, read);
35230
36280
  const memory = importedMemory(bytes);
35231
36281
  const foreign = foreignImports(bytes);
35232
- const compiled = await WebAssembly.compile(bytes);
36282
+ const libc = libcVersionOf(bytes);
36283
+ const named = customSectionsOf(bytes, "name").length > 0;
36284
+ const compiled = this.compile ? await this.compile(bytes, key) : await WebAssembly.compile(bytes);
36285
+ if (libc !== void 0) this.libcs.set(compiled, libc);
35233
36286
  return {
35234
- value: { module: compiled, ...memory ? { memory } : {}, foreign },
36287
+ value: { module: compiled, ...memory ? { memory } : {}, foreign, named },
35235
36288
  key: sum === void 0 ? readKey : key
35236
36289
  };
35237
36290
  });
@@ -35307,8 +36360,7 @@ var Launcher = class {
35307
36360
  if (this.urlsInUse.get(held.made.url) === held) this.urlsInUse.delete(held.made.url);
35308
36361
  held.made.revoke();
35309
36362
  }
35310
- async names(path, module) {
35311
- if (WebAssembly.Module.customSections(module, "name").length > 0) return void 0;
36363
+ async names(path) {
35312
36364
  const beside = `${path}.names`;
35313
36365
  if (await this.base.exists(beside)) return beside;
35314
36366
  const root = PACKAGE_ROOT.exec(path)?.[1];
@@ -35381,6 +36433,10 @@ var Launcher = class {
35381
36433
  const { url, source } = this.urlFor(await this.text(target.wasm, caller, asked));
35382
36434
  return { abi: "js", glue: "", url, path: target.wasm, ...source ? { source } : {} };
35383
36435
  }
36436
+ if (target.abi !== "wasi" && this.emscripten === "kernel") {
36437
+ const { module: module2 } = await this.module(target.wasm, caller, asked && modulePath(asked));
36438
+ return { abi: "emscripten", emscripten: "kernel", glue: "", module: module2, path: target.glue };
36439
+ }
35384
36440
  if (target.abi !== "wasi") {
35385
36441
  const [glue, { module: module2 }] = await Promise.all([
35386
36442
  this.text(target.glue, caller, asked),
@@ -35388,8 +36444,8 @@ var Launcher = class {
35388
36444
  ]);
35389
36445
  return { glue, module: module2, path: target.glue };
35390
36446
  }
35391
- const { module, memory, foreign } = await this.module(target.wasm, caller, asked);
35392
- const names2 = env.SLICC_WASM_BACKTRACE === "1" ? await this.names(target.wasm, module) : void 0;
36447
+ const { module, memory, foreign, named } = await this.module(target.wasm, caller, asked);
36448
+ const names2 = env.SLICC_WASM_BACKTRACE === "1" && !named ? await this.names(target.wasm) : void 0;
35393
36449
  const imports = target.imports ? await this.text(target.imports, caller) : void 0;
35394
36450
  return {
35395
36451
  abi: "wasi",
@@ -35424,7 +36480,7 @@ var Launcher = class {
35424
36480
  try {
35425
36481
  const cwdSlot = await this.cwds.hold(cwd, req.cwdFrom);
35426
36482
  const handle = await this.admitted(
35427
- program.abi !== "js",
36483
+ program,
35428
36484
  req.fds,
35429
36485
  (fds, quietOom) => this.start({
35430
36486
  ...req,
@@ -35439,7 +36495,8 @@ var Launcher = class {
35439
36495
  args,
35440
36496
  env,
35441
36497
  cwdSlot
35442
- })
36498
+ }),
36499
+ req.ppid
35443
36500
  ).finally(() => this.cwds.release(cwdSlot));
35444
36501
  void handle.exited.finally(done5);
35445
36502
  return handle;
@@ -35463,7 +36520,8 @@ var Launcher = class {
35463
36520
  };
35464
36521
  if (this.integrity) await this.checkedSources(planned, caller);
35465
36522
  const [program, exeId] = await this.loaded(planned.target, env, caller);
35466
- if (readsEtcHostname(program)) setOrDrop(env, "HOSTNAME", own);
36523
+ const libc = program.abi === "js" ? void 0 : this.libcs.get(program.module);
36524
+ if (readsEtcHostname(program, libc)) setOrDrop(env, "HOSTNAME", own);
35467
36525
  return { planned, env, program, exeId };
35468
36526
  }
35469
36527
  packageRootIs(path) {
@@ -35560,12 +36618,25 @@ var Launcher = class {
35560
36618
  if (req.command !== void 0) this.programs.set(pid, req.command);
35561
36619
  this.cwdPaths.set(pid, req.cwd);
35562
36620
  }
35563
- async admitted(wasm, fds, start2) {
36621
+ async reserved(program, fds, ppid) {
36622
+ if (!this.admit) return () => {
36623
+ };
36624
+ try {
36625
+ return await this.admit(program, ppid === void 0 ? {} : { ppid });
36626
+ } catch (err) {
36627
+ this.memories.ended();
36628
+ await fds.closeAll();
36629
+ throw err;
36630
+ }
36631
+ }
36632
+ async admitted(program, fds, start2, ppid) {
36633
+ const wasm = program.abi !== "js";
35564
36634
  for (; ; ) {
35565
36635
  await this.memories.admit().catch(async (err) => {
35566
36636
  await fds.closeAll();
35567
36637
  throw err;
35568
36638
  });
36639
+ const release = await this.reserved(program, fds, ppid);
35569
36640
  const counted2 = (handle2) => {
35570
36641
  void handle2.exited.finally(() => this.memories.ended());
35571
36642
  void Promise.resolve(handle2.ready).then(() => this.memories.started());
@@ -35577,6 +36648,8 @@ var Launcher = class {
35577
36648
  } catch (err) {
35578
36649
  this.memories.ended();
35579
36650
  throw err;
36651
+ } finally {
36652
+ release();
35580
36653
  }
35581
36654
  }
35582
36655
  const forked = fds.fork();
@@ -35584,7 +36657,7 @@ var Launcher = class {
35584
36657
  this.memories.ended();
35585
36658
  await forked.closeAll();
35586
36659
  throw err;
35587
- });
36660
+ }).finally(release);
35588
36661
  const fit = await (handle.ready ?? true);
35589
36662
  if (fit) {
35590
36663
  this.traceAdmitted(handle.pid, true);
@@ -35627,6 +36700,7 @@ var Launcher = class {
35627
36700
  this.settling.syscall(pid, call.op);
35628
36701
  },
35629
36702
  settling: () => this.settling.isSettling(pid),
36703
+ durable: this.durable,
35630
36704
  ...req.ignored ? { ignored: req.ignored } : {},
35631
36705
  ...anyBlocked(req.blocked) ? { blocked: req.blocked } : {},
35632
36706
  ...req.umask !== void 0 ? { umask: req.umask } : {},
@@ -35639,6 +36713,7 @@ var Launcher = class {
35639
36713
  ...scrubs ? { outputFilter: (file) => scrubbedAll(file, scrubs) } : {},
35640
36714
  clipboard: this.clipboard,
35641
36715
  embedder: { broker: this.embedder, session: () => this.sessionOf(pid) },
36716
+ devices: this.devices,
35642
36717
  ...this.dac ? { dac: this.dac } : {},
35643
36718
  program: req.program,
35644
36719
  changes: this.changes.sab,
@@ -35822,8 +36897,8 @@ var Launcher = class {
35822
36897
  this.sampledAt = Math.max(this.sampledAt, now);
35823
36898
  this.load = this.load.map((avg, i) => {
35824
36899
  const window = LOAD_WINDOWS_MS[i];
35825
- const fresh3 = 1 - Math.exp(-LOAD_SAMPLE_MS / window);
35826
- return avg * Math.exp(-elapsed / window) + running * fresh3;
36900
+ const fresh4 = 1 - Math.exp(-LOAD_SAMPLE_MS / window);
36901
+ return avg * Math.exp(-elapsed / window) + running * fresh4;
35827
36902
  });
35828
36903
  }
35829
36904
  idleSince;
@@ -36170,7 +37245,7 @@ var Launcher = class {
36170
37245
  forker(ppid, parent) {
36171
37246
  const { exec: _exec, pgid: _pgid, group: _group, pid: _pid, scrub: _scrub, ...image } = parent;
36172
37247
  return async (state, given) => {
36173
- const fresh3 = (fds, quietOom) => this.start({
37248
+ const fresh4 = (fds, quietOom) => this.start({
36174
37249
  ...image,
36175
37250
  quietOom,
36176
37251
  cwd: state.cwd ?? parent.cwd,
@@ -36186,7 +37261,7 @@ var Launcher = class {
36186
37261
  tagBase: this.tagBases.get(ppid),
36187
37262
  links: this.links.get(ppid)
36188
37263
  });
36189
- return childHandle(await this.admitted(parent.program.abi !== "js", given, fresh3));
37264
+ return childHandle(await this.admitted(parent.program, given, fresh4, ppid));
36190
37265
  };
36191
37266
  }
36192
37267
  keySignal(tty, fallback, sig, send2) {
@@ -36227,6 +37302,14 @@ var Launcher = class {
36227
37302
  this.sealed.userOf = async (uid) => (await this.users.lookup(uid))?.name;
36228
37303
  this.sealed.factsOf = (pid) => this.processFacts(pid);
36229
37304
  }
37305
+ deviceNodes(hook) {
37306
+ const nodes = new DeviceNodes(this.usersMode, {
37307
+ groupId: async (name2) => (await this.users.groups()).find((g) => g.name === name2)?.gid,
37308
+ userId: async (name2) => (await this.users.lookup(name2))?.uid
37309
+ });
37310
+ if (hook) nodes.register(0, hook);
37311
+ return nodes;
37312
+ }
36230
37313
  embedderBroker(hook) {
36231
37314
  const broker = new EmbedderBroker(
36232
37315
  this.usersMode,
@@ -36308,6 +37391,8 @@ var Launcher = class {
36308
37391
  return targets.length > 0;
36309
37392
  }
36310
37393
  async driver(type, spec) {
37394
+ const inProcess = openInProcess(spec, this.ports);
37395
+ if (inProcess) return inProcess;
36311
37396
  if (type === "fsa") return this.fsaDriver(spec);
36312
37397
  if (type === "hostfs") {
36313
37398
  const { hostfs, hostfsFetch, hostfsTiming } = this.hostfs;
@@ -36316,11 +37401,12 @@ var Launcher = class {
36316
37401
  return openHostfs(
36317
37402
  spec,
36318
37403
  grantConnect(hostfs, hostfsFetch ?? ((url, init) => fetch(url, init)), hostfsTiming),
36319
- hostfsTiming
37404
+ hostfsTiming,
37405
+ this.ports
36320
37406
  );
36321
37407
  }
36322
37408
  if (type === "tmpfs") {
36323
- const { port1, port2 } = new MessageChannel();
37409
+ const { port1, port2 } = this.ports();
36324
37410
  serveFilesystem(
36325
37411
  port2,
36326
37412
  tmpfs(),
@@ -36381,7 +37467,7 @@ var Launcher = class {
36381
37467
  async fsaDriver(spec) {
36382
37468
  const { target, source } = spec;
36383
37469
  const ask = (handle) => this.onMountPending?.({ target, source, ...handle ? { handle } : {} });
36384
- const { port1, port2 } = new MessageChannel();
37470
+ const { port1, port2 } = this.ports();
36385
37471
  const medium = removableMedium((handle) => {
36386
37472
  served2.invalidate(true);
36387
37473
  ask(handle);
@@ -36516,8 +37602,8 @@ var Launcher = class {
36516
37602
  for (const [path, mode] of layout) {
36517
37603
  if (isProtected(this.prefixes, normalizePath(path))) continue;
36518
37604
  const real = await this.realLayoutPath(path);
36519
- const fresh3 = real !== void 0 && !await this.base.hasOwner?.(real);
36520
- if (fresh3) await this.base.chown?.(real, { uid: 0, gid: 0, mode, follow: false });
37605
+ const fresh4 = real !== void 0 && !await this.base.hasOwner?.(real);
37606
+ if (fresh4) await this.base.chown?.(real, { uid: 0, gid: 0, mode, follow: false });
36521
37607
  }
36522
37608
  }
36523
37609
  async realLayoutPath(given) {
@@ -36651,10 +37737,10 @@ var Launcher = class {
36651
37737
  }
36652
37738
  async mountFstab() {
36653
37739
  const text = await this.base.readFile(FSTAB_PATH).catch(() => "");
36654
- const lines2 = parseFstab(text);
36655
- for (const { spec } of lines2) this.mounts.note(spec, "pending");
37740
+ const lines3 = parseFstab(text);
37741
+ for (const { spec } of lines3) this.mounts.note(spec, "pending");
36656
37742
  return mountFstab(
36657
- lines2,
37743
+ lines3,
36658
37744
  (spec) => this.mount(spec).catch((err) => {
36659
37745
  this.mounts.note(spec, "pending", err?.message ?? String(err));
36660
37746
  throw err;
@@ -37551,7 +38637,7 @@ function isAttestRequest(req) {
37551
38637
  return ATTEST_OPS.has(req.op);
37552
38638
  }
37553
38639
  function isUsersRequest(req) {
37554
- return USERS_OPS.has(req.op);
38640
+ return USERS_OPS.has(req.op) || req.op === "devices-add" || req.op === "devices-remove";
37555
38641
  }
37556
38642
  function transferOf2(req, result) {
37557
38643
  if (result instanceof MessagePort) return [result];
@@ -37584,7 +38670,18 @@ function failure(err) {
37584
38670
  ...typeof code === "string" ? { code } : {}
37585
38671
  };
37586
38672
  }
38673
+ function pageReplied(data, requests, devices) {
38674
+ const embedderReply = embedderReplyOf(data);
38675
+ if (embedderReply) requests.answer(embedderReply);
38676
+ const devicesReply = devicesReplyOf(data);
38677
+ if (devicesReply) devices.answer(devicesReply);
38678
+ return embedderReply !== void 0 || devicesReply !== void 0;
38679
+ }
38680
+ function devicesOp(l, req) {
38681
+ return req.op === "devices-add" ? l.devices.add(req.spec, req.client) : l.devices.remove(req.node);
38682
+ }
37587
38683
  function usersOp(l, req) {
38684
+ if (req.op === "devices-add" || req.op === "devices-remove") return devicesOp(l, req);
37588
38685
  if (req.op === "users-add") return l.users.add(req.user);
37589
38686
  if (req.op === "users-remove") return l.users.remove(req.name, req.options);
37590
38687
  if (req.op === "groups-list") return l.users.groups();
@@ -37594,7 +38691,7 @@ function usersOp(l, req) {
37594
38691
  return l.users.list();
37595
38692
  }
37596
38693
  var clientIds = 0;
37597
- async function connectClient(deps, { user, tag, bind: bind2 }) {
38694
+ async function connectClient(deps, { user, tag, requests: bind2, devices }) {
37598
38695
  const l = await deps.ready();
37599
38696
  tagOption(tag);
37600
38697
  if (user !== void 0 && !await l.users.lookup(user)) {
@@ -37608,6 +38705,7 @@ async function connectClient(deps, { user, tag, bind: bind2 }) {
37608
38705
  signal: signalNumber,
37609
38706
  session: client,
37610
38707
  ...bind2 === "attach" ? { attachRequests: true } : {},
38708
+ ...devices === "attach" ? { attachDevices: true } : {},
37611
38709
  ...user !== void 0 ? { user } : {},
37612
38710
  ...tag !== void 0 ? { tag } : {},
37613
38711
  ...deps.locks ? { locks: deps.locks } : {},
@@ -37615,13 +38713,15 @@ async function connectClient(deps, { user, tag, bind: bind2 }) {
37615
38713
  });
37616
38714
  deps.clients.add(served2);
37617
38715
  const unbind = bind2 && bind2 !== "attach" ? l.embedder.register(client, deps.requests.hookFor(client, bind2)) : void 0;
38716
+ const unbindDevices = devices === true ? l.devices.register(client, deps.devices.hookFor(client)) : void 0;
37618
38717
  void served2.closed.then(() => {
37619
38718
  deps.clients.delete(served2);
37620
38719
  unbind?.();
38720
+ unbindDevices?.();
37621
38721
  });
37622
- return unbind ? { port: port2, client } : port2;
38722
+ return unbind || devices ? { port: port2, client } : port2;
37623
38723
  }
37624
- function hostOptions(req, port, sealed, sealedFetch, clipboard, lookup2, requests) {
38724
+ function hostOptions(req, port, sealed, sealedFetch, clipboard, lookup2, requests, devices) {
37625
38725
  return {
37626
38726
  cron: { lock: `slicc-kernel-cron:${req.metadata ?? META_DB}` },
37627
38727
  ...req.hostname !== void 0 ? { hostname: req.hostname } : {},
@@ -37633,7 +38733,8 @@ function hostOptions(req, port, sealed, sealedFetch, clipboard, lookup2, request
37633
38733
  ...req.sealed ? { sealed } : {},
37634
38734
  ...req.sealedFetch ? { sealedFetch } : {},
37635
38735
  ...req.clipboard ? { clipboard } : {},
37636
- ...req.requests ? { embedder: requests.hookFor(0, req.requests) } : {}
38736
+ ...req.requests ? { embedder: requests.hookFor(0, req.requests) } : {},
38737
+ ...req.devices ? { devices: devices.hookFor(0) } : {}
37637
38738
  };
37638
38739
  }
37639
38740
  function hostProtect(init, lookup2) {
@@ -37687,6 +38788,20 @@ function processOps(ready2, reply) {
37687
38788
  }
37688
38789
  return { terminal, sudoRun, act: onTerminal };
37689
38790
  }
38791
+ function lockHolder() {
38792
+ let holding;
38793
+ return (locks) => {
38794
+ holding ??= new Promise((resolve2) => {
38795
+ const name2 = `slicc-kernel:${crypto.randomUUID()}`;
38796
+ void locks.request(name2, () => {
38797
+ resolve2(name2);
38798
+ return new Promise(() => {
38799
+ });
38800
+ });
38801
+ });
38802
+ return holding;
38803
+ };
38804
+ }
37690
38805
  function serveKernel(port, deps) {
37691
38806
  let launcher;
37692
38807
  let remote;
@@ -37696,24 +38811,14 @@ function serveKernel(port, deps) {
37696
38811
  const sealed = sealedAsker(port);
37697
38812
  const clipboard = clipboardAsker(port);
37698
38813
  const requests = embedderAsker(port);
38814
+ const devices = devicesAsker(port);
37699
38815
  const integrity = integrityAsker(port);
37700
38816
  const approvals = sudoApprovals(port);
37701
38817
  const locks = deps.locks === null ? void 0 : deps.locks ?? locksOf();
37702
- let holding;
37703
- function holdLock(locks2) {
37704
- holding ??= new Promise((resolve2) => {
37705
- const name2 = `slicc-kernel:${crypto.randomUUID()}`;
37706
- void locks2.request(name2, () => {
37707
- resolve2(name2);
37708
- return new Promise(() => {
37709
- });
37710
- });
37711
- });
37712
- return holding;
37713
- }
37714
- const connect2 = (user, tag, bind2) => connectClient(
37715
- { ready: ready2, clients, requests, held: locks ? () => holdLock(locks) : void 0, locks },
37716
- { user, tag, bind: bind2 }
38818
+ const holdLock = lockHolder();
38819
+ const connect2 = (req) => connectClient(
38820
+ { ready: ready2, clients, requests, devices, held: locks && (() => holdLock(locks)), locks },
38821
+ req
37717
38822
  );
37718
38823
  async function ready2() {
37719
38824
  if (!launcher) throw new Error("the kernel is not initialized");
@@ -37744,7 +38849,8 @@ function serveKernel(port, deps) {
37744
38849
  sealed.fetch,
37745
38850
  clipboard.hook,
37746
38851
  integrity.lookup,
37747
- requests
38852
+ requests,
38853
+ devices
37748
38854
  ),
37749
38855
  ...req.approve ? { approve: approvals.ask } : {},
37750
38856
  ...net,
@@ -37776,7 +38882,7 @@ function serveKernel(port, deps) {
37776
38882
  if (req.op === "sealed-placeholders") return (await ready2()).setPlaceholders(req.list);
37777
38883
  if (req.op === "open-terminal") return processes2.terminal(req);
37778
38884
  if (req.op === "sudo-run") return processes2.sudoRun(req);
37779
- if (req.op === "connect") return connect2(req.user, req.tag, req.requests);
38885
+ if (req.op === "connect") return connect2(req);
37780
38886
  if (isUsersRequest(req)) return usersOp(await ready2(), req);
37781
38887
  if (req.op === "routes" || req.op === "transport-traits") {
37782
38888
  return networkOp(await ready2(), req, remote);
@@ -37813,8 +38919,7 @@ function serveKernel(port, deps) {
37813
38919
  if (sealedReply) return sealed.answer(sealedReply);
37814
38920
  const clipboardReply = event.data.clipboardReply;
37815
38921
  if (clipboardReply) return clipboard.answer(clipboardReply);
37816
- const embedderReply = embedderReplyOf(event.data);
37817
- if (embedderReply) return requests.answer(embedderReply);
38922
+ if (pageReplied(event.data, requests, devices)) return;
37818
38923
  const integrityReply = event.data.integrityReply;
37819
38924
  if (integrityReply) return integrity.answer(integrityReply);
37820
38925
  const grant = event.data.hostfsGrant;