@ai-ecoverse/slicc-kernel 1.168.1 → 1.170.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
@@ -217,14 +217,14 @@ function bodyOf(source, head, method) {
217
217
  }
218
218
  return counted(source, size);
219
219
  }
220
- function stream(chunks3, socket, signal) {
220
+ function stream(chunks2, socket, signal) {
221
221
  return new ReadableStream({
222
222
  start(controller) {
223
223
  signal?.addEventListener("abort", () => controller.error(signal.reason), { once: true });
224
224
  },
225
225
  async pull(controller) {
226
226
  try {
227
- const next = await chunks3.next();
227
+ const next = await chunks2.next();
228
228
  if (next.done) {
229
229
  controller.close();
230
230
  socket.close();
@@ -274,9 +274,9 @@ async function loopbackFetch(dial, input, options) {
274
274
  if (!raw) throw errorWithCode("ECONNRESET: the connection closed before a response");
275
275
  head = parseHead(raw);
276
276
  } while (head.status >= 100 && head.status < 200);
277
- const chunks3 = bodyOf(source, head, request.method);
278
- if (!chunks3) socket.close();
279
- return new Response(chunks3 ? stream(chunks3, socket, options.signal) : null, {
277
+ const chunks2 = bodyOf(source, head, request.method);
278
+ if (!chunks2) socket.close();
279
+ return new Response(chunks2 ? stream(chunks2, socket, options.signal) : null, {
280
280
  status: head.status,
281
281
  statusText: head.statusText,
282
282
  headers: head.headers
@@ -1063,7 +1063,7 @@ function sendableClose(code) {
1063
1063
  function blockedReason(url, e) {
1064
1064
  const name = e?.name;
1065
1065
  if (name === "SecurityError" && url.startsWith("ws:")) {
1066
- return `${url}: ws:// is blocked from an https page; use wss:// or slicc-node`;
1066
+ return `${url}: ws:// is blocked from an https page; use wss://, or link a slicc CLI (npx sliccy@next)`;
1067
1067
  }
1068
1068
  return `${url}: ${e instanceof Error ? e.message : String(e)}`;
1069
1069
  }
@@ -1186,7 +1186,7 @@ function requestBody(request) {
1186
1186
  return request.body ? { body: request.body } : {};
1187
1187
  }
1188
1188
  function fetchTransport(options = {}) {
1189
- const send2 = options.fetch ?? globalThis.fetch.bind(globalThis);
1189
+ const send = options.fetch ?? globalThis.fetch.bind(globalThis);
1190
1190
  const Socket = options.webSocket === true ? globalThis.WebSocket : options.webSocket || void 0;
1191
1191
  const headers = options.webSocketHeaders === true;
1192
1192
  const redirect = options.redirect ?? "follow";
@@ -1203,7 +1203,7 @@ function fetchTransport(options = {}) {
1203
1203
  async fetch(request) {
1204
1204
  let response;
1205
1205
  try {
1206
- response = await send2(request.url, {
1206
+ response = await send(request.url, {
1207
1207
  method: request.method,
1208
1208
  headers: joinHeaders(request.headers),
1209
1209
  ...requestBody(request),
@@ -1221,7 +1221,8 @@ function fetchTransport(options = {}) {
1221
1221
  `fetch ${request.url} failed (unreachable, or not allowed by CORS)${options.hint ? `: ${options.hint}` : ""}`
1222
1222
  ),
1223
1223
  { status: 502 },
1224
- dns ? { code: causeCode } : {}
1224
+ dns ? { code: causeCode } : {},
1225
+ typeof causeCode === "string" ? {} : { detail: "transport" }
1225
1226
  );
1226
1227
  }
1227
1228
  const headers2 = [];
@@ -1270,13 +1271,14 @@ function serveTransport(peer, transport, { closeWaitMs = CLOSE_WAIT_MS } = {}) {
1270
1271
  const open = /* @__PURE__ */ new Map();
1271
1272
  const fail = (nid, e) => {
1272
1273
  open.delete(nid);
1273
- const { status, code } = e;
1274
+ const { status, code, detail } = e;
1274
1275
  peer.postMessage({
1275
1276
  net: "error",
1276
1277
  nid,
1277
1278
  message: e instanceof Error ? e.message : String(e),
1278
1279
  ...typeof status === "number" ? { status } : {},
1279
- ...typeof code === "string" ? { code } : {}
1280
+ ...typeof code === "string" ? { code } : {},
1281
+ ...detail === "transport" ? { detail } : {}
1280
1282
  });
1281
1283
  };
1282
1284
  const uploads = uploadsFor(peer);
@@ -1451,10 +1453,12 @@ function serveTransport(peer, transport, { closeWaitMs = CLOSE_WAIT_MS } = {}) {
1451
1453
  var TransportError = class extends Error {
1452
1454
  status;
1453
1455
  code;
1454
- constructor(message, status, code) {
1456
+ detail;
1457
+ constructor(message, status, code, detail) {
1455
1458
  super(message);
1456
1459
  this.status = status;
1457
1460
  this.code = code;
1461
+ this.detail = detail === "transport" ? detail : void 0;
1458
1462
  }
1459
1463
  };
1460
1464
  var RemoteTransport = class {
@@ -1480,7 +1484,7 @@ var RemoteTransport = class {
1480
1484
  if (!waiter) return;
1481
1485
  this.waiting.delete(reply.nid);
1482
1486
  if (reply.net === "error") {
1483
- waiter.reject(new TransportError(reply.message, reply.status, reply.code));
1487
+ waiter.reject(new TransportError(reply.message, reply.status, reply.code, reply.detail));
1484
1488
  } else waiter.resolve(reply);
1485
1489
  }
1486
1490
  toSocket(reply, socket) {
@@ -1700,10 +1704,10 @@ async function holdLock(locks) {
1700
1704
  await granted.promise;
1701
1705
  return { name, release: () => held.resolve() };
1702
1706
  }
1703
- function concat(chunks3) {
1704
- const out = new Uint8Array(chunks3.reduce((n, c) => n + c.length, 0));
1707
+ function concat(chunks2) {
1708
+ const out = new Uint8Array(chunks2.reduce((n, c) => n + c.length, 0));
1705
1709
  let at = 0;
1706
- for (const chunk of chunks3) {
1710
+ for (const chunk of chunks2) {
1707
1711
  out.set(chunk, at);
1708
1712
  at += chunk.length;
1709
1713
  }
@@ -1753,8 +1757,8 @@ var Channel = class {
1753
1757
  }
1754
1758
  request(call, handlers = {}) {
1755
1759
  const id = ++this.nextId;
1756
- const { failure: failure3 } = this;
1757
- if (failure3) return { id, done: Promise.reject(failure3) };
1760
+ const { failure: failure2 } = this;
1761
+ if (failure2) return { id, done: Promise.reject(failure2) };
1758
1762
  const done = new Promise((resolve, reject) => {
1759
1763
  this.pending.set(id, { resolve, reject, ...handlers });
1760
1764
  this.port.postMessage({ ...call, id });
@@ -1919,10 +1923,10 @@ function endedOf(done, signal) {
1919
1923
  }
1920
1924
  async function runOn(channel, argv, opts) {
1921
1925
  const { onStdout, onStderr, ...rest } = opts;
1922
- const chunks3 = { 1: [], 2: [] };
1926
+ const chunks2 = { 1: [], 2: [] };
1923
1927
  const live = { 1: new TextDecoder(), 2: new TextDecoder() };
1924
1928
  const tee = (fd, on) => (bytes) => {
1925
- chunks3[fd].push(bytes);
1929
+ chunks2[fd].push(bytes);
1926
1930
  on?.(live[fd].decode(bytes, { stream: true }));
1927
1931
  };
1928
1932
  const child = await spawnOn(channel, argv, {
@@ -1931,7 +1935,7 @@ async function runOn(channel, argv, opts) {
1931
1935
  onStderr: tee(2, onStderr)
1932
1936
  });
1933
1937
  const { status, signal } = await child.ended;
1934
- const text = (fd) => new TextDecoder().decode(concat(chunks3[fd]));
1938
+ const text = (fd) => new TextDecoder().decode(concat(chunks2[fd]));
1935
1939
  return {
1936
1940
  pid: child.pid,
1937
1941
  status,
@@ -1960,7 +1964,7 @@ async function terminalOn(channel, argv, opts) {
1960
1964
  );
1961
1965
  done.catch(started.reject);
1962
1966
  const pid = await started.promise;
1963
- const send2 = (action) => void channel.call({ op: "terminal", terminal: id, ...action }).catch(() => void 0);
1967
+ const send = (action) => void channel.call({ op: "terminal", terminal: id, ...action }).catch(() => void 0);
1964
1968
  return {
1965
1969
  pid,
1966
1970
  exited: done,
@@ -1972,10 +1976,10 @@ async function terminalOn(channel, argv, opts) {
1972
1976
  listener = next;
1973
1977
  if (next) for (const bytes of backlog.splice(0)) next(bytes);
1974
1978
  },
1975
- write: (data) => send2({ action: "write", bytes: bytesOf2(data) }),
1976
- resize: (cols, rows) => send2({ action: "resize", cols, rows }),
1977
- signal: (name) => send2({ action: "signal", signal: name }),
1978
- close: () => send2({ action: "close" })
1979
+ write: (data) => send({ action: "write", bytes: bytesOf2(data) }),
1980
+ resize: (cols, rows) => send({ action: "resize", cols, rows }),
1981
+ signal: (name) => send({ action: "signal", signal: name }),
1982
+ close: () => send({ action: "close" })
1979
1983
  };
1980
1984
  }
1981
1985
  function fsOn(channel) {
@@ -2111,187 +2115,6 @@ async function attachKernel(port, options = {}) {
2111
2115
  };
2112
2116
  }
2113
2117
 
2114
- // src/local-proxy-transport.ts
2115
- var PATH = "/api/fetch-proxy";
2116
- var RAW_CONTENT_TYPE = "application/vnd.slicc.raw-fetch";
2117
- var MAX_HEAD = 1024 * 1024;
2118
- var MAX_REQUEST_BODY2 = 64 * 1024 * 1024;
2119
- var PERMISSIONS = ["loopback-network", "local-network-access"];
2120
- var LOOPBACK_PAGE = /^(127\.\d+\.\d+\.\d+|localhost|\[::1\])$/;
2121
- var failure2 = (message, status = 502) => Object.assign(new Error(`local proxy: ${message}`), { status });
2122
- function encodeHead(url, method, headers) {
2123
- return JSON.stringify({ url, method, headers }).replace(
2124
- /[\u007f-￿]/g,
2125
- (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`
2126
- );
2127
- }
2128
- function hopHeaders(options, extra) {
2129
- return new Headers({ "X-Bridge-Token": options.key, ...extra });
2130
- }
2131
- function send(options) {
2132
- return options.fetch ?? globalThis.fetch.bind(globalThis);
2133
- }
2134
- async function refusalMessage(response) {
2135
- const text = await response.text().catch(() => "");
2136
- try {
2137
- const parsed = JSON.parse(text);
2138
- if (typeof parsed.error === "string") return parsed.error;
2139
- } catch {
2140
- }
2141
- return text || response.statusText || `answered ${response.status}`;
2142
- }
2143
- async function refusal(response) {
2144
- return failure2(await refusalMessage(response), response.ok ? 502 : response.status);
2145
- }
2146
- async function permission(permissions) {
2147
- if (!permissions) return "unknown";
2148
- for (const name of PERMISSIONS) {
2149
- try {
2150
- return (await permissions.query({ name })).state;
2151
- } catch {
2152
- }
2153
- }
2154
- return "unknown";
2155
- }
2156
- function isHead(value) {
2157
- const head = value;
2158
- return !!head && typeof head.status === "number" && typeof head.statusText === "string" && Array.isArray(head.headers) && head.headers.every(
2159
- (pair) => Array.isArray(pair) && pair.length === 2 && typeof pair[0] === "string" && typeof pair[1] === "string"
2160
- );
2161
- }
2162
- function concat2(a, b) {
2163
- const out = new Uint8Array(a.byteLength + b.byteLength);
2164
- out.set(a);
2165
- out.set(b, a.byteLength);
2166
- return out;
2167
- }
2168
- async function readHead(reader, idleMs) {
2169
- let buffer = new Uint8Array(0);
2170
- for (; ; ) {
2171
- if (buffer.byteLength >= 4) {
2172
- const length = new DataView(buffer.buffer, buffer.byteOffset, 4).getUint32(0);
2173
- if (length > MAX_HEAD) throw failure2(`response head of ${length} bytes`);
2174
- if (buffer.byteLength >= 4 + length) {
2175
- let head;
2176
- try {
2177
- head = JSON.parse(new TextDecoder().decode(buffer.subarray(4, 4 + length)));
2178
- } catch {
2179
- }
2180
- if (!isHead(head)) throw failure2("malformed response head");
2181
- return { head, rest: buffer.subarray(4 + length) };
2182
- }
2183
- }
2184
- const next = await readWithin(reader, idleMs);
2185
- if (next.done) throw failure2("closed before the response head");
2186
- buffer = concat2(buffer, next.value);
2187
- }
2188
- }
2189
- async function* chunks2(rest, reader, idleMs) {
2190
- try {
2191
- if (rest.byteLength > 0) yield rest;
2192
- for (let next = await readWithin(reader, idleMs); !next.done; next = await readWithin(reader, idleMs)) {
2193
- if (next.value.byteLength > 0) yield next.value;
2194
- }
2195
- } finally {
2196
- await reader.cancel().catch(() => void 0);
2197
- }
2198
- }
2199
- async function checkLocalProxy(options) {
2200
- const onLoopback = LOOPBACK_PAGE.test(globalThis.location?.hostname ?? "");
2201
- const permissions = onLoopback ? void 0 : options.permissions ?? globalThis.navigator?.permissions;
2202
- if (await permission(permissions) === "denied") return { state: "blocked" };
2203
- let response;
2204
- try {
2205
- response = await send(options)(new URL(PATH, options.url), {
2206
- method: "POST",
2207
- headers: hopHeaders(options, { "X-Slicc-Raw-Probe": "1" }),
2208
- credentials: "omit",
2209
- mode: "cors"
2210
- });
2211
- } catch {
2212
- const now = await permission(permissions);
2213
- if (now === "denied") return { state: "blocked" };
2214
- return {
2215
- state: "unreachable",
2216
- permission: now === "granted" || now === "prompt" ? now : "unknown"
2217
- };
2218
- }
2219
- if (!response.ok) {
2220
- return { state: "refused", status: response.status, error: await refusalMessage(response) };
2221
- }
2222
- const reply = await response.json().catch(() => null);
2223
- if (!reply || typeof reply.rawFetch !== "number" || reply.rawFetch < 1 || typeof reply.requestBodyStreaming !== "boolean" || typeof reply.maxRequestBodyBytes !== "number") {
2224
- return { state: "incompatible" };
2225
- }
2226
- return {
2227
- state: "ready",
2228
- probe: {
2229
- rawFetch: reply.rawFetch,
2230
- requestBodyStreaming: reply.requestBodyStreaming,
2231
- maxRequestBodyBytes: reply.maxRequestBodyBytes,
2232
- ...typeof reply.kernelTunnel === "number" ? { kernelTunnel: reply.kernelTunnel } : {},
2233
- ...typeof reply.kernelPort === "number" ? { kernelPort: reply.kernelPort } : {},
2234
- ...typeof reply.cdp === "number" ? { cdp: reply.cdp } : {}
2235
- }
2236
- };
2237
- }
2238
- async function probeLocalProxy(options) {
2239
- const status = await checkLocalProxy(options);
2240
- return status.state === "ready" ? status.probe : null;
2241
- }
2242
- function localProxyTransport(options) {
2243
- const endpoint = new URL(PATH, options.url);
2244
- return {
2245
- traits: {
2246
- manualRedirects: true,
2247
- encodedBodies: false,
2248
- maxRequestBody: options.maxRequestBody ?? MAX_REQUEST_BODY2
2249
- },
2250
- async fetch(request) {
2251
- let response;
2252
- try {
2253
- response = await send(options)(endpoint, {
2254
- method: "POST",
2255
- headers: hopHeaders(options, {
2256
- "X-Slicc-Raw-Request": encodeHead(request.url, request.method, request.headers)
2257
- }),
2258
- ...request.body ? { body: request.body } : {},
2259
- signal: request.signal,
2260
- credentials: "omit",
2261
- mode: "cors"
2262
- });
2263
- } catch (e) {
2264
- if (request.signal.aborted) throw e;
2265
- throw failure2(`${endpoint.origin} is unreachable or refuses this origin`);
2266
- }
2267
- const type = response.headers.get("content-type") ?? "";
2268
- if (response.status !== 200 || !type.startsWith(RAW_CONTENT_TYPE) || !response.body) {
2269
- throw await refusal(response);
2270
- }
2271
- const reader = response.body.getReader();
2272
- const idleMs = options.bodyIdleMs ?? BODY_IDLE_MS;
2273
- let framed;
2274
- try {
2275
- framed = await readHead(reader, idleMs);
2276
- } catch (e) {
2277
- await reader.cancel().catch(() => void 0);
2278
- throw e;
2279
- }
2280
- const body = chunks2(framed.rest, reader, idleMs);
2281
- return {
2282
- status: framed.head.status,
2283
- statusText: framed.head.statusText,
2284
- headers: framed.head.headers,
2285
- body,
2286
- cancel: async () => {
2287
- await body.return(void 0);
2288
- await reader.cancel().catch(() => void 0);
2289
- }
2290
- };
2291
- }
2292
- };
2293
- }
2294
-
2295
2118
  // src/mount/driver.ts
2296
2119
  function fsError2(code, message = code) {
2297
2120
  return Object.assign(new Error(message), { code });
@@ -2313,7 +2136,7 @@ function serveHostfsPort(port, transport) {
2313
2136
  });
2314
2137
  handles.clear();
2315
2138
  };
2316
- const send2 = (reply, transfer = []) => port.postMessage(reply, transfer);
2139
+ const send = (reply, transfer = []) => port.postMessage(reply, transfer);
2317
2140
  const pending = /* @__PURE__ */ new Set();
2318
2141
  const track = (work) => {
2319
2142
  pending.add(work);
@@ -2333,7 +2156,7 @@ function serveHostfsPort(port, transport) {
2333
2156
  data
2334
2157
  }) => {
2335
2158
  const { id, op } = data;
2336
- if (op === "ping") return send2({ id, pong: true });
2159
+ if (op === "ping") return send({ id, pong: true });
2337
2160
  if (op === "bye") return stop();
2338
2161
  if (op === "cleanup")
2339
2162
  return void Promise.allSettled([...pending]).then(() => answer(data.name, data.body)).catch(() => {
@@ -2345,12 +2168,12 @@ function serveHostfsPort(port, transport) {
2345
2168
  try {
2346
2169
  await transport.watch(
2347
2170
  stop2.signal,
2348
- (event) => send2({ id, event }),
2349
- () => send2({ id, open: true })
2171
+ (event) => send({ id, event }),
2172
+ () => send({ id, open: true })
2350
2173
  );
2351
- send2({ id, end: true });
2174
+ send({ id, end: true });
2352
2175
  } catch (err) {
2353
- send2({ id, error: errorOf2(err) });
2176
+ send({ id, error: errorOf2(err) });
2354
2177
  } finally {
2355
2178
  watches.delete(id);
2356
2179
  }
@@ -2367,18 +2190,18 @@ function serveHostfsPort(port, transport) {
2367
2190
  )
2368
2191
  );
2369
2192
  const bytes = read.slice();
2370
- return send2({ id, bytes }, [bytes.buffer]);
2193
+ return send({ id, bytes }, [bytes.buffer]);
2371
2194
  }
2372
2195
  if (op === "write") {
2373
2196
  await track(
2374
2197
  transport.write(data.fh, data.offset, data.bytes)
2375
2198
  );
2376
- return send2({ id });
2199
+ return send({ id });
2377
2200
  }
2378
2201
  if (op !== "call") throw fsError2("EINVAL", `unknown hostfs port op ${op}`);
2379
- send2({ id, result: await answer(data.name, data.body) });
2202
+ send({ id, result: await answer(data.name, data.body) });
2380
2203
  } catch (err) {
2381
- send2({ id, error: errorOf2(err) });
2204
+ send({ id, error: errorOf2(err) });
2382
2205
  }
2383
2206
  };
2384
2207
  const stop = () => {
@@ -2662,7 +2485,7 @@ async function createKernel(options = {}) {
2662
2485
  const worker = new Worker(url, { type: "module", name: "slicc-kernel" });
2663
2486
  const pending = /* @__PURE__ */ new Map();
2664
2487
  let nextId = 0;
2665
- let failure3;
2488
+ let failure2;
2666
2489
  const dials = dialer((req) => call(req));
2667
2490
  const files = fileWatches(
2668
2491
  (req) => request(req),
@@ -2679,7 +2502,7 @@ async function createKernel(options = {}) {
2679
2502
  facades.close();
2680
2503
  sealed.close();
2681
2504
  approvals.close();
2682
- failure3 = error;
2505
+ failure2 = error;
2683
2506
  bridge?.close();
2684
2507
  uplinks?.close();
2685
2508
  for (const call2 of pending.values()) call2.reject(error);
@@ -2739,7 +2562,7 @@ async function createKernel(options = {}) {
2739
2562
  });
2740
2563
  function request(req, handlers = {}) {
2741
2564
  const id = ++nextId;
2742
- if (failure3) return { id, done: Promise.reject(failure3) };
2565
+ if (failure2) return { id, done: Promise.reject(failure2) };
2743
2566
  const done = new Promise((resolve, reject) => {
2744
2567
  pending.set(id, { resolve, reject, ...handlers });
2745
2568
  worker.postMessage({ ...req, id });
@@ -2761,7 +2584,7 @@ async function createKernel(options = {}) {
2761
2584
  );
2762
2585
  done.catch(started.reject);
2763
2586
  const pid = await started.promise;
2764
- const send2 = (action) => void call({ op: "terminal", terminal: id, ...action }).catch(() => void 0);
2587
+ const send = (action) => void call({ op: "terminal", terminal: id, ...action }).catch(() => void 0);
2765
2588
  return {
2766
2589
  pid,
2767
2590
  exited: quiet(done.then((r) => endedOf2(r).status)),
@@ -2773,13 +2596,13 @@ async function createKernel(options = {}) {
2773
2596
  listener = next;
2774
2597
  if (next) for (const bytes of backlog.splice(0)) next(bytes);
2775
2598
  },
2776
- write: (data) => send2({
2599
+ write: (data) => send({
2777
2600
  action: "write",
2778
2601
  bytes: typeof data === "string" ? new TextEncoder().encode(data) : data
2779
2602
  }),
2780
- resize: (cols, rows) => send2({ action: "resize", cols, rows }),
2781
- signal: (name) => send2({ action: "signal", signal: name }),
2782
- close: () => send2({ action: "close" })
2603
+ resize: (cols, rows) => send({ action: "resize", cols, rows }),
2604
+ signal: (name) => send({ action: "signal", signal: name }),
2605
+ close: () => send({ action: "close" })
2783
2606
  };
2784
2607
  }
2785
2608
  const { dial } = dials;
@@ -2822,11 +2645,8 @@ export {
2822
2645
  KernelCallError,
2823
2646
  KernelGoneError,
2824
2647
  attachKernel,
2825
- checkLocalProxy,
2826
2648
  createKernel,
2827
2649
  fetchTransport,
2828
- localProxyTransport,
2829
- probeLocalProxy,
2830
2650
  serveHostfsPort
2831
2651
  };
2832
2652
  //# sourceMappingURL=index.js.map