@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
4 lines (3 loc) • 41.2 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{SessionEventWriter,answerSubscribeSessions,answerUnsubscribeSessions,drainFacts,drainUntilQuiet,fenceForClose,gracefulWaitMs,presenterContextReply,recordGracefulClose,refusal,reopenAfterDrain,socketSink,startMcpPresenterControl}from"./chunk-NOJJLIHF.js";import{CONNECTION_ROLE_FIXED,ConnectionRoles,MAX_RPC_MESSAGE_CHARACTERS,TerminalSealedSecrets,WakeScheduler,admitExternalMessage,admitExternalMessageFieldError,answerGetEntries,answeredUiRequestId,availableModelsData,buildRpcSessionState,getSnapshot,interruptBackgroundError,interruptRunningTurn,onProcessContinue,remoteOriginDeclaration,rpcCommandShapeError,runAbort,runGetEffectStatus,sessionRuntimeView,sessionUiAnswerLedger,settledQuestionStatus,subscribeSessionRecords,unansweredQuestionIds,unsupportedThinkingLevel,watchInbox}from"./chunk-VHOAN5G5.js";import{RPC_ERROR_INVALID_ARGUMENT}from"./chunk-ARIPHUYY.js";import"./chunk-TQHNFP77.js";import"./chunk-XI6THO4F.js";import{isSessionArchived,parseSessionSettled,readSessionSettled,setSessionArchived,setSessionSettled,settledFields}from"./chunk-4R7JSL3B.js";import"./chunk-7AEFFKBD.js";import"./chunk-5QZIEDOI.js";import"./chunk-MOVB6H22.js";import{ENTRIES_TAIL_CAPABILITY,INTERACTIVE_USER_CAPABILITY,OBSERVE_READS_CAPABILITY,SESSION_STATUS_CAPABILITY,TUI_OBSERVER_CAPABILITY,UNLOAD_GRACEFUL_CAPABILITY,describeRpcMethodClasses,engineBuildIdentity,gcHostEndpoints}from"./chunk-OPUPPWQY.js";import"./chunk-QMRJYMNH.js";import"./chunk-BICMCIHT.js";import"./chunk-2C4UHQNO.js";import"./chunk-26UBFF6N.js";import"./chunk-4SA7RJES.js";import{tuiSocketName}from"./chunk-E25CXSWH.js";import"./chunk-7WYJAYHH.js";import{acquireHostEnsureLock,thisProcessStartTime,writeHostRegistration}from"./chunk-O5NRXQZ2.js";import{createDaemonDirectories,createHostDaemonPaths}from"./chunk-2ZYJNMJZ.js";import"./chunk-YQHLIPNR.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-NJ43NBSP.js";import"./chunk-DPNC7S74.js";import"./chunk-OBXBNBXE.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-7K42R46I.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-QD45L5SP.js";import"./chunk-WDTJ6JKE.js";import"./chunk-AFDUWYAX.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-42XRJQM6.js";import{MAX_SOCKET_PATH_BYTES}from"./chunk-5XHOHZIR.js";import{authenticateSocket,createSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-HW6AAS3R.js";import"./chunk-IDTQWHTP.js";import{VERSION}from"./chunk-QJTWAOBX.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIKPY3E7.js";import"./chunk-YWBNR4MT.js";import"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{rm as rm3}from"node:fs/promises";var ControlAttachments=class{constructor(session,pendingQuestions,presenters){this.writer=new SessionEventWriter(()=>{}),this.roles=new ConnectionRoles,this.receipts=new Map,this.attached=new Set,this.session=session,this.presenters=presenters,this.writer.status.setSource({sessionIds:()=>[this.handle],entryView:id=>id===this.handle?this.entryView():void 0,view:id=>id===this.handle?{entry:this.entryView(),runtime:sessionRuntimeView(session,pendingQuestions())}:void 0}),this.writer.registerConnection(NULL_CONNECTION,{writeRaw:()=>{},waitForBackpressure:async()=>{}}),this.stopRecords=subscribeSessionRecords(session,record=>this.writer.enqueue(this.handle,record))}get handle(){return this.session.sessionId}opened(connection){this.writer.registerConnection(keyOf(connection),connection.transport),this.presenters?.opened(keyOf(connection),connection.transport)}closed(connection){let key=keyOf(connection);this.attached.delete(key)&&this.writer.status.publish(this.handle,"detach","client"),this.roles.release(key),this.presenters?.closed(key),this.writer.unregisterConnection(key)}detach(connection){let key=keyOf(connection);return this.attached.delete(key)?(this.presenters?.detach(key),this.writer.detachConnectionFromSession(key,this.handle),this.writer.status.publish(this.handle,"detach","client"),!0):!1}attach(connection){let key=keyOf(connection);return this.attached.has(key)?!1:(this.attached.add(key),this.presenters?.attach(key),this.writer.attachConnectionToSession(key,this.handle),this.writer.status.publish(this.handle,"attach","client"),!0)}isAttached(connection){return this.attached.has(keyOf(connection))}run(connection,task){return this.writer.withConnection(keyOf(connection),task)}respond(connection,answer2){this.writer.enqueueControl(answer2,keyOf(connection)).catch(()=>connection.transport.close?.())}dispose(){this.stopRecords()}entryView(){let manager=this.session.sessionManager,path=this.session.sessionFile,name=manager.getSessionName();return{state:"open",kind:"interactive",cwd:manager.getCwd(),attachments:1+this.attached.size,durableSessionId:this.session.sessionId,...path!==void 0?{sessionPath:path}:{},...name!==void 0?{name}:{},archived:isSessionArchived(manager),settled:settledFields(readSessionSettled(manager)),context:{}}}},NULL_CONNECTION="tui-null";function keyOf(connection){return`tui-${connection.id}`}import{chmod}from"node:fs/promises";import{createServer}from"node:net";async function listenControlSocket(socketPath,secret,handlers){let clients=new Set,nextConnection=0,server=createServer(socket=>{clients.add(socket),socket.once("close",()=>clients.delete(socket)),socket.on("error",()=>socket.destroy()),authenticateSocket(socket,secret,()=>acceptConnection(socket,++nextConnection,handlers))});return await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(resolveSocketTransportAddress(socketPath,process.platform,secret),()=>{server.off("error",reject),resolve2()})}),server.on("error",error=>handlers.listenerError(error)),process.platform!=="win32"&&await chmod(socketPath,384),{close:()=>closeServer(server,clients)}}function acceptConnection(socket,id,handlers){let connection={id,send:record=>{handlers.respond!==void 0?handlers.respond(connection,record):socket.destroyed||socket.write(serializeJsonLine(record))},transport:socketSink(socket)};handlers.opened?.(connection);let detach=attachJsonlLineReader(socket,line=>{answer(connection,line,handlers)},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>connection.send(failure(void 0,"parse","RPC line exceeds the size limit."))});socket.once("close",()=>{detach(),handlers.closed(connection)})}async function answer(connection,line,handlers){let parsed;try{parsed=JSON.parse(line)}catch{connection.send(failure(void 0,"parse","Invalid JSON."));return}let shapeError=rpcCommandShapeError(parsed);if(shapeError!==void 0||!isCommand(parsed)){connection.send(failure(void 0,"parse",shapeError??"RPC command needs a string `type`."));return}let answer2=await handlers.command(connection,parsed);answer2!==null&&connection.send(answer2)}function isCommand(value){return typeof value=="object"&&value!==null&&"type"in value&&typeof value.type=="string"}function failure(id,command,error){return{...id===void 0?{}:{id},type:"response",command,success:!1,error}}function success(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,...data===void 0?{}:{data}}}function closeServer(server,clients){for(let client of clients)client.destroy();return new Promise(resolve2=>server.close(()=>resolve2()))}var COMMAND="unload_session",DRAFT_ACTION="send or clear the composer in that terminal, then close it again",EXPIRED_ACTION="the terminal is still open and admitting again: retry with a longer waitMs, or interrupt its turn first";function terminalBusy(session){let activity=session.activitySnapshot;return[activity.isStreaming&&"an agent run",activity.isCompacting&&"compaction",activity.hasSessionWork&&"session work",activity.isBashRunning&&"a bash command",session.externalAdmission.list().pending.length>0&&"an admitted delivery not yet written"].filter(label=>typeof label=="string")}function refusedDraft(context,command,drain){return success(command.id,COMMAND,{outcome:"refused",reason:"composer_draft",detail:"the terminal's composer holds an unsent draft; closing would discard it",action:DRAFT_ACTION,...drain===void 0?{}:{dropped:drain.dropped,open:!0,admission:"reopened"}})}async function closeTerminalGracefully(context,connection,command){let{session,surface}=context;if(command.graceful!==!0)return success(command.id,COMMAND,{outcome:"refused",reason:"unsupported",detail:"a terminal's own session closes only with graceful: true, and its terminal then exits"});if(surface.hasDraft())return refusedDraft(context,command);let drain=fenceForClose(session),waitMs=gracefulWaitMs(typeof command.waitMs=="number"?command.waitMs:void 0);if(!await drainUntilQuiet(session,{busy:()=>terminalBusy(session),settling:()=>[]},waitMs))return reopenAfterDrain(session),success(command.id,COMMAND,{outcome:"refused",reason:"turn_active",detail:`still working after ${waitMs} ms: ${terminalBusy(session).join(", ")}`,action:EXPIRED_ACTION,dropped:drain.dropped,timed_out:!0,open:!0,admission:"reopened",...drainFacts(session,drain)});if(surface.hasDraft())return reopenAfterDrain(session),refusedDraft(context,command,drain);let closed=recordGracefulClose(session,drain);return connection.send(success(command.id,COMMAND,{outcome:"unloaded",sessionPath:session.sessionFile??null,dropped:drain.dropped,graceful:{turn:closed.turn,waited_ms:closed.waited_ms,stopped:closed.stopped}})),surface.closeSession(),null}import{realpathSync}from"node:fs";import{resolve}from"node:path";import{randomUUID}from"node:crypto";function idOf(command){return typeof command.id=="string"?command.id:void 0}function answered(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,data}}function admitPrompt(context,command){let behavior=command.streamingBehavior;return behavior===void 0&&context.session.isStreaming?refusal(idOf(command),"prompt","session_busy",{reason:"a turn is running and the prompt names no streamingBehavior",action:'send it with streamingBehavior "steer" or "followUp", or as a steer/follow_up'}):admitInput(context,command,behavior==="followUp"?"followUp":"steer","start")}var UNSERVED_INPUT_FIELDS=["images","thinkingLevel","expandPromptTemplates","unknownCommandAsText","sessionTitlePrompt","enqueueOrder","chainCount","expectedLeafId"];function admitInput(context,command,deliverAs,whenIdle){let id=idOf(command),unserved=UNSERVED_INPUT_FIELDS.filter(field=>command[field]!==void 0);if(unserved.length>0)return refusal(id,command.type,"unsupported_field",{reason:`a terminal delivers input through its admission, which carries text only, not ${unserved.join(", ")}`,action:"send the message without those fields, or send it to a host session"});let message=command.message;if(typeof message!="string"||message.trim()==="")return refusal(id,command.type,"invalid_message",{reason:"message is empty",action:"send a non-empty message"});if(whenIdle!==void 0&&whenIdle!=="queue"&&whenIdle!=="start")return refusal(id,command.type,"invalid_when_idle",{reason:`whenIdle must be "queue" or "start", not ${JSON.stringify(whenIdle)}`,action:'send whenIdle: "queue" (the default) or "start"'});let admission=context.session.externalAdmission,clientMessageId=typeof command.clientMessageId=="string"?command.clientMessageId:void 0,fingerprint=JSON.stringify([command.type,message,deliverAs,whenIdle??null]),prior=clientMessageId===void 0?void 0:context.attachments.receipts.get(clientMessageId);if(prior!==void 0)return prior.fingerprint!==fingerprint?refusal(id,command.type,"client_message_id_conflict",{reason:`clientMessageId ${clientMessageId} was already used for different input`,action:"send new input with a new clientMessageId"}):answered(id,command.type,{disposition:prior.disposition,clientMessageId,replayed:!0,duplicate:!0,admission:prior.admission});let expected=typeof command.expected_turn_id=="number"?command.expected_turn_id:admission.turnEpoch,result=admission.admit({delivery_id:clientMessageId??`tui-rpc-${randomUUID()}`,text:message,sender:{kind:"external",platform:"rpc"},deliverAs,expected_turn_id:expected,whenIdle:whenIdle==="start"?"start":"queue"}),identity=clientMessageId===void 0?{}:{clientMessageId},admitted=disposition=>{let holds=result.holds===void 0?{}:{holds:[...result.holds]};if(clientMessageId===void 0)return answered(id,command.type,{disposition,...holds});let receipt={fingerprint,disposition,admission:{clientMessageId,durableSessionId:context.session.sessionId,disposition}};return context.attachments.receipts.set(clientMessageId,receipt),answered(id,command.type,{disposition,clientMessageId,admission:receipt.admission,...holds})};switch(result.kind){case"started":return admitted("started");case"held":return admitted("held");case"steered":case"queued":return admitted("queued");case"already_admitted":return answered(id,command.type,{disposition:"queued",duplicate:!0,...identity});case"held_draft":return refusal(id,command.type,"held_draft",{reason:"input the user submitted in this terminal has not reached the runtime yet, so nothing was delivered",action:"retry once that input was taken"});case"turn_conflict":return refusal(id,command.type,"turn_conflict",{reason:`the turn moved on (now ${result.turn_epoch}); this steer named an earlier one`,action:"read get_state's turn_epoch and send it again"})}}function setClientInfo(attachments,connection,command){let key=keyOf(connection),origin=remoteOriginDeclaration(command.remoteOrigin,declared=>attachments.roles.acceptsOrigin(key,declared));if("refusal"in origin)return failure(command.id,"set_client_info",origin.refusal);let capabilities=command.capabilities;if(capabilities!==void 0){if(!Array.isArray(capabilities)||!capabilities.every(entry=>typeof entry=="string"))return failure(command.id,"set_client_info","capabilities must be an array of strings");if(attachments.roles.declare(key,capabilities)!=="declared")return failure(command.id,"set_client_info",CONNECTION_ROLE_FIXED);attachments.presenters?.declare(key,capabilities)}return origin.origin!==void 0&&attachments.roles.declareOrigin(key,origin.origin),success(command.id,"set_client_info")}function admitTerminalDelivery(session,attachments,connection,command){let key=keyOf(connection),answer2=admitExternalMessage(session,command,{origin:attachments.roles.originOf(key),connectionOrigin:attachments.roles.isDelegated(key)?"delegated":"local"}),{id}=command;if(answer2.ok)return success(id,command.type,answer2.data);let{refusal:refusal2}=answer2;return{...failure(id,command.type,refusal2.message),errorCode:refusal2.errorCode,..."errorData"in refusal2&&refusal2.errorData!==void 0?{errorData:refusal2.errorData}:{}}}import{rm}from"node:fs/promises";var TERMINAL_PRESENTER_COMMANDS=["mcp_presenter_context","mcp_form_presented","mcp_form_response","mcp_form_sync","mcp_presenter_secret_answer"];async function startTerminalPresenters(presenter){let surface=new TerminalPresenterSurface(presenter.local),started=await startMcpPresenterControl(surface,{enforcement:!0,account:presenter.account});return{surface,dispose:async()=>{started?.control.dispose(),started?.dir&&await rm(started.dir,{recursive:!0,force:!0})}}}function presents(capabilities){return capabilities.includes("interactive_user")&&capabilities.includes("mcp_form_presenter_v1")}function writePrivate(transport,record){try{return transport.writeRaw(serializeJsonLine(record)),!0}catch{return!1}}var TerminalPresenterSurface=class{constructor(local){this.sharedAuthority=!0,this.peers=new Map,this.local=local,this.authority=local.authority,this.binding=local.binding,this.sessionId=local.sessionId}attachSealedSecrets(source){let sealed=new TerminalSealedSecrets(source,this.sessionId,this.local.admit);return this.local.sealed=sealed,()=>{this.local.sealed===sealed&&(this.local.sealed=void 0),sealed.dispose()}}getMcpFormBinding(sessionId){return sessionId===this.sessionId?this.binding:void 0}findMcpPresenterConnection(nonce){for(let peer of this.peers.values())if(peer.sender?.nonce===nonce)return peer.sender}getConnectionCapabilities(id){return this.peers.get(id)?.capabilities}advertiseMcpPresenterControl(path){this.controlEndpoint=path}withdrawMcpPresenterControl(path){this.controlEndpoint===path&&(this.controlEndpoint=void 0)}opened(id,transport){this.peers.set(id,{transport,capabilities:[],attached:!1})}declare(id,capabilities){let peer=this.peers.get(id);if(peer){if(peer.capabilities=[...capabilities],!presents(capabilities)){peer.sender&&this.authority.withdraw(peer.sender);return}if(!peer.sender){let sender=this.authority.connect(id,frame=>this.peers.get(id)!==peer||!writePrivate(peer.transport,frame)?(this.authority.detach(sender),!1):(peer.transport.waitForBackpressure().catch(()=>this.authority.detach(sender)),!0));peer.sender=sender}peer.attached&&this.authority.attach(peer.sender,this.binding)}}attach(id){let peer=this.peers.get(id);peer&&(peer.attached=!0,peer.sender&&this.authority.attach(peer.sender,this.binding))}detach(id){let peer=this.peers.get(id);peer&&(peer.attached=!1,peer.sender&&this.authority.detach(peer.sender,this.binding))}closed(id){let sender=this.peers.get(id)?.sender;this.peers.delete(id),sender&&this.authority.detach(sender)}receive(id,frame){let peer=this.peers.get(id);if(!peer)return;if(frame.type==="mcp_presenter_secret_answer"){let lineId=typeof frame.id=="string"?{id:frame.id}:{};(this.local.sealed?.receive(id,frame)??Promise.resolve({error:"secret_answer_refused"})).catch(()=>({error:"secret_answer_refused"})).then(reply2=>{!writePrivate(peer.transport,{type:"mcp_presenter_secret_reply",...lineId,...reply2})&&peer.sender&&this.authority.detach(peer.sender)});return}let sender=peer.sender,reply=frame.type==="mcp_presenter_context"?presenterContextReply(this.authority,sender,frame,this.controlEndpoint):sender?this.authority.receive(sender,frame):{error:"presenter_not_authorized"},answer2={type:"mcp_form_reply",...typeof frame.id=="string"?{id:frame.id}:{},...reply};!writePrivate(peer.transport,answer2)&&sender&&this.authority.detach(sender)}};var TUI_RPC_COMMANDS=["open_session","park_session","claim_session","get_snapshot","subscribe_sessions","unsubscribe_sessions","steer","follow_up","prompt","admit_external_message","get_effect_status","set_client_info","attach_session","release_attachment","abort",...TERMINAL_PRESENTER_COMMANDS],STOP_REQUIRES_INTERACTIVE_CLIENT="stop_requires_interactive_client: declare interactive_user with set_client_info first";async function runTuiRpcCommand(context,connection,command){switch(command.type){case"get_snapshot":{let{attachments,session}=context;if(command.sessionId!==void 0&&command.sessionId!==attachments.handle)return{id:command.id,type:"response",command:command.type,success:!1,error:"unknown_session"};let snapshot=getSnapshot(session,{tail:command.tail,maxBytes:command.maxBytes},{enqueue:markerId=>attachments.run(connection,()=>attachments.writer.enqueue(attachments.handle,{type:"snapshot_marker",markerId}))});return"error"in snapshot?{id:command.id,type:"response",command:command.type,success:!1,error:snapshot.error}:answered(idOf(command),command.type,snapshot.data)}case"open_session":return openSession(context,connection,command);case"park_session":case"claim_session":return failure(idOf(command),command.type,"multi_session_disabled");case"subscribe_sessions":return subscribe(context,connection,command);case"unsubscribe_sessions":return answerUnsubscribeSessions(command,keyOf(connection),context.attachments.writer.status);case"steer":case"follow_up":return admitInput(context,command,command.type==="steer"?"steer":"followUp",command.whenIdle);case"prompt":return admitPrompt(context,command);case"admit_external_message":{let fieldError=admitExternalMessageFieldError(command,MAX_RPC_MESSAGE_CHARACTERS);return fieldError!==void 0?failure(idOf(command),command.type,fieldError):admitTerminalDelivery(context.session,context.attachments,connection,command)}case"set_client_info":return setClientInfo(context.attachments,connection,command);case"attach_session":return attachSession(context,connection,command);case"release_attachment":return releaseAttachment(context,connection,command);case"abort":return abort(context,connection,command);case"mcp_presenter_context":case"mcp_form_presented":case"mcp_form_response":case"mcp_form_sync":case"mcp_presenter_secret_answer":return context.attachments.presenters?(context.attachments.presenters.receive(keyOf(connection),command),null):void 0;case"get_effect_status":return runGetEffectStatus({session:context.session,by:{connectionId:keyOf(connection)},sessionId:context.attachments.handle},command);default:return}}function openSession(context,connection,command){let{session,attachments}=context,ownPath=typeof command.sessionPath=="string"&&samePath(command.sessionPath,session.sessionFile),ownId=command.sessionId!==void 0&&command.sessionId===session.sessionId;return!ownPath&&!ownId?refusal(idOf(command),"open_session","terminal_single_session",{reason:"this terminal hosts one session and the request names another",action:"open it by this terminal's sessionPath, or open the other session on a host"}):(attachments.run(connection,()=>{attachments.attach(connection),attachments.writer.enqueue(attachments.handle,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:attachments.handle,state:buildRpcSessionState(session),attached:!0}})}),null)}function attachSession(context,connection,command){let{session,attachments}=context,id=idOf(command);if(command.sessionId!==attachments.handle)return refusal(id,"attach_session","unknown_session",{reason:"this terminal hosts one session and the request names another",action:"attach with this terminal's sessionId from list_sessions"});let instanceMatches=command.expectedHostInstance===void 0||command.expectedHostInstance===context.instanceId;return command.durableSessionId!==session.sessionId||!instanceMatches?refusal(id,"attach_session","session_identity_mismatch",{reason:"durableSessionId or expectedHostInstance does not name this terminal's session",action:"read list_sessions and get_protocol_info again, then attach with their ids"}):command.takeover===!0?refusal(id,"attach_session","takeover_unsupported",{reason:"only a headless engine with a takeover ledger takes sessions over",action:"attach without takeover"}):(attachments.run(connection,()=>{attachments.attach(connection),attachments.writer.enqueue(attachments.handle,{id:command.id,type:"response",command:"attach_session",success:!0,data:{sessionId:attachments.handle,attached:!0}})}),null)}function releaseAttachment(context,connection,command){return command.sessionId!==context.attachments.handle||!context.attachments.detach(connection)?refusal(idOf(command),"release_attachment","session_not_attached",{reason:"this connection is not attached to that session",action:"attach first with attach_session or open_session"}):success(command.id,"release_attachment",{deferred:!1})}async function abort(context,connection,command){let key=keyOf(connection);if(command.intent==="stop"&&!context.attachments.roles.has(key,INTERACTIVE_USER_CAPABILITY))return failure(command.id,"abort",STOP_REQUIRES_INTERACTIVE_CLIENT);let{session}=context;return runAbort({session,by:{connectionId:key},sessionId:context.attachments.handle},command,()=>(command.intent==="stop"?session.stop():session.abort()).catch(cause=>{connection.send({type:"rpc_error",error:String(cause)})}))}function subscribe(context,connection,command){let{writer}=context.attachments,key=keyOf(connection),{answer:answer2,activate}=answerSubscribeSessions(command,key,writer.status);return activate===void 0?answer2:(writer.enqueueControl(answer2,key).then(()=>{writer.hasConnection(key)?writer.status.activate(activate):writer.status.unsubscribe(key,activate)}).catch(()=>writer.status.unsubscribe(key,activate)),null)}function samePath(requested,own){if(own===void 0)return!1;let canonical=path=>{try{return realpathSync(resolve(path))}catch{return resolve(path)}};return canonical(requested)===canonical(own)}var SESSION_CONTROL_COMMANDS=["get_available_models","get_available_thinking_levels","set_model","set_thinking_level","interrupt"];async function runSessionControlCommand(session,controls,command){let{id,type}=command;switch(type){case"get_available_models":return success(id,type,await availableModelsData(session));case"get_available_thinking_levels":return success(id,type,{levels:session.getAvailableThinkingLevels()});case"set_model":return await setModel(session,controls,command);case"set_thinking_level":{let level=session.getAvailableThinkingLevels().find(candidate=>candidate===command.level);return level===void 0?failure(id,type,unsupportedThinkingLevel(command.level)):(controls.selectThinkingLevel(level,command.scope!=="turn"),success(id,type))}case"interrupt":{let backgroundError=interruptBackgroundError(command.background);return backgroundError!==void 0?failure(id,type,backgroundError):success(id,type,await interruptRunningTurn(session,command.turnId,()=>controls.interruptTurn(),command.background))}default:return}}async function setModel(session,controls,command){let{id,type}=command,model=(await session.modelRegistry.getAvailable()).find(candidate=>candidate.provider===command.provider&&candidate.id===command.modelId);if(model===void 0)return failure(id,type,`Model not found: ${String(command.provider)}/${String(command.modelId)}`);try{let change=await controls.selectModel(model);return success(id,type,{...model,systemPromptName:change?.systemPromptName})}catch(error){return failure(id,type,error instanceof Error?error.message:String(error))}}var TUI_CONTROL_CAPABILITY="tui_control",TUI_CONTROL_COMMANDS=["get_protocol_info","list_sessions","get_state","get_messages","get_entries","set_session_name","set_session_archived","set_session_settled","subscribe","wake","extension_ui_response","unload_session",...SESSION_CONTROL_COMMANDS,...TUI_RPC_COMMANDS];async function runControlCommand(context,connection,command){let{id,type}=command,{session}=context;switch(type){case"get_protocol_info":{let build=engineBuildIdentity();return success(id,type,{protocolVersion:1,serverVersion:VERSION,capabilities:[TUI_CONTROL_CAPABILITY,SESSION_STATUS_CAPABILITY,TUI_OBSERVER_CAPABILITY,OBSERVE_READS_CAPABILITY,ENTRIES_TAIL_CAPABILITY,"snapshot_cursor","ui_answer_ledger",UNLOAD_GRACEFUL_CAPABILITY],mode:"tui",endpoint_kind:"tui",instanceId:context.instanceId,generation:0,engineVersion:build.text,engineOrdinal:build.ordinal,commands:TUI_CONTROL_COMMANDS,method_classes:describeRpcMethodClasses()})}case"list_sessions":return success(id,type,{sessions:[sessionRow(session)]});case"get_state":return success(id,type,{...buildRpcSessionState(session),turn_epoch:session.externalAdmission.turnEpoch,blocking_question:context.surface.blockingQuestion(),compacting:session.isCompacting,editor_has_draft:context.surface.submissionInFlight()||context.surface.hasDraft(),state_version:context.feed.stateVersion});case"get_messages":return success(id,type,{messages:session.messages});case"get_entries":return answerGetEntries(session,command);case"set_session_name":{let name=typeof command.name=="string"?command.name.trim():"";return name===""?failure(id,type,"Session name cannot be empty"):(session.setSessionName(name),success(id,type))}case"set_session_archived":{if(typeof command.archived!="boolean")return failure(id,type,"archived must be a boolean");let{attachments}=context;setSessionArchived(session.sessionManager,command.archived);let change={type:"session_archived_changed",archived:command.archived};return attachments.run(connection,()=>attachments.writer.enqueue(attachments.handle,change)),success(id,type)}case"set_session_settled":{let parsed=parseSessionSettled({settled:command.settled,by:command.by});if(!parsed.ok)return{...failure(id,type,parsed.error),errorCode:RPC_ERROR_INVALID_ARGUMENT};let{attachments}=context;setSessionSettled(session.sessionManager,parsed.value);let change={type:"session_settled_changed",...settledFields(parsed.value)};return attachments.run(connection,()=>attachments.writer.enqueue(attachments.handle,change)),success(id,type)}case"subscribe":{let cursor=typeof command.cursor=="number"?command.cursor:void 0;return success(id,type,{cursor:context.feed.subscribe(connection.id,cursor,connection.send)})}case"wake":{let ids=Array.isArray(command.delivery_ids)?command.delivery_ids.filter(entry=>typeof entry=="string"):void 0,result=await context.wake(ids);return success(id,type,{admitted:result.admitted??[]})}case"extension_ui_response":return answerQuestion(context,command);case"unload_session":return closeTerminalGracefully(context,connection,command);default:{let rpc=await runTuiRpcCommand(context,connection,command);return rpc!==void 0?rpc:await runSessionControlCommand(session,context.surface,command)??failure(id,type,"unsupported")}}}function sessionRow(session){let manager=session.sessionManager,created=manager.getHeader()?.timestamp??null,last=manager.getEntries().at(-1);return{sessionId:session.sessionId,sessionPath:session.sessionFile??null,session_file:session.sessionFile??null,kind:"interactive",surface:"tui",cwd:manager.getCwd(),name:session.sessionName??null,created_at:created,updated_at:last?.timestamp??created,attachments:1,retain_on_disconnect:!0,archived:isSessionArchived(manager),...settledFields(readSessionSettled(manager)),activity:session.isStreaming?"running":"idle",...session.model!==void 0?{model:{provider:session.model.provider,id:session.model.id}}:{}}}function answerQuestion(context,command){if(command.secret===!0)return failure(command.id,"extension_ui_response","invalid_secret_response");let{surface,session}=context,ledger=sessionUiAnswerLedger(session),answerId=command.answerId;if(answerId!==void 0&&(typeof answerId!="string"||answerId.length<1||answerId.length>256))return failure(command.id,"extension_ui_response","invalid_answer_id");let frameId=command.id,requestId=answeredUiRequestId(command),receipt=requestId===void 0||answerId===void 0?void 0:ledger.lookup(requestId,answerId);if(receipt==="replay")return{...success(frameId,"extension_ui_response"),disposition:receipt};if(receipt==="already_answered")return{...failure(frameId,"extension_ui_response","already_answered"),disposition:receipt};let request=requestId===void 0?void 0:surface.pendingQuestion(requestId);if(requestId===void 0||request===void 0)return{...failure(frameId,"extension_ui_response",answerId===void 0?"unknown_request":"unknown_extension_ui_request"),disposition:"unknown"};let response=questionResponse(command,request.questions);return response==="question_incomplete"?failure(frameId,"extension_ui_response",response):response===void 0||!surface.answerQuestion(requestId,response)?failure(frameId,"extension_ui_response","invalid_response"):(ledger.record(requestId,answerId),{...success(frameId,"extension_ui_response"),disposition:"applied"})}function questionResponse(command,questions){if(command.cancelled===!0)return{status:"cancelled",cancelOrigin:"user",answers:{},unanswered:[]};let answers=command.answers;if(typeof answers!="object"||answers===null||Array.isArray(answers))return;let parsed={};for(let[question,value]of Object.entries(answers)){if(typeof value!="object"||value===null||!("selected"in value)||!Array.isArray(value.selected))return;let selected=value.selected.filter(entry=>typeof entry=="string"),text="text"in value&&typeof value.text=="string"?value.text:void 0;parsed[question]=text===void 0?{selected}:{selected,text}}let comment=typeof command.comment=="string"?command.comment:void 0,status=settledQuestionStatus(parsed,comment);if(status===void 0)return"question_incomplete";let unanswered=unansweredQuestionIds(questions,parsed);return{status,resolvedBy:"control_endpoint",answers:parsed,unanswered,...comment===void 0?{}:{comment}}}var ControlFeed=class{constructor(){this.seq=0,this.stateVersionValue=0,this.ring=[],this.subscribers=new Map}get stateVersion(){return this.stateVersionValue}publish(kind,data={}){kind==="state"&&(this.stateVersionValue+=1);let event={type:"session_control_event",seq:++this.seq,kind,data:kind==="state"?{...data,state_version:this.stateVersionValue}:data};this.ring.push(event),this.ring.length>256&&this.ring.shift();for(let send of this.subscribers.values())send(event)}subscribe(connection,cursor,send){if(this.subscribers.set(connection,send),cursor!==void 0)for(let event of this.ring)event.seq>cursor&&send(event);return this.seq}unsubscribe(connection){this.subscribers.delete(connection)}clear(){this.subscribers.clear()}};import{createHash}from"node:crypto";import{rmSync}from"node:fs";import{chmod as chmod2,lstat,mkdir,realpath,rm as rm2}from"node:fs/promises";import{tmpdir}from"node:os";import{dirname,join}from"node:path";var PRIVATE_DIRECTORY_MODE=448,REGISTRY_LOCK_WAIT_MS=5e3;async function resolveTuiSocket(agentDir,instanceId){let name=tuiSocketName(instanceId),primary=join(agentDir,"rpc","tui",name);if(process.platform==="win32"||Buffer.byteLength(primary)<=MAX_SOCKET_PATH_BYTES)return await makePrivateDirectory(dirname(primary)),primary;let fallbackName=`senpi-rpc-${createHash("sha256").update(agentDir).digest("hex").slice(0,8)}`,scopedRoot=join(tmpdir(),fallbackName),root=Buffer.byteLength(join(scopedRoot,"tui",name))<=MAX_SOCKET_PATH_BYTES?scopedRoot:join("/tmp",fallbackName),tuiRoot=join(root,"tui");await makePrivateDirectory(tuiRoot);for(let directory of[root,tuiRoot])await assertPrivateDirectory(directory);let fallback=join(tuiRoot,name);if(Buffer.byteLength(fallback)>MAX_SOCKET_PATH_BYTES)throw new Error(`socket path ${fallback} exceeds ${MAX_SOCKET_PATH_BYTES} bytes`);return fallback}async function makePrivateDirectory(directory){await mkdir(directory,{recursive:!0,mode:PRIVATE_DIRECTORY_MODE}),await chmod2(directory,PRIVATE_DIRECTORY_MODE)}async function assertPrivateDirectory(directory){let stat=await lstat(await realpath(directory)),ownedByUs=process.getuid===void 0||stat.uid===process.getuid();if(!stat.isDirectory()||!ownedByUs||(stat.mode&63)!==0)throw new Error(`alt_root_unsafe: ${directory} is not a private directory of this user`)}async function registerTuiEndpoint(options){let paths=createHostDaemonPaths({socket:options.socket,agentDir:options.agentDir}),release=await acquireHostEnsureLock(options.socket,REGISTRY_LOCK_WAIT_MS);try{await writeHostRegistration(paths,{record:{pid:process.pid,processStartTime:await thisProcessStartTime()},socket:options.socket,instanceId:options.instanceId,generation:0,launchProfileId:"tui",build:engineBuildIdentity()},{fresh:!0}),await createDaemonDirectories(paths,{kind:"tui"})}finally{await release()}return{paths,socket:options.socket}}async function unregisterTuiEndpoint(entry){let release=await acquireHostEnsureLock(entry.socket,REGISTRY_LOCK_WAIT_MS).catch(()=>{});try{await rm2(entry.socket,{force:!0}),await rm2(socketSecretPath(entry.socket),{force:!0}),await rm2(entry.paths.dir,{recursive:!0,force:!0})}finally{await release?.()}}function unregisterTuiEndpointSync(entry){rmSync(entry.socket,{force:!0}),rmSync(socketSecretPath(entry.socket),{force:!0}),rmSync(entry.paths.dir,{recursive:!0,force:!0})}var REPORT_TEXT_LIMIT=4e3;function activateControlEndpoint(parts){let{context,feed,wake}=parts,{session,surface}=context;session.externalAdmission.setEditorSource(()=>editorHold(context));let unsubscribeSession=session.subscribe(event=>{event.type==="agent_start"?feed.publish("state"):event.type==="agent_idle"?(feed.publish("completion",{turn_epoch:session.externalAdmission.turnEpoch}),feed.publish("state"),wake("idle")):event.type==="agent_end"||event.type==="queue_update"||event.type==="compaction_start"||event.type==="compaction_end"?feed.publish("state"):event.type==="message_end"&&event.message.role==="assistant"&&feed.publish("report",{text:assistantText(event.message).slice(0,REPORT_TEXT_LIMIT)})}),unsubscribeEmitted=session.externalAdmission.onEmitted(()=>{wake("emitted")}),unsubscribeInputs=session.externalAdmission.onInputsSettled(()=>queueMicrotask(()=>{wake("submission")})),stopContinue=onProcessContinue(()=>{wake("continue")}),exitCleanup=()=>unregisterTuiEndpointSync(parts.entry);process.once("exit",exitCleanup);let disposing,dispose=()=>(disposing??=(async()=>{process.removeListener("exit",exitCleanup),unsubscribeSession(),unsubscribeEmitted(),unsubscribeInputs(),stopContinue(),parts.stopInbox(),parts.scheduler.dispose(),feed.clear(),session.externalAdmission.setEditorSource(void 0),await parts.server.close(),await sessionReferenced(parts.options,surface)||await session.sessionManager.discardHeaderOnlyFile(),await unregisterTuiEndpoint(parts.entry)})(),disposing);return{socket:parts.entry.socket,wake:reason=>{wake(reason)},noteState:()=>feed.publish("state"),noteQuestions:()=>feed.publish("question",{pending:[...surface.pendingQuestionIds()]}),dispose}}function editorHold(context){let revision=context.editorRevision();return context.surface.submissionInFlight()?{hold_reason:"draft",revision}:{revision}}async function sessionReferenced(options,surface){if(options.isSessionReferenced===void 0)return!1;try{return await options.isSessionReferenced()}catch(error){return surface.notice(`control endpoint kept the session file: ${error instanceof Error?error.message:String(error)}`),!0}}function assistantText(message){return message.role!=="assistant"?"":message.content.flatMap(part=>part.type==="text"?[part.text]:[]).join(`
`)}async function registerSessionControlEndpoint(context,options){let cleanups=[];try{let endpoint=await openEndpoint(context,options,cleanups);return{registration:{status:"registered",socket:endpoint.socket,dispose:endpoint.dispose},endpoint}}catch(error){for(let cleanup of cleanups.reverse())await Promise.resolve(cleanup()).catch(()=>{});let reason=errorText(error);return context.surface.notice(`control endpoint unavailable: ${reason}`),{registration:{status:"failed",reason}}}}async function openEndpoint(context,options,cleanups){let{session,agentDir,surface}=context;thisProcessStartTime();let headerDurable=session.sessionManager.persistHeaderNow();headerDurable.catch(()=>{});let instanceId=randomUUID2(),socket=await resolveTuiSocket(agentDir,instanceId);cleanups.push(()=>rm3(socket,{force:!0}),()=>rm3(socketSecretPath(socket),{force:!0}));let secret=await createSocketSecret(socketSecretPath(socket)),feed=new ControlFeed,failing,scheduler=new WakeScheduler(async event=>{await session.extensionRunner.emit(event);let result=await options.drain(event)??{admitted:[]};return failing=void 0,result},error=>{let reason=errorText(error);reason!==failing&&(failing=reason,surface.notice(`control endpoint drain failed: ${reason}`))});cleanups.push(()=>scheduler.dispose());let wake=(reason,ids)=>scheduler.request(reason,ids),presenters=context.mcpPresenter?await startTerminalPresenters(context.mcpPresenter):void 0;presenters&&cleanups.push(presenters.dispose);let attachments=new ControlAttachments(session,()=>surface.pendingQuestionIds().length,presenters?.surface);cleanups.push(()=>attachments.dispose());let commandContext={instanceId,session,surface,feed,wake:ids=>wake("command",ids),attachments},server=await listenControlSocket(socket,secret,{command:(connection,command)=>runControlCommand(commandContext,connection,command),opened:connection=>attachments.opened(connection),respond:(connection,answer2)=>attachments.respond(connection,answer2),closed:connection=>{feed.unsubscribe(connection.id),attachments.closed(connection)},listenerError:error=>surface.notice(`control endpoint listener failed: ${error.message}`)});cleanups.push(()=>server.close()),await headerDurable;let entry=await registerTuiEndpoint({agentDir,socket,instanceId});cleanups.push(()=>unregisterTuiEndpoint(entry));let inbox=await watchInbox(options.inboxDir,()=>{wake("inbox")},error=>surface.notice(`control endpoint inbox watch failed: ${errorText(error)}`));cleanups.push(()=>inbox.stop());let endpoint=activateControlEndpoint({context,options,entry,server,scheduler,feed,stopInbox:inbox.stop,wake});return endpoint.wake("inbox"),inbox.armed.then(()=>endpoint.wake("inbox")),setImmediate(()=>{gcHostEndpoints(agentDir,{kinds:["tui"]}).catch(error=>surface.notice(`control endpoint gc of dead terminals failed: ${errorText(error)}`))}),presenters?{...endpoint,dispose:()=>endpoint.dispose().finally(presenters.dispose)}:endpoint}function errorText(error){return error instanceof Error?error.message:String(error)}export{registerSessionControlEndpoint};