@sema-agent/core
Version:
Stateless, task-oriented AI agent core
20 lines (19 loc) • 781 B
JavaScript
import { randomBytes } from "node:crypto";
import { constants as FS, openSync } from "node:fs";
export const PRIVATE_FILE_MODE = 0o600;
const TEMP_OPEN_ATTEMPTS = 8;
export function openExclusiveTemp(stem) {
let lastExists;
for (let attempt = 0; attempt < TEMP_OPEN_ATTEMPTS; attempt++) {
const path = `${stem}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
try {
return { fd: openSync(path, FS.O_CREAT | FS.O_EXCL | FS.O_WRONLY, PRIVATE_FILE_MODE), path };
}
catch (err) {
if (err.code !== "EEXIST")
throw err;
lastExists = err;
}
}
throw new Error(`file store: no unused temp file name for ${stem} after ${TEMP_OPEN_ATTEMPTS} attempts`, { cause: lastExists });
}