UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

79 lines (78 loc) • 3.3 kB
import { readProgramPosition } from "../tools/fs/bash-program-position.js"; import { argvOf, lexShell } from "../shell/lex.js"; import { startedShellOfCall } from "./call-shell.js"; import { isSensitiveRecordKey } from "@sema-agent/primitives"; import { egressText } from "./untrusted-egress.js"; const ACTIVITY_ARG_MAX = 80; function truncCodePoints(s) { const cp = Array.from(s); return cp.length > ACTIVITY_ARG_MAX ? cp.slice(0, ACTIVITY_ARG_MAX).join("") + "…" : s; } const basename = (p) => p.split(/[/\\]/).filter((x) => x.length > 0).pop() ?? p; export function primaryActivityArg(call, args) { if (!args || typeof args !== "object") return undefined; const a = args; const str = (k) => typeof a[k] === "string" && a[k].length > 0 ? a[k] : undefined; let val; const command = str("command"); const path = str("file_path") ?? str("filePath") ?? str("path") ?? str("notebook_path"); const url = str("url"); if (command !== undefined) { const lexed = lexShell(startedShellOfCall(call), command); if ("parseFailure" in lexed) return undefined; const named = lexed.segments.map((segment) => { const argv = argvOf(segment); const pos = readProgramPosition(argv); return { segment, word: pos.written === undefined ? undefined : argv[pos.written + pos.assignments.length] }; }).find((s) => s.word !== undefined); if (named?.word === undefined) return undefined; const word = named.word; if (word.assignment !== undefined || word.expansions.length > 0 || word.unresolved !== undefined) return undefined; const name = basename(word.folded); const more = named.segment.tokens.indexOf(word) < named.segment.tokens.length - 1 || lexed.segments.slice(lexed.segments.indexOf(named.segment) + 1).some((s) => s.tokens.length > 0); val = more ? `${name} …` : name; } else if (path !== undefined) { val = basename(path); } else if (url !== undefined) { const parsed = (() => { try { return new URL(url); } catch { return undefined; } })(); if (parsed !== undefined && parsed.host !== "") { val = `${parsed.origin}${parsed.pathname}`; } else { const head = url.split(/[?#]/, 1)[0] ?? url; const sep = head.indexOf("://"); const scheme = sep > 0 && /^[a-z][a-z0-9+.-]*$/i.test(head.slice(0, sep)) ? head.slice(0, sep + 3) : ""; const rest = head.slice(scheme.length); const at = rest.lastIndexOf("@"); val = scheme + (at === -1 ? rest : rest.slice(at + 1)); } } else { val = str("pattern") ?? str("query") ?? str("description"); if (val === undefined) { for (const k of Object.keys(a)) { if (isSensitiveRecordKey(k)) continue; const v = a[k]; if (typeof v === "string" && v.length > 0) { val = v; break; } } } } if (val === undefined) return undefined; return truncCodePoints(egressText("same-principal", val)); }