@sema-agent/core
Version:
Stateless, task-oriented AI agent core
170 lines (169 loc) • 7.71 kB
JavaScript
import { ANSI_C_ESCAPES, SHELL_LEX_DIALECT, argvOf, lexShell, literalTextOf, segmentsAroundStop } from "../../shell/lex.js";
import { readProgramPosition } from "./bash-program-position.js";
import { dropDefinitionHeads } from "./shell-read-bindings.js";
const SOURCE_WORDS = new Set([".", "source"]);
const SPLICE_DEPTH_MAX = 4;
function sameFileSpelling(a, b) {
const strip = (s) => s.replace(/^(?:\.\/)+/, "");
return a.length > 0 && b.length > 0 && strip(a) === strip(b);
}
const PRINTF_ESCAPES = Object.fromEntries(["n", "t", "\\", '"', "a", "b", "f", "r", "v", "e", "E"].map((k) => [k, ANSI_C_ESCAPES[k]]));
function printfFormatText(format) {
const escapes = PRINTF_ESCAPES;
let out = "";
for (let i = 0; i < format.length; i++) {
const ch = format[i];
if (ch === "%") {
if (format[i + 1] === "%") {
out += "%";
i++;
continue;
}
return undefined;
}
if (ch === "\\") {
const e = format[i + 1];
if (e === undefined || !(e in escapes))
return undefined;
out += escapes[e];
i++;
continue;
}
out += ch;
}
return out;
}
function hereDocumentText(h) {
if (h.body.split("\n").some((line) => line.startsWith("\t")))
return undefined;
if (!h.quoted && /[$`\\]/.test(h.body))
return undefined;
return h.body.length === 0 ? "" : `${h.body}\n`;
}
function writtenLiteralOf(segment) {
const redirects = segment.tokens.filter((t) => t.kind === "redirect");
const heredocs = segment.tokens.filter((t) => t.kind === "heredoc");
if (redirects.length !== 1 || heredocs.length > 1 || segment.tokens.some((t) => t.kind === "group"))
return undefined;
const r = redirects[0];
if (r.kind !== "redirect" || r.op !== ">" || (r.fd ?? 1) !== 1 || r.target === undefined)
return undefined;
const file = literalTextOf(r.target.pieces);
if (file === undefined)
return undefined;
const argv = argvOf(segment);
const pos = readProgramPosition(argv);
if (pos.program === undefined || pos.refusal !== undefined || pos.launchers.length > 0 || pos.assignments.length > 0 || pos.controlWords.length > 0)
return undefined;
const words = argv.slice(pos.program.index + 1).map((w) => literalTextOf(w.pieces));
if (words.some((w) => w === undefined))
return undefined;
const literal = words;
const heredoc = heredocs[0];
if (pos.program.basename === "cat") {
if (heredoc === undefined || literal.length !== 0 || (heredoc.fd ?? 0) !== 0 || heredoc.allocated === true)
return undefined;
const text = hereDocumentText(heredoc);
return text === undefined ? undefined : { file, text };
}
if (heredoc !== undefined)
return undefined;
if (pos.program.basename === "printf") {
if (literal.length !== 1)
return undefined;
const text = printfFormatText(literal[0]);
return text === undefined ? undefined : { file, text };
}
if (pos.program.basename === "echo") {
let noNewline = false;
let k = 0;
for (; k < literal.length && /^-[neE]+$/.test(literal[k]); k++) {
if (literal[k].includes("e"))
return undefined;
if (literal[k].includes("n"))
noNewline = true;
}
const rest = literal.slice(k);
if (rest.some((w) => w.includes("\\")))
return undefined;
return { file, text: rest.join(" ") + (noNewline ? "" : "\n") };
}
return undefined;
}
function sourcedFileOf(argv) {
const pos = readProgramPosition(argv);
if (pos.program === undefined || !SOURCE_WORDS.has(pos.program.basename) || pos.refusal !== undefined || pos.launchers.length > 0 || pos.assignments.length > 0)
return undefined;
const rest = argv.slice(pos.program.index + 1);
const at = rest.findIndex((w) => !w.folded.startsWith("-") || w.folded === "-");
if (at < 0 || rest.length !== at + 1)
return undefined;
return literalTextOf(rest[at].pieces);
}
function leavesFileBe(s, next, file, readers, defined) {
if (s.spliced === true || s.sourced === true || s.connector === "|" || next.connector === "|" || next.connector === "&")
return false;
if (s.tokens.some((t) => t.kind !== "word") || s.substitutions.length > 0)
return false;
const argv = argvOf(s);
const pos = readProgramPosition(argv);
if (pos.program === undefined || pos.refusal !== undefined || pos.launchers.length > 0 || pos.assignments.length > 0 || pos.controlWords.length > 0)
return false;
if (pos.program.name !== pos.program.basename || !readers.has(pos.program.basename) || defined.has(pos.program.basename))
return false;
const name = file.replace(/^.*\//, "");
return argv.every((w) => { const text = literalTextOf(w.pieces); return text !== undefined && w.expansions.length === 0 && !text.endsWith(name); });
}
export function inlineSourcedLiterals(lexed, readers = new Set()) {
let segments = lexed.segments;
const defined = new Set(segments.flatMap((s) => dropDefinitionHeads([...s.tokens]).flat()));
for (let depth = 0; depth < SPLICE_DEPTH_MAX; depth++) {
let spliced = false;
const out = [];
for (let si = 0; si < segments.length; si++) {
const segment = segments[si];
if (segment.stopHead === true) {
out.push(segment);
continue;
}
const file = sourcedFileOf(argvOf(segment));
if (file === undefined || segment.connector === "|" || segment.sourced === true || segment.tokens.some((t) => t.kind !== "word")) {
out.push(segment);
continue;
}
let back = out.length - 1;
const between = [];
for (;;) {
while (back >= 0 && out[back].stopHead === true)
back--;
const s = out[back];
if (s === undefined || !leavesFileBe(s, out[back + 1] ?? segment, file, readers, defined))
break;
between.push(s);
back--;
}
const prev = out[back];
const written = prev === undefined || prev.connector === "|" ? undefined : writtenLiteralOf(prev);
const after = [...between.map((s) => s.connector), segment.connector];
const conditional = prev !== undefined && (prev.connector === "||" || after.includes("||") || (prev.connector === "&&" && after.some((c) => c !== "&&")));
const text = written !== undefined && !conditional && sameFileSpelling(written.file, file) ? written.text : undefined;
if (text === undefined) {
out.push(segment);
continue;
}
const inner = lexShell(SHELL_LEX_DIALECT, text);
const read = "parseFailure" in inner ? segmentsAroundStop(text, inner) : inner.segments;
if (read.length === 0) {
out.push(segment);
continue;
}
read.forEach((s, k) => out.push(k === 0 ? { ...s, connector: segment.connector, spliced: true } : { ...s, spliced: true }));
out.push({ ...segment, connector: ";", spliced: true, sourced: true });
spliced = true;
}
segments = out;
if (!spliced)
break;
}
return segments === lexed.segments ? lexed : { segments, substitutions: segments.flatMap((s) => s.substitutions) };
}