@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
428 lines • 17.4 kB
JavaScript
import { existsSync } from "node:fs";
import { delimiter, join } from "node:path";
import { listWindowsProcessRowsSync, windowsTreeKillArgs, } from "@earendil-works/pi-agent-core/node";
import { spawnSync } from "child_process";
import { getBinDir } from "../config.js";
import { withCredentialProxy } from "../core/credential-proxy/runtime.js";
import { withKillGuardRuntime } from "../core/kill-guard/runtime.js";
import { childEnvironmentOf } from "../modes/rpc/host-identity-env.js";
import { withBundledBunCommands } from "./bundled-bun.js";
/** Environment variable that overrides shell resolution with an explicit bash path (Windows-first). */
export const GIT_BASH_PATH_ENV = "SENPI_GIT_BASH_PATH";
/**
* Find bash executable on PATH (cross-platform)
*/
function isLegacyWslBashPath(path) {
const normalized = path.replace(/\//g, "\\").toLowerCase();
return /^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized);
}
/** Classify a shell executable by its basename so non-bash shells get correct args. */
export function resolveShellKind(shellPath) {
const base = shellPath
.replace(/\\/g, "/")
.split("/")
.pop()
?.toLowerCase()
.replace(/\.exe$/, "");
if (base === "cmd")
return "cmd";
if (base === "powershell" || base === "pwsh")
return "powershell";
if (base === "sh")
return "sh";
return "bash";
}
function getBashShellConfig(shell) {
return isLegacyWslBashPath(shell)
? { shell, args: ["-s"], commandTransport: "stdin", kind: "bash" }
: { shell, args: ["-c"], kind: "bash" };
}
/**
* Build a ShellConfig for an explicit shell path, honoring the shell KIND so
* cmd.exe uses `/c`, PowerShell uses `-NoProfile -Command`, and bash/sh use
* `-c` (or WSL bash `-s` via stdin).
*/
function getShellConfigForPath(shellPath) {
const kind = resolveShellKind(shellPath);
switch (kind) {
case "cmd":
return { shell: shellPath, args: ["/c"], kind };
case "powershell":
return { shell: shellPath, args: ["-NoProfile", "-Command"], kind };
case "sh":
return { shell: shellPath, args: ["-c"], kind };
default:
return getBashShellConfig(shellPath);
}
}
function findExecutableOnPath(executable) {
if (process.platform === "win32") {
// Windows: Use 'where' and verify file exists (where can return non-existent paths)
try {
const result = spawnSync("where", [executable], {
encoding: "utf-8",
timeout: 5000,
windowsHide: true,
});
if (result.status === 0 && result.stdout) {
const firstMatch = result.stdout.trim().split(/\r?\n/)[0];
if (firstMatch && existsSync(firstMatch)) {
return firstMatch;
}
}
}
catch {
// Ignore errors
}
return null;
}
// Unix: Use 'which' and trust its output (handles Termux and special filesystems)
try {
const result = spawnSync("which", [executable], { encoding: "utf-8", timeout: 5000 });
if (result.status === 0 && result.stdout) {
const firstMatch = result.stdout.trim().split(/\r?\n/)[0];
if (firstMatch) {
return firstMatch;
}
}
}
catch {
// Ignore errors
}
return null;
}
/**
* Resolve shell configuration based on platform and an optional explicit shell path.
* Resolution order:
* 1. User-specified shellPath
* 2. On Windows: Git Bash in known locations, then bash on PATH
* 3. On Unix: /bin/bash, then bash on PATH, then fallback to sh
*/
export function getShellConfig(customShellPath) {
// 1. Check user-specified shell path
if (customShellPath) {
if (existsSync(customShellPath)) {
return getShellConfigForPath(customShellPath);
}
throw new Error(`Custom shell path not found: ${customShellPath}`);
}
// 2. SENPI_GIT_BASH_PATH override wins over platform probing.
const gitBashOverride = process.env[GIT_BASH_PATH_ENV];
if (gitBashOverride) {
if (existsSync(gitBashOverride)) {
return getShellConfigForPath(gitBashOverride);
}
throw new Error(`${GIT_BASH_PATH_ENV} points to a missing shell: ${gitBashOverride}`);
}
if (process.platform === "win32") {
// 3. Try Git Bash in known locations
const paths = [];
const programFiles = process.env.ProgramFiles;
if (programFiles) {
paths.push(`${programFiles}\\Git\\bin\\bash.exe`);
}
const programFilesX86 = process.env["ProgramFiles(x86)"];
if (programFilesX86) {
paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`);
}
for (const path of paths) {
if (existsSync(path)) {
return getBashShellConfig(path);
}
}
// 3. Fallback: search bash.exe on PATH (Cygwin, MSYS2, WSL, etc.)
const bashOnPath = findExecutableOnPath("bash.exe");
if (bashOnPath) {
return getBashShellConfig(bashOnPath);
}
throw new Error(`No bash shell found. Options:\n` +
` 1. Install Git for Windows: https://git-scm.com/download/win\n` +
` 2. Add your bash to PATH (Cygwin, MSYS2, etc.)\n` +
" 3. Set shellPath in settings.json\n\n" +
`Searched Git Bash in:\n${paths.map((p) => ` ${p}`).join("\n")}`);
}
// Unix: try /bin/bash, then bash on PATH, then fallback to sh
if (existsSync("/bin/bash")) {
return getBashShellConfig("/bin/bash");
}
const bashOnPath = findExecutableOnPath("bash");
if (bashOnPath) {
return getBashShellConfig(bashOnPath);
}
return { shell: "sh", args: ["-c"] };
}
export const POWERSHELL_ARGS = ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"];
/** Resolve PowerShell on Windows, preferring PowerShell 7 when available. */
export function getPowerShellConfig() {
if (process.platform !== "win32") {
throw new Error("The powershell tool is only available on Windows.");
}
const shell = findExecutableOnPath("pwsh.exe") ?? findExecutableOnPath("powershell.exe");
if (!shell) {
throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");
}
return { shell, args: [...POWERSHELL_ARGS] };
}
/**
* The environment agent-spawned shells get: the user's shell environment with declared credentials withheld
* (senpi#6820), plus the kill guard's runtime layer.
*/
export function getShellEnv() {
// The kill guard's runtime shims go first on PATH while the host has them active (senpi#5349).
return withKillGuardRuntime(withCredentialProxy(getUserShellEnv()));
}
/**
* The environment for a command the user typed (`!cmd`): no kill guard runtime layer, which judges only what the agent
* runs (senpi#5349).
*/
export function getUserShellEnv() {
const binDir = getBinDir();
const pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === "path") ?? "PATH";
const currentPath = process.env[pathKey] ?? "";
const pathEntries = currentPath.split(delimiter).filter(Boolean);
const hasBinDir = pathEntries.includes(binDir);
const updatedPath = hasBinDir ? currentPath : [binDir, currentPath].filter(Boolean).join(delimiter);
// An RPC host's supervisor hand-off stays in the host; the shell gets the origin attribution instead (senpi#5635).
return withBundledBunCommands({
...childEnvironmentOf(process.env),
[pathKey]: updatedPath,
});
}
/**
* Sanitize binary output for display/storage.
* Removes characters that crash string-width or cause display issues:
* - Control characters (except tab, newline, carriage return)
* - Unicode interlinear annotation characters U+FFF9..U+FFFB (crash string-width due to a bug)
*/
export function sanitizeBinaryOutput(str) {
// Fork fast path: most output has nothing to remove, so skip the scan-and-copy entirely.
if (!hasUnsafeDisplayCharacter(str)) {
return str;
}
// All removed characters are single UTF-16 code units, so surrogate pairs are never split.
return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g, "");
}
function hasUnsafeDisplayCharacter(str) {
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
const isAllowedControl = code === 0x09 || code === 0x0a || code === 0x0d;
if (code <= 0x1f && !isAllowedControl)
return true;
if (code >= 0xfff9 && code <= 0xfffb)
return true;
}
return false;
}
/**
* Detached child processes must be tracked so they can be killed on parent
* shutdown signals (SIGHUP/SIGTERM).
*
* What is tracked on unix is the process GROUP, not the bare pid: every tracked child is
* spawned `detached`, so it leads its own group, and a command like `sleep 30 &` or
* `nohup server &` keeps running in that group long after the shell that started it exited.
* Dropping the entry on the leader's exit orphaned those descendants past shutdown
* ([#1697](https://github.com/code-yeongyu/senpi/issues/1697)).
*/
const trackedDetachedChildren = new Map();
export function trackDetachedChildPid(pid) {
trackedDetachedChildren.set(pid, { pid, pgid: pid, leaderExited: false });
}
export function untrackDetachedChildPid(pid) {
trackedDetachedChildren.delete(pid);
}
/** Read-only snapshot of the tracked groups (diagnostics and tests; never module state). */
export function listTrackedDetachedChildren() {
return Array.from(trackedDetachedChildren.values(), (entry) => Object.freeze({ ...entry }));
}
/**
* Record that a tracked child exited. Ownership is released only when its process group
* is empty; while descendants survive there, shutdown must still be able to kill them.
* Windows has no such group, so the entry is dropped on exit as before.
*/
export function noteDetachedChildExited(pid) {
const entry = trackedDetachedChildren.get(pid);
if (entry === undefined)
return;
if (process.platform === "win32" || !processGroupIsAlive(entry.pgid)) {
trackedDetachedChildren.delete(pid);
return;
}
entry.leaderExited = true;
}
/** Drop tracked groups that have no members left, so a long session cannot accumulate entries. */
export function pruneTrackedDetachedChildren() {
if (process.platform === "win32")
return;
for (const [pid, entry] of trackedDetachedChildren) {
if (trackedDetachedChildIsGone(entry))
trackedDetachedChildren.delete(pid);
}
}
function signalTargetExists(target) {
try {
process.kill(target, 0);
return true;
}
catch (error) {
// EPERM means the target exists but is not ours to signal; only ESRCH proves it is gone.
return error.code !== "ESRCH";
}
}
function processGroupIsAlive(pgid) {
return signalTargetExists(-pgid);
}
function trackedDetachedChildIsGone(entry) {
if (processGroupIsAlive(entry.pgid))
return false;
// A leader that already exited must not be probed by pid: that number can have been
// recycled onto an unrelated process. An empty group is proof enough.
return entry.leaderExited || !signalTargetExists(entry.pid);
}
export function killTrackedDetachedChildren() {
pruneTrackedDetachedChildren();
if (trackedDetachedChildren.size === 0)
return;
// One listing for the whole batch: each tree kill would otherwise list every process again.
const rows = process.platform === "win32" ? listWindowsProcesses() : undefined;
for (const entry of trackedDetachedChildren.values()) {
if (process.platform === "win32")
killWindowsProcessTree(entry.pid, undefined, () => rows);
else
killTrackedDetachedGroup(entry);
}
trackedDetachedChildren.clear();
}
/**
* Kill a tracked group on unix.
*
* The direct-pid fallback of `killProcessTree()` is deliberately not reused here: a tracked
* entry can outlive its leader by minutes, and signalling that stale pid could hit whatever
* unrelated process the kernel has since given the number to. Only a leader still known to
* be alive may be signalled directly.
*/
function killTrackedDetachedGroup(entry) {
try {
process.kill(-entry.pgid, "SIGKILL");
return;
}
catch {
// The group is already empty, or this child never led one.
}
if (entry.leaderExited)
return;
try {
process.kill(entry.pid, "SIGKILL");
}
catch {
// Process already dead.
}
}
/**
* Ordered `taskkill` launchers to try, most reliable first.
*
* `spawn("taskkill", ...)` relies on a PATH lookup, so any session whose PATH lost
* `%SystemRoot%\System32` (a POSIX-style PATH inherited from a Git Bash/MSYS launcher,
* a truncated user PATH, a locked-down service account) fails to resolve it. A broken PATH
* must not cost us the process-tree kill, so every absolute System32 location that actually
* exists is tried before the bare PATH-resolved name.
*/
export function windowsTaskkillCandidates(env = process.env) {
// A bare `SystemDrive` is drive-relative ("C:"), so anchor it before joining.
const systemDrive = env.SystemDrive ? `${env.SystemDrive}\\` : undefined;
const roots = [env.SystemRoot, env.SYSTEMROOT, env.windir, systemDrive && join(systemDrive, "Windows")];
const candidates = [];
for (const root of roots) {
if (!root)
continue;
// Sysnative reaches the real 64-bit System32 from a 32-bit process, where System32
// is redirected to SysWOW64.
for (const systemDir of ["System32", "Sysnative"]) {
const absolute = join(root, systemDir, "taskkill.exe");
if (!candidates.includes(absolute) && existsSync(absolute))
candidates.push(absolute);
}
}
candidates.push("taskkill.exe");
return candidates;
}
function killProcessDirectly(pid) {
try {
process.kill(pid);
}
catch {
// Process already dead.
}
}
/** Upper bound on how long a shutdown may block waiting for `taskkill` to finish. */
const TASKKILL_TIMEOUT_MS = 5_000;
function listWindowsProcesses() {
return listWindowsProcessRowsSync(TASKKILL_TIMEOUT_MS);
}
function taskkillHandledTree(taskkillPath, killArgs) {
if (killArgs.length === 0)
return true;
try {
const result = spawnSync(taskkillPath, [...killArgs], {
stdio: "ignore",
windowsHide: true,
timeout: TASKKILL_TIMEOUT_MS,
});
// `error` means the launcher never started (ENOENT, EACCES); a null status means
// the timeout killed it. Any real taskkill exit code counts as handled.
return result.error === undefined && result.status !== null;
}
catch {
return false;
}
}
/**
* Kill a process and its descendants on Windows: one process listing (bounded by `TASKKILL_TIMEOUT_MS`)
* decides the tree, a process counting as a child only when it started at or after the parent it names,
* and `taskkill /F` ends each pid by name. `/T` would also adopt an unrelated older process through a
* recycled parent pid (senpi#2999); it is used only when no listing can be read.
*
* Synchronous on purpose. Shutdown paths call `killTrackedDetachedChildren()` and then
* `process.exit()` in the same tick (`emergencyTerminalExit()`), so neither an
* asynchronous killer nor a fallback wired to a child's `error` event would ever run and
* the tracked child would survive. `spawnSync` also reports a failed executable lookup on
* its returned `error` field instead of emitting it, so a PATH without
* `%SystemRoot%\System32` can no longer surface as an uncaught `spawn taskkill ENOENT`.
*
* The direct `process.kill` at the end is a degraded last resort reached only when no
* `taskkill.exe` can be launched at all. It maps to `TerminateProcess`, which does not
* touch descendants — the same limitation `packages/pty/src/pipe-fallback.ts` documents.
* Nothing in-process can walk a Windows process tree without an external tool, so this
* still beats leaving the whole tree running.
*/
export function killWindowsProcessTree(pid, taskkillPaths = windowsTaskkillCandidates(), listProcesses = listWindowsProcesses) {
const killArgs = windowsTreeKillArgs(pid, listProcesses());
for (const taskkillPath of taskkillPaths) {
if (taskkillHandledTree(taskkillPath, killArgs))
return;
}
killProcessDirectly(pid);
}
/**
* Kill a process and all its children (cross-platform)
*/
export function killProcessTree(pid) {
if (process.platform === "win32") {
killWindowsProcessTree(pid);
}
else {
// Use SIGKILL on Unix/Linux/Mac
try {
process.kill(-pid, "SIGKILL");
}
catch {
// Fallback to killing just the child if process group kill fails
try {
process.kill(pid, "SIGKILL");
}
catch {
// Process already dead
}
}
}
}
//# sourceMappingURL=shell.js.map