UNPKG

@code-yeongyu/senpi

Version:

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

273 lines • 11.2 kB
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { readFile, rename, stat, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import lockfile from "proper-lockfile"; import { canonicalizePathStrict, resolvePath } from "../utils/paths.js"; import { stripBom } from "../utils/text.js"; import { linkedWorktreeMainCheckoutDir } from "./linked-worktree-checkout.js"; import { fsErrorCode } from "./tools/fs-error-code.js"; import { holdTrustStoreLockInRealm, inTrustStoreWriteTurn, trustStoreLockHeldInRealm } from "./trust-store-writers.js"; export { hasTrustRequiringProjectResources, projectAgentsSkillDirs } from "./trust-requiring-resources.js"; function normalizeCwd(cwd) { const resolved = resolvePath(cwd); try { return canonicalizePathStrict(resolved); } catch { // A workspace path the filesystem will not confirm must not be keyed by its raw // spelling: that is how a decision recorded for one directory leaks to another // that merely writes the same way. Returning the resolved-but-unconfirmed path // keeps the lookup total, and because no stored key can match a location the // kernel does not agree on, the effect is "ask again" rather than "inherit". return resolved; } } /** * The nearest entry at or above `cwd`. An explicit `null` saved for a folder (`set_project_trust`'s `no_inherit`) is an * entry as well: it holds no decision, and the walk stops there, so neither a folder above it nor, for a linked * worktree, the main checkout decides for it. Readers older than that skip a `null` and keep walking: they inherit as * before, and never fail on it. */ function findNearestTrustEntry(data, cwd) { let currentDir = normalizeCwd(cwd); while (true) { const value = data[currentDir]; if (value === true || value === false || value === null) { return { path: currentDir, decision: value }; } const parentDir = dirname(currentDir); if (parentDir === currentDir) { return null; } currentDir = parentDir; } } export function getProjectTrustParentPath(cwd) { const trustPath = normalizeCwd(cwd); const parentDir = dirname(trustPath); return parentDir === trustPath ? undefined : parentDir; } export function getProjectTrustOptions(cwd, options) { const trustPath = normalizeCwd(cwd); const trustOptions = [ { label: "Trust", trusted: true, updates: [{ path: trustPath, decision: true }], savedPath: trustPath }, ]; const parentPath = getProjectTrustParentPath(cwd); if (parentPath !== undefined) { trustOptions.push({ label: `Trust parent folder (${parentPath})`, trusted: true, updates: [ { path: parentPath, decision: true }, { path: trustPath, decision: null }, ], savedPath: parentPath, }); } if (options?.includeSessionOnly) { trustOptions.push({ label: "Trust (this session only)", trusted: true, updates: [] }); } trustOptions.push({ label: "Do not trust", trusted: false, updates: [{ path: trustPath, decision: false }], savedPath: trustPath, }); if (options?.includeSessionOnly) { trustOptions.push({ label: "Do not trust (this session only)", trusted: false, updates: [] }); } return trustOptions; } /** * `set_project_trust`'s `no_inherit`: no decision for the folder, and none inherited from a folder above it or, for a * linked worktree, from its main checkout, so the folder is decided as if nothing were saved (Full access trusts it, * a session that may ask asks). `/trust` never offers it. */ export function getProjectTrustNoInheritOption(cwd) { const trustPath = normalizeCwd(cwd); return { label: "No decision, and none inherited", trusted: false, updates: [{ path: trustPath, decision: "no_inherit" }], savedPath: trustPath, }; } function readTrustFile(path) { if (!existsSync(path)) { return {}; } let parsed; try { parsed = JSON.parse(stripBom(readFileSync(path, "utf-8"))); } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new Error(`Failed to read trust store ${path}: ${message}`); } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { throw new Error(`Invalid trust store ${path}: expected an object`); } const data = {}; for (const [key, value] of Object.entries(parsed)) { if (value !== true && value !== false && value !== null) { throw new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`); } data[key] = value; } return data; } function writeTrustFile(path, data) { const sorted = {}; for (const key of Object.keys(data).sort()) { const value = data[key]; if (value === true || value === false || value === null) { sorted[key] = value; } } mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, `${JSON.stringify(sorted, null, 2)}\n`, "utf-8"); } function acquireTrustLockSync(path) { const trustDir = dirname(path); mkdirSync(trustDir, { recursive: true }); const maxAttempts = 10; const delayMs = 20; let lastError; for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return lockfile.lockSync(trustDir, { realpath: false, lockfilePath: `${path}.lock` }); } catch (error) { const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : undefined; if (code !== "ELOCKED" || attempt === maxAttempts) { throw error; } lastError = error; const start = Date.now(); while (Date.now() - start < delayMs) { // Sleep synchronously to avoid changing trust store callers to async. } } } if (lastError instanceof Error) { throw lastError; } throw new Error("Failed to acquire trust store lock"); } function absentAsUndefined(error) { if (fsErrorCode(error) === "ENOENT") return undefined; throw error; } function withTrustFileLock(path, fn) { if (trustStoreLockHeldInRealm(path)) return fn(); const release = acquireTrustLockSync(path); try { return fn(); } finally { release(); } } /** * Runs `write` holding the store lock across its awaits, after every earlier write of this realm. The lock is taken * and recorded as this realm's in one synchronous step, so a synchronous reader of the realm never meets it unrecorded. */ function withTrustFileWriteLock(path, write) { return inTrustStoreWriteTurn(path, async () => { const release = acquireTrustLockSync(path); const releaseHold = holdTrustStoreLockInRealm(path); try { await write(); } finally { releaseHold(); release(); } }); } export class ProjectTrustStore { constructor(agentDir) { this.trustPath = join(resolvePath(agentDir), "trust.json"); this.generationPath = `${this.trustPath}.generation`; } /** * Changes on every write made through `setMany` by an engine that has this generation file, in any process or * engine copy: each such write bumps it under the store lock before it writes `trust.json`, so a value read * before the write never equals one read after it. Any other writer (an older engine sharing the agent * directory, another program editing `trust.json`) changes it only when it changes the file's modification * time or size. */ async revision() { const stats = await stat(this.trustPath, { bigint: true }).catch(absentAsUndefined); return `${await this.readGeneration()}:${stats === undefined ? "absent" : `${stats.mtimeNs}:${stats.size}`}`; } async readGeneration() { const text = await readFile(this.generationPath, "utf-8").catch(absentAsUndefined); if (text === undefined) return 0; const generation = Number.parseInt(text, 10); return Number.isSafeInteger(generation) && generation >= 0 ? generation : 0; } get(cwd) { return this.getNearestEntry(cwd)?.decision ?? null; } /** The nearest saved decision at or above `cwd`; `null` also when the nearest entry holds no decision. */ getEntry(cwd) { const entry = this.getNearestEntry(cwd); return entry === null || entry.decision === null ? null : { path: entry.path, decision: entry.decision }; } getNearestEntry(cwd) { return withTrustFileLock(this.trustPath, () => { const data = readTrustFile(this.trustPath); return findNearestTrustEntry(data, cwd); }); } async set(cwd, decision) { await this.setMany([{ path: cwd, decision }]); } async setMany(decisions) { await withTrustFileWriteLock(this.trustPath, async () => { const data = readTrustFile(this.trustPath); for (const { path, decision } of decisions) { const key = normalizeCwd(path); if (decision === null) { delete data[key]; } else { data[key] = decision === "no_inherit" ? null : decision; } } // Bumped first and replaced whole: a failed bump saves nothing, and a reader never sees a half-written count. const nextGeneration = `${this.generationPath}.next`; await writeFile(nextGeneration, `${(await this.readGeneration()) + 1}\n`, "utf-8"); await rename(nextGeneration, this.generationPath); writeTrustFile(this.trustPath, data); }); } } /** * What is saved for `cwd`: the store's own entry (the folder or the nearest folder above it), and only * when it has none and `cwd` is inside a linked git worktree, the main checkout's entry for the * matching folder. An entry saved for the worktree or above it always wins, including the explicit * no-decision entry, which leaves the folder undecided. */ export async function getSavedProjectTrustState(store, cwd) { const own = store.getNearestEntry(cwd); if (own !== null) return own.decision ?? "no_inherit"; const mainCheckoutDir = await linkedWorktreeMainCheckoutDir(cwd); if (mainCheckoutDir === undefined) return null; const main = store.getNearestEntry(mainCheckoutDir); return main === null ? null : (main.decision ?? "no_inherit"); } /** The saved decision for `cwd` (`getSavedProjectTrustState`), with both undecided values as `null`. */ export async function getSavedProjectTrust(store, cwd) { const saved = await getSavedProjectTrustState(store, cwd); return saved === "no_inherit" ? null : saved; } //# sourceMappingURL=trust-manager.js.map