UNPKG

@code-yeongyu/senpi

Version:

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

3 lines (2 loc) • 8.79 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } } import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{constants}from"node:fs";import{chmod,link,mkdir,open,readFile,realpath,rename,unlink,writeFile}from"node:fs/promises";import{basename,dirname,join,win32}from"node:path";import{stat}from"node:fs/promises";var LegacyLockArtifactError=class extends Error{constructor(lockPath){super(`Legacy lock directory is present at ${lockPath}`),this.code="ELEGACY_LOCK_ARTIFACT",this.name="LegacyLockArtifactError",this.lockPath=lockPath}},DEFAULT_RETRIES={retries:100,minTimeout:20,maxTimeout:100};async function openLockDatabase(lockPath){if(typeof globalThis.Bun<"u"){let{Database}=await import("bun:sqlite"),database2=new Database(lockPath,{create:!0});return{exec:sql=>database2.exec(sql),close:()=>database2.close(!1)}}let{DatabaseSync}=await import("node:sqlite"),database=new DatabaseSync(lockPath);return{exec:sql=>database.exec(sql),close:()=>database.close()}}async function acquireOwnershipSafeLock(lockPath,options={}){let retries=options.retries??DEFAULT_RETRIES,deadline=Date.now()+retries.retries*retries.maxTimeout;for(;;){await rejectLegacyDirectory(lockPath);let busyMs=Math.max(1,Math.min(retries.maxTimeout,deadline-Date.now())),database;try{database=await openLockDatabase(lockPath),database.exec(`PRAGMA busy_timeout = ${busyMs}; BEGIN EXCLUSIVE;`);let released=!1,held=database;return async()=>{if(!released){released=!0;try{held.exec("COMMIT;")}finally{held.close()}}}}catch(error){try{database?.close()}catch{}if(await rejectLegacyDirectory(lockPath),isBusy(error)&&Date.now()<deadline){await new Promise(resolve=>setTimeout(resolve,Math.min(retries.minTimeout,Math.max(1,deadline-Date.now()))));continue}throw error}}}async function rejectLegacyDirectory(lockPath){try{if((await stat(lockPath)).isDirectory())throw new LegacyLockArtifactError(lockPath)}catch(error){if(error instanceof LegacyLockArtifactError||error.code!=="ENOENT")throw error}}function isBusy(error){let message=error instanceof Error?error.message:String(error);return/busy|locked/i.test(message)||error?.code==="SQLITE_BUSY"}var WINDOWS_PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",SOCKET_SECRET_BYTES=32,SOCKET_SECRET_SUFFIX=".secret",SOCKET_SECRET_FILE_ENV="SENPI_RPC_SOCKET_SECRET_FILE",SOCKET_HANDSHAKE_TIMEOUT_MS=2e3;function socketSecretPath(logicalPath){if(logicalPath.toLowerCase().startsWith("\\\\.\\pipe\\"))throw new Error(`Windows RPC named-pipe addresses need a logical filesystem path for their secret: ${logicalPath}`);return`${logicalPath}${SOCKET_SECRET_SUFFIX}`}async function ensureSocketSecret(path){let existing=await readSecretEntry(path);if(existing?.length===SOCKET_SECRET_BYTES)return existing;await mkdir(dirname(path),{recursive:!0,mode:448});let release=await acquireOwnershipSafeLock(await socketSecretLockPath(path));try{let current=await readSecretEntry(path);if(current?.length===SOCKET_SECRET_BYTES)return current;if(process.platform==="win32")return await writeSocketSecretInPlace(path);let candidate=randomBytes(SOCKET_SECRET_BYTES);if(current===void 0){if(await publishSocketSecretIfAbsent(path,candidate)==="published")return candidate;let winner=await readSecretEntry(path);if(winner?.length===SOCKET_SECRET_BYTES)return winner;throw new Error(`RPC socket secret is invalid and was not replaced: ${path}`)}return await replaceSocketSecret(path,candidate),candidate}finally{await release()}}async function readSecretEntry(path){let handle;try{handle=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0))}catch(error){if(isNodeErrorCode(error,"ENOENT"))return;throw isNodeErrorCode(error,"ELOOP")?new Error(`RPC socket secret is not a regular file: ${path}`):error}try{if(!(await handle.stat()).isFile())throw new Error(`RPC socket secret is not a regular file: ${path}`);let buffer=Buffer.alloc(SOCKET_SECRET_BYTES+1),length=0;for(;length<buffer.length;){let{bytesRead}=await handle.read(buffer,length,buffer.length-length,null);if(bytesRead===0)break;length+=bytesRead}return buffer.subarray(0,length)}finally{await handle.close()}}async function createSocketSecret(path){if(process.platform==="win32")return writeSocketSecretInPlace(path);await mkdir(dirname(path),{recursive:!0,mode:448});let candidate=randomBytes(SOCKET_SECRET_BYTES);if(await readSecretEntry(path)===void 0&&await publishSocketSecretIfAbsent(path,candidate)==="published")return candidate;let winner=await readSecretEntry(path);if(winner?.length!==SOCKET_SECRET_BYTES)throw new Error(`RPC socket secret is invalid and was not replaced: ${path}`);return winner}async function publishSocketSecretIfAbsent(path,candidate){let staging=stagingPath(path);await writeStaging(staging,candidate);try{return await link(staging,path),await syncDirectory(dirname(path)),"published"}catch(error){if(isNodeErrorCode(error,"EEXIST"))return"collision";throw error}finally{await unlink(staging).catch(error=>{if(!isNodeErrorCode(error,"ENOENT"))throw error})}}async function writeStaging(staging,candidate){let handle=await open(staging,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|(constants.O_NOFOLLOW??0),384),failure;try{await handle.chmod(384);let offset=0;for(;offset<candidate.length;){let{bytesWritten}=await handle.write(candidate,offset,candidate.length-offset,null);if(bytesWritten===0)throw new Error(`short write to the RPC socket secret staging file: ${staging}`);offset+=bytesWritten}await handle.sync()}catch(error){failure=error}if(await handle.close().catch(error=>{failure??=error}),failure!==void 0)throw await unlink(staging).catch(()=>{}),failure}async function syncDirectory(dir){let handle=await open(dir,constants.O_RDONLY);try{await handle.sync()}finally{await handle.close()}}async function socketSecretLockPath(path){let lockPath=join(await realpath(dirname(path)),`${basename(path)}.publish.lock`),handle=await open(lockPath,constants.O_RDONLY|constants.O_CREAT|(constants.O_NOFOLLOW??0),384);try{if(!(await handle.stat()).isFile())throw new Error(`RPC socket secret lock is not a regular file: ${lockPath}`)}finally{await handle.close()}return lockPath}async function replaceSocketSecret(path,candidate){let staging=stagingPath(path);await writeStaging(staging,candidate);try{await rename(staging,path)}catch(error){throw await unlink(staging).catch(()=>{}),error}await syncDirectory(dirname(path))}function stagingPath(path){return join(dirname(path),`.${basename(path)}.stage-${process.pid}-${randomBytes(8).toString("hex")}`)}async function writeSocketSecretInPlace(path){await mkdir(dirname(path),{recursive:!0});let secret=randomBytes(SOCKET_SECRET_BYTES);return await writeFile(path,secret,{mode:384}),await chmod(path,384),secret}async function readSocketSecret(path){let secret=await readFile(path);if(secret.length!==SOCKET_SECRET_BYTES)throw new Error(`invalid RPC socket secret: ${path}`);return secret}function resolveSocketTransportAddress(socketPath,platform,secret){if(platform!=="win32"||socketPath.toLowerCase().startsWith("\\\\.\\pipe\\"))return socketPath;if(!/^[a-zA-Z]:[\\/]/.test(socketPath)&&!/^\\\\[^/]/.test(socketPath))throw new Error(`Windows RPC socket path must be drive-qualified or UNC: ${socketPath}`);let canonical=win32.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret??[])]),name=createHash("sha256").update(identity).digest("hex").slice(0,32);return`${WINDOWS_PIPE_PREFIX}${name}`}function authenticateSocket(socket,secret,onAuthenticated){let received=Buffer.alloc(0),finish=()=>{clearTimeout(timer),socket.off("data",onData),socket.off("error",onError)},onError=()=>{finish(),socket.destroy()},timer=setTimeout(()=>{finish(),socket.destroy()},SOCKET_HANDSHAKE_TIMEOUT_MS),onData=chunk=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(finish(),!timingSafeEqual(received.subarray(0,secret.length),Buffer.from(secret))){socket.destroy();return}let remainder=received.subarray(secret.length);remainder.length>0&&socket.unshift(remainder),onAuthenticated()};socket.on("data",onData),socket.once("error",onError),socket.once("close",finish)}function sendSocketHandshake(socket,secret){socket.write(Buffer.from(secret))}function isNodeErrorCode(error,code){return error instanceof Error&&"code"in error&&error.code===code}export{acquireOwnershipSafeLock,isBusy,SOCKET_SECRET_BYTES,SOCKET_SECRET_FILE_ENV,SOCKET_HANDSHAKE_TIMEOUT_MS,socketSecretPath,ensureSocketSecret,createSocketSecret,readSocketSecret,resolveSocketTransportAddress,authenticateSocket,sendSocketHandshake};