UNPKG

@code-yeongyu/senpi

Version:

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

93 lines • 3.24 kB
import { closeSync, existsSync, mkdirSync, openSync, rmSync, statSync } from "node:fs"; import { LegacyLockAcquireError, withLegacyLock } from "./legacy-lock.js"; export function adoptLegacyRecord(options) { // Nothing to migrate needs no lock: every request's token lookup lands here when a server has no saved grant. if (!existsSync(options.legacyTokens)) return undefined; const release = acquireSync(options); try { return claim(options); } finally { release(); } } export async function readRecordAsync(options) { const record = options.read(options.tokensPath); if (record !== undefined) return record; if (!existsSync(options.legacyTokens)) return undefined; if (options.disableLock) return claim(options); mkdirSync(options.rootDir, { mode: 0o700, recursive: true }); try { return await withLegacyLock(options.lockPath, options.stale, () => claim(options)); } catch (cause) { if (cause instanceof LegacyLockAcquireError) throw options.lockError(cause.cause); throw cause; } } function claim(options) { const legacy = options.read(options.legacyTokens); if (legacy === undefined) return undefined; const existing = options.read(options.tokensPath); if (existing !== undefined) { rmSync(options.legacyTokens, { force: true }); return existing; } options.write(legacy); rmSync(options.legacyTokens, { force: true }); return legacy; } function acquireSync(options) { if (options.disableLock) return () => undefined; mkdirSync(options.rootDir, { mode: 0o700, recursive: true }); const deadline = Date.now() + options.stale; for (;;) { let fd; try { fd = openSync(options.lockPath, "wx", 0o600); const file = fd; return () => { try { closeSync(file); } catch { // A caller may already have closed its descriptor. } rmSync(options.lockPath, { force: true }); }; } catch (cause) { if (fd !== undefined) closeSync(fd); if (!(cause instanceof Error) || !("code" in cause) || cause.code !== "EEXIST") throw cause; let age; try { age = Date.now() - statSync(options.lockPath).mtimeMs; } catch (error) { if (error instanceof Error && "code" in error && error.code === "ENOENT") continue; throw error; } if (age >= options.stale) { rmSync(options.lockPath, { force: true }); continue; } if (Date.now() >= deadline) throw options.lockError(new Error(`legacy migration lock held for ${age}ms`)); const until = Date.now() + 20; while (Date.now() < until) { // Preserve the synchronous API; background preparation uses readRecordAsync. } } } } //# sourceMappingURL=legacy-migration.js.map