@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
5 lines (4 loc) • 9.4 kB
JavaScript
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{HOST_INSTANCE_ID_ENV,ORIGIN_HOST_INSTANCE_ENV,presentInstanceId}from"./chunk-IDTQWHTP.js";import{ProcessIdentityUnreadableError,processMatchesPidFile,readProcessStartTime}from"./chunk-YWBNR4MT.js";import{createHmac,timingSafeEqual}from"node:crypto";var RPC_AUTH_CAPABILITY="socket_auth",RPC_AUTH_HEX=/^[a-f0-9]{64}$/,RPC_LAUNCH_ID=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,RPC_LAUNCH_PROOF_RECORD="launch_proven";function launchProofRecordRefusal(id){return{...id===void 0?{}:{id},type:"response",command:RPC_LAUNCH_PROOF_RECORD,success:!1,error:"reserved_record",errorCode:"reserved_record"}}function rpcAuthProof(key,label,...parts){return createHmac("sha256",key).update([`senpi-rpc-${label}`,...parts].join(`
`),"utf8").digest("hex")}function rpcProofMatches(expected,received){return typeof received=="string"&&RPC_AUTH_HEX.test(received)&&timingSafeEqual(Buffer.from(expected,"hex"),Buffer.from(received,"hex"))}var RpcEndpointAuthError=class extends Error{constructor(code,detail,options){super(`${code}: ${detail}`,options),this.code=code,this.name="RpcEndpointAuthError"}};function authRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}var OBSERVE_REQUEST_FIELD="observe",WATCH_HOST_OCCUPANCY="watch_host_occupancy",HOST_OCCUPANCY_RECORD="host_occupancy",ORIGIN_HOST_INSTANCE_FIELD="origin_host_instance",HOLD_HOST_FIELD="hold_host",OBSERVING_COMMANDS=new Set(["get_protocol_info","get_snapshot","list_sessions","subscribe_sessions","unsubscribe_sessions","get_effect_status","get_pending_inputs","get_subscription_limits","get_state","get_entries",WATCH_HOST_OCCUPANCY]);function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record=request;return record.type==="warm"||record.type==="park_session"||record.type==="authenticate"||record.type===RPC_LAUNCH_PROOF_RECORD?!0:record[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record.type)}function observingHoldChange(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let record=request;if(record[OBSERVE_REQUEST_FIELD]!==!0||!OBSERVING_COMMANDS.has(record.type))return;let hold=record[HOLD_HOST_FIELD];return typeof hold=="boolean"?hold:void 0}function isHostOccupancyWatch(line){if(!line.includes(WATCH_HOST_OCCUPANCY))return!1;try{let request=JSON.parse(line);return typeof request=="object"&&request!==null&&Reflect.get(request,"type")===WATCH_HOST_OCCUPANCY}catch{return!1}}function hostOccupancyHolders(line){if(!line.includes(HOST_OCCUPANCY_RECORD))return;let record;try{record=JSON.parse(line)}catch{return}if(typeof record!="object"||record===null||Reflect.get(record,"type")!==HOST_OCCUPANCY_RECORD)return;let holders=Reflect.get(record,"holders");return typeof holders=="number"&&Number.isSafeInteger(holders)&&holders>=0?holders:void 0}function originHostInstance(env=process.env){return presentInstanceId(env[HOST_INSTANCE_ID_ENV])??presentInstanceId(env[ORIGIN_HOST_INSTANCE_ENV])}function requestOriginHostInstance(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let origin=Reflect.get(request,ORIGIN_HOST_INSTANCE_FIELD);return typeof origin=="string"&&origin.length>0?origin:void 0}import{randomBytes,randomUUID}from"node:crypto";import{constants,unlinkSync}from"node:fs";import*as fs from"node:fs/promises";import{join}from"node:path";var MAX_KEY_RECORD_BYTES=4096;async function checkRpcKeyDirectory(path,privateKeys=!1){let checked=privateKeys?path:await fs.realpath(path),problem=keyDirectoryProblem(await fs.lstat(checked),checked,privateKeys);if(problem!==void 0)throw new RpcEndpointAuthError("unsafe_key_record",`${checked} ${problem}`)}function keyDirectoryProblem(info,path,privateKeys){if(!info.isDirectory())return"is not a directory";if(info.uid!==process.getuid?.())return"is not owned by this user";let mode=info.mode&4095;return privateKeys?mode===448?void 0:`must be mode 0700 (is 0${mode.toString(8)}); run: chmod 700 ${path}`:(mode&18)===0?void 0:`is writable by group or others; run: chmod go-w ${path}`}async function checkRpcKeyParents(root){await checkRpcKeyDirectory(root),await checkRpcKeyDirectory(join(root,"rpc"))}async function readRpcKeyRecord(root,launchId){if(!RPC_LAUNCH_ID.test(launchId))throw new RpcEndpointAuthError("unsafe_key_record",`invalid launch id under ${root}`);let path=join(root,"rpc","keys",launchId);try{await checkRpcKeyParents(root),await checkRpcKeyDirectory(join(root,"rpc","keys"),!0);let handle=await fs.open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{let info=await handle.stat();if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&4095)!==384||info.size>MAX_KEY_RECORD_BYTES)throw new RpcEndpointAuthError("unsafe_key_record",path);let record=authRecord(JSON.parse(await handle.readFile("utf8")));if(record?.version!==1||record.launch_id!==launchId||typeof record.key!="string"||!RPC_AUTH_HEX.test(record.key))throw new RpcEndpointAuthError("unsafe_key_record",path);return record}finally{await handle.close()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause instanceof RpcEndpointAuthError?cause:new RpcEndpointAuthError("unsafe_key_record",path,{cause})}}var RpcPublicEndpoint=class{constructor(agentDir,endpoint){this.key=randomBytes(32),this.launchId=randomUUID(),this.publication=Promise.withResolvers(),this.created=!1,this.exitCleanup=()=>{if(this.created)try{unlinkSync(this.recordPath)}catch(cause){cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"||process.stderr.write(`senpi rpc host: could not remove own endpoint key record
`)}},this.agentDir=agentDir,this.endpoint=endpoint,this.recordPath=join(agentDir,"rpc","keys",this.launchId),this.ready=this.publication.promise,this.ready.catch(()=>{})}async publish(){try{await fs.mkdir(join(this.agentDir,"rpc"),{recursive:!0,mode:448}),await checkRpcKeyParents(this.agentDir);let keys=join(this.agentDir,"rpc","keys");await fs.mkdir(keys,{recursive:!0,mode:448});let directory=await fs.lstat(keys);if(!directory.isDirectory()||directory.uid!==process.getuid?.())throw new RpcEndpointAuthError("unsafe_key_record",keys);(directory.mode&4095)!==448&&await fs.chmod(keys,448),await checkRpcKeyDirectory(keys,!0);let handle=await fs.open(this.recordPath,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,384);this.created=!0,process.once("exit",this.exitCleanup);try{await handle.writeFile(JSON.stringify({version:1,launch_id:this.launchId,key:this.key.toString("hex"),pid:process.pid,process_start:await readProcessStartTime(process.pid)??null,endpoint:this.endpoint,created_at:new Date().toISOString()})),await handle.sync();let info=await handle.stat();if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&4095)!==384)throw new RpcEndpointAuthError("unsafe_key_record",this.recordPath)}finally{await handle.close()}this.publication.resolve()}catch(cause){let error=new RpcEndpointAuthError("key_publication_failed",cause instanceof RpcEndpointAuthError?cause.message:this.recordPath,{cause});throw this.publication.reject(error),error}}async dispose(){process.off("exit",this.exitCleanup),this.created&&(this.created=!1,await fs.unlink(this.recordPath).catch(cause=>{if(!(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"))throw cause}))}};async function gcRpcPublicKeys(agentDir,budget={}){let keys=join(agentDir,"rpc","keys");try{await checkRpcKeyParents(agentDir),await checkRpcKeyDirectory(keys,!0)}catch(cause){if(cause instanceof RpcEndpointAuthError||cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause}let names=await fs.readdir(keys).catch(cause=>{if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return[];throw cause}),examined=0;for(let name of names){if(Date.now()>=(budget.deadline??1/0)||examined>=(budget.maxRecords??1/0))break;if(RPC_LAUNCH_ID.test(name)){examined++;try{let record=await readRpcKeyRecord(agentDir,name);if(record===void 0||typeof record.pid!="number"||!Number.isSafeInteger(record.pid)||record.pid<=0||!(record.process_start===null||typeof record.process_start=="string")||await processMatchesPidFile({pid:record.pid,processStartTime:record.process_start}))continue;await fs.unlink(join(keys,name))}catch(cause){if(cause instanceof ProcessIdentityUnreadableError||cause instanceof RpcEndpointAuthError||cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")continue;throw cause}}}}export{RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RPC_LAUNCH_ID,RPC_LAUNCH_PROOF_RECORD,launchProofRecordRefusal,rpcAuthProof,rpcProofMatches,RpcEndpointAuthError,authRecord,OBSERVE_REQUEST_FIELD,WATCH_HOST_OCCUPANCY,HOST_OCCUPANCY_RECORD,ORIGIN_HOST_INSTANCE_FIELD,isObservingRequest,observingHoldChange,isHostOccupancyWatch,hostOccupancyHolders,originHostInstance,requestOriginHostInstance,readRpcKeyRecord,RpcPublicEndpoint,gcRpcPublicKeys};