pi-landstrip 0.20.24 → 0.20.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.ts +500 -169
  2. package/package.json +2 -2
package/dist/index.ts CHANGED
@@ -2,18 +2,21 @@
2
2
  import { spawn as spawn2, spawnSync } from "node:child_process";
3
3
  import {
4
4
  existsSync as existsSync6,
5
+ lstatSync as lstatSync2,
5
6
  mkdirSync as mkdirSync4,
6
7
  mkdtempSync as mkdtempSync2,
7
8
  readFileSync as readFileSync7,
8
9
  readdirSync as readdirSync3,
9
10
  realpathSync as realpathSync3,
10
11
  rmSync as rmSync2,
12
+ rmdirSync,
11
13
  writeFileSync as writeFileSync4
12
14
  } from "node:fs";
13
15
  import { createServer, Socket as NetSocket } from "node:net";
14
16
  import { tmpdir as tmpdir2 } from "node:os";
15
17
  import { dirname as dirname5, isAbsolute as isAbsolute4, join as join8, parse as parse2, resolve as resolve4 } from "node:path";
16
18
  import { StringDecoder as StringDecoder3 } from "node:string_decoder";
19
+ import { setTimeout as delay } from "node:timers/promises";
17
20
  import { fileURLToPath as fileURLToPath2 } from "node:url";
18
21
  import { quote as quoteShell } from "shell-quote";
19
22
  import {
@@ -1690,19 +1693,16 @@ var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
1690
1693
  var DEFAULT_SETTLE_TIMEOUT_MS = 60000;
1691
1694
  var DEFAULT_STOP_TIMEOUT_MS = 1000;
1692
1695
  var DEFAULT_KILL_TIMEOUT_MS = 1000;
1696
+ var DEFAULT_DRAIN_TIMEOUT_MS = 100;
1693
1697
  var DEFAULT_STDERR_LIMIT_BYTES = 64 * 1024;
1694
1698
  var DEFAULT_STDOUT_FRAME_LIMIT_BYTES = 64 * 1024 * 1024;
1695
1699
  function defaultSpawn(command, args, options) {
1696
1700
  return spawn(command, [...args], options);
1697
1701
  }
1698
- function delay(milliseconds) {
1699
- return new Promise((resolve) => setTimeout(resolve, milliseconds));
1700
- }
1701
1702
 
1702
1703
  class RpcProcess {
1703
1704
  options;
1704
- child = null;
1705
- exitPromise = null;
1705
+ session = null;
1706
1706
  nextRequestId = 0;
1707
1707
  pending = new Map;
1708
1708
  eventListeners = new Set;
@@ -1712,7 +1712,6 @@ class RpcProcess {
1712
1712
  fatalError = null;
1713
1713
  stopping = null;
1714
1714
  promptQueue = Promise.resolve();
1715
- disposeAuthPipe;
1716
1715
  constructor(options) {
1717
1716
  if (!options.command)
1718
1717
  throw new Error("RPC command must not be empty");
@@ -1725,7 +1724,7 @@ class RpcProcess {
1725
1724
  this.options = options;
1726
1725
  }
1727
1726
  async start() {
1728
- if (this.child)
1727
+ if (this.session)
1729
1728
  throw new Error("RPC process is already started");
1730
1729
  if (this.stopping)
1731
1730
  throw new Error("RPC process is stopping");
@@ -1743,43 +1742,33 @@ class RpcProcess {
1743
1742
  } catch (error) {
1744
1743
  throw this.asError(error, "Failed to spawn RPC process");
1745
1744
  }
1746
- this.child = child;
1747
1745
  this.fatalError = null;
1748
1746
  this.stderr = Buffer.alloc(0);
1749
- this.attachStdout(child, child.stdout);
1750
- child.stderr.on("data", (chunk) => {
1751
- if (this.child === child)
1752
- this.captureStderr(chunk);
1753
- });
1754
- child.stdin.on("error", (error) => this.handleChildError(child, error, "RPC stdin error"));
1755
- child.on("error", (error) => this.handleChildError(child, error, "RPC process error"));
1756
- this.exitPromise = new Promise((resolve) => {
1757
- child.once("exit", (code, signal) => {
1758
- this.disposeAuthPipe?.();
1759
- this.disposeAuthPipe = undefined;
1760
- if (this.child === child) {
1761
- this.child = null;
1762
- this.failAll(new Error(this.exitMessage(code, signal)));
1763
- }
1764
- resolve();
1765
- });
1766
- });
1747
+ const session = this.createSession(child);
1748
+ this.session = session;
1767
1749
  await new Promise((resolve, reject) => {
1768
1750
  const onSpawn = () => {
1751
+ session.spawned = true;
1769
1752
  cleanup();
1770
1753
  resolve();
1771
1754
  };
1772
1755
  const onError = (error) => {
1773
1756
  cleanup();
1774
- if (this.child === child)
1775
- this.child = null;
1757
+ session.abortStartup();
1776
1758
  const spawnError = this.asError(error, "Failed to spawn RPC process");
1777
1759
  this.failAll(spawnError);
1778
1760
  reject(spawnError);
1779
1761
  };
1780
1762
  const onExit = (code, signal) => {
1781
1763
  cleanup();
1782
- reject(new Error(this.exitMessage(code, signal)));
1764
+ (async () => {
1765
+ await session.settledPromise;
1766
+ if (this.stopping)
1767
+ await this.stopping.catch(() => {
1768
+ return;
1769
+ });
1770
+ reject(session.stopped ? new Error("RPC process stopped during startup") : new Error(this.exitMessage(code, signal)));
1771
+ })();
1783
1772
  };
1784
1773
  const cleanup = () => {
1785
1774
  child.off("spawn", onSpawn);
@@ -1790,16 +1779,41 @@ class RpcProcess {
1790
1779
  child.once("error", onError);
1791
1780
  child.once("exit", onExit);
1792
1781
  });
1793
- if (this.child !== child || this.stopping)
1782
+ if (session.stopped || this.stopping) {
1783
+ if (this.stopping)
1784
+ await this.stopping;
1785
+ else if (this.session === session)
1786
+ await this.stop();
1787
+ if (this.fatalError)
1788
+ throw this.fatalError;
1789
+ await session.settledPromise;
1794
1790
  throw new Error("RPC process stopped during startup");
1791
+ }
1792
+ if (this.session !== session || session.exited) {
1793
+ await session.settledPromise;
1794
+ if (this.stopping)
1795
+ await this.stopping;
1796
+ if (session.stopped) {
1797
+ if (this.fatalError)
1798
+ throw this.fatalError;
1799
+ throw new Error("RPC process stopped during startup");
1800
+ }
1801
+ throw new Error(this.exitMessage(session.exitCode, session.exitSignal));
1802
+ }
1803
+ if (this.fatalError) {
1804
+ const error = this.fatalError;
1805
+ await this.stop().catch(() => {
1806
+ return;
1807
+ });
1808
+ throw error;
1809
+ }
1795
1810
  if (this.options.onAuthPipe) {
1796
1811
  try {
1797
- const stdio = "stdio" in child ? child.stdio : undefined;
1798
- const pipe = Array.isArray(stdio) ? stdio[WORKER_AUTH_FD] : undefined;
1812
+ const pipe = this.authPipe(child);
1799
1813
  if (!(pipe instanceof Duplex)) {
1800
1814
  throw new Error("Worker launcher does not support private authentication pipes");
1801
1815
  }
1802
- this.disposeAuthPipe = this.options.onAuthPipe(pipe);
1816
+ session.disposeAuthPipe = this.options.onAuthPipe(pipe);
1803
1817
  } catch (error) {
1804
1818
  await this.stop();
1805
1819
  throw error;
@@ -1820,8 +1834,7 @@ class RpcProcess {
1820
1834
  async request(type, fields = {}) {
1821
1835
  if (!type)
1822
1836
  throw new Error("RPC request type must not be empty");
1823
- const child = this.child;
1824
- if (!child || child.stdin.destroyed)
1837
+ if (!this.canWrite(this.session))
1825
1838
  throw this.notRunningError();
1826
1839
  if (this.fatalError)
1827
1840
  throw this.fatalError;
@@ -1883,47 +1896,184 @@ class RpcProcess {
1883
1896
  await this.request("abort");
1884
1897
  }
1885
1898
  async stop() {
1886
- this.disposeAuthPipe?.();
1887
- this.disposeAuthPipe = undefined;
1899
+ const session = this.session;
1900
+ if (session)
1901
+ this.disposeAuthPipe(session);
1888
1902
  if (this.stopping)
1889
1903
  return this.stopping;
1890
- const child = this.child;
1891
- if (!child)
1904
+ if (!session)
1892
1905
  return;
1893
- this.stopping = this.stopChild(child);
1906
+ const stopping = this.stopChild(session).finally(() => {
1907
+ if (this.stopping === stopping)
1908
+ this.stopping = null;
1909
+ });
1910
+ this.stopping = stopping;
1911
+ await stopping;
1912
+ }
1913
+ async stopChild(session) {
1914
+ session.stopped = true;
1915
+ const stopTimeout = this.options.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS;
1916
+ const killTimeout = this.options.killTimeoutMs ?? DEFAULT_KILL_TIMEOUT_MS;
1917
+ if (!session.exited) {
1918
+ const abort = this.abort().catch(() => {
1919
+ return;
1920
+ });
1921
+ await this.waitWithin(abort, stopTimeout);
1922
+ session.child.stdin.end();
1923
+ }
1924
+ if (!session.exited && !await this.waitWithin(session.exitedPromise, stopTimeout)) {
1925
+ session.child.kill("SIGTERM");
1926
+ if (!session.exited && !await this.waitWithin(session.exitedPromise, killTimeout)) {
1927
+ session.child.kill("SIGKILL");
1928
+ if (!session.exited && !await this.waitWithin(session.exitedPromise, killTimeout)) {
1929
+ const error = this.withStderr("RPC process did not exit after SIGKILL");
1930
+ session.abortStartup();
1931
+ this.fatalError = error;
1932
+ this.failAll(error);
1933
+ this.reportError(error);
1934
+ throw error;
1935
+ }
1936
+ }
1937
+ }
1938
+ await session.settledPromise;
1939
+ }
1940
+ async waitWithin(promise, timeoutMs) {
1941
+ let timer;
1894
1942
  try {
1895
- await this.stopping;
1943
+ return await Promise.race([
1944
+ promise.then(() => true),
1945
+ new Promise((resolve) => {
1946
+ timer = setTimeout(() => resolve(false), timeoutMs);
1947
+ })
1948
+ ]);
1896
1949
  } finally {
1897
- this.stopping = null;
1950
+ if (timer)
1951
+ clearTimeout(timer);
1898
1952
  }
1899
1953
  }
1900
- async stopChild(child) {
1901
- const stopTimeout = this.options.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS;
1902
- const killTimeout = this.options.killTimeoutMs ?? DEFAULT_KILL_TIMEOUT_MS;
1903
- const exit = this.exitPromise ?? Promise.resolve();
1904
- const abort = this.abort().catch(() => {
1905
- return;
1954
+ createSession(child) {
1955
+ let resolveExited;
1956
+ let resolveSettled;
1957
+ const exitedPromise = new Promise((resolve) => {
1958
+ resolveExited = resolve;
1906
1959
  });
1907
- await Promise.race([abort, delay(stopTimeout)]);
1908
- child.stdin.end();
1909
- if (await this.waitForExit(exit, stopTimeout))
1910
- return;
1911
- child.kill("SIGTERM");
1912
- if (await this.waitForExit(exit, killTimeout))
1913
- return;
1914
- child.kill("SIGKILL");
1915
- if (await this.waitForExit(exit, killTimeout))
1916
- return;
1917
- const error = this.withStderr("RPC process did not exit after SIGKILL");
1918
- this.fatalError = error;
1919
- this.failAll(error);
1920
- this.reportError(error);
1921
- throw error;
1922
- }
1923
- async waitForExit(exit, timeout) {
1924
- return Promise.race([exit.then(() => true), delay(timeout).then(() => false)]);
1960
+ const settledPromise = new Promise((resolve) => {
1961
+ resolveSettled = resolve;
1962
+ });
1963
+ let detachStdout = () => {};
1964
+ const session = {
1965
+ child,
1966
+ exitedPromise,
1967
+ settledPromise,
1968
+ spawned: false,
1969
+ exited: false,
1970
+ settled: false,
1971
+ stopped: false,
1972
+ exitCode: null,
1973
+ exitSignal: null,
1974
+ stdoutEnded: child.stdout.readableEnded || child.stdout.destroyed,
1975
+ stderrEnded: child.stderr.readableEnded || child.stderr.destroyed,
1976
+ abortStartup: () => {
1977
+ if (session.settled)
1978
+ return;
1979
+ session.exited = true;
1980
+ session.settled = true;
1981
+ if (session.drainTimer) {
1982
+ clearTimeout(session.drainTimer);
1983
+ session.drainTimer = undefined;
1984
+ }
1985
+ detachStreams();
1986
+ child.off("exit", onSessionExit);
1987
+ this.disposeAuthPipe(session);
1988
+ if (this.session === session)
1989
+ this.session = null;
1990
+ resolveExited();
1991
+ resolveSettled();
1992
+ }
1993
+ };
1994
+ const finalizeExit = () => {
1995
+ if (session.settled)
1996
+ return;
1997
+ session.settled = true;
1998
+ if (session.drainTimer) {
1999
+ clearTimeout(session.drainTimer);
2000
+ session.drainTimer = undefined;
2001
+ }
2002
+ detachStreams();
2003
+ if (this.session === session) {
2004
+ this.session = null;
2005
+ this.failAll(this.fatalError ?? new Error(this.exitMessage(session.exitCode, session.exitSignal)));
2006
+ }
2007
+ resolveSettled();
2008
+ };
2009
+ const maybeFinalizeExit = () => {
2010
+ if (session.exited && session.stdoutEnded && session.stderrEnded) {
2011
+ finalizeExit();
2012
+ }
2013
+ };
2014
+ const onStdoutClose = () => {
2015
+ session.stdoutEnded = true;
2016
+ maybeFinalizeExit();
2017
+ };
2018
+ const onStderrData = (chunk) => {
2019
+ if (this.session === session && !session.settled)
2020
+ this.captureStderr(chunk);
2021
+ };
2022
+ const onStderrEnd = () => {
2023
+ session.stderrEnded = true;
2024
+ maybeFinalizeExit();
2025
+ };
2026
+ const detachStreams = () => {
2027
+ detachStdout();
2028
+ child.stdout.off("close", onStdoutClose);
2029
+ child.stderr.off("data", onStderrData);
2030
+ child.stderr.off("end", onStderrEnd);
2031
+ child.stderr.off("close", onStderrEnd);
2032
+ };
2033
+ detachStdout = this.attachStdout(session, onStdoutClose);
2034
+ child.stdout.on("close", onStdoutClose);
2035
+ child.stdout.on("error", (error) => {
2036
+ this.handleChildError(session, error, "RPC stdout error");
2037
+ onStdoutClose();
2038
+ });
2039
+ child.stderr.on("data", onStderrData);
2040
+ child.stderr.on("end", onStderrEnd);
2041
+ child.stderr.on("close", onStderrEnd);
2042
+ child.stderr.on("error", (error) => {
2043
+ this.handleChildError(session, error, "RPC stderr error");
2044
+ onStderrEnd();
2045
+ });
2046
+ child.stdin.on("error", (error) => this.handleChildError(session, error, "RPC stdin error"));
2047
+ child.on("error", (error) => this.handleChildError(session, error, "RPC process error"));
2048
+ if (this.options.onAuthPipe) {
2049
+ const pipe = this.authPipe(child);
2050
+ if (pipe instanceof Duplex)
2051
+ pipe.on("error", () => {});
2052
+ }
2053
+ const onSessionExit = (code, signal) => {
2054
+ if (session.settled)
2055
+ return;
2056
+ session.exited = true;
2057
+ session.exitCode = code;
2058
+ session.exitSignal = signal;
2059
+ this.disposeAuthPipe(session);
2060
+ resolveExited();
2061
+ if (session.stdoutEnded && session.stderrEnded) {
2062
+ finalizeExit();
2063
+ return;
2064
+ }
2065
+ session.drainTimer = setTimeout(() => {
2066
+ session.drainTimer = undefined;
2067
+ child.stdout.destroy();
2068
+ child.stderr.destroy();
2069
+ finalizeExit();
2070
+ }, DEFAULT_DRAIN_TIMEOUT_MS);
2071
+ };
2072
+ child.once("exit", onSessionExit);
2073
+ return session;
1925
2074
  }
1926
- attachStdout(child, stdout) {
2075
+ attachStdout(session, onEnded) {
2076
+ const { stdout } = session.child;
1927
2077
  const decoder = new StringDecoder2("utf8");
1928
2078
  const limit = this.options.stdoutFrameLimitBytes ?? DEFAULT_STDOUT_FRAME_LIMIT_BYTES;
1929
2079
  let buffer = "";
@@ -1948,34 +2098,42 @@ class RpcProcess {
1948
2098
  }
1949
2099
  if (line.endsWith("\r"))
1950
2100
  line = line.slice(0, -1);
1951
- this.handleLine(line);
2101
+ this.handleLine(session, line);
1952
2102
  if (this.fatalError)
1953
2103
  return;
1954
2104
  }
1955
2105
  };
1956
- stdout.on("data", (chunk) => {
1957
- if (this.child !== child || this.fatalError)
2106
+ const onData = (chunk) => {
2107
+ if (this.session !== session || session.settled || this.fatalError)
1958
2108
  return;
1959
2109
  buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
1960
2110
  consume();
1961
- });
1962
- stdout.on("end", () => {
1963
- if (this.child !== child || this.fatalError)
1964
- return;
1965
- buffer += decoder.end();
1966
- if (buffer.length === 0)
1967
- return;
1968
- if (Buffer.byteLength(buffer) > limit) {
1969
- rejectOversizedFrame();
1970
- return;
2111
+ };
2112
+ const onEnd = () => {
2113
+ if (this.session === session && !session.settled && !this.fatalError) {
2114
+ buffer += decoder.end();
2115
+ consume();
2116
+ if (buffer.length > 0) {
2117
+ if (Buffer.byteLength(buffer) > limit) {
2118
+ rejectOversizedFrame();
2119
+ } else {
2120
+ if (buffer.endsWith("\r"))
2121
+ buffer = buffer.slice(0, -1);
2122
+ this.handleLine(session, buffer);
2123
+ buffer = "";
2124
+ }
2125
+ }
1971
2126
  }
1972
- if (buffer.endsWith("\r"))
1973
- buffer = buffer.slice(0, -1);
1974
- this.handleLine(buffer);
1975
- buffer = "";
1976
- });
2127
+ onEnded();
2128
+ };
2129
+ stdout.on("data", onData);
2130
+ stdout.on("end", onEnd);
2131
+ return () => {
2132
+ stdout.off("data", onData);
2133
+ stdout.off("end", onEnd);
2134
+ };
1977
2135
  }
1978
- handleLine(line) {
2136
+ handleLine(session, line) {
1979
2137
  if (this.fatalError)
1980
2138
  return;
1981
2139
  let value;
@@ -1996,7 +2154,7 @@ class RpcProcess {
1996
2154
  for (const listener of this.eventListeners)
1997
2155
  listener(event);
1998
2156
  if (event.type === "extension_ui_request") {
1999
- this.handleExtensionUiRequest(event);
2157
+ this.handleExtensionUiRequest(session, event);
2000
2158
  }
2001
2159
  }
2002
2160
  handleResponse(value) {
@@ -2015,11 +2173,13 @@ class RpcProcess {
2015
2173
  }
2016
2174
  pending.resolve(value);
2017
2175
  }
2018
- async handleExtensionUiRequest(event) {
2176
+ async handleExtensionUiRequest(session, event) {
2019
2177
  if (typeof event.id !== "string" || typeof event.method !== "string") {
2020
2178
  this.failProtocol(new Error("Invalid extension_ui_request"));
2021
2179
  return;
2022
2180
  }
2181
+ if (this.session !== session || !this.canWrite(session) || session.stopped)
2182
+ return;
2023
2183
  const request = event;
2024
2184
  const callback = this.options.onExtensionUiRequest;
2025
2185
  let result;
@@ -2040,6 +2200,8 @@ class RpcProcess {
2040
2200
  return;
2041
2201
  }
2042
2202
  }
2203
+ if (this.session !== session || !this.canWrite(session) || session.stopped)
2204
+ return;
2043
2205
  this.write({ ...result, type: "extension_ui_response", id: request.id }, (error) => {
2044
2206
  if (error)
2045
2207
  this.reportError(this.asError(error, "Failed to write extension UI response"));
@@ -2071,17 +2233,36 @@ class RpcProcess {
2071
2233
  }
2072
2234
  this.settledWaiters.clear();
2073
2235
  }
2236
+ authPipe(child) {
2237
+ const stdio = "stdio" in child ? child.stdio : undefined;
2238
+ return Array.isArray(stdio) ? stdio[WORKER_AUTH_FD] : undefined;
2239
+ }
2240
+ disposeAuthPipe(session) {
2241
+ if (session.disposeAuthPipe) {
2242
+ session.disposeAuthPipe();
2243
+ session.disposeAuthPipe = undefined;
2244
+ return;
2245
+ }
2246
+ if (!this.options.onAuthPipe)
2247
+ return;
2248
+ const pipe = this.authPipe(session.child);
2249
+ if (pipe instanceof Duplex)
2250
+ pipe.destroy();
2251
+ }
2252
+ canWrite(session) {
2253
+ return !!session && !session.exited && !session.settled && !session.child.stdin.destroyed && !session.child.stdin.writableEnded;
2254
+ }
2074
2255
  write(record, callback) {
2075
- const child = this.child;
2076
- if (!child || child.stdin.destroyed) {
2256
+ const session = this.session;
2257
+ if (!this.canWrite(session)) {
2077
2258
  callback(this.notRunningError());
2078
2259
  return;
2079
2260
  }
2080
- child.stdin.write(`${JSON.stringify(record)}
2261
+ session.child.stdin.write(`${JSON.stringify(record)}
2081
2262
  `, callback);
2082
2263
  }
2083
- handleChildError(child, error, prefix) {
2084
- if (this.child !== child)
2264
+ handleChildError(session, error, prefix) {
2265
+ if (this.session !== session || !session.spawned || session.exited || session.settled)
2085
2266
  return;
2086
2267
  const processError = this.asError(error, prefix);
2087
2268
  this.fatalError = processError;
@@ -6618,22 +6799,32 @@ function patchProcessGroupKill(child) {
6618
6799
  };
6619
6800
  }
6620
6801
  async function stopPreparedChild(child) {
6621
- if (!child)
6622
- return;
6623
- child.kill("SIGKILL");
6624
- if (child.exitCode !== null || child.signalCode !== null)
6802
+ if (!child || child.pid === undefined || child.exitCode !== null || child.signalCode !== null) {
6625
6803
  return;
6626
- await new Promise((resolve) => {
6627
- let settleTimer;
6628
- const done = () => {
6629
- if (settleTimer)
6804
+ }
6805
+ const waitForExit = (timeoutMs) => {
6806
+ if (child.exitCode !== null || child.signalCode !== null)
6807
+ return Promise.resolve();
6808
+ return new Promise((resolveExit) => {
6809
+ const settleTimer = setTimeout(() => {
6810
+ child.off("exit", onExit);
6811
+ resolveExit();
6812
+ }, timeoutMs);
6813
+ const onExit = () => {
6630
6814
  clearTimeout(settleTimer);
6631
- child.removeListener("exit", done);
6632
- resolve();
6633
- };
6634
- child.once("exit", done);
6635
- settleTimer = setTimeout(done, 1000);
6636
- });
6815
+ resolveExit();
6816
+ };
6817
+ child.once("exit", onExit);
6818
+ });
6819
+ };
6820
+ if (process.platform !== "win32") {
6821
+ child.kill("SIGTERM");
6822
+ await waitForExit(200);
6823
+ if (child.exitCode !== null || child.signalCode !== null)
6824
+ return;
6825
+ }
6826
+ child.kill("SIGKILL");
6827
+ await waitForExit(1000);
6637
6828
  }
6638
6829
  async function showPermissionPrompt(ctx, title, options, signal, label) {
6639
6830
  if (!ctx.hasUI)
@@ -6723,8 +6914,6 @@ var WINDOWS_LAUNCHER_ENVIRONMENT = [
6723
6914
  "PATHEXT"
6724
6915
  ];
6725
6916
  function createLandstripLauncherEnvironment(providerEnv, hostEnv = process.env, platform = process.platform) {
6726
- if (platform === "linux")
6727
- return { ...providerEnv, APPIMAGE_EXTRACT_AND_RUN: "1" };
6728
6917
  if (platform !== "win32")
6729
6918
  return providerEnv;
6730
6919
  const result = { ...providerEnv };
@@ -7335,10 +7524,80 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7335
7524
  let childEnd;
7336
7525
  let preparedChild;
7337
7526
  let disposed = false;
7527
+ const isolatedTmpDir = (() => {
7528
+ if (process.platform !== "linux")
7529
+ return;
7530
+ const raw = options.env?.TMPDIR?.trim();
7531
+ if (!raw)
7532
+ return;
7533
+ const resolved = canonicalizePath2(raw, options.cwd);
7534
+ if (resolved === canonicalizePath2(tmpdir2(), options.cwd))
7535
+ return;
7536
+ const hostTmpDir = process.env.TMPDIR?.trim();
7537
+ if (hostTmpDir && resolved === canonicalizePath2(hostTmpDir, options.cwd))
7538
+ return;
7539
+ return resolved;
7540
+ })();
7338
7541
  const cleanup = async () => {
7339
7542
  const errors = [];
7340
7543
  for (const release of [
7341
7544
  () => stopPreparedChild(preparedChild),
7545
+ async () => {
7546
+ if (preparedChild?.pid === undefined || !isolatedTmpDir)
7547
+ return;
7548
+ const deadline = Date.now() + 2000;
7549
+ for (;; ) {
7550
+ let parentDev;
7551
+ let entries;
7552
+ try {
7553
+ parentDev = lstatSync2(isolatedTmpDir).dev;
7554
+ entries = readdirSync3(isolatedTmpDir);
7555
+ } catch (error) {
7556
+ const code = error.code;
7557
+ if (code === "ENOENT" || code === "ENOTDIR")
7558
+ return;
7559
+ throw error;
7560
+ }
7561
+ const mounts = entries.filter((entry) => entry.startsWith(".mount_"));
7562
+ if (mounts.length === 0)
7563
+ return;
7564
+ for (const entry of mounts) {
7565
+ const mountPath = join8(isolatedTmpDir, entry);
7566
+ try {
7567
+ if (lstatSync2(mountPath).dev === parentDev) {
7568
+ rmdirSync(mountPath);
7569
+ }
7570
+ } catch (error) {
7571
+ const code = error.code;
7572
+ if (code === "ENOENT" || code === "EBUSY")
7573
+ continue;
7574
+ if (code === "ENOTCONN" || code === "ECONNABORTED") {
7575
+ for (const tool of ["fusermount", "fusermount3"]) {
7576
+ const result = spawnSync(tool, ["-u", "-q", "-z", mountPath], {
7577
+ stdio: "ignore"
7578
+ });
7579
+ if (result.status === 0)
7580
+ break;
7581
+ }
7582
+ try {
7583
+ rmdirSync(mountPath);
7584
+ } catch (removeError) {
7585
+ const removeCode = removeError.code;
7586
+ if (removeCode !== "ENOENT" && removeCode !== "EBUSY") {
7587
+ throw removeError;
7588
+ }
7589
+ }
7590
+ continue;
7591
+ }
7592
+ throw error;
7593
+ }
7594
+ }
7595
+ if (Date.now() >= deadline) {
7596
+ throw new Error(`Timed out waiting for AppImage mount cleanup in ${isolatedTmpDir}`);
7597
+ }
7598
+ await delay(5);
7599
+ }
7600
+ },
7342
7601
  () => trapSocket?.destroy(),
7343
7602
  () => childEnd?.destroy(),
7344
7603
  () => {
@@ -7654,18 +7913,24 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7654
7913
  function killChild() {
7655
7914
  child.kill("SIGKILL");
7656
7915
  }
7916
+ const execAbort = new AbortController;
7917
+ const querySignal = signal ? AbortSignal.any([signal, execAbort.signal]) : execAbort.signal;
7657
7918
  function onAbort() {
7919
+ execAbort.abort();
7658
7920
  killChild();
7659
7921
  }
7660
7922
  if (timeout !== undefined && timeout > 0) {
7661
7923
  timeoutHandle = setTimeout(() => {
7662
7924
  timedOut = true;
7925
+ execAbort.abort();
7663
7926
  killChild();
7664
7927
  }, timeout * 1000);
7665
7928
  }
7666
7929
  signal?.addEventListener("abort", onAbort, { once: true });
7667
7930
  if (signal?.aborted)
7668
7931
  onAbort();
7932
+ const stderrDecoder = new StringDecoder3("utf8");
7933
+ let stderrFlushed = false;
7669
7934
  let stderrAcc = "";
7670
7935
  let errorFdAcc = "";
7671
7936
  let execSettled = false;
@@ -7674,15 +7939,91 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7674
7939
  let postExitTimer;
7675
7940
  let stdoutEnded = child.stdout === null;
7676
7941
  let stderrEnded = child.stderr === null;
7942
+ let trapEnded = trapSocket === undefined;
7943
+ const trapDecoder = new StringDecoder3("utf8");
7944
+ let trapFlushed = false;
7945
+ let trapBuffer = "";
7946
+ let queryChain = Promise.resolve();
7947
+ const flushStderr = () => {
7948
+ if (stderrFlushed)
7949
+ return;
7950
+ stderrFlushed = true;
7951
+ stderrAcc += stderrDecoder.end();
7952
+ };
7953
+ const respondQuery = (queryId, action) => {
7954
+ if (!trapSocket || trapSocket.destroyed)
7955
+ return;
7956
+ trapSocket.write(controlResponseLine(queryId, action));
7957
+ };
7958
+ const appendErrorLine = (line) => {
7959
+ const infoLine = line + `
7960
+ `;
7961
+ errorFdAcc += infoLine;
7962
+ callbacks.onErrorFd?.(Buffer.from(infoLine, "utf8"));
7963
+ };
7964
+ const processTrapLine = (line) => {
7965
+ if (line.length === 0)
7966
+ return;
7967
+ const trap = parseTrapLine(line);
7968
+ if (trap && isQueryTrap(trap)) {
7969
+ queryChain = queryChain.then(async () => {
7970
+ const result = await resolveTrapQuery(trap, ctx, cwd, processAllowances, callbacks.promptOnBlock === true, querySignal);
7971
+ if (result.action === "deny") {
7972
+ if (result.reason === "rejected" && isFilesystemTrap(trap)) {
7973
+ callbacks.onRejectedPath?.(trap.operation, normalizeBlockedPath(trap.path, cwd));
7974
+ }
7975
+ appendErrorLine(line);
7976
+ }
7977
+ respondQuery(trap.query_id, result.action);
7978
+ }).catch((error) => {
7979
+ respondQuery(trap.query_id, "deny");
7980
+ if (!querySignal.aborted && formatError(error) !== "Permission request cancelled") {
7981
+ const target = isFilesystemTrap(trap) ? trap.path : trap.target;
7982
+ const message = `Sandbox permission request failed (${trap.operation} "${target}"): ${formatError(error)}`;
7983
+ appendErrorLine(JSON.stringify({ kind: "internal", code: "INTERNAL_ERROR", message }));
7984
+ onData(Buffer.from(`pi-landstrip: ${message}
7985
+ `, "utf8"));
7986
+ }
7987
+ });
7988
+ } else {
7989
+ appendErrorLine(line);
7990
+ }
7991
+ };
7992
+ const drainTrapLines = () => {
7993
+ let nl = trapBuffer.indexOf(`
7994
+ `);
7995
+ while (nl !== -1) {
7996
+ const line = trapBuffer.slice(0, nl);
7997
+ trapBuffer = trapBuffer.slice(nl + 1);
7998
+ nl = trapBuffer.indexOf(`
7999
+ `);
8000
+ processTrapLine(line);
8001
+ }
8002
+ };
8003
+ const flushTrap = () => {
8004
+ if (trapFlushed)
8005
+ return;
8006
+ trapFlushed = true;
8007
+ trapBuffer += trapDecoder.end();
8008
+ drainTrapLines();
8009
+ const rest = trapBuffer.trim();
8010
+ trapBuffer = "";
8011
+ if (rest.length > 0)
8012
+ processTrapLine(rest);
8013
+ };
7677
8014
  const finalizeExec = (code) => {
7678
8015
  if (execSettled)
7679
8016
  return;
7680
8017
  execSettled = true;
8018
+ execAbort.abort();
7681
8019
  if (postExitTimer)
7682
8020
  clearTimeout(postExitTimer);
8021
+ flushStderr();
8022
+ flushTrap();
7683
8023
  child.stdout?.destroy();
7684
8024
  child.stderr?.destroy();
7685
8025
  (async () => {
8026
+ await queryChain;
7686
8027
  await cleanup();
7687
8028
  if (signal?.aborted) {
7688
8029
  reject(new Error("aborted"));
@@ -7709,83 +8050,53 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7709
8050
  })().catch(reject);
7710
8051
  };
7711
8052
  const maybeFinalizeAfterExit = () => {
7712
- if (childExited && !execSettled && stdoutEnded && stderrEnded) {
8053
+ if (childExited && !execSettled && stdoutEnded && stderrEnded && trapEnded) {
7713
8054
  finalizeExec(childExitCode);
7714
8055
  }
7715
8056
  };
7716
- child.stdout?.on("data", onData);
7717
- child.stderr?.on("data", (data) => {
7718
- stderrAcc += data.toString("utf8");
7719
- callbacks.onStderr?.(data);
7720
- onData(data);
7721
- });
7722
- child.stdout?.once("end", () => {
8057
+ const onStdoutEnd = () => {
7723
8058
  stdoutEnded = true;
7724
8059
  maybeFinalizeAfterExit();
7725
- });
7726
- child.stderr?.once("end", () => {
8060
+ };
8061
+ const onStderrEnd = () => {
7727
8062
  stderrEnded = true;
8063
+ flushStderr();
7728
8064
  maybeFinalizeAfterExit();
7729
- });
7730
- const trapDecoder = new StringDecoder3("utf8");
7731
- let trapBuffer = "";
7732
- let queryChain = Promise.resolve();
7733
- const respondQuery = (queryId, action) => {
7734
- if (!trapSocket || trapSocket.destroyed)
7735
- return;
7736
- trapSocket.write(controlResponseLine(queryId, action));
7737
8065
  };
7738
- const appendErrorLine = (line) => {
7739
- const infoLine = line + `
7740
- `;
7741
- errorFdAcc += infoLine;
7742
- callbacks.onErrorFd?.(Buffer.from(infoLine, "utf8"));
8066
+ const onTrapEnd = () => {
8067
+ if (trapEnded)
8068
+ return;
8069
+ trapEnded = true;
8070
+ flushTrap();
8071
+ maybeFinalizeAfterExit();
7743
8072
  };
8073
+ child.stdout?.on("data", onData);
8074
+ child.stderr?.on("data", (data) => {
8075
+ stderrAcc += stderrDecoder.write(data);
8076
+ callbacks.onStderr?.(data);
8077
+ onData(data);
8078
+ });
8079
+ child.stdout?.once("end", onStdoutEnd);
8080
+ child.stdout?.once("close", onStdoutEnd);
8081
+ child.stderr?.once("end", onStderrEnd);
8082
+ child.stderr?.once("close", onStderrEnd);
7744
8083
  trapSocket?.on("data", (data) => {
7745
8084
  trapBuffer += trapDecoder.write(data);
7746
- let nl = trapBuffer.indexOf(`
7747
- `);
7748
- while (nl !== -1) {
7749
- const line = trapBuffer.slice(0, nl);
7750
- trapBuffer = trapBuffer.slice(nl + 1);
7751
- nl = trapBuffer.indexOf(`
7752
- `);
7753
- if (line.length === 0)
7754
- continue;
7755
- const trap = parseTrapLine(line);
7756
- if (trap && isQueryTrap(trap)) {
7757
- queryChain = queryChain.then(async () => {
7758
- const result = await resolveTrapQuery(trap, ctx, cwd, processAllowances, callbacks.promptOnBlock === true, signal);
7759
- if (result.action === "deny") {
7760
- if (result.reason === "rejected" && isFilesystemTrap(trap)) {
7761
- callbacks.onRejectedPath?.(trap.operation, normalizeBlockedPath(trap.path, cwd));
7762
- }
7763
- appendErrorLine(line);
7764
- }
7765
- respondQuery(trap.query_id, result.action);
7766
- }).catch((error) => {
7767
- respondQuery(trap.query_id, "deny");
7768
- if (!signal?.aborted && formatError(error) !== "Permission request cancelled") {
7769
- const target = isFilesystemTrap(trap) ? trap.path : trap.target;
7770
- const message = `Sandbox permission request failed (${trap.operation} "${target}"): ${formatError(error)}`;
7771
- appendErrorLine(JSON.stringify({ kind: "internal", code: "INTERNAL_ERROR", message }));
7772
- onData(Buffer.from(`pi-landstrip: ${message}
7773
- `, "utf8"));
7774
- }
7775
- });
7776
- } else {
7777
- appendErrorLine(line);
7778
- }
7779
- }
8085
+ drainTrapLines();
7780
8086
  });
8087
+ trapSocket?.once("end", onTrapEnd);
8088
+ trapSocket?.once("close", onTrapEnd);
8089
+ trapSocket?.on("error", onTrapEnd);
7781
8090
  child.on("error", (error) => {
7782
8091
  if (execSettled)
7783
8092
  return;
7784
8093
  execSettled = true;
8094
+ execAbort.abort();
7785
8095
  if (postExitTimer)
7786
8096
  clearTimeout(postExitTimer);
7787
8097
  (async () => {
7788
8098
  try {
8099
+ await queryChain;
7789
8100
  await cleanup();
7790
8101
  reject(error);
7791
8102
  } catch (cleanupError) {
@@ -7796,12 +8107,24 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7796
8107
  child.once("exit", (code) => {
7797
8108
  childExited = true;
7798
8109
  childExitCode = code;
8110
+ execAbort.abort();
7799
8111
  maybeFinalizeAfterExit();
7800
8112
  if (!execSettled) {
7801
8113
  postExitTimer = setTimeout(() => finalizeExec(code), EXIT_STDIO_GRACE_MS);
7802
8114
  }
7803
8115
  });
7804
- child.once("close", (code) => finalizeExec(code));
8116
+ child.once("close", (code) => {
8117
+ childExited = true;
8118
+ childExitCode ??= code;
8119
+ stdoutEnded = true;
8120
+ stderrEnded = true;
8121
+ flushStderr();
8122
+ execAbort.abort();
8123
+ maybeFinalizeAfterExit();
8124
+ if (!execSettled && !postExitTimer) {
8125
+ postExitTimer = setTimeout(() => finalizeExec(childExitCode), EXIT_STDIO_GRACE_MS);
8126
+ }
8127
+ });
7805
8128
  })().catch((error) => {
7806
8129
  pendingSocketPair?.forEach((socket) => socket.destroy());
7807
8130
  teardownResources().then(() => reject(error), (cleanupError) => reject(new AggregateError([error, cleanupError], "Shell setup and cleanup failed")));
@@ -7813,6 +8136,7 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7813
8136
  async function runBashWithOptionalRetry(id, params, signal, onUpdate, ctx) {
7814
8137
  let landstripErrorOutput = "";
7815
8138
  let stderrOutput = "";
8139
+ let stderrOutputDecoder = new StringDecoder3("utf8");
7816
8140
  const rejectedPaths = {
7817
8141
  read: new Set,
7818
8142
  write: new Set
@@ -7829,7 +8153,7 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7829
8153
  landstripErrorOutput += data.toString("utf8");
7830
8154
  },
7831
8155
  onStderr: (data) => {
7832
- stderrOutput += data.toString("utf8");
8156
+ stderrOutput += stderrOutputDecoder.write(data);
7833
8157
  },
7834
8158
  onRejectedPath: (operation, path) => {
7835
8159
  rejectedPaths[operation].add(path);
@@ -7838,7 +8162,13 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7838
8162
  }, allowances),
7839
8163
  shellPath: SettingsManager2.create(ctx.cwd).getShellPath()
7840
8164
  });
7841
- const run = () => sandboxedBash.execute(id, params, signal, onUpdate, ctx);
8165
+ const run = async () => {
8166
+ try {
8167
+ return await sandboxedBash.execute(id, params, signal, onUpdate, ctx);
8168
+ } finally {
8169
+ stderrOutput += stderrOutputDecoder.end();
8170
+ }
8171
+ };
7842
8172
  const formatTrapErrors = () => {
7843
8173
  const landstripErrors = parseLandstripTraps2(landstripErrorOutput);
7844
8174
  if (landstripErrors.length === 0)
@@ -7900,6 +8230,7 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7900
8230
  });
7901
8231
  landstripErrorOutput = "";
7902
8232
  stderrOutput = "";
8233
+ stderrOutputDecoder = new StringDecoder3("utf8");
7903
8234
  return run();
7904
8235
  };
7905
8236
  let result;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-landstrip",
3
- "version": "0.20.24",
3
+ "version": "0.20.26",
4
4
  "description": "Sandboxed Bash and process-backed agents for Pi",
5
5
  "keywords": [
6
6
  "landstrip",
@@ -39,7 +39,7 @@
39
39
  "ci:test": "npm run test"
40
40
  },
41
41
  "dependencies": {
42
- "@landstrip/landstrip-api": "^0.20.24",
42
+ "@landstrip/landstrip-api": "^0.20.26",
43
43
  "jsonc-parser": "^3.3.1",
44
44
  "minimatch": "^10.2.5",
45
45
  "semver": "^7.8.6",