@sema-agent/core
Version:
Stateless, task-oriented AI agent core
51 lines (50 loc) • 2.42 kB
JavaScript
import { statSync } from "node:fs";
import { normalizeAbsPathLexically } from "../tools/fs/safety.js";
import { validatePath } from "./effective-path-target.js";
export const AGENT_CONFIG_DIR_SEGMENT = ".sema";
export const AGENT_CONFIG_DIR_INVALID_CODE = "config.agent_config_dir_invalid";
export function agentConfigDirTail(run, caseSensitive = false) {
const [first, ...rest] = run.split("/").filter((segment) => segment.length > 0);
if (first === undefined)
return undefined;
const folded = caseSensitive ? first : first.replace(/[A-Z]/g, (c) => c.toLowerCase());
return folded === AGENT_CONFIG_DIR_SEGMENT ? rest.join("/") : undefined;
}
export function agentConfigDirSegments(dir) {
return normalizeAbsPathLexically(dir).split(/[\\/]/).filter((segment) => segment.length > 0);
}
function shown(value) {
try {
return JSON.stringify(value) ?? String(value);
}
catch {
return typeof value;
}
}
function invalidAgentConfigDir(seat, value, why) {
const e = new Error(`${seat} ${shown(value)} ${why} — it must be the absolute path of an existing directory (the host's own configuration root); ` +
`a value that names no directory would guard nothing, so it is refused rather than read as the default \`~/${AGENT_CONFIG_DIR_SEGMENT}\` location.`);
e.code = AGENT_CONFIG_DIR_INVALID_CODE;
return e;
}
export function checkedAgentConfigDir(value, seat) {
if (value === undefined)
return undefined;
if (typeof value !== "string")
throw invalidAgentConfigDir(seat, value, `is a ${value === null ? "null" : typeof value}, not a string`);
if (value.length === 0)
throw invalidAgentConfigDir(seat, value, "is an empty string");
if (validatePath(value, { intent: "validate-coordinate" }) === undefined)
throw invalidAgentConfigDir(seat, value, "is not an absolute path");
let isDirectory;
try {
isDirectory = statSync(value).isDirectory();
}
catch (e) {
const code = typeof e === "object" && e !== null && "code" in e && typeof e.code === "string" ? e.code : "unreadable";
throw invalidAgentConfigDir(seat, value, code === "ENOENT" || code === "ENOTDIR" ? "names no existing directory" : `could not be examined (${code})`);
}
if (!isDirectory)
throw invalidAgentConfigDir(seat, value, "names a file, not a directory");
return value;
}