UNPKG

@code-yeongyu/senpi

Version:

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

8 lines (7 loc) • 17.9 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{envValue,normalizePath,shortenPath}from"./chunk-QJTWAOBX.js";var EventLoopSlicer=class{constructor(options={}){this.budgetMs=options.budgetMs??8,this.clock=options.clock??(()=>performance.now()),this.sliceStart=this.clock()}get due(){return this.clock()-this.sliceStart>=this.budgetMs}async yield(){await new Promise(resolve=>setImmediate(resolve)),this.sliceStart=this.clock()}};async function mapInSlices(items,transform,slicer){let mapped=[];for(let item of items)mapped.push(transform(item)),slicer.due&&await slicer.yield();return mapped}import{randomUUID}from"node:crypto";function blockCallKey(messageId,contentIndex){return`blk:${messageId}:${contentIndex}`}var executionKeys=new WeakMap;function executionCallKey(record){return executionKeys.get(record)}function carryExecutionCallKey(from,to){let key=executionKeys.get(from);key!==void 0&&from!==to&&executionKeys.set(to,key)}function toolCallBlocks(content){return Array.isArray(content)?content.flatMap((part,index)=>{let id=typeof part=="object"&&part!==null?Reflect.get(part,"id"):void 0;return Reflect.get(Object(part),"type")==="toolCall"&&typeof id=="string"?[[index,id]]:[]}):[]}var BridgedCallKeys=class{constructor(){this.open=!1,this.seen=new Set,this.waiting=new Map,this.bridged=new Map,this.keyed=new Map}observe(event){let assistant=event.message?.role==="assistant";if(event.type==="message_start"&&assistant)this.open=!0,this.seen=new Set,this.waiting=new Map,this.bridged=new Map,this.keyed=new Map;else if((event.type==="message_update"||event.type==="message_end")&&assistant){for(let[index,id]of toolCallBlocks(event.message?.content))this.block(index,id);event.type==="message_end"&&(this.open=!1)}else if(event.type==="tool_execution_start"&&this.open){let id=event.toolCallId;if(typeof id!="string"||event.parentToolCallId!==void 0)return;let waiting=this.waiting.get(id)??0;if(waiting>0)return void this.waiting.set(id,waiting-1);let key=`exe:${randomUUID()}`;this.bridged.set(id,[...this.bridged.get(id)??[],key]),executionKeys.set(event,key)}}take(){let taken=this.keyed;return this.keyed=new Map,taken}block(index,id){if(this.seen.has(index)||id==="")return;this.seen.add(index);let[key,...rest]=this.bridged.get(id)??[];if(key===void 0)return void this.waiting.set(id,(this.waiting.get(id)??0)+1);this.bridged.set(id,rest),this.keyed.set(index,key)}};import{createHash}from"node:crypto";import{close,fstat}from"node:fs";function captureFileIdentity(fd,path){return new Promise(resolve=>{fstat(fd,{bigint:!0},(error,stat)=>{resolve(error?void 0:{path,dev:String(stat.dev),ino:String(stat.ino)})})})}async function captureAndCloseFileIdentity(fd,path){let identity=await captureFileIdentity(fd,path);return new Promise(resolve=>close(fd,error=>resolve(error?void 0:identity)))}var loadedFileIdentities=new WeakMap,BASE_CONTENT_DOMAIN="senpi-recovery-base/1/sha256",BaseContentHash=class{constructor(){this.hash=createHash("sha256").update(`${BASE_CONTENT_DOMAIN}\0`)}line(text){this.hash.update(text).update(` `)}digest(){return this.hash.digest("hex")}},loadedContentFingerprints=new WeakMap;import{randomUUID as randomUUID2}from"node:crypto";import{closeSync,fchmodSync,fsyncSync,openSync,realpathSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";var UNSUPPORTED_DIRECTORY_SYNC=new Set(["EINVAL","ENOTSUP","EOPNOTSUPP","EISDIR"]),DIRECTORY_NOT_WRITABLE=new Set(["EACCES","EPERM","EROFS"]);function errnoCode(error){return error instanceof Error&&"code"in error&&typeof error.code=="string"?error.code:void 0}function resolveTarget(filePath){try{let path=realpathSync(filePath);return{path,mode:statSync(path).mode&4095}}catch(error){if(errnoCode(error)==="ENOENT")return{path:filePath,mode:void 0};throw error}}function openTemp(tempPath){try{return openSync(tempPath,"wx")}catch(error){let code=errnoCode(error);if(code!==void 0&&DIRECTORY_NOT_WRITABLE.has(code))return;throw error}}function rewriteInPlace(path,chunks,capture){let fd=openSync(path,"w");try{for(let chunk of chunks)writeFileSync(fd,chunk)}finally{capture?capture(captureAndCloseFileIdentity(fd,path)):closeSync(fd)}}function writeDurably(fd,chunks,mode,path,capture){try{mode!==void 0&&fchmodSync(fd,mode);for(let chunk of chunks)writeFileSync(fd,chunk);fsyncSync(fd)}finally{capture?capture(captureAndCloseFileIdentity(fd,path)):closeSync(fd)}}function syncDirectory(directory){if(process.platform==="win32")return;let fd=openSync(directory,"r");try{fsyncSync(fd)}catch(error){let code=errnoCode(error);if(code===void 0||!UNSUPPORTED_DIRECTORY_SYNC.has(code))throw error}finally{closeSync(fd)}}function replaceFileAtomically(filePath,chunks,capture){let identity,captured=capture?value=>{identity=value}:void 0,target=resolveTarget(filePath),tempPath=join(dirname(target.path),`.${basename(target.path)}.${randomUUID2()}.tmp`),tempFd=openTemp(tempPath);if(tempFd===void 0){rewriteInPlace(target.path,chunks,captured),identity&&capture?.(identity);return}try{writeDurably(tempFd,chunks,target.mode,filePath,captured),renameSync(tempPath,target.path)}catch(error){try{rmSync(tempPath,{force:!0})}catch(cleanupError){throw new AggregateError([error,cleanupError],"session file rewrite failed and its temporary file could not be removed")}throw error}syncDirectory(dirname(target.path)),identity&&capture?.(identity)}import{randomUUID as randomUUID3}from"node:crypto";import{closeSync as closeSync2,fstatSync,ftruncateSync,openSync as openSync2,readSync,rmSync as rmSync2}from"node:fs";import{rm}from"node:fs/promises";var NEWLINE=10,SCAN_CHUNK_BYTES=64*1024,DISK_FULL_CODES=new Set(["ENOSPC","EDQUOT"]);function sessionRecoveryCause(error){let current=error;for(let depth=0;depth<8&&current instanceof Error;depth++){if("code"in current&&typeof current.code=="string"&&DISK_FULL_CODES.has(current.code))return"disk_full";current=current.cause}return"write_failed"}function recoveryNotice(cause,backupPath){let shortened=shortenPath(backupPath),backup=shortened.startsWith("~/")||shortened.startsWith("~\\")?shortened:"a session recovery backup";return cause==="disk_full"?`The last message wasn't saved because the disk was full. Free disk space to keep saving this session; the incomplete record was kept in ${backup}.`:cause==="write_failed"?`The last message wasn't saved because writing the session file failed. The incomplete record was kept in ${backup}.`:`The last message of this session wasn't saved completely (an earlier save was interrupted, for example by a full disk). Everything before it was loaded; the incomplete record was kept in ${backup}.`}function backupTornBytes(path,bytes,cause){let backupPath=`${path}.torn-${Date.now()}-${randomUUID3().slice(0,8)}`;return replaceFileAtomically(backupPath,[bytes]),{cause,backupPath,droppedBytes:bytes.length,notice:recoveryNotice(cause,backupPath)}}function truncateToLastCompleteLine(path,cause){let fd=openSync2(path,"r+");try{let size=fstatSync(fd).size,chunk=Buffer.alloc(Math.min(SCAN_CHUNK_BYTES,size)),tail=[],end=size;for(;end>0;){let start=Math.max(0,end-chunk.length),read=readSync(fd,chunk,0,end-start,start),newline=chunk.subarray(0,read).lastIndexOf(NEWLINE);if(newline>=0){let completeLength=start+newline+1;if(completeLength>=size)return;tail.unshift(Buffer.from(chunk.subarray(newline+1,read)));let recovery=backupTornBytes(path,Buffer.concat(tail),cause);return ftruncateSync(fd,completeLength),recovery}tail.unshift(Buffer.from(chunk.subarray(0,read))),end=start}return}finally{closeSync2(fd)}}function discardFailedFirstFlush(path,fd,writeError){let cleanupErrors=[];try{closeSync2(fd)}catch(closeError){cleanupErrors.push(closeError)}try{rmSync2(path,{force:!0})}catch(removeError){cleanupErrors.push(removeError)}throwWriteError(path,writeError,cleanupErrors)}async function discardFailedFirstFlushAsync(path,handle,writeError){let cleanupErrors=[];if(handle!==void 0)try{await handle.close()}catch(closeError){cleanupErrors.push(closeError)}try{await rm(path,{force:!0})}catch(removeError){cleanupErrors.push(removeError)}throwWriteError(path,writeError,cleanupErrors)}function throwWriteError(path,writeError,cleanupErrors){throw cleanupErrors.length>0?new AggregateError([writeError,...cleanupErrors],`Session file write failed and the partial file ${path} could not be cleaned up`):writeError}import{closeSync as closeSync3,existsSync,fstatSync as fstatSync2,ftruncateSync as ftruncateSync2,openSync as openSync3,readSync as readSync2,statSync as statSync2,writeSync}from"node:fs";import{open}from"node:fs/promises";import{StringDecoder}from"node:string_decoder";var SESSION_READ_BUFFER_SIZE=1024*1024;function parseSessionEntryLine(line){if(!line.trim())return null;try{return JSON.parse(line)}catch{return null}}var SessionLineSplitter=class{constructor(){this.decoder=new StringDecoder("utf8"),this.pending=""}push(chunk){this.pending+=this.decoder.write(chunk);let lines=[],lineStart=0,newlineIndex=this.pending.indexOf(` `,lineStart);for(;newlineIndex!==-1;)lines.push(this.pending.slice(lineStart,newlineIndex)),lineStart=newlineIndex+1,newlineIndex=this.pending.indexOf(` `,lineStart);return this.pending=this.pending.slice(lineStart),lines}finish(){return this.pending+this.decoder.end()}};function countEntry(entries,line,content){let entry=parseSessionEntryLine(line);entry&&(entries.push(entry),content?.line(line))}function acceptSessionEntries(entries){if(entries.length===0)return entries;let header=entries[0];return header?.type!=="session"||typeof header.id!="string"?[]:entries}function loadEntriesFromFile(filePath,captureIdentity=!1){return acceptSessionEntries(readRawEntriesFromFile(filePath,captureIdentity))}var isSessionShapedEntry=entry=>{let candidate=entry;return typeof candidate.type=="string"&&candidate.type!=="session"&&typeof candidate.id=="string"&&(candidate.parentId===null||typeof candidate.parentId=="string")};function readForkSource(filePath){let raw=readRawEntriesFromFile(filePath);if(raw.length===0)return{kind:"empty"};let accepted=acceptSessionEntries(raw);return accepted.length>0?{kind:"session",entries:accepted}:raw.every(isSessionShapedEntry)?{kind:"headerless",entries:raw}:{kind:"not-a-session"}}function readRawEntriesFromFile(filePath,captureIdentity=!1){let resolvedFilePath=normalizePath(filePath);if(!existsSync(resolvedFilePath))return[];let entries=[],splitter=new SessionLineSplitter,content=captureIdentity?new BaseContentHash:void 0,fd=openSync3(resolvedFilePath,"r");try{let buffer=Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE);for(;;){let bytesRead=readSync2(fd,buffer,0,buffer.length,null);if(bytesRead===0)break;for(let line of splitter.push(buffer.subarray(0,bytesRead)))countEntry(entries,line,content)}countEntry(entries,splitter.finish(),content)}finally{captureIdentity?loadedFileIdentities.set(entries,captureAndCloseFileIdentity(fd,resolvedFilePath)):closeSync3(fd)}return content&&loadedContentFingerprints.set(entries,content.digest()),entries}async function loadEntriesFromFileAsync(filePath,slicer=new EventLoopSlicer,captureIdentity=!1){let resolvedFilePath=normalizePath(filePath);if(!existsSync(resolvedFilePath))return[];let entries=[],splitter=new SessionLineSplitter,content=captureIdentity?new BaseContentHash:void 0,handle=await open(resolvedFilePath,"r");try{let buffer=Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE);for(;;){let{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0)break;for(let line of splitter.push(buffer.subarray(0,bytesRead)))countEntry(entries,line,content),slicer.due&&await slicer.yield()}countEntry(entries,splitter.finish(),content),content&&loadedContentFingerprints.set(entries,content.digest())}finally{if(captureIdentity){let identity=captureFileIdentity(handle.fd,resolvedFilePath);loadedFileIdentities.set(entries,identity),await identity}await handle.close()}return acceptSessionEntries(entries)}function terminateFinalSessionLine(filePath,cause="unknown"){if(!existsSync(filePath)||!statSync2(filePath).isFile())return;let fd=openSync3(filePath,"r+");try{let size=fstatSync2(fd).size,segmentStart=finalSegmentStart(fd,size);if(segmentStart===size)return;let segment=Buffer.alloc(size-segmentStart);if(readSync2(fd,segment,0,segment.length,segmentStart),parseSessionEntryLine(segment.toString("utf8"))!==null){writeSync(fd,` `,size);return}let recovery;try{recovery=backupTornBytes(filePath,segment,cause)}catch(error){if(error instanceof Error)return{kind:"deferred"};throw error}return ftruncateSync2(fd,segmentStart),{kind:"set_aside",recovery}}finally{closeSync3(fd)}}function finalSegmentStart(fd,size){let chunk=Buffer.alloc(Math.min(65536,size)),end=size;for(;end>0;){let start=Math.max(0,end-chunk.length),read=readSync2(fd,chunk,0,end-start,start),newline=chunk.subarray(0,read).lastIndexOf(10);if(newline>=0)return start+newline+1;end=start}return 0}var SESSION_ARCHIVED_CUSTOM_TYPE="session_archived";function sessionMarkerData(entry,customType,sessionId){if(entry.type!=="custom"||entry.customType!==customType)return;let data=entry.data;return data?.sessionId===sessionId?data:void 0}function archivedFlagOf(entry,sessionId){let data=sessionMarkerData(entry,SESSION_ARCHIVED_CUSTOM_TYPE,sessionId);return data===void 0?void 0:data.archived===!0}function isSessionArchived(manager){return manager.isArchived()}function setSessionArchived(manager,archived){manager.appendCustomEntry(SESSION_ARCHIVED_CUSTOM_TYPE,{archived,sessionId:manager.getSessionId()})}var SESSION_SETTLED_CUSTOM_TYPE="session_settled",NOT_SETTLED={settled:!1},BY_REFUSAL="set_session_settled: by must be a ThreadSettledBy (kind user, agent, pr-merged, pr-closed or inactivity, with its fields)";function isIntegerAtLeast(value,minimum){return typeof value=="number"&&Number.isInteger(value)&&value>=minimum}function optionalText(value){if(value===void 0)return;let text=typeof value=="string"?value.trim():"";return text===""?null:text}function parseThreadSettledBy(value){if(typeof value!="object"||value===null)return;let by=value,kind=by.kind;switch(kind){case"user":return{kind};case"agent":{let threadId=optionalText(by.threadId),threadTitle=optionalText(by.threadTitle);return threadId===null||threadTitle===null?void 0:{kind,...threadId!==void 0?{threadId}:{},...threadTitle!==void 0?{threadTitle}:{}}}case"pr-merged":case"pr-closed":{let pullRequestNumber=by.pullRequestNumber;return pullRequestNumber===void 0?{kind}:isIntegerAtLeast(pullRequestNumber,1)?{kind,pullRequestNumber}:void 0}case"inactivity":{let days=by.days;return isIntegerAtLeast(days,0)?{kind,days}:void 0}default:return}}function parseSessionSettled(command){if(typeof command.settled!="boolean")return{ok:!1,error:"set_session_settled: settled must be a boolean"};if(command.by===void 0)return{ok:!0,value:{settled:command.settled}};let by=parseThreadSettledBy(command.by);return by===void 0?{ok:!1,error:BY_REFUSAL}:{ok:!0,value:command.settled?{settled:!0,by}:NOT_SETTLED}}function settledStateOf(entry,sessionId){let data=sessionMarkerData(entry,SESSION_SETTLED_CUSTOM_TYPE,sessionId);if(data===void 0)return;if(data.settled!==!0)return NOT_SETTLED;let by=parseThreadSettledBy(data.by);return by===void 0?{settled:!0}:{settled:!0,by}}function settledFields(state){return state.settled&&state.by!==void 0?{settled:!0,settledBy:state.by}:{settled:state.settled}}function readSessionSettled(manager){return manager.getSettled()}function setSessionSettled(manager,state){manager.appendCustomEntry(SESSION_SETTLED_CUSTOM_TYPE,{settled:state.settled,...state.settled&&state.by!==void 0?{by:state.by}:{},at:new Date().toISOString(),sessionId:manager.getSessionId()})}function compactUpdatesEnabled(){let value=envValue("ENGINE_SOCKET_COMPACT_UPDATES");return value==="1"||value==="true"}import{createHash as createHash2}from"node:crypto";var TranscriptJournal=class{constructor(){this.pending=[]}record(...transitions){this.pending.push(...transitions)}drain(){let taken=this.pending;return this.pending=[],taken}},fingerprintLine=entry=>`${entry.type}\0${entry.id} `;function fingerprint(entries){let hash=createHash2("sha256");for(let entry of entries)hash.update(fingerprintLine(entry));return hash.digest("hex")}var entryParent=entry=>entry.type==="session"?null:entry.parentId;function captureTranscriptBase(entries){return{count:entries.length,idFingerprint:fingerprint(entries),history:entries.filter(entry=>entry.type!=="session").length}}function snapshotTranscript(state){return state.unpersisted===void 0?[{kind:"unavailable",reason:"transcript_tail_trimmed"}]:state.unpersisted.some(entry=>typeof entry.id!="string")?[{kind:"unavailable",reason:"transcript_entry_unidentified"}]:[{kind:"replace",base:state.base},...state.unpersisted.map(entry=>({kind:"append",id:entry.id,type:entry.type,parentId:entryParent(entry),...state.persistence?{persistence:state.persistence}:{entry:state.own(entry)}})),{kind:"leaf",leafId:state.leafId}]}export{EventLoopSlicer,mapInSlices,blockCallKey,executionCallKey,carryExecutionCallKey,BridgedCallKeys,captureFileIdentity,captureAndCloseFileIdentity,loadedFileIdentities,BaseContentHash,loadedContentFingerprints,replaceFileAtomically,sessionRecoveryCause,truncateToLastCompleteLine,discardFailedFirstFlush,discardFailedFirstFlushAsync,parseSessionEntryLine,SessionLineSplitter,loadEntriesFromFile,readForkSource,loadEntriesFromFileAsync,terminateFinalSessionLine,archivedFlagOf,isSessionArchived,setSessionArchived,NOT_SETTLED,parseSessionSettled,settledStateOf,settledFields,readSessionSettled,setSessionSettled,compactUpdatesEnabled,TranscriptJournal,fingerprintLine,captureTranscriptBase,snapshotTranscript};