UNPKG

@code-yeongyu/senpi

Version:

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

5 lines (4 loc) • 7.52 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{resolveSocketTransportAddress}from"./chunk-HW6AAS3R.js";import{execFile as execFile2}from"node:child_process";import{lstat,mkdir,readFile,rename,unlink,writeFile}from"node:fs/promises";import{createConnection}from"node:net";import{dirname}from"node:path";import{execFile}from"node:child_process";import{stat}from"node:fs/promises";var SCAN_TIMEOUT_MS=5e3;async function socketHoldersByIdentity(identity){let listing=await new Promise(resolve=>{execFile("lsof",["-U","-w","-F","pn"],{timeout:SCAN_TIMEOUT_MS,maxBuffer:67108864},(error,out)=>{let code=error===null?void 0:Reflect.get(error,"code");resolve(error===null||code===1?String(out):void 0)})});if(listing===void 0)return;let pids=new Set,sameInode=new Map,pid;for(let line of listing.split(` `)){if(line.startsWith("p")&&(pid=Number(line.slice(1))),!line.startsWith("n/")||pid===void 0||!Number.isInteger(pid))continue;let name=line.slice(1).replace(/ type=\S+.*$/,""),same=sameInode.get(name);if(same===void 0){let entry=await stat(name).catch(()=>{});same=entry!==void 0&&entry.dev===identity.dev&&entry.ino===identity.ino,sameInode.set(name,same)}same&&pids.add(pid)}return[...pids]}var PUBLIC_SOCKET_IDENTITY_FILE="public-socket.owner",SOCKET_IDENTITY_WAIT_MS=3e4,MAX_SOCKET_PATH_BYTES=103,BIND_SCRATCH_INFIX=".bind-",BIND_SCRATCH_SOCKET="s";function isBindScratchName(name){return/\.bind-[0-9a-f]{12}$/.test(name)}function generationBindPath(publicSocket,generation){return`${publicSocket}.next-${generation}`}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function sameSocketIdentity(a,b){return a.dev===b.dev&&a.ino===b.ino}function classifyConnectError(code,platform){return code==="ENOENT"?"gone":code==="ECONNREFUSED"?platform==="linux"?"dead":"confirm-holder":"live"}var HOLDER_PROBE_TIMEOUT_MS=5e3,lsofSocketHolders=async socketPath=>{let byPath=await lsofHoldersByPath(socketPath);if(byPath===void 0||byPath.length>0)return byPath;let entry=await lstat(socketPath).catch(()=>{});return entry!==void 0&&entry.nlink>1?socketHoldersByIdentity(entry):byPath},lsofHoldersByPath=socketPath=>new Promise(resolve=>{execFile2("lsof",["-t","--",socketPath],{timeout:HOLDER_PROBE_TIMEOUT_MS},(error,stdout)=>{let pids=String(stdout).split(/\s+/).filter(part=>/^\d+$/.test(part)).map(Number);if(pids.length>0)return resolve(pids);let exitCode=error===null?void 0:Reflect.get(error,"code");resolve(error===null||exitCode===1?[]:void 0)})}),CONNECT_PROBE_TIMEOUT_MS=2e3;function connectOnce(socketPath){return new Promise(resolve=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform)),settle=value=>{socket.destroy(),resolve(value)};socket.setTimeout(CONNECT_PROBE_TIMEOUT_MS,()=>settle({code:"timeout"})),socket.once("connect",()=>settle({connected:!0})),socket.once("error",cause=>settle({code:cause.code}))})}async function socketEntryListenerState(socketPath,platform=process.platform,holders=lsofSocketHolders){let attempt=await connectOnce(socketPath);if("connected"in attempt)return{verdict:"live",evidence:"accepting connections"};let verdict=classifyConnectError(attempt.code,platform);if(verdict!=="confirm-holder")return{verdict,evidence:`connect ${attempt.code??"failed"}`};let pids=await holders(socketPath);return pids===void 0?{verdict:"live",evidence:"connect ECONNREFUSED, holders unknown"}:pids.length>0?{verdict:"live",evidence:`connect ECONNREFUSED, held open by pid ${pids.join(",")}`}:{verdict:"dead",evidence:"connect ECONNREFUSED, held by nobody"}}async function statSocketIdentity(socketPath){try{let{dev,ino}=await lstat(socketPath);return{dev,ino}}catch(cause){if(isNodeErrorCode(cause,"ENOENT"))return;throw cause}}async function classifyEndpointOwnership(socketPath,identity){if(identity===void 0||process.platform==="win32"||socketPath.startsWith("\0"))return"unknown";let current;try{current=await statSocketIdentity(socketPath)}catch{return"unknown"}return current===void 0?"absent":sameSocketIdentity(current,identity)?"held":"replaced"}async function socketEntryReplaced(socketPath,identity){return await classifyEndpointOwnership(socketPath,identity)==="replaced"}async function writeSocketIdentityFile(path,identity){await mkdir(dirname(path),{recursive:!0,mode:448});let tmpPath=`${path}.${process.pid}.tmp`;await writeFile(tmpPath,`${JSON.stringify(identity)} `,{mode:384}),await rename(tmpPath,path)}async function readSocketIdentityFile(path){let raw;try{raw=await readFile(path,"utf8")}catch(cause){if(isNodeErrorCode(cause,"ENOENT"))return;throw cause}let parsed;try{parsed=JSON.parse(raw)}catch{return}if(!(typeof parsed!="object"||parsed===null||typeof parsed.dev!="number"||typeof parsed.ino!="number"))return{dev:parsed.dev,ino:parsed.ino}}async function waitForSocketIdentityFile(path,timeoutMs=SOCKET_IDENTITY_WAIT_MS,intervalMs=25){let deadline=Date.now()+timeoutMs;for(;;){let identity=await readSocketIdentityFile(path);if(identity!==void 0)return identity;if(Date.now()>=deadline)return;await delayUnrefed(intervalMs)}}async function unlinkOwnedSocket(socketPath,identity,log){if(process.platform==="win32"||socketPath.startsWith("\0"))return;let current;try{current=await statSocketIdentity(socketPath)}catch(cause){log(`socket ${socketPath} ownership could not be verified (${errorMessage(cause)}); leaving it`);return}if(current!==void 0){if(identity===void 0){log(`socket path ${socketPath} ownership unknown; leaving it`);return}if(!sameSocketIdentity(current,identity)){log(`socket path ${socketPath} now owned by another host; leaving it`);return}try{await unlink(socketPath)}catch(cause){isNodeErrorCode(cause,"ENOENT")||log(`socket ${socketPath} removal failed (${errorMessage(cause)})`)}}}async function shieldSocketDuringClose(socketPath,close){if(process.platform==="win32"||socketPath.startsWith("\0"))return close();let shieldPath=`${socketPath}.shield-${process.pid}`,shielded=!1;try{await statSocketIdentity(socketPath)!==void 0&&(await rename(socketPath,shieldPath),shielded=!0)}catch{}try{await close()}finally{if(shielded)try{await rename(shieldPath,socketPath)}catch{}}}function delayUnrefed(ms){return new Promise(resolve=>{setTimeout(resolve,ms).unref?.()})}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}async function adoptPublicSocket(bindSocket,publicSocket,expected){if(expected===void 0)throw new Error(`${publicSocket}: a generation launch must name the entry it replaces`);let current=await statSocketIdentity(publicSocket);if(current===void 0||current.dev!==expected.dev||current.ino!==expected.ino)throw new Error(`${publicSocket}: owned by another socket entry now; refusing to replace it`);await rename(bindSocket,publicSocket)}export{PUBLIC_SOCKET_IDENTITY_FILE,MAX_SOCKET_PATH_BYTES,BIND_SCRATCH_INFIX,BIND_SCRATCH_SOCKET,isBindScratchName,generationBindPath,parseSocketIdentity,socketEntryListenerState,statSocketIdentity,classifyEndpointOwnership,socketEntryReplaced,writeSocketIdentityFile,readSocketIdentityFile,waitForSocketIdentityFile,unlinkOwnedSocket,shieldSocketDuringClose,adoptPublicSocket};