@sema-agent/core
Version:
Stateless, task-oriented AI agent core
431 lines (430 loc) • 22.5 kB
JavaScript
import { spawn } from "node:child_process";
import { readFile } from "node:fs/promises";
import { errorResult } from "../../core/tools.js";
import { processTableOf } from "../../core/remote-env.js";
import { inheritedHostEnv } from "../../core/secret-env.js";
import { inlineUntrusted } from "../../core/untrusted-text.js";
import { foreignLine } from "../../core/protocol-http-auth.js";
import { planShellReads } from "./shell-read-plan.js";
import { programArgs } from "./shell-read-write-targets.js";
const PROBE_TIMEOUT_MS = 5_000;
const ANCESTOR_HOPS_MAX = 128;
const SHELL_PID_SPELLING = String.raw `\$(?:\$|\{\$\})`;
const SHELL_PID_WORD = new RegExp(`^${SHELL_PID_SPELLING}$`);
const SHELL_PID_EXPANSION = new RegExp(SHELL_PID_SPELLING, "g");
const NAME_SELECTION_KEEPS_ANCESTORS = process.platform === "linux" ? [] : ["-a"];
const OPTIONS_END_AT_FIRST_OPERAND = process.platform !== "linux";
const SIGNAL_ONLY_FIRST_ARGUMENT = process.platform !== "linux";
const HANDLER_SELECTS_BY_SIGNAL = process.platform === "linux";
const LONG_OPTIONS = new Map([
["signal", "signal"], ["ignore-ancestors", "A"], ["require-handler", "H"], ["count", "c"], ["cgroup", "cgroup"], ["delimiter", "d"], ["list-name", "l"],
["list-full", "a"], ["full", "f"], ["pgroup", "g"], ["group", "G"], ["ignore-case", "i"], ["newest", "n"], ["oldest", "o"], ["older", "O"], ["parent", "P"],
["session", "s"], ["terminal", "t"], ["euid", "u"], ["uid", "U"], ["inverse", "v"], ["lightweight", "w"], ["exact", "x"], ["pidfile", "F"], ["logpidfile", "L"],
["echo", "e"], ["ns", "ns"], ["nslist", "nslist"], ["queue", "q"], ["runstates", "r"], ["help", "h"], ["version", "V"],
]);
function longKeyOf(name) {
if (!name.startsWith("--") || name.length < 3)
return undefined;
const word = name.slice(2);
const exact = LONG_OPTIONS.get(word);
if (exact !== undefined)
return exact;
const named = [...LONG_OPTIONS].filter(([o]) => o.startsWith(word));
return named.length === 1 ? named[0][1] : undefined;
}
const QUEUE_PAYLOAD = process.platform === "linux";
const VALUED_LETTERS = new Set(["F", "g", "G", "P", "s", "t", "u", "U", "N", "T", "O", "d", "r", ...(QUEUE_PAYLOAD ? ["q"] : [])]);
const VALUED_LONG_ONLY = new Set(["signal", "cgroup", "ns", "nslist"]);
const OUTPUT_LETTERS = new Set(["c", "e", "d", ...(QUEUE_PAYLOAD ? ["q"] : [])]);
const takesValueKey = (key) => VALUED_LETTERS.has(key) || VALUED_LONG_ONLY.has(key);
const fateOfKey = (key) => (key === "signal" ? "signal" : OUTPUT_LETTERS.has(key) ? "drop" : "ask");
function bundledLetters(w, valued = VALUED_LETTERS) {
if (!/^-[A-Za-z]/.test(w))
return undefined;
const letters = [];
for (const ch of w.slice(1)) {
letters.push(ch);
if (valued.has(ch))
break;
}
return letters;
}
const SIGNAL_NAMES = new Set([
"HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "IOT", "EMT", "FPE", "KILL", "BUS", "SEGV", "SYS", "PIPE", "ALRM", "TERM", "URG", "STOP", "TSTP", "CONT",
"CHLD", "CLD", "TTIN", "TTOU", "IO", "POLL", "XCPU", "XFSZ", "VTALRM", "PROF", "WINCH", "INFO", "USR1", "USR2", "STKFLT", "PWR", "LOST", "UNUSED", "THR", "LIBRT",
]);
const SIGNAL_WORD = /^-(?:\d+|(?:SIG)?(?:RT(?:MIN|MAX)(?:[+-]\d+)?|([A-Z][A-Z0-9]*)))$/i;
const isSignalWord = (w) => {
const m = SIGNAL_WORD.exec(w);
return m !== null && (m[1] === undefined || SIGNAL_NAMES.has(m[1].toUpperCase()));
};
function readSelection(allWords, killer) {
const signalAt = killer !== "pkill" ? -1 : SIGNAL_ONLY_FIRST_ARGUMENT ? (isSignalWord(allWords[0] ?? "") ? 0 : -1) : allWords.findIndex(isSignalWord);
const signalWord = signalAt < 0 ? undefined : allWords[signalAt].slice(1);
const words = signalAt < 0 ? allWords : allWords.filter((_, i) => i !== signalAt);
const out = [];
const parentLists = [];
let ended = false;
let requireHandler = false;
let negated = false;
let signalOption;
let valueOf;
const valueGiven = (key, value) => {
if (key === "P")
parentLists.push(value.split(","));
};
for (const w of words) {
if (valueOf !== undefined) {
if (valueOf.fate === "ask")
out.push(w);
else if (valueOf.fate === "signal")
signalOption = w;
valueGiven(valueOf.key, w);
valueOf = undefined;
continue;
}
if (ended || w === "--") {
ended ||= w === "--";
out.push(w);
continue;
}
const [, longName, longValue] = /^(--[^=]*)(?:=(.*))?$/s.exec(w) ?? [];
const key = longName === undefined ? undefined : longKeyOf(longName);
if (key !== undefined && (takesValueKey(key) || longValue === undefined)) {
if (key === "H")
requireHandler = true;
if (key === "v")
negated = true;
const fate = fateOfKey(key);
if (fate === "ask")
out.push(w);
if (takesValueKey(key) && longValue === undefined)
valueOf = { fate, key };
else if (longValue !== undefined) {
if (fate === "signal")
signalOption = longValue;
valueGiven(key, longValue);
}
continue;
}
const letters = bundledLetters(w);
if (letters === undefined) {
out.push(w);
if (OPTIONS_END_AT_FIRST_OPERAND && (w === "-" || !w.startsWith("-")))
ended = true;
continue;
}
if (letters.includes("H"))
requireHandler = true;
if (letters.includes("v"))
negated = true;
const last = letters[letters.length - 1];
const fate = fateOfKey(last);
const kept = letters.filter((ch) => fateOfKey(ch) === "ask").join("");
const attached = VALUED_LETTERS.has(last) ? w.slice(1 + letters.length) : "";
if (kept !== "")
out.push(`-${kept}${fate === "ask" ? attached : ""}`);
if (VALUED_LETTERS.has(last)) {
if (attached === "")
valueOf = { fate, key: last };
else
valueGiven(last, attached);
}
}
const signal = signalOption ?? signalWord;
return { words: HANDLER_SELECTS_BY_SIGNAL && requireHandler && signal !== undefined ? ["--signal", signal, ...out] : out, parentLists, negated };
}
const LAST_PARENT_LIST_WINS = process.platform === "linux";
function boundedToShellChildren(read, unread) {
if (unread !== undefined)
return false;
const standing = LAST_PARENT_LIST_WINS ? read.parentLists.slice(-1) : read.parentLists;
return standing.length > 0 && standing.every((list) => list.every((pid) => SHELL_PID_WORD.test(pid)));
}
const literalName = (name) => name.replace(/[\\.[\]{}()*+?^$|]/g, "\\$&");
function wordsOf(segment) {
const args = programArgs(segment);
const expands = (a) => `\`${inlineUntrusted(a.raw, 60)}\` is expanded by the shell when the command runs`;
const stream = segment.reentry === "argv" ? "its arguments arrive on a stream" : undefined;
const opaque = args.find((a) => a.rewritten === true && /[$`*?[~{\\]/.test(a.raw.replace(SHELL_PID_EXPANSION, "0")));
const first = args.find((a) => a.rewritten === true);
const unread = stream ?? (opaque === undefined ? undefined : expands(opaque));
const computed = unread ?? (first === undefined ? undefined : expands(first));
return { words: args.map((a) => a.spelled), ...(computed !== undefined ? { computed } : {}), ...(unread !== undefined ? { unread } : {}) };
}
const shown = (segment) => inlineUntrusted(segment.text, 200);
function readPkill(segment) {
const { words, computed, unread } = wordsOf(segment);
const read = readSelection(words, "pkill");
if (boundedToShellChildren(read, unread)) {
return read.negated ? { text: shown(segment), probes: [], computed: "the selection is negated (`-v` / `--inverse`), so `-P` of the shell's pid no longer limits it to the shell's children" } : undefined;
}
if (computed !== undefined)
return { text: shown(segment), probes: [], computed };
return read.words.length === 0 ? undefined : { text: shown(segment), probes: [read.words] };
}
const OPT_FLAG = { does: "flag" };
const OPT_FILTER = { does: "filter" };
const OPT_VALUED = { does: "valued" };
const OPT_CONTEXT = { does: "context" };
const OPT_REGEX = { does: "regex" };
const OPT_GROUP = { does: "group" };
const OPT_USER = { does: "select", pgrep: "-u" };
const OPT_TTY = { does: "select", pgrep: "-t" };
const KILLALL_OPTIONS = new Map([
["-u", OPT_USER], ["--user", OPT_USER], ["-t", OPT_TTY],
["-Z", OPT_CONTEXT], ["--context", OPT_CONTEXT],
["-r", OPT_REGEX], ["-m", OPT_REGEX], ["--regexp", OPT_REGEX],
["-I", { does: "ignoreCase" }], ["--ignore-case", { does: "ignoreCase" }],
["-g", OPT_GROUP], ["--process-group", OPT_GROUP],
["-s", OPT_VALUED], ["--signal", OPT_VALUED], ["-o", OPT_VALUED], ["--older-than", OPT_VALUED], ["-y", OPT_VALUED], ["--younger-than", OPT_VALUED],
["-n", OPT_VALUED], ["--ns", OPT_VALUED], ["-c", OPT_FILTER],
["-e", OPT_FLAG], ["--exact", OPT_FLAG], ["-i", OPT_FLAG], ["--interactive", OPT_FLAG], ["-l", OPT_FLAG], ["--list", OPT_FLAG], ["-q", OPT_FLAG], ["--quiet", OPT_FLAG],
["-v", OPT_FLAG], ["--verbose", OPT_FLAG], ["-V", OPT_FLAG], ["--version", OPT_FLAG], ["-w", OPT_FLAG], ["--wait", OPT_FLAG], ["-d", OPT_FLAG], ["-z", OPT_FLAG], ["--help", OPT_FLAG],
]);
const takesValue = (opt) => opt !== undefined && (opt.does === "select" || opt.does === "context" || opt.does === "filter" || opt.does === "valued");
const KILLALL_VALUED_LETTERS = new Set([...KILLALL_OPTIONS].filter(([spelling, opt]) => !spelling.startsWith("--") && takesValue(opt)).map(([spelling]) => spelling.slice(1)));
function optionsOf(w) {
if (w.startsWith("--")) {
const eq = w.indexOf("=");
return [eq < 0 ? { opt: w } : { opt: w.slice(0, eq), attached: w.slice(eq + 1) }];
}
const letters = bundledLetters(w, KILLALL_VALUED_LETTERS);
if (letters === undefined)
return [{ opt: w }];
const rest = w.slice(1 + letters.length);
return letters.map((ch, i) => ({ opt: `-${ch}`, ...(i === letters.length - 1 && rest !== "" ? { attached: rest } : {}) }));
}
function readKillallWords(words) {
const names = [];
const selecting = new Map();
let filter;
let byContext = false;
let regex = false;
let ignoreCase = false;
for (let i = 0; i < words.length; i++) {
const w = words[i];
if (w === "--") {
names.push(...words.slice(i + 1));
break;
}
if (!w.startsWith("-") || w === "-") {
names.push(w);
if (OPTIONS_END_AT_FIRST_OPERAND) {
names.push(...words.slice(i + 1));
break;
}
continue;
}
if (isSignalWord(w))
continue;
for (const { opt: spelling, attached } of optionsOf(w)) {
const opt = KILLALL_OPTIONS.get(spelling);
if (opt === undefined || (attached !== undefined && !takesValue(opt)))
return { unreadable: `\`${inlineUntrusted(w, 60)}\` is not a form of a \`killall\` option this check reads` };
if (opt.does === "group")
return { unreadable: "`-g` signals the whole process group of each match, a set this check cannot list" };
const value = takesValue(opt) ? (attached ?? words[++i]) : undefined;
if (opt.does === "select" && value !== undefined)
selecting.set(opt.pgrep, value);
else if (opt.does === "filter" && value !== undefined)
filter = value;
else if (opt.does === "context")
byContext = true;
else if (opt.does === "regex")
regex = true;
else if (opt.does === "ignoreCase")
ignoreCase = true;
}
}
if (filter !== undefined && !names.includes(filter))
names.push(filter);
if (byContext && names.length === 0 && selecting.size === 0)
return { unreadable: "`-Z` selects by security context, a set this check cannot ask `pgrep` for" };
return { names, selecting: [...selecting].flat(), regex, ignoreCase };
}
function readKillall(segment) {
const read = wordsOf(segment);
if (read.computed !== undefined)
return { text: shown(segment), probes: [], computed: read.computed };
const sel = readKillallWords(read.words);
if ("unreadable" in sel)
return { text: shown(segment), probes: [], computed: sel.unreadable };
const narrow = sel.ignoreCase ? ["-i"] : [];
const pattern = (n) => [...(n.startsWith("-") ? ["--"] : []), sel.regex ? n : literalName(n)];
const probes = sel.names.length > 0 ? sel.names.map((n) => [...NAME_SELECTION_KEEPS_ANCESTORS, ...(sel.regex ? [] : ["-x"]), ...narrow, ...sel.selecting, ...pattern(n)]) : sel.selecting.length === 0 ? [] : [[...NAME_SELECTION_KEEPS_ANCESTORS, ...sel.selecting]];
return { text: shown(segment), probes };
}
function readSelector(segment) {
const read = wordsOf(segment);
if (read.computed !== undefined)
return { text: shown(segment), probes: [], computed: read.computed };
if (segment.verb?.basename === "pidof") {
const names = read.words.filter((w, i) => !w.startsWith("-") && read.words[i - 1] !== "-o");
return { text: shown(segment), probes: names.map((n) => [...NAME_SELECTION_KEEPS_ANCESTORS, "-x", literalName(n)]) };
}
return { text: shown(segment), probes: [readSelection(read.words, "pgrep").words] };
}
const SELECTORS = new Set(["pgrep", "pidof"]);
const EVERY_PROCESS_PID = /^-0*1$/;
function readKill(segment) {
const { words } = wordsOf(segment);
const slot = words[0] === "-s" || words[0] === "-n" ? 2 : words[0]?.startsWith("-") === true && words[0] !== "--" ? 1 : 0;
const rest = words.slice(slot);
const pids = rest[0] === "--" ? rest.slice(1) : rest;
return pids.some((w) => EVERY_PROCESS_PID.test(w)) ? { text: shown(segment), probes: [], everyProcess: true } : undefined;
}
const isFedKill = (s) => s.verb?.basename === "kill" && (s.reentry === "argv" || programArgs(s).some((a) => a.rewritten === true));
const feedsKill = (plan) => plan.segments.some((s) => isFedKill(s) || s.nested.some(feedsKill));
function selectorsIn(plan) {
return plan.segments.flatMap((s) => [...(SELECTORS.has(s.verb?.basename ?? "") ? [s] : []), ...s.nested.flatMap(selectorsIn)]);
}
function readingsOf(plan, seen = new Set()) {
const out = [];
const take = (s, read) => {
if (seen.has(s))
return;
seen.add(s);
const r = read();
if (r !== undefined)
out.push(r);
};
for (const s of plan.segments) {
const program = s.verb?.basename;
if (program === "pkill")
take(s, () => readPkill(s));
else if (program === "killall")
take(s, () => readKillall(s));
else if (program === "kill")
take(s, () => readKill(s));
for (const n of s.nested)
out.push(...readingsOf(n, seen));
}
if (feedsKill(plan))
for (const s of selectorsIn(plan))
take(s, () => readSelector(s));
return out;
}
export function patternKillReadings(shell, command, cwd) {
return readingsOf(planShellReads(shell, command, { readers: new Set(), cwd, roots: [cwd], cdPath: "unknown" }));
}
function runProbe(program, args, signal) {
return new Promise((resolve) => {
let stdout = "";
let stderr = "";
let settled = false;
const settle = (r) => {
if (settled)
return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
resolve(r);
};
const child = spawn(program, [...args], { env: inheritedHostEnv("scrub"), stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
const stop = (why) => {
child.kill("SIGKILL");
settle({ ok: false, why });
};
const timer = setTimeout(() => stop(`${program} did not answer within ${PROBE_TIMEOUT_MS / 1000}s`), PROBE_TIMEOUT_MS);
const onAbort = () => stop("the call was cancelled");
signal?.addEventListener("abort", onAbort, { once: true });
child.stdout.on("data", (c) => { stdout += c.toString("utf8"); });
child.stderr.on("data", (c) => { stderr += c.toString("utf8"); });
child.on("error", (e) => settle({ ok: false, why: e.code === "ENOENT" ? `${program} is not available here` : `${program} could not start (${e.code ?? e.message})` }));
child.on("close", (code) => settle(code === 0 || code === 1 ? { ok: true, stdout, code } : { ok: false, why: `${program} exited ${code ?? "by signal"}${stderr.trim() === "" ? "" : `: ${foreignLine(stderr, 120)}`}` }));
});
}
async function selected(args, signal) {
const run = await runProbe("pgrep", args, signal);
if (!run.ok)
return { why: run.why };
return { pids: run.code === 1 ? [] : run.stdout.split("\n").flatMap((line) => { const m = /^\s*(\d+)\b/.exec(line); return m === null ? [] : [Number(m[1])]; }) };
}
async function selfAndAncestors(signal) {
const chain = [process.pid];
if (process.platform === "linux") {
for (let pid = process.pid; chain.length <= ANCESTOR_HOPS_MAX && pid > 1;) {
let stat;
try {
stat = await readFile(`/proc/${pid}/stat`, "utf8");
}
catch {
return tableAncestors(signal);
}
const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
if (!(parent > 0) || parent === pid)
break;
chain.push(parent);
pid = parent;
}
return { pids: chain };
}
return tableAncestors(signal);
}
async function tableAncestors(signal) {
const run = await runProbe("ps", ["-A", "-o", "pid=", "-o", "ppid="], signal);
if (!run.ok)
return { why: run.why };
const parentOf = new Map();
for (const line of run.stdout.split("\n")) {
const m = /^\s*(\d+)\s+(\d+)\s*$/.exec(line);
if (m !== null)
parentOf.set(Number(m[1]), Number(m[2]));
}
const chain = [process.pid];
for (let pid = parentOf.get(process.pid); pid !== undefined && pid > 0 && !chain.includes(pid) && chain.length <= ANCESTOR_HOPS_MAX; pid = parentOf.get(pid))
chain.push(pid);
return chain.length > 1 ? { pids: chain } : { why: "this process's parent could not be read from the process table" };
}
const WAY_OUT = "or stop the process by its PID, or target your own children with `pkill -P $$ ...`";
const SENTENCE = {
hit: (f) => `Error (Bash): refusing to run \`${f.text}\` — its selection includes ${f.own ? "this agent's own process" : "a process above this agent (the shell or program that started it)"} (PID ${f.pid}), so running it would terminate the session that is running this command. Narrow the pattern (a word that is in your launcher's command line matches the launcher), ${WAY_OUT}.`,
computed: (f) => `Error (Bash): refusing to run \`${f.text}\` — which processes it selects is decided when the command runs (${f.why}), so it cannot first be checked against this agent's own process and the processes above it. Write the pattern into the command as a literal, ${WAY_OUT}.`,
unavailable: (f) => `Error (Bash): refusing to run \`${f.text}\` — the check that its selection holds neither this agent's own process nor a process above it could not run (${f.why}). Stop the process by its PID, or target your own children with \`pkill -P $$ ...\`.`,
};
const UNDECLARED_TABLE = "the execution environment does not declare whether its commands run on this agent's process table — `capabilities.sharesProcessTable` is missing or not a boolean";
async function findingsOnThisTable(readings, signal) {
const found = [];
const asked = await Promise.all(readings.map(async (r) => ({ r, answers: await Promise.all(r.probes.map((p) => selected(p, signal))) })));
let ancestry;
for (const { r, answers } of asked) {
if (r.computed !== undefined)
found.push({ kind: "computed", text: r.text, why: r.computed });
if (r.everyProcess === true)
found.push({ kind: "hit", text: r.text, pid: process.pid, own: true });
for (const a of answers) {
if ("why" in a) {
found.push({ kind: "unavailable", text: r.text, why: a.why });
continue;
}
if (a.pids.length === 0)
continue;
ancestry ??= await selfAndAncestors(signal);
if ("why" in ancestry) {
found.push({ kind: "unavailable", text: r.text, why: ancestry.why });
continue;
}
const pid = ancestry.pids.find((p) => a.pids.includes(p));
if (pid !== undefined)
found.push({ kind: "hit", text: r.text, pid, own: pid === process.pid });
}
}
return found;
}
export async function patternKillRefusal(shell, command, env, cwd, signal) {
if (process.platform === "win32")
return undefined;
const readings = patternKillReadings(shell, command, cwd).filter((r) => r.probes.length > 0 || r.computed !== undefined || r.everyProcess === true);
if (readings.length === 0)
return undefined;
const table = processTableOf(env);
if (table === "other")
return undefined;
const found = table === "this" ? await findingsOnThisTable(readings, signal) : [{ kind: "unavailable", text: readings[0].text, why: UNDECLARED_TABLE }];
const f = found.find((x) => x.kind === "hit") ?? found.find((x) => x.kind === "computed") ?? found[0];
if (f === undefined || signal?.aborted === true)
return undefined;
const text = f.kind === "hit" ? SENTENCE.hit(f) : f.kind === "computed" ? SENTENCE.computed(f) : SENTENCE.unavailable(f);
return errorResult(inlineUntrusted(text, 1_200), { type: "bash_self_kill_refused", code: "bash_self_kill_refused", finding: f.kind, ...(f.kind === "hit" ? { pid: f.pid, relation: f.own ? "engine" : "ancestor" } : {}) });
}