@sema-agent/core
Version:
Stateless, task-oriented AI agent core
151 lines (150 loc) • 6.66 kB
JavaScript
import { appendFileSync as nodeAppendFileSync, chmodSync as nodeChmodSync, closeSync as nodeCloseSync, constants as fsConstants, copyFileSync as nodeCopyFileSync, linkSync as nodeLinkSync, mkdirSync as nodeMkdirSync, openSync as nodeOpenSync, readdirSync as nodeReaddirSync, readFileSync as nodeReadFileSync, renameSync as nodeRenameSync, rmdirSync as nodeRmdirSync, rmSync as nodeRmSync, unlinkSync as nodeUnlinkSync, utimesSync as nodeUtimesSync, writeFileSync as nodeWriteFileSync, } from "node:fs";
import { devNull } from "node:os";
import { openExclusiveTemp as coreOpenExclusiveTemp } from "../../core/exclusive-temp.js";
import { deliverEngineNotice } from "../../core/engine-notice.js";
import { receiptRefusal } from "../../core/own-property-receipt.js";
import { describeRejectedValue } from "../../core/tool-search-setting.js";
const DEFAULT_APPEND_LOG_DESCRIPTOR_BUDGET = 256;
const MAX_APPEND_LOG_DESCRIPTOR_BUDGET = 65_536;
const DESCRIPTORS_EXHAUSTED = new Set(["EMFILE", "ENFILE"]);
export const descriptorPool = {
budget: DEFAULT_APPEND_LOG_DESCRIPTOR_BUDGET,
held: new Map(),
peak: 0,
parks: 0,
reopens: 0,
refusals: 0,
announced: new Set(),
};
export function parkDownTo(keep, except, cause) {
const before = descriptorPool.parks;
for (const [log, park] of descriptorPool.held) {
if (descriptorPool.held.size <= keep)
break;
if (log !== except)
park();
}
if (descriptorPool.parks !== before)
announceParking(cause);
}
function announceParking(cause) {
const budget = descriptorPool.budget;
const said = `${cause}:${budget}`;
if (descriptorPool.announced.has(said))
return;
descriptorPool.announced.add(said);
queueStoreNotice({
code: "store.append_log_parked",
message: (cause === "descriptors_exhausted"
? `[sema] file store: an open of the file store met the process's descriptor limit, so the append logs' descriptor budget is now ${budget} — `
: `[sema] file store: the append logs reached their descriptor budget (${budget}) — `) +
`the least recently written ones now release their descriptors and reopen on their next write. Nothing is lost; a budget this process keeps reaching ` +
`costs a reopen per switch (setAppendLogDescriptorBudget, appendLogDescriptorStats).`,
detail: { budget, cause },
});
}
export function takeYielding(attempt) {
for (;;) {
try {
return attempt();
}
catch (err) {
if (descriptorPool.held.size === 0 || !metDescriptorLimit(err))
throw err;
descriptorPool.budget = Math.max(1, Math.floor(descriptorPool.held.size / 2));
parkDownTo(descriptorPool.budget - 1, undefined, "descriptors_exhausted");
}
}
}
const REMOVAL_DESCRIPTOR_HEADROOM = 32;
function metDescriptorLimit(err) {
const { code, syscall } = (err ?? {});
if (code !== undefined && DESCRIPTORS_EXHAUSTED.has(code))
return true;
if (syscall !== "rm" || (code !== "" && code !== "ENOTEMPTY"))
return false;
const asked = [];
try {
while (asked.length < REMOVAL_DESCRIPTOR_HEADROOM)
asked.push(nodeOpenSync(devNull, "r"));
return false;
}
catch (refused) {
return DESCRIPTORS_EXHAUSTED.has(refused?.code ?? "");
}
finally {
for (const fd of asked) {
try {
nodeCloseSync(fd);
}
catch {
}
}
}
}
function seated(fn) {
return new Proxy(fn, { apply: (target, self, args) => (typeof args[0] === "number" ? Reflect.apply(target, self, args) : takeYielding(() => Reflect.apply(target, self, args))) });
}
let lostLockGuard;
export function setLostLockGuard(guard) {
lostLockGuard = guard;
}
function guardPath(p) {
if (lostLockGuard !== undefined && typeof p === "string")
lostLockGuard(p);
}
function opensForWrite(flags) {
if (flags === undefined)
return false;
if (typeof flags === "number")
return (flags & (fsConstants.O_WRONLY | fsConstants.O_RDWR | fsConstants.O_CREAT | fsConstants.O_TRUNC | fsConstants.O_APPEND)) !== 0;
return typeof flags === "string" && !/^(?:r|rs|sr)$/.test(flags);
}
function guarded(fn, targets) {
return new Proxy(fn, {
apply: (target, self, args) => {
for (const p of targets(args))
guardPath(p);
return Reflect.apply(target, self, args);
},
});
}
const first = (args) => [args[0]];
export const openSync = guarded(seated(nodeOpenSync), (args) => (opensForWrite(args[1]) ? [args[0]] : []));
export const openSyncUnguarded = seated(nodeOpenSync);
export const readFileSync = seated(nodeReadFileSync);
export const writeFileSync = guarded(seated(nodeWriteFileSync), first);
export const appendFileSync = guarded(seated(nodeAppendFileSync), first);
export const readdirSync = seated(nodeReaddirSync);
export const rmSync = guarded(seated(nodeRmSync), first);
export const copyFileSync = guarded(seated(nodeCopyFileSync), (args) => [args[1]]);
export const openExclusiveTemp = guarded(seated(coreOpenExclusiveTemp), first);
export const unlinkSync = guarded(nodeUnlinkSync, first);
export const unlinkLockFile = nodeUnlinkSync;
export const renameSync = guarded(nodeRenameSync, (args) => [args[0], args[1]]);
export const linkSync = guarded(nodeLinkSync, (args) => [args[1]]);
export const mkdirSync = guarded(nodeMkdirSync, first);
export const rmdirSync = guarded(nodeRmdirSync, first);
export const utimesSync = guarded(nodeUtimesSync, first);
export const chmodSync = guarded(nodeChmodSync, first);
export function setAppendLogDescriptorBudget(budget) {
if (typeof budget !== "number" || !Number.isInteger(budget) || budget < 1 || budget > MAX_APPEND_LOG_DESCRIPTOR_BUDGET) {
throw receiptRefusal(`setAppendLogDescriptorBudget: the budget must be a whole number from 1 to ${MAX_APPEND_LOG_DESCRIPTOR_BUDGET} (got ${describeRejectedValue(budget)}) — the budget in force (${descriptorPool.budget}) is kept`);
}
descriptorPool.budget = budget;
parkDownTo(budget, undefined, "budget_reached");
}
export function appendLogDescriptorStats() {
const p = descriptorPool;
return { budget: p.budget, held: p.held.size, peak: p.peak, parks: p.parks, reopens: p.reopens, refusals: p.refusals };
}
export function queueStoreNotice(notice) {
queueMicrotask(() => sayStoreNotice(notice));
}
function sayStoreNotice(notice) {
try {
deliverEngineNotice(undefined, notice);
}
catch {
}
}