UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

160 lines (159 loc) • 6.96 kB
import { statSync } from "node:fs"; import { foldRedundantPathSegments, normalizeAbsPathLexically } from "../tools/fs/safety.js"; import { validatePath } from "./effective-path-target.js"; import { thrownText } from "./thrown-value.js"; import { envErrorDetail } from "../tools/fs/env-error-detail.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; } } export const AGENT_HOME_DIR_INVALID_CODE = "config.agent_home_dir_invalid"; const DECLARED_DIR = { config: { code: AGENT_CONFIG_DIR_INVALID_CODE, what: "the host's own configuration root", absent: `the default \`~/${AGENT_CONFIG_DIR_SEGMENT}\` location` }, home: { code: AGENT_HOME_DIR_INVALID_CODE, what: "the caller's own home directory", absent: "the engine's own home directories alone" }, }; function invalidDeclaredDir(kind, seat, value, why) { const d = DECLARED_DIR[kind]; const e = new Error(`${seat} ${shown(value)} ${why} — it must be the absolute path of an existing directory (${d.what}); ` + `a value that names no directory would guard nothing, so it is refused rather than read as ${d.absent}.`); e.code = d.code; return e; } function shapedDeclaredDir(kind, value, seat) { if (value === undefined) return undefined; if (typeof value !== "string") throw invalidDeclaredDir(kind, seat, value, `is a ${value === null ? "null" : typeof value}, not a string`); if (value.length === 0) throw invalidDeclaredDir(kind, seat, value, "is an empty string"); if (validatePath(value, { intent: "validate-coordinate" }) === undefined) throw invalidDeclaredDir(kind, seat, value, "is not an absolute path"); return value; } export function checkedDeclaredDir(kind, value, seat) { const dir = shapedDeclaredDir(kind, value, seat); if (dir === undefined) return undefined; let isDirectory; try { isDirectory = statSync(dir).isDirectory(); } catch (e) { const code = typeof e === "object" && e !== null && "code" in e && typeof e.code === "string" ? e.code : "unreadable"; throw invalidDeclaredDir(kind, seat, dir, code === "ENOENT" || code === "ENOTDIR" ? "names no existing directory" : `could not be examined (${code})`); } if (!isDirectory) throw invalidDeclaredDir(kind, seat, dir, "names a file, not a directory"); return dir; } export function assertTaskDeclaredDirsOnHost(spec) { const seats = [ ["config", "TaskSpec.agentConfigDirs", spec.agentConfigDirs], ["home", "TaskSpec.agentHomeDirs", spec.agentHomeDirs], ]; for (const [kind, seat, list] of seats) { if (!Array.isArray(list)) continue; const entries = list; for (let i = 0; i < entries.length; i++) checkedDeclaredDir(kind, entries[i], `${seat}[${i}]`); } } const NOTHING_THERE = new Set(["not_found", "not_directory", "name_too_long"]); export async function judgeTaskDeclaredDirs(kind, list, seat, env, unverified, absent = "refuse") { for (let i = 0; i < (list ?? []).length; i++) { const dir = list[i]; const at = `${seat}[${i}]`; const nothing = (why, answered) => { if (absent === "refuse") throw invalidDeclaredDir(kind, at, dir, why); unverified(dir, `${answered} (a resume places it by its spelling)`); }; const answer = (e) => `${e.code}: ${envErrorDetail(e.message)}`; const canonical = await env.canonicalPath(dir); if (!canonical.ok) { if (NOTHING_THERE.has(canonical.error.code)) nothing("names no existing directory", answer(canonical.error)); else unverified(dir, answer(canonical.error)); continue; } const info = await env.fileInfo(canonical.value); if (!info.ok) { if (info.error.code === "invalid") nothing("names a file, not a directory", `not_directory: ${answer(info.error)}`); else if (NOTHING_THERE.has(info.error.code)) nothing("names no existing directory", answer(info.error)); else unverified(dir, answer(info.error)); continue; } if (info.value.kind !== "directory") nothing("names a file, not a directory", `not_directory: ${canonical.value} is a ${info.value.kind}`); } } export function checkedAgentConfigDir(value, seat) { return checkedDeclaredDir("config", value, seat); } function checkedDeclaredDirEntry(kind, entry, seat) { if (entry === undefined) throw invalidDeclaredDir(kind, seat, entry, "is missing (undefined, or a hole in the list), not a string"); shapedDeclaredDir(kind, entry, seat); } export function assertTaskDeclaredDirs(kind, value, seat) { if (value === undefined) return; if (!Array.isArray(value)) throw invalidDeclaredDir(kind, seat, value, `is a ${value === null ? "null" : typeof value}, not a list of directories`); const list = value; for (let i = 0; i < list.length; i++) checkedDeclaredDirEntry(kind, list[i], `${seat}[${i}]`); } export function declaredDirDoor(kind) { return (value, owner) => assertTaskDeclaredDirs(kind, value, owner); } export function declaredDirEntryLaw(kind) { return (entry, owner) => { try { checkedDeclaredDirEntry(kind, entry, owner); return undefined; } catch (e) { return thrownText(e); } }; } export function declaredDirIdentity(dir) { return foldRedundantPathSegments(dir); } export function recordedDeclaredDirs(kind, value, seat) { if (value === undefined) return undefined; if (!Array.isArray(value)) throw invalidDeclaredDir(kind, seat, value, "is not a list (a damaged row)"); const list = value; const out = []; for (let i = 0; i < list.length; i++) { const entry = list[i]; if (typeof entry !== "string" || validatePath(entry, { intent: "validate-coordinate" }) === undefined) throw invalidDeclaredDir(kind, `${seat}[${i}]`, entry, "is not an absolute path (a damaged row)"); out.push(entry); } return out; }