UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

176 lines (175 loc) • 8.49 kB
import { literalTildeSpelling } from "../../shell/lex.js"; import { joinedFloors } from "./shell-read-bindings.js"; import { programBasename } from "./bash-program-position.js"; import { launcherOptionPathRole, launcherOptionStep, programRow, readOptionRole } from "./program-read-model.js"; import { chdirFrom, chdirMayLeadTo } from "./shell-read-object-path.js"; import { anchorSpelling, pathFamilyOf } from "./safety.js"; const NO_NAMES = new Set(); export function heldAt(table, bound = NO_NAMES) { return { start: (key) => table.stateOf(key), bound }; } const ROOT_HOMES = ["/root", "/var/root"]; export function startedAt(later, at) { if (at === undefined) return later; const fed = at.stdin !== undefined && at.stdin.length > 0 ? { ...later, stdin: at.stdin } : later; const withFloors = at.floors === undefined || at.floors.size === 0 ? fed : { ...fed, inherited: { ...fed.inherited, floors: joinedFloors(fed.inherited.floors, at.floors) } }; const as = at.as; if (as === undefined || as.home === "caller") return withFloors; const homes = as.name === "root" ? ROOT_HOMES : undefined; const target = homes === undefined ? "unknown" : homes.map((spelled) => ({ spelled })); const caller = later.initial("HOME"); const home = as.home === "target" ? target : caller === "unknown" || target === "unknown" ? "unknown" : [...caller, ...target]; return { ...withFloors, initial: (name) => (name === "HOME" ? home : withFloors.initial(name)), homeTouched: true, ...(as.login ? { bases: homes ?? "unmodelled" } : {}), }; } export function plannedOnce(plan) { const planned = new Map(); return (text, kind, at) => { const key = JSON.stringify([kind, text, [...(at?.floors ?? [])], at?.as, at?.stdin]); if (!planned.has(key)) planned.set(key, plan(text, kind, at)); return planned.get(key); }; } export function stdinFeeds(segments, start, piped) { const opener = []; const enclosing = []; const open = []; segments.forEach((segment, si) => { enclosing[si] = open.at(-1); let opens = false; for (const t of segment.tokens) { if ((t.kind === "group" && t.op === "(") || (t.kind === "word" && t.raw === "{")) { open.push(si); opens = true; } else if ((t.kind === "group" && t.op === ")") || (t.kind === "word" && t.raw === "}")) open.pop(); } opener[si] = opens ? si : enclosing[si]; }); const fedAt = (si) => { if (si > 0 && segments[si].connector === "|") return [...new Map(piped(si).map((s) => [JSON.stringify(s), s])).values()]; const group = opener[si] !== si ? opener[si] : enclosing[si]; return group !== undefined ? fedAt(group) : start; }; return fedAt; } export function nestedStartOf(cwd) { return anchorSpelling(pathFamilyOf({ cwd }), cwd, "\u0000"); } export function walkFromStart(base) { const at = base.search(/[\\/]\u0000(?:[\\/]|$)/); return at < 0 ? undefined : base.slice(at + 3); } const settledWord = (r) => r.expands === false && (r.values?.length ?? 1) <= 1 && r.word.pieces.every((q) => q.literal !== undefined || q.expansion !== undefined); export function launchedInOf(pos, toks) { if (pos.baseMovedAt.length === 0) return undefined; const dirs = []; let owner; for (const at of pos.baseMovedAt) { const l = pos.launchers.filter((x) => x.index < at).at(-1); const row = programRow(programBasename(l.name)); const w = toks[at].folded; const step = launcherOptionStep(row, w); const own = step === 2 ? undefined : readOptionRole(row, w); const role = step === 2 ? launcherOptionPathRole(row, w) : own?.form === "attached" ? own.role : undefined; if (role?.kind !== "path" || role.base !== "working-directory") return "unmodelled"; const word = toks[step === 2 ? at + 1 : at]; const twoWays = own?.form === "attached" && own.spec?.arity === "attached" && own.value.startsWith("="); const value = step === 2 ? word.folded : own?.form === "attached" && !twoWays ? literalTildeSpelling(own.value) : undefined; const dir = !settledWord(word) ? null : value !== undefined && value !== "" ? value : undefined; if (l.index === owner) dirs[dirs.length - 1] = dir; else dirs.push(dir); owner = l.index; } return dirs.includes(undefined) ? "unmodelled" : dirs; } export function launchedAt(launchedIn, bases, floor, homeDir) { if (launchedIn === undefined) return undefined; const here = bases !== "unmodelled" ? bases : floor; let to = launchedIn === "unmodelled" ? "unmodelled" : bases; let toFloor = here; let unsettled = false; for (const dir of launchedIn === "unmodelled" ? [] : launchedIn) { if (dir === null) { toFloor = [...new Set([...(to !== "unmodelled" ? to : (toFloor ?? [])), ...(here ?? [])])]; to = "unmodelled"; unsettled = true; } else if (to !== "unmodelled") { const next = chdirFrom(to, dir, homeDir); if (next === undefined) [toFloor, to] = [[...new Set([...(toFloor ?? []), ...chdirMayLeadTo(to, dir, homeDir)])], "unmodelled"]; else toFloor = to = next; } else if (toFloor !== undefined) toFloor = chdirFrom(toFloor, dir, homeDir) ?? [...new Set([...toFloor, ...chdirMayLeadTo(toFloor, dir, homeDir)])]; } const words = [...new Set([...(here ?? []), ...(toFloor ?? [])])]; return { to, ...(toFloor !== undefined && toFloor.length > 0 ? { floor: toFloor } : {}), ...(words.length > 0 ? { words } : {}), ...(unsettled ? { unsettled: true } : {}) }; } export function rebasePlan(plan, to, floor, unsettled = false) { const key = JSON.stringify([to, floor, unsettled]); const known = REBASED.get(plan)?.get(key); if (known !== undefined) return known; const out = rebasedOnto(plan, to, floor, unsettled); REBASED.set(plan, (REBASED.get(plan) ?? new Map()).set(key, out)); return out; } const REBASED = new WeakMap(); function rebasedOnto(plan, to, floor, unsettled) { const placed = (into, b) => { const rest = walkFromStart(b); if (rest === undefined) return [b]; return (into ?? []).map((t) => (rest === "" ? t : anchorSpelling(pathFamilyOf({ cwd: t }), t, rest))); }; const moveBase = (b) => (to === "unmodelled" ? [] : placed(to, b)); const floorAt = to === "unmodelled" ? floor : to; const floorsOf = (bases, into) => { const floors = [...new Set(bases.flatMap((b) => placed(into, b)))]; const fromStart = unsettled && to === "unmodelled" && bases.some((b) => walkFromStart(b) !== undefined); return { ...(floors.length > 0 ? { floorBases: floors } : {}), ...(fromStart ? { unsettledStart: true } : {}) }; }; const moveCandidate = (c) => { if (c.bases === "unmodelled") { if (c.floorBases === undefined) return c; const { floorBases: _, ...rest } = c; return { ...rest, ...floorsOf(c.floorBases, floorAt) }; } if (c.bases.length === 0) return c; if (to === "unmodelled") return { ...c, bases: "unmodelled", ...floorsOf(c.bases, floor) }; return { ...c, bases: [...new Set(c.bases.flatMap(moveBase))] }; }; return { ...plan, segments: plan.segments.map((s) => ({ ...s, reads: s.reads.map(moveCandidate), redirects: s.redirects.map((r) => (r.target === undefined ? r : { ...r, target: moveCandidate(r.target) })), ...(s.baseMove !== undefined ? { baseMove: { target: typeof s.baseMove.target === "string" ? s.baseMove.target : moveCandidate(s.baseMove.target) } } : {}), bases: s.bases === "unmodelled" || to === "unmodelled" ? "unmodelled" : [...new Set(s.bases.flatMap(moveBase))], ...(s.programStart !== undefined ? { programStart: moveCandidate(s.programStart) } : {}), nested: s.nested.map((n) => rebasePlan(n, to, floor, unsettled)), ...(s.printed !== undefined ? { printed: s.printed.map((n) => rebasePlan(n, to, floor, unsettled)) } : {}), })), }; }