@ai-ecoverse/slicc-kernel 1.193.3 → 1.194.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.
@@ -238,6 +238,10 @@ function under(path, root) {
238
238
  }
239
239
  var MemoryMeta = class {
240
240
  entries = new PathMap();
241
+ limit;
242
+ constructor(limit = Infinity) {
243
+ this.limit = limit;
244
+ }
241
245
  async get(paths) {
242
246
  return paths.map((path) => this.entries.get(path));
243
247
  }
@@ -248,6 +252,8 @@ var MemoryMeta = class {
248
252
  this.set(path, change(this.entries.get(path)));
249
253
  }
250
254
  set(path, entry) {
255
+ if (entry && this.entries.size >= this.limit && !this.entries.has(path))
256
+ throw Object.assign(new Error("metadata quota"), { code: "ENOSPC" });
251
257
  if (entry) this.entries.set(path, entry);
252
258
  else this.entries.delete(path);
253
259
  }
@@ -257,14 +263,14 @@ var MemoryMeta = class {
257
263
  for (const entry of carried) this.entries.delete(entry.path);
258
264
  for (const entry of carried) {
259
265
  const path = to + entry.path.slice(from.length);
260
- if (path !== to) this.entries.set(path, moved(entry, path));
266
+ if (path !== to) this.set(path, moved(entry, path));
261
267
  }
262
- this.entries.set(to, moved(root(carried.find((entry) => entry.path === from)), to));
263
- if (left) this.entries.set(from, left);
268
+ this.set(to, moved(root(carried.find((entry) => entry.path === from)), to));
269
+ if (left) this.set(from, left);
264
270
  }
265
271
  async remove(paths, left) {
266
272
  for (const path of paths) this.entries.deleteTree(path);
267
- if (left) this.entries.set(left.path, left);
273
+ if (left) this.set(left.path, left);
268
274
  }
269
275
  absent(path) {
270
276
  return !this.entries.has(path);
@@ -808,8 +814,8 @@ function integrityUnknown(options) {
808
814
  }
809
815
  return unknown;
810
816
  }
811
- function hex(digest) {
812
- return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
817
+ function hex(digest2) {
818
+ return [...new Uint8Array(digest2)].map((b) => b.toString(16).padStart(2, "0")).join("");
813
819
  }
814
820
  async function sha256(bytes) {
815
821
  return hex(await crypto.subtle.digest("SHA-256", bytes));
@@ -4485,6 +4491,10 @@ function chunk(bytes) {
4485
4491
  }
4486
4492
  var LAST_CHUNK = latin1Bytes("0\r\n\r\n");
4487
4493
 
4494
+ // src/cdp/lease.ts
4495
+ var LEASE_MAX_MESSAGE = 128 * 1024;
4496
+ var LEASE_MAX_CONNECTIONS = 8;
4497
+
4488
4498
  // src/cdp/types.ts
4489
4499
  var CDP_PORT = 9222;
4490
4500
  var NO_CDP_HOST = "slicc-kernel: no CDP host is attached (createKernel({ cdp }) or client.serveCdp)";
@@ -4537,8 +4547,8 @@ async function acceptKey(headers) {
4537
4547
  return acceptFor(key);
4538
4548
  }
4539
4549
  async function acceptFor(key) {
4540
- const digest = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(key + GUID));
4541
- return btoa(String.fromCharCode(...new Uint8Array(digest)));
4550
+ const digest2 = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(key + GUID));
4551
+ return btoa(String.fromCharCode(...new Uint8Array(digest2)));
4542
4552
  }
4543
4553
  function isUpgrade(headers) {
4544
4554
  return (field(headers, "upgrade") ?? "").toLowerCase().includes("websocket");
@@ -4799,11 +4809,21 @@ var CdpFacade = class {
4799
4809
  }
4800
4810
  }
4801
4811
  async route(conn, incoming, req) {
4812
+ const { hosts } = this.options;
4813
+ if (hosts.leaseOnly) {
4814
+ hosts.authorize(conn);
4815
+ if (req.method !== "GET") throw new HttpError(405, "expected GET");
4816
+ if (req.target === hosts.path && isUpgrade(req.headers))
4817
+ return this.upgrade(conn, incoming, req);
4818
+ if (req.target === "/json/version")
4819
+ return this.write(conn, json({ Browser: "cdp-lease-v1", webSocketDebuggerUrl: hosts.url }));
4820
+ if (req.target === "/json" || req.target === "/json/list") return this.write(conn, json([]));
4821
+ throw new HttpError(404, "lease route unavailable");
4822
+ }
4802
4823
  const url = new URL(req.target, "http://127.0.0.1");
4803
4824
  const runtime = url.searchParams.get("runtime") ?? void 0;
4804
4825
  const host = req.headers.find(([n]) => n.toLowerCase() === "host")?.[1] ?? "127.0.0.1";
4805
4826
  if (req.method !== "GET") throw new HttpError(405, `${req.method} is not supported here`);
4806
- const { hosts } = this.options;
4807
4827
  if (url.pathname === hosts.path && isUpgrade(req.headers)) {
4808
4828
  return this.upgrade(conn, incoming, req, runtime);
4809
4829
  }
@@ -4825,10 +4845,10 @@ var CdpFacade = class {
4825
4845
  );
4826
4846
  return;
4827
4847
  }
4828
- await this.write(conn, json(await this.list(runtime, conn.peerStamp)));
4848
+ await this.write(conn, json(await this.list(conn, runtime)));
4829
4849
  }
4830
- async list(runtime, stamp) {
4831
- const conn = await this.host(runtime, stamp);
4850
+ async list(peer, runtime) {
4851
+ const conn = await this.options.hosts.connect(peer, runtime);
4832
4852
  try {
4833
4853
  const reply = await new Promise(
4834
4854
  (resolve2, reject) => {
@@ -4863,17 +4883,12 @@ var CdpFacade = class {
4863
4883
  conn.close();
4864
4884
  }
4865
4885
  }
4866
- host(runtime, stamp) {
4867
- return this.options.hosts.connect({
4868
- ...runtime ? { runtime } : {},
4869
- ...stamp ? { stamp } : {}
4870
- });
4871
- }
4872
4886
  async upgrade(conn, incoming, req, runtime) {
4873
4887
  const accept2 = await acceptKey(req.headers);
4874
- const host = await this.host(runtime, conn.peerStamp);
4888
+ const host = await this.options.hosts.connect(conn, runtime);
4875
4889
  const limits = {
4876
- max: this.options.maxMessage ?? MAX_MESSAGE,
4890
+ max: this.options.hosts.leaseOnly ? LEASE_MAX_MESSAGE : this.options.maxMessage ?? MAX_MESSAGE,
4891
+ serial: this.options.hosts.leaseOnly,
4877
4892
  closeWaitMs: this.options.closeWaitMs ?? CLOSE_WAIT_MS
4878
4893
  };
4879
4894
  await new Relay(conn, incoming, host, limits, this.stop.signal).start(switchingHead(accept2)).finally(() => host.close());
@@ -4882,6 +4897,8 @@ var CdpFacade = class {
4882
4897
  var Relay = class {
4883
4898
  writes = Promise.resolve();
4884
4899
  ended = false;
4900
+ busy = false;
4901
+ serial;
4885
4902
  conn;
4886
4903
  incoming;
4887
4904
  host;
@@ -4893,6 +4910,7 @@ var Relay = class {
4893
4910
  this.incoming = incoming;
4894
4911
  this.host = host;
4895
4912
  this.max = limits.max;
4913
+ this.serial = limits.serial;
4896
4914
  this.closeWaitMs = limits.closeWaitMs;
4897
4915
  this.stop = stop;
4898
4916
  }
@@ -4906,7 +4924,8 @@ var Relay = class {
4906
4924
  return this.send(closeFrame(code, reason));
4907
4925
  }
4908
4926
  async start(head) {
4909
- await this.send(head);
4927
+ const handshake2 = this.send(head);
4928
+ if (!this.serial) await handshake2;
4910
4929
  const hostGone = new Promise((resolve2) => {
4911
4930
  this.host.onclose = (reason) => {
4912
4931
  void this.end(reason ? CLOSE.error : CLOSE.normal, reason ?? "").then(() => resolve2());
@@ -4917,8 +4936,13 @@ var Relay = class {
4917
4936
  const bytes = new TextEncoder().encode(message3);
4918
4937
  if (bytes.length > this.max)
4919
4938
  void this.end(CLOSE.tooBig, `a message is over ${this.max} bytes`);
4920
- else void this.send(frame(OP_TEXT, bytes));
4939
+ else if (!this.serial) void this.send(frame(OP_TEXT, bytes));
4940
+ else
4941
+ void this.send(frame(OP_TEXT, bytes)).then(() => {
4942
+ this.busy = false;
4943
+ });
4921
4944
  };
4945
+ await handshake2;
4922
4946
  const pumping = this.pump();
4923
4947
  await Promise.race([pumping, hostGone]);
4924
4948
  await this.writes;
@@ -4934,10 +4958,18 @@ var Relay = class {
4934
4958
  try {
4935
4959
  for (; ; ) {
4936
4960
  const event = await reader.next(this.stop);
4937
- if (!event) return;
4938
- if (event.kind === "text") this.host.send(event.text);
4939
- else if (event.kind === "ping") void this.send(pongFrame(event.payload));
4940
- else {
4961
+ if (!event || this.serial && this.ended) return;
4962
+ if (event.kind === "text") {
4963
+ if (this.serial && this.busy) {
4964
+ await this.end(CLOSE.protocol, "one lease operation at a time");
4965
+ return;
4966
+ }
4967
+ this.busy = this.serial;
4968
+ this.host.send(event.text);
4969
+ } else if (event.kind === "ping") {
4970
+ const pong = this.send(pongFrame(event.payload));
4971
+ if (this.serial) await pong;
4972
+ } else {
4941
4973
  await this.end(event.code === 1005 ? CLOSE.normal : event.code, "");
4942
4974
  return;
4943
4975
  }
@@ -5017,12 +5049,43 @@ var CdpHosts = class {
5017
5049
  embedder;
5018
5050
  clients = [];
5019
5051
  closed = false;
5020
- path = `/devtools/browser/${crypto.randomUUID()}`;
5021
- url = `ws://127.0.0.1:${CDP_PORT}${this.path}`;
5022
- constructor(hook) {
5052
+ leaseTag;
5053
+ sessionOf;
5054
+ session;
5055
+ opening = 0;
5056
+ path;
5057
+ url;
5058
+ constructor(hook, leaseTag, sessionOf2 = (_pid) => -1) {
5059
+ this.leaseTag = leaseTag;
5060
+ this.sessionOf = sessionOf2;
5061
+ this.path = `${this.leaseOnly ? "/slicc/lease/v1/" : "/devtools/browser/"}${crypto.randomUUID()}`;
5062
+ this.url = `ws://127.0.0.1:${CDP_PORT}${this.path}`;
5023
5063
  this.embedder = hook ? { hook, runtime: void 0, open: /* @__PURE__ */ new Set() } : void 0;
5024
5064
  }
5065
+ get leaseOnly() {
5066
+ return this.leaseTag !== void 0;
5067
+ }
5068
+ env(session) {
5069
+ if (!this.leaseOnly) return { SLICC_CDP_URL: this.url };
5070
+ if (session === void 0 || this.session !== session || this.closed) return {};
5071
+ return { SLICC_CDP_LEASE_URL: this.url };
5072
+ }
5073
+ bindClient(session, tag, extraHost) {
5074
+ if (!this.leaseOnly) return void 0;
5075
+ if (this.closed || this.session !== void 0 || tag !== this.leaseTag || extraHost) {
5076
+ throw new Error("lease unavailable for this client");
5077
+ }
5078
+ this.session = session;
5079
+ return () => this.close();
5080
+ }
5081
+ authorize(socket) {
5082
+ if (!this.leaseOnly) return;
5083
+ if (this.closed || this.session === void 0 || socket.peerStamp?.tag !== this.leaseTag || !socket.peerCred || this.sessionOf(socket.peerCred.pid) !== this.session) {
5084
+ throw new HttpError(403, "lease unavailable");
5085
+ }
5086
+ }
5025
5087
  register(hook, runtime) {
5088
+ if (this.leaseOnly) throw new Error("a lease-only kernel cannot register a CDP host");
5026
5089
  const entry = { hook, runtime, open: /* @__PURE__ */ new Set() };
5027
5090
  this.clients.push(entry);
5028
5091
  return () => {
@@ -5033,20 +5096,28 @@ var CdpHosts = class {
5033
5096
  }
5034
5097
  pick(runtime) {
5035
5098
  if (this.closed) return void 0;
5099
+ if (this.leaseOnly) return runtime === void 0 ? this.embedder : void 0;
5036
5100
  const named = runtime ? this.clients.findLast((c) => c.runtime === runtime) : void 0;
5037
5101
  return named ?? this.embedder ?? this.clients.at(-1);
5038
5102
  }
5039
5103
  available(runtime) {
5040
5104
  return this.pick(runtime) !== void 0;
5041
5105
  }
5042
- async connect(request3) {
5043
- const entry = this.pick(request3.runtime);
5106
+ async connect(peer, runtime) {
5107
+ this.authorize(peer);
5108
+ const entry = this.pick(runtime);
5044
5109
  if (!entry) throw new HttpError(503, NO_CDP_HOST);
5110
+ if (this.leaseOnly && this.opening + entry.open.size >= LEASE_MAX_CONNECTIONS)
5111
+ throw new HttpError(503, "lease busy");
5045
5112
  let conn;
5113
+ this.opening++;
5046
5114
  try {
5047
- conn = held(await entry.hook(hookRequest(request3)));
5115
+ conn = held(await entry.hook(hookRequest(peer, runtime)));
5048
5116
  } catch (e) {
5117
+ if (this.leaseOnly) throw new HttpError(502, "lease unavailable");
5049
5118
  throw new HttpError(502, `CDP host: ${e instanceof Error ? e.message : String(e)}`);
5119
+ } finally {
5120
+ this.opening--;
5050
5121
  }
5051
5122
  if (this.closed || !(entry === this.embedder || this.clients.includes(entry))) {
5052
5123
  conn.close();
@@ -5073,7 +5144,7 @@ function held(host) {
5073
5144
  host.onclose = end;
5074
5145
  return conn;
5075
5146
  }
5076
- function hookRequest({ runtime, stamp }) {
5147
+ function hookRequest({ peerStamp: stamp }, runtime) {
5077
5148
  return {
5078
5149
  ...runtime ? { runtime } : {},
5079
5150
  ...stamp ? { stamp: structuredClone(stamp) } : {}
@@ -5086,6 +5157,80 @@ function closeAll(entry) {
5086
5157
  }
5087
5158
  }
5088
5159
 
5160
+ // src/cdp/lease-cli.ts
5161
+ var CLI_PKG = "/node_modules/@ai-ecoverse/slicc-cdp";
5162
+ var CLI_FILE = `${CLI_PKG}/bin/playwright-cli.wasm`;
5163
+ var CLI_MAX = 8 * 1024 * 1024;
5164
+ var LEASE_USER = "leasejob";
5165
+ function checkCli({ wasm, sha256: sha2564 }) {
5166
+ if (!(wasm instanceof Uint8Array) || wasm.length < 8 || wasm.length > CLI_MAX || !/^[a-f0-9]{64}$/.test(sha2564))
5167
+ throw fsError("EINVAL", "invalid lease CLI image or SHA-256");
5168
+ }
5169
+ async function digest(bytes) {
5170
+ const hash = await crypto.subtle.digest("SHA-256", bytes);
5171
+ return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, "0")).join("");
5172
+ }
5173
+ var MANIFEST = JSON.stringify({
5174
+ name: "@ai-ecoverse/slicc-cdp",
5175
+ slicc: { abi: "wasi", commands: { "playwright-cli": { wasm: "bin/playwright-cli.wasm" } } }
5176
+ });
5177
+ var LeaseCliImage = class {
5178
+ state = "new";
5179
+ sha;
5180
+ fs;
5181
+ constructor(fs) {
5182
+ this.fs = fs;
5183
+ }
5184
+ async install(input) {
5185
+ if (this.state !== "new") throw fsError("EPERM", "lease CLI installation is one-shot");
5186
+ this.state = "installing";
5187
+ try {
5188
+ checkCli(input);
5189
+ const bytes = new Uint8Array(input.wasm);
5190
+ const sha = input.sha256;
5191
+ if (await digest(bytes) !== sha) throw fsError("EACCES", "lease CLI digest mismatch");
5192
+ this.active();
5193
+ await this.fs.mkdir(`${CLI_PKG}/bin`, { recursive: true });
5194
+ await this.fs.writeFile(CLI_FILE, bytes, { uid: 0, gid: 0, mode: 365 });
5195
+ await this.fs.writeFile(`${CLI_PKG}/package.json`, MANIFEST, { uid: 0, gid: 0, mode: 292 });
5196
+ if (await digest(await this.fs.readFileBuffer(CLI_FILE)) !== sha)
5197
+ throw fsError("EACCES", "installed lease CLI digest mismatch");
5198
+ this.active();
5199
+ this.sha = sha;
5200
+ this.state = "installed";
5201
+ } catch (err) {
5202
+ this.close();
5203
+ throw err;
5204
+ }
5205
+ }
5206
+ active() {
5207
+ if (this.state === "closed") throw fsError("EPERM", "lease job ended");
5208
+ }
5209
+ attest(record3) {
5210
+ if (record3.path !== CLI_FILE) return;
5211
+ if (this.state !== "installed" && this.state !== "attested" || !("sha256" in record3) || record3.sha256 !== this.sha || record3.uid !== 0 || (record3.mode & 146) !== 0)
5212
+ throw fsError("EACCES", "lease CLI attestation failed");
5213
+ this.state = "attested";
5214
+ }
5215
+ ready() {
5216
+ if (this.state !== "attested")
5217
+ throw fsError("EACCES", "install and attest the lease CLI first");
5218
+ }
5219
+ async bytes(path) {
5220
+ this.ready();
5221
+ if (path !== CLI_FILE) throw fsError("EACCES", "only the installed lease CLI can execute");
5222
+ const bytes = await this.fs.readFileBuffer(path);
5223
+ if (bytes.length > CLI_MAX || await digest(bytes) !== this.sha)
5224
+ throw fsError("EACCES", "lease CLI digest changed");
5225
+ this.ready();
5226
+ return bytes;
5227
+ }
5228
+ close() {
5229
+ this.state = "closed";
5230
+ this.sha = void 0;
5231
+ }
5232
+ };
5233
+
5089
5234
  // src/bytes.ts
5090
5235
  function fresh(bytes, start2 = 0, end = bytes.length) {
5091
5236
  return new Uint8Array(bytes.subarray(start2, end));
@@ -7854,7 +7999,7 @@ function serveTransport(peer, transport, {
7854
7999
  attributed = false
7855
8000
  } = {}) {
7856
8001
  const open2 = /* @__PURE__ */ new Map();
7857
- const fail2 = (nid, e) => {
8002
+ const fail3 = (nid, e) => {
7858
8003
  open2.delete(nid);
7859
8004
  const { status, code, detail } = e;
7860
8005
  peer.postMessage({
@@ -7884,7 +8029,7 @@ function serveTransport(peer, transport, {
7884
8029
  open2.set(call.nid, { abort, body: response.body[Symbol.asyncIterator](), response });
7885
8030
  peer.postMessage(headOf(call.nid, response));
7886
8031
  } catch (e) {
7887
- fail2(call.nid, e);
8032
+ fail3(call.nid, e);
7888
8033
  }
7889
8034
  };
7890
8035
  const sockets = /* @__PURE__ */ new Map();
@@ -7918,7 +8063,7 @@ function serveTransport(peer, transport, {
7918
8063
  peer.postMessage({ net: "ws-opened", nid: call.nid, protocol: socket.protocol });
7919
8064
  void relay2(call.nid, socket);
7920
8065
  } catch (e) {
7921
- fail2(call.nid, e);
8066
+ fail3(call.nid, e);
7922
8067
  }
7923
8068
  };
7924
8069
  const relay2 = async (nid, socket) => {
@@ -7991,7 +8136,7 @@ function serveTransport(peer, transport, {
7991
8136
  peer.postMessage({ net: "chunk", nid, bytes }, [bytes.buffer]);
7992
8137
  }
7993
8138
  } catch (e) {
7994
- fail2(nid, e);
8139
+ fail3(nid, e);
7995
8140
  }
7996
8141
  };
7997
8142
  const drop = (nid) => {
@@ -9131,7 +9276,7 @@ function satisfies(version, range2) {
9131
9276
  }
9132
9277
 
9133
9278
  // src/version.ts
9134
- var KERNEL_VERSION = true ? "1.193.3" : "0.0.0-dev";
9279
+ var KERNEL_VERSION = true ? "1.194.0" : "0.0.0-dev";
9135
9280
  var OS_RELEASE = "6.0.0-slicc";
9136
9281
  function procVersion() {
9137
9282
  return `Linux version ${OS_RELEASE} (slicc-kernel ${KERNEL_VERSION}) #1 SMP PREEMPT_DYNAMIC
@@ -10583,12 +10728,12 @@ var UnlinkedKeeper = class {
10583
10728
  adopt(hidden, refs) {
10584
10729
  return this.keptFile(hidden, { refs });
10585
10730
  }
10586
- async peerKeep(target, over, valid = async () => true) {
10731
+ async peerKeep(target, over, valid2 = async () => true) {
10587
10732
  const none = { whole: false, undoing: (op) => op() };
10588
10733
  const peers = this.peers;
10589
10734
  if (!peers?.shared() || this.rootOf(target) !== "/") return none;
10590
10735
  const held2 = peers.heldWithin(target).filter((holder) => holder.instance !== void 0);
10591
- if (held2.length === 0 || !await valid()) return none;
10736
+ if (held2.length === 0 || !await valid2()) return none;
10592
10737
  const tabs = /* @__PURE__ */ new Map();
10593
10738
  for (const holder of held2) tabs.set(holder.tab, [...tabs.get(holder.tab) ?? [], holder]);
10594
10739
  const asked = [...tabs].map(([tab, holders]) => {
@@ -11996,12 +12141,12 @@ function unchanged(a, b, bytes) {
11996
12141
  return a.ino === b.ino && a.mtime.getTime() === b.mtime.getTime() && a.size === b.size && bytes.length === b.size;
11997
12142
  }
11998
12143
  async function sha2562(bytes) {
11999
- const digest = new Uint8Array(
12144
+ const digest2 = new Uint8Array(
12000
12145
  await crypto.subtle.digest("SHA-256", bytes)
12001
12146
  );
12002
- return Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("");
12147
+ return Array.from(digest2, (b) => b.toString(16).padStart(2, "0")).join("");
12003
12148
  }
12004
- function attested(path, st, bytes, digest, o, parents) {
12149
+ function attested(path, st, bytes, digest2, o, parents) {
12005
12150
  const { uid, gid, mode } = owned(path, st);
12006
12151
  return {
12007
12152
  path,
@@ -12011,7 +12156,7 @@ function attested(path, st, bytes, digest, o, parents) {
12011
12156
  mode,
12012
12157
  ino: st.ino,
12013
12158
  mtimeMs: st.mtime.getTime(),
12014
- sha256: digest,
12159
+ sha256: digest2,
12015
12160
  users: o.users,
12016
12161
  onRootFs: true,
12017
12162
  parents
@@ -12057,7 +12202,8 @@ async function attest(fs, asked, o) {
12057
12202
  if (before.isSymbolicLink) refuse("EACCES", path, "is a symlink");
12058
12203
  if (!before.isFile)
12059
12204
  refuse(before.isDirectory ? "EISDIR" : "EINVAL", path, "is not a regular file");
12060
- if (before.size > ATTEST_MAX) refuse("EFBIG", path, `is over ${ATTEST_MAX} bytes`);
12205
+ if (before.size > (o.maxBytes ?? ATTEST_MAX))
12206
+ refuse("EFBIG", path, `is over ${o.maxBytes ?? ATTEST_MAX} bytes`);
12061
12207
  const bytes = (await fs.readFileBuffer(path)).slice();
12062
12208
  const after = await fs.lstat(path);
12063
12209
  if (unchanged(before, after, bytes)) {
@@ -12403,13 +12549,13 @@ function materializer(fs, listedAbsent) {
12403
12549
  };
12404
12550
  }
12405
12551
  function withEtcFiles(fs, files) {
12406
- const bytesOf2 = (path) => {
12552
+ const bytesOf3 = (path) => {
12407
12553
  const text = files.get(path)?.();
12408
12554
  return text === void 0 ? void 0 : new TextEncoder().encode(text);
12409
12555
  };
12410
12556
  const absent2 = (path) => fs.lstat(path).then(() => false, missing5);
12411
12557
  const follow2 = linkFollower(fs, files);
12412
- const listedAbsent = async (path) => files.has(path) && await absent2(path) ? bytesOf2(path) : void 0;
12558
+ const listedAbsent = async (path) => files.has(path) && await absent2(path) ? bytesOf3(path) : void 0;
12413
12559
  const fallback = (path, make) => async (err) => {
12414
12560
  const at = missing5(err) ? await follow2(path) : void 0;
12415
12561
  const bytes = at === void 0 ? void 0 : await listedAbsent(at);
@@ -13208,10 +13354,10 @@ var ChangedError = class extends SpawnError {
13208
13354
  };
13209
13355
  function interrupted(signal) {
13210
13356
  const { promise, reject } = Promise.withResolvers();
13211
- const fail2 = () => reject(new KernelError("EINTR"));
13212
- if (signal?.aborted) fail2();
13213
- else signal?.addEventListener("abort", fail2, { once: true });
13214
- return { promise, done: () => signal?.removeEventListener("abort", fail2) };
13357
+ const fail3 = () => reject(new KernelError("EINTR"));
13358
+ if (signal?.aborted) fail3();
13359
+ else signal?.addEventListener("abort", fail3, { once: true });
13360
+ return { promise, done: () => signal?.removeEventListener("abort", fail3) };
13215
13361
  }
13216
13362
  function stoppedStatus(sig) {
13217
13363
  return (sig & 255) << 8 | 127;
@@ -21989,8 +22135,8 @@ function replayOf(value2) {
21989
22135
  const bound3 = filesOf(r.userWritable);
21990
22136
  const named = (s) => typeof s === "string" && s !== "";
21991
22137
  const absolute2 = (s) => typeof s === "string" && s.startsWith("/") && s.length <= PATH_MAX && !s.includes("\0");
21992
- 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;
21993
- if (!valid) return failed2("EINVAL", NOT_A_REQUEST);
22138
+ const valid2 = 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;
22139
+ if (!valid2) return failed2("EINVAL", NOT_A_REQUEST);
21994
22140
  const all = tags ?? (tag === void 0 ? [] : [tag]);
21995
22141
  return {
21996
22142
  id: id2,
@@ -22014,10 +22160,10 @@ function visudoCall(req) {
22014
22160
  if (!Array.isArray(files) || files.length === 0 || files.length > VISUDO_FILES_MAX) {
22015
22161
  return void 0;
22016
22162
  }
22017
- const valid = files.every(
22163
+ const valid2 = files.every(
22018
22164
  (f) => typeof f === "object" && f !== null && typeof f.name === "string" && typeof f.text === "string" && f.text.length <= VISUDO_TEXT_MAX
22019
22165
  );
22020
- return valid ? { op: "proc-visudo", files: files.map(({ name: name2, text }) => ({ name: name2, text })) } : void 0;
22166
+ return valid2 ? { op: "proc-visudo", files: files.map(({ name: name2, text }) => ({ name: name2, text })) } : void 0;
22021
22167
  }
22022
22168
  function skippedNotice(n) {
22023
22169
  const what = n === 1 ? "policy line or file was" : "policy lines or files were";
@@ -25907,10 +26053,10 @@ function ready(fds, read, write) {
25907
26053
  }
25908
26054
  function interruption(signal) {
25909
26055
  const { promise, reject } = Promise.withResolvers();
25910
- const fail2 = () => reject(new KernelError("EINTR"));
25911
- if (signal.aborted) fail2();
25912
- else signal.addEventListener("abort", fail2, { once: true });
25913
- return { promise, done: () => signal.removeEventListener("abort", fail2) };
26056
+ const fail3 = () => reject(new KernelError("EINTR"));
26057
+ if (signal.aborted) fail3();
26058
+ else signal.addEventListener("abort", fail3, { once: true });
26059
+ return { promise, done: () => signal.removeEventListener("abort", fail3) };
25914
26060
  }
25915
26061
  async function selectFds(fds, read, write, timeoutMs, interrupt) {
25916
26062
  const deadline = timeoutMs < 0 ? Number.POSITIVE_INFINITY : performance.now() + timeoutMs;
@@ -27907,10 +28053,10 @@ function pausing(signal) {
27907
28053
  const pausedAt = new Promise((resolve2) => {
27908
28054
  paused = resolve2;
27909
28055
  });
27910
- const select = (offer) => new Promise((choose, fail2) => {
27911
- if (signal.aborted) fail2(signal.reason);
27912
- signal.addEventListener("abort", () => fail2(signal.reason), { once: true });
27913
- paused({ offer, choose, fail: fail2 });
28056
+ const select = (offer) => new Promise((choose, fail3) => {
28057
+ if (signal.aborted) fail3(signal.reason);
28058
+ signal.addEventListener("abort", () => fail3(signal.reason), { once: true });
28059
+ paused({ offer, choose, fail: fail3 });
27914
28060
  });
27915
28061
  return { pausedAt, select };
27916
28062
  }
@@ -33625,7 +33771,7 @@ var PackageLocks = class {
33625
33771
  metadata;
33626
33772
  constructor(metadata, locks = replacingLocks()) {
33627
33773
  this.metadata = metadata;
33628
- this.locks = locks;
33774
+ this.locks = locks ?? void 0;
33629
33775
  }
33630
33776
  loading(roots, run2) {
33631
33777
  if (!this.locks || roots.length === 0) return run2(false);
@@ -36027,6 +36173,9 @@ function addTimes(into, pid, t) {
36027
36173
  const at = into.get(pid) ?? { utime: 0, stime: 0 };
36028
36174
  into.set(pid, { utime: at.utime + t.utime, stime: at.stime + t.stime });
36029
36175
  }
36176
+ function locksForPackages(options) {
36177
+ return new PackageLocks(options.packageLocks ?? META_DB, options.leaseImage ? null : void 0);
36178
+ }
36030
36179
  var Launcher = class {
36031
36180
  emscripten;
36032
36181
  admit;
@@ -36042,6 +36191,8 @@ var Launcher = class {
36042
36191
  unlinkOwnerOption;
36043
36192
  durable;
36044
36193
  base;
36194
+ leaseImage;
36195
+ disposing = false;
36045
36196
  createWorker;
36046
36197
  compile;
36047
36198
  moduleUrl;
@@ -36174,7 +36325,8 @@ var Launcher = class {
36174
36325
  this.memories = memoriesOf(options.wasmMemories);
36175
36326
  this.rootFs = options.fs;
36176
36327
  this.locks = kernelLocks(options.fs.rootName, this.flushingPeers(options.fs));
36177
- this.packageLocks = new PackageLocks(options.packageLocks ?? META_DB);
36328
+ this.leaseImage = options.leaseImage;
36329
+ this.packageLocks = locksForPackages(options);
36178
36330
  this.dac = this.usersMode === "off" ? void 0 : new Dac(this.usersMode, options.onDenial);
36179
36331
  if (this.dac) this.wireDac(this.dac);
36180
36332
  this.clipboard = new ClipboardBroker(
@@ -36228,7 +36380,7 @@ var Launcher = class {
36228
36380
  this.pnpmChain = new Set(chain(normalizePath(this.pnpmHome)));
36229
36381
  this.modulesDir = options.modules ?? "/node_modules";
36230
36382
  this.appended = appendedRoots(options.commands);
36231
- this.cdp = new CdpHosts(options.cdp);
36383
+ this.cdp = new CdpHosts(options.cdp, options.leaseTag, (pid) => this.sessionOf(pid).client);
36232
36384
  this.facades = new FacadeHosts(options.facades);
36233
36385
  const hostname = options.hostname ?? DEFAULT_HOSTNAME;
36234
36386
  if (!isHostname(hostname)) throw new Error(`not a host name: ${String(hostname)}`);
@@ -36238,7 +36390,7 @@ var Launcher = class {
36238
36390
  ...networkEnv(hostname),
36239
36391
  HOSTNAME: hostname,
36240
36392
  TZ: this.timeZone,
36241
- SLICC_CDP_URL: this.cdp.url,
36393
+ ...this.cdp.env(),
36242
36394
  ...this.facades.env(),
36243
36395
  ...options.env
36244
36396
  };
@@ -36282,7 +36434,7 @@ var Launcher = class {
36282
36434
  { [Symbol.iterator]: () => holders.flatMap((set3) => [...set3]).values() },
36283
36435
  (path) => this.mountRoot(path),
36284
36436
  {
36285
- locks: webLocks(),
36437
+ locks: this.leaseImage ? void 0 : webLocks(),
36286
36438
  busy: (path) => [...this.openFiles].some((nodes) => nodes.holds(path)),
36287
36439
  owner: options.unlinkOwner,
36288
36440
  marks: this.pathMarks,
@@ -36332,6 +36484,9 @@ var Launcher = class {
36332
36484
  now: sudoClock ? () => sudoClock.now() : void 0
36333
36485
  });
36334
36486
  this.cron = this.cronService(options.cron);
36487
+ this.watchCatalogs();
36488
+ }
36489
+ watchCatalogs() {
36335
36490
  void this.unlinked.sweep("/");
36336
36491
  this.watchers.watch(
36337
36492
  [this.modulesDir, this.pnpmHome, ...this.appended],
@@ -36777,9 +36932,13 @@ var Launcher = class {
36777
36932
  };
36778
36933
  }
36779
36934
  async plan(file, argv, cwd, scope, argv0, catalogOnly = false) {
36935
+ if (this.leaseImage && file !== "playwright-cli" && file !== "/usr/bin/playwright-cli" && file !== CLI_FILE)
36936
+ throw fsError("EACCES", "only the installed lease CLI can execute");
36780
36937
  const found = await this.resolve(file, argv[0] ?? file, cwd, scope);
36781
36938
  const named = typeof argv0 === "string" && found && !found.fixed;
36782
36939
  const direct = named ? { ...found, argv0 } : found;
36940
+ if (this.leaseImage && (!direct || direct.wasm !== CLI_FILE || direct.shim || direct.copy))
36941
+ throw fsError("EACCES", "lease CLI path mismatch");
36783
36942
  if (direct) {
36784
36943
  const shim = direct.shim ? { sources: [direct.shim], asked: direct.asked ? { [direct.shim]: direct.asked } : {} } : {};
36785
36944
  return { target: direct, args: [...direct.prefix ?? [], ...argv.slice(1)], ...shim };
@@ -37074,8 +37233,9 @@ var Launcher = class {
37074
37233
  const pin = await this.pinOf(path, caller);
37075
37234
  const sum = Object.values(pin)[0];
37076
37235
  const key = sum === void 0 ? await this.cacheKey(path, asked) : `${path}:sha256:${sum}`;
37236
+ const checked = this.leaseImage ? await this.leaseImage.bytes(path) : void 0;
37077
37237
  const loaded = this.cached(this.compiled, key, async () => {
37078
- const { bytes: read, key: readKey } = await this.keyed(path, caller, asked);
37238
+ const { bytes: read, key: readKey } = checked ? { bytes: checked, key } : await this.keyed(path, caller, asked);
37079
37239
  const bytes = sum === void 0 ? read : await this.pinnedBytes(pin, read);
37080
37240
  const memory = importedMemory(bytes);
37081
37241
  const foreign = foreignImports(bytes);
@@ -37295,7 +37455,16 @@ var Launcher = class {
37295
37455
  const base = { abi: "emscripten", emscripten: "kernel", glue: "", module };
37296
37456
  return { ...base, ...memory ? { memory } : {}, path: target.glue };
37297
37457
  }
37458
+ checkLeaseProgram(target) {
37459
+ if (this.cdp.leaseOnly && (target.abi !== "wasi" || target.imports !== void 0)) {
37460
+ throw fsError(
37461
+ "EACCES",
37462
+ "a lease-only kernel runs only WASI modules without JavaScript imports"
37463
+ );
37464
+ }
37465
+ }
37298
37466
  async program(target, env, caller) {
37467
+ this.checkLeaseProgram(target);
37299
37468
  if (target.abi === "js" && target.wasm === SUDO_PATH) {
37300
37469
  return { abi: "js", glue: SUDO_SOURCE, path: SUDO_PATH };
37301
37470
  }
@@ -37554,11 +37723,16 @@ var Launcher = class {
37554
37723
  });
37555
37724
  }
37556
37725
  }
37726
+ mayStart(req) {
37727
+ if (this.leaseImage && req.cred.euid === 0)
37728
+ throw fsError("EACCES", "lease CLI may not run as root");
37729
+ if (this.disposing) throw fsError("EACCES", "lease job ended");
37730
+ if (req.pgid !== void 0 && this.jobs.sessionOf(req.pgid) === void 0)
37731
+ throw new SpawnError("ESRCH");
37732
+ }
37557
37733
  start(req) {
37734
+ this.mayStart(req);
37558
37735
  this.sampling();
37559
- if (req.pgid !== void 0 && this.jobs.sessionOf(req.pgid) === void 0) {
37560
- throw new SpawnError("ESRCH");
37561
- }
37562
37736
  const pid = req.pid ?? this.nextPid++;
37563
37737
  const cwdSlot = this.cwds.share(req.cwdSlot);
37564
37738
  this.cwdSlots.set(pid, cwdSlot);
@@ -38039,8 +38213,8 @@ var Launcher = class {
38039
38213
  childGroup(ppid, req) {
38040
38214
  const { pgid, session } = req;
38041
38215
  if (pgid === void 0 && session === void 0) return {};
38042
- const valid = pgid === void 0 || Number.isInteger(pgid) && pgid >= 0;
38043
- if (req.exec || !valid || session !== void 0 && session !== true) return "EINVAL";
38216
+ const valid2 = pgid === void 0 || Number.isInteger(pgid) && pgid >= 0;
38217
+ if (req.exec || !valid2 || session !== void 0 && session !== true) return "EINVAL";
38044
38218
  if (session) return pgid === void 0 ? { group: "session" } : "EINVAL";
38045
38219
  if (pgid === 0) return { group: "lead" };
38046
38220
  const sid = this.jobs.sessionOf(pgid);
@@ -38390,8 +38564,12 @@ var Launcher = class {
38390
38564
  attest(path, options = {}) {
38391
38565
  return attest(this.rootFs, path, {
38392
38566
  ...options,
38567
+ ...this.leaseImage && path === CLI_FILE ? { maxBytes: CLI_MAX } : {},
38393
38568
  users: this.usersMode,
38394
38569
  mounts: this.mounts.list().map((entry) => entry.target).filter((target) => this.mounts.mounted(target) !== void 0)
38570
+ }).then((record3) => {
38571
+ this.leaseImage?.attest(record3);
38572
+ return record3;
38395
38573
  });
38396
38574
  }
38397
38575
  watchSource(pid) {
@@ -38421,6 +38599,8 @@ var Launcher = class {
38421
38599
  return this.fileWatches.watch(paths, notify);
38422
38600
  }
38423
38601
  async mount(spec) {
38602
+ if (this.cdp.leaseOnly)
38603
+ throw fsError("EACCES", "a lease-only kernel cannot mount host services");
38424
38604
  this.guardMount(spec.target);
38425
38605
  const fsa = spec.type === "fsa" && !spec.source.startsWith("fsa:");
38426
38606
  const entry = await this.mounts.mount(
@@ -38433,7 +38613,8 @@ var Launcher = class {
38433
38613
  }
38434
38614
  async mountShm() {
38435
38615
  await this.base.mkdir(SHM, { recursive: true });
38436
- await this.mounts.mountSystem({ type: "tmpfs", source: "shm", target: SHM }, this.fs);
38616
+ if (!this.leaseImage)
38617
+ await this.mounts.mountSystem({ type: "tmpfs", source: "shm", target: SHM }, this.fs);
38437
38618
  await this.fs.chmod(SHM, 1023);
38438
38619
  }
38439
38620
  async ownTmp() {
@@ -38544,6 +38725,12 @@ var Launcher = class {
38544
38725
  for (const nodes of this.openFiles) nodes.revoke(at);
38545
38726
  for (const holds3 of this.held) holds3.revoke(at);
38546
38727
  }
38728
+ endLeaseProcesses() {
38729
+ this.disposing = true;
38730
+ this.leaseImage?.close();
38731
+ this.cdp.close();
38732
+ for (const process of this.processes.values()) process.kill();
38733
+ }
38547
38734
  unmountAll() {
38548
38735
  this.cron.stop();
38549
38736
  this.booting.abort();
@@ -38551,7 +38738,7 @@ var Launcher = class {
38551
38738
  for (const target of targets.sort((a, b) => b.length - a.length)) this.umount(target, true);
38552
38739
  }
38553
38740
  async permit(req) {
38554
- const policy = this.processMounts;
38741
+ const policy = !this.cdp.leaseOnly && this.processMounts;
38555
38742
  const allowed = typeof policy === "function" ? await policy(req) : policy;
38556
38743
  if (!allowed) throw fsError("EPERM", `process ${req.pid} may not ${req.op} ${req.target}`);
38557
38744
  }
@@ -38615,7 +38802,7 @@ var Launcher = class {
38615
38802
  await writeCaFile(this.base, this.ca).catch(() => void 0);
38616
38803
  await this.cron.provision().catch(() => void 0);
38617
38804
  this.fstab = this.mountFstab();
38618
- void this.cron.start();
38805
+ if (!this.leaseImage) void this.cron.start();
38619
38806
  }
38620
38807
  async mountFstab() {
38621
38808
  const text = await this.base.readFile(FSTAB_PATH).catch(() => "");
@@ -38637,10 +38824,11 @@ var Launcher = class {
38637
38824
  }
38638
38825
  );
38639
38826
  }
38640
- environment(cwd, extra, account, login2 = false) {
38827
+ environment(cwd, extra, account, session, login2 = false) {
38641
38828
  const env = {
38642
38829
  ...login2 ? { ...networkEnv(this.hostname), HOSTNAME: this.hostname, TZ: this.timeZone } : this.env,
38643
38830
  ...userEnv(account, this.pnpmHome),
38831
+ ...this.cdp.leaseOnly ? this.cdp.env(session) : {},
38644
38832
  PWD: cwd,
38645
38833
  ...extra
38646
38834
  };
@@ -38998,7 +39186,8 @@ var Launcher = class {
38998
39186
  COLORTERM: "truecolor",
38999
39187
  ...options.env
39000
39188
  },
39001
- account
39189
+ account,
39190
+ options.session
39002
39191
  );
39003
39192
  const report = (message3) => options.onData(encoder10.encode(`${message3}\r
39004
39193
  `));
@@ -39037,7 +39226,7 @@ var Launcher = class {
39037
39226
  tagged.tagBase,
39038
39227
  missing6
39039
39228
  );
39040
- const env = this.environment(cwd, options.env, account, options.login);
39229
+ const env = this.environment(cwd, options.env, account, options.session, options.login);
39041
39230
  const out = [];
39042
39231
  const err = [];
39043
39232
  const keep2 = options.collect !== false;
@@ -39217,6 +39406,31 @@ function clipboardAsker(port) {
39217
39406
  return { hook, answer: answer2 };
39218
39407
  }
39219
39408
 
39409
+ // src/fs/memory-budget.ts
39410
+ var LEASE_FS_BYTES = 64 * 1024 * 1024;
39411
+ var LEASE_FS_ENTRIES = 4096;
39412
+ var MemoryBudget = class {
39413
+ bytes = 0;
39414
+ entries = 0;
39415
+ closed = false;
39416
+ resize(before, after) {
39417
+ if (this.closed) throw new DOMException("job ended", "InvalidStateError");
39418
+ if (!Number.isSafeInteger(after) || after < 0 || this.bytes - before + after > LEASE_FS_BYTES) {
39419
+ throw new DOMException("lease file byte quota", "QuotaExceededError");
39420
+ }
39421
+ this.bytes += after - before;
39422
+ }
39423
+ entry(add) {
39424
+ this.resize(0, 0);
39425
+ if (this.entries + add > LEASE_FS_ENTRIES)
39426
+ throw new DOMException("lease file count quota", "QuotaExceededError");
39427
+ this.entries += add;
39428
+ }
39429
+ close() {
39430
+ this.closed = true;
39431
+ }
39432
+ };
39433
+
39220
39434
  // src/integrity-relay.ts
39221
39435
  function integrityAsker(port) {
39222
39436
  const asks = /* @__PURE__ */ new Map();
@@ -39238,6 +39452,261 @@ function integrityAsker(port) {
39238
39452
  return { lookup: lookup2, answer: answer2 };
39239
39453
  }
39240
39454
 
39455
+ // src/node/memory-root.ts
39456
+ var fail2 = (name2) => {
39457
+ throw new DOMException(name2, name2);
39458
+ };
39459
+ function valid(name2) {
39460
+ if (name2 === "" || name2 === "." || name2 === ".." || name2.includes("/")) {
39461
+ throw new TypeError(`invalid name: ${name2}`);
39462
+ }
39463
+ }
39464
+ var CHUNK4 = 1024 * 1024;
39465
+ function bytesOf2(data) {
39466
+ if (typeof data === "string") return new TextEncoder().encode(data);
39467
+ if (data instanceof Blob) return data.arrayBuffer().then((buffer) => new Uint8Array(buffer));
39468
+ if (ArrayBuffer.isView(data)) {
39469
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
39470
+ }
39471
+ return new Uint8Array(data);
39472
+ }
39473
+ var isParams = (data) => ["write", "seek", "truncate"].includes(data?.type) && !(data instanceof Blob);
39474
+ var Chunks = class {
39475
+ blobs;
39476
+ size;
39477
+ constructor(blobs = [], size = 0) {
39478
+ this.blobs = blobs;
39479
+ this.size = size;
39480
+ }
39481
+ pad(index, length2) {
39482
+ const blob = this.blobs[index] ?? new Blob([]);
39483
+ if (blob.size < length2)
39484
+ this.blobs[index] = new Blob([blob, new Uint8Array(length2 - blob.size)]);
39485
+ }
39486
+ grow(end) {
39487
+ if (end <= this.size) return;
39488
+ const last = Math.floor((end - 1) / CHUNK4);
39489
+ for (let i = 0; i < last; i++) this.pad(i, CHUNK4);
39490
+ this.pad(last, end - last * CHUNK4);
39491
+ this.size = end;
39492
+ }
39493
+ async write(at, bytes) {
39494
+ if (bytes.length === 0) return;
39495
+ const first = Math.floor(at / CHUNK4);
39496
+ for (let i = 0; i < first; i++) this.pad(i, CHUNK4);
39497
+ for (let done5 = 0; done5 < bytes.length; ) {
39498
+ const index = Math.floor((at + done5) / CHUNK4);
39499
+ const from = at + done5 - index * CHUNK4;
39500
+ const n = Math.min(CHUNK4 - from, bytes.length - done5);
39501
+ const view2 = bytes.subarray(done5, done5 + n);
39502
+ const part = view2.buffer instanceof ArrayBuffer ? view2 : view2.slice();
39503
+ const old = this.blobs[index];
39504
+ if (from === 0 && n >= (old?.size ?? 0)) this.blobs[index] = new Blob([part]);
39505
+ else {
39506
+ const merged3 = new Uint8Array(Math.max(old?.size ?? 0, from + n));
39507
+ if (old) merged3.set(new Uint8Array(await old.arrayBuffer()));
39508
+ merged3.set(part, from);
39509
+ this.blobs[index] = new Blob([merged3]);
39510
+ }
39511
+ done5 += n;
39512
+ }
39513
+ this.size = Math.max(this.size, at + bytes.length);
39514
+ }
39515
+ truncate(size) {
39516
+ if (size >= this.size) {
39517
+ this.grow(size);
39518
+ return;
39519
+ }
39520
+ const keep2 = Math.ceil(size / CHUNK4);
39521
+ this.blobs.length = keep2;
39522
+ if (keep2 > 0)
39523
+ this.blobs[keep2 - 1] = this.blobs[keep2 - 1].slice(0, size - (keep2 - 1) * CHUNK4);
39524
+ this.size = size;
39525
+ }
39526
+ };
39527
+ var MemoryFile = class {
39528
+ kind = "file";
39529
+ name;
39530
+ parent;
39531
+ data = new Chunks();
39532
+ removed = false;
39533
+ staging = /* @__PURE__ */ new Set();
39534
+ remove() {
39535
+ this.removed = true;
39536
+ for (const done5 of this.staging) done5();
39537
+ this.parent.budget?.resize(this.data.size, 0);
39538
+ this.data = new Chunks();
39539
+ this.parent.budget?.entry(-1);
39540
+ }
39541
+ lastModified = Date.now();
39542
+ constructor(name2, parent) {
39543
+ this.name = name2;
39544
+ this.parent = parent;
39545
+ }
39546
+ async getFile() {
39547
+ if (this.parent.removed || this.parent.children.get(this.name) !== this) fail2("NotFoundError");
39548
+ return new File(this.data.blobs, this.name, { lastModified: this.lastModified });
39549
+ }
39550
+ async createWritable({ keepExistingData = false } = {}) {
39551
+ const next3 = keepExistingData ? new Chunks([...this.data.blobs], this.data.size) : new Chunks();
39552
+ let position = 0;
39553
+ const budget = this.parent.budget;
39554
+ let reserved2 = next3.size;
39555
+ budget?.resize(0, reserved2);
39556
+ let ended = false;
39557
+ const abort = () => {
39558
+ if (ended) return;
39559
+ ended = true;
39560
+ budget?.resize(reserved2, 0);
39561
+ this.staging.delete(abort);
39562
+ };
39563
+ if (budget) this.staging.add(abort);
39564
+ const reserve = (size) => {
39565
+ if (budget && (ended || this.removed)) fail2("NotFoundError");
39566
+ budget?.resize(reserved2, size);
39567
+ reserved2 = size;
39568
+ };
39569
+ const truncate = (size) => {
39570
+ reserve(size);
39571
+ next3.truncate(size);
39572
+ };
39573
+ const put = async (data) => {
39574
+ const bytes = await bytesOf2(data);
39575
+ reserve(Math.max(next3.size, position + bytes.length));
39576
+ await next3.write(position, bytes);
39577
+ position += bytes.length;
39578
+ };
39579
+ return {
39580
+ write: async (data) => {
39581
+ if (!isParams(data)) return put(data);
39582
+ if (data.type === "truncate") return truncate(data.size ?? 0);
39583
+ position = data.position ?? position;
39584
+ if (data.type === "write") await put(data.data);
39585
+ },
39586
+ seek: async (at) => {
39587
+ position = at;
39588
+ },
39589
+ truncate: async (size) => truncate(size),
39590
+ close: async () => {
39591
+ if (budget && (ended || this.removed)) fail2("NotFoundError");
39592
+ budget?.resize(this.data.size, 0);
39593
+ ended = true;
39594
+ this.staging.delete(abort);
39595
+ this.data = next3;
39596
+ this.lastModified = Date.now();
39597
+ },
39598
+ abort: async () => abort()
39599
+ };
39600
+ }
39601
+ async move(parent, name2) {
39602
+ valid(name2);
39603
+ const old = parent.children.get(name2);
39604
+ if (old?.kind === "directory") fail2("InvalidModificationError");
39605
+ if (old && old !== this && parent.budget) old.remove();
39606
+ this.parent.children.delete(this.name);
39607
+ this.name = name2;
39608
+ this.parent = parent;
39609
+ parent.children.set(name2, this);
39610
+ }
39611
+ };
39612
+ var MemoryDirectory = class _MemoryDirectory {
39613
+ kind = "directory";
39614
+ name;
39615
+ parent;
39616
+ children = /* @__PURE__ */ new Map();
39617
+ removed = false;
39618
+ budget;
39619
+ constructor(name2, parent, budget = parent?.budget) {
39620
+ this.budget = budget;
39621
+ this.name = name2;
39622
+ this.parent = parent;
39623
+ }
39624
+ present() {
39625
+ if (this.removed) fail2("NotFoundError");
39626
+ }
39627
+ async getDirectoryHandle(name2, { create = false } = {}) {
39628
+ this.present();
39629
+ valid(name2);
39630
+ const found = this.children.get(name2);
39631
+ if (found?.kind === "file") fail2("TypeMismatchError");
39632
+ if (found) return found;
39633
+ if (!create) fail2("NotFoundError");
39634
+ this.budget?.entry(1);
39635
+ const dir = new _MemoryDirectory(name2, this);
39636
+ this.children.set(name2, dir);
39637
+ return dir;
39638
+ }
39639
+ async getFileHandle(name2, { create = false } = {}) {
39640
+ this.present();
39641
+ valid(name2);
39642
+ const found = this.children.get(name2);
39643
+ if (found?.kind === "directory") fail2("TypeMismatchError");
39644
+ if (found) return found;
39645
+ if (!create) fail2("NotFoundError");
39646
+ this.budget?.entry(1);
39647
+ const file = new MemoryFile(name2, this);
39648
+ this.children.set(name2, file);
39649
+ return file;
39650
+ }
39651
+ async removeEntry(name2, { recursive = false } = {}) {
39652
+ this.present();
39653
+ valid(name2);
39654
+ const found = this.children.get(name2);
39655
+ if (!found) return fail2("NotFoundError");
39656
+ if (found.kind === "directory" && found.children.size > 0 && !recursive) {
39657
+ fail2("InvalidModificationError");
39658
+ }
39659
+ this.children.delete(name2);
39660
+ if (found.kind === "directory" || this.budget) found.remove();
39661
+ }
39662
+ async resolve(handle) {
39663
+ const names2 = [];
39664
+ for (let at = handle; at !== this; at = at.parent) {
39665
+ if (!at || at.kind === "directory" && at.removed) return null;
39666
+ names2.unshift(at.name);
39667
+ }
39668
+ return names2;
39669
+ }
39670
+ remove() {
39671
+ this.removed = true;
39672
+ for (const child of this.children.values())
39673
+ if (child.kind === "directory" || this.budget) child.remove();
39674
+ if (this.budget) {
39675
+ this.children.clear();
39676
+ if (this.parent) this.budget.entry(-1);
39677
+ }
39678
+ }
39679
+ async *keys() {
39680
+ this.present();
39681
+ for (const name2 of [...this.children.keys()]) yield name2;
39682
+ }
39683
+ async *values() {
39684
+ for (const handle of [...this.children.values()]) yield handle;
39685
+ }
39686
+ async *entries() {
39687
+ for (const entry of [...this.children]) yield entry;
39688
+ }
39689
+ async move(parent, name2) {
39690
+ valid(name2);
39691
+ if (parent.children.has(name2)) fail2("InvalidModificationError");
39692
+ this.parent?.children.delete(this.name);
39693
+ this.name = name2;
39694
+ this.parent = parent;
39695
+ parent.children.set(name2, this);
39696
+ }
39697
+ };
39698
+ function leaseMemoryRoot() {
39699
+ const budget = new MemoryBudget();
39700
+ const dir = new MemoryDirectory("", null, budget);
39701
+ return {
39702
+ root: dir,
39703
+ clear() {
39704
+ dir.remove();
39705
+ budget.close();
39706
+ }
39707
+ };
39708
+ }
39709
+
39241
39710
  // src/sealed-relay.ts
39242
39711
  function textOf(err) {
39243
39712
  return err instanceof Error ? err.message : String(err);
@@ -39431,8 +39900,9 @@ async function stores(deps, name2, media) {
39431
39900
  };
39432
39901
  }
39433
39902
  function cdpOption(req, port) {
39434
- if (!req.cdp) return {};
39903
+ if (!req.cdp && !req.leaseTag) return {};
39435
39904
  return {
39905
+ ...req.leaseTag ? { leaseTag: req.leaseTag } : {},
39436
39906
  cdp: portCdpHook(
39437
39907
  (request3, cdp) => port.postMessage({ cdpOpen: request3, port: cdp }, [cdp])
39438
39908
  )
@@ -39580,9 +40050,16 @@ async function connectClient(deps, { user, tag, requests: bind2, devices }) {
39580
40050
  if (user !== void 0 && !await l.users.lookup(user)) {
39581
40051
  throw fsError("ENOENT", `no user ${String(user)}`);
39582
40052
  }
39583
- const { port1, port2 } = new MessageChannel();
39584
- const held2 = deps.held ? await deps.held() : void 0;
40053
+ if (l.leaseImage) {
40054
+ l.leaseImage.ready();
40055
+ if (user !== void 0 && user !== LEASE_USER)
40056
+ throw fsError("EPERM", "lease job user is fixed");
40057
+ user = LEASE_USER;
40058
+ }
40059
+ const held2 = !l.leaseImage && deps.held ? await deps.held() : void 0;
39585
40060
  const client = ++clientIds;
40061
+ const endLease = l.cdp.bindClient(client, tag, bind2 || devices);
40062
+ const { port1, port2 } = new MessageChannel();
39586
40063
  const served2 = serveClient(port1, {
39587
40064
  launcher: deps.ready,
39588
40065
  signal: signalNumber,
@@ -39591,13 +40068,14 @@ async function connectClient(deps, { user, tag, requests: bind2, devices }) {
39591
40068
  ...devices === "attach" ? { attachDevices: true } : {},
39592
40069
  ...user !== void 0 ? { user } : {},
39593
40070
  ...tag !== void 0 ? { tag } : {},
39594
- ...deps.locks ? { locks: deps.locks } : {},
40071
+ ...!l.leaseImage && deps.locks ? { locks: deps.locks } : {},
39595
40072
  ...held2 ? { lock: held2 } : {}
39596
40073
  });
39597
40074
  deps.clients.add(served2);
39598
40075
  const unbind = bind2 && bind2 !== "attach" ? l.embedder.register(client, deps.requests.hookFor(client, bind2)) : void 0;
39599
40076
  const unbindDevices = devices === true ? l.devices.register(client, deps.devices.hookFor(client)) : void 0;
39600
40077
  void served2.closed.then(() => {
40078
+ endLease?.();
39601
40079
  deps.clients.delete(served2);
39602
40080
  unbind?.();
39603
40081
  unbindDevices?.();
@@ -39685,8 +40163,63 @@ function lockHolder() {
39685
40163
  return holding;
39686
40164
  };
39687
40165
  }
40166
+ async function memoryLauncher(deps, port, req, root) {
40167
+ const fs = new OpfsFs(root, new MemoryMeta(LEASE_FS_ENTRIES), void 0, {
40168
+ ranged: true,
40169
+ locks: null
40170
+ });
40171
+ const image = new LeaseCliImage(fs.unguarded());
40172
+ const l = new Launcher({
40173
+ fs,
40174
+ ...workers(deps),
40175
+ ...cdpOption(req, port),
40176
+ leaseImage: image,
40177
+ protect: { paths: ["/node_modules"] },
40178
+ users: "enforce",
40179
+ cron: { poll: false }
40180
+ });
40181
+ await l.prepare();
40182
+ await l.users.add({ name: LEASE_USER });
40183
+ return l;
40184
+ }
40185
+ var LeaseWorker = class {
40186
+ memory;
40187
+ disposed = false;
40188
+ get active() {
40189
+ return this.memory !== void 0;
40190
+ }
40191
+ boot(req, deps, port, initialized) {
40192
+ if (initialized || !req.leaseTag || !req.leaseMemory || req.root || req.rootPath || req.metadata !== false || req.media !== false || req.ca !== false)
40193
+ throw fsError("EINVAL", "invalid memory lease initialization");
40194
+ this.memory = leaseMemoryRoot();
40195
+ return memoryLauncher(deps, port, req, this.memory.root);
40196
+ }
40197
+ async command(req, ready2, clients, next3) {
40198
+ if (this.disposed) throw fsError("EPERM", "lease job ended");
40199
+ if (req.op === "lease-memory-end") {
40200
+ if (this.memory === void 0) throw fsError("EPERM", "not a memory lease");
40201
+ this.disposed = true;
40202
+ const l = await ready2();
40203
+ l.endLeaseProcesses();
40204
+ for (const c of clients) c.detach();
40205
+ l.unmountAll();
40206
+ this.memory.clear();
40207
+ return true;
40208
+ }
40209
+ if (req.op === "lease-cli-install") {
40210
+ const l = await ready2();
40211
+ if (!l.leaseImage) throw fsError("EPERM", "not a memory lease");
40212
+ await l.leaseImage.install(req.input);
40213
+ return true;
40214
+ }
40215
+ if (this.active && req.op !== "attest" && req.op !== "connect")
40216
+ throw fsError("EPERM", "use the bound lease job port");
40217
+ return next3(req);
40218
+ }
40219
+ };
39688
40220
  function serveKernel(port, deps) {
39689
40221
  let launcher;
40222
+ const leaseWorker = new LeaseWorker();
39690
40223
  let remote;
39691
40224
  let uplink;
39692
40225
  const reply = (id2, body, transfer) => port.postMessage({ id: id2, ...body }, transfer);
@@ -39709,6 +40242,11 @@ function serveKernel(port, deps) {
39709
40242
  }
39710
40243
  const processes2 = processOps(ready2, reply);
39711
40244
  async function init(req) {
40245
+ if (req.leaseTag || req.leaseMemory) {
40246
+ launcher = leaseWorker.boot(req, deps, port, launcher !== void 0);
40247
+ await launcher;
40248
+ return "cdp-lease-v1";
40249
+ }
39712
40250
  launcher = rootOf(deps, req).then(async (root) => {
39713
40251
  req = await rootNamed(deps, req, root);
39714
40252
  const name2 = req.metadata ?? META_DB;
@@ -39810,7 +40348,7 @@ function serveKernel(port, deps) {
39810
40348
  if (allowed(event.data)) return;
39811
40349
  if (answered2(event.data, remote, uplink, approvals)) return;
39812
40350
  const req = event.data;
39813
- handle(req).then(
40351
+ leaseWorker.command(req, ready2, clients, handle).then(
39814
40352
  (result) => reply(req.id, { result }, transferOf2(req, result)),
39815
40353
  (err) => reply(req.id, failure(err))
39816
40354
  );