UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

2,286 lines • 97 kB
import { spawn, spawnSync } from "node:child_process";
import { FOREIGN_WINDOW_MARGIN, redactThenCut } from "../../core/untrusted-egress.js";
import { describeRejectedValue } from "../../core/tool-search-setting.js";
import { createHash, randomUUID } from "node:crypto";
import { closeSync, constants, createReadStream, mkdtempSync, openSync, readSync, rmSync, statSync, truncateSync, unlinkSync } from "node:fs";
import { access, appendFile, lstat, mkdir, mkdtemp, open, readdir, readFile, readlink, rename, rm, stat, unlink, writeFile, } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, dirname, isAbsolute, join, posix as posixPath, sep, win32 as win32Path } from "node:path";
import { createInterface } from "node:readline";
import { ExecutionError, err, FileError, ok, toError, } from "../harness/types.js";
import { killProcessTree, shutdownDebug } from "./kill-tree.js";
import { __resetSecretEnvScrubNoticeAnnouncement, announceSecretEnvScrub, composedUnderScrub, declaredInheritEntry, envNameKeyOn, hostChildEnv, hostChildEnvProblem, inheritEnvPolicyProblem, inheritedHostEnv, readInheritEnvForms, recordChildSpawned } from "../../core/secret-env.js";
import { deliverEngineNotice } from "../../core/engine-notice.js";
import { confineShellStart, SANDBOX_EXEC, SEATBELT_PROBE_PROFILE } from "../../core/shell-confinement.js";
import { physicalPathOfAsync } from "../../core/physical-path.js";
import { posixModeBitsMeaningful } from "../../core/posix-mode-face.js";
import { isAbsoluteForFamily, isWinFormPath } from "../../core/unc-spelling.js";
import { SHELL_KIND_QUESTION, SHELL_KIND_QUESTION_OPTIONS, STARTED_SHELL, STARTUP_FILE_NAMES, configuredNamesKeptOut, configuredShellLayer, inheritedShellState, readShellKindAnswer, shellKindQuestionEnv, shellStartArgs } from "../../core/model-shell.js";
import { anchorAtLinkDir, walkSymlinkChain } from "./symlink-chain.js";
import { RollingTailBuffer, markTruncated, newStreamCursorState, sliceStreamIncrement, } from "../../core/exec-output-tail.js";
import { BackgroundShellError } from "../../core/background-shell.js";
import { SchedulerError } from "../../core/scheduler.js";
const MAX_TIMER_TIMEOUT_MS = 2_147_000_000;
const NODE_ENV_CAPABILITIES = Object.freeze({
    isolation: false,
    suspendable: false,
    sharesProcessTable: true,
    canonicalPathAuthoritative: true,
    hostLocalPaths: true,
    externalContentTarget: false,
    io: true,
    keepsReadFloor: false,
    commandSandbox: false,
});
const NODE_ENV_CONFINED_CAPABILITIES = Object.freeze({ ...NODE_ENV_CAPABILITIES, keepsReadFloor: true });
function probeReadFloorConfinement() {
    if (process.platform !== "darwin")
        return { ok: false, reason: `this platform (${process.platform}) has no process confinement the engine applies — macOS only` };
    try {
        const r = spawnSync(SANDBOX_EXEC, ["-p", SEATBELT_PROBE_PROFILE, "/usr/bin/true"], { env: {}, stdio: ["ignore", "ignore", "pipe"], timeout: 10_000, encoding: "utf8" });
        if (r.status === 0)
            return { ok: true };
        const said = redactThenCut((r.error?.message ?? r.stderr ?? "").trim(), 300);
        return { ok: false, reason: `${SANDBOX_EXEC} could not apply the confinement base here (${r.status === null ? `signal ${r.signal ?? "none"}` : `exit ${r.status}`}${said !== "" ? `: ${said}` : ""})` };
    }
    catch (e) {
        return { ok: false, reason: `${SANDBOX_EXEC} could not be run (${redactThenCut(toError(e).message, 300)})` };
    }
}
function profileApplyFailure(profile) {
    return new Promise((resolve) => {
        let said = "";
        let child;
        try {
            child = spawn(SANDBOX_EXEC, ["-p", profile, "/usr/bin/true"], { env: {}, stdio: ["ignore", "ignore", "pipe"] });
        }
        catch (e) {
            resolve(`${SANDBOX_EXEC} could not be run: ${redactThenCut(toError(e).message, 300)}`);
            return;
        }
        child.stderr?.setEncoding("utf8");
        child.stderr?.on("data", (chunk) => {
            if (said.length < 300 + 2 * FOREIGN_WINDOW_MARGIN)
                said += chunk;
        });
        child.on("error", (e) => resolve(`${SANDBOX_EXEC} could not be run: ${redactThenCut(e.message, 300)}`));
        child.on("close", (code, signal) => {
            const words = redactThenCut(said.trim(), 300);
            resolve(code === 0 ? undefined : `${code === null ? `signal ${signal ?? "none"}` : `exit ${code}`}${words !== "" ? `: ${words}` : ""}`);
        });
    });
}
function resolvePath(cwd, path) {
    if (isAbsolute(path))
        return path;
    return anchorAtLinkDir(isAbsolute(cwd) ? cwd : anchorAtLinkDir(process.cwd(), cwd, sep), path, sep);
}
export function resolveExecTimeoutMs(timeoutSeconds) {
    if (typeof timeoutSeconds !== "number" ||
        !Number.isFinite(timeoutSeconds) ||
        timeoutSeconds <= 0) {
        return undefined;
    }
    const milliseconds = Math.floor(timeoutSeconds * 1000);
    if (!Number.isFinite(milliseconds) || milliseconds <= 0) {
        return 1;
    }
    return Math.min(milliseconds, MAX_TIMER_TIMEOUT_MS);
}
function fileKindFromStats(stats) {
    if (stats.isFile()) {
        return "file";
    }
    if (stats.isDirectory()) {
        return "directory";
    }
    if (stats.isSymbolicLink()) {
        return "symlink";
    }
    return undefined;
}
const HAS_POSIX_MODE_FACE = posixModeBitsMeaningful();
const O_NOFOLLOW_ANY = 0x20000000;
let linksRefusedOnTheWay;
function refusesLinksOnTheWay() {
    return (linksRefusedOnTheWay ??= probeLinksRefusedOnTheWay().then((answer) => {
        if (answer === undefined)
            linksRefusedOnTheWay = undefined;
        return answer === true;
    }));
}
async function probeLinksRefusedOnTheWay() {
    try {
        if (!(await lstat("/var")).isSymbolicLink())
            return undefined;
        await stat("/var/tmp");
    }
    catch {
        return undefined;
    }
    try {
        await (await open("/var/tmp", constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | O_NOFOLLOW_ANY)).close();
        return false;
    }
    catch (error) {
        if (isNodeError(error) && error.code === "ELOOP")
            return true;
        if (isNodeError(error) && error.code === "EINVAL")
            return false;
        return undefined;
    }
}
async function readUpTo(handle, size, limit, aborted) {
    const readAt = async (into, offset, length, position) => {
        const { bytesRead } = await handle.read(into, offset, length, position);
        if (aborted())
            throw new FileError("aborted", "Operation aborted");
        return bytesRead;
    };
    if (size > 0) {
        const want = Math.min(size, limit);
        const out = Buffer.allocUnsafe(want);
        let at = 0;
        while (at < want) {
            const bytesRead = await readAt(out, at, want - at, at);
            if (bytesRead === 0)
                break;
            at += bytesRead;
        }
        return out.subarray(0, at);
    }
    const scratch = Buffer.allocUnsafe(Math.min(1 << 16, limit));
    const chunks = [];
    let at = 0;
    while (at < limit) {
        const bytesRead = await readAt(scratch, 0, Math.min(scratch.length, limit - at), at);
        if (bytesRead === 0)
            break;
        chunks.push(Buffer.from(scratch.subarray(0, bytesRead)));
        at += bytesRead;
    }
    return Buffer.concat(chunks, at);
}
async function readAllFrom(handle, max, aborted) {
    const overCap = (bytes) => new FileError("invalid", `The held file is over the ${max}-byte read cap (${bytes} bytes or more); it was not read`);
    const size = Number((await handle.stat()).size);
    if (size > max)
        throw overCap(size);
    const got = await readUpTo(handle, size, max + 1, aborted);
    if (got.length > max)
        throw overCap(got.length);
    return got;
}
async function readFirstBytes(resolved, maxBytes, abortSignal) {
    let handle;
    try {
        handle = await open(resolved, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
        const held = await handle.stat();
        if (held.isDirectory())
            return err(new FileError("is_directory", `EISDIR: illegal operation on a directory, read '${resolved}'`, resolved));
        if (!held.isFile())
            return err(new FileError("invalid", "Not a regular file (a FIFO, socket or device is not read by name)", resolved));
        const aborted = abortResult(abortSignal, resolved);
        if (aborted)
            return aborted;
        return ok(await readUpTo(handle, Number(held.size), maxBytes, () => abortResult(abortSignal, resolved) !== undefined));
    }
    catch (error) {
        return err(toFileError(error, resolved));
    }
    finally {
        await handle?.close().catch(() => { });
    }
}
function fileInfoFromStats(path, stats) {
    const kind = fileKindFromStats(stats);
    if (!kind) {
        return err(new FileError("invalid", "Unsupported file type", path));
    }
    return ok({
        name: (() => {
            const t = path.replace(/[\\/]+$/, "");
            return t.slice(Math.max(t.lastIndexOf("/"), t.lastIndexOf("\\")) + 1) || path;
        })(),
        path,
        kind,
        size: stats.size,
        mtimeMs: stats.mtimeMs,
        ...(HAS_POSIX_MODE_FACE && typeof stats.mode === "number" ? { mode: stats.mode & 0o7777 } : {}),
    });
}
function isNodeError(error) {
    return error instanceof Error && "code" in error;
}
async function listedEntryInfo(shown, statAt) {
    try {
        const info = fileInfoFromStats(shown, await lstat(statAt));
        return info.ok ? info.value : undefined;
    }
    catch (error) {
        if (isNodeError(error) && error.code === "ENOENT")
            return undefined;
        throw error;
    }
}
function toFileError(error, path) {
    if (error instanceof FileError) {
        return error;
    }
    const cause = toError(error);
    if (isNodeError(error)) {
        const message = error.message;
        switch (error.code) {
            case "ABORT_ERR":
                return new FileError("aborted", message, path, cause);
            case "ENOENT":
                return new FileError("not_found", message, path, cause);
            case "EACCES":
            case "EPERM":
                return new FileError("permission_denied", message, path, cause);
            case "ENOTDIR":
                return new FileError("not_directory", message, path, cause);
            case "ELOOP":
                return new FileError("symlink_loop", message, path, cause);
            case "EISDIR":
                return new FileError("is_directory", message, path, cause);
            case "ENAMETOOLONG":
                if (path !== undefined && path.split(/[\\/]/).some((part) => Buffer.byteLength(part, "utf8") > 255))
                    return new FileError("name_too_long", message, path, cause);
                break;
            case "EINVAL":
                return new FileError("invalid", message, path, cause);
            default:
                break;
        }
    }
    return new FileError("unknown", cause.message, path, cause);
}
async function readLinkTarget(resolved) {
    try {
        return ok(await readlink(resolved));
    }
    catch (error) {
        return err(toFileError(error, resolved));
    }
}
function abortResult(signal, path) {
    return signal?.aborted ? err(new FileError("aborted", "aborted", path)) : undefined;
}
function isFsSupportError(error) {
    const code = isNodeError(error) ? error.code : undefined;
    return code === "EINVAL" || code === "ENOTSUP" || code === "EPERM" || code === "ENOSYS";
}
const RENAME_FALLBACK_CODES = new Set(["EXDEV", "EPERM", "EEXIST", "EBUSY"]);
const NAME_MAX_BYTES = 255;
const STAGING_NAME_DIGEST_HEX = 12;
const STAGING_CUT_AT_BYTES = NAME_MAX_BYTES - 3;
const STAGING_SUFFIX = /\.tmp\.(\d+)\.[0-9a-f]{12}$/;
function stagingSuffix(pid) {
    return `.tmp.${pid}.${randomUUID().replace(/-/g, "").slice(0, 12)}`;
}
function stagingNameOf(name, suffix) {
    const nameBytes = Buffer.byteLength(name, "utf8");
    const suffixBytes = Buffer.byteLength(suffix, "utf8");
    if (nameBytes + suffixBytes < STAGING_CUT_AT_BYTES || nameBytes > NAME_MAX_BYTES)
        return `${name}${suffix}`;
    const mark = `~${createHash("sha256").update(name, "utf8").digest("hex").slice(0, STAGING_NAME_DIGEST_HEX)}`;
    const keep = NAME_MAX_BYTES - suffixBytes - Buffer.byteLength(mark, "utf8");
    let kept = "";
    let used = 0;
    for (const char of name) {
        const bytes = Buffer.byteLength(char, "utf8");
        if (used + bytes > keep)
            break;
        kept += char;
        used += bytes;
    }
    return `${kept}${mark}${suffix}`;
}
function stagingSiblingOf(target) {
    const suffix = stagingSuffix(process.pid);
    const name = basename(target);
    if (!target.endsWith(name))
        return `${target}${suffix}`;
    return `${target.slice(0, target.length - name.length)}${stagingNameOf(name, suffix)}`;
}
function processIsGone(pid) {
    if (!Number.isSafeInteger(pid) || pid < 1)
        return false;
    try {
        process.kill(pid, 0);
        return false;
    }
    catch (error) {
        return isNodeError(error) && error.code === "ESRCH";
    }
}
async function sweepDeadStaging(target) {
    const name = basename(target);
    if (!target.endsWith(name))
        return 0;
    const prefix = target.slice(0, target.length - name.length);
    let entries;
    try {
        entries = await readdir(dirname(target));
    }
    catch {
        return 0;
    }
    let swept = 0;
    for (const entry of entries) {
        if (entry === name)
            continue;
        const tail = STAGING_SUFFIX.exec(entry);
        if (tail === null || entry !== stagingNameOf(name, tail[0]) || !processIsGone(Number(tail[1])))
            continue;
        const at = `${prefix}${entry}`;
        if (SWEEPING.has(at))
            continue;
        SWEEPING.add(at);
        try {
            const st = await lstat(at);
            if (!st.isFile() || st.nlink !== 1)
                continue;
            await unlink(at);
            swept += 1;
        }
        catch {
        }
        finally {
            SWEEPING.delete(at);
        }
    }
    return swept;
}
const SWEEPING = new Set();
async function discardStaging(tmp) {
    try {
        await unlink(tmp);
        return undefined;
    }
    catch (error) {
        const code = isNodeError(error) ? error.code : undefined;
        return code === "ENOENT" ? undefined : { path: tmp, sentence: `staging file left at ${tmp} (${code ?? "unlink failed"})` };
    }
}
const tellEnvironmentSeat = (onNotice, notice) => deliverEngineNotice(onNotice, notice, undefined, undefined, "environment");
function withStagingResidue(result, left, onNotice) {
    if (left === undefined)
        return result;
    if (result.ok) {
        tellEnvironmentSeat(onNotice, { code: "fs.staging_file_left", message: `${left.sentence}; the write itself succeeded`, detail: { path: left.path } });
        return result;
    }
    const { code, message, path, cause } = result.error;
    return err(new FileError(code, `${message}; ${left.sentence}`, path, cause instanceof Error ? cause : undefined));
}
async function pathExists(path) {
    try {
        await access(path, constants.F_OK);
        return true;
    }
    catch {
        return false;
    }
}
async function runCommand(command, args, timeoutMs, start, maxStdoutBytes) {
    return await new Promise((resolveLocal) => {
        const kept = [];
        let total = 0;
        let exited;
        let settled = false;
        let child;
        const settle = (status) => {
            if (settled)
                return;
            settled = true;
            clearTimeout(timeout);
            child.stdout?.destroy();
            child.unref();
            resolveLocal({ stdout: Buffer.concat(kept).toString("utf8"), status, overflowed: maxStdoutBytes !== undefined && total > maxStdoutBytes });
        };
        try {
            child = spawn(command, args, {
                stdio: ["ignore", "pipe", "ignore"],
                windowsHide: true,
                env: start === undefined ? inheritedHostEnv("scrub") : start.env(),
                ...(start === undefined ? {} : { cwd: start.cwd }),
            });
        }
        catch {
            resolveLocal({ stdout: "", status: null, overflowed: false });
            return;
        }
        const timeout = setTimeout(() => {
            if (child.pid) {
                killProcessTree(child.pid, { force: true });
            }
            settle(exited ?? null);
        }, timeoutMs);
        child.stdout?.on("data", (chunk) => {
            const before = total;
            total += chunk.length;
            const room = maxStdoutBytes === undefined ? chunk.length : maxStdoutBytes - before;
            if (room > 0)
                kept.push(chunk.subarray(0, room));
            if (maxStdoutBytes !== undefined && total > maxStdoutBytes)
                child.stdout?.destroy();
        });
        child.on("exit", (status) => {
            exited = status;
        });
        child.stdout?.on("error", () => { });
        child.on("error", () => settle(null));
        child.on("close", (status) => settle(status));
    });
}
export function isWslBashLauncher(p) {
    return /[/\\](system32|windowsapps)[/\\]bash\.exe$/i.test(p);
}
async function findBashOnPath() {
    const result = process.platform === "win32"
        ? await runCommand("where", ["bash.exe"], 5000)
        : await runCommand("which", ["bash"], 5000);
    if (result.status !== 0 || !result.stdout) {
        return null;
    }
    const lines = result.stdout.trim().split(/\r?\n/);
    const firstMatch = process.platform === "win32" ? lines.find((l) => !isWslBashLauncher(l)) : lines[0];
    return firstMatch && (await pathExists(firstMatch)) ? firstMatch : null;
}
export async function getShellConfig(customShellPath) {
    if (customShellPath) {
        if (await pathExists(customShellPath)) {
            return ok({ shell: customShellPath, args: ["-c"] });
        }
        return err(new ExecutionError("shell_unavailable", `Custom shell path not found: ${customShellPath}`));
    }
    if (process.platform === "win32") {
        const candidates = [];
        const programFiles = process.env.ProgramFiles;
        if (programFiles) {
            candidates.push(`${programFiles}\\Git\\bin\\bash.exe`);
        }
        const programFilesX86 = process.env["ProgramFiles(x86)"];
        if (programFilesX86) {
            candidates.push(`${programFilesX86}\\Git\\bin\\bash.exe`);
        }
        for (const candidate of candidates) {
            if (await pathExists(candidate)) {
                return ok({ shell: candidate, args: ["-c"] });
            }
        }
        const bashOnPath = await findBashOnPath();
        if (bashOnPath) {
            return ok({ shell: bashOnPath, args: ["-c"] });
        }
        return err(new ExecutionError("shell_unavailable", "No bash shell found"));
    }
    if (await pathExists("/bin/bash")) {
        return ok({ shell: "/bin/bash", args: ["-c"] });
    }
    const bashOnPath = await findBashOnPath();
    if (bashOnPath) {
        return ok({ shell: bashOnPath, args: ["-c"] });
    }
    return ok({ shell: "sh", args: ["-c"] });
}
const HOST_PROBE = {
    get platform() {
        return process.platform;
    },
    exists: pathExists,
    executable: async (path) => {
        try {
            await access(path, constants.X_OK);
            return (await stat(path)).isFile();
        }
        catch {
            return false;
        }
    },
    get programFiles() {
        return [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]];
    },
};
export function modelShellSearchPath(env, platform = process.platform) {
    const key = Object.keys(env).find((k) => envNameKeyOn(k, platform) === "PATH");
    const value = key === undefined ? undefined : env[key];
    return value === undefined || value === "" ? [] : value.split(platform === "win32" ? ";" : ":");
}
async function programOf(name, place, probe) {
    const at = probe.platform === "win32" ? win32Path : posixPath;
    if (isAbsoluteCandidate(name, probe.platform))
        return (await probe.exists(name)) ? name : undefined;
    if (name.includes("/") || (probe.platform === "win32" && isWinFormPath(name))) {
        const joined = at.resolve(place.cwd, name);
        return (await probe.exists(joined)) ? joined : undefined;
    }
    const names = probe.platform === "win32" && !/\.exe$/i.test(name) ? [name, `${name}.exe`] : [name];
    for (const dir of place.searchPath) {
        if (!isAbsoluteCandidate(dir, probe.platform))
            continue;
        for (const candidate of names.map((n) => at.join(dir, n))) {
            if (probe.platform === "win32" && isWslBashLauncher(candidate))
                continue;
            if (await probe.executable(candidate))
                return candidate;
        }
    }
    return undefined;
}
const SHELL_KIND_ANSWER_KEPT_BYTES = 64;
export async function askShellKind(path, cwd) {
    return (await askShellKindOnce(path, cwd)).answer;
}
async function askShellKindOnce(path, cwd) {
    const run = await runCommand(path, [...SHELL_KIND_QUESTION_OPTIONS, SHELL_KIND_QUESTION], 5000, { env: () => shellKindQuestionEnv(inheritedHostEnv("scrub")), cwd }, SHELL_KIND_ANSWER_KEPT_BYTES);
    if (run.overflowed)
        return { ran: run.status !== null, answer: { ok: false, reason: "gave no answer to the shell-kind question" } };
    if (run.status === null)
        return { ran: false, answer: { ok: false, reason: "gave no answer to the shell-kind question (it could not be started, timed out or was ended by a signal)" } };
    return { ran: true, answer: run.status !== 0 ? { ok: false, reason: `gave no answer to the shell-kind question (it exited with status ${run.status})` } : readShellKindAnswer(run.stdout) };
}
export async function resolveModelShell(shellPath, place, probe = HOST_PROBE, ask = askShellKind) {
    const refusals = [];
    const asked = new Set();
    let zsh;
    const tryOne = async (path) => {
        asked.add(path);
        const answer = await ask(path, place.cwd);
        if (!answer.ok) {
            refusals.push(`${path} ${answer.reason}`);
            return undefined;
        }
        const resolved = { path, shell: answer.shell, version: answer.version };
        if (answer.shell === STARTED_SHELL)
            return resolved;
        zsh ??= resolved;
        return undefined;
    };
    const unavailable = () => err(new ExecutionError("shell_unavailable", refusals.length === 0 ? "No bash or zsh shell found" : `No bash (3.2 or later, not in POSIX mode) or zsh to start commands on: ${refusals.join("; ")}`));
    if (shellPath) {
        const program = await programOf(shellPath, place, probe);
        if (program === undefined)
            return err(new ExecutionError("shell_unavailable", `Custom shell path not found: ${shellPath}`));
        const resolved = (await tryOne(program)) ?? zsh;
        return resolved !== undefined ? ok(resolved) : unavailable();
    }
    const fixed = probe.platform === "win32" ? probe.programFiles.flatMap((root) => (root ? [`${root}\\Git\\bin\\bash.exe`] : [])) : ["/bin/bash"];
    const fixedZsh = probe.platform === "win32" ? [] : ["/bin/zsh"];
    const tryFixed = async (candidate) => !isAbsoluteCandidate(candidate, probe.platform) || asked.has(candidate) || !(await probe.exists(candidate)) ? undefined : await tryOne(candidate);
    const tryOnPath = async (name) => {
        const onPath = await programOf(name, place, probe);
        return onPath === undefined || asked.has(onPath) ? undefined : await tryOne(onPath);
    };
    for (const candidate of fixed) {
        const resolved = await tryFixed(candidate);
        if (resolved !== undefined)
            return ok(resolved);
    }
    const bashOnPath = await tryOnPath("bash");
    if (bashOnPath !== undefined)
        return ok(bashOnPath);
    for (const candidate of fixedZsh) {
        if (zsh !== undefined)
            break;
        const resolved = await tryFixed(candidate);
        if (resolved !== undefined)
            return ok(resolved);
    }
    if (zsh === undefined) {
        const resolved = await tryOnPath("zsh");
        if (resolved !== undefined)
            return ok(resolved);
    }
    return zsh !== undefined ? ok(zsh) : unavailable();
}
function isAbsoluteCandidate(path, platform) {
    return isAbsoluteForFamily(platform === "win32" ? "win" : "posix", path);
}
const EXEC_FORCE_SETTLE_GRACE_MS = 3000;
let secretScrubSeatDefectAnnounced = false;
export function __resetSecretScrubAnnouncement() {
    secretScrubSeatDefectAnnounced = false;
    __resetSecretEnvScrubNoticeAnnouncement();
}
function getShellEnv(inheritEnv, baseEnv, extraEnv, onScrub, onNotice) {
    const { env, withheld: findings } = hostChildEnv(inheritEnv, baseEnv, extraEnv);
    if (findings.length > 0) {
        if (typeof onScrub === "function") {
            try {
                const r = onScrub(findings);
                if (typeof r?.then === "function") {
                    r.then(undefined, () => {
                    });
                }
            }
            catch {
            }
        }
        else if (onScrub !== undefined && !secretScrubSeatDefectAnnounced) {
            secretScrubSeatDefectAnnounced = true;
            tellEnvironmentSeat(onNotice, {
                code: "config.seat_malformed",
                message: `onSecretEnvScrub seat holds ${onScrub === null ? "null" : typeof onScrub} — not a function; scrub findings fall back to the console summary (once per process)`,
                detail: { seat: "onSecretEnvScrub" },
            });
        }
        if (!(typeof onScrub === "function" && onNotice === undefined)) {
            announceSecretEnvScrub(onNotice, findings);
        }
    }
    return env;
}
function lateDeclarationRefusal(refusal) {
    return `This execution environment (NodeExecutionEnv) was built before the process-level declaration that now names one of its inheritEnv entries, so it refuses every shell child it would start. Way out: build a new execution environment. Reason: ${refusal}`;
}
function lateDeclarationNoticeOf(sentence, entry) {
    return { code: "config.inherit_env_declared_late", message: sentence, detail: { index: entry.index, name: entry.name } };
}
const LATE_BRIEF_NAME_MAX = 64;
function lateDeclarationBrief(entry) {
    const name = entry.name.length > LATE_BRIEF_NAME_MAX ? `${entry.name.slice(0, LATE_BRIEF_NAME_MAX)}…` : entry.name;
    return `Refused again, for the reason its earlier refusal gave (inheritEnv[${entry.index}] names ${name}, declared after this execution environment was built). Way out: build a new execution environment.`;
}
class StartRefusal extends Error {
    brief;
    constructor(message, brief) {
        super(message);
        this.brief = brief;
        this.name = "StartRefusal";
    }
}
function briefOf(thrown) {
    return thrown instanceof StartRefusal ? thrown.brief : undefined;
}
const EXIT_SETTLE_DRAIN_MS = 500;
const EXEC_SPOOL_PUMP_MS = 200;
const EXEC_SPOOL_ROTATE_BYTES = 8 * 1024 * 1024;
const EXEC_SPOOL_FINAL_TAIL_BYTES = 8 * 1024 * 1024;
const EXEC_SPOOL_HARD_CAP_BYTES = 16 * 1024 * 1024;
export function decideSpoolReclaim(args) {
    const rotate = args.rotateBytes ?? EXEC_SPOOL_ROTATE_BYTES;
    const hardCap = args.hardCapBytes ?? EXEC_SPOOL_HARD_CAP_BYTES;
    if (args.writerLive)
        return { reclaim: false };
    if (args.cursor < rotate)
        return { reclaim: false };
    if (args.size === args.cursor)
        return { reclaim: true, skippedBytes: 0 };
    if (args.size > args.cursor && args.size >= hardCap)
        return { reclaim: true, skippedBytes: args.size - args.cursor };
    return { reclaim: false };
}
const SIGNUM = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGABRT: 6, SIGKILL: 9, SIGSEGV: 11, SIGPIPE: 13, SIGTERM: 15 };
export function openSpoolPair(base) {
    const outPath = `${base}.out.log`;
    const errPath = `${base}.err.log`;
    const fdOut = openSync(outPath, "ax", 0o600);
    let fdErr;
    try {
        fdErr = openSync(errPath, "ax", 0o600);
    }
    catch (e) {
        try {
            closeSync(fdOut);
        }
        catch {
        }
        throw e;
    }
    return { outPath, errPath, fds: [fdOut, fdErr] };
}
function shellChildStdio(spoolFds, stdinFed) {
    const stdin = stdinFed ? "pipe" : "ignore";
    return { stdio: spoolFds ? [stdin, spoolFds[0], spoolFds[1]] : [stdin, "pipe", "pipe"] };
}
export const MODEL_SHELL_DROPPED_KEPT = 32;
const RUN_SHELL = Symbol("NodeExecutionEnv.runShell");
const START_BACKGROUND = Symbol("NodeExecutionEnv.startBackground");
const MODEL_START = Symbol("NodeExecutionEnv.modelStart");
function withModelStart(options, start) {
    const own = options === undefined ? {} : Object.getOwnPropertyDescriptors(options);
    return Object.create(options === undefined ? Object.prototype : Object.getPrototypeOf(options), { ...own, [MODEL_START]: { value: start, enumerable: true } });
}
function modelStartOf(options) {
    let s;
    try {
        s = options?.[MODEL_START];
    }
    catch {
        return undefined;
    }
    return typeof s === "object" && s !== null ? s : undefined;
}
function modelStartAt(env, options) {
    const carried = modelStartOf(options);
    if (carried === undefined || carried.owner === env)
        return carried;
    const own = modelStartOfEnv(env);
    return {
        ...own,
        shellOf: async () => {
            const readFor = await kindKeptBy(carried);
            const mine = await own.resolutionOf();
            const refused = (why) => err(new ExecutionError("shell_unavailable", `${why}, so it does not run — give that environment a ${readFor ?? "shell"} of the same kind, or forward modelShell whole from the environment that runs the calls`));
            if (readFor === undefined)
                return refused("the shell the command was read for could not be read off the start it was handed on from");
            if (!mine.ok)
                return mine;
            if (mine.value.shell !== readFor)
                return refused(`${mine.value.path} is ${mine.value.shell} ${mine.value.version}; the command was read for ${readFor} (the start it was handed on from)`);
            return ok({ shell: mine.value.path, args: shellStartArgs(mine.value.shell, mine.value.path) });
        },
    };
}
async function kindKeptBy(start) {
    try {
        const resolved = await start.resolutionOf();
        return resolved.ok ? resolved.value.shell : undefined;
    }
    catch {
        return undefined;
    }
}
let modelStartOfEnv;
let spawnEnvOf;
export class NodeExecutionEnv {
    cwd;
    capabilities;
    confined;
    profileApplies = new Map();
    get homeDir() {
        return this.childEnvForRead()?.HOME;
    }
    get cdPath() {
        const value = this.childEnvForRead()?.CDPATH;
        return value === undefined || value === "" ? [] : value.split(":");
    }
    get searchPath() {
        const value = this.childEnvForRead()?.PATH;
        return value === undefined || value === "" ? [] : value.split(":");
    }
    get receivedEnvNames() {
        return Object.entries(this.childEnvForRead() ?? {}).flatMap(([name, value]) => (value === undefined ? [] : [name]));
    }
    get configuredStartupFileNames() {
        try {
            return configuredShellLayer(this.shellEnv, "env grant 1").dropped.filter((d) => d.row.match === "name" && STARTUP_FILE_NAMES.includes(d.row.text)).map((d) => d.key);
        }
        catch {
            return [];
        }
    }
    get withheldEnv() {
        let withheld = [];
        this.childEnvForRead((f) => (withheld = f));
        return withheld;
    }
    childEnvForRead(collect = () => { }) {
        try {
            const layer = configuredShellLayer(this.shellEnv, "env grant 1");
            return inheritedShellState(getShellEnv(this.inheritEnv, layer.kept, undefined, collect), process.platform, configuredNamesKeptOut([layer])).kept;
        }
        catch {
            return undefined;
        }
    }
    spawnEnv(extraEnv, base) {
        try {
            return getShellEnv(this.inheritEnv, base === undefined ? this.shellEnv : base.env, extraEnv, this.onSecretEnvScrub, this.onNotice);
        }
        catch (error) {
            const entry = declaredInheritEntry(this.inheritEnv);
            if (entry === undefined)
                throw error;
            const sentence = lateDeclarationRefusal(entry.refusal);
            if (this.lateDeclarationRaised === undefined) {
                const notice = lateDeclarationNoticeOf(sentence, entry);
                this.lateDeclarationRaised = notice;
                tellEnvironmentSeat(this.onNotice, notice);
            }
            throw new StartRefusal(sentence, lateDeclarationBrief(entry));
        }
    }
    shellPath;
    shellEnv;
    inheritEnv;
    inheritEnvForms;
    scheduler;
    bgShells = new Map();
    bgCounter = 0;
    retainBackgroundProcesses;
    onSecretEnvScrub;
    onNotice;
    lateDeclarationRaised;
    get lateDeclarationNotice() {
        return this.lateDeclarationRaised;
    }
    bgSpoolDir;
    spoolPairs = new Set();
    backgroundCapabilities;
    constructor(options) {
        if (options.readFloorConfinement !== undefined && options.readFloorConfinement !== "os") {
            throw new Error(`NodeExecutionEnv: readFloorConfinement must be "os" or absent (got ${describeRejectedValue(options.readFloorConfinement)}) — a confinement request that cannot be read is no request, so it refuses instead of reading as one side.`);
        }
        this.cwd = options.cwd;
        this.shellPath = options.shellPath;
        this.shellEnv = options.shellEnv;
        const inheritEnv = options.inheritEnv;
        let inheritEnvProblem;
        try {
            inheritEnvProblem = inheritEnvPolicyProblem(inheritEnv);
        }
        catch {
            inheritEnvProblem = "inheritEnv threw while it was read — refused";
        }
        inheritEnvProblem ??= hostChildEnvProblem(inheritEnv, options.shellEnv);
        if (inheritEnvProblem !== undefined)
            throw new Error(`NodeExecutionEnv: ${inheritEnvProblem}`);
        this.inheritEnv = Array.isArray(inheritEnv) ? [...inheritEnv] : (inheritEnv ?? "scrub");
        const formsRead = readInheritEnvForms(options.inheritEnvForms);
        if (!formsRead.ok)
            throw new Error(`NodeExecutionEnv: inheritEnvForms must be a plain array of distinct "scrub", "all", "list" words (got ${formsRead.valueType})`);
        if (formsRead.forms !== undefined)
            this.inheritEnvForms = formsRead.forms;
        this.scheduler = options.scheduler;
        this.retainBackgroundProcesses = options.retainBackgroundProcesses ?? false;
        this.onSecretEnvScrub = options.onSecretEnvScrub;
        this.onNotice = options.onNotice;
        const probe = options.readFloorConfinement === "os" ? probeReadFloorConfinement() : undefined;
        this.confined = probe?.ok === true;
        this.capabilities = this.confined ? NODE_ENV_CONFINED_CAPABILITIES : NODE_ENV_CAPABILITIES;
        if (probe !== undefined && !probe.ok) {
            tellEnvironmentSeat(this.onNotice, {
                code: "config.read_floor_confinement_unavailable",
                message: `Process confinement of the byte floor was requested (readFloorConfinement: "os") and is not available: ${probe.reason}. This environment declares that it does not keep the floor (capabilities.keepsReadFloor is false), so a run whose read-deny table holds rows is refused under readDenyFloorRequired, and otherwise announced to its user when the caller brought read-deny rows of its own.`,
                detail: { reason: probe.reason },
            });
        }
        this.backgroundCapabilities = {
            supported: true,
            maxConcurrent: 8,
            defaultBgTimeoutSec: 60 * 60,
            maxBgTimeoutSec: 2 * 60 * 60,
            supportsDetach: true,
            retainBackgroundProcesses: this.retainBackgroundProcesses,
        };
    }
    get schedulerCapabilities() {
        return (this.scheduler?.schedulerCapabilities ?? {
            supported: false,
            maxScheduledPerScope: 0,
            minDelaySec: 0,
            minCronIntervalSec: 0,
            maxScheduledHorizonSec: 0,
        });
    }
    async schedule(intent, ctx) {
        if (!this.scheduler)
            return err(new SchedulerError("unsupported", "No scheduler backend wired on this environment."));
        return this.scheduler.schedule(intent, ctx);
    }
    async cancel(id, ctx) {
        if (!this.scheduler)
            return err(new SchedulerError("unsupported", "No scheduler backend wired on this environment."));
        return this.scheduler.cancel(id, ctx);
    }
    async list(ctx) {
        if (!this.scheduler)
            return err(new SchedulerError("unsupported", "No scheduler backend wired on this environment."));
        return this.scheduler.list(ctx);
    }
    async absolutePath(path) {
        return ok(resolvePath(this.cwd, path));
    }
    async joinPath(parts) {
        const leading = sep === "\\" ? /^[\\/]+/ : /^\/+/;
        const named = parts.map((part, i) => (i === 0 ? part : part.replace(leading, ""))).filter((part) => part !== "");
        return ok(named.length === 0 ? "." : named.reduce((at, part) => anchorAtLinkDir(at, part, sep)));
    }
    async startOf(shell, command, options) {
        if (options?.sandbox !== undefined)
            return { ok: false, refusedBy: "environment", reason: "this environment keeps no command sandbox (capabilities.commandSandbox is false) — the command was not started" };
        const floor = options?.readFloor;
        const start = { command: shell.shell, args: [...shell.args, command] };
        if (!this.confined)
            return { ok: true, ...start };
        const confined = confineShellStart(start, floor);
        if (!confined.ok)
            return { ok: false, refusedBy: "this_call", reason: `the read-deny row ${JSON.stringify(confined.row)} cannot be kept by this environment's process confinement (${confined.reason}) — the command was not started` };
        if (confined.profile === undefined)
            return { ok: true, ...confined.start };
        let applies = this.profileApplies.get(confined.profile);
        if (applies === undefined) {
            if (this.profileApplies.size >= 16)
                this.profileApplies.clear();
            applies = profileApplyFailure(confined.profile);
            this.profileApplies.set(confined.profile, applies);
        }
        const failed = await applies;
        if (failed !== undefined)
            return { ok: false, refusedBy: "environment", reason: `the read-deny table's confinement profile does not apply on this host (${failed}) — the command was not started` };
        return { ok: true, ...confined.start };
    }
    exec(command, options) {
        const start = modelStartAt(this, options);
        return NodeExecutionEnv.prototype[RUN_SHELL].call(this, command, options, () => start?.shellOf() ?? getShellConfig(this.shellPath), () => start?.childEnvOf() ?? spawnEnvOf(this));
    }
    static {
        spawnEnvOf = (env) => {
            const spawnEnv = env.spawnEnv;
            return (extraEnv) => spawnEnv.call(env, extraEnv);
        };
    }
    get modelShell() {
        const start = () => modelStartOfEnv(this);
        return {
            exec: (script, options) => this.exec(script, withModelStart(options, start())),
            spawnBackground: (script, options) => this.spawnBackground(script, withModelStart(options, start())),
            ready: async () => {
                const resolved = await start().resolvedOf();
                return resolved.ok ? ok({ shell: resolved.value.shell, version: resolved.value.version }) : resolved;
            },
        };
    }
    static {
        modelStartOfEnv = (self) => {
            let layer;
            const layerOf = () => (layer ??= configuredShellLayer(self.shellEnv, "env grant 1"));
            const resolvedOf = async () => {
                let env;
                try {
                    env = self.spawnEnv(undefined, { env: layerOf().kept });
                }
                catch (error) {
                    const cause = toError(error);
                    const failure = new ExecutionError("spawn_error", cause.message, cause);
                    const brief = briefOf(error);
                    if (brief !== undefined)
                        failure.briefMessage = brief;
                    return err(failure);
                }
                return self.modelShellPath(env);
            };
            return {
                owner: self,
                resolvedOf,
                resolutionOf: () => self.modelShellResolved ?? resolvedOf(),
                shellOf: async () => {
                    const resolved = await (self.modelShellResolved ?? resolvedOf());
                    return resolved.ok ? ok({ shell: resolved.value.path, args: shellStartArgs(resolved.value.shell, resolved.value.path) }) : resolved;
                },
                childEnvOf: () => (extraEnv) => self.modelShellSpawnEnv(layerOf(), extraEnv),
            };
        };
    }
    modelShellResolved;
    modelShellPath(env) {
        if (this.modelShellResolved !== undefined)
            return this.modelShellResolved;
        let unanswered = false;
        const ask = async (path, cwd) => {
            const asked = await askShellKindOnce(path, cwd);
            if (!asked.ran)
                unanswered = true;
            return asked.answer;
        };
        const resolving = resolveModelShell(this.shellPath, { cwd: this.cwd, searchPath: modelShellSearchPath(env) }, HOST_PROBE, ask).then((resolved) => {
            if (!resolved.ok && unanswered && this.modelShellResolved === resolving)
                this.modelShellResolved = undefined;
            return resolved;
        });
        this.modelShellResolved = resolving;
        return resolving;
    }
    get modelShellDropped() {
        return this.modelShellDroppedRecord;
    }
    modelShellDroppedRecord = { entries: [], more: false };
    modelShellSpawnEnv(layer, extraEnv) {
        const extra = configuredShellLayer(extraEnv, "env grant 2");
        const composed = inheritedShellState(this.spawnEnv(extra.kept, { env: layer.kept }), process.platform, configuredNamesKeptOut([layer, extra]));
        const record = this.modelShellDroppedRecord;
        for (const d of [...layer.dropped, ...extra.dropped, ...composed.dropped]) {
            if (record.entries.some((e) => e.from === d.from && e.key === d.key))
                continue;
            if (record.entries.length >= MODEL_SHELL_DROPPED_KEPT)
                record.more = true;
            else
                record.entries.push(d);
        }
        return composed.kept;
    }
    async [RUN_SHELL](command, options, shellOf, childEnvOf) {
        if (options?.abortSignal?.aborted) {
            return err(new ExecutionError("aborted", "aborted"));
        }
        const cwd = options?.cwd ? resolvePath(this.cwd, options.cwd) : this.cwd;
        const shellConfig = await shellOf();
        if (!shellConfig.ok) {
            return shellConfig;
        }
        const start = await this.startOf(shellConfig.value, command, options);
        if (!start.ok)
            return err(Object.assign(new ExecutionError("sandbox_unavailable", start.reason), { refusedBy: start.refusedBy }));
        return await new Promise((resolvePromise) => {
            const stdoutTail = new RollingTailBuffer();
            const stderrTail = new RollingTailBuffer();
            let settled = false;
            let timedOut = false;
            let terminationInFlight = false;
            let callbackError;
            let child;
            const timeoutRef = {};
            const forceSettleRef = {};
            const spoolPumpRef = {};
            const execSpoolRef = {};
            const adoptOnTimeoutRef = {};
            const pumpSpoolRef = {};
            const drainSpoolRef = {};
            const writerLive = () => !settled && child !== undefined && child.exitCode === null && child.signalCode === null;
            const armForceSettle = (result) => {
                if (forceSettleRef.current || settled)
                    return;
                forceSettleRef.current = setTimeout(() => {
                    try {
                        child?.stdout?.destroy();
                        child?.stderr?.destroy();
                    }
                    catch {
                    }
                    settle(result);
                }, EXEC_FORCE_SETTLE_GRACE_MS);
                forceSettleRef.current.unref?.();
            };
            const partialOutput = () => {
                drainSpoolRef.current?.();
                const so = stdoutTail.result();
                const se = stderrTail.result();
                return { stdout: markTruncated(so.text, so.droppedBytes), stderr: markTruncated(se.text, se.droppedBytes) };
            };
            const onAbort = () => {
                terminationInFlight = true;
                if (child?.pid) {
                    const abortTarget = child;
                    killProcessTree(child.pid, { stillRunning: () => abortTarget.exitCode === null && abortTarget.signalCode === null });
                }
                if (callbackError) {
                    const p = partialOutput();
                    callbackError.partialStdout = p.stdout;
                    callbackError.partialStderr = p.stderr;
                    armForceSettle(err(callbackError));
                    return;
                }
                armForceSettle(err(new ExecutionError("aborted", "aborted", undefined, partialOutput())));
            };
            const settle = (result) => {
                if (timeoutRef.current) {
                    clearTimeout(timeoutRef.current);
                }
                if (forceSettleRef.current) {
                    clearTimeout(forceSettleRef.current);
                }
                if (options?.abortSignal) {
                    options.abortSignal.removeEventListener("abort", onAbort);
                }
                if (settled) {
                    return;
                }
                settled = true;
                if (spoolPumpRef.current)
                    clearInterval(spoolPumpRef.current);
                if (execSpoolRef.current && !(result.ok && result.value.detached !== undefined)) {
                    this.releaseSpoolPair(execSpoolRef.current);
                    execSpoolRef.current = undefined;
                }
                resolvePromise(result);
            };
            let execSpoolFds;
            if (process.platform !== "win32") {
                try {
                    const pair = this.mintSpoolPair(`fg_${randomUUID()}`);
                    execSpoolRef.current = { outPath: pair.outPath, errPath: pair.errPath };
                    execSpoolFds = pair.fds;
                }
                catch {
                    execSpoolRef.current = undefined;
                    execSpoolFds = undefined;
                }
            }
            const closeSpoolFds = () => {
                if (!execSpoolFds)
                    return;
                for (const fd of execSpoolFds) {
                    try {
                        closeSync(fd);
                    }
                    catch {
                    }
                }
                execSpoolFds = undefined;
            };
            const input = options?.stdinFrom;
            try {
                child = spawn(start.command, [...start.args], {
                    cwd,
                    detached: process.platform !== "win32",
                    env: childEnvOf()(options?.env),
                    ...shellChildStdio(execSpoolFds, input !== undefined),
                    windowsHide: true,
                });
                recordChildSpawned(composedUnderScrub(this.inheritEnv));
            }
            catch (error) {
                closeSpoolFds();
                const cause = toError(error);
                const failure = new ExecutionError("spawn_error", cause.message, cause);
                const brief = briefOf(error);
                if (brief !== undefined)
                    failure.briefMessage = brief;
                settle(err(failure));
                return;
            }
            closeSpoolFds();
            if (input !== undefined && child.stdin !== null) {
                const stdin = child.stdin;
                stdin.on("error", () => { });
                try {
                    stdin.end(Buffer.from(input.buffer, input.byteOffset, input.byteLength));
                }
                catch {
                    stdin.destroy();
                }
            }
            const timeoutMs = resolveExecTimeoutMs(options?.timeout);
            timeoutRef.current =
                timeoutMs === undefined
                    ? undefined
                    : setTimeout(() => {
                        if (options?.autoBackgroundOnTimeout && !terminationInFlight && adoptOnTimeoutRef.current) {
                            adoptOnTimeoutRef.current();
                            return;
                        }
                        terminationInFlight = true;
                        timedOut = true;
                        if (child?.pid) {
                            const timeoutTarget = child;
                            killProcessTree(child.pid, { stillRunning: () => timeoutTarget.exitCode === null && timeoutTarget.signalCode === null });
                        }
                        armForceSettle(err(new ExecutionError("timeout", `timeout:${options?.timeout}`, undefined, partialOutput())));
                    }, timeoutMs);
            if (options?.abortSignal) {
                if (options.abortSignal.aborted) {
                    onAbort();
                }
                else {
                    options.abortSignal.addEventListener("abort", onAbort, { once: true });
                }
            }
            const spoolCursor = { out: 0, err: 0 };
            const readSpoolIncrement = (path, cursor) => {
                try {
                    const size = statSync(path).size;
                    if (size <= spoolCursor[cursor])
                        return undefined;
                    const fd = openSync(path, "r");
                    try {
                        const want = Math.min(size - spoolCursor[cursor], 8 * 1024 * 1024 + 4096);
                        const buf = Buffer.alloc(want);
                        const got = readSync(fd, buf, 0, want, spoolCursor[cursor]);
                        if (got <= 0)
                            return undefined;
                        spoolCursor[cursor] += got;
                        return buf.subarray(0, got);
                    }
                    finally {
                        closeSync(fd);
                    }
                }
                catch {
                    return undefined;
                }
            };
            const feed = (tail, cb, buf) => {
                tail.push(buf);
                if (cb === undefined || settled)
                    return;
                try {
                    cb(buf.toString("utf8"));
                }
                catch (error) {
                    const cause = toError(error);
                    callbackError = new ExecutionError("callback_error", cause.message, cause);
                    onAbort();
                }
            };
            const spoolLanes = () => {
                const sp = execSpoolRef.current;
                if (sp === undefined)
                    return [];
                return [
                    { path: sp.outPath, cursor: "out", tail: stdoutTail, cb: options?.onStdout },
                    { path: sp.errPath, cursor: "err", tail: stderrTail, cb: options?.onStderr },
                ];
            };
            const skipAhead = (lane, keep) => {
                try {
                    const behind = statSync(lane.path).size - spoolCursor[lane.cursor];
                    if (behind <= keep)
                        return;
                    lane.tail.recordSkippedBytes(behind - keep);
                    spoolCursor[lane.cursor] += behind - keep;
                }
                catch {
                }
            };
            const reclaimSpool = (lane) => {
                if (spoolCursor[lane.cursor] < EXEC_SPOOL_ROTATE_BYTES)
                    return;
                try {
                    const d = decideSpoolReclaim({ size: statSync(lane.path).size, cursor: spoolCursor[lane.cursor], writerLive: writerLive() });
                    if (!d.reclaim)
                        return;
                    if (d.skippedBytes > 0)
                        lane.tail.recordSkippedBytes(d.skippedBytes);
                    truncateSync(lane.path, 0);
                    spoolCursor[lane.cursor] = 0;
                }
                catch {
                }
            };
            const pumpSpool = () => {
                for (const lane of spoolLanes()) {
                    skipAhead(lane, EXEC_SPOOL_ROTATE_BYTES);
                    const inc = readSpoolIncrement(lane.path, lane.cursor);
                    if (inc)
                        feed(lane.tail, lane.cb, inc);
                    reclaimSpool(lane);
                }
            };
            pumpSpoolRef.current = pumpSpool;
            const drainSpoolFinal = () => {
                for (const lane of spoolLanes()) {
                    skipAhead(lane, EXEC_SPOOL_FINAL_TAIL_BYTES);
                    for (let i = 0; i < 4; i++) {
                        const inc = readSpoolIncrement(lane.path, lane.cursor);
                        if (!inc)
                            break;
                        feed(lane.tail, lane.cb, inc);
                    }
                }
            };
            drainSpoolRef.current = drainSpoolFinal;
            if (execSpoolRef.current) {
                spoolPumpRef.current = setInterval(pumpSpool, EXEC_SPOOL_PUMP_MS);
                spoolPumpRef.current.unref?.();
            }
            const onDetach = (cause) => {
                if (settled || terminationInFlight || !child)
                    return false;
                pumpSpoolRef.current?.();
                if (settled || terminationInFlight)
                    return false;
                const shellId = this.adoptRunningChild(child, stdoutTail.result(), stderrTail.result(), execSpoolRef.current !== undefined ? { spool: execSpoolRef.current, cursors: { out: spoolCursor.out, err: spoolCursor.err } } : undefined);
                if (shellId === undefined)
                    return false;
                if (spoolPumpRef.current)
                    clearInterval(spoolPumpRef.current);
                if (timeoutRef.current)
                    clearTimeout(timeoutRef.current);
                const dso = stdoutTail.result();
                const dse = stderrTail.result();
                settle(ok({ stdout: markTruncated(dso.text, dso.droppedBytes), stderr: markTruncated(dse.text, dse.droppedBytes), exitCode: 0, detached: { shellId, ...(cause !== undefined ? { cause } : {}) } }));
                return true;
            };
            adoptOnTimeoutRef.current = () => {
                if (onDetach("timeout"))
                    return;
                if (terminationInFlight)
                    return;
                terminationInFlight = true;
                timedOut = true;
                if (child?.pid) {
                    const adoptFallbackTarget = child;
                    killProcessTree(child.pid, { stillRunning: () => adoptFallbackTarget.exitCode === null && adoptFallbackTarget.signalCode === null });
                }
                armForceSettle(err(new ExecutionError("timeout", `timeout:${options?.timeout}`, undefined, partialOutput())));
            };
            if (options?.detachSignal) {
                if (options.detachSignal.aborted)
                    onDetach();
                else {
                    const dl = () => onDetach();
                    options.detachSignal.addEventListener("abort", dl, { once: true });
                }
            }
            if (!execSpoolRef.current) {
                child.stdout?.setEncoding("utf8");
                child.stderr?.setEncoding("utf8");
                child.stdout?.on("data", (chunk) => {
                    stdoutTail.push(Buffer.from(chunk, "utf8"));
                    try {
                        options?.onStdout?.(chunk);
                    }
                    catch (error) {
                        const cause = toError(error);
                        callbackError = new ExecutionError("callback_error", cause.message, cause);
                        onAbort();
                    }
                });
                child.stderr?.on("data", (chunk) => {
                    stderrTail.push(Buffer.from(chunk, "utf8"));
                    try {
                        options?.onStderr?.(chunk);
                    }
                    catch (error) {
                        const cause = toError(error);
                        callbackError = new ExecutionError("callback_error", cause.message, cause);
                        onAbort();
                    }
                });
            }
            child.stdout?.on("error", () => { });
            child.stderr?.on("error", () => { });
            child.on("error", (error) => {
                if (options?.abortSignal?.aborted) {
                    settle(err(new ExecutionError("aborted", "aborted", undefined, partialOutput())));
                    return;
                }
                settle(err(new ExecutionError("spawn_error", error.message, error)));
            });
            const settleFromTermination = (code, signal) => {
                drainSpoolFinal();
                if (callbackError) {
                    const p = partialOutput();
                    callbackError.partialStdout = p.stdout;
                    callbackError.partialStderr = p.stderr;
                    settle(err(callbackError));
                    return;
                }
                if (timedOut) {
                    settle(err(new ExecutionError("timeout", `timeout:${options?.timeout}`, undefined, partialOutput())));
                    return;
                }
                if (options?.abortSignal?.aborted) {
                    settle(err(new ExecutionError("aborted", "aborted", undefined, partialOutput())));
                    return;
                }
                const so = stdoutTail.result();
                const se = stderrTail.result();
                if (code === null && signal) {
                    const signum = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGABRT: 6, SIGKILL: 9, SIGSEGV: 11, SIGPIPE: 13, SIGTERM: 15 };
                    settle(ok({
                        stdout: markTruncated(so.text, so.droppedBytes),
                        stderr: `${markTruncated(se.text, se.droppedBytes)}${se.text.endsWith("\n") || se.text === "" ? "" : "\n"}[process terminated by ${signal}]`,
                        exitCode: 128 + (signum[signal] ?? 9),
                    }));
                    return;
                }
                settle(ok({ stdout: markTruncated(so.text, so.droppedBytes), stderr: markTruncated(se.text, se.droppedBytes), exitCode: code ?? 0 }));
            };
            child.on("close", (code, signal) => settleFromTermination(code, signal));
            child.on("exit", (code, signal) => {
                if (execSpoolRef.current === undefined)
                    return;
                const drain = setTimeout(() => {
                    settleFromTermination(code, signal);
                }, EXIT_SETTLE_DRAIN_MS);
                drain.unref?.();
                child.once("close", () => clearTimeout(drain));
            });
        });
    }
    async readTextFile(path, abortSignal) {
        const resolved = resolvePath(this.cwd, path);
        const aborted = abortResult(abortSignal, resolved);
        if (aborted) {
            return aborted;
        }
        try {
            return ok(await readFile(resolved, { encoding: "utf8", signal: abortSignal }));
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
    }
    async readTextLines(path, options) {
        const resolved = resolvePath(this.cwd, path);
        const aborted = abortResult(options?.abortSignal, resolved);
        if (aborted) {
            return aborted;
        }
        if (options?.maxLines !== undefined && options.maxLines <= 0) {
            return ok([]);
        }
        let stream;
        let lineReader;
        try {
            stream = createReadStream(resolved, { encoding: "utf8", signal: options?.abortSignal });
            lineReader = createInterface({ input: stream, crlfDelay: Infinity });
            const lines = [];
            for await (const line of lineReader) {
                const loopAbort = abortResult(options?.abortSignal, resolved);
                if (loopAbort) {
                    return loopAbort;
                }
                lines.push(line);
                if (options?.maxLines !== undefined && lines.length >= options.maxLines) {
                    break;
                }
            }
            const afterReadAbort = abortResult(options?.abortSignal, resolved);
            if (afterReadAbort) {
                return afterReadAbort;
            }
            return ok(lines);
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
        finally {
            lineReader?.close();
            stream?.destroy();
        }
    }
    async readBinaryFile(path, abortSignal, maxBytes) {
        const resolved = resolvePath(this.cwd, path);
        if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 0)) {
            return err(new FileError("invalid", `maxBytes must be a non-negative whole number of bytes (got ${typeof maxBytes === "number" ? String(maxBytes) : typeof maxBytes})`, resolved));
        }
        const aborted = abortResult(abortSignal, resolved);
        if (aborted) {
            return aborted;
        }
        if (maxBytes !== undefined)
            return readFirstBytes(resolved, maxBytes, abortSignal);
        try {
            return ok(await readFile(resolved, { signal: abortSignal }));
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
    }
    async writeFile(path, content, abortSignal) {
        const resolved = resolvePath(this.cwd, path);
        const aborted = abortResult(abortSignal, resolved);
        if (aborted) {
            return aborted;
        }
        try {
            await mkdir(dirname(resolved), { recursive: true });
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
        const afterMkdirAbort = abortResult(abortSignal, resolved);
        if (afterMkdirAbort) {
            return afterMkdirAbort;
        }
        let target = resolved;
        let existingMode;
        let st;
        try {
            st = await lstat(resolved);
        }
        catch {
            st = undefined;
        }
        if (st !== undefined) {
            if (st.isSymbolicLink()) {
                let hop;
                try {
                    const link = await readlink(resolved);
                    const parentReal = await physicalPathOfAsync(dirname(resolved)).catch(() => dirname(resolved));
                    hop = isAbsolute(link) ? link : anchorAtLinkDir(parentReal, link, sep);
                }
                catch {
                    hop = undefined;
                }
                if (hop === undefined)
                    return await this.writeFileInPlace(resolved, content, abortSignal);
                let hopStat;
                try {
                    hopStat = await lstat(hop);
                }
                catch {
                    hopStat = undefined;
                }
                if (hopStat !== undefined && !hopStat.isFile()) {
                    return await this.writeFileInPlace(resolved, content, abortSignal);
                }
                target = hop;
                existingMode = hopStat !== undefined ? hopStat.mode & 0o7777 : undefined;
            }
            else if (!st.isFile()) {
                return await this.writeFileInPlace(resolved, content, abortSignal);
            }
            else {
                existingMode = st.mode & 0o7777;
            }
        }
        const swept = await sweepDeadStaging(target);
        if (swept > 0) {
            tellEnvironmentSeat(this.onNotice, {
                code: "fs.staging_file_swept",
                message: `removed ${swept} staging file${swept === 1 ? "" : "s"} that a process which no longer runs left beside a file this write replaces`,
                detail: { count: swept },
            });
        }
        const afterSweepAbort = abortResult(abortSignal, resolved);
        if (afterSweepAbort)
            return afterSweepAbort;
        const tmp = stagingSiblingOf(target);
        let tmpDurable = false;
        let created = false;
        try {
            const handle = await open(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), existingMode === undefined ? 0o666 : 0o600);
            created = true;
            try {
                await handle.writeFile(content, { signal: abortSignal });
                if (existingMode !== undefined) {
                    try {
                        await handle.chmod(existingMode);
                    }
                    catch (error) {
                        if (!isFsSupportError(error))
                            throw error;
                    }
                }
                try {
                    await handle.sync();
                }
                catch (error) {
                    if (!isFsSupportError(error))
                        throw error;
                }
                tmpDurable = true;
            }
            finally {
                await handle.close().catch(() => { });
            }
        }
        catch (error) {
            const left = created ? await discardStaging(tmp) : undefined;
            if (isNodeError(error) && error.code === "EACCES" && existingMode !== undefined) {
                return withStagingResidue(await this.writeFileInPlace(resolved, content, abortSignal), left, this.onNotice);
            }
            return withStagingResidue(err(toFileError(error, resolved)), left, this.onNotice);
        }
        const preRenameAbort = abortResult(abortSignal, resolved);
        if (preRenameAbort)
            return withStagingResidue(preRenameAbort, await discardStaging(tmp), this.onNotice);
        try {
            await rename(tmp, target);
            return ok(undefined);
        }
        catch (error) {
            const code = isNodeError(error) ? error.code : undefined;
            if (tmpDurable && code !== undefined && RENAME_FALLBACK_CODES.has(code)) {
                const inPlace = await this.writeFileInPlace(resolved, content, abortSignal);
                if (inPlace.ok || inPlace.error.code === "aborted")
                    return withStagingResidue(inPlace, await discardStaging(tmp), this.onNotice);
                return err(new FileError("unknown", `write to ${resolved} failed after the atomic rename was refused (${code}): ${inPlace.error.message}. The new content was preserved at ${tmp}`, resolved, inPlace.error));
            }
            return withStagingResidue(err(toFileError(error, resolved)), await discardStaging(tmp), this.onNotice);
        }
    }
    async writeFileInPlace(resolved, content, abortSignal) {
        const aborted = abortResult(abortSignal, resolved);
        if (aborted)
            return aborted;
        try {
            await writeFile(resolved, content);
            return ok(undefined);
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
    }
    async writeFileExclusive(path, content, abortSignal) {
        const resolved = resolvePath(this.cwd, path);
        const aborted = abortResult(abortSignal, resolved);
        if (aborted) {
            return aborted;
        }
        try {
            await mkdir(dirname(resolved), { recursive: true });
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
        const afterMkdirAbort = abortResult(abortSignal, resolved);
        if (afterMkdirAbort) {
            return afterMkdirAbort;
        }
        try {
            await writeFile(resolved, content, { flag: "wx" });
            return ok(undefined);
        }
        catch (error) {
            if (error?.code === "EEXIST") {
                return err(new FileError("already_exists", `file already exists: ${resolved}`, resolved, error instanceof Error ? error : undefined));
            }
            return err(toFileError(error, resolved));
        }
    }
    async appendFile(path, content) {
        const resolved = resolvePath(this.cwd, path);
        try {
            await mkdir(dirname(resolved), { recursive: true });
            await appendFile(resolved, content);
            return ok(undefined);
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
    }
    async fileInfo(path) {
        const resolved = resolvePath(this.cwd, path);
        try {
            return fileInfoFromStats(resolved, await lstat(resolved));
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
    }
    async setFileMode(path, mode, abortSignal) {
        const resolved = resolvePath(this.cwd, path);
        if (!HAS_POSIX_MODE_FACE) {
            return err(new FileError("not_supported", "This platform has no POSIX permission model", resolved));
        }
        const placed = await this.openPlaced(resolved, abortSignal);
        if (!placed.ok)
            return placed;
        try {
            await placed.value.handle.chmod(mode & 0o7777);
            return ok(undefined);
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
        finally {
            await placed.value.handle.close().catch(() => { });
        }
    }
    async listDir(path, abortSignal) {
        const resolved = resolvePath(this.cwd, path);
        const aborted = abortResult(abortSignal, resolved);
        if (aborted) {
            return aborted;
        }
        try {
            const entries = await readdir(resolved, { withFileTypes: true });
            const infos = [];
            for (const entry of entries) {
                const loopAbort = abortResult(abortSignal, resolved);
                if (loopAbort) {
                    return loopAbort;
                }
                const entryPath = anchorAtLinkDir(resolved, entry.name, sep);
                try {
                    const info = await listedEntryInfo(entryPath, entryPath);
                    if (info !== undefined) {
                        infos.push(info);
                    }
                }
                catch (error) {
                    return err(toFileError(error, entryPath));
                }
            }
            return ok(infos);
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
    }
    async canonicalPath(path) {
        const resolved = resolvePath(this.cwd, path);
        try {
            return ok(await physicalPathOfAsync(resolved));
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
    }
    async fileIdentity(path) {
        const resolved = resolvePath(this.cwd, path);
        try {
            const s = await stat(resolved, { bigint: true });
            return ok(`${s.dev}:${s.ino}`);
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
    }
    async openBound(path, abortSignal) {
        const resolved = resolvePath(this.cwd, path);
        const placed = await this.openPlaced(resolved, abortSignal);
        if (!placed.ok)
            return placed;
        const { handle, held } = placed.value;
        const identity = `${held.dev}:${held.ino}`;
        const kind = held.isDirectory() ? "directory" : "file";
        return ok({
            identity,
            kind,
            size: async () => {
                try {
                    return ok(Number((await handle.stat()).size));
                }
                catch (error) {
                    return err(toFileError(error, resolved));
                }
            },
            readBytes: async (max, signal) => {
                if (kind !== "file")
                    return err(new FileError("is_directory", "The held object is a directory", resolved));
                try {
                    return ok(await readAllFrom(handle, max, () => abortResult(signal, resolved) !== undefined));
                }
                catch (error) {
                    return err(toFileError(error, resolved));
                }
            },
            list: async (signal) => {
                if (kind !== "directory")
                    return err(new FileError("not_directory", "The held object is a file", resolved));
                try {
                    return await this.listOpenDirectory(handle, resolved, identity, signal);
                }
                catch (error) {
                    return err(toFileError(error, resolved));
                }
            },
            close: () => handle.close().catch(() => { }),
        });
    }
    async openPlaced(resolved, abortSignal) {
        const aborted = abortResult(abortSignal, resolved);
        if (aborted)
            return aborted;
        const observation = process.platform === "darwin" ? "open" : process.platform === "linux" ? "descriptor" : undefined;
        if (observation === undefined)
            return err(new FileError("not_supported", "This platform gives no kernel observation of where an opened object is, so it cannot be placed at the path that was checked", resolved));
        if (observation === "open" && !(await refusesLinksOnTheWay())) {
            return err(new FileError("not_supported", "This macOS does not refuse a link on the way of an open, so a read cannot be bound to the path that was checked", resolved));
        }
        const abortedWhileAsked = abortResult(abortSignal, resolved);
        if (abortedWhileAsked)
            return abortedWhileAsked;
        let handle;
        try {
            handle = await open(resolved, constants.O_RDONLY | (observation === "open" ? O_NOFOLLOW_ANY : (constants.O_NOFOLLOW ?? 0)) | (constants.O_NONBLOCK ?? 0));
        }
        catch (error) {
            if (isNodeError(error) && error.code === "ELOOP")
                return err(new FileError("precondition_failed", "A link stands on the path now, so it is not the object that was checked", resolved));
            return err(toFileError(error, resolved));
        }
        const refuse = async (code, message) => {
            await handle.close().catch(() => { });
            return err(new FileError(code, message, resolved));
        };
        try {
            const held = await handle.stat({ bigint: true });
            const place = observation === "open" ? "at" : await this.heldPlace(handle, resolved);
            if (place === "unobservable")
                return refuse("not_supported", "This platform gives no kernel path for an opened descriptor, so the opened object cannot be placed at its path");
            if (place === "elsewhere")
                return refuse("precondition_failed", "The path named another object than the one opened");
            if (!held.isFile() && !held.isDirectory())
                return refuse("invalid", "Neither a regular file nor a directory");
            if (abortSignal?.aborted === true)
                return refuse("aborted", "aborted");
            return ok({ handle, held });
        }
        catch (error) {
            return refuse(toFileError(error, resolved).code, error.message ?? "open failed");
        }
    }
    async heldPlace(handle, resolved) {
        const placed = await readlink(`/proc/self/fd/${handle.fd}`).catch(() => undefined);
        return placed === undefined ? "unobservable" : placed === resolved ? "at" : "elsewhere";
    }
    async listOpenDirectory(held, resolved, identity, abortSignal) {
        const throughHandle = process.platform === "linux";
        const listed = throughHandle ? `/proc/self/fd/${held.fd}` : resolved;
        const infos = [];
        for (const entry of await readdir(listed, { withFileTypes: true })) {
            const loopAbort = abortResult(abortSignal, resolved);
            if (loopAbort)
                return loopAbort;
            const info = await listedEntryInfo(anchorAtLinkDir(resolved, entry.name, sep), anchorAtLinkDir(listed, entry.name, sep));
            if (info !== undefined)
                infos.push(info);
        }
        if (!throughHandle) {
            const after = await stat(resolved, { bigint: true });
            if (`${after.dev}:${after.ino}` !== identity)
                return err(new FileError("precondition_failed", "The path named another directory by the time it was listed", resolved));
        }
        return ok(infos);
    }
    async readLink(path) {
        return readLinkTarget(resolvePath(this.cwd, path));
    }
    async canonicalChain(path) {
        return walkSymlinkChain(resolvePath(this.cwd, path), readLinkTarget);
    }
    async exists(path) {
        const result = await this.fileInfo(path);
        if (result.ok) {
            return ok(true);
        }
        if (result.error.code === "not_found") {
            return ok(false);
        }
        return err(result.error);
    }
    async createDir(path, options) {
        const resolved = resolvePath(this.cwd, path);
        try {
            await mkdir(resolved, { recursive: options?.recursive ?? true });
            return ok(undefined);
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
    }
    async remove(path, options) {
        const resolved = resolvePath(this.cwd, path);
        try {
            await rm(resolved, {
                recursive: options?.recursive ?? false,
                force: options?.force ?? false,
            });
            return ok(undefined);
        }
        catch (error) {
            return err(toFileError(error, resolved));
        }
    }
    async createTempDir(prefix = "tmp-") {
        try {
            return ok(await mkdtemp(join(tmpdir(), prefix)));
        }
        catch (error) {
            return err(toFileError(error));
        }
    }
    async createTempFile(options) {
        const dir = await this.createTempDir("tmp-");
        if (!dir.ok) {
            return dir;
        }
        const filePath = join(dir.value, `${options?.prefix ?? ""}${randomUUID()}${options?.suffix ?? ""}`);
        try {
            await writeFile(filePath, "");
            return ok(filePath);
        }
        catch (error) {
            return err(toFileError(error, filePath));
        }
    }
    adoptRunningChild(child, stdoutSoFar, stderrSoFar, handover) {
        const liveCount = [...this.bgShells.values()].filter((e) => e.status === "running").length;
        if (liveCount >= this.backgroundCapabilities.maxConcurrent)
            return undefined;
        const shellId = `bg_${++this.bgCounter}_${randomUUID()}`;
        const entry = {
            child,
            stdout: { ...newStreamCursorState(), totalBytes: 0 },
            stderr: { ...newStreamCursorState(), totalBytes: 0 },
            status: "running",
            ...(handover !== undefined
                ? { spool: { outPath: handover.spool.outPath, errPath: handover.spool.errPath, fileCursor: { ...handover.cursors }, ephemeral: true } }
                : {}),
        };
        const seedOut = Buffer.from(stdoutSoFar.text, "utf8");
        const seedErr = Buffer.from(stderrSoFar.text, "utf8");
        entry.stdout.tail.recordSkippedBytes(stdoutSoFar.droppedBytes);
        entry.stderr.tail.recordSkippedBytes(stderrSoFar.droppedBytes);
        entry.stdout.tail.push(seedOut);
        entry.stderr.tail.push(seedErr);
        entry.stdout.totalBytes += stdoutSoFar.droppedBytes + seedOut.length;
        entry.stderr.totalBytes += stderrSoFar.droppedBytes + seedErr.length;
        entry.stdout.acceptedBytes += seedOut.length;
        entry.stderr.acceptedBytes += seedErr.length;
        child.stdout?.on("data", (chunk) => {
            const buf = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
            entry.stdout.tail.push(buf);
            entry.stdout.totalBytes += buf.length;
            entry.stdout.acceptedBytes += buf.length;
        });
        child.stderr?.on("data", (chunk) => {
            const buf = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
            entry.stderr.tail.push(buf);
            entry.stderr.totalBytes += buf.length;
            entry.stderr.acceptedBytes += buf.length;
        });
        child.on("error", () => {
            if (entry.timer)
                clearTimeout(entry.timer);
            if (entry.status === "running")
                entry.status = "failed";
        });
        child.on("close", (code, signal) => {
            if (entry.timer)
                clearTimeout(entry.timer);
            this.reclaimEphemeralSpool(entry);
            if (entry.status === "killed")
                return;
            entry.status = "exited";
            entry.exitCode = code === null && signal ? 128 + (SIGNUM[signal] ?? 9) : (code ?? 0);
        });
        if (child.exitCode !== null || child.signalCode !== null) {
            entry.status = "exited";
            entry.exitCode = child.exitCode ?? (child.signalCode ? 128 + (SIGNUM[child.signalCode] ?? 9) : 0);
            this.reclaimEphemeralSpool(entry);
        }
        else {
            const timeoutSec = this.backgroundCapabilities.defaultBgTimeoutSec;
            entry.timeoutSecApplied = timeoutSec;
            entry.timer = setTimeout(() => {
                entry.status = "killed";
                entry.killCause = "timeout";
                if (child.pid)
                    killProcessTree(child.pid, { force: true });
            }, timeoutSec * 1000);
            entry.timer.unref?.();
        }
        if (entry.spool?.ephemeral) {
            entry.spoolPump = setInterval(() => this.syncSpool(entry), 1000);
            entry.spoolPump.unref?.();
        }
        this.bgShells.set(shellId, entry);
        return shellId;
    }
    spawnBackground(command, options) {
        const start = modelStartAt(this, options);
        return NodeExecutionEnv.prototype[START_BACKGROUND].call(this, command, options, () => start?.shellOf() ?? getShellConfig(this.shellPath), () => start?.childEnvOf() ?? spawnEnvOf(this));
    }
    async [START_BACKGROUND](command, options, shellOf, childEnvOf) {
        const liveCount = [...this.bgShells.values()].filter((e) => e.status === "running").length;
        if (liveCount >= this.backgroundCapabilities.maxConcurrent) {
            return err(new BackgroundShellError("limit_exceeded", `Too many running background shells (max ${this.backgroundCapabilities.maxConcurrent}); TaskStop one first.`));
        }
        const shellConfig = await shellOf();
        if (!shellConfig.ok) {
            return err(Object.assign(new BackgroundShellError("spawn_failed", shellConfig.error.message, shellConfig.error), shellConfig.error.briefMessage !== undefined ? { briefMessage: shellConfig.error.briefMessage } : {}));
        }
        const start = await this.startOf(shellConfig.value, command, options);
        if (!start.ok)
            return err(Object.assign(new BackgroundShellError("sandbox_unavailable", start.reason), { refusedBy: start.refusedBy }));
        let spool;
        let spoolFds;
        if (this.retainBackgroundProcesses || process.platform !== "win32") {
            try {
                const pair = this.mintSpoolPair(`bg_${this.bgCounter + 1}_${randomUUID()}`);
                spool = {
                    outPath: pair.outPath,
                    errPath: pair.errPath,
                    fileCursor: { out: 0, err: 0 },
                    ...(this.retainBackgroundProcesses ? {} : { ephemeral: true }),
                };
                spoolFds = pair.fds;
            }
            catch {
                spool = undefined;
                spoolFds = undefined;
            }
        }
        let child;
        try {
            child = spawn(start.command, [...start.args], {
                cwd: options?.cwd ? resolvePath(this.cwd, options.cwd) : this.cwd,
                detached: process.platform !== "win32",
                env: childEnvOf()(options?.env),
                ...shellChildStdio(spoolFds, false),
                windowsHide: true,
            });
            recordChildSpawned(composedUnderScrub(this.inheritEnv));
        }
        catch (error) {
            if (spoolFds) {
                for (const fd of spoolFds) {
                    try {
                        closeSync(fd);
                    }
                    catch {
                    }
                }
            }
            if (spool)
                this.releaseSpoolPair(spool);
            const cause = toError(error);
            const failure = new BackgroundShellError("spawn_failed", cause.message, cause);
            const brief = briefOf(error);
            if (brief !== undefined)
                failure.briefMessage = brief;
            return err(failure);
        }
        if (spoolFds) {
            for (const fd of spoolFds) {
                try {
                    closeSync(fd);
                }
                catch {
                }
            }
        }
        const shellId = `bg_${++this.bgCounter}_${randomUUID()}`;
        const entry = {
            child,
            stdout: { ...newStreamCursorState(), totalBytes: 0 },
            stderr: { ...newStreamCursorState(), totalBytes: 0 },
            status: "running",
            ...(spool ? { spool } : {}),
        };
        child.stdout?.setEncoding("utf8");
        child.stderr?.setEncoding("utf8");
        child.stdout?.on("data", (chunk) => {
            const buf = Buffer.from(chunk, "utf8");
            entry.stdout.tail.push(buf);
            entry.stdout.totalBytes += buf.length;
            entry.stdout.acceptedBytes += buf.length;
        });
        child.stderr?.on("data", (chunk) => {
            const buf = Buffer.from(chunk, "utf8");
            entry.stderr.tail.push(buf);
            entry.stderr.totalBytes += buf.length;
            entry.stderr.acceptedBytes += buf.length;
        });
        child.stdout?.on("error", () => { });
        child.stderr?.on("error", () => { });
        child.on("error", () => {
            if (entry.timer)
                clearTimeout(entry.timer);
            if (entry.status === "running")
                entry.status = "failed";
        });
        child.on("close", (code, signal) => {
            if (entry.timer)
                clearTimeout(entry.timer);
            this.reclaimEphemeralSpool(entry);
            if (entry.status === "killed")
                return;
            entry.status = "exited";
            entry.exitCode = code === null && signal ? 128 + (SIGNUM[signal] ?? 9) : (code ?? 0);
        });
        const timeoutSec = Math.min(options?.timeout ?? this.backgroundCapabilities.defaultBgTimeoutSec, this.backgroundCapabilities.maxBgTimeoutSec);
        entry.timeoutSecApplied = timeoutSec;
        entry.timer = setTimeout(() => {
            if (child.pid && entry.status === "running") {
                entry.status = "killed";
                entry.killCause = "timeout";
                shutdownDebug("bg hard-wall timeout", { shellId, pid: child.pid, timeoutSec });
                killProcessTree(child.pid, { force: true });
            }
        }, timeoutSec * 1000);
        entry.timer.unref?.();
        if (entry.spool?.ephemeral) {
            entry.spoolPump = setInterval(() => this.syncSpool(entry), 1000);
            entry.spoolPump.unref?.();
        }
        this.bgShells.set(shellId, entry);
        return ok({ shellId });
    }
    async pollBackground(shellId) {
        const entry = this.bgShells.get(shellId);
        if (!entry) {
            return err(new BackgroundShellError("not_found", `Unknown background shell: ${shellId}`));
        }
        this.syncSpool(entry);
        const terminal = entry.status !== "running";
        const out = sliceStreamIncrement(entry.stdout, terminal);
        const er = sliceStreamIncrement(entry.stderr, terminal);
        const droppedBeforeCursor = out.droppedBeforeCursor + er.droppedBeforeCursor;
        return ok({
            stdout: out.inc,
            stderr: er.inc,
            status: entry.status,
            ...(entry.exitCode !== undefined ? { exitCode: entry.exitCode } : {}),
            ...(droppedBeforeCursor > 0 ? { truncated: true, bytesDroppedBeforeCursor: droppedBeforeCursor } : {}),
            ...(entry.killCause === "timeout"
                ? { timedOut: true, ...(entry.timeoutSecApplied !== undefined ? { timeoutSec: entry.timeoutSecApplied } : {}) }
                : {}),
            bytesFromStart: entry.stdout.totalBytes + entry.stderr.totalBytes,
        });
    }
    async killBackground(shellId) {
        const entry = this.bgShells.get(shellId);
        if (!entry) {
            return err(new BackgroundShellError("not_found", `Unknown background shell: ${shellId}`));
        }
        if (entry.status === "running" && entry.child.pid) {
            entry.status = "killed";
            if (entry.timer)
                clearTimeout(entry.timer);
            shutdownDebug("killBackground", { shellId, pid: entry.child.pid });
            killProcessTree(entry.child.pid, { force: true });
        }
        return ok(undefined);
    }
    killBackgroundNow(shellId) {
        const entry = this.bgShells.get(shellId);
        if (!entry || entry.hardKilled)
            return "already_gone";
        const child = entry.child;
        if (child.exitCode !== null || child.signalCode !== null)
            return "already_gone";
        const pid = child.pid;
        if (pid === undefined || pid <= 0)
            return "no_pgid";
        if (process.platform === "win32")
            return "no_pgid";
        shutdownDebug("killBackgroundNow", { shellId, pid });
        try {
            process.kill(-pid, "SIGKILL");
        }
        catch (e) {
            return e.code === "ESRCH" ? "already_gone" : "no_pgid";
        }
        entry.hardKilled = true;
        if (entry.timer)
            clearTimeout(entry.timer);
        if (entry.status === "running")
            entry.status = "killed";
        return "killed";
    }
    syncSpool(entry) {
        const spool = entry.spool;
        if (!spool)
            return;
        const streams = [
            [entry.stdout, spool.outPath, "out"],
            [entry.stderr, spool.errPath, "err"],
        ];
        for (const [stream, path, lane] of streams) {
            try {
                const size = statSync(path).size;
                if (spool.ephemeral) {
                    const behind = size - spool.fileCursor[lane];
                    if (behind > EXEC_SPOOL_ROTATE_BYTES) {
                        const skipped = behind - EXEC_SPOOL_ROTATE_BYTES;
                        stream.tail.recordSkippedBytes(skipped);
                        stream.totalBytes += skipped;
                        spool.fileCursor[lane] += skipped;
                    }
                }
                if (size > spool.fileCursor[lane]) {
                    const fd = openSync(path, "r");
                    try {
                        const want = Math.min(size - spool.fileCursor[lane], 8 * 1024 * 1024 + 4096);
                        const buf = Buffer.alloc(want);
                        const got = readSync(fd, buf, 0, want, spool.fileCursor[lane]);
                        if (got > 0) {
                            stream.tail.push(buf.subarray(0, got));
                            stream.totalBytes += got;
                            stream.acceptedBytes += got;
                            spool.fileCursor[lane] += got;
                        }
                    }
                    finally {
                        closeSync(fd);
                    }
                }
                if (spool.ephemeral && spool.fileCursor[lane] >= EXEC_SPOOL_ROTATE_BYTES) {
                    const d = decideSpoolReclaim({
                        size: statSync(path).size,
                        cursor: spool.fileCursor[lane],
                        writerLive: entry.status === "running" || (entry.child.exitCode === null && entry.child.signalCode === null),
                    });
                    if (d.reclaim) {
                        if (d.skippedBytes > 0) {
                            stream.tail.recordSkippedBytes(d.skippedBytes);
                            stream.totalBytes += d.skippedBytes;
                        }
                        truncateSync(path, 0);
                        spool.fileCursor[lane] = 0;
                    }
                }
            }
            catch {
            }
        }
    }
    mintSpoolPair(name) {
        this.bgSpoolDir ??= mkdtempSync(join(tmpdir(), "sema-bg-"));
        try {
            const pair = openSpoolPair(join(this.bgSpoolDir, name));
            this.spoolPairs.add(pair.outPath);
            return pair;
        }
        catch (error) {
            this.reapSpoolDirIfIdle();
            throw error;
        }
    }
    releaseSpoolPair(pair) {
        for (const path of [pair.outPath, pair.errPath]) {
            try {
                unlinkSync(path);
            }
            catch {
            }
        }
        this.spoolPairs.delete(pair.outPath);
        this.reapSpoolDirIfIdle();
    }
    reapSpoolDirIfIdle() {
        const dir = this.bgSpoolDir;
        if (dir === undefined || this.spoolPairs.size > 0)
            return;
        this.bgSpoolDir = undefined;
        try {
            rmSync(dir, { recursive: true, force: true });
        }
        catch {
        }
    }
    reclaimEphemeralSpool(entry) {
        if (entry.spoolPump !== undefined) {
            clearInterval(entry.spoolPump);
            entry.spoolPump = undefined;
        }
        const spool = entry.spool;
        if (!spool || (!spool.ephemeral && entry.child.pid !== undefined))
            return;
        this.syncSpool(entry);
        entry.spool = undefined;
        this.releaseSpoolPair(spool);
    }
    async disposeBackgroundShells(opts) {
        if (this.retainBackgroundProcesses)
            return;
        const keep = opts?.except !== undefined && opts.except.length > 0 ? new Set(opts.except) : undefined;
        shutdownDebug("disposeBackgroundShells", { entries: this.bgShells.size, except: opts?.except?.length ?? 0 });
        for (const [id, entry] of this.bgShells) {
            if (keep?.has(id))
                continue;
            try {
                if (entry.timer)
                    clearTimeout(entry.timer);
                shutdownDebug("dispose entry", { id, status: entry.status, pid: entry.child.pid, action: entry.status === "running" ? "group-kill" : "spare" });
                if (entry.status === "running" && entry.child.pid) {
                    entry.status = "killed";
                    killProcessTree(entry.child.pid, { force: true });
                }
                this.reclaimEphemeralSpool(entry);
            }
            catch {
            }
            if (keep !== undefined)
                this.bgShells.delete(id);
        }
        if (keep === undefined)
            this.bgShells.clear();
    }
    async cleanup() {
        await this.disposeBackgroundShells();
    }
}