@sema-agent/core
Version:
Stateless, task-oriented AI agent core
59 lines (58 loc) • 2.51 kB
JavaScript
import { lstatSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { DEFAULT_MAX_ENTRY_DEPTH, MEMORY_INDEX_FILENAME } from "./entry-scan.js";
import { expectedScopesInvalid } from "./export-bundle.js";
import { parseEntryFile } from "./frontmatter.js";
export const PATCH_TARGET_OUTSIDE = "target scope outside the permitted scopes (refused)";
export function readPatchScopeSet(opts) {
const given = opts?.expectedScopes;
if (given === undefined)
return undefined;
const raw = Array.isArray(given) ? Array.from(given) : given;
const bad = expectedScopesInvalid(raw);
if (bad !== undefined)
throw Object.assign(new TypeError(`applyPatches: ${bad}`), { code: "config.invalid_argument" });
return new Set(raw);
}
export function patchScopeRefusal(set, patch, owner, notHeld) {
if (patch.op === "update" && patch.entry !== undefined && !set.has(patch.entry.scope))
return { op: patch.op, id: patch.id, reason: PATCH_TARGET_OUTSIDE };
return owner === undefined || set.has(owner) ? undefined : { op: patch.op, id: patch.id, reason: notHeld };
}
export function applyPatchesWithin(backend, patches, scopes, opts) {
const seated = backend.judgesPatchScopes === true && scopes.every((s) => s.length > 0) ? { ...opts, expectedScopes: [...scopes] } : opts;
return seated === undefined ? backend.applyPatches(patches) : backend.applyPatches(patches, seated);
}
export function idStandsIn(dirs, id) {
const walk = (d, depth) => {
let names;
try {
names = readdirSync(d);
}
catch (err) {
return !(depth === 0 && err.code === "ENOENT");
}
for (const name of names) {
if (name.startsWith(".") || name === MEMORY_INDEX_FILENAME)
continue;
const p = join(d, name);
try {
const st = lstatSync(p);
if (st.isSymbolicLink())
continue;
if (st.isDirectory()) {
if (depth + 1 <= DEFAULT_MAX_ENTRY_DEPTH && walk(p, depth + 1))
return true;
continue;
}
if (st.isFile() && name.endsWith(".md") && parseEntryFile(readFileSync(p, "utf8")).id === id)
return true;
}
catch {
return true;
}
}
return false;
};
return dirs.some((dir) => walk(dir, 0));
}