UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

102 lines • 3.19 kB
import { createHash } from "node:crypto"; import * as fsPromises from "node:fs/promises"; import { CONFIG_DIR_NAME, resolveAgentDir } from "../../../../config.js"; export class LoopFileError extends Error { constructor(message, code, path, options) { super(message, options); this.name = "LoopFileError"; this.code = code; this.path = path; } } const MAX_MODEL_BYTES = 25000; const READ_LIMIT = MAX_MODEL_BYTES + 1; const TRUNCATION_WARNING = "[loop.md truncated to the first 25000 bytes]"; function isEnoentError(err) { return typeof err === "object" && err !== null && err.code === "ENOENT"; } function sha256(text) { return createHash("sha256").update(text).digest("hex"); } function safeUtf8Truncate(buf, maxBytes) { const decoder = new TextDecoder("utf-8", { fatal: true }); let slice = buf.subarray(0, maxBytes); while (slice.length > 0) { try { return decoder.decode(slice); } catch { slice = slice.subarray(0, slice.length - 1); } } return ""; } async function tryResolveOne(path, fs) { let stat; try { stat = await fs.stat(path); } catch (err) { if (isEnoentError(err)) return { found: false }; return { error: new LoopFileError(`Failed to stat loop file ${path}`, "stat_failed", path, { cause: err }), }; } let raw; try { raw = await fs.readBytes(path, READ_LIMIT); } catch (err) { if (isEnoentError(err)) return { found: false }; return { error: new LoopFileError(`Failed to read loop file ${path}`, "read_failed", path, { cause: err }), }; } const truncated = raw.length > MAX_MODEL_BYTES; const modelVisible = truncated ? `${safeUtf8Truncate(raw, MAX_MODEL_BYTES)}\n${TRUNCATION_WARNING}` : raw.toString("utf-8"); return { found: true, path, content: modelVisible, fingerprint: { path, mtimeMs: stat.mtimeMs, size: stat.size, contentHash: sha256(modelVisible), }, }; } export async function resolveLoopFile(deps) { const { cwd, homeDir, fs, path } = deps; const candidates = [path.join(cwd, CONFIG_DIR_NAME, "loop.md"), path.join(resolveAgentDir(cwd, homeDir), "loop.md")]; for (const candidate of candidates) { const outcome = await tryResolveOne(candidate, fs); if ("error" in outcome) { throw outcome.error; } if (outcome.found) { return outcome; } } return { found: false }; } export const nodeFs = { stat: (path) => fsPromises.stat(path), readFile: (path) => fsPromises.readFile(path), readBytes: async (path, maxBytes) => { const handle = await fsPromises.open(path, "r"); try { const buf = Buffer.alloc(maxBytes); const { bytesRead } = await handle.read(buf, 0, maxBytes, 0); return buf.subarray(0, bytesRead); } finally { await handle.close(); } }, }; //# sourceMappingURL=loopfile.js.map