UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

232 lines (231 loc) • 9.83 kB
import { isFrontmatterFence } from "@sema-agent/primitives"; import { sliceHeadSafe } from "../surrogate-safe-slice.js"; import { compileGlobToken } from "../../tools/fs/search.js"; export const INSTRUCTION_FILE_MIN_CHARS = 40_000; export const INSTRUCTION_FILE_WINDOW_SHARE = 0.05; export const INSTRUCTION_INCLUDE_MAX_DEPTH = 5; export const INSTRUCTION_FILE_MAX_BYTES = 4 * 1024 * 1024; export function instructionFileCap(contextWindow, charsPerToken) { const window = Number.isFinite(contextWindow) && contextWindow > 0 ? contextWindow : 0; return Math.max(INSTRUCTION_FILE_MIN_CHARS, Math.round(window * INSTRUCTION_FILE_WINDOW_SHARE * charsPerToken)); } export function processInstructionText(text, withIncludes) { const { body, paths, spansLines } = splitFrontmatter(text); const globs = paths === undefined ? undefined : ruleGlobsOf(paths); const content = body.includes("<!--") ? stripBlockComments(body) : body; return { content, ...(globs !== undefined ? { globs } : {}), ...(paths !== undefined && globs === undefined ? { noLimit: true } : {}), ...(spansLines === true && globs !== undefined ? { spansLines: true } : {}), includes: withIncludes && content.includes("@") ? includePathsOf(content) : [], }; } function splitFrontmatter(text) { const lines = text.split("\n"); if (!isFrontmatterFence(lines[0] ?? "")) return { body: text }; const end = lines.findIndex((l, i) => i > 0 && isFrontmatterFence(l)); if (end < 0) return { body: text }; const body = lines.slice(end + 1).join("\n"); const block = lines.slice(1, end).map((l) => (l.endsWith("\r") ? l.slice(0, -1) : l)); const at = block.findIndex((l) => /^paths[ \t]*:/.test(l)); if (at < 0) return { body }; const value = pathsValueOf(block[at].replace(/^paths[ \t]*:/, "").trim(), block.slice(at + 1)); return { body, paths: value.values, ...(value.spansLines === true ? { spansLines: true } : {}) }; } const spansLinesOf = (lines) => (splitTopLevel(lines.join("\n")).some((p) => p.includes("\n")) ? { spansLines: true } : {}); function pathsValueOf(raw, below) { const rest = unquote(raw); if (rest.startsWith("[") && rest.endsWith("]")) return { values: splitTopLevel(rest.slice(1, -1)).flatMap(globText) }; const header = /^([|>])(?:([1-9])[+-]?|[+-]([1-9])?)?$/.exec(raw); if (header !== null) { const lines = blockScalarLines(below, Number(header[2] ?? header[3] ?? 0)); const text = lines.join("\n"); return { values: [header[1] === ">" ? text.replace(/([^\n])\n(?=[^\n ])/g, "$1 ") : text], ...spansLinesOf(lines) }; } if (rest !== raw) return { values: globText(raw) }; const blank = (l) => /^[ \t]*(?:#.*)?$/.test(l); const first = below.find((l) => !blank(l)); if (raw === "" && first !== undefined && /^[ \t]*-(?:[ \t]|$)/.test(first)) { const items = []; for (const l of below) { if (blank(l)) continue; const m = /^[ \t]*-(?:[ \t]+(.*))?$/.exec(l); if (m === null) break; items.push(...globText((m[1] ?? "").trim())); } return { values: items }; } const folded = raw === "" ? [] : [raw]; for (const l of below) { if (l.trim() === "") continue; if (/^[ \t]*#/.test(l)) { if (folded.length > 0) break; continue; } if (!/^[ \t]/.test(l)) break; folded.push(l.trim()); } const value = folded.join(" "); return /:(?:[ \t]|$)/.test(value) ? { values: [] } : { values: globText(value), ...spansLinesOf(folded) }; } function blockScalarLines(below, explicitIndent) { let indent = explicitIndent; const lines = []; for (const l of below) { if (l.trim() === "") { lines.push(""); continue; } const n = l.length - l.trimStart().length; if (indent === 0) indent = n; if (n === 0 || n < indent) break; lines.push(l.slice(indent)); } return lines; } const unquote = (s) => (s.length >= 2 && ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) ? s.slice(1, -1) : s); const PLAIN_NON_STRING = /^(?:~|null|Null|NULL|true|True|TRUE|false|False|FALSE|[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?|0x[0-9a-fA-F]+|0o[0-7]+|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$/; const globText = (raw) => { const text = unquote(raw); return text === raw && PLAIN_NON_STRING.test(raw) ? [] : [text]; }; function splitTopLevel(s) { const out = []; let depth = 0; let cur = ""; for (const ch of s) { if (ch === "{") depth++; else if (ch === "}") depth--; if (ch === "," && depth === 0) { out.push(cur.trim()); cur = ""; } else cur += ch; } out.push(cur.trim()); return out.filter((x) => x.length > 0); } function ruleGlobsOf(values) { const globs = values.flatMap(splitTopLevel).map((g) => (g.endsWith("/**") ? g.slice(0, -3) : g)).filter((g) => g.length > 0); return globs.length === 0 || globs.every((g) => g === "**") ? undefined : globs; } export function ruleGlobsMatch(globs, rel) { if (rel === "" || rel.startsWith("../") || rel === ".." || rel.startsWith("/")) return false; return globs.some((raw) => { let g = raw; while (g.startsWith("./")) g = g.slice(2); const anchored = g.includes("/"); const re = compileGlobToken(g.replace(/^\/+/, ""), anchored, true); if (re.test(rel)) return true; const segments = rel.split("/"); for (let i = 1; i < segments.length; i++) if (re.test(segments.slice(0, i).join("/"))) return true; return !anchored && segments.some((s) => re.test(s)); }); } const fenceOf = (line) => /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1]; function stripBlockComments(text) { const lines = text.split("\n"); const out = []; let fence; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (fence !== undefined) { out.push(line); if (line.trimStart().startsWith(fence)) fence = undefined; continue; } const opens = fenceOf(line); if (opens !== undefined) { fence = opens; out.push(line); continue; } if (!/^ {0,3}<!--/.test(line)) { out.push(line); continue; } let end = i; while (end < lines.length && !lines[end].slice(end === i ? line.indexOf("<!--") + 4 : 0).includes("-->")) end++; if (end >= lines.length) { out.push(line); continue; } const kept = lines.slice(i, end + 1).join("\n").replace(/<!--[\s\S]*?-->/g, ""); if (kept.trim().length > 0) out.push(kept); i = end; } return out.join("\n"); } function includePathsOf(text) { const found = new Set(); let fence; for (const line of text.replace(/<!--[\s\S]*?-->/g, "").split("\n")) { if (fence !== undefined) { if (line.trimStart().startsWith(fence)) fence = undefined; continue; } const opens = fenceOf(line); if (opens !== undefined) { fence = opens; continue; } const prose = line.replace(/`+[^`]*`+/g, " "); for (const m of prose.matchAll(/(?:^|\s)@((?:[^\s\\]|\\ )+)/g)) { let p = m[1]; const hash = p.indexOf("#"); if (hash !== -1) p = p.slice(0, hash); p = p.replaceAll("\\ ", " "); if (p === "" || p.includes("://")) continue; const isPath = p.startsWith("./") || p.startsWith("~/") || (p.startsWith("/") && p !== "/") || (!p.startsWith("@") && !/^[#%^&*()]+/.test(p) && /^[a-zA-Z0-9._-]/.test(p)); if (isPath) found.add(p); } } return [...found]; } const INCLUDE_TEXT_EXTENSIONS = new Set(".md .txt .text .json .yaml .yml .toml .xml .csv .html .htm .css .scss .sass .less .js .ts .tsx .jsx .mjs .cjs .mts .cts .py .pyi .pyw .rb .erb .rake .go .rs .java .kt .kts .scala .c .cpp .cc .cxx .h .hpp .hxx .cs .swift .sh .bash .zsh .fish .ps1 .bat .cmd .env .ini .cfg .conf .config .properties .sql .graphql .gql .proto .vue .svelte .astro .ejs .hbs .pug .jade .php .pl .pm .lua .r .dart .ex .exs .erl .hrl .clj .cljs .cljc .edn .hs .lhs .elm .ml .mli .f .f90 .f95 .for .cmake .make .makefile .gradle .sbt .rst .adoc .asciidoc .org .tex .latex .lock .log .diff .patch".split(" ")); export function isTextIncludeTarget(path) { const base = path.slice(path.lastIndexOf("/") + 1); const dot = base.lastIndexOf("."); return dot <= 0 || INCLUDE_TEXT_EXTENSIONS.has(base.slice(dot).toLowerCase()); } export function cutInstructionText(text, cap, charsPerToken) { if (text.length <= cap) return { text }; const nl = text.lastIndexOf("\n", cap); const approxTokens = (head) => Math.ceil(head.length / charsPerToken); if (nl > 0) { const head = text.slice(0, nl); const total = text.endsWith("\n") ? text.split("\n").length - 1 : text.split("\n").length; return { text: head, note: { kind: "partial_page", end: head.split("\n").length, total, approxTokens: approxTokens(head) } }; } const head = sliceHeadSafe(text, cap); return { text: head, note: { kind: "partial_chars", cut: head.length, totalChars: text.length, approxTokens: approxTokens(head) } }; }