@ai-ecoverse/slicc-kernel 1.193.4 → 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.
package/dist/index.js CHANGED
@@ -1,5 +1,174 @@
1
+ // src/cdp/lease.ts
2
+ var CDP_LEASE_VERSION = 1;
3
+ var LEASE_MAX_MESSAGE = 128 * 1024;
4
+ var BOOT_FIELDS = {
5
+ browser: /* @__PURE__ */ new Set(["cdpLease", "metadata", "media", "ca"]),
6
+ node: /* @__PURE__ */ new Set(["cdpLease"]),
7
+ cloudflare: /* @__PURE__ */ new Set(["cdpLease", "loader"])
8
+ };
9
+ function checkedLease(options, host) {
10
+ const lease = options.cdpLease;
11
+ if (lease === void 0) return void 0;
12
+ if (typeof lease?.tag !== "string" || Reflect.ownKeys(lease).some((k) => k !== "tag" && k !== "adapter") || !/^[a-zA-Z0-9:_-]{1,128}$/.test(lease.tag) || typeof lease.adapter?.request !== "function" || typeof lease.adapter?.action !== "function") {
13
+ throw new TypeError("cdpLease requires one job tag and a request/action adapter");
14
+ }
15
+ if (Object.getPrototypeOf(options) !== Object.prototype || Reflect.ownKeys(options).some((k) => typeof k !== "string" || !BOOT_FIELDS[host].has(k))) {
16
+ throw new TypeError("unexpected boot option for a lease-only kernel");
17
+ }
18
+ return { tag: lease.tag, adapter: lease.adapter };
19
+ }
20
+ var LEASE_MAX_CONNECTIONS = 8;
21
+ var ERRORS = /* @__PURE__ */ new Map([
22
+ ["E_PENDING", "Waiting for the owner."],
23
+ ["E_SCOPE", "Outside the approved lease."],
24
+ ["E_EXPIRED", "The lease expired."],
25
+ ["E_REVOKED", "The lease is no longer active."],
26
+ ["E_DENIED", "The owner declined the request."],
27
+ ["E_UNSUPPORTED", "Lease operation unavailable."],
28
+ ["E_REPLACED", "The lease was replaced."],
29
+ ["E_STALE", "The element reference is stale."],
30
+ ["E_UNAVAILABLE", "No job-scoped adapter is available."],
31
+ ["E_OUTCOME_UNKNOWN", "The action may have taken effect. Do not automatically retry."]
32
+ ]);
33
+ function record(value) {
34
+ return typeof value === "object" && value !== null && !Array.isArray(value);
35
+ }
36
+ function fields(obj, ...keys) {
37
+ return Object.keys(obj).every((k) => keys.includes(k));
38
+ }
39
+ function opaque(v) {
40
+ return typeof v === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(v);
41
+ }
42
+ function hasControl(text) {
43
+ for (let i = 0; i < text.length; i++) {
44
+ const n = text.charCodeAt(i);
45
+ if (n < 32 || n === 127) return true;
46
+ }
47
+ return false;
48
+ }
49
+ function https(v) {
50
+ if (typeof v !== "string" || v.length > 8192 || !v.startsWith("https://") || /\s/u.test(v) || v.includes("\\") || hasControl(v))
51
+ return false;
52
+ const url = URL.parse(v);
53
+ return url !== null && !url.username && !url.password && !/^https:\/\/[^/?#]*@/.test(v);
54
+ }
55
+ function rule(v) {
56
+ if (!record(v) || !fields(v, "kind", "url") || !https(v.url) || /\*|%(?![0-9a-f]{2})/i.test(v.url))
57
+ return false;
58
+ const url = new URL(v.url);
59
+ if (v.kind === "origin") return url.origin === v.url;
60
+ if (url.href !== v.url || /%2f|%5c/i.test(url.pathname)) return false;
61
+ if (v.kind === "exact") return true;
62
+ return v.kind === "path-prefix" && url.origin + url.pathname === v.url && (url.pathname === "/" || !url.pathname.endsWith("/"));
63
+ }
64
+ function request(p) {
65
+ return fields(p, "allow", "ttlSeconds", "lease", "reason") && Array.isArray(p.allow) && p.allow.length > 0 && p.allow.length <= 64 && p.allow.every(rule) && new Set(p.allow.map(({ kind, url }) => `${kind}:${url}`)).size === p.allow.length && (p.lease === void 0 ? Number.isSafeInteger(p.ttlSeconds) && p.ttlSeconds > 0 : opaque(p.lease) && p.ttlSeconds === void 0) && (p.reason === void 0 || typeof p.reason === "string" && p.reason.length > 0 && p.reason.length <= 1024);
66
+ }
67
+ function action(p) {
68
+ if (!fields(p, "lease", "op", "args") || !opaque(p.lease) || !record(p.args)) return false;
69
+ const a = p.args;
70
+ switch (p.op) {
71
+ case "goto":
72
+ return fields(a, "url") && https(a.url);
73
+ case "snapshot":
74
+ return fields(a);
75
+ default:
76
+ return false;
77
+ }
78
+ }
79
+ async function dispatch(adapter, ctx, method, p) {
80
+ if (record(p) && method === "Slicc.leaseRequest" && request(p)) {
81
+ const reply2 = await adapter.request(p, ctx);
82
+ if (opaque(reply2.request) && opaque(reply2.lease) && typeof reply2.jkt === "string" && /^[A-Za-z0-9_-]{43}$/.test(reply2.jkt)) {
83
+ return { request: reply2.request, lease: reply2.lease, jkt: reply2.jkt };
84
+ }
85
+ }
86
+ if (record(p) && method === "Slicc.leaseAction" && action(p)) {
87
+ let result;
88
+ try {
89
+ ({ result } = await adapter.action(p, ctx));
90
+ } catch (err) {
91
+ if (record(err) && typeof err.reason === "string" && ERRORS.has(err.reason)) throw err;
92
+ throw { reason: "E_OUTCOME_UNKNOWN" };
93
+ }
94
+ if (record(result)) {
95
+ if (p.op !== "snapshot" && fields(result)) return { result: {} };
96
+ if (p.op === "snapshot" && fields(result, "text") && typeof result.text === "string" && result.text.length <= 65536)
97
+ return { result: { text: result.text } };
98
+ }
99
+ throw { reason: "E_OUTCOME_UNKNOWN" };
100
+ }
101
+ throw new Error();
102
+ }
103
+ async function reply(adapter, ctx, message, busy) {
104
+ let id = null;
105
+ try {
106
+ const cmd = JSON.parse(message);
107
+ if (!record(cmd) || !Number.isSafeInteger(cmd.id) || cmd.id < 1) throw new Error();
108
+ id = cmd.id;
109
+ if (!fields(cmd, "id", "method", "params")) throw new Error();
110
+ if (busy) throw { reason: "E_UNAVAILABLE" };
111
+ const result = await dispatch(adapter, ctx, cmd.method, cmd.params);
112
+ const text = JSON.stringify({ id, result });
113
+ if (new TextEncoder().encode(text).length > LEASE_MAX_MESSAGE) throw new Error();
114
+ return text;
115
+ } catch (err) {
116
+ const reason = record(err) && typeof err.reason === "string" && ERRORS.has(err.reason) ? err.reason : "E_UNSUPPORTED";
117
+ return JSON.stringify({
118
+ id,
119
+ error: { code: -32e3, message: ERRORS.get(reason), data: { reason } }
120
+ });
121
+ }
122
+ }
123
+ function leaseHook({ tag, adapter }) {
124
+ let pending = 0;
125
+ return async ({ stamp }) => {
126
+ if (!stamp || stamp.tag !== tag) throw new Error("lease unavailable");
127
+ const stop = new AbortController();
128
+ const conn = {
129
+ onmessage: null,
130
+ onclose: null,
131
+ send(message) {
132
+ if (stop.signal.aborted) return;
133
+ const busy = pending >= LEASE_MAX_CONNECTIONS;
134
+ pending++;
135
+ void reply(
136
+ adapter,
137
+ { stamp: structuredClone(stamp), signal: stop.signal },
138
+ message,
139
+ busy
140
+ ).then((text) => {
141
+ pending--;
142
+ if (!stop.signal.aborted) conn.onmessage?.(text);
143
+ });
144
+ },
145
+ close: () => stop.abort()
146
+ };
147
+ return conn;
148
+ };
149
+ }
150
+
151
+ // src/fs/types.ts
152
+ var DEFAULT_USERS = "enforce";
153
+ function fsError(code, path) {
154
+ return Object.assign(new Error(`${code}: ${path}`), { code });
155
+ }
156
+
157
+ // src/cdp/lease-cli.ts
158
+ var CLI_PKG = "/node_modules/@ai-ecoverse/slicc-cdp";
159
+ var CLI_FILE = `${CLI_PKG}/bin/playwright-cli.wasm`;
160
+ var CLI_MAX = 8 * 1024 * 1024;
161
+ function checkCli({ wasm, sha256 }) {
162
+ if (!(wasm instanceof Uint8Array) || wasm.length < 8 || wasm.length > CLI_MAX || !/^[a-f0-9]{64}$/.test(sha256))
163
+ throw fsError("EINVAL", "invalid lease CLI image or SHA-256");
164
+ }
165
+ var MANIFEST = JSON.stringify({
166
+ name: "@ai-ecoverse/slicc-cdp",
167
+ slicc: { abi: "wasi", commands: { "playwright-cli": { wasm: "bin/playwright-cli.wasm" } } }
168
+ });
169
+
1
170
  // src/cdp/port.ts
2
- function serveCdpPort(port, hook, request, onDone) {
171
+ function serveCdpPort(port, hook, request2, onDone) {
3
172
  let conn;
4
173
  let done = false;
5
174
  const end = () => {
@@ -20,7 +189,7 @@ function serveCdpPort(port, hook, request, onDone) {
20
189
  }
21
190
  });
22
191
  port.start?.();
23
- new Promise((resolve) => resolve(hook(request))).then(
192
+ new Promise((resolve) => resolve(hook(request2))).then(
24
193
  (opened) => {
25
194
  conn = opened;
26
195
  if (done) return opened.close();
@@ -239,11 +408,11 @@ function stream(chunks2, socket, signal) {
239
408
  }
240
409
  });
241
410
  }
242
- async function requestBytes(request) {
243
- const url = new URL(request.url);
244
- const body = request.body ? new Uint8Array(await request.arrayBuffer()) : void 0;
245
- const lines = [`${request.method} ${url.pathname}${url.search} HTTP/1.1`, `Host: ${url.host}`];
246
- request.headers.forEach((value, name) => {
411
+ async function requestBytes(request2) {
412
+ const url = new URL(request2.url);
413
+ const body = request2.body ? new Uint8Array(await request2.arrayBuffer()) : void 0;
414
+ const lines = [`${request2.method} ${url.pathname}${url.search} HTTP/1.1`, `Host: ${url.host}`];
415
+ request2.headers.forEach((value, name) => {
247
416
  if (!OWN_HEADERS.has(name)) lines.push(`${name}: ${value}`);
248
417
  });
249
418
  if (body) lines.push(`Content-Length: ${body.length}`);
@@ -256,8 +425,8 @@ async function requestBytes(request) {
256
425
  }
257
426
  async function loopbackFetch(dial, input, options) {
258
427
  options.signal?.throwIfAborted();
259
- const request = input instanceof Request ? input : new Request(input);
260
- const bytes = await requestBytes(request);
428
+ const request2 = input instanceof Request ? input : new Request(input);
429
+ const bytes = await requestBytes(request2);
261
430
  const socket = await dial({
262
431
  port: options.port,
263
432
  ...options.host ? { host: options.host } : {}
@@ -274,7 +443,7 @@ async function loopbackFetch(dial, input, options) {
274
443
  if (!raw) throw errorWithCode("ECONNRESET: the connection closed before a response");
275
444
  head = parseHead(raw);
276
445
  } while (head.status >= 100 && head.status < 200);
277
- const chunks2 = bodyOf(source, head, request.method);
446
+ const chunks2 = bodyOf(source, head, request2.method);
278
447
  if (!chunks2) socket.close();
279
448
  return new Response(chunks2 ? stream(chunks2, socket, options.signal) : null, {
280
449
  status: head.status,
@@ -444,9 +613,9 @@ function errorOf2(err) {
444
613
  const message = err instanceof Error ? err.message : String(err);
445
614
  return { name: typeof name === "string" ? name : "Error", message };
446
615
  }
447
- function bytesOf(reply) {
448
- if (reply instanceof ReadableStream) return reply;
449
- const bytes = typeof reply === "string" ? new TextEncoder().encode(reply) : reply instanceof Uint8Array ? reply : new Uint8Array(0);
616
+ function bytesOf(reply2) {
617
+ if (reply2 instanceof ReadableStream) return reply2;
618
+ const bytes = typeof reply2 === "string" ? new TextEncoder().encode(reply2) : reply2 instanceof Uint8Array ? reply2 : new Uint8Array(0);
450
619
  return new ReadableStream({
451
620
  start(controller) {
452
621
  if (bytes.length > 0) controller.enqueue(bytes);
@@ -490,7 +659,7 @@ function embedderAnswerer(port, hookFor) {
490
659
  name: "NotSupportedError"
491
660
  });
492
661
  const body = bodyStream(ask.id, state, post);
493
- const reply = await hook.handle({
662
+ const reply2 = await hook.handle({
494
663
  kind: ask.kind,
495
664
  options: ask.options,
496
665
  body,
@@ -498,8 +667,8 @@ function embedderAnswerer(port, hookFor) {
498
667
  signal: state.abort.signal,
499
668
  progress: (line) => post({ id: ask.id, progress: String(line) })
500
669
  });
501
- if (!(reply instanceof ReadableStream)) post({ id: ask.id, bodyCancel: true });
502
- state.reader = bytesOf(reply).getReader();
670
+ if (!(reply2 instanceof ReadableStream)) post({ id: ask.id, bodyCancel: true });
671
+ state.reader = bytesOf(reply2).getReader();
503
672
  post({ id: ask.id, ready: true });
504
673
  } catch (err) {
505
674
  fail(ask.id, err);
@@ -593,9 +762,6 @@ function serveFacadePort(port, hook, { name, stamp }, onDone) {
593
762
  };
594
763
  }
595
764
 
596
- // src/fs/types.ts
597
- var DEFAULT_USERS = "enforce";
598
-
599
765
  // src/fs/protect.ts
600
766
  function protectInit(protection) {
601
767
  const writers = [...writerTags(protection)];
@@ -860,7 +1026,7 @@ var HIGH_WATER = 64 * 1024;
860
1026
  var DEFAULT_SETTINGS = settingsOf(SERIAL_CFLAG, 9600);
861
1027
  function devicesHook(hook) {
862
1028
  if (typeof hook?.open !== "function") throw new TypeError("devices needs open");
863
- return { open: (request) => hook.open(request) };
1029
+ return { open: (request2) => hook.open(request2) };
864
1030
  }
865
1031
 
866
1032
  // src/kernel/net/loopback-names.ts
@@ -904,26 +1070,26 @@ var UNSAFE_FIELD = /[\r\n\0]/;
904
1070
  function sealedHooks(option) {
905
1071
  if (!option) return {};
906
1072
  if (typeof option === "function") return { request: option };
907
- const { request, fetch } = option;
908
- if (typeof request !== "function" || fetch !== void 0 && typeof fetch !== "function") {
1073
+ const { request: request2, fetch } = option;
1074
+ if (typeof request2 !== "function" || fetch !== void 0 && typeof fetch !== "function") {
909
1075
  throw new TypeError("sealed takes a function or { request, fetch? }");
910
1076
  }
911
- return { request, ...fetch ? { fetch } : {} };
1077
+ return { request: request2, ...fetch ? { fetch } : {} };
912
1078
  }
913
1079
  function headerList(headers) {
914
1080
  return Array.isArray(headers) && headers.every(
915
1081
  (field) => Array.isArray(field) && field.length === 2 && field.every((text) => typeof text === "string" && !UNSAFE_FIELD.test(text))
916
1082
  );
917
1083
  }
918
- function sealedReplyValid(reply) {
919
- if (typeof reply !== "object" || reply === null) return false;
920
- const { redirects, redirected, status, statusText, headers, url, body, cancel } = reply;
1084
+ function sealedReplyValid(reply2) {
1085
+ if (typeof reply2 !== "object" || reply2 === null) return false;
1086
+ const { redirects, redirected, status, statusText, headers, url, body, cancel } = reply2;
921
1087
  return redirects === void 0 && redirected !== true && Number.isInteger(status) && status >= 100 && status <= 599 && typeof statusText === "string" && !UNSAFE_FIELD.test(statusText) && headerList(headers) && (url === void 0 || typeof url === "string") && typeof body?.[Symbol.asyncIterator] === "function" && typeof cancel === "function";
922
1088
  }
923
- function dropSealedReply(reply) {
924
- const { cancel } = reply ?? {};
1089
+ function dropSealedReply(reply2) {
1090
+ const { cancel } = reply2 ?? {};
925
1091
  if (typeof cancel !== "function") return;
926
- void Promise.resolve().then(() => cancel.call(reply)).catch(() => void 0);
1092
+ void Promise.resolve().then(() => cancel.call(reply2)).catch(() => void 0);
927
1093
  }
928
1094
 
929
1095
  // src/kernel/net/routes.ts
@@ -1046,7 +1212,7 @@ function serveUplink(peer, uplink) {
1046
1212
  const abort = new AbortController();
1047
1213
  pending.set(uid, abort);
1048
1214
  void work(abort.signal).then(
1049
- (reply) => reply && peer.postMessage(reply, transferOf(reply)),
1215
+ (reply2) => reply2 && peer.postMessage(reply2, transferOf(reply2)),
1050
1216
  (e) => peer.postMessage(failure(uid, e))
1051
1217
  ).finally(() => pending.delete(uid));
1052
1218
  };
@@ -1173,12 +1339,12 @@ var UdpServer = class {
1173
1339
  for (const cid of [...this.sockets.keys()]) this.drop(cid);
1174
1340
  }
1175
1341
  };
1176
- function transferOf(reply) {
1177
- if (reply.uplink === "udp-message" && reply.message && "bytes" in reply.message) {
1178
- return [reply.message.bytes.buffer];
1342
+ function transferOf(reply2) {
1343
+ if (reply2.uplink === "udp-message" && reply2.message && "bytes" in reply2.message) {
1344
+ return [reply2.message.bytes.buffer];
1179
1345
  }
1180
- if (reply.uplink !== "data" || !reply.bytes) return void 0;
1181
- return [reply.bytes.buffer];
1346
+ if (reply2.uplink !== "data" || !reply2.bytes) return void 0;
1347
+ return [reply2.bytes.buffer];
1182
1348
  }
1183
1349
 
1184
1350
  // src/sealed-relay.ts
@@ -1226,10 +1392,10 @@ function uploadOf(far) {
1226
1392
  }
1227
1393
  function answerFetch(hook, { req, port: far }, live) {
1228
1394
  const control = new AbortController();
1229
- const { streamed, ...fields } = req;
1395
+ const { streamed, ...fields2 } = req;
1230
1396
  const upload = uploadOf(far);
1231
1397
  let source;
1232
- let reply;
1398
+ let reply2;
1233
1399
  let closed = false;
1234
1400
  const settle = () => {
1235
1401
  closed = true;
@@ -1241,7 +1407,7 @@ function answerFetch(hook, { req, port: far }, live) {
1241
1407
  if (closed) return;
1242
1408
  settle();
1243
1409
  control.abort(reason);
1244
- dropSealedReply(reply);
1410
+ dropSealedReply(reply2);
1245
1411
  far.close();
1246
1412
  }
1247
1413
  };
@@ -1251,7 +1417,7 @@ function answerFetch(hook, { req, port: far }, live) {
1251
1417
  far.postMessage(message);
1252
1418
  };
1253
1419
  const failWith = (err) => {
1254
- dropSealedReply(reply);
1420
+ dropSealedReply(reply2);
1255
1421
  finish({ t: "error", message: textOf(err) });
1256
1422
  };
1257
1423
  const read = async () => {
@@ -1268,17 +1434,17 @@ function answerFetch(hook, { req, port: far }, live) {
1268
1434
  const ask = async () => {
1269
1435
  try {
1270
1436
  if (!hook) throw new Error("no vault is connected");
1271
- const request = {
1272
- ...fields,
1437
+ const request2 = {
1438
+ ...fields2,
1273
1439
  ...streamed ? { bodyStream: upload.stream } : {}
1274
1440
  };
1275
- const answered = await hook(request, { signal: control.signal });
1441
+ const answered = await hook(request2, { signal: control.signal });
1276
1442
  if (!sealedReplyValid(answered)) {
1277
1443
  dropSealedReply(answered);
1278
1444
  throw new Error("the reply is not a scrubbed response");
1279
1445
  }
1280
1446
  if (closed) return dropSealedReply(answered);
1281
- reply = answered;
1447
+ reply2 = answered;
1282
1448
  source = answered.body[Symbol.asyncIterator]();
1283
1449
  const { status, statusText, headers, url } = answered;
1284
1450
  far.postMessage({
@@ -1310,8 +1476,8 @@ function sealedAnswerer(port, hook, fetchHook) {
1310
1476
  asked.set(id, control);
1311
1477
  try {
1312
1478
  if (!hook) throw new Error("no vault is connected");
1313
- const reply = await hook(req, { signal: control.signal });
1314
- port.postMessage({ sealedReply: { id, reply } });
1479
+ const reply2 = await hook(req, { signal: control.signal });
1480
+ port.postMessage({ sealedReply: { id, reply: reply2 } });
1315
1481
  } catch (err) {
1316
1482
  const error = err instanceof Error ? err.message : String(err);
1317
1483
  port.postMessage({ sealedReply: { id, error } });
@@ -1474,12 +1640,12 @@ function unopened(url, code) {
1474
1640
  status: 502
1475
1641
  });
1476
1642
  }
1477
- function openWebSocket(Socket, request, withHeaders) {
1478
- const { url, protocols, signal } = request;
1643
+ function openWebSocket(Socket, request2, withHeaders) {
1644
+ const { url, protocols, signal } = request2;
1479
1645
  signal.throwIfAborted();
1480
1646
  let socket;
1481
1647
  try {
1482
- socket = withHeaders ? new Socket(url, { protocols, headers: headerRecord(request.headers) }) : new Socket(url, protocols);
1648
+ socket = withHeaders ? new Socket(url, { protocols, headers: headerRecord(request2.headers) }) : new Socket(url, protocols);
1483
1649
  } catch (e) {
1484
1650
  return Promise.reject(Object.assign(new Error(blockedReason(url, e)), { status: 502 }));
1485
1651
  }
@@ -1624,11 +1790,11 @@ function streamOf(body) {
1624
1790
  { highWaterMark: 0 }
1625
1791
  );
1626
1792
  }
1627
- function requestBody(request) {
1628
- if (request.bodyStream) {
1629
- return { body: streamOf(request.bodyStream), duplex: "half" };
1793
+ function requestBody(request2) {
1794
+ if (request2.bodyStream) {
1795
+ return { body: streamOf(request2.bodyStream), duplex: "half" };
1630
1796
  }
1631
- return request.body ? { body: request.body } : {};
1797
+ return request2.body ? { body: request2.body } : {};
1632
1798
  }
1633
1799
  function fetchTransport(options = {}) {
1634
1800
  const send = options.fetch ?? globalThis.fetch.bind(globalThis);
@@ -1647,28 +1813,28 @@ function fetchTransport(options = {}) {
1647
1813
  ...Socket ? { websocket: true } : {},
1648
1814
  ...options.streamingBodies ? { streamingBodies: true } : {}
1649
1815
  },
1650
- ...Socket ? { websocket: (request) => openWebSocket(Socket, request, headers) } : {},
1651
- async fetch(request) {
1652
- const sent = sentHeaders(request.headers, inPage);
1653
- if (refuse) refuseUnsendable(request.url, sent, options.hint);
1816
+ ...Socket ? { websocket: (request2) => openWebSocket(Socket, request2, headers) } : {},
1817
+ async fetch(request2) {
1818
+ const sent = sentHeaders(request2.headers, inPage);
1819
+ if (refuse) refuseUnsendable(request2.url, sent, options.hint);
1654
1820
  let response;
1655
1821
  try {
1656
- response = await send(request.url, {
1657
- method: request.method,
1822
+ response = await send(request2.url, {
1823
+ method: request2.method,
1658
1824
  headers: sent,
1659
- ...requestBody(request),
1660
- signal: request.signal,
1661
- redirect: request.redirect ?? instance,
1825
+ ...requestBody(request2),
1826
+ signal: request2.signal,
1827
+ redirect: request2.redirect ?? instance,
1662
1828
  credentials: "omit",
1663
1829
  mode: "cors"
1664
1830
  });
1665
1831
  } catch (e) {
1666
- if (request.signal.aborted) throw e;
1832
+ if (request2.signal.aborted) throw e;
1667
1833
  const causeCode = e?.cause?.code;
1668
1834
  const dns = typeof causeCode === "string" && DNS_CODES.has(causeCode);
1669
1835
  throw Object.assign(
1670
1836
  new Error(
1671
- `fetch ${request.url} failed (unreachable, or not allowed by CORS)${options.hint ? `: ${options.hint}` : ""}`
1837
+ `fetch ${request2.url} failed (unreachable, or not allowed by CORS)${options.hint ? `: ${options.hint}` : ""}`
1672
1838
  ),
1673
1839
  { status: 502 },
1674
1840
  dns ? { code: causeCode } : {},
@@ -1953,26 +2119,26 @@ var RemoteTransport = class {
1953
2119
  this.port = port;
1954
2120
  this.traits = traits;
1955
2121
  }
1956
- receive(reply) {
1957
- if (reply.net === "body-pull") {
1958
- void this.pull(reply.nid);
2122
+ receive(reply2) {
2123
+ if (reply2.net === "body-pull") {
2124
+ void this.pull(reply2.nid);
1959
2125
  return;
1960
2126
  }
1961
- const socket = this.sockets.get(reply.nid);
1962
- if (socket && this.toSocket(reply, socket)) return;
1963
- const waiter = this.waiting.get(reply.nid);
2127
+ const socket = this.sockets.get(reply2.nid);
2128
+ if (socket && this.toSocket(reply2, socket)) return;
2129
+ const waiter = this.waiting.get(reply2.nid);
1964
2130
  if (!waiter) return;
1965
- this.waiting.delete(reply.nid);
1966
- if (reply.net === "error") {
1967
- waiter.reject(new TransportError(reply.message, reply.status, reply.code, reply.detail));
1968
- } else waiter.resolve(reply);
1969
- }
1970
- toSocket(reply, socket) {
1971
- if (reply.net === "ws-message") socket.queue.push(reply.data);
1972
- else if (reply.net === "ws-acked") socket.acked(reply.n);
1973
- else if (reply.net === "ws-closed") {
1974
- this.sockets.delete(reply.nid);
1975
- socket.queue.end({ code: reply.code, reason: reply.reason });
2131
+ this.waiting.delete(reply2.nid);
2132
+ if (reply2.net === "error") {
2133
+ waiter.reject(new TransportError(reply2.message, reply2.status, reply2.code, reply2.detail));
2134
+ } else waiter.resolve(reply2);
2135
+ }
2136
+ toSocket(reply2, socket) {
2137
+ if (reply2.net === "ws-message") socket.queue.push(reply2.data);
2138
+ else if (reply2.net === "ws-acked") socket.acked(reply2.n);
2139
+ else if (reply2.net === "ws-closed") {
2140
+ this.sockets.delete(reply2.nid);
2141
+ socket.queue.end({ code: reply2.code, reason: reply2.reason });
1976
2142
  } else return false;
1977
2143
  return true;
1978
2144
  }
@@ -2024,9 +2190,9 @@ var RemoteTransport = class {
2024
2190
  waiter?.reject(new TransportError("the request was cancelled"));
2025
2191
  this.port.postMessage({ net: "cancel", nid });
2026
2192
  }
2027
- async fetch(request, owner, stamp) {
2193
+ async fetch(request2, owner, stamp) {
2028
2194
  const nid = ++this.nextId;
2029
- const { signal, redirect } = request;
2195
+ const { signal, redirect } = request2;
2030
2196
  signal.throwIfAborted();
2031
2197
  if (unfollowed(redirect) && !honors(this.traits, redirect)) {
2032
2198
  throw refused2(`this transport cannot honor redirect: ${redirect}`);
@@ -2044,16 +2210,16 @@ var RemoteTransport = class {
2044
2210
  finished = true;
2045
2211
  signal.removeEventListener("abort", abort);
2046
2212
  };
2047
- if (request.bodyStream) this.uploads.set(nid, request.bodyStream[Symbol.asyncIterator]());
2213
+ if (request2.bodyStream) this.uploads.set(nid, request2.bodyStream[Symbol.asyncIterator]());
2048
2214
  let head;
2049
2215
  try {
2050
2216
  head = await this.ask({
2051
2217
  net: "fetch",
2052
2218
  nid,
2053
- url: request.url,
2054
- method: request.method,
2055
- headers: request.headers,
2056
- ...request.bodyStream ? { streamed: true } : request.body ? { body: request.body } : {},
2219
+ url: request2.url,
2220
+ method: request2.method,
2221
+ headers: request2.headers,
2222
+ ...request2.bodyStream ? { streamed: true } : request2.body ? { body: request2.body } : {},
2057
2223
  ...redirect !== void 0 ? { redirect } : {},
2058
2224
  ...owner !== void 0 ? { owner } : {},
2059
2225
  ...stamp ? { stamp } : {}
@@ -2065,11 +2231,11 @@ var RemoteTransport = class {
2065
2231
  const { status, statusText, headers, url, redirected, redirects, opaqueRedirect } = head;
2066
2232
  const read = async () => {
2067
2233
  if (finished) return void 0;
2068
- const reply = await this.ask({ net: "read", nid }).catch((e) => {
2234
+ const reply2 = await this.ask({ net: "read", nid }).catch((e) => {
2069
2235
  finish();
2070
2236
  throw e;
2071
2237
  });
2072
- if (reply.net === "chunk") return reply.bytes;
2238
+ if (reply2.net === "chunk") return reply2.bytes;
2073
2239
  finish();
2074
2240
  return void 0;
2075
2241
  };
@@ -2105,9 +2271,9 @@ var RemoteTransport = class {
2105
2271
  }
2106
2272
  };
2107
2273
  }
2108
- async websocket(request) {
2274
+ async websocket(request2) {
2109
2275
  const nid = ++this.nextId;
2110
- const { signal } = request;
2276
+ const { signal } = request2;
2111
2277
  signal.throwIfAborted();
2112
2278
  const abort = () => this.cancel(nid);
2113
2279
  signal.addEventListener("abort", abort, { once: true });
@@ -2116,9 +2282,9 @@ var RemoteTransport = class {
2116
2282
  opened = await this.ask({
2117
2283
  net: "ws-open",
2118
2284
  nid,
2119
- url: request.url,
2120
- protocols: request.protocols,
2121
- headers: request.headers
2285
+ url: request2.url,
2286
+ protocols: request2.protocols,
2287
+ headers: request2.headers
2122
2288
  });
2123
2289
  } finally {
2124
2290
  signal.removeEventListener("abort", abort);
@@ -2299,21 +2465,21 @@ var Channel = class {
2299
2465
  this.remote?.receive(data);
2300
2466
  return;
2301
2467
  }
2302
- const reply = data;
2303
- const call = this.pending.get(reply.id);
2468
+ const reply2 = data;
2469
+ const call = this.pending.get(reply2.id);
2304
2470
  if (!call) return;
2305
- if (reply.fd !== void 0) {
2306
- call.output?.(reply.fd, reply.bytes);
2471
+ if (reply2.fd !== void 0) {
2472
+ call.output?.(reply2.fd, reply2.bytes);
2307
2473
  return;
2308
2474
  }
2309
- if (reply.started !== void 0) {
2310
- call.started?.(reply.started);
2475
+ if (reply2.started !== void 0) {
2476
+ call.started?.(reply2.started);
2311
2477
  return;
2312
2478
  }
2313
- this.pending.delete(reply.id);
2314
- call.ended?.(reply.signal);
2315
- if (reply.error !== void 0) call.reject(new KernelCallError(reply.error, reply.code));
2316
- else call.resolve(reply.result);
2479
+ this.pending.delete(reply2.id);
2480
+ call.ended?.(reply2.signal);
2481
+ if (reply2.error !== void 0) call.reject(new KernelCallError(reply2.error, reply2.code));
2482
+ else call.resolve(reply2.result);
2317
2483
  }
2318
2484
  traced(trace, events, dropped) {
2319
2485
  const listener = this.tracing.get(trace);
@@ -2332,24 +2498,24 @@ var Channel = class {
2332
2498
  }
2333
2499
  }
2334
2500
  }
2335
- openCdp({ cdpOpen: { registration, ...request }, port }) {
2501
+ openCdp({ cdpOpen: { registration, ...request2 }, port }) {
2336
2502
  const hook = registration === void 0 ? void 0 : this.cdpHooks.get(registration);
2337
2503
  if (!hook || this.failure) {
2338
2504
  port.postMessage({ error: "this client no longer serves CDP" });
2339
2505
  port.close();
2340
2506
  return;
2341
2507
  }
2342
- const close = serveCdpPort(port, hook, request, () => this.cdpOpen.delete(close));
2508
+ const close = serveCdpPort(port, hook, request2, () => this.cdpOpen.delete(close));
2343
2509
  this.cdpOpen.add(close);
2344
2510
  }
2345
- openFacade({ facadeOpen: { registration, ...request }, port }) {
2511
+ openFacade({ facadeOpen: { registration, ...request2 }, port }) {
2346
2512
  const hook = registration === void 0 ? void 0 : this.facadeHooks.get(registration);
2347
2513
  if (!hook || this.failure) {
2348
2514
  port.postMessage({ error: "this client no longer serves the facade" });
2349
2515
  port.close();
2350
2516
  return;
2351
2517
  }
2352
- const close = serveFacadePort(port, hook, request, () => this.facadeOpen.delete(close));
2518
+ const close = serveFacadePort(port, hook, request2, () => this.facadeOpen.delete(close));
2353
2519
  this.facadeOpen.add(close);
2354
2520
  }
2355
2521
  };
@@ -2526,7 +2692,7 @@ async function terminalOn(channel, argv, opts) {
2526
2692
  );
2527
2693
  done.catch(started.reject);
2528
2694
  const pid = await started.promise;
2529
- const send = (action) => void channel.call({ op: "terminal", terminal: id, ...action }).catch(() => void 0);
2695
+ const send = (action2) => void channel.call({ op: "terminal", terminal: id, ...action2 }).catch(() => void 0);
2530
2696
  return {
2531
2697
  pid,
2532
2698
  exited: done,
@@ -2708,7 +2874,7 @@ function serveHostfsPort(port, transport) {
2708
2874
  });
2709
2875
  handles.clear();
2710
2876
  };
2711
- const send = (reply, transfer = []) => port.postMessage(reply, transfer);
2877
+ const send = (reply2, transfer = []) => port.postMessage(reply2, transfer);
2712
2878
  const pending = /* @__PURE__ */ new Set();
2713
2879
  const track = (work) => {
2714
2880
  pending.add(work);
@@ -2799,13 +2965,13 @@ function streamer(callback) {
2799
2965
  function dialer(call) {
2800
2966
  const open = /* @__PURE__ */ new Set();
2801
2967
  const dial = async ({ port, host }) => {
2802
- let reply;
2968
+ let reply2;
2803
2969
  try {
2804
- reply = await call({ op: "dial", port, ...host ? { host } : {} });
2970
+ reply2 = await call({ op: "dial", port, ...host ? { host } : {} });
2805
2971
  } catch (err) {
2806
2972
  throw errorWithCode(err.message);
2807
2973
  }
2808
- const handle = dialStream(reply, () => open.delete(handle));
2974
+ const handle = dialStream(reply2, () => open.delete(handle));
2809
2975
  open.add(handle);
2810
2976
  return handle;
2811
2977
  };
@@ -2949,7 +3115,7 @@ async function mountPolicy(options, worker, { id, req }) {
2949
3115
  }
2950
3116
  worker.postMessage({ mountAllowed: { id, allowed } });
2951
3117
  }
2952
- function fileWatches(request, call) {
3118
+ function fileWatches(request2, call) {
2953
3119
  const watching = /* @__PURE__ */ new Map();
2954
3120
  return {
2955
3121
  event(data) {
@@ -2958,7 +3124,7 @@ function fileWatches(request, call) {
2958
3124
  return true;
2959
3125
  },
2960
3126
  async watch(paths, onChange) {
2961
- const { id, done } = request({ op: "watch-files", paths });
3127
+ const { id, done } = request2({ op: "watch-files", paths });
2962
3128
  watching.set(id, onChange);
2963
3129
  await done.catch((err) => {
2964
3130
  watching.delete(id);
@@ -3031,6 +3197,13 @@ function checkOptions(options) {
3031
3197
  integrityOptions(options.protect?.integrity);
3032
3198
  facadesInit(options.facades);
3033
3199
  sealedHooks(options.sealed);
3200
+ const lease = checkedLease(options, "browser");
3201
+ if (lease && (options.metadata !== false || options.media !== false || options.ca !== false)) {
3202
+ throw new TypeError(
3203
+ "a browser lease-only kernel requires metadata:false, media:false, ca:false"
3204
+ );
3205
+ }
3206
+ return lease;
3034
3207
  }
3035
3208
  function connector(call, bound) {
3036
3209
  return async (connectOptions = {}) => {
@@ -3093,9 +3266,9 @@ function decodedRun(result) {
3093
3266
  stderr: decoder2.decode(result.stderr)
3094
3267
  };
3095
3268
  }
3096
- async function sudoRunOn2(request, replay, { stdout, stderr, tag }) {
3269
+ async function sudoRunOn2(request2, replay, { stdout, stderr, tag }) {
3097
3270
  const started = Promise.withResolvers();
3098
- const { done } = request(
3271
+ const { done } = request2(
3099
3272
  { op: "sudo-run", replay, options: { stdout, stderr, tag } },
3100
3273
  { started: started.resolve }
3101
3274
  );
@@ -3128,8 +3301,46 @@ function pageOnly(call) {
3128
3301
  attest: ((path, options) => call({ op: "attest", path, ...options ? { options } : {} }))
3129
3302
  };
3130
3303
  }
3304
+ async function bootWorker(options, leaseTag, call, worker, fail) {
3305
+ try {
3306
+ const init = await initCall(options, options.network?.transport);
3307
+ const initialized = await call({
3308
+ ...init,
3309
+ ...leaseTag ? { leaseTag, leaseMemory: true } : {}
3310
+ });
3311
+ if (leaseTag && initialized !== "cdp-lease-v1")
3312
+ throw new Error("worker does not support a lease-only kernel");
3313
+ } catch (err) {
3314
+ fail(err instanceof Error ? err : new Error("kernel initialization failed"));
3315
+ worker.terminate();
3316
+ throw err;
3317
+ }
3318
+ }
3319
+ function endWorker(worker, lease, call, close) {
3320
+ let ending;
3321
+ const end = () => {
3322
+ close();
3323
+ worker.terminate();
3324
+ };
3325
+ return () => {
3326
+ if (!lease) return end();
3327
+ ending ??= call({ op: "lease-memory-end" }).then(
3328
+ () => {
3329
+ },
3330
+ () => {
3331
+ }
3332
+ ).finally(end);
3333
+ return ending;
3334
+ };
3335
+ }
3336
+ function installer(call) {
3337
+ return async (input) => {
3338
+ checkCli(input);
3339
+ await call({ op: "lease-cli-install", input });
3340
+ };
3341
+ }
3131
3342
  async function createKernel(options = {}) {
3132
- checkOptions(options);
3343
+ const lease = checkOptions(options);
3133
3344
  const url = options.worker ?? new URL("./kernel-worker.js", import.meta.url);
3134
3345
  const worker = new Worker(url, { type: "module", name: "slicc-kernel" });
3135
3346
  const pending = /* @__PURE__ */ new Map();
@@ -3137,10 +3348,10 @@ async function createKernel(options = {}) {
3137
3348
  let failure2;
3138
3349
  const dials = dialer((req) => call(req));
3139
3350
  const files = fileWatches(
3140
- (req) => request(req),
3351
+ (req) => request2(req),
3141
3352
  (req) => call(req)
3142
3353
  );
3143
- const cdp = cdpBridge(options.cdp);
3354
+ const cdp = cdpBridge(lease ? leaseHook(lease) : options.cdp);
3144
3355
  const facades = facadeBridge(options.facades);
3145
3356
  const bound = { requests: /* @__PURE__ */ new Map(), devices: /* @__PURE__ */ new Map(), ports: /* @__PURE__ */ new WeakMap() };
3146
3357
  const sealed = hookRelays(worker, options, bound);
@@ -3209,7 +3420,7 @@ async function createKernel(options = {}) {
3209
3420
  event.preventDefault();
3210
3421
  fail(new Error(`slicc-kernel worker failed: ${event.message}`));
3211
3422
  });
3212
- function request(req, handlers = {}) {
3423
+ function request2(req, handlers = {}) {
3213
3424
  const id = ++nextId;
3214
3425
  if (failure2) return { id, done: Promise.reject(failure2) };
3215
3426
  const done = new Promise((resolve, reject) => {
@@ -3218,13 +3429,13 @@ async function createKernel(options = {}) {
3218
3429
  });
3219
3430
  return { id, done };
3220
3431
  }
3221
- const call = (req, handlers) => request(req, handlers).done;
3432
+ const call = (req, handlers) => request2(req, handlers).done;
3222
3433
  async function openTerminal(argv, opts = {}) {
3223
3434
  const { onData, ...options2 } = opts;
3224
3435
  let listener = onData ?? null;
3225
3436
  const backlog = [];
3226
3437
  const started = Promise.withResolvers();
3227
- const { id, done } = request(
3438
+ const { id, done } = request2(
3228
3439
  { op: "open-terminal", argv, options: options2 },
3229
3440
  {
3230
3441
  output: (_fd, bytes) => listener ? listener(bytes) : backlog.push(bytes),
@@ -3233,7 +3444,7 @@ async function createKernel(options = {}) {
3233
3444
  );
3234
3445
  done.catch(started.reject);
3235
3446
  const pid = await started.promise;
3236
- const send = (action) => void call({ op: "terminal", terminal: id, ...action }).catch(() => void 0);
3447
+ const send = (action2) => void call({ op: "terminal", terminal: id, ...action2 }).catch(() => void 0);
3237
3448
  return {
3238
3449
  pid,
3239
3450
  exited: quiet2(done.then((r) => endedOf2(r).status)),
@@ -3254,9 +3465,9 @@ async function createKernel(options = {}) {
3254
3465
  close: () => send({ action: "close" })
3255
3466
  };
3256
3467
  }
3257
- const { dial } = dials;
3258
- await call(await initCall(options, transport));
3468
+ await bootWorker(options, lease?.tag, call, worker, fail);
3259
3469
  return {
3470
+ installLeaseCli: installer(call),
3260
3471
  async run(argv, runOptions = {}) {
3261
3472
  const { onStdout, onStderr, stdin, ...rest } = runOptions;
3262
3473
  const streams = { 1: streamer(onStdout), 2: streamer(onStderr) };
@@ -3268,7 +3479,7 @@ async function createKernel(options = {}) {
3268
3479
  return decodedRun(result);
3269
3480
  },
3270
3481
  openTerminal,
3271
- sudoRun: (replay, sudoOptions = {}) => sudoRunOn2(request, replay, sudoOptions),
3482
+ sudoRun: (replay, sudoOptions = {}) => sudoRunOn2(request2, replay, sudoOptions),
3272
3483
  ...clientApi(call, bound),
3273
3484
  ...accounts(call, options.users === void 0 ? DEFAULT_USERS : options.users),
3274
3485
  setRoutes: async (routes) => void await call({ op: "routes", routes }),
@@ -3277,21 +3488,24 @@ async function createKernel(options = {}) {
3277
3488
  revoke: async (path) => void await call({ op: "integrity-revoke", ...path !== void 0 ? { path } : {} })
3278
3489
  },
3279
3490
  updateTransportTraits: traitsUpdater(transport, call),
3280
- dial,
3281
- loopbackFetch: (input, fetchOptions) => loopbackFetch(dial, input, fetchOptions),
3491
+ dial: dials.dial,
3492
+ loopbackFetch: (input, fetchOptions) => loopbackFetch(dials.dial, input, fetchOptions),
3282
3493
  mount: async (spec) => await call({ op: "mount", spec }),
3283
3494
  umount: async (target) => void await call({ op: "umount", target }),
3284
3495
  mounts: async () => await call({ op: "mounts" }),
3285
3496
  insert: async (target, handle) => void await call(await insertCall(target, handle)),
3286
3497
  ...pageOnly(call),
3287
3498
  watch: files.watch,
3288
- terminate() {
3289
- fail(new Error("slicc-kernel terminated"));
3290
- worker.terminate();
3291
- }
3499
+ terminate: endWorker(
3500
+ worker,
3501
+ Boolean(lease),
3502
+ call,
3503
+ () => fail(new Error("slicc-kernel terminated"))
3504
+ )
3292
3505
  };
3293
3506
  }
3294
3507
  export {
3508
+ CDP_LEASE_VERSION,
3295
3509
  KernelCallError,
3296
3510
  KernelGoneError,
3297
3511
  SEALED_FETCH_VERSION,