UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

45 lines (44 loc) • 2.08 kB
import { literalTextOf } from "../../shell/lex.js"; import { readProgramPosition } from "./bash-program-position.js"; import { programRow } from "./program-read-model.js"; import { removalActionOf } from "./removal-actions.js"; const FIND_LEAD_SWITCHES = /^-(?:[HLPEXdsx]|O\d*|D)$/; const GETOPT_TAKES = /^-[EHLPXdsx]*(?:f[\s\S]*)?$/; export const FIND_ACTING_WORDS = new Set(["-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls", "-files0-from"]); function leadingText(w) { const whole = literalTextOf(w.pieces); if (whole !== undefined) return { text: whole, whole: true }; const cut = w.pieces.findIndex((p) => p.literal === undefined); return { text: w.pieces.slice(0, cut).map((p) => p.literal).join(""), whole: false }; } export function findLeadUnreadAt(args) { for (let i = 0; i < args.length; i++) { const w = args[i]; if (w.pieces.length > 0 && w.pieces.every((p) => p.expansion?.yields === "many")) continue; const { text, whole } = leadingText(w); if (!text.startsWith("-") || (whole && text === "-")) return undefined; if (whole && FIND_LEAD_SWITCHES.test(text)) continue; return GETOPT_TAKES.test(text) ? i : undefined; } return undefined; } export function unreadActingFinds(plan) { const out = []; for (const s of plan.segments) { const row = s.verb === undefined ? undefined : programRow(s.verb.basename); const at = readProgramPosition(s.argv).program?.index; if (row !== undefined && at !== undefined && removalActionOf(row.key) === "walk") { const args = s.argv.slice(at + 1); const k = findLeadUnreadAt(args); if (k !== undefined && args.slice(k + 1).some((w) => FIND_ACTING_WORDS.has(literalTextOf(w.pieces) ?? ""))) out.push({ program: s.verb.basename, word: args[k].raw, text: s.text.trim() }); } for (const n of s.nested) out.push(...unreadActingFinds(n)); } return out; }