@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
11 lines (9 loc) • 33.6 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{RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_UNKNOWN_COMMAND,clientMessageIdentity}from"./chunk-ARIPHUYY.js";import{OPEN_AFTER_QUEUED_DEADLINE_MS,PROMPT_ACK_MAX_WAIT_MS,PROMPT_AFTER_QUEUED_DEADLINE_MS,PROMPT_COMPACTION_DEADLINE_MS,REQUEST_DEADLINE_MS,RpcRequestTimeoutError,armRequestDeadline,connectRpcClientSocket,openStalledMessage,promptStalledMessage,requestDeadlineMs}from"./chunk-R7SWQZBB.js";import{DETACH_CONNECTION_CAPABILITY}from"./chunk-2JCYUXD3.js";import{ORIGIN_HOST_INSTANCE_FIELD,originHostInstance}from"./chunk-APCZVDHX.js";import{attachJsonlLineReader,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{external_exports}from"./chunk-36BLGKRO.js";import{fuzzyFilter}from"./chunk-4PMRUR4L.js";import{childEnvironmentOf}from"./chunk-IDTQWHTP.js";import{RecoveryRepairController}from"./chunk-4EGD7FGJ.js";var COMMAND_TOKEN=/^\/[A-Za-z][A-Za-z0-9:_-]*$/,MAX_SUGGESTIONS=3,UnknownCommandError=class extends Error{constructor(command,suggestions,reason){super(formatUnknownCommandMessage(command,suggestions,reason)),this.name="UnknownCommandError",this.command=command,this.suggestions=suggestions,this.reason=reason}};function formatUnknownCommandMessage(command,suggestions,reason){if(reason==="interactive_only")return`/${command} is an interactive command and cannot be sent as a prompt.`;let hint=suggestions.length===0?"":` Did you mean ${suggestions.map(name=>`/${name}`).join(", ")}?`;return`Unknown command /${command}.${hint}`}var UNKNOWN_COMMAND_CONFIRM_HINT='Resend with "unknownCommandAsText": true to send it as text.';function unknownCommandErrorFromWire(data){if(typeof data!="object"||data===null)return;let command=Reflect.get(data,"command"),suggestions=Reflect.get(data,"suggestions"),reason=Reflect.get(data,"reason");if(typeof command!="string"||!Array.isArray(suggestions)||reason!=="unknown"&&reason!=="interactive_only")return;let names=suggestions.filter(name=>typeof name=="string");return new UnknownCommandError(command,names,reason)}function commandShapedName(text){let token=text.trim().split(/\s/,1)[0]??"";return COMMAND_TOKEN.test(token)?token.slice(1):void 0}function findUnknownCommand(text,catalog){let command=commandShapedName(text);if(command===void 0||catalog.promptCommands.has(command))return;if(catalog.interactiveCommands.has(command))return new UnknownCommandError(command,[],"interactive_only");let known=[...new Set([...catalog.promptCommands,...catalog.interactiveCommands])],suggestions=fuzzyFilter(known,command,name=>name).slice(0,MAX_SUGGESTIONS);return new UnknownCommandError(command,suggestions,"unknown")}import{existsSync}from"node:fs";import{stat}from"node:fs/promises";function getMissingSessionCwdIssue(sessionManager,fallbackCwd){let sessionFile=sessionManager.getSessionFile();if(!sessionFile)return;let sessionCwd=sessionManager.getCwd();if(!(!sessionCwd||existsSync(sessionCwd)))return{sessionFile,sessionCwd,fallbackCwd}}function formatMissingSessionCwdError(issue){let sessionFile=issue.sessionFile?`
Session file: ${issue.sessionFile}`:"";return`Stored session working directory does not exist: ${issue.sessionCwd}${sessionFile}
Current working directory: ${issue.fallbackCwd}`}function formatMissingSessionCwdPrompt(issue){return`cwd from session file does not exist
${issue.sessionCwd}
continue in current cwd
${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{constructor(issue){super(formatMissingSessionCwdError(issue)),this.name="MissingSessionCwdError",this.issue=issue}},SessionCwdNotDirectoryError=class extends Error{constructor(issue){let sessionFile=issue.sessionFile?`
Session file: ${issue.sessionFile}`:"";super(`Session working directory is not a directory: ${issue.sessionCwd}${sessionFile}`),this.name="SessionCwdNotDirectoryError",this.issue=issue}};async function assertSessionCwdExists(sessionManager,fallbackCwd){let issue=getMissingSessionCwdIssue(sessionManager,fallbackCwd);if(issue)throw new MissingSessionCwdError(issue);let sessionCwd=sessionManager.getCwd(),stats=sessionCwd?await stat(sessionCwd).catch(()=>{}):void 0;if(sessionCwd&&stats!==void 0&&!stats.isDirectory()){let sessionFile=sessionManager.getSessionFile();throw new SessionCwdNotDirectoryError({...sessionFile?{sessionFile}:{},sessionCwd})}}import{spawn}from"node:child_process";var RpcCommandError=class extends Error{constructor(message,errorCode,errorData){super(message),this.name="RpcCommandError",this.errorCode=errorCode,this.errorData=errorData}};var UnawaitedReplies=class{constructor(max=1024){this.counts=new Map,this.max=max}note(id){this.counts.set(id,(this.counts.get(id)??0)+1);for(let oldest of this.counts.keys()){if(this.counts.size<=this.max)break;this.counts.delete(oldest)}}take(id){let count=this.counts.get(id);return count===void 0?!1:(count<=1?this.counts.delete(id):this.counts.set(id,count-1),!0)}};function handleRpcReply(value,requests,admissions,unawaited){if(typeof value!="object"||value===null||!("type"in value)||value.type!=="response")return!1;let id="id"in value&&typeof value.id=="string"?value.id:void 0,pending=id===void 0?void 0:requests.get(id);if(pending===void 0&&id!==void 0&&unawaited?.take(id)===!0)return!0;if(pending===void 0||id===void 0)return process.stderr.write(`senpi rpc client: dropped response with no pending request
`),!0;requests.delete(id);let response=value;return admissions.receive(response),pending.onResponse?.(response),pending.resolve(response),!0}var routeSchema=external_exports.object({sessionId:external_exports.string(),admissionId:external_exports.string(),generation:external_exports.number().int().nonnegative(),token:external_exports.string().optional()}),answerSchema=routeSchema.extend({data:external_exports.object({recovery:external_exports.object({token:external_exports.string(),componentRef:external_exports.string()})})}),SENT_ADMISSION_IDS=4096,RpcClientAdmissions=class{constructor(send){this.routes=new Map,this.sent=new Set,this.serial=0,this.send=send}clear(){this.routes.clear()}remember(admissionId){let retry=this.sent.delete(admissionId);this.sent.add(admissionId);for(let oldest of this.sent){if(this.sent.size<=SENT_ADMISSION_IDS)break;this.sent.delete(oldest)}return retry}receive(input){if(this.routes.size===0)return;let parsed=routeSchema.safeParse(input);if(!parsed.success)return;let frame=parsed.data,route=this.routes.get(frame.admissionId);!route||frame.generation<route.generation||(route.sessionId=frame.sessionId,route.generation=frame.generation,frame.token!==void 0&&(route.token=frame.token))}accept(response){if(!response.success)throw new RpcCommandError(response.error,response.errorCode,response.errorData);let parsed=answerSchema.parse(response);this.receive({...parsed,token:parsed.data.recovery.token});let current=this.routes.get(parsed.admissionId);return{sessionId:current?.sessionId??parsed.sessionId,admissionId:parsed.admissionId,generation:current?.generation??parsed.generation,recovery:{...parsed.data.recovery,token:current?.token??parsed.data.recovery.token}}}async open(options){let existing=this.routes.has(options.admissionId);existing||this.routes.set(options.admissionId,{repair:new RecoveryRepairController,generation:0,notBefore:0});let retry=this.remember(options.admissionId);try{let opened=this.accept(await this.send({...options,type:"open_session",...retry?{retry:!0}:{}})),manifest=await this.page(options.admissionId,"manifest");return manifest.action==="restart_from_catalog"?manifest.identity:opened}catch(cause){throw existing||this.routes.delete(options.admissionId),cause}}async page(admissionId,componentRef,cursor){let route=this.routes.get(admissionId);if(!route?.token||!route.sessionId)throw new RpcCommandError("unknown compact admission","unknown_admission",{code:"unknown_admission",admissionId});let now=Date.now();if(now<route.notBefore)return{action:"wait",retryAfterMs:route.notBefore-now};let token=route.token,response=await this.send({type:"get_recovery_page",sessionId:route.sessionId,admissionId,token,componentRef,requestId:`page-${++this.serial}`,...cursor===void 0?{}:{cursor}}),parsed=external_exports.object({repair:external_exports.unknown(),reason:external_exports.string().optional()}).safeParse(response.success?"data"in response?response.data:void 0:response.errorData);if(!parsed.success)throw response.success?parsed.error:new RpcCommandError(response.error,response.errorCode,response.errorData);let body=parsed.data,received=Date.now(),action=route.repair.observe(body.repair,received,{token,reason:body.reason??""});switch(action.action){case"ready":return{action:"ready",response};case"wait":return route.notBefore=received+action.retryAfterMs,action;case"restart_from_catalog":{let reset=await this.send({type:"reset_stream",sessionId:route.sessionId,admissionId}),identity=this.accept(reset);return{action:"restart_from_catalog",response:reset,identity}}}}};function isProviderAccountEvent(event){return event.type==="auth_accounts_changed"||event.type==="account_failover"}var RpcTransportGoneError=class extends Error{constructor(message="Shared RPC host is unavailable"){super(message),this.code="rpc_transport_gone",this.name="RpcTransportGoneError"}};function isTransportGoneError(error){return error instanceof RpcTransportGoneError||error instanceof Error&&(error.message==="Client not started"||error.message.startsWith("RPC transport is not writable.")||error.message==="RPC socket closed")}var RpcClientOpenInFlightError=class extends Error{constructor(){super("An open_session request is already in flight"),this.code="open_session_in_flight",this.name="RpcClientOpenInFlightError"}},MAX_PENDING_SESSION_EVENTS=512,MAX_PENDING_SESSION_EVENT_BYTES=1024*1024,RpcClient=class{constructor(options={}){this.admissions=new RpcClientAdmissions(command=>this.send(command,!1)),this.process=null,this.socket=null,this.stopReadingStdout=null,this.eventListeners=[],this.unawaitedReplies=new UnawaitedReplies,this.pendingRequests=new Map,this.requestId=0,this.compactions=new Map,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.stderr="",this.exitError=null,this.disconnectNotified=!1,this.stopping=!1,this.originHost=originHostInstance(),this.options=options,this.onEvent(event=>{switch(event.type){case"compaction_start":{let key=event.requestId??"";if(this.compactions.has(key))return;this.compactions.set(key,Date.now());break}case"compaction_end":if(!this.compactions.delete(event.requestId??""))return;break;case"session_replaced":this.compactions.clear();break;default:return}for(let pending of this.pendingRequests.values())pending.sessionId===this.sessionId&&pending.onCompaction?.(this.isCompacting())})}async start(){if(this.process||this.socket)throw new Error("Client already started");if(this.exitError=null,this.compactions.clear(),this.stopping=!1,this.disconnectNotified=!1,this.options.socketPath){await this.startSocket(this.options.socketPath);return}let cliPath=this.options.cliPath??"dist/cli.js",args=["--mode","rpc"];this.options.provider&&this.options.model&&args.push("--provider",this.options.provider),this.options.model&&args.push("--model",this.options.model),this.options.args&&args.push(...this.options.args);let childProcess=spawn("node",[cliPath,...args],{cwd:this.options.cwd,env:{...childEnvironmentOf(process.env),SENPI_RUNTIME:"node",...this.options.env},stdio:["pipe","pipe","pipe"],windowsHide:!0});if(this.process=childProcess,childProcess.stderr?.on("data",data=>{this.stderr+=data.toString(),process.stderr.write(data)}),childProcess.once("exit",(code,signal)=>{if(this.process!==childProcess)return;let error=this.createProcessExitError(code,signal);this.exitError=error,this.rejectPendingRequests(error)}),childProcess.once("error",error=>{if(this.process!==childProcess)return;let processError=new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=processError,this.rejectPendingRequests(processError)}),childProcess.stdin?.on("error",error=>{if(this.process!==childProcess)return;let stdinError=this.exitError??new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=stdinError,this.rejectPendingRequests(stdinError)}),this.stopReadingStdout=attachJsonlLineReader(childProcess.stdout,line=>{this.handleLine(line)}),await new Promise(resolve=>setTimeout(resolve,100)),this.process.exitCode!==null){let error=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=error,error}}isCompacting(){let now=Date.now();for(let[key,startedAt]of this.compactions)now-startedAt>=PROMPT_COMPACTION_DEADLINE_MS&&this.compactions.delete(key);return this.compactions.size>0}async stop(){if(this.compactions.clear(),this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.socket){this.stopping=!0,this.stopReadingStdout?.(),this.stopReadingStdout=null,this.socket.destroy(),this.socket=null,this.sessionId=void 0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.notifyDisconnect(new RpcTransportGoneError);return}this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,signalSpawnedChild(this.process,"SIGTERM"),await new Promise(resolve=>{let timeout=setTimeout(()=>{this.process&&signalSpawnedChild(this.process,"SIGKILL"),resolve()},1e3);this.process?.on("exit",()=>{clearTimeout(timeout),resolve()})}),this.process=null,this.pendingRequests.clear())}async startSocket(path){let socket=await connectRpcClientSocket(path,this.options);this.socket=socket,this.stopReadingStdout=attachJsonlLineReader(socket,line=>this.handleLine(line)),socket.once("close",()=>{this.socket===socket&&(this.socket=null,this.notifyDisconnect(new RpcTransportGoneError))}),socket.once("error",error=>{this.socket===socket&&this.notifyDisconnect(new RpcTransportGoneError)})}onEvent(listener){return this.eventListeners.push(listener),()=>{let index=this.eventListeners.indexOf(listener);index!==-1&&this.eventListeners.splice(index,1)}}getStderr(){return this.stderr}async setClientInfo(width,capabilities){await this.send({type:"set_client_info",width,capabilities},this.sessionId!==void 0)}async openSession(options){if(this.pendingOpenSession)throw new RpcClientOpenInFlightError;this.pendingOpenSession=!0;try{let opened=options.admissionId===void 0?this.getData(await this.send({type:"open_session",...options},!1)):await this.admissions.open({...options,admissionId:options.admissionId});return this.sessionId=opened.sessionId,this.compactions.clear(),this.pendingOpenSession=!1,this.flushPendingSessionEvents(),opened}catch(error){throw this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,error}}async sendExtensionUIResponse(response){await this.send(response,!0,void 0,!1)}async resumeSession(){await this.send({type:"resume_session"})}async pauseForRun(command){return this.getData(await this.send({...command,type:"pause_for_run"}))}async resumeForRun(command){return this.getData(await this.send({...command,type:"resume_for_run"}))}async holdInput(command){return this.getData(await this.send({...command,type:"hold_input"}))}async sendExtensionUIProgress(progress){await this.send(progress,!0,void 0,!1)}async unloadSession(options){let sessionId=options.sessionId??this.sessionId;if(!sessionId)throw new Error("unload_session needs a session");return this.getData(await this.send({...options,type:"unload_session",sessionId},!1))}async setSessionContext(patch,sessionId=this.sessionId){if(!sessionId)throw new RpcCommandError(`${RPC_ERROR_SESSION_NOT_ATTACHED}: set_session_context needs a session`,RPC_ERROR_SESSION_NOT_ATTACHED,{reason:"this client has no attached session",action:"attach with openSession first, or pass a sessionId"});this.getData(await this.send({type:"set_session_context",sessionId,patch},!1))}async closeSession(sessionId=this.sessionId){if(sessionId){try{this.getData(await this.send({type:"close_session",sessionId},!1))}catch(error){if(!isTransportGoneError(error))throw error}this.sessionId===sessionId&&(this.sessionId=void 0,this.compactions.clear())}}async detachConnection(){let info=this.getData(await this.send({type:"get_protocol_info"},!1));if(!Array.isArray(info.capabilities)||!info.capabilities.includes(DETACH_CONNECTION_CAPABILITY))return"unsupported";let data=this.getData(await this.send({type:"detach_connection"},!1));return{deferred:Array.isArray(data?.deferred)?data.deferred.filter(id=>typeof id=="string"):[]}}async listSessions(options){let response=await this.send({type:"list_sessions",...options},!1);return this.getData(response).sessions}async prompt(message,optionsOrImages){let options=Array.isArray(optionsOrImages)?{images:optionsOrImages}:optionsOrImages??{},response=await this.send({type:"prompt",message,...clientMessageIdentity(options),...options.images?{images:options.images}:{},...options.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{},...options.unknownCommandAsText?{unknownCommandAsText:!0}:{}},!0,{onResponse:wireResponse=>{if(!wireResponse.success){options?.preflightResult?.(!1);return}let data=wireResponse.data;options?.promptDisposition?.(data?.disposition??"handled"),options?.preflightResult?.(!0)},onReject:()=>{options?.preflightResult?.(!1)}});if(!response.success){let failure=response;throw(failure.errorCode===RPC_ERROR_UNKNOWN_COMMAND?unknownCommandErrorFromWire(failure.errorData):void 0)??new RpcCommandError(failure.error,failure.errorCode,failure.errorData)}return response.data?.disposition??"handled"}async appendUserMessage(content){await this.send({type:"append_user_message",content})}async appendSessionEntry(entry){await this.send({type:"append_session_entry",entry})}async sendCustomMessage(message,options){await this.send({type:"send_custom_message",...message,...options})}async continueFromLeaf(){let response=await this.send({type:"continue_from_leaf"});this.getData(response)}async steer(message,images,recovery){let response=await this.send({type:"steer",message,images,enqueueOrder:recovery?.enqueueOrder,...clientMessageIdentity(recovery)});return this.getData(response)?.disposition??"handled"}async followUp(message,images,recovery){let response=await this.send({type:"follow_up",message,images,enqueueOrder:recovery?.enqueueOrder,...clientMessageIdentity(recovery)});return this.getData(response)?.disposition??"handled"}async abort(options){if(options===void 0){try{await this.send({type:"abort"})}catch(error){if(!isTransportGoneError(error))throw error}return}return this.getData(await this.send({...options,type:"abort"}))}async getEffectStatus(effectId,options={}){let command={type:"get_effect_status",effectId,...options.sessionPath===void 0?{}:{sessionPath:options.sessionPath}};return this.getData(await this.send(command,options.sessionPath===void 0))}async getPendingInputs(knownClientMessageIds){let command={type:"get_pending_inputs",...knownClientMessageIds===void 0?{}:{knownClientMessageIds:[...knownClientMessageIds]}};return this.getData(await this.send(command))}async abortStrict(){this.getData(await this.send({type:"abort"}))}async abortCompaction(){await this.send({type:"abort_compaction"})}async reload(){let response=await this.send({type:"reload"});return this.getData(response)}async checkReloadVeto(){let response=await this.send({type:"check_reload_veto"});return this.getData(response)}async clearQueue(options){let response=await this.send({type:"clear_queue",abortWillFollow:options?.abortWillFollow});return this.getData(response)}async getSteeringMessages(){let response=await this.send({type:"get_steering_messages"});return this.getData(response).messages}async getFollowUpMessages(){let response=await this.send({type:"get_follow_up_messages"});return this.getData(response).messages}async abortBranchSummary(){await this.send({type:"abort_branch_summary"})}async recordBashResult(command,result,excludeFromContext){await this.send({type:"record_bash_result",command,result,excludeFromContext})}async setLabel(entryId,label){await this.send({type:"set_label",entryId,label})}async newSession(parentSession){let response=await this.send({type:"new_session",parentSession});return this.getData(response)}async getState(){let response=await this.send({type:"get_state"});return this.getData(response)}async setModel(provider,modelId){let response=await this.send({type:"set_model",provider,modelId});return this.getData(response)}async setFavoriteModels(models){await this.send({type:"set_favorite_models",models})}async setScopedModels(models){await this.send({type:"set_scoped_models",models})}async cycleModel(direction="forward"){let response=await this.send({type:"cycle_model",direction});return this.getData(response)}async getAvailableModels(){let response=await this.send({type:"get_available_models"});return this.getData(response).models}async setThinkingLevel(level,options){let response=await this.send({type:"set_thinking_level",level,scope:options?.scope});if(!response.success)throw new Error(response.error)}async cycleThinkingLevel(){let response=await this.send({type:"cycle_thinking_level"});return this.getData(response)}async getAvailableThinkingLevels(){let response=await this.send({type:"get_available_thinking_levels"});return this.getData(response).levels}async getModelThinkingLevel(provider,modelId){let response=await this.send({type:"get_model_thinking_level",provider,modelId});return this.getData(response)}async setFastMode(enabled){let response=await this.send({type:"set_fast_mode",enabled});return this.getData(response)}async getFastMode(){let response=await this.send({type:"get_fast_mode"});return this.getData(response)}async setSteeringMode(mode){await this.send({type:"set_steering_mode",mode})}async setFollowUpMode(mode){await this.send({type:"set_follow_up_mode",mode})}async compact(customInstructions){let response=await this.send({type:"compact",customInstructions});return this.getData(response)}async setAutoCompaction(enabled){await this.send({type:"set_auto_compaction",enabled})}async setAutoRetry(enabled){await this.send({type:"set_auto_retry",enabled})}async abortRetry(){await this.send({type:"abort_retry"})}async setRetryFallback(retryFallback){await this.send({type:"set_retry_fallback",retryFallback})}async bash(command,options){let response=await this.send({type:"bash",command,excludeFromContext:options?.excludeFromContext,executionId:options?.executionId,operations:options?.operations});return this.getData(response)}async navigateTree(targetId,options){let response=await this.send({type:"navigate_tree",targetId,...options});return this.getData(response)}async abortBash(){await this.send({type:"abort_bash"})}async cleanupBashOutput(path){await this.send({type:"cleanup_bash_output",path})}async getSessionStats(){let response=await this.send({type:"get_session_stats"});return this.getData(response)}async resolvePath(path){let response=await this.send({type:"resolve_path",path});return this.getData(response)}async exportHtml(outputPath,themeName){let response=await this.send({type:"export_html",outputPath,themeName});return this.getData(response)}async exportJsonl(outputPath){let response=await this.send({type:"export_jsonl",outputPath});return this.getData(response)}async switchSession(sessionPath,options){let response=await this.send({type:"switch_session",sessionPath,cwdOverride:options?.cwdOverride});return this.getData(response)}async fork(entryId,options){let response=await this.send({type:"fork",entryId,position:options?.position});return this.getData(response)}async clone(){let response=await this.send({type:"clone"});return this.getData(response)}async getForkMessages(){let response=await this.send({type:"get_fork_messages"});return this.getData(response).messages}async getEntries(since,page){let response=await this.send({type:"get_entries",since,...page});return this.getData(response)}async getTree(){let response=await this.send({type:"get_tree"});return this.getData(response)}async editAssistantMessage(entryId,text,options={}){let response=await this.send({type:"edit_assistant_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async editUserMessage(entryId,text,options={}){let response=await this.send({type:"edit_user_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async getLastAssistantText(){let response=await this.send({type:"get_last_assistant_text"});return this.getData(response).text}async setSessionName(name){await this.send({type:"set_session_name",name})}async setSessionArchived(archived){await this.send({type:"set_session_archived",archived})}async setSessionSettled(settled,by){await this.send({type:"set_session_settled",settled,...by!==void 0?{by}:{}})}async recordDraftActivity(){await this.send({type:"record_user_activity",kind:"draft"})}async importJsonl(inputPath,cwdOverride){let response=await this.send({type:"import_jsonl",inputPath,cwdOverride});return this.getData(response)}async getMessages(){let response=await this.send({type:"get_messages"});return this.getData(response).messages}async getMedia(toolCallId,contentIndex){let response=await this.send({type:"get_media",toolCallId,contentIndex});return this.getData(response).content}async getCommands(){let response=await this.send({type:"get_commands"});return this.getData(response).commands}async requestExtension(name,data){let response=await this.send({type:"extension_request",name,...data===void 0?{}:{data}});return this.getData(response)}async listEvalCells(){return this.getData(await this.send({type:"eval_cells.list"}))}async peekEvalCell(cellId,tailBytes){return this.getData(await this.send({type:"eval_cells.peek",cellId,...tailBytes===void 0?{}:{tailBytes}}))}async stopEvalCell(cellId){return this.getData(await this.send({type:"eval_cells.stop",cellId}))}async getProviderAccounts(provider){let response=await this.send({type:"get_provider_accounts",provider});return this.getData(response).accounts}async testProviderAccount(provider,name){let response=await this.send({type:"test_provider_account",provider,name});return this.getData(response).check}async pinProviderAccount(provider,name){await this.send({type:"account_pin",provider,name})}async orderProviderAccounts(provider,names){await this.send({type:"account_order",provider,names})}async removeProviderAccount(provider,name){let data=this.getData(await this.send({type:"account_remove",provider,name}));return data===void 0?{}:{notice:data.notice}}async resetProviderAccount(provider,name){this.getData(await this.send({type:"account_reset",provider,name}))}waitForIdle(timeout=6e4){return new Promise((resolve,reject)=>{let timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{event.type==="agent_idle"&&(clearTimeout(timer),unsubscribe(),resolve())})})}collectEvents(timeout=6e4){return new Promise((resolve,reject)=>{let events=[],timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{isProviderAccountEvent(event)||event.type==="extension_event"||event.type==="bash_start"||event.type==="bash_end"||event.type==="extension_ui_request"||event.type==="secret_input_settled"||event.type==="session_replaced"||event.type==="session_parked"||event.type==="session_released"||event.type==="session_archived_changed"||event.type==="session_settled_changed"||event.type==="queued"||event.type==="socket_closing"||event.type==="message_tool_arguments_reset"||(events.push(event),event.type==="agent_idle"&&(clearTimeout(timer),unsubscribe(),resolve(events)))})})}async promptAndWait(message,images,timeout=6e4){let eventsPromise=this.collectEvents(timeout);return await this.prompt(message,images?{images}:void 0),eventsPromise}handleLine(line){try{let data=JSON.parse(line);if(handleRpcReply(data,this.pendingRequests,this.admissions,this.unawaitedReplies))return;if(this.admissions.receive(data),data.type==="queued"&&typeof data.for_request=="string"&&this.pendingRequests.get(data.for_request)?.onQueued?.(data.position),typeof data.sessionId=="string"&&data.sessionId!==this.sessionId){if(this.pendingOpenSession){let bytes=Buffer.byteLength(line);for(this.pendingSessionEvents.push({sessionId:data.sessionId,event:data,bytes}),this.pendingSessionEventBytes+=bytes;this.pendingSessionEvents.length>MAX_PENDING_SESSION_EVENTS||this.pendingSessionEventBytes>MAX_PENDING_SESSION_EVENT_BYTES;){let oldest=this.pendingSessionEvents.shift();if(!oldest)break;this.pendingSessionEventBytes-=oldest.bytes}}return}for(let listener of[...this.eventListeners])listener(data)}catch{}}flushPendingSessionEvents(){let pending=this.pendingSessionEvents;this.pendingSessionEvents=[],this.pendingSessionEventBytes=0;for(let{sessionId,event}of pending)if(sessionId===this.sessionId)for(let listener of[...this.eventListeners])listener(event)}createProcessExitError(code,signal){return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`)}notifyDisconnect(error){this.admissions.clear(),this.rejectPendingRequests(error),!this.disconnectNotified&&!this.stopping&&(this.disconnectNotified=!0,this.options.onDisconnect?.(error))}rejectPendingRequests(error){for(let pending of this.pendingRequests.values())pending.onReject?.(error),pending.reject(error);this.pendingRequests.clear()}async send(command,route=!0,hooks,expectResponse=!0){let childProcess=this.process,stream=this.socket??childProcess?.stdin;if(!stream)throw new RpcTransportGoneError;if(this.exitError)throw this.exitError;if(childProcess?.exitCode!==null&&childProcess?.exitCode!==void 0){let error=this.createProcessExitError(childProcess.exitCode,childProcess.signalCode);throw this.exitError=error,error}if(stream.destroyed||!stream.writable){let error=new RpcTransportGoneError;throw this.notifyDisconnect(error),error}let ownId=command.type==="extension_ui_response"||command.type==="extension_ui_progress"?command.id:void 0,id=ownId??`req_${++this.requestId}`,fullCommand={...command,...route&&this.sessionId&&!("sessionId"in command)?{sessionId:this.sessionId}:{},...ownId===void 0?{id}:{},...this.socket&&this.originHost?{[ORIGIN_HOST_INSTANCE_FIELD]:this.originHost}:{}};if(!expectResponse)return this.unawaitedReplies.note(id),stream.write(serializeJsonLine(fullCommand)),Promise.resolve({type:"response",command:command.type,success:!0});let sessionId="sessionId"in fullCommand?fullCommand.sessionId:void 0;return new Promise((resolve,reject)=>{let timeoutMessage=()=>`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`,promptCap,promptReceived=!1,expire=timeoutError=>{clearTimeout(promptCap);let pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(timeoutError),reject(timeoutError)},deadline=armRequestDeadline(command.type==="prompt"&&sessionId===this.sessionId&&this.isCompacting()?PROMPT_COMPACTION_DEADLINE_MS:requestDeadlineMs(command),timeoutMessage,expire);command.type==="prompt"&&(promptCap=setTimeout(()=>{deadline.clear(),expire(new RpcRequestTimeoutError(timeoutMessage()))},PROMPT_ACK_MAX_WAIT_MS)),this.pendingRequests.set(id,{sessionId,resolve:response=>{deadline.clear(),clearTimeout(promptCap),resolve(response)},reject:error=>{deadline.clear(),clearTimeout(promptCap),reject(error)},...command.type==="prompt"?{onCompaction:compacting=>compacting?deadline.extend(PROMPT_COMPACTION_DEADLINE_MS,timeoutMessage):promptReceived?deadline.extend(PROMPT_AFTER_QUEUED_DEADLINE_MS,promptStalledMessage):deadline.extend(REQUEST_DEADLINE_MS,timeoutMessage),onQueued:()=>{promptReceived=!0,this.isCompacting()||deadline.extend(PROMPT_AFTER_QUEUED_DEADLINE_MS,promptStalledMessage)}}:{},...command.type==="open_session"?{onQueued:position=>deadline.extend(OPEN_AFTER_QUEUED_DEADLINE_MS,()=>openStalledMessage(position))}:{},...hooks?.onResponse?{onResponse:hooks.onResponse}:{},...hooks?.onReject?{onReject:hooks.onReject}:{}});try{stream.write(serializeJsonLine(fullCommand))}catch(error){let writeError=error instanceof Error?error:new Error(String(error)),pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(writeError),pending?.reject(writeError)}})}getData(response){if(!response.success){let errorResponse=response;throw errorResponse.errorCode==="missing_session_cwd"&&errorResponse.errorData?new MissingSessionCwdError(errorResponse.errorData):new RpcCommandError(errorResponse.error,errorResponse.errorCode,errorResponse.errorData)}return response.data}};export{UnknownCommandError,UNKNOWN_COMMAND_CONFIRM_HINT,commandShapedName,findUnknownCommand,getMissingSessionCwdIssue,formatMissingSessionCwdPrompt,MissingSessionCwdError,assertSessionCwdExists,RpcCommandError,RpcTransportGoneError,isTransportGoneError,RpcClientOpenInFlightError,RpcClient};