UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

424 lines (423 loc) • 22.2 kB
import { SHELL_LEX_DIALECT, argvOf, descriptorNameWords, expansionsInHeredocBody, lexShell } from "../../shell/lex.js"; import { shellWordsOf } from "../../shell/shell-words.js"; import { resolveOperandSpellings } from "./bash-readonly-classifier.js"; import { readProgramPosition } from "./bash-program-position.js"; import { arithmeticSubstitutions, exportedFunctionNames, isArithmeticCommand, substitutionBodies } from "./shell-read-bindings.js"; import { twinFloor, twinsAfter } from "./shell-read-lost-walk.js"; import { programRow, readArgRoles } from "./program-read-model.js"; import { evalDefinedFunctions, functionCallOf } from "./shell-read-functions.js"; import { codeBodies, literalEvalText, reentersShell, reentryText, stdinTextsOf } from "./shell-reentry-text.js"; import { isAbsoluteForFamily } from "./safety.js"; import { movedTo } from "./shell-climb.js"; import { walkFromStart } from "./shell-read-start.js"; const TEXT_RUNNING_PROGRAMS = new Set(["eval", "source", "."]); const BASE_CANDIDATE_MAX = 256; const tableSays = (name, si, at, ctx) => ctx.textBinds(name, si) || at.table.commandSets.has(name); export class WorkdirThread { candidates; lostAt = false; floors; physical; movedAt = -1; readable; constructor(start, startsPhysical = false) { this.physical = startsPhysical; this.lostAt = start === "unmodelled"; this.readable = start === "unmodelled" || start.every((c) => walkFromStart(typeof c === "string" ? c : c.base) === undefined); this.candidates = start === "unmodelled" ? [] : start.map((c) => (typeof c === "string" ? { base: c, skippedCd: -1, ...(this.readable && isAbsoluteForFamily("own", c) ? { pwd: c } : {}), dirStack: [] } : { ...c, skippedCd: -1 })); } get lost() { return this.lostAt; } get unsettled() { return this.unsettledAt; } unsettledAt = false; get floorBases() { return this.closedFloors.length === 0 && this.mayLead.length === 0 ? this.floors : [...new Set([...(this.floors ?? []), ...this.closedFloors, ...this.mayLead])]; } closedFloors = []; get carriedFloor() { return [...new Set([...(this.floors ?? []), ...this.closedFloors])]; } mayLead = []; reachable(andRunStart) { return this.candidates.filter((c) => c.skippedCd < andRunStart); } end() { return this.lostAt ? "unmodelled" : this.candidates; } where(andRunStart) { if (!this.readable) return { PWD: "unknown", OLDPWD: "unknown", movedAt: this.movedAt }; const reachable = this.lostAt ? [] : this.reachable(andRunStart); const floor = twinFloor(this.lostAt ? this.twins : reachable, andRunStart), withFloor = floor !== undefined ? { floor } : {}; if (this.lostAt) return { PWD: "unknown", OLDPWD: "unknown", movedAt: this.movedAt, ...withFloor }; const values = (pick) => { const out = new Set(); for (const c of reachable) { const v = pick(c); if (v === undefined) return "unknown"; out.add(v); } return [...out].map((spelled) => ({ spelled })); }; return { PWD: values((c) => c.pwd), OLDPWD: values((c) => c.old), movedAt: this.movedAt, ...withFloor }; } twins; setPhysical() { this.physical = true; } get mayBePhysical() { return this.physical; } snapshot() { return { candidates: this.candidates, lost: this.lostAt, floors: this.floors, physical: this.physical, movedAt: this.movedAt, twins: this.twins }; } restore(s) { this.reach(this.lostAt ? (this.floors ?? []) : this.candidates.map((c) => c.base)); if (this.lostAt && this.floors !== undefined) this.closedFloors = [...this.closedFloors, ...this.floors]; this.candidates = s.candidates; this.lostAt = s.lost; this.floors = s.floors; this.physical = s.physical; this.movedAt = s.movedAt; this.twins = s.twins; } scopeReached = new Set(); get reached() { return this.scopeReached; } reach(bases) { this.scopeReached = new Set([...this.scopeReached, ...bases]); } fork(at, floor = []) { const w = new WorkdirThread(at === "lost" ? "unmodelled" : at, this.physical); if (at === "lost") { w.candidates = this.candidates; const floors = [...new Set([...this.carriedFloor, ...floor])]; if (floors.length > 0) w.floors = floors; w.mayLead = this.mayLead; } w.scopeReached = this.scopeReached; w.unsettledAt = this.unsettledAt; w.movedAt = this.movedAt; if (at === "lost") w.twins = this.twins; return w; } widen(places) { if ((this.floorBases ?? []).length > 0) this.closedFloors = [...new Set([...this.closedFloors, ...places])]; } lose(at, reachable, floorTargets = [], unsettled = false, twin = !unsettled) { this.movedAt = Math.max(this.movedAt, at); if (!this.lostAt) this.twins = twin ? reachable : undefined; this.lostAt = true; if (unsettled) this.unsettledAt = true; this.floors ??= [...new Set([...reachable.map((c) => c.base), ...floorTargets, ...this.scopeReached])]; } shift(si, at, ctx) { if (this.lostAt) { this.twins = twinsAfter(this.twins, si, at, (c, twinAt) => this.movedFrom(c, si, twinAt, ctx), BASE_CANDIDATE_MAX); const floors = this.floors ?? []; const before = this.reachable(at.andRunStart).map((c) => c.base); const named = [...new Set([...floors, ...before])]; if (named.length > BASE_CANDIDATE_MAX) this.unsettledAt = true; const from = floors.length === 0 ? [] : named.length > BASE_CANDIDATE_MAX ? [...new Set(before)] : named; const ran = at.shift.kind === "eval" ? ctx.evalEnd(at.shift.text, from.length === 0 ? "unmodelled" : from.map((base) => ({ base, skippedCd: -1 })), at.table, si) : undefined; const led = []; if (from.length > 0) this.floors = [...new Set([...floors, ...(ran === undefined ? floorOf(at.shift, from, ctx, led) : [...ran.reached, ...(ran.end === "unmodelled" ? [] : ran.end.map((c) => c.base))])])]; if (ran === undefined && this.mayLead.length > 0 && this.mayLead.length <= BASE_CANDIDATE_MAX) led.push(...floorOf(at.shift, this.mayLead, ctx, led)); if (led.length > 0) this.mayLead = [...new Set([...this.mayLead, ...led])]; if (movesToUnsettled(at.shift) || ran?.unsettled === true) this.unsettledAt = true; return; } this.movedAt = si; const reachable = this.reachable(at.andRunStart); const s = at.shift; if (s.kind === "lost") return this.lose(si, reachable); if (s.kind === "stack") { this.candidates = this.candidates.map(({ dirStack: _, ...c }) => c); return; } const branched = []; for (const c of this.candidates) { if (c.skippedCd < at.andRunStart) { const moved = this.movedFrom(c, si, at, ctx); if (moved === "lost") { if (movesToUnsettled(s)) this.unsettledAt = true; const led = []; const targets = floorOf(s, reachable.map((r) => r.base), ctx, led); this.mayLead = [...new Set([...this.mayLead, ...led])]; return this.lose(si, reachable, targets); } for (const m of moved) branched.push({ ...m, skippedCd: c.skippedCd }); } branched.push({ ...c, skippedCd: at.provable ? si : c.skippedCd }); } const byKey = new Map(); for (const c of branched) { const key = JSON.stringify([c.base, c.pwd, c.old, c.oldFloor, c.dirStack]); const prior = byKey.get(key); if (prior === undefined || c.skippedCd < prior.skippedCd) byKey.set(key, c); } const next = [...byKey.values()]; if (next.length > BASE_CANDIDATE_MAX) this.lose(si, reachable, [], false, false); else this.candidates = next; } movedFrom(c, si, at, ctx) { const s = at.shift; if (s.kind === "eval") { const ran = ctx.evalEnd(s.text, [c], at.table, si); if (ran.physical) this.physical = true; if (ran.unsettled === true) this.unsettledAt = true; this.reach(ran.reached); return ran.end === "unmodelled" ? "lost" : ran.end.map((e) => (this.physical ? withoutPwd(e) : e)); } const old = !tableSays("PWD", si, at, ctx) ? (c.pwd !== undefined ? { old: c.pwd } : {}) : c.pwd !== undefined && at.table.floorOf("PWD").values.some((v) => v.spelled === c.pwd) ? { oldFloor: c.pwd } : {}; const land = (base, physical, stack) => ({ base, skippedCd: c.skippedCd, ...(physical || this.physical || !this.readable ? {} : { pwd: base }), ...old, ...(stack !== undefined ? { dirStack: stack } : {}) }); if (s.kind === "swap" || s.kind === "pop") { const top = c.dirStack?.[0]; if (top === undefined) return "lost"; return [land(top, false, s.kind === "swap" ? [c.base, ...c.dirStack.slice(1)] : c.dirStack.slice(1))]; } if (s.kind !== "cd") return "lost"; const stack = s.push === true ? (c.dirStack === undefined ? undefined : [c.base, ...c.dirStack]) : c.dirStack; const targets = targetsOf(s.target, c, si, at, ctx); if (targets === "lost") return "lost"; const out = []; for (const t of targets) { if ((s.physical || this.physical || c.pwd === undefined) && t.split("/").includes("..")) return "lost"; const moved = movedTo(c.base, t, ctx.homeDir, typeof s.target !== "string" && t !== c.base && t !== c.pwd && t !== c.old); if (moved === undefined) return "lost"; out.push(land(moved, s.physical, stack)); } return out; } } const withoutPwd = ({ pwd: _, ...c }) => c; function floorOf(s, from, ctx, mayLead) { if (s.kind !== "cd") return []; if (s.target === "home") return ctx.homeDir !== undefined ? [ctx.homeDir] : []; if (typeof s.target === "string") return []; const target = s.target; return [...(target.floorSpelled !== undefined ? [target.floorSpelled] : []), ...(target.expands === false ? from.flatMap((base) => { const at = resolveOperandSpellings(base, target.spelled, ctx.homeDir); if (at?.standIn === true) { mayLead.push(at.spelled ?? at.folded); return []; } return at === undefined ? [] : [at.spelled ?? at.folded]; }) : [])]; } function movesToUnsettled(s) { return s.kind === "cd" && typeof s.target !== "string" && s.target.expands !== false; } function targetsOf(target, c, si, at, ctx) { if (target === "home") return settledValues(at.table.stateOf("HOME")); if (target === "previous") return tableSays("OLDPWD", si, at, ctx) ? settledValues(at.table.stateOf("OLDPWD")) : c.old === undefined ? "lost" : [c.old]; if (target.expands !== false) return "lost"; const dir = target.spelled; if (!searchesCdPath(dir)) return [dir]; if (at.cdable && /^[A-Za-z_][A-Za-z0-9_]*$/.test(dir)) return "lost"; const cdPath = settledValues(at.table.stateOf("CDPATH")); if (cdPath === "lost") return "lost"; const entries = cdPath.flatMap((v) => (v === "" ? [] : v.split(":"))); return [...new Set([...entries.map((e) => (e === "" ? dir : `${e.replace(/\/+$/, "")}/${dir}`)), dir])]; } export function searchesCdPath(dir) { return dir !== "" && !isAbsoluteForFamily("own", dir) && !/^\.\.?(?:\/|$)/.test(dir) && !dir.startsWith("~"); } function settledValues(state) { if (state === "unknown" || state.some((v) => v.glob === true)) return "lost"; return state.map((v) => v.spelled); } export function baseShiftOf(program, args, targetOf) { if (program === "cd") { let physical = false; let at = 0; for (; at < args.length; at++) { const w = args[at].folded; if (w === "--") { at++; break; } if (!w.startsWith("-") || w === "-") break; for (const letter of w.slice(1)) { if (letter === "P") physical = true; else if (letter === "L") physical = false; else if (letter !== "e" && letter !== "@") return { shift: { kind: "lost" }, reported: "unmodelled" }; } } if (at >= args.length) return { shift: { kind: "cd", target: "home", physical }, reported: "home" }; if (args[at].folded === "-") return { shift: { kind: "cd", target: "previous", physical }, reported: "previous" }; const target = targetOf(args[at]); return { shift: { kind: "cd", target, physical }, reported: target }; } if (shellWordsOf("stack_mover").has(program)) { const words = args.map((a) => a.folded); if (words.some((w) => w === "-n")) return { shift: { kind: "stack" }, reported: "unmodelled" }; if (words.some((w) => /^[+-]\d+$/.test(w)) || words.some((w) => w.startsWith("-") && w !== "--")) return { shift: { kind: "lost" }, reported: "unmodelled" }; const operand = args.find((a) => a.folded !== "--"); if (program === "popd") return { shift: operand === undefined ? { kind: "pop" } : { kind: "lost" }, reported: "unmodelled" }; if (operand === undefined) return { shift: { kind: "swap" }, reported: "unmodelled" }; return { shift: { kind: "cd", target: targetOf(operand), physical: false, push: true }, reported: targetOf(operand) }; } if (shellWordsOf("stack_editor").has(program) && args.some((a) => a.folded.startsWith("-") || a.folded.startsWith("+"))) return { shift: { kind: "stack" } }; return undefined; } export function textMayMove(text, functions) { const lexed = lexShell(SHELL_LEX_DIALECT, text); if ("parseFailure" in lexed) return true; return lexed.segments.some((s) => segmentMayMove(argvOf(s), functions)); } const programOf = (argv) => { const pos = readProgramPosition(argv); return pos.program === undefined ? undefined : { name: pos.program.basename, args: argv.slice(pos.program.index + 1).map((w) => w.folded) }; }; const setsPhysical = (p) => p?.name === "set" && p.args.some((a, k) => /^-[A-Za-z]*P/.test(a) || (a === "-o" && p.args[k + 1] === "physical")); export function textSetsPhysical(text) { const lexed = lexShell(SHELL_LEX_DIALECT, text); return !("parseFailure" in lexed) && lexed.segments.some((s) => setsPhysical(programOf(argvOf(s)))); } export function textCalls(text, functions) { const lexed = lexShell(SHELL_LEX_DIALECT, text); if ("parseFailure" in lexed) return true; return lexed.segments.some((s) => functionCallOf(argvOf(s), functions) !== undefined); } export function segmentMayMove(argv, functions) { const pos = readProgramPosition(argv); if (pos.program === undefined) return false; const word = argv[pos.program.index]; return shellWordsOf("base_mover").has(pos.program.basename) || TEXT_RUNNING_PROGRAMS.has(pos.program.basename) || functionCallOf(argv, functions) !== undefined || word.pieces.some((p) => p.expansion !== undefined || p.literal === undefined); } const runsAny = (r) => r.here || r.texts.length > 0; function segmentRunsBody(segment, argv, functions, exported = functions, fed = []) { const HERE = { here: true, texts: [] }; const pos = readProgramPosition(argv); const word = pos.program === undefined ? undefined : argv[pos.program.index]; const p = programOf(argv); if (functionCallOf(argv, functions) !== undefined || (p !== undefined && codeBodies(p.name, p.args).length > 0)) return HERE; const evalText = pos.program?.basename === "eval" ? literalEvalText(argv.slice(pos.program.index + 1)) : undefined; const own = evalText === undefined || "parseFailure" in lexShell(SHELL_LEX_DIALECT, evalText) ? [] : [{ text: evalText, in: "shell", functions }]; if (word !== undefined && own.length === 0 && (TEXT_RUNNING_PROGRAMS.has(pos.program.basename) || word.pieces.some((q) => q.expansion !== undefined || q.literal === undefined))) return HERE; if (functions.size === 0) return { here: false, texts: own }; const words = segment.tokens.flatMap((t) => (t.kind === "word" ? [t] : t.kind === "redirect" && t.target !== undefined ? [t.target] : [])); const unread = { here: true, texts: own }; if (words.some((w) => w.unresolved === "parameter_text")) return unread; const heredocs = segment.tokens.flatMap((t) => (t.kind === "heredoc" && !t.quoted ? [expansionsInHeredocBody(t.body)] : [])); if (heredocs.some((b) => b === undefined || b.some((x) => x.unresolved !== undefined))) return unread; const texts = [...segment.substitutions, ...heredocs.flatMap((b) => (b ?? []).flatMap((x) => (x.expansion.kind === "command" ? [x.expansion.body ?? ""] : [])))]; let unreadable = false; const handed = []; const hand = (text, by, fns) => { const lexed = lexShell(SHELL_LEX_DIALECT, text); if ("parseFailure" in lexed) unreadable = true; else if (lexed.segments.some((s) => runsAny(segmentRunsBody(s, argvOf(s), fns, exported)))) handed.push({ text, in: by, functions: fns }); }; const row = p === undefined ? undefined : programRow(p.name); const evaluated = argv.flatMap((w) => (w.assignment?.subscript !== undefined ? [`[${w.assignment.subscript.folded}]`] : [])); if (row !== undefined && p !== undefined) { for (const e of readArgRoles(row, p.args)) { const role = e.kind === "value" || e.kind === "operand" ? e.role : e.kind === "option" && typeof e.reading === "object" ? e.reading.role : undefined; const text = e.kind === "option" && typeof e.reading === "object" ? e.reading.attached : p.args[e.at]; if (role?.kind === "program-text" && role.language === "arithmetic" && e.kind !== "end-of-options" && e.kind !== "dash-word-operand") { evaluated.push(`[${text}]`); continue; } if (role?.kind !== "binds-name" || role.asWritten === true) continue; const at = text.indexOf("["); if (at >= 0) evaluated.push(text.slice(at)); } } if (isArithmeticCommand(segment)) evaluated.push(`[${argv.map((w) => w.raw).join(" ")}]`); for (const t of [...evaluated.flatMap((t) => arithmeticSubstitutions(t, undefined)), ...evaluated.flatMap((t) => substitutionBodies(t))]) hand(t, "subshell", functions); const stdin = stdinTextsOf(segment, fed); const named = descriptorNameWords(segment); const readings = [{ program: p, last: stdin.at(-1) }, ...(named.size > 0 ? [{ program: programOf(argv.filter((w) => !named.has(w))), last: stdin.filter((t) => t.allocated !== true).at(-1) }] : [])]; const children = new Set(readings.flatMap(({ program, last }) => (program !== undefined && !TEXT_RUNNING_PROGRAMS.has(program.name) && reentersShell(program.name, program.args) ? [reentryText(program.name, program.args, last?.literal ?? last?.printed)] : []))); if (exported.size > 0) for (const child of children) if (child !== undefined) hand(child, "child", exported); for (const text of texts) hand(text, "subshell", functions); return { here: unreadable, texts: [...own, ...handed] }; } export function textMovesOf(defined, segments, argvs, inFunctionBody, inherited, exportedInherited = new Set(), fedAt) { const unread = new Set([...evalDefinedFunctions(argvs), ...(inherited?.unread ?? [])]); const functions = new Set([...defined, ...unread, ...(inherited?.functions ?? [])]); const programs = argvs.map(programOf); const exportedSoFar = new Set(exportedInherited); const exportedAt = argvs.map((argv) => { const at = new Set([...exportedSoFar].filter((n) => functions.has(n))); for (const name of exportedFunctionNames(argv)) exportedSoFar.add(name); return at; }); const mayMove = argvs.map((argv) => segmentMayMove(argv, functions)); const bodyMoves = mayMove.some((m, si) => m && inFunctionBody(si)); const bodiesAt = programs.map((p) => (p === undefined ? [] : codeBodies(p.name, p.args))); const mayCallAt = argvs.map((argv) => functionCallOf(argv, functions) !== undefined); const callAt = (si, table) => functionCallOf(argvs[si], functions, (name) => table.functionState(name)); const callsUnread = (si, table) => functionCallOf(argvs[si], unread, (name) => table.functionState(name)) !== undefined; const bodyRunsAt = argvs.map((argv, si) => segmentRunsBody(segments[si], argv, functions, exportedAt[si], fedAt?.(si) ?? [])); return { functions, unread, mayMove, mayCallAt, runsBodyAt: bodyRunsAt.map(runsAny), bodyRunsAt, bodiesAt, bodyMoves, callAt, callsUnread, physicalAt: programs.map(setsPhysical), cdableFrom: programs.findIndex((p) => p?.name === "shopt" && p.args.includes("-s") && p.args.includes("cdable_vars")), losesBaseAt: (si, table) => (callAt(si, table) !== undefined && bodyMoves) || callsUnread(si, table) || bodiesAt[si].some((b) => bodyMoves || textMayMove(b, functions)), }; }