pi-landstrip 0.20.25 → 0.20.27

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 -167
  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)
@@ -7333,10 +7524,80 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7333
7524
  let childEnd;
7334
7525
  let preparedChild;
7335
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
+ })();
7336
7541
  const cleanup = async () => {
7337
7542
  const errors = [];
7338
7543
  for (const release of [
7339
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
+ },
7340
7601
  () => trapSocket?.destroy(),
7341
7602
  () => childEnd?.destroy(),
7342
7603
  () => {
@@ -7652,18 +7913,24 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7652
7913
  function killChild() {
7653
7914
  child.kill("SIGKILL");
7654
7915
  }
7916
+ const execAbort = new AbortController;
7917
+ const querySignal = signal ? AbortSignal.any([signal, execAbort.signal]) : execAbort.signal;
7655
7918
  function onAbort() {
7919
+ execAbort.abort();
7656
7920
  killChild();
7657
7921
  }
7658
7922
  if (timeout !== undefined && timeout > 0) {
7659
7923
  timeoutHandle = setTimeout(() => {
7660
7924
  timedOut = true;
7925
+ execAbort.abort();
7661
7926
  killChild();
7662
7927
  }, timeout * 1000);
7663
7928
  }
7664
7929
  signal?.addEventListener("abort", onAbort, { once: true });
7665
7930
  if (signal?.aborted)
7666
7931
  onAbort();
7932
+ const stderrDecoder = new StringDecoder3("utf8");
7933
+ let stderrFlushed = false;
7667
7934
  let stderrAcc = "";
7668
7935
  let errorFdAcc = "";
7669
7936
  let execSettled = false;
@@ -7672,15 +7939,91 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7672
7939
  let postExitTimer;
7673
7940
  let stdoutEnded = child.stdout === null;
7674
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
+ };
7675
8014
  const finalizeExec = (code) => {
7676
8015
  if (execSettled)
7677
8016
  return;
7678
8017
  execSettled = true;
8018
+ execAbort.abort();
7679
8019
  if (postExitTimer)
7680
8020
  clearTimeout(postExitTimer);
8021
+ flushStderr();
8022
+ flushTrap();
7681
8023
  child.stdout?.destroy();
7682
8024
  child.stderr?.destroy();
7683
8025
  (async () => {
8026
+ await queryChain;
7684
8027
  await cleanup();
7685
8028
  if (signal?.aborted) {
7686
8029
  reject(new Error("aborted"));
@@ -7707,83 +8050,53 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7707
8050
  })().catch(reject);
7708
8051
  };
7709
8052
  const maybeFinalizeAfterExit = () => {
7710
- if (childExited && !execSettled && stdoutEnded && stderrEnded) {
8053
+ if (childExited && !execSettled && stdoutEnded && stderrEnded && trapEnded) {
7711
8054
  finalizeExec(childExitCode);
7712
8055
  }
7713
8056
  };
7714
- child.stdout?.on("data", onData);
7715
- child.stderr?.on("data", (data) => {
7716
- stderrAcc += data.toString("utf8");
7717
- callbacks.onStderr?.(data);
7718
- onData(data);
7719
- });
7720
- child.stdout?.once("end", () => {
8057
+ const onStdoutEnd = () => {
7721
8058
  stdoutEnded = true;
7722
8059
  maybeFinalizeAfterExit();
7723
- });
7724
- child.stderr?.once("end", () => {
8060
+ };
8061
+ const onStderrEnd = () => {
7725
8062
  stderrEnded = true;
8063
+ flushStderr();
7726
8064
  maybeFinalizeAfterExit();
7727
- });
7728
- const trapDecoder = new StringDecoder3("utf8");
7729
- let trapBuffer = "";
7730
- let queryChain = Promise.resolve();
7731
- const respondQuery = (queryId, action) => {
7732
- if (!trapSocket || trapSocket.destroyed)
7733
- return;
7734
- trapSocket.write(controlResponseLine(queryId, action));
7735
8065
  };
7736
- const appendErrorLine = (line) => {
7737
- const infoLine = line + `
7738
- `;
7739
- errorFdAcc += infoLine;
7740
- callbacks.onErrorFd?.(Buffer.from(infoLine, "utf8"));
8066
+ const onTrapEnd = () => {
8067
+ if (trapEnded)
8068
+ return;
8069
+ trapEnded = true;
8070
+ flushTrap();
8071
+ maybeFinalizeAfterExit();
7741
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);
7742
8083
  trapSocket?.on("data", (data) => {
7743
8084
  trapBuffer += trapDecoder.write(data);
7744
- let nl = trapBuffer.indexOf(`
7745
- `);
7746
- while (nl !== -1) {
7747
- const line = trapBuffer.slice(0, nl);
7748
- trapBuffer = trapBuffer.slice(nl + 1);
7749
- nl = trapBuffer.indexOf(`
7750
- `);
7751
- if (line.length === 0)
7752
- continue;
7753
- const trap = parseTrapLine(line);
7754
- if (trap && isQueryTrap(trap)) {
7755
- queryChain = queryChain.then(async () => {
7756
- const result = await resolveTrapQuery(trap, ctx, cwd, processAllowances, callbacks.promptOnBlock === true, signal);
7757
- if (result.action === "deny") {
7758
- if (result.reason === "rejected" && isFilesystemTrap(trap)) {
7759
- callbacks.onRejectedPath?.(trap.operation, normalizeBlockedPath(trap.path, cwd));
7760
- }
7761
- appendErrorLine(line);
7762
- }
7763
- respondQuery(trap.query_id, result.action);
7764
- }).catch((error) => {
7765
- respondQuery(trap.query_id, "deny");
7766
- if (!signal?.aborted && formatError(error) !== "Permission request cancelled") {
7767
- const target = isFilesystemTrap(trap) ? trap.path : trap.target;
7768
- const message = `Sandbox permission request failed (${trap.operation} "${target}"): ${formatError(error)}`;
7769
- appendErrorLine(JSON.stringify({ kind: "internal", code: "INTERNAL_ERROR", message }));
7770
- onData(Buffer.from(`pi-landstrip: ${message}
7771
- `, "utf8"));
7772
- }
7773
- });
7774
- } else {
7775
- appendErrorLine(line);
7776
- }
7777
- }
8085
+ drainTrapLines();
7778
8086
  });
8087
+ trapSocket?.once("end", onTrapEnd);
8088
+ trapSocket?.once("close", onTrapEnd);
8089
+ trapSocket?.on("error", onTrapEnd);
7779
8090
  child.on("error", (error) => {
7780
8091
  if (execSettled)
7781
8092
  return;
7782
8093
  execSettled = true;
8094
+ execAbort.abort();
7783
8095
  if (postExitTimer)
7784
8096
  clearTimeout(postExitTimer);
7785
8097
  (async () => {
7786
8098
  try {
8099
+ await queryChain;
7787
8100
  await cleanup();
7788
8101
  reject(error);
7789
8102
  } catch (cleanupError) {
@@ -7794,12 +8107,24 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7794
8107
  child.once("exit", (code) => {
7795
8108
  childExited = true;
7796
8109
  childExitCode = code;
8110
+ execAbort.abort();
7797
8111
  maybeFinalizeAfterExit();
7798
8112
  if (!execSettled) {
7799
8113
  postExitTimer = setTimeout(() => finalizeExec(code), EXIT_STDIO_GRACE_MS);
7800
8114
  }
7801
8115
  });
7802
- 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
+ });
7803
8128
  })().catch((error) => {
7804
8129
  pendingSocketPair?.forEach((socket) => socket.destroy());
7805
8130
  teardownResources().then(() => reject(error), (cleanupError) => reject(new AggregateError([error, cleanupError], "Shell setup and cleanup failed")));
@@ -7811,6 +8136,7 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7811
8136
  async function runBashWithOptionalRetry(id, params, signal, onUpdate, ctx) {
7812
8137
  let landstripErrorOutput = "";
7813
8138
  let stderrOutput = "";
8139
+ let stderrOutputDecoder = new StringDecoder3("utf8");
7814
8140
  const rejectedPaths = {
7815
8141
  read: new Set,
7816
8142
  write: new Set
@@ -7827,7 +8153,7 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7827
8153
  landstripErrorOutput += data.toString("utf8");
7828
8154
  },
7829
8155
  onStderr: (data) => {
7830
- stderrOutput += data.toString("utf8");
8156
+ stderrOutput += stderrOutputDecoder.write(data);
7831
8157
  },
7832
8158
  onRejectedPath: (operation, path) => {
7833
8159
  rejectedPaths[operation].add(path);
@@ -7836,7 +8162,13 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7836
8162
  }, allowances),
7837
8163
  shellPath: SettingsManager2.create(ctx.cwd).getShellPath()
7838
8164
  });
7839
- 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
+ };
7840
8172
  const formatTrapErrors = () => {
7841
8173
  const landstripErrors = parseLandstripTraps2(landstripErrorOutput);
7842
8174
  if (landstripErrors.length === 0)
@@ -7898,6 +8230,7 @@ ${paths}${note}`, permissionOptionsFor(ctx), promptSignal);
7898
8230
  });
7899
8231
  landstripErrorOutput = "";
7900
8232
  stderrOutput = "";
8233
+ stderrOutputDecoder = new StringDecoder3("utf8");
7901
8234
  return run();
7902
8235
  };
7903
8236
  let result;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-landstrip",
3
- "version": "0.20.25",
3
+ "version": "0.20.27",
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.25",
42
+ "@landstrip/landstrip-api": "^0.20.27",
43
43
  "jsonc-parser": "^3.3.1",
44
44
  "minimatch": "^10.2.5",
45
45
  "semver": "^7.8.6",