@sema-agent/core
Version:
Stateless, task-oriented AI agent core
462 lines (461 loc) • 21.1 kB
JavaScript
import { arithmeticTextIsPlain, arithmeticTextRunsOf, heredocRunsOf, SHELL_LEX_DIALECT, lexShell, namesRedirectDescriptor, PARSE_FAILURE_SENTENCE, segmentsPastStop, wordRunsOf, } from "../shell/lex.js";
import { shellWordsOf } from "../shell/shell-words.js";
import { isLauncherAssignmentOperand } from "../tools/fs/bash-program-position.js";
import { extglobOpenerIn } from "../tools/fs/bash-readonly-classifier.js";
import { evaluatesOperand, SHELL_WRAPPER_TABLE } from "./shell-wrapper-table.js";
export { SHELL_WRAPPER_TABLE } from "./shell-wrapper-table.js";
const WRAPPERS = new Map(Object.entries(SHELL_WRAPPER_TABLE));
const PREFIX_KEYWORDS = shellWordsOf("stripped_prefix");
const CLOSING_KEYWORDS = shellWordsOf("stripped_standalone");
const OPAQUE_KEYWORDS = shellWordsOf("opaque");
const CONTROL_PREFIXES = shellWordsOf("control_prefix");
export const DURATION_RE = /^\d+(?:\.\d+)?[smhd]?$/;
export const MAX_SHELL_READ_CHARS = 10_000;
const PAST_THE_LIMIT = `the command is longer than ${MAX_SHELL_READ_CHARS} characters — what follows them is not read`;
const LEADING_SPACE = /^\s*/;
const LEXED_WORDS = new WeakMap();
export function lexedWordOf(w) {
return LEXED_WORDS.get(w);
}
function wordOf(w) {
let expands = false;
const widen = (to) => { if (expands !== "many")
expands = to; };
let text = "";
for (const p of w.pieces) {
const e = p.expansion;
if (p.quotedBy === "$'" || (e === undefined && p.literal === undefined)) {
widen("many");
continue;
}
if (e === undefined) {
text += p.literal ?? "";
continue;
}
if (e.kind === "tilde") {
if (p === w.pieces[0])
widen(e.yields);
text += e.body ?? "";
}
else if (e.kind === "brace") {
widen("many");
text += `{${e.body ?? ""}}`;
}
else {
widen(e.yields);
text += e.pattern?.folded ?? "";
}
}
const out = { text, raw: w.raw, expands };
LEXED_WORDS.set(out, w);
return out;
}
const literalIn = (w, set) => w !== undefined && w.expands === false && set.has(w.text);
const bareAssignment = (w) => lexedWordOf(w)?.assignment?.bare === true;
const runsOf = wordRunsOf;
const emptyPiece = () => ({ words: [], redirections: [], lines: [] });
export const MAX_SUBSTITUTION_DEPTH = 16;
const CASE_ARM_UNREAD = "a `case` arm terminator outside a `case` this lane reads";
const EXTGLOB_UNREAD = "an extended pattern (`?(…)` `*(…)` `+(…)` `@(…)` `!(…)`) is one this reader does not expand";
export function readShellCommand(source) { return readShellCommandIn(SHELL_LEX_DIALECT, source); }
export function readShellCommandIn(shell, source) { return readShellCommandAt(shell, source, 0); }
function readShellCommandAt(shell, source, depth) {
const limit = (LEADING_SPACE.exec(source)?.[0].length ?? 0) + MAX_SHELL_READ_CHARS;
const text = source.length > limit ? source.slice(0, limit) : source;
const lexed = lexShell(shell, text);
const failed = "parseFailure" in lexed ? lexed : undefined;
const stopped = text !== source ? PAST_THE_LIMIT : failed !== undefined ? PARSE_FAILURE_SENTENCE[failed.parseFailure.reason] : undefined;
const read = "parseFailure" in lexed ? [...lexed.readBefore, ...segmentsPastStop(text, lexed)] : lexed.segments;
const segments = [];
const connectors = [];
let grouped = false;
let backgrounded = false;
let strayRedirection = false;
let seg = emptyPiece();
let afterBoundary = true;
let lastConnector;
let arithmetic;
const dropCutWord = () => {
const last = text !== source ? seg.words[seg.words.length - 1] : undefined;
const end = last === undefined ? undefined : lexedWordOf(last)?.pieces.at(-1)?.span[1];
if (end !== undefined && /^(?:["'`]|\\\n)*$/.test(text.slice(end))) {
seg.words.pop();
seg.stopped ??= PAST_THE_LIMIT;
}
};
const finishSegment = (connector) => {
dropCutWord();
let built = buildSegment(shell, seg, depth);
if (built === "keyworded")
grouped = true;
if ((built === "empty" || built === "keyworded") && seg.redirections.length > 0)
strayRedirection = true;
if (built === "empty" || built === "keyworded") {
const continuation = connector === "\n" && lastConnector !== undefined && lastConnector !== ";" && lastConnector !== "&" && lastConnector !== "\n";
const legal = built === "keyworded" || afterBoundary || connector === undefined || connector === "\n" || lastConnector === "\n";
if (!legal)
built = { argv: [], redirections: seg.redirections, peeled: [], unreadable: `an empty command before \`${connector}\` — a syntax error` };
else {
if (connector !== undefined && connector !== "\n" && segments.length > 0)
grouped = true;
if (connector !== undefined && !continuation)
lastConnector = connector;
seg = emptyPiece();
afterBoundary = false;
return;
}
}
if (segments.length > 0)
connectors.push(lastConnector ?? "\n");
segments.push(built);
if (connector !== undefined)
lastConnector = connector;
seg = emptyPiece();
afterBoundary = false;
};
const boundary = () => { finishSegment(undefined); grouped = true; afterBoundary = true; lastConnector = undefined; };
const carry = (r) => { if (r.hidden)
seg.hiddenRun = true; seg.lines.push(...r.lines); };
const word = (w) => { carry(runsOf(w)); return wordOf(w); };
const readTokens = (s) => {
const tokens = s.tokens;
const shown = tokens.flatMap((t) => (t.kind === "word" ? t.expansions : t.kind === "redirect" ? t.target?.expansions ?? [] : [])).filter((p) => p.expansion?.kind === "command" || p.expansion?.kind === "process" || p.expansion?.kind === "arithmetic").length;
if (s.substitutions.length > shown)
seg.hiddenRun = true;
let definitionClose = false;
tokens.forEach((t, i) => {
if (arithmetic !== undefined) {
if (t.kind === "group") {
arithmetic.depth += t.op === "(" ? 1 : -1;
if (arithmetic.depth === 0)
arithmetic = undefined;
return;
}
const w = t.kind === "word" ? t : t.kind === "redirect" ? t.target : undefined;
if (w !== undefined) {
carry(runsOf(w));
carry(arithmeticTextRunsOf(w.raw));
}
if (w === undefined || !arithmeticTextIsPlain(w.raw) || t.kind === "heredoc")
seg.hiddenRun = true;
if (t.kind === "redirect" && t.dup !== undefined && !arithmeticTextIsPlain(t.dup))
seg.hiddenRun = true;
return;
}
if (t.kind === "word") {
if (!namesRedirectDescriptor(tokens[i + 1]))
seg.words.push(word(t));
return;
}
if (t.kind === "redirect") {
const target = t.target !== undefined ? word(t.target) : { text: t.dup ?? "", raw: t.dup ?? "", expands: false };
seg.redirections.push({ op: t.op, target });
return;
}
if (t.kind === "heredoc") {
seg.redirections.push({ op: "<<", target: { text: t.delimiter, raw: t.delimiter, expands: false } });
if (!t.quoted)
carry(heredocRunsOf(t.body));
return;
}
const next = tokens[i + 1];
if (definitionClose) {
definitionClose = false;
return;
}
if (t.op === "(" && next?.kind === "group" && next.op === "(" && seg.redirections.length === 0 && seg.words.every((w) => literalIn(w, CONTROL_PREFIXES) || literalIn(w, CLOSING_KEYWORDS) || (w.expands === false && w.text === "-p"))) {
arithmetic = { depth: 1 };
return;
}
if (t.op === "(" && next?.kind === "group" && next.op === ")" && seg.words.length === 1 && seg.words[0].expands === false && seg.redirections.length === 0) {
seg.words.pop();
definitionClose = true;
}
boundary();
});
};
for (let k = 0; k < read.length; k++) {
const s = read[k];
if (k > 0 && k === failed?.readBefore.length) {
seg.stopped = PARSE_FAILURE_SENTENCE[failed.parseFailure.reason];
arithmetic = undefined;
finishSegment("\n");
readTokens(s);
continue;
}
if (k > 0) {
const armEnd = caseArmEnd(read, k);
if (armEnd !== undefined) {
seg.unreadable ??= CASE_ARM_UNREAD;
k = armEnd;
readTokens(read[k]);
continue;
}
const connector = s.pipesStderr === true ? "|&" : s.connector;
if (arithmetic !== undefined) {
if (connector === ";")
seg.hiddenRun = true;
}
else {
if (connector === "&")
backgrounded = true;
finishSegment(connector);
}
}
readTokens(s);
}
if (stopped !== undefined) {
if (text !== source || read.length === failed.readBefore.length)
seg.stopped = stopped;
}
else if (arithmetic !== undefined) {
seg.unreadable ??= "an unterminated arithmetic command";
}
else {
const dangling = seg.words.length === 0 && seg.redirections.length === 0 && lastConnector !== undefined && lastConnector !== ";" && lastConnector !== "&" && lastConnector !== "\n";
if (dangling)
seg.unreadable ??= `the connector \`${lastConnector}\` has no command after it — a syntax error`;
}
finishSegment(undefined);
const stop = stopped !== undefined ? { stopped } : {};
if (failed === undefined && "segments" in lexed && extglobOpenerIn(lexed, text))
return { segments: segments.map((s) => (s.unreadable !== undefined ? s : { ...s, peelUnreadable: s.peelUnreadable ?? EXTGLOB_UNREAD })), connectors, grouped, backgrounded, strayRedirection, ...stop };
return { segments, connectors, grouped, backgrounded, strayRedirection, ...stop };
}
function caseArmEnd(read, k) {
const arm = (j) => read[j].connector === ";" && read[j].text === "" && read[j].tokens.length === 0;
const next = read[k + 1];
if (!arm(k) || next === undefined || (next.connector !== ";" && next.connector !== "&"))
return undefined;
const third = read[k + 2];
return next.connector === ";" && arm(k + 1) && third?.connector === "&" ? k + 2 : k + 1;
}
const SUBSTITUTION_UNREAD = "a command substitution runs a program this reader does not read";
const MAX_WRAPPER_LAYERS = 8;
export function isFullyReadable(shape) {
return shape.segments.every((s) => s.unreadable === undefined && s.peelUnreadable === undefined && (s.argv.length === 0 || [s.argv, ...s.peeled].every((argv) => argv[0]?.expands === false)) && (s.substituted ?? []).every(isFullyReadable));
}
const operandsOf = (run) => run.map((w) => ({ text: w.text, raw: w.raw, assignment: lexedWordOf(w)?.assignment }));
function substitutedOf(shell, seg, depth) {
if (seg.lines.length === 0)
return [];
if (depth + 1 > MAX_SUBSTITUTION_DEPTH)
return undefined;
return [...new Set(seg.lines)].map((line) => readShellCommandAt(shell, line, depth + 1));
}
function buildSegment(shell, seg, depth) {
const built = buildRuns(shell, seg, depth);
if (seg.stopped === undefined || (typeof built !== "string" && built.unreadable !== undefined))
return built;
if (typeof built === "string")
return { argv: seg.words, redirections: seg.redirections, peeled: [], unreadable: seg.stopped };
const unread = { text: "", raw: "<text the reader did not read>", expands: "many" };
const tailed = (run) => (run.length === 0 ? run : [...run, unread]);
return { ...built, argv: tailed(built.argv), peeled: built.peeled.map(tailed), peelUnreadable: seg.stopped };
}
function buildRuns(shell, seg, depth) {
if (seg.unreadable !== undefined)
return { argv: seg.words, redirections: seg.redirections, peeled: [], unreadable: seg.unreadable };
const read = substitutedOf(shell, seg, depth);
if (read === undefined)
seg.hiddenRun = true;
const substituted = read !== undefined && read.length > 0 ? { substituted: read } : {};
const carried = () => seg.hiddenRun === true ? { argv: [], redirections: seg.redirections, peeled: [], peelUnreadable: SUBSTITUTION_UNREAD, ...substituted }
: "substituted" in substituted ? { argv: [], redirections: seg.redirections, peeled: [], ...substituted }
: keyworded ? "keyworded" : "empty";
let keyworded = false;
let k0 = 0;
while (k0 < seg.words.length && (literalIn(seg.words[k0], PREFIX_KEYWORDS) || literalIn(seg.words[k0], CLOSING_KEYWORDS))) {
k0++;
keyworded = true;
}
const words = k0 === 0 ? seg.words : seg.words.slice(k0);
const head = words[0];
if (head === undefined)
return carried();
if (evaluatesOperand(operandsOf(words)))
seg.hiddenRun = true;
if (head.expands === false && (head.text === "[[" || head.text === "["))
return carried();
if (literalIn(head, OPAQUE_KEYWORDS))
return { argv: words, redirections: seg.redirections, peeled: [], unreadable: `a \`${head.text}\` control structure — its commands need a syntax tree` };
const argv = words;
const peeled = [];
let peelUnreadable;
let k = 0;
while (k < argv.length && bareAssignment(argv[k]))
k++;
let run = argv.slice(k);
if (k > 0 && run.length > 0)
peeled.push(run);
for (let layer = 0; run.length > 0; layer++) {
let j = 0;
while (j < run.length && ((run[j].text === "!" && run[j].expands === false) || bareAssignment(run[j])))
j++;
if (j > 0) {
run = run.slice(j);
if (run.length === 0)
break;
peeled.push(run);
}
if (run[0].expands !== false) {
peelUnreadable = "the program name is an expansion";
break;
}
if (layer >= MAX_WRAPPER_LAYERS) {
peelUnreadable = `more than ${MAX_WRAPPER_LAYERS} wrapper layers`;
break;
}
const next = unwrap(run);
if (typeof next === "string") {
peelUnreadable = next;
break;
}
if (next === run)
break;
run = next;
peeled.push(run);
}
if (seg.hiddenRun === true || [argv, ...peeled].some((c) => c[0]?.expands === false && evaluatesOperand(operandsOf(c))))
peelUnreadable ??= SUBSTITUTION_UNREAD;
return { argv, redirections: seg.redirections, peeled, ...(peelUnreadable !== undefined ? { peelUnreadable } : {}), ...substituted };
}
function unwrap(words) {
const head = words[0];
const name = head.text.slice(head.text.lastIndexOf("/") + 1);
const row = WRAPPERS.get(name);
if (row === undefined)
return words;
if (row.viaShell === true)
return `\`${name}\` evaluates its operands as shell input this reader does not read`;
if (row.executes !== undefined) {
const hit = words.slice(1).find((w) => w.expands !== false || row.executes.some((x) => w.text === x || (x.length === 2 && /^-[^-]/.test(w.text) && w.text.includes(x[1]))));
return hit === undefined ? words : hit.expands !== false ? `an expansion where \`${name}\` reads its arguments` : `\`${name} ${hit.text}\` runs a command this reader does not read`;
}
const valueFlags = new Set(row.valueFlags);
const flags = new Set(row.flags);
const attached = new Set(row.attached ?? []);
const commandString = new Set(row.commandString);
const assignmentOperand = (w) => row.assignments === true && w.expands === false && isLauncherAssignmentOperand(w.text);
let positionalTaken = row.positional === undefined;
let durationTaken = row.duration !== true;
let replaceToken;
let i = 1;
const unknown = (t) => `the \`${name}\` option ${t} is not one this reader knows`;
const takeValue = (flag) => {
const value = words[i + 1];
if (name === "xargs" && flag === "-I" && value !== undefined) {
replaceToken = value.text;
if (value.expands !== false)
return false;
}
i += value === undefined ? 1 : 2;
return value === undefined || value.expands !== "many";
};
const operand = (w) => {
if (w.expands !== false)
return `an expansion where \`${name}\` reads its operands`;
if (!durationTaken) {
durationTaken = true;
return DURATION_RE.test(w.text) ? true : `the \`${name}\` duration "${w.text}" cannot be read`;
}
if (!positionalTaken) {
positionalTaken = true;
return row.positional.test(w.text) ? true : `the \`${name}\` operand "${w.text}" cannot be read`;
}
return false;
};
while (i < words.length) {
const w = words[i];
if (w.expands !== false)
return `an expansion where \`${name}\` reads its options`;
const t = w.text;
if (t === "--") {
i++;
while (i < words.length && (!durationTaken || !positionalTaken)) {
const r = operand(words[i]);
if (r !== true)
return r;
i++;
}
while (i < words.length && assignmentOperand(words[i]))
i++;
break;
}
if (t === "-" && row.bareDash === true) {
i++;
continue;
}
if (name === "nice" && /^-\d+$/.test(t)) {
i++;
continue;
}
if (t.startsWith("-") && t !== "-") {
if (name === "command" && /^-[pvV]+$/.test(t) && /[vV]/.test(t))
return words;
if (t.startsWith("--")) {
const eq = t.indexOf("=");
const flag = eq > 0 ? t.slice(0, eq) : t;
if (commandString.has(flag))
return `\`${name} ${flag}\` takes its command as one string`;
if (eq < 0 && valueFlags.has(flag)) {
if (!takeValue(flag))
return `an expansion where \`${name}\` reads its options`;
continue;
}
if (!flags.has(flag) && !(eq > 0 && valueFlags.has(flag)))
return unknown(flag);
if (name === "xargs" && flag === "--replace")
replaceToken = eq > 0 ? t.slice(eq + 1) : "{}";
i++;
continue;
}
let k = 1;
for (; k < t.length; k++) {
const letter = `-${t[k]}`;
if (commandString.has(letter))
return `\`${name} ${letter}\` takes its command as one string`;
if (valueFlags.has(letter)) {
if (name === "xargs" && letter === "-I" && k < t.length - 1)
replaceToken = t.slice(k + 1);
break;
}
if (attached.has(letter)) {
if (name === "xargs" && letter === "-i")
replaceToken = t.length > k + 1 ? t.slice(k + 1) : "{}";
k = t.length;
break;
}
if (!flags.has(letter))
return unknown(letter);
}
if (k === t.length - 1) {
if (!takeValue(`-${t[k]}`))
return `an expansion where \`${name}\` reads its options`;
continue;
}
i++;
continue;
}
if (assignmentOperand(w)) {
i++;
continue;
}
const r = operand(w);
if (r === false)
break;
if (r !== true)
return r;
i++;
if (durationTaken && positionalTaken)
break;
}
if (i >= words.length)
return words;
const rest = words.slice(i);
if (name !== "xargs")
return rest;
if (replaceToken === undefined)
return [...rest, { text: "", raw: "<xargs input>", expands: "many" }];
return rest.map((w) => (w.text.includes(replaceToken) || w.raw.includes(replaceToken) ? { ...w, expands: "many" } : w));
}