@code-yeongyu/senpi 2026.9.28-6 → 2026.9.28-7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/bundle/chunks/{app-server-command-5WCSZ4A5.js → app-server-command-OUTRKHMK.js} +8 -8
- package/dist/bundle/chunks/{chunk-AWPLVQ4K.js → chunk-56COAYOU.js} +5 -5
- package/dist/bundle/chunks/{chunk-4BDFNRBE.js → chunk-B32PXL7U.js} +1 -1
- package/dist/bundle/chunks/chunk-CEMOA3TF.js +2 -0
- package/dist/bundle/chunks/{chunk-WXN35RD7.js → chunk-DB2X7SOZ.js} +2 -2
- package/dist/bundle/chunks/{chunk-DKP4BUY5.js → chunk-F2YU5BZG.js} +1 -1
- package/dist/bundle/chunks/{chunk-VGJESQOS.js → chunk-JASECXGC.js} +1 -1
- package/dist/bundle/chunks/{chunk-KDZAVHA7.js → chunk-L4OOEWAT.js} +2 -2
- package/dist/bundle/chunks/{chunk-DOEV7ITR.js → chunk-LM2UMEX6.js} +1 -1
- package/dist/bundle/chunks/{chunk-HS2LJYBI.js → chunk-Y4CH7LYI.js} +1 -1
- package/dist/bundle/chunks/chunk-YJUO37UX.js +2 -0
- package/dist/bundle/chunks/{cli-main-IBG7ONGV.js → cli-main-26P4V2BK.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-MWSJXPH6.js → help-fast-path-BOMUI7U3.js} +1 -1
- package/dist/bundle/chunks/{host-command-MTK5WOPH.js → host-command-ZVXNTXMN.js} +1 -1
- package/dist/bundle/chunks/{host-lifecycle-7IJCAHHL.js → host-lifecycle-MPLSJ5NB.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +1 -1
- package/dist/bundle/chunks/{interactive-host-runtime-FWMZWK6G.js → interactive-host-runtime-Q5EORM6B.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-XUJM4MCN.js → interactive-mode-OVSKUTVC.js} +1 -1
- package/dist/bundle/chunks/{list-tips-S4U7TKER.js → list-tips-ARO4HRVK.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-7KCH3HUA.js → multi-session-host-LJNXZRFA.js} +7 -7
- package/dist/bundle/chunks/{package-manager-cli-SNVT3VKW.js → package-manager-cli-MJCRY2JU.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-VYB2Q43O.js → rpc-mode-LY4HAZ5G.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-JQ65HF2K.js → schedule-command-3ANAEUY6.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +30 -30
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.js +2 -2
- package/dist/cli/args.js.map +1 -1
- package/dist/main.d.ts +2 -2
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +25 -6
- package/dist/main.js.map +1 -1
- package/dist/modes/app-server/cli-args.d.ts +3 -0
- package/dist/modes/app-server/cli-args.d.ts.map +1 -1
- package/dist/modes/app-server/cli-args.js +25 -4
- package/dist/modes/app-server/cli-args.js.map +1 -1
- package/dist/modes/app-server/daemon/probe.d.ts +1 -0
- package/dist/modes/app-server/daemon/probe.d.ts.map +1 -1
- package/dist/modes/app-server/daemon/probe.js +4 -1
- package/dist/modes/app-server/daemon/probe.js.map +1 -1
- package/dist/modes/app-server/daemon/spawn.d.ts +26 -0
- package/dist/modes/app-server/daemon/spawn.d.ts.map +1 -0
- package/dist/modes/app-server/daemon/spawn.js +112 -0
- package/dist/modes/app-server/daemon/spawn.js.map +1 -0
- package/dist/modes/app-server/daemon.d.ts.map +1 -1
- package/dist/modes/app-server/daemon.js +14 -112
- package/dist/modes/app-server/daemon.js.map +1 -1
- package/dist/modes/app-server/extension-paths.d.ts +7 -0
- package/dist/modes/app-server/extension-paths.d.ts.map +1 -0
- package/dist/modes/app-server/extension-paths.js +10 -0
- package/dist/modes/app-server/extension-paths.js.map +1 -0
- package/dist/modes/app-server/index.d.ts.map +1 -1
- package/dist/modes/app-server/index.js +4 -1
- package/dist/modes/app-server/index.js.map +1 -1
- package/dist/modes/app-server/runtime.d.ts +5 -1
- package/dist/modes/app-server/runtime.d.ts.map +1 -1
- package/dist/modes/app-server/runtime.js +19 -3
- package/dist/modes/app-server/runtime.js.map +1 -1
- package/dist/modes/interactive/tips/catalog/computer-tips.js +1 -1
- package/dist/modes/interactive/tips/catalog/computer-tips.js.map +1 -1
- package/dist/modes/rpc/custom-capability.d.ts +5 -0
- package/dist/modes/rpc/custom-capability.d.ts.map +1 -1
- package/dist/modes/rpc/custom-capability.js +5 -0
- package/dist/modes/rpc/custom-capability.js.map +1 -1
- package/dist/modes/rpc/host-observe-request.d.ts +2 -0
- package/dist/modes/rpc/host-observe-request.d.ts.map +1 -1
- package/dist/modes/rpc/host-observe-request.js +4 -0
- package/dist/modes/rpc/host-observe-request.js.map +1 -1
- package/dist/modes/rpc/host-warm.d.ts +57 -0
- package/dist/modes/rpc/host-warm.d.ts.map +1 -0
- package/dist/modes/rpc/host-warm.js +125 -0
- package/dist/modes/rpc/host-warm.js.map +1 -0
- package/dist/modes/rpc/rpc-types.d.ts +24 -1
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js +2 -0
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/modes/rpc/session-command-router.d.ts +1 -1
- package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
- package/dist/modes/rpc/session-command-router.js +12 -1
- package/dist/modes/rpc/session-command-router.js.map +1 -1
- package/dist/modes/rpc/session-registry.d.ts +6 -2
- package/dist/modes/rpc/session-registry.d.ts.map +1 -1
- package/dist/modes/rpc/session-registry.js +6 -0
- package/dist/modes/rpc/session-registry.js.map +1 -1
- package/docs/app-server-daemon.md +1 -1
- package/docs/app-server.md +3 -0
- package/docs/rpc.md +48 -2
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
- package/dist/bundle/chunks/chunk-A4UMPXQF.js +0 -2
- package/dist/bundle/chunks/chunk-BTMM2C5X.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
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 = () => {}; } }
|
|
2
|
-
import{RpcClient,RpcCommandError,SessionManager,executeBashWithOperations,isTransportGoneError}from"./chunk-DKP4BUY5.js";import{SessionStreamingError,UserEditError}from"./chunk-AIM2YESB.js";import{SettingsManager}from"./chunk-CXVI2YV7.js";import{ensureHost}from"./chunk-DOEV7ITR.js";import{QUESTION_CAPABILITY,RENDERED_COMPONENTS_CAPABILITY}from"./chunk-BTMM2C5X.js";import"./chunk-HS2LJYBI.js";import"./chunk-E5F5SVZF.js";import"./chunk-ASAQQ6VM.js";import"./chunk-7X72IACK.js";import"./chunk-KDZAVHA7.js";import"./chunk-26UBFF6N.js";import"./chunk-TOCWAEQB.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-UDTWLXSQ.js";import"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-J5TMX734.js";import"./chunk-TJV2LFKM.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-7X4ZMME4.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";import{randomUUID}from"node:crypto";import{rm}from"node:fs/promises";async function attachEnsuredHost(ensure,client){let ensured=await ensure();try{await client.start()}finally{ensured?.release()}}var HOST_CLIENT_CAPABILITIES=[RENDERED_COMPONENTS_CAPABILITY,QUESTION_CAPABILITY],INTERACTIVE_HOST_FALLBACK_WARNING="Warning: shared interactive host unavailable; continuing locally",INTERACTIVE_HOST_RECONNECTING_WARNING="Warning: shared interactive host connection lost; reconnecting";async function createInteractiveHostRuntime(localRuntime,options){let sessionPath=localRuntime.session.sessionFile;if(!sessionPath)return localRuntime;let startHost=options.ensureHost??(hostOptions=>ensureHost(hostOptions)),remoteSession,remoteRuntime,reconnecting,disconnectQueued=!1,disposed=!1,fallbackWarned=!1,reconnectWarningShown=!1,warnReconnect=cause=>{reconnectWarningShown||(reconnectWarningShown=!0,options.onWarning?.({type:"interactive_host_action_failed",message:INTERACTIVE_HOST_RECONNECTING_WARNING,cause}))},warnFallback=cause=>{fallbackWarned||(fallbackWarned=!0,options.onWarning?.({type:"interactive_host_fallback",message:INTERACTIVE_HOST_FALLBACK_WARNING,cause}))},scheduleReconnect=()=>{},client=new RpcClient({socketPath:options.socket,onDisconnect:()=>{disconnectQueued=!0,scheduleReconnect()}});scheduleReconnect=()=>{!remoteSession||reconnecting||disposed||remoteRuntime?.isFallback||(remoteRuntime?.enterReconnecting(),reconnecting=(async()=>{let cause;for(let attempt=0;attempt<3;attempt++){if(disposed)return;disconnectQueued=!1;try{if(await attachEnsuredHost(()=>startHost({socket:options.socket,agentDir:options.agentDir}),client),disposed||(await client.openSession({sessionPath,cwd:localRuntime.cwd}),disposed)||(remoteRuntime&&await remoteRuntime.reRegisterClientInfo(),disposed)||(await remoteSession.refresh(),disposed))return;fallbackWarned=!1,reconnectWarningShown=!1,remoteRuntime?.enterConnected();return}catch(error){if(cause=error,await client.stop().catch(()=>{}),disposed)return}}disposed||(await remoteRuntime?.enterFallback(),warnFallback(cause))})().finally(()=>{reconnecting=void 0,disconnectQueued&&!disposed&&!remoteRuntime?.isFallback&&scheduleReconnect()}))};try{await attachEnsuredHost(()=>startHost({socket:options.socket,agentDir:options.agentDir}),client),await client.setClientInfo(80,[...HOST_CLIENT_CAPABILITIES]);let startupEvents=[],stopBuffering=client.onEvent(event=>startupEvents.push(event)),opened=await client.openSession({sessionPath,cwd:localRuntime.cwd,provider:localRuntime.session.model?.provider,modelId:localRuntime.session.model?.id,thinkingLevel:localRuntime.session.thinkingLevel});return remoteSession=createRemoteSessionProxy(localRuntime.session,localRuntime.services.agentDir,client,opened.state,options.onWarning,cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},startupEvents.filter(event=>!("sessionId"in event)||event.sessionId===opened.sessionId)),stopBuffering(),opened.state.isBashRunning&&!opened.attached&&await client.abortBash().catch(()=>{}),opened.attached&&await remoteSession.refresh(),remoteRuntime=new RemoteInteractiveRuntime(localRuntime,remoteSession,client,{onTransportGone:cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},get reconnecting(){return reconnecting},dispose:()=>{disposed=!0}}),remoteRuntime}catch(cause){return await client.stop().catch(()=>{}),warnFallback(cause),localRuntime}}var RemoteInteractiveRuntime=class{#local;#remoteSession;#client;#lifecycle;#onTransportGone;#rebindSession;#beforeSessionInvalidate;#state="connected";#fallbackHandoff;get isReconnecting(){return this.#state==="reconnecting"}get isFallback(){return this.#state==="fallback"}constructor(local,remoteSession,client,lifecycle){this.#local=local,this.#remoteSession=remoteSession,this.#client=client,this.#lifecycle=lifecycle,this.#onTransportGone=lifecycle?.onTransportGone??(()=>{})}async#call(call){try{return await call()}catch(error){if(isTransportGoneError(error))return this.#onTransportGone(error),{cancelled:!0};throw error}}enterConnected(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="connected")}enterReconnecting(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="reconnecting")}async enterFallback(){if(this.#state==="disposed"||this.#state==="fallback")return;this.#state="fallback",this.#beforeSessionInvalidate?.();let rebind=this.#rebindSession?.();rebind&&(this.#fallbackHandoff=rebind.catch(error=>{this.#onTransportGone(error)}),await this.#fallbackHandoff)}get session(){return this.#state==="fallback"||this.#state==="disposed"?this.#local.session:this.#remoteSession.session}get services(){return this.#local.services}get cwd(){return this.session.sessionManager.getCwd()}get diagnostics(){return this.#local.diagnostics}get modelFallbackMessage(){return this.#local.modelFallbackMessage}get launchProfile(){return this.#local.launchProfile}setBeforeSessionInvalidate(callback){this.#beforeSessionInvalidate=callback,this.#local.setBeforeSessionInvalidate(callback)}setRebindSession(callback){this.#rebindSession=callback,this.#local.setRebindSession(callback),callback&&this.#state==="fallback"&&!this.#fallbackHandoff&&(this.#fallbackHandoff=callback().catch(error=>{this.#onTransportGone(error)}))}setHostUiHandler(callback){this.#remoteSession.setHostUiHandler(callback)}sendHostUiProgress(record){this.#client.sendExtensionUIProgress(record).catch(()=>{})}#clientInfoSent=!1;#lastClientWidth=80;setClientInfo(width){this.#lastClientWidth=width;let capabilities=this.#clientInfoSent?void 0:[...HOST_CLIENT_CAPABILITIES];this.#clientInfoSent=!0,this.#client.setClientInfo(width,capabilities).catch(()=>{})}async reRegisterClientInfo(){await this.#client.setClientInfo(this.#lastClientWidth,[...HOST_CLIENT_CAPABILITIES])}async dispose(){if(this.#state==="disposed")return;this.#state="disposed",this.#lifecycle?.dispose(),await this.#lifecycle?.reconnecting?.catch(()=>{}),await this.#fallbackHandoff?.catch(()=>{});let errors=[];for(let cleanup of[()=>this.#remoteSession.abortLocalBash(),()=>this.#client.closeSession(),()=>this.#client.stop(),()=>this.#local.dispose()])try{await cleanup()}catch(error){errors.push(error)}if(errors.length>0)throw errors[0]}async newSession(options){return this.#state==="fallback"?this.#local.newSession(options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.newSession(options?.parentSession));if(!result.cancelled){if(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),options?.setup){let capture=SessionManager.inMemory(this.#remoteSession.session.sessionManager.getCwd());await options.setup(capture);for(let entry of capture.getEntries())await this.#client.appendSessionEntry(entry);await this.#remoteSession.refresh()}await this.#rebindSession?.(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())}return result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async switchSession(sessionPath,options){return this.#state==="fallback"?this.#local.switchSession(sessionPath,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.switchSession(sessionPath,options?.cwdOverride===void 0?void 0:{cwdOverride:options.cwdOverride}));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),await this.#rebindSession?.(),options?.projectTrustContextFactory?.(this.#remoteSession.session.sessionManager.getCwd()),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async fork(entryId,options){return this.#state==="fallback"?this.#local.fork(entryId,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.fork(entryId,options));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),{cancelled:result.cancelled,selectedText:result.text}}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async importFromJsonl(inputPath,cwdOverride){return this.#state==="fallback"?this.#local.importFromJsonl(inputPath,cwdOverride):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.importJsonl(inputPath,cwdOverride));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind()),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async#refreshAndRebind(){await this.#remoteSession.refresh(),await this.#rebindSession?.()}};function createRemoteSessionProxy(local,agentDir,client,initialState,onWarning,onTransportGone,startupEvents=[]){let reportActionFailure=action=>error=>{isTransportGoneError(error)?onTransportGone?.(error):onWarning?.({type:"interactive_host_action_failed",message:`Warning: shared interactive host ${action} failed: ${error instanceof Error?error.message:String(error)}`,cause:error})},transportCall=async(action,call,cancelledValue)=>{try{return await call()}catch(error){if(!isTransportGoneError(error))throw error;return reportActionFailure(action)(error),cancelledValue}},state={...initialState},waitForBashCallbacks=async(promises,allowAbandonment)=>{if(promises.size===0)return!0;let settled=Promise.allSettled([...promises]).then(()=>!0),timeout,bounded=new Promise(resolve=>{timeout=setTimeout(resolve,allowAbandonment?100:5e3,!1),timeout.unref?.()});try{return await Promise.race([settled,bounded])}finally{timeout&&clearTimeout(timeout)}},executionNamespace=randomUUID(),cleanupRemoteBashOutput=async path=>{let cleanupTimeout;try{await Promise.race([client.cleanupBashOutput(path),new Promise((_,reject)=>{cleanupTimeout=setTimeout(()=>reject(new Error("RPC cleanup timed out")),1e3)})]);return}catch(transportError){try{await rm(path,{force:!0});return}catch(localError){onWarning?.({type:"interactive_host_action_failed",message:`Warning: failed to clean up shared bash output spill: ${localError instanceof Error?localError.message:String(localError)}`,cause:new AggregateError([transportError,localError])})}}finally{cleanupTimeout&&clearTimeout(cleanupTimeout)}},nextBashExecutionId=0,bashExecutions=new Map,hostUiHandler,pendingUiRequests=[],localBashAbortController,localBashRunning=!1,hostBashRunning=initialState.isBashRunning,nextQueuedInputOrder=Math.max(0,...initialState.ordered.map(item=>item.enqueueOrder)),sessionManager=local.sessionManager,settingsManager=SettingsManager.create(initialState.cwd,agentDir,{projectTrusted:initialState.projectTrusted}),updateBashState=()=>{state={...state,isBashRunning:localBashRunning||hostBashRunning}},remoteSessionManager=new Proxy({},{get(_target,property,_receiver){if(property==="appendLabelChange")return(entryId,label)=>{client.setLabel(entryId,label).catch(reportActionFailure("appendLabelChange"))};if(property==="getCwd")return()=>state.cwd;if(property==="getSessionName")return()=>state.sessionName;if(property==="getUsageTotals")return()=>state.usageTotals;let value=Reflect.get(sessionManager,property,sessionManager);return typeof value=="function"?value.bind(sessionManager):value}}),streamingAssistant,mirroredCurrentAssistantUsage=!1,localReplacementDepth=0,listeners=new Set,handleWireEvent=wireEvent=>{if(wireEvent.type==="extension_ui_request"){let request=wireEvent;hostUiHandler?Promise.resolve(hostUiHandler(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response")):pendingUiRequests.push(request);return}if(wireEvent.type==="session_replaced"){localReplacementDepth===0&&refresh().catch(reportActionFailure("session refresh after replacement"));return}if(wireEvent.type==="agent_settled"&&(state={...state,isStreaming:!1,retryAttempt:0}),wireEvent.type==="bash_start"&&(hostBashRunning=!0,updateBashState()),wireEvent.type==="bash_end"&&(hostBashRunning=!1,updateBashState()),wireEvent.type==="bash_execution_update"&&wireEvent.id){let execution=bashExecutions.get(wireEvent.id);if(execution?.chunk&&!execution.hasError)try{let callbackPromise=Promise.resolve(execution.chunk(wireEvent.delta)).catch(error=>{throw execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{})),error});execution.promises.add(callbackPromise),callbackPromise.catch(()=>{}).finally(()=>execution.promises.delete(callbackPromise))}catch(error){execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{}))}}if(wireEvent.type==="agent_start"&&(state={...state,isStreaming:!0}),wireEvent.type==="compaction_start"&&(state={...state,isCompacting:!0}),wireEvent.type==="compaction_end"&&(state={...state,isCompacting:!1}),wireEvent.type==="auto_retry_start"&&(state={...state,retryAttempt:wireEvent.attempt}),wireEvent.type==="auto_retry_end"&&(state={...state,retryAttempt:0}),wireEvent.type==="queue_update"&&(nextQueuedInputOrder=Math.max(nextQueuedInputOrder,...wireEvent.ordered.map(item=>item.enqueueOrder)),state={...state,steering:[...wireEvent.steering],followUp:[...wireEvent.followUp],ordered:[...wireEvent.ordered],pendingMessageCount:wireEvent.steering.length+wireEvent.followUp.length}),wireEvent.type==="model_changed"&&(state={...state,model:wireEvent.model,thinkingLevel:wireEvent.thinkingLevel}),wireEvent.type==="thinking_level_changed"&&(state={...state,thinkingLevel:wireEvent.level}),wireEvent.type==="service_tier_changed"&&(state={...state,serviceTier:wireEvent.tier,fastMode:wireEvent.fastMode}),wireEvent.type==="session_settings_changed"&&(state={...state,steeringMode:wireEvent.steeringMode,followUpMode:wireEvent.followUpMode,autoCompactionEnabled:wireEvent.autoCompactionEnabled}),wireEvent.type==="entry_appended")try{sessionManager.appendEntry(wireEvent.entry),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}if(wireEvent.type==="session_info_changed"&&(state={...state,sessionName:wireEvent.name}),wireEvent.type==="message_start"&&(wireEvent.message.role==="assistant"&&(streamingAssistant=structuredClone(wireEvent.message),mirroredCurrentAssistantUsage=!1),local.agent.state.messages.push(structuredClone(wireEvent.message))),wireEvent.type==="message_end"){if(wireEvent.message.role==="assistant"){streamingAssistant=structuredClone(wireEvent.message);let usage=wireEvent.message.usage;if(usage&&!mirroredCurrentAssistantUsage){mirroredCurrentAssistantUsage=!0;let latestPromptTokens=usage.input+usage.cacheRead+usage.cacheWrite,contextWindow=state.model?.contextWindow??0,contextTokens=usage.input+usage.cacheRead+usage.cacheWrite;state={...state,contextUsage:contextWindow>0?{tokens:contextTokens,contextWindow,percent:contextTokens/contextWindow*100}:void 0,usageTotals:{...state.usageTotals,input:state.usageTotals.input+usage.input,output:state.usageTotals.output+usage.output,cacheRead:state.usageTotals.cacheRead+usage.cacheRead,cacheWrite:state.usageTotals.cacheWrite+usage.cacheWrite,cost:state.usageTotals.cost+(usage.cost?.total??0),latestCacheHitRate:latestPromptTokens>0?usage.cacheRead/latestPromptTokens*100:void 0}}}}let messages=local.agent.state.messages;messages.at(-1)?.role===wireEvent.message.role&&(messages[messages.length-1]=structuredClone(wireEvent.message))}if(wireEvent.type==="compaction_end"&&wireEvent.accepted&&!wireEvent.aborted)try{local.sessionManager.reloadFromDisk?.(),sessionManager!==local.sessionManager&&sessionManager.reloadFromDisk?.(),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}let event=hydrateMessageUpdate(wireEvent,streamingAssistant);for(let listener of listeners)listener(event)};client.onEvent(handleWireEvent);for(let event of startupEvents)handleWireEvent(event);let performRefresh=async()=>{let idsAtRefreshStart=new Set(sessionManager.getEntries().map(entry=>entry.id)),nextState=await transportCall("refresh",()=>client.getState());if(!nextState)return;state={...nextState},nextQueuedInputOrder=Math.max(0,...nextState.ordered.map(item=>item.enqueueOrder));let messages;if(settingsManager=SettingsManager.create(nextState.cwd,agentDir,{projectTrusted:nextState.projectTrusted}),nextState.sessionFile){sessionManager.getSessionFile()===nextState.sessionFile?sessionManager.reloadFromDisk?.():sessionManager=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);let authoritative=nextState.entries;if(authoritative?.length){let mirror=sessionManager.getEntries();if(!(mirror.length===authoritative.length&&mirror.every((entry,index)=>entry.id===authoritative[index]?.id))){let rebuilt=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);for(let entry of authoritative)rebuilt.appendEntry(entry);let authoritativeIds=new Set(authoritative.map(entry=>entry.id));for(let entry of mirror)!idsAtRefreshStart.has(entry.id)&&!authoritativeIds.has(entry.id)&&rebuilt.appendEntry(entry);sessionManager=rebuilt}}messages=sessionManager.buildSessionContext().messages}else messages=await transportCall("refresh",()=>client.getMessages(),[]);local.agent.state.messages.splice(0,local.agent.state.messages.length,...structuredClone(messages)),streamingAssistant=void 0},refreshChain=Promise.resolve(),refresh=()=>{let next=refreshChain.then(performRefresh,performRefresh);return refreshChain=next.then(()=>{},()=>{}),next};return{session:new Proxy(local,{get(target,property,receiver){if(property==="prompt")return async(message,options)=>{try{await client.prompt(message,{...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?.promptDisposition?{promptDisposition:options.promptDisposition}:{},...options?.preflightResult?{preflightResult:options.preflightResult}:{}})}catch(error){if(!isTransportGoneError(error))throw error;reportActionFailure("prompt")(error)}};if(property==="abort")return()=>client.abort();if(property==="abortCompaction")return()=>{client.abortCompaction().catch(reportActionFailure("abortCompaction"))};if(property==="steer")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,steering:[...state.steering,message],ordered:[...state.ordered,{text:message,mode:"steer",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("steer",()=>client.steer(message,images,{...recovery,enqueueOrder}))};if(property==="followUp")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,followUp:[...state.followUp,message],ordered:[...state.ordered,{text:message,mode:"followUp",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("followUp",()=>client.followUp(message,images,{...recovery,enqueueOrder}))};if(property==="waitForIdle")return()=>client.waitForIdle();if(property==="getLastAssistantText")return()=>target.getLastAssistantText();if(property==="setModel"||property==="setSessionModel")return async model=>{let next=await transportCall("setModel",()=>client.setModel(model.provider,model.id),void 0);return next?{systemPromptName:next.systemPromptName,model:next}:void 0};if(property==="setSessionThinkingLevel")return level=>{client.setThinkingLevel(level,{scope:"turn"}).catch(reportActionFailure("setSessionThinkingLevel"))};if(property==="setSessionFastMode")return enabled=>{client.setFastMode(enabled).catch(reportActionFailure("setSessionFastMode"))};if(property==="abortRetry")return()=>{client.abortRetry().catch(reportActionFailure("abortRetry"))};if(property==="setAutoRetryEnabled")return enabled=>{client.setAutoRetry(enabled).catch(reportActionFailure("setAutoRetryEnabled"))};if(property==="reserveQueuedInputOrder")return()=>++nextQueuedInputOrder;if(property==="setFavoriteModels")return models=>{state={...state,favoriteModels:[...models]},client.setFavoriteModels(models).catch(reportActionFailure("setFavoriteModels"))};if(property==="setScopedModels")return models=>{state={...state,scopedModels:[...models]},client.setScopedModels(models).catch(reportActionFailure("setScopedModels"))};if(property==="cycleModel")return direction=>transportCall("cycleModel",()=>client.cycleModel(direction),void 0);if(property==="setThinkingLevel")return level=>{client.setThinkingLevel(level).catch(reportActionFailure("setThinkingLevel"))};if(property==="cycleThinkingLevel")return()=>transportCall("cycleThinkingLevel",()=>client.cycleThinkingLevel(),void 0).then(result=>result?.level);if(property==="getAvailableThinkingLevels")return()=>transportCall("getAvailableThinkingLevels",()=>client.getAvailableThinkingLevels(),[]);if(property==="setSteeringMode")return mode=>{client.setSteeringMode(mode).catch(reportActionFailure("setSteeringMode"))};if(property==="setFollowUpMode")return mode=>{client.setFollowUpMode(mode).catch(reportActionFailure("setFollowUpMode"))};if(property==="compact")return instructions=>transportCall("compact",()=>client.compact(instructions));if(property==="setAutoCompactionEnabled")return enabled=>{client.setAutoCompaction(enabled).catch(reportActionFailure("setAutoCompaction"))};if(property==="executeBash")return async(command,onChunk,options)=>{if(options?.operations&&typeof options.operations.exec=="function"){let abortController=new AbortController;localBashAbortController=abortController,localBashRunning=!0,updateBashState();let sessionAtStart=state.sessionId,prefix=settingsManager.getShellCommandPrefix(),resolvedCommand=prefix?`${prefix}
|
|
2
|
+
import{RpcClient,RpcCommandError,SessionManager,executeBashWithOperations,isTransportGoneError}from"./chunk-F2YU5BZG.js";import{SessionStreamingError,UserEditError}from"./chunk-AIM2YESB.js";import{SettingsManager}from"./chunk-CXVI2YV7.js";import{ensureHost}from"./chunk-LM2UMEX6.js";import{QUESTION_CAPABILITY,RENDERED_COMPONENTS_CAPABILITY}from"./chunk-CEMOA3TF.js";import"./chunk-Y4CH7LYI.js";import"./chunk-E5F5SVZF.js";import"./chunk-ASAQQ6VM.js";import"./chunk-7X72IACK.js";import"./chunk-L4OOEWAT.js";import"./chunk-26UBFF6N.js";import"./chunk-TOCWAEQB.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-UDTWLXSQ.js";import"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-J5TMX734.js";import"./chunk-TJV2LFKM.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-7X4ZMME4.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";import{randomUUID}from"node:crypto";import{rm}from"node:fs/promises";async function attachEnsuredHost(ensure,client){let ensured=await ensure();try{await client.start()}finally{ensured?.release()}}var HOST_CLIENT_CAPABILITIES=[RENDERED_COMPONENTS_CAPABILITY,QUESTION_CAPABILITY],INTERACTIVE_HOST_FALLBACK_WARNING="Warning: shared interactive host unavailable; continuing locally",INTERACTIVE_HOST_RECONNECTING_WARNING="Warning: shared interactive host connection lost; reconnecting";async function createInteractiveHostRuntime(localRuntime,options){let sessionPath=localRuntime.session.sessionFile;if(!sessionPath)return localRuntime;let startHost=options.ensureHost??(hostOptions=>ensureHost(hostOptions)),remoteSession,remoteRuntime,reconnecting,disconnectQueued=!1,disposed=!1,fallbackWarned=!1,reconnectWarningShown=!1,warnReconnect=cause=>{reconnectWarningShown||(reconnectWarningShown=!0,options.onWarning?.({type:"interactive_host_action_failed",message:INTERACTIVE_HOST_RECONNECTING_WARNING,cause}))},warnFallback=cause=>{fallbackWarned||(fallbackWarned=!0,options.onWarning?.({type:"interactive_host_fallback",message:INTERACTIVE_HOST_FALLBACK_WARNING,cause}))},scheduleReconnect=()=>{},client=new RpcClient({socketPath:options.socket,onDisconnect:()=>{disconnectQueued=!0,scheduleReconnect()}});scheduleReconnect=()=>{!remoteSession||reconnecting||disposed||remoteRuntime?.isFallback||(remoteRuntime?.enterReconnecting(),reconnecting=(async()=>{let cause;for(let attempt=0;attempt<3;attempt++){if(disposed)return;disconnectQueued=!1;try{if(await attachEnsuredHost(()=>startHost({socket:options.socket,agentDir:options.agentDir}),client),disposed||(await client.openSession({sessionPath,cwd:localRuntime.cwd}),disposed)||(remoteRuntime&&await remoteRuntime.reRegisterClientInfo(),disposed)||(await remoteSession.refresh(),disposed))return;fallbackWarned=!1,reconnectWarningShown=!1,remoteRuntime?.enterConnected();return}catch(error){if(cause=error,await client.stop().catch(()=>{}),disposed)return}}disposed||(await remoteRuntime?.enterFallback(),warnFallback(cause))})().finally(()=>{reconnecting=void 0,disconnectQueued&&!disposed&&!remoteRuntime?.isFallback&&scheduleReconnect()}))};try{await attachEnsuredHost(()=>startHost({socket:options.socket,agentDir:options.agentDir}),client),await client.setClientInfo(80,[...HOST_CLIENT_CAPABILITIES]);let startupEvents=[],stopBuffering=client.onEvent(event=>startupEvents.push(event)),opened=await client.openSession({sessionPath,cwd:localRuntime.cwd,provider:localRuntime.session.model?.provider,modelId:localRuntime.session.model?.id,thinkingLevel:localRuntime.session.thinkingLevel});return remoteSession=createRemoteSessionProxy(localRuntime.session,localRuntime.services.agentDir,client,opened.state,options.onWarning,cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},startupEvents.filter(event=>!("sessionId"in event)||event.sessionId===opened.sessionId)),stopBuffering(),opened.state.isBashRunning&&!opened.attached&&await client.abortBash().catch(()=>{}),opened.attached&&await remoteSession.refresh(),remoteRuntime=new RemoteInteractiveRuntime(localRuntime,remoteSession,client,{onTransportGone:cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},get reconnecting(){return reconnecting},dispose:()=>{disposed=!0}}),remoteRuntime}catch(cause){return await client.stop().catch(()=>{}),warnFallback(cause),localRuntime}}var RemoteInteractiveRuntime=class{#local;#remoteSession;#client;#lifecycle;#onTransportGone;#rebindSession;#beforeSessionInvalidate;#state="connected";#fallbackHandoff;get isReconnecting(){return this.#state==="reconnecting"}get isFallback(){return this.#state==="fallback"}constructor(local,remoteSession,client,lifecycle){this.#local=local,this.#remoteSession=remoteSession,this.#client=client,this.#lifecycle=lifecycle,this.#onTransportGone=lifecycle?.onTransportGone??(()=>{})}async#call(call){try{return await call()}catch(error){if(isTransportGoneError(error))return this.#onTransportGone(error),{cancelled:!0};throw error}}enterConnected(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="connected")}enterReconnecting(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="reconnecting")}async enterFallback(){if(this.#state==="disposed"||this.#state==="fallback")return;this.#state="fallback",this.#beforeSessionInvalidate?.();let rebind=this.#rebindSession?.();rebind&&(this.#fallbackHandoff=rebind.catch(error=>{this.#onTransportGone(error)}),await this.#fallbackHandoff)}get session(){return this.#state==="fallback"||this.#state==="disposed"?this.#local.session:this.#remoteSession.session}get services(){return this.#local.services}get cwd(){return this.session.sessionManager.getCwd()}get diagnostics(){return this.#local.diagnostics}get modelFallbackMessage(){return this.#local.modelFallbackMessage}get launchProfile(){return this.#local.launchProfile}setBeforeSessionInvalidate(callback){this.#beforeSessionInvalidate=callback,this.#local.setBeforeSessionInvalidate(callback)}setRebindSession(callback){this.#rebindSession=callback,this.#local.setRebindSession(callback),callback&&this.#state==="fallback"&&!this.#fallbackHandoff&&(this.#fallbackHandoff=callback().catch(error=>{this.#onTransportGone(error)}))}setHostUiHandler(callback){this.#remoteSession.setHostUiHandler(callback)}sendHostUiProgress(record){this.#client.sendExtensionUIProgress(record).catch(()=>{})}#clientInfoSent=!1;#lastClientWidth=80;setClientInfo(width){this.#lastClientWidth=width;let capabilities=this.#clientInfoSent?void 0:[...HOST_CLIENT_CAPABILITIES];this.#clientInfoSent=!0,this.#client.setClientInfo(width,capabilities).catch(()=>{})}async reRegisterClientInfo(){await this.#client.setClientInfo(this.#lastClientWidth,[...HOST_CLIENT_CAPABILITIES])}async dispose(){if(this.#state==="disposed")return;this.#state="disposed",this.#lifecycle?.dispose(),await this.#lifecycle?.reconnecting?.catch(()=>{}),await this.#fallbackHandoff?.catch(()=>{});let errors=[];for(let cleanup of[()=>this.#remoteSession.abortLocalBash(),()=>this.#client.closeSession(),()=>this.#client.stop(),()=>this.#local.dispose()])try{await cleanup()}catch(error){errors.push(error)}if(errors.length>0)throw errors[0]}async newSession(options){return this.#state==="fallback"?this.#local.newSession(options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.newSession(options?.parentSession));if(!result.cancelled){if(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),options?.setup){let capture=SessionManager.inMemory(this.#remoteSession.session.sessionManager.getCwd());await options.setup(capture);for(let entry of capture.getEntries())await this.#client.appendSessionEntry(entry);await this.#remoteSession.refresh()}await this.#rebindSession?.(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())}return result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async switchSession(sessionPath,options){return this.#state==="fallback"?this.#local.switchSession(sessionPath,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.switchSession(sessionPath,options?.cwdOverride===void 0?void 0:{cwdOverride:options.cwdOverride}));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),await this.#rebindSession?.(),options?.projectTrustContextFactory?.(this.#remoteSession.session.sessionManager.getCwd()),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async fork(entryId,options){return this.#state==="fallback"?this.#local.fork(entryId,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.fork(entryId,options));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),{cancelled:result.cancelled,selectedText:result.text}}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async importFromJsonl(inputPath,cwdOverride){return this.#state==="fallback"?this.#local.importFromJsonl(inputPath,cwdOverride):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.importJsonl(inputPath,cwdOverride));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind()),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async#refreshAndRebind(){await this.#remoteSession.refresh(),await this.#rebindSession?.()}};function createRemoteSessionProxy(local,agentDir,client,initialState,onWarning,onTransportGone,startupEvents=[]){let reportActionFailure=action=>error=>{isTransportGoneError(error)?onTransportGone?.(error):onWarning?.({type:"interactive_host_action_failed",message:`Warning: shared interactive host ${action} failed: ${error instanceof Error?error.message:String(error)}`,cause:error})},transportCall=async(action,call,cancelledValue)=>{try{return await call()}catch(error){if(!isTransportGoneError(error))throw error;return reportActionFailure(action)(error),cancelledValue}},state={...initialState},waitForBashCallbacks=async(promises,allowAbandonment)=>{if(promises.size===0)return!0;let settled=Promise.allSettled([...promises]).then(()=>!0),timeout,bounded=new Promise(resolve=>{timeout=setTimeout(resolve,allowAbandonment?100:5e3,!1),timeout.unref?.()});try{return await Promise.race([settled,bounded])}finally{timeout&&clearTimeout(timeout)}},executionNamespace=randomUUID(),cleanupRemoteBashOutput=async path=>{let cleanupTimeout;try{await Promise.race([client.cleanupBashOutput(path),new Promise((_,reject)=>{cleanupTimeout=setTimeout(()=>reject(new Error("RPC cleanup timed out")),1e3)})]);return}catch(transportError){try{await rm(path,{force:!0});return}catch(localError){onWarning?.({type:"interactive_host_action_failed",message:`Warning: failed to clean up shared bash output spill: ${localError instanceof Error?localError.message:String(localError)}`,cause:new AggregateError([transportError,localError])})}}finally{cleanupTimeout&&clearTimeout(cleanupTimeout)}},nextBashExecutionId=0,bashExecutions=new Map,hostUiHandler,pendingUiRequests=[],localBashAbortController,localBashRunning=!1,hostBashRunning=initialState.isBashRunning,nextQueuedInputOrder=Math.max(0,...initialState.ordered.map(item=>item.enqueueOrder)),sessionManager=local.sessionManager,settingsManager=SettingsManager.create(initialState.cwd,agentDir,{projectTrusted:initialState.projectTrusted}),updateBashState=()=>{state={...state,isBashRunning:localBashRunning||hostBashRunning}},remoteSessionManager=new Proxy({},{get(_target,property,_receiver){if(property==="appendLabelChange")return(entryId,label)=>{client.setLabel(entryId,label).catch(reportActionFailure("appendLabelChange"))};if(property==="getCwd")return()=>state.cwd;if(property==="getSessionName")return()=>state.sessionName;if(property==="getUsageTotals")return()=>state.usageTotals;let value=Reflect.get(sessionManager,property,sessionManager);return typeof value=="function"?value.bind(sessionManager):value}}),streamingAssistant,mirroredCurrentAssistantUsage=!1,localReplacementDepth=0,listeners=new Set,handleWireEvent=wireEvent=>{if(wireEvent.type==="extension_ui_request"){let request=wireEvent;hostUiHandler?Promise.resolve(hostUiHandler(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response")):pendingUiRequests.push(request);return}if(wireEvent.type==="session_replaced"){localReplacementDepth===0&&refresh().catch(reportActionFailure("session refresh after replacement"));return}if(wireEvent.type==="agent_settled"&&(state={...state,isStreaming:!1,retryAttempt:0}),wireEvent.type==="bash_start"&&(hostBashRunning=!0,updateBashState()),wireEvent.type==="bash_end"&&(hostBashRunning=!1,updateBashState()),wireEvent.type==="bash_execution_update"&&wireEvent.id){let execution=bashExecutions.get(wireEvent.id);if(execution?.chunk&&!execution.hasError)try{let callbackPromise=Promise.resolve(execution.chunk(wireEvent.delta)).catch(error=>{throw execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{})),error});execution.promises.add(callbackPromise),callbackPromise.catch(()=>{}).finally(()=>execution.promises.delete(callbackPromise))}catch(error){execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{}))}}if(wireEvent.type==="agent_start"&&(state={...state,isStreaming:!0}),wireEvent.type==="compaction_start"&&(state={...state,isCompacting:!0}),wireEvent.type==="compaction_end"&&(state={...state,isCompacting:!1}),wireEvent.type==="auto_retry_start"&&(state={...state,retryAttempt:wireEvent.attempt}),wireEvent.type==="auto_retry_end"&&(state={...state,retryAttempt:0}),wireEvent.type==="queue_update"&&(nextQueuedInputOrder=Math.max(nextQueuedInputOrder,...wireEvent.ordered.map(item=>item.enqueueOrder)),state={...state,steering:[...wireEvent.steering],followUp:[...wireEvent.followUp],ordered:[...wireEvent.ordered],pendingMessageCount:wireEvent.steering.length+wireEvent.followUp.length}),wireEvent.type==="model_changed"&&(state={...state,model:wireEvent.model,thinkingLevel:wireEvent.thinkingLevel}),wireEvent.type==="thinking_level_changed"&&(state={...state,thinkingLevel:wireEvent.level}),wireEvent.type==="service_tier_changed"&&(state={...state,serviceTier:wireEvent.tier,fastMode:wireEvent.fastMode}),wireEvent.type==="session_settings_changed"&&(state={...state,steeringMode:wireEvent.steeringMode,followUpMode:wireEvent.followUpMode,autoCompactionEnabled:wireEvent.autoCompactionEnabled}),wireEvent.type==="entry_appended")try{sessionManager.appendEntry(wireEvent.entry),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}if(wireEvent.type==="session_info_changed"&&(state={...state,sessionName:wireEvent.name}),wireEvent.type==="message_start"&&(wireEvent.message.role==="assistant"&&(streamingAssistant=structuredClone(wireEvent.message),mirroredCurrentAssistantUsage=!1),local.agent.state.messages.push(structuredClone(wireEvent.message))),wireEvent.type==="message_end"){if(wireEvent.message.role==="assistant"){streamingAssistant=structuredClone(wireEvent.message);let usage=wireEvent.message.usage;if(usage&&!mirroredCurrentAssistantUsage){mirroredCurrentAssistantUsage=!0;let latestPromptTokens=usage.input+usage.cacheRead+usage.cacheWrite,contextWindow=state.model?.contextWindow??0,contextTokens=usage.input+usage.cacheRead+usage.cacheWrite;state={...state,contextUsage:contextWindow>0?{tokens:contextTokens,contextWindow,percent:contextTokens/contextWindow*100}:void 0,usageTotals:{...state.usageTotals,input:state.usageTotals.input+usage.input,output:state.usageTotals.output+usage.output,cacheRead:state.usageTotals.cacheRead+usage.cacheRead,cacheWrite:state.usageTotals.cacheWrite+usage.cacheWrite,cost:state.usageTotals.cost+(usage.cost?.total??0),latestCacheHitRate:latestPromptTokens>0?usage.cacheRead/latestPromptTokens*100:void 0}}}}let messages=local.agent.state.messages;messages.at(-1)?.role===wireEvent.message.role&&(messages[messages.length-1]=structuredClone(wireEvent.message))}if(wireEvent.type==="compaction_end"&&wireEvent.accepted&&!wireEvent.aborted)try{local.sessionManager.reloadFromDisk?.(),sessionManager!==local.sessionManager&&sessionManager.reloadFromDisk?.(),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}let event=hydrateMessageUpdate(wireEvent,streamingAssistant);for(let listener of listeners)listener(event)};client.onEvent(handleWireEvent);for(let event of startupEvents)handleWireEvent(event);let performRefresh=async()=>{let idsAtRefreshStart=new Set(sessionManager.getEntries().map(entry=>entry.id)),nextState=await transportCall("refresh",()=>client.getState());if(!nextState)return;state={...nextState},nextQueuedInputOrder=Math.max(0,...nextState.ordered.map(item=>item.enqueueOrder));let messages;if(settingsManager=SettingsManager.create(nextState.cwd,agentDir,{projectTrusted:nextState.projectTrusted}),nextState.sessionFile){sessionManager.getSessionFile()===nextState.sessionFile?sessionManager.reloadFromDisk?.():sessionManager=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);let authoritative=nextState.entries;if(authoritative?.length){let mirror=sessionManager.getEntries();if(!(mirror.length===authoritative.length&&mirror.every((entry,index)=>entry.id===authoritative[index]?.id))){let rebuilt=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);for(let entry of authoritative)rebuilt.appendEntry(entry);let authoritativeIds=new Set(authoritative.map(entry=>entry.id));for(let entry of mirror)!idsAtRefreshStart.has(entry.id)&&!authoritativeIds.has(entry.id)&&rebuilt.appendEntry(entry);sessionManager=rebuilt}}messages=sessionManager.buildSessionContext().messages}else messages=await transportCall("refresh",()=>client.getMessages(),[]);local.agent.state.messages.splice(0,local.agent.state.messages.length,...structuredClone(messages)),streamingAssistant=void 0},refreshChain=Promise.resolve(),refresh=()=>{let next=refreshChain.then(performRefresh,performRefresh);return refreshChain=next.then(()=>{},()=>{}),next};return{session:new Proxy(local,{get(target,property,receiver){if(property==="prompt")return async(message,options)=>{try{await client.prompt(message,{...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?.promptDisposition?{promptDisposition:options.promptDisposition}:{},...options?.preflightResult?{preflightResult:options.preflightResult}:{}})}catch(error){if(!isTransportGoneError(error))throw error;reportActionFailure("prompt")(error)}};if(property==="abort")return()=>client.abort();if(property==="abortCompaction")return()=>{client.abortCompaction().catch(reportActionFailure("abortCompaction"))};if(property==="steer")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,steering:[...state.steering,message],ordered:[...state.ordered,{text:message,mode:"steer",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("steer",()=>client.steer(message,images,{...recovery,enqueueOrder}))};if(property==="followUp")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,followUp:[...state.followUp,message],ordered:[...state.ordered,{text:message,mode:"followUp",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("followUp",()=>client.followUp(message,images,{...recovery,enqueueOrder}))};if(property==="waitForIdle")return()=>client.waitForIdle();if(property==="getLastAssistantText")return()=>target.getLastAssistantText();if(property==="setModel"||property==="setSessionModel")return async model=>{let next=await transportCall("setModel",()=>client.setModel(model.provider,model.id),void 0);return next?{systemPromptName:next.systemPromptName,model:next}:void 0};if(property==="setSessionThinkingLevel")return level=>{client.setThinkingLevel(level,{scope:"turn"}).catch(reportActionFailure("setSessionThinkingLevel"))};if(property==="setSessionFastMode")return enabled=>{client.setFastMode(enabled).catch(reportActionFailure("setSessionFastMode"))};if(property==="abortRetry")return()=>{client.abortRetry().catch(reportActionFailure("abortRetry"))};if(property==="setAutoRetryEnabled")return enabled=>{client.setAutoRetry(enabled).catch(reportActionFailure("setAutoRetryEnabled"))};if(property==="reserveQueuedInputOrder")return()=>++nextQueuedInputOrder;if(property==="setFavoriteModels")return models=>{state={...state,favoriteModels:[...models]},client.setFavoriteModels(models).catch(reportActionFailure("setFavoriteModels"))};if(property==="setScopedModels")return models=>{state={...state,scopedModels:[...models]},client.setScopedModels(models).catch(reportActionFailure("setScopedModels"))};if(property==="cycleModel")return direction=>transportCall("cycleModel",()=>client.cycleModel(direction),void 0);if(property==="setThinkingLevel")return level=>{client.setThinkingLevel(level).catch(reportActionFailure("setThinkingLevel"))};if(property==="cycleThinkingLevel")return()=>transportCall("cycleThinkingLevel",()=>client.cycleThinkingLevel(),void 0).then(result=>result?.level);if(property==="getAvailableThinkingLevels")return()=>transportCall("getAvailableThinkingLevels",()=>client.getAvailableThinkingLevels(),[]);if(property==="setSteeringMode")return mode=>{client.setSteeringMode(mode).catch(reportActionFailure("setSteeringMode"))};if(property==="setFollowUpMode")return mode=>{client.setFollowUpMode(mode).catch(reportActionFailure("setFollowUpMode"))};if(property==="compact")return instructions=>transportCall("compact",()=>client.compact(instructions));if(property==="setAutoCompactionEnabled")return enabled=>{client.setAutoCompaction(enabled).catch(reportActionFailure("setAutoCompaction"))};if(property==="executeBash")return async(command,onChunk,options)=>{if(options?.operations&&typeof options.operations.exec=="function"){let abortController=new AbortController;localBashAbortController=abortController,localBashRunning=!0,updateBashState();let sessionAtStart=state.sessionId,prefix=settingsManager.getShellCommandPrefix(),resolvedCommand=prefix?`${prefix}
|
|
3
3
|
${command}`:command;try{let result=await executeBashWithOperations(resolvedCommand,state.cwd,options.operations,{onChunk,signal:abortController.signal});return state.sessionId===sessionAtStart&&await transportCall("recordBashResult",()=>client.recordBashResult(command,result,options.excludeFromContext)),result}finally{localBashAbortController=void 0,localBashRunning=!1,updateBashState()}}let executionId=`bash-${executionNamespace}-${++nextBashExecutionId}`,execution={chunk:onChunk,promises:new Set,error:void 0,hasError:!1};bashExecutions.set(executionId,execution);try{let result=await transportCall("bash",()=>client.bash(command,{excludeFromContext:options?.excludeFromContext,executionId,operations:options?.operations}),{output:"",exitCode:void 0,cancelled:!0,truncated:!1});if(!await waitForBashCallbacks(execution.promises,!1))throw result.fullOutputPath&&await cleanupRemoteBashOutput(result.fullOutputPath),new Error("Bash output callback did not settle within 5000ms");if(execution.hasError)throw result.fullOutputPath&&await cleanupRemoteBashOutput(result.fullOutputPath),execution.error;return result}finally{bashExecutions.delete(executionId)}};if(property==="abortBash")return()=>{localBashAbortController?localBashAbortController.abort():client.abortBash().catch(reportActionFailure("abortBash"))};if(property==="getContextUsage")return()=>state.contextUsage;if(property==="getSessionStats")return()=>transportCall("getSessionStats",()=>client.getSessionStats(),local.getSessionStats());if(property==="exportToHtml")return(outputPath,options)=>transportCall("exportToHtml",()=>client.exportHtml(outputPath,options?.themeName)).then(result=>result?.path);if(property==="setSessionName")return name=>client.setSessionName(name).catch(reportActionFailure("setSessionName"));if(property==="navigateTree")return async(targetId,options)=>{let result=await transportCall("navigateTree",()=>client.navigateTree(targetId,options),{cancelled:!0});return result.cancelled||await refresh(),result};if(property==="editAssistantMessage")return async(entryId,text,options)=>{let result=await client.editAssistantMessage(entryId,text,{expectedLeafId:options?.expectedLeafId,summarize:options?.summarize,customInstructions:options?.customInstructions});return result.outcome==="unchanged"?{cancelled:!1,unchanged:!0}:result.outcome==="cancelled"?{cancelled:!0,aborted:result.aborted}:(await refresh(),{cancelled:!1,entryId:result.entry.id})};if(property==="editUserMessage")return async(entryId,text,options)=>{let result;try{result=await client.editUserMessage(entryId,text,{expectedLeafId:options?.expectedLeafId,summarize:options?.summarize,customInstructions:options?.customInstructions})}catch(error){if(error instanceof RpcCommandError)switch(error.errorCode){case"streaming":throw new SessionStreamingError;case"not_found":throw new UserEditError("not-found",error.message);case"not_user":throw new UserEditError("not-user",error.message);case"empty":throw new UserEditError("empty",error.message);case"stale_leaf":throw new UserEditError("stale-leaf",error.message)}throw error}return result.outcome==="unchanged"?{cancelled:!1,unchanged:!0}:result.outcome==="cancelled"?{cancelled:!0,aborted:result.aborted}:(await refresh(),{cancelled:!1,entryId:result.entry.id})};if(property==="getUserMessagesForForking")return()=>transportCall("getUserMessagesForForking",()=>client.getForkMessages(),[]);if(property==="subscribe")return listener=>{listeners.add(listener);let localUnsubscribe=target.subscribe(listener);return()=>{listeners.delete(listener),localUnsubscribe()}};if(property==="isStreaming")return state.isStreaming;if(property==="isIdle")return!state.isStreaming;if(property==="isCompacting")return state.isCompacting;if(property==="pendingMessageCount")return state.pendingMessageCount;if(property==="getSteeringMessages")return()=>state.steering;if(property==="getFollowUpMessages")return()=>state.followUp;if(property==="clearQueue")return options=>{let result={steering:[...state.steering],followUp:[...state.followUp],ordered:[...state.ordered]};return Object.defineProperty(result,"ordered",{value:result.ordered,enumerable:!1}),client.clearQueue(options).catch(reportActionFailure("clearQueue")),result};if(property==="abortBranchSummary")return()=>{client.abortBranchSummary().catch(reportActionFailure("abortBranchSummary"))};if(property==="recordBashResult")return(command,result,options)=>{client.recordBashResult(command,result,options?.excludeFromContext).catch(reportActionFailure("recordBashResult"))};if(property!=="set_label"){if(property==="retryAttempt")return state.retryAttempt;if(property==="isBashRunning")return state.isBashRunning;if(property==="reload")return _options=>transportCall("reload",()=>client.reload(),{cancelled:!0});if(property==="checkReloadVeto")return()=>transportCall("checkReloadVeto",()=>client.checkReloadVeto(),{cancelled:!0});if(property==="exportToJsonl")return outputPath=>transportCall("exportToJsonl",()=>client.exportJsonl(outputPath)).then(result=>result?.path);if(property==="state"){let localState=target.state;return{...localState,model:state.model??localState.model,thinkingLevel:state.thinkingLevel,isStreaming:state.isStreaming,isCompacting:state.isCompacting}}return property==="sessionFile"?state.sessionFile:property==="sessionId"?state.sessionId:property==="sessionName"?state.sessionName:property==="serviceTier"?state.serviceTier:property==="steeringMode"?state.steeringMode:property==="followUpMode"?state.followUpMode:property==="autoCompactionEnabled"?state.autoCompactionEnabled:property==="isFastModeActive"?()=>state.fastMode:property==="sessionManager"?remoteSessionManager:property==="settingsManager"?settingsManager:property==="messages"?target.messages:property==="favoriteModels"?state.favoriteModels:property==="scopedModels"?state.scopedModels:property==="model"?state.model??target.model:property==="thinkingLevel"?state.thinkingLevel:Reflect.get(target,property,receiver)}}}),setHostUiHandler:callback=>{if(hostUiHandler=callback,callback)for(let request of pendingUiRequests.splice(0))Promise.resolve(callback(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response"))},refresh,aroundLocalReplacement:async body=>{localReplacementDepth++;try{return await body()}finally{localReplacementDepth--}},abortLocalBash:()=>localBashAbortController?.abort(),createReplacedSessionContext:()=>{let context=local.createReplacedSessionContext();return Object.defineProperty(context,"cwd",{value:state.cwd}),Object.defineProperty(context,"sessionManager",{value:remoteSessionManager}),context.sendMessage=(message,options)=>transportCall("sendMessage",()=>client.sendCustomMessage(message,{triggerTurn:options?.triggerTurn,deliverAs:options?.deliverAs})),context.sendUserMessage=(content,options)=>{if(typeof content=="string")return transportCall("sendUserMessage",()=>client.prompt(content,{streamingBehavior:options?.deliverAs,expandPromptTemplates:options?.expandPromptTemplates}));let text=content.filter(part=>part.type==="text").map(part=>part.text).join(`
|
|
4
4
|
`),images=content.filter(part=>part.type==="image");return transportCall("sendUserMessage",()=>client.prompt(text,{images,streamingBehavior:options?.deliverAs,expandPromptTemplates:options?.expandPromptTemplates}))},context}}}function hydrateMessageUpdate(event,streamingAssistant){if(event.type!=="message_update"||!streamingAssistant)return event;let update=event.assistantMessageEvent;if(update.type!=="text_delta"&&update.type!=="thinking_delta"&&update.type!=="toolcall_delta")return event;let content=streamingAssistant.content[update.contentIndex];if(update.type==="text_delta"&&content?.type==="text"&&(content.text+=update.delta),update.type==="thinking_delta"&&content?.type==="thinking"&&(content.thinking+=update.delta),update.type==="toolcall_delta"&&content?.type==="toolCall"){let raw=JSON.stringify(content.arguments)+update.delta;try{let parsed=JSON.parse(raw);typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed)&&(content.arguments=parsed)}catch{}}return streamingAssistant.usage=event.usage,{type:"message_update",message:structuredClone(streamingAssistant),assistantMessageEvent:{...update,partial:structuredClone(streamingAssistant)}}}function isInteractiveHostEvent(event){return typeof event=="object"&&event!==null&&"type"in event}export{INTERACTIVE_HOST_FALLBACK_WARNING,INTERACTIVE_HOST_RECONNECTING_WARNING,RemoteInteractiveRuntime,createInteractiveHostRuntime,createRemoteSessionProxy,isInteractiveHostEvent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
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 = () => {}; } }
|
|
2
|
-
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-
|
|
2
|
+
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-56COAYOU.js";import"./chunk-FAV4DX74.js";import"./chunk-VW3QZSX3.js";import"./chunk-YJUO37UX.js";import"./chunk-TFA3YAJK.js";import"./chunk-F2YU5BZG.js";import"./chunk-NZRVAZL2.js";import"./chunk-U5KVIAHJ.js";import{isApiKeyLoginProvider}from"./chunk-DB2X7SOZ.js";import"./chunk-3HCYHGK2.js";import"./chunk-6BWCPOCV.js";import"./chunk-AIM2YESB.js";import"./chunk-CXVI2YV7.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-JASECXGC.js";import"./chunk-LM2UMEX6.js";import"./chunk-CEMOA3TF.js";import"./chunk-Y4CH7LYI.js";import"./chunk-E5F5SVZF.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-SQUUL72H.js";import"./chunk-JK5LVAOU.js";import"./chunk-ASAQQ6VM.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-B32PXL7U.js";import"./chunk-Y5A6TKBN.js";import"./chunk-L4OOEWAT.js";import"./chunk-26UBFF6N.js";import"./chunk-TOCWAEQB.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-UDTWLXSQ.js";import"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-J5TMX734.js";import"./chunk-LHYG7TK7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TJV2LFKM.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-7X4ZMME4.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
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 = () => {}; } }
|
|
2
|
-
import{TIP_DEFINITIONS}from"./chunk-
|
|
2
|
+
import{TIP_DEFINITIONS}from"./chunk-YJUO37UX.js";import{KeybindingsManager}from"./chunk-TFA3YAJK.js";import"./chunk-6BWCPOCV.js";import"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";function collectTips(){let keybindings=new KeybindingsManager,keys=binding=>keybindings.getKeys(binding).join("/");return TIP_DEFINITIONS.map(tip=>{let text=tip.render(keys);return tip.requiresCommand!==void 0?{id:tip.id,text,requiresCommand:tip.requiresCommand}:{id:tip.id,text}})}function listTips(){console.log(JSON.stringify(collectTips(),null,2))}export{collectTips,listTips};
|
package/dist/bundle/chunks/{multi-session-host-7KCH3HUA.js → multi-session-host-LJNXZRFA.js}
RENAMED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
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 = () => {}; } }
|
|
2
|
-
import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,isSessionBusySnapshot,readOwnFootprint,runWithProviderScope,startHostChildReaper}from"./chunk-
|
|
2
|
+
import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,isSessionBusySnapshot,readOwnFootprint,runWithProviderScope,startHostChildReaper}from"./chunk-56COAYOU.js";import"./chunk-FAV4DX74.js";import"./chunk-VW3QZSX3.js";import"./chunk-YJUO37UX.js";import"./chunk-TFA3YAJK.js";import{SessionManager,assertValidSessionId}from"./chunk-F2YU5BZG.js";import"./chunk-NZRVAZL2.js";import"./chunk-U5KVIAHJ.js";import{RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_WARM_FAILED,SessionEventWriter,buildRpcSessionState,createRpcConnectionHandler,recordLoopBlockedMs,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError}from"./chunk-DB2X7SOZ.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-3HCYHGK2.js";import"./chunk-6BWCPOCV.js";import"./chunk-AIM2YESB.js";import"./chunk-CXVI2YV7.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-JASECXGC.js";import{GENERATION_HANDOFF_CAPABILITY,runAsHostGenerationProcess}from"./chunk-LM2UMEX6.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,WARM_CAPABILITY,hostGeneration,hostInstanceId,parseClientCapabilities,protocolIdentity}from"./chunk-CEMOA3TF.js";import{ClientOccupancy,PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,armHostWatchdog,authenticateSocket,canonicalSessionPath,createEndpointReservations,ensureSocketSecret,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv,readSocketIdentityFile,resolveSocketTransportAddress,sessionDirectoryRemoved,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-Y4CH7LYI.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-E5F5SVZF.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-SQUUL72H.js";import"./chunk-JK5LVAOU.js";import{killTrackedDetachedChildren}from"./chunk-ASAQQ6VM.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-B32PXL7U.js";import"./chunk-Y5A6TKBN.js";import"./chunk-L4OOEWAT.js";import"./chunk-26UBFF6N.js";import"./chunk-TOCWAEQB.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-UDTWLXSQ.js";import"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-J5TMX734.js";import"./chunk-LHYG7TK7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TJV2LFKM.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-7X4ZMME4.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";import{access as access2,chmod,mkdir,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{basename,dirname,join}from"node:path";var RPC_SESSION_IDLE_EVICTION_MS_ENV="SENPI_RPC_SESSION_IDLE_EVICTION_MS",RPC_HOST_EMPTY_EXIT_MS_ENV="SENPI_RPC_HOST_EMPTY_EXIT_MS",RPC_CLOSE_GRACE_MS_ENV="SENPI_RPC_CLOSE_GRACE_MS",DEFAULT_SESSION_IDLE_EVICTION_MS=30*6e4,DEFAULT_HOST_EMPTY_EXIT_MS=15*6e4;function resolveHostIdlePolicy(env,overrides={}){return{now:overrides.now??Date.now,idleEvictionMs:overrides.idleEvictionMs??parseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV])??DEFAULT_SESSION_IDLE_EVICTION_MS,emptyExitMs:overrides.emptyExitMs??parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV])??DEFAULT_HOST_EMPTY_EXIT_MS}}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB",DEFAULT_HOST_RSS_WARN_MB=4096,HOST_MEMORY_SAMPLE_MS=3e4,HOST_MEMORY_STDERR_INTERVAL_MS=5*6e4,BYTES_PER_MEGABYTE=1024*1024;function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.idleReported=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,options.onIdlePressure&&(this.onIdlePressure=options.onIdlePressure),this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readFootprint=options.readFootprint??readOwnFootprint,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??DEFAULT_HOST_RSS_WARN_MB}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),HOST_MEMORY_SAMPLE_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let footprint=this.readFootprint(),reading={footprintMb:Math.round(footprint.bytes/BYTES_PER_MEGABYTE),measure:footprint.measure,rssMb:Math.round(this.readRssBytes()/BYTES_PER_MEGABYTE)};if(reading.footprintMb<=this.warnMb){if(this.idleReported=!1,!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();sessions>0?this.idleReported=!1:this.idleReported||(this.idleReported=!0,this.onIdlePressure?.(reading));let{footprintMb,measure,rssMb}=reading;this.emit({type:"host_memory_pressure",rssMb,footprintMb,measure,sessions});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<HOST_MEMORY_STDERR_INTERVAL_MS||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: footprintMb=${footprintMb} (${measure}) rssMb=${rssMb} sessions=${sessions} (idle parking halved)
|
|
3
3
|
`))}};import{AsyncLocalStorage}from"node:async_hooks";var attributionStore=new AsyncLocalStorage,sequence=0,openActivities=new Map,lastFinished;function runWithSessionAttribution(attribution,task){let mark=++sequence;openActivities.set(mark,attribution);let finish=()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution})},awaited=!1;try{let result=attributionStore.run(attribution,task);return isPromiseLike(result)&&(awaited=!0,Promise.resolve(result).then(finish,finish)),result}finally{awaited||finish()}}function isPromiseLike(value){return typeof value=="object"&&value!==null&&"then"in value&&typeof value.then=="function"}function openSessionAttributionSpan(attribution){let ambient=attributionStore.getStore(),merged={sessionId:attribution.sessionId??ambient?.sessionId,tool:attribution.tool},mark=++sequence;return openActivities.set(mark,merged),()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution:merged})}}function sessionActivityMark(){return sequence}function sessionActivitySince(mark){if(lastFinished!==void 0&&lastFinished.sequence>mark)return lastFinished.attribution;let newest;for(let attribution of openActivities.values())newest=attribution;return newest}function toolRecord(record){if(!(!("type"in record)||typeof record.type!="string"))return{type:record.type,toolCallId:"toolCallId"in record&&typeof record.toolCallId=="string"?record.toolCallId:void 0,toolName:"toolName"in record&&typeof record.toolName=="string"?record.toolName:void 0}}function createToolAttributionSpans(sessionId){let spans=new Map,closeAll=()=>{for(let close of spans.values())close();spans.clear()};return{closeAll,observe:record=>{let parsed=toolRecord(record);if(parsed!==void 0){if(parsed.type==="tool_execution_start"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.set(parsed.toolCallId,openSessionAttributionSpan({sessionId,tool:parsed.toolName}));return}if(parsed.type==="tool_execution_end"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.delete(parsed.toolCallId);return}(parsed.type==="agent_settled"||parsed.type==="agent_idle")&&closeAll()}}}}var LOOP_LAG_WARN_MS_ENV="SENPI_RPC_LOOP_LAG_WARN_MS",LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_WARN_MS=500,DEFAULT_LOOP_LAG_ERROR_MS=5e3,LOOP_LAG_TICK_MS=200,LOOP_LAG_WARN_INTERVAL_MS=1e4,BYTES_PER_MB=1024*1024;function describeWindow(processCpuMs,heapDeltaMb){return`cpu=${processCpuMs}ms heap=${heapDeltaMb>=0?"+":""}${heapDeltaMb}MB`}function describeAttribution(attribution){return attribution?.sessionId===void 0&&attribution?.tool===void 0?"no attributed session":`sessionId=${attribution.sessionId??"unknown"}${attribution.tool?` tool=${attribution.tool}`:""}`}var LoopLagWatchdog=class{constructor(options){this.activityMark=0,this.cpuMicrosAtTick=0,this.heapBytesAtTick=0;let env=options.env??process.env;this.emit=options.emit,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.cpuUsage=options.cpuUsage??(()=>process.cpuUsage()),this.heapUsed=options.heapUsed??(()=>process.memoryUsage().heapUsed),this.warnMs=parseIdleExitMs(env[LOOP_LAG_WARN_MS_ENV])??DEFAULT_LOOP_LAG_WARN_MS,this.errorMs=parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}start(){if(this.timer!==void 0)return;this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage();this.cpuMicrosAtTick=cpu.user+cpu.system,this.heapBytesAtTick=this.heapUsed(),this.timer=setInterval(()=>this.tick(),LOOP_LAG_TICK_MS),this.timer.unref?.()}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0,this.expectedTickAt=void 0)}tick(){let now=this.now(),expectedAt=this.expectedTickAt??now,previousMark=this.activityMark;this.expectedTickAt=now+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage(),cpuMicros=cpu.user+cpu.system,heapBytes=this.heapUsed(),previousCpuMicros=this.cpuMicrosAtTick,previousHeapBytes=this.heapBytesAtTick;this.cpuMicrosAtTick=cpuMicros,this.heapBytesAtTick=heapBytes;let driftMs=Math.round(now-expectedAt);if(recordLoopBlockedMs(driftMs),driftMs<=this.warnMs)return;let attribution=sessionActivitySince(previousMark),processCpuMs=Math.round((cpuMicros-previousCpuMicros)/1e3),heapDeltaMb=Math.round((heapBytes-previousHeapBytes)/BYTES_PER_MB);driftMs>this.errorMs&&this.emit({type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool,processCpuMs,heapDeltaMb}),!(this.lastWarnAt!==void 0&&now-this.lastWarnAt<LOOP_LAG_WARN_INTERVAL_MS)&&(this.lastWarnAt=now,this.log(`senpi rpc host stall: event loop blocked ${driftMs}ms (${describeAttribution(attribution)}; ${describeWindow(processCpuMs,heapDeltaMb)})
|
|
4
|
-
`))}};async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecords=chunk=>{for(let line of chunk.split(`
|
|
4
|
+
`))}};import{access}from"node:fs/promises";import{isAbsolute}from"node:path";var MAX_WARM_PROFILES=64;function profileKey(profile){let context=Object.entries(profile.sessionContext??{}).sort(([a],[b])=>a<b?-1:a>b?1:0);return JSON.stringify([profile.cwd,profile.sessionKind??"interactive",context])}var HostWarmer=class{constructor(load){this.warm=new Set,this.loading=new Map,this.load=load}async run(profile){let key=profileKey(profile);if(this.warm.has(key))return"already_warm";let pending=this.loading.get(key);return pending===void 0&&(pending=this.loadOnce(key,profile),this.loading.set(key,pending)),await pending,"warmed"}async loadOnce(key,profile){try{if(await this.load(profile),this.warm.add(key),this.warm.size>MAX_WARM_PROFILES){let oldest=this.warm.values().next().value;oldest!==void 0&&this.warm.delete(oldest)}}finally{this.loading.delete(key)}}};function createRegistryWarm(prepare,host){let warmer=new HostWarmer(async profile=>{await access(profile.cwd);let launchProfile={cwd:profile.cwd,...profile.sessionKind!==void 0?{sessionKind:profile.sessionKind}:{},...profile.sessionContext!==void 0?{sessionContext:Object.freeze({...profile.sessionContext})}:{}},scope=new ProviderScope;try{await runWithProviderScope(scope,()=>prepare({cwd:profile.cwd,agentDir:host.agentDir,launchProfile:Object.freeze(launchProfile),...host.mcpRegistry!==void 0?{mcpRegistry:host.mcpRegistry}:{}}))}finally{scope.close()}});return profile=>warmer.run(profile)}function refusal(command,code){return{id:command.id,type:"response",command:"warm",success:!1,error:code}}async function answerWarm(command,host){if(host.draining)return refusal(command,"host_draining");let kindError=sessionKindError(command.kind);if(kindError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);if(host.warm===void 0)return{id:command.id,type:"response",command:"warm",success:!0,data:{state:"unsupported"}};let sessionContext=host.hostContext?{...command.context,...host.hostContext}:command.context,cwd=command.cwd??host.cwd;if(!isAbsolute(cwd))return refusal(command,RPC_ERROR_INVALID_PATH);try{let state=await host.warm({cwd,...command.kind!==void 0?{sessionKind:command.kind}:{},...sessionContext!==void 0?{sessionContext}:{}});return{id:command.id,type:"response",command:"warm",success:!0,data:{state}}}catch(cause){return refusal(command,`${RPC_ERROR_WARM_FAILED}: ${cause instanceof Error?cause.message:String(cause)}`)}}async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecords=chunk=>{for(let line of chunk.split(`
|
|
5
5
|
`)){if(!line)continue;let record=JSON.parse(line);toolSpans.observe(record),writer.enqueue(sessionId,record)}},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry.switchSession)return entry.switchSession;if(property==="setRebindSession")return callback=>{entry.rebindSession=callback,entry.runtime?.setRebindSession(callback)};let runtime=entry.runtime;if(!runtime)throw new Error("Session runtime was not created");let value=Reflect.get(runtime,property,runtime);return typeof value=="function"?value.bind(runtime):value}}),handler=await runWithProviderScope(entry.scope,async()=>{let taggedSink={writeRaw:bindToProviderScope(enqueueRecords),waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,eventFlushScheduler:flush=>flush(),...options})});return await handler.ready,{handle:command=>runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),rerenderComponents:()=>runWithProviderScope(entry.scope,()=>handler.rerenderComponents()),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}function isHandoffBusy(snapshot){return isSessionBusySnapshot({...snapshot,hasActiveWakeSource:!1})}function selectDrainVerdicts(registry,inFlight,unreadable){let park=[],gone=[];for(let{sessionId,status,sessionPath}of registry.list()){if(status!=="open"||inFlight(sessionId))continue;let entry=registry.peek(sessionId);!entry||handoffBusy(entry,sessionId,unreadable)||(sessionPath!==void 0&&sessionDirectoryRemoved(sessionPath)?gone.push(sessionId):park.push(sessionId))}return{park,gone}}function handoffBusy(entry,sessionId,unreadable){try{let snapshot=entry.runtime?.session.activitySnapshot;return entry.worker?.handoffBusy===!0||snapshot!==void 0&&isHandoffBusy(snapshot)}catch(cause){return unreadable(sessionId,cause),!1}}function readDrainVerdicts(registry,inFlight){try{return selectDrainVerdicts(registry,inFlight,(sessionId,cause)=>{process.stderr.write(`senpi rpc handoff activity of ${sessionId} unreadable, parking: ${String(cause)}
|
|
6
6
|
`)})}catch(cause){process.stderr.write(`senpi rpc handoff drain pass failed, retrying: ${String(cause)}
|
|
7
|
-
`);return}}import{existsSync}from"node:fs";import{isAbsolute}from"node:path";function sessionIsWriting(entry){return entry.worker?.busy===!0||entry.runtime?.session.isSessionBusy===!0}function reportDetachedFailure(handle,cause){process.stderr.write(`senpi rpc session ${handle} teardown failed: ${String(cause)}
|
|
8
|
-
`)}function beginSessionClose(host,handle,onRole,options){let entry=host.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing")return onRole?.(!1),entry;if(entry.state!=="open")throw new RpcSessionRegistryError("unknown_session");return entry.attachments-=1,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry.reservationKey&&!sessionIsWriting(entry)&&host.markDetached(entry.reservationKey),entry):(entry.state="closing",onRole?.(!0),entry.closeCompletion=new Promise(resolve=>{entry.closeResolve=resolve}),entry)}function closeSession(host,handle){return beginSessionClose(host,handle).state!=="closing"?Promise.resolve():closeMarkedSession(host,handle)}function closeMarkedSession(host,handle){host.sync();let entry=host.get(handle);if(entry?.state!=="closing")throw new RpcSessionRegistryError("unknown_session");let completion=entry.closeCompletion;if(!completion)return Promise.resolve();if(entry.closeStarted)return completion;entry.closeStarted=!0;let previousLifecycle=entry.lifecycleMutex,releaseTimer,released=!1,disposePromise,scopeClosed=!1,disposeOnce=()=>disposePromise||(disposePromise=Promise.resolve(entry.runtime?.dispose()),disposePromise),closeScopeOnce=async()=>{scopeClosed||(scopeClosed=!0,await disposeOnce().catch(()=>{}),await entry.scope.close?.())},release=()=>{released||(released=!0,releaseTimer&&clearTimeout(releaseTimer),entry.state="closed",host.delete(handle),entry.reservationKey&&host.releaseReservation(entry.reservationKey))},graceful=(async()=>{await previousLifecycle;try{await entry.runtime?.session.abort()}catch(cause){reportDetachedFailure(handle,cause)}try{await entry.runtime?.session.waitForIdle()}catch(cause){reportDetachedFailure(handle,cause)}try{await disposeOnce()}catch(cause){reportDetachedFailure(handle,cause)}try{await closeScopeOnce()}catch(cause){reportDetachedFailure(handle,cause)}})(),settled=!1,finish=()=>{settled||(settled=!0,release(),entry.closeResolve?.())};return releaseTimer=setTimeout(()=>{disposeOnce().catch(cause=>reportDetachedFailure(handle,cause)),closeScopeOnce().catch(cause=>reportDetachedFailure(handle,cause)),graceful.catch(cause=>reportDetachedFailure(handle,cause)),finish()},host.closeGraceMs),graceful.then(finish,cause=>{reportDetachedFailure(handle,cause),finish()}),completion}var RpcSessionRegistryError=class extends Error{constructor(code,reason,detail){super(code==="open_failed"&&reason?`${code}: ${reason}`:code),this.code=code,this.name="RpcSessionRegistryError",detail&&(this.detail=detail)}};function frozenProfile(profile){return Object.freeze({...profile,...profile.creationModel?{creationModel:Object.freeze({...profile.creationModel})}:{},...profile.sessionContext?{sessionContext:Object.freeze({...profile.sessionContext})}:{}})}function sessionIdentity(profile){return{kind:profile.sessionKind??"interactive",context:profile.sessionContext??EMPTY_SESSION_CONTEXT}}var RpcSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new Set,this.nextHandle=0,this.options=options.mcpRegistry===void 0?options:{...options,createRuntime:runtimeOptions=>options.createRuntime({...runtimeOptions,mcpRegistry:options.mcpRegistry})},this.now=options.now??Date.now,this.closeGraceMs=options.closeGraceMs??1e4,this.teardownHost={closeGraceMs:this.closeGraceMs,get:handle=>this.entries.get(handle),delete:handle=>this.entries.delete(handle),releaseReservation:key=>{this.reservations.delete(key),this.options.pathReservations?.release(key)},markDetached:key=>this.options.pathReservations?.setAttached(key,!1),sync:()=>this.syncRuntimeMetadata()}}get size(){return this.entries.size}async openSession(profile,options){this.validateProfile(profile),this.syncRuntimeMetadata();let sessionPath=profile.sessionPath?canonicalSessionPath(profile.sessionPath):void 0,requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){for(let entry2 of this.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(sessionPath!==void 0&&entry2.reservationKey===sessionPath))throw new RpcSessionRegistryError("session_id_in_use")}if(sessionPath&&await this.settleClosingReservation(sessionPath),sessionPath&&this.reservations.has(sessionPath)){let existing=[...this.entries].find(([,entry3])=>entry3.reservationKey===sessionPath&&entry3.state==="open");if(!existing)throw new RpcSessionRegistryError("session_path_in_use");let[handle2,entry2]=existing,wasParked=entry2.retainOnDisconnect===!0&&entry2.attachments===0;if(entry2.attachments+=1,this.options.pathReservations?.setAttached(sessionPath,!0),options?.retainOnDisconnect&&(entry2.retainOnDisconnect=!0),!entry2.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return entry2.lastCommandAt=this.now(),wasParked&&(entry2.lifecycleMutex=entry2.lifecycleMutex.then(()=>entry2.runtime?.emitAttachmentEvent("session_resumed")),await entry2.lifecycleMutex),{sessionId:handle2,durableSessionId:entry2.durableSessionId,sessionPath:entry2.sessionPath,attached:!0}}if(sessionPath){this.reservations.add(sessionPath);let holder=this.options.pathReservations?await this.options.pathReservations.claim(sessionPath):void 0;if(holder)throw this.reservations.delete(sessionPath),new RpcSessionRegistryError("session_path_in_use",void 0,{owner:holder,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}let isResume=sessionPath!==void 0&&existsSync(sessionPath),sessionStartEvent=isResume?{type:"session_start",reason:"resume"}:void 0,storedProfile=frozenProfile({...profile,...sessionPath?{sessionPath}:{}}),runtimeProfile=isResume?frozenProfile({...storedProfile,creationModel:void 0,initialThinkingLevel:void 0}):storedProfile,handle=`rpc-${++this.nextHandle}`,entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),sessionPath,reservationKey:sessionPath,cwd:storedProfile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve()};entry.switchSession=(sessionPath2,options2)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options2?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath2,options2);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,this.options.createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),runtime.releaseSessionHold(),entry.runtime=replacement,this.syncRuntimeMetadata(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation},requestedDurableId!==void 0&&(entry.durableSessionId=requestedDurableId),this.entries.set(handle,entry);try{let newSessionOptions=requestedDurableId!==void 0?{id:requestedDurableId}:void 0,manager=sessionPath?SessionManager.open(sessionPath,void 0,storedProfile.cwd,newSessionOptions):SessionManager.create(storedProfile.cwd,void 0,newSessionOptions);return entry.runtime=await runWithProviderScope(entry.scope,()=>createAgentSessionRuntime(this.options.createRuntime,{cwd:manager.getCwd(),agentDir:this.options.agentDir,sessionManager:manager,sessionStartEvent,launchProfile:runtimeProfile})),entry.durableSessionId=manager.getSessionId(),entry.sessionPath??=manager.getSessionFile(),entry.state="open",{sessionId:handle,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath}}catch(error2){try{await entry.runtime?.dispose()}catch{}finally{try{await entry.scope.close?.()}finally{this.entries.delete(handle),sessionPath&&(this.reservations.delete(sessionPath),this.options.pathReservations?.release(sessionPath))}}throw error2 instanceof RpcSessionRegistryError?error2:new RpcSessionRegistryError("open_failed",error2 instanceof Error?error2.message:void 0)}}async settleClosingReservation(sessionPath){let closing=[...this.entries.values()].find(entry=>entry.reservationKey===sessionPath&&entry.state==="closing");if(!closing?.closeCompletion)return;let deadline;try{await Promise.race([closing.closeCompletion,new Promise(resolve=>{deadline=setTimeout(resolve,this.closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}peek(handle){return this.entries.get(handle)}getForCommand(handle,command){let entry=this.entries.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(command))throw new RpcSessionRegistryError("session_closing");if(entry.state!=="open"&&entry.state!=="closing")throw new RpcSessionRegistryError("unknown_session");return entry.lastCommandAt=this.now(),entry}beginClose(handle,onRole,options){return beginSessionClose(this.teardownHost,handle,onRole,options)}async close(handle){return closeSession(this.teardownHost,handle)}async closeMarked(handle){return closeMarkedSession(this.teardownHost,handle)}list(){return this.syncRuntimeMetadata(),[...this.entries].map(([sessionId,entry])=>({sessionId,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,cwd:entry.cwd,name:entry.runtime?.session.sessionManager.getSessionName(),kind:entry.kind,context:entry.context,attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state}))}syncRuntimeMetadata(){for(let entry of this.entries.values()){let manager=entry.runtime?.session.sessionManager;if(!manager)continue;let currentPath=manager.getSessionFile(),currentKey=currentPath?canonicalSessionPath(currentPath):void 0;(currentPath!==entry.sessionPath||currentKey!==entry.reservationKey)&&(entry.reservationKey&&(this.reservations.delete(entry.reservationKey),this.options.pathReservations?.release(entry.reservationKey)),currentKey&&(this.reservations.add(currentKey),this.options.pathReservations?.claim(currentKey,entry.attachments>0)),entry.reservationKey=currentKey,entry.sessionPath=currentPath),entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}validateProfile(profile){if(!isAbsolute(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");if(profile.durableSessionId!==void 0)try{assertValidSessionId(profile.durableSessionId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}}};function selectSweepEvictions(registry,now,idleEvictionMs){let idle=[],orphaned=[];for(let{sessionId,status,sessionPath}of registry.list()){if(status!=="open")continue;let entry=registry.peek(sessionId);if(entry){if(entry.attachments===0&&sessionPath!==void 0&&sessionDirectoryRemoved(sessionPath)){orphaned.push(sessionId);continue}if(Number.isFinite(idleEvictionMs)){if(entry.worker?.busy||entry.runtime?.session.isSessionBusy){entry.lastCommandAt=now;continue}now-entry.lastCommandAt>=idleEvictionMs&&idle.push(sessionId)}}}return{idle,orphaned}}var DRAIN_SWEEP_MS=50;function error(id,command,code,data){return{id,type:"response",command,success:!1,error:code,...data&&{errorCode:code,errorData:data}}}var SessionCommandRouter=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.opensByConnection=new Map,this.releasedConnections=new Set,this.widths=new Map,this.pendingCapabilities=new Map,this.finalizations=new Map,this.draining=!1,this.handoffParks=0,this.drainExitRequested=!1,this.handoffClosed=new Set,this.activeRequests=new Map,this.memoryPressure=!1,this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.onHandoffParked=idle?.onHandoffParked,this.canExitWhenEmpty=idle?.canExitWhenEmpty,Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>this.sweepIdleSessions(),tickMs),this.sweepTimer.unref?.()}}get sessionCount(){return this.registry.size}beginDrain(){this.draining=!0,this.stopSweep(),this.drainTimer===void 0&&!this.drainExitRequested&&(this.drainTimer=setInterval(()=>this.sweepDrain(),DRAIN_SWEEP_MS),this.drainTimer.unref?.()),this.sweepDrain()}sweepDrain(){if(this.activeRequests.has(void 0))return;let verdicts=readDrainVerdicts(this.registry,sessionId=>this.activeRequests.has(sessionId));if(verdicts){for(let sessionId of verdicts.gone)this.parkForHandoff(sessionId,"session_dir_removed");for(let sessionId of verdicts.park)this.parkForHandoff(sessionId,"handoff_parked");this.registry.size>0||this.handoffParks>0||this.finalizations.size>0||(this.drainTimer!==void 0&&(clearInterval(this.drainTimer),this.drainTimer=void 0),this.stopSweep(),!this.drainExitRequested&&(this.drainExitRequested=!0,this.onEmptyExit?.()))}}parkForHandoff(sessionId,reason){this.handoffClosed.add(sessionId),this.handoffParks++,this.evictIdleSession(sessionId,reason).catch(cause=>{process.stderr.write(`senpi rpc handoff park ${sessionId} failed: ${String(cause)}
|
|
9
|
-
`)}).finally(()=>{this.handoffParks--,this.sweepDrain()})}setMemoryPressure(pressure){this.memoryPressure=pressure}handle(command){let sessionId="sessionId"in command?command.sessionId:void 0;return this.draining&&sessionId!==void 0&&this.handoffClosed.has(sessionId)?Promise.resolve(void 0):this.draining&&command.type==="open_session"?Promise.resolve(error(command.id,command.type,"host_draining")):(this.activeRequests.set(sessionId,(this.activeRequests.get(sessionId)??0)+1),runWithSessionAttribution({sessionId},()=>this.dispatch(command)).finally(()=>{let remaining=(this.activeRequests.get(sessionId)??1)-1;remaining>0?this.activeRequests.set(sessionId,remaining):this.activeRequests.delete(sessionId),this.draining&&this.sweepDrain()}))}async dispatch(command){if(command.type==="get_protocol_info"){let capabilities=new Set(["multi_session",AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,...this.connectionOptions?.capabilities??[]]);return{id:command.id,type:"response",command:"get_protocol_info",success:!0,data:{protocolVersion:1,serverVersion:VERSION,capabilities:[...capabilities],mode:"multi",...protocolIdentity(),memory_pressure:this.memoryPressure}}}if(command.type==="list_sessions"){let rows=this.registry.list(),sessions=command.include_workers===!0?rows:rows.filter(row=>row.kind!=="worker").map(({context:_context,...row})=>row);return{id:command.id,type:"response",command:"list_sessions",success:!0,data:{sessions}}}if(command.type==="open_session")return this.openWithBarrier(command);if(command.type==="close_session")return this.close(command);if(command.type==="set_client_info"&&!command.sessionId){let connection=this.writer.currentConnection();return connection!==void 0&&(this.pendingCapabilities.set(connection,command.capabilities??[]),this.writer.setConnectionCapabilities(connection,command.capabilities??[])),{id:command.id,type:"response",command:"set_client_info",success:!0}}if(!command.sessionId)return error(command.id,command.type,RPC_ERROR_MISSING_SESSION_ID);try{this.registry.getForCommand(command.sessionId,command.type);let binding=this.bindings.get(command.sessionId);if(!binding)return error(command.id,command.type,RPC_ERROR_UNKNOWN_SESSION);await binding.handle(command);return}catch(cause){return error(command.id,command.type,this.code(cause))}}async dispose(){this.drainExitRequested=!0,this.stopSweep(),this.drainTimer!==void 0&&clearInterval(this.drainTimer),await Promise.all([...this.bindings.entries()].map(async([sessionId,binding])=>{let claim=this.tryClaimClose(sessionId,{drainAttachments:!0});claim&&(claim.finalizer?await this.finalizeClose(sessionId,binding,()=>this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},"host_shutdown")):await this.finalizations.get(sessionId)?.promise,this.writer.forgetSession(sessionId))})),this.bindings.clear()}sweepIdleSessions(){let now=this.idleNow(),idleEvictionMs=this.memoryPressure?this.idleEvictionMs/2:this.idleEvictionMs,verdicts=selectSweepEvictions(this.registry,now,idleEvictionMs);for(let sessionId of verdicts.orphaned)this.evictIdleSession(sessionId,"session_dir_removed");for(let sessionId of verdicts.idle)this.evictIdleSession(sessionId);Number.isFinite(this.emptyExitMs)&&(this.registry.size===0&&(this.canExitWhenEmpty?.()??!0)?this.emptySince===void 0?this.emptySince=now:now-this.emptySince>=this.emptyExitMs&&(this.stopSweep(),this.onEmptyExit?.()):this.emptySince=void 0)}async evictIdleSession(sessionId,reason){let retained=this.registry.peek(sessionId),parkedPath=retained?.retainOnDisconnect===!0||reason==="handoff_parked"?retained?.sessionPath:void 0,handoff=reason==="handoff_parked"||reason==="session_dir_removed"&&this.draining,owners=handoff?[...this.sessionsByConnection].filter(([,owned])=>owned.has(sessionId)).map(([connection])=>connection):[],claim=this.tryClaimClose(sessionId,{drainAttachments:!0});if(!claim)return;let binding=this.bindings.get(sessionId);binding?.cancelPendingExtensionUiRequests?.(),handoff||this.forgetSessionOwnership(sessionId),claim.finalizer?await this.finalizeClose(sessionId,binding,()=>parkedPath!==void 0&&reason===void 0?this.writer.parkSession(sessionId,parkedPath):this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},reason??"idle_evicted",reason==="handoff_parked"?parkedPath:void 0)):await this.finalizations.get(sessionId)?.promise,handoff&&(this.forgetSessionOwnership(sessionId),await this.onHandoffParked?.(owners.filter(connection=>!this.sessionsByConnection.has(connection)))),this.writer.forgetSession(sessionId)}forgetSessionOwnership(sessionId){for(let[connection,owned]of this.sessionsByConnection)owned.delete(sessionId),owned.size===0&&this.sessionsByConnection.delete(connection);this.widths.delete(sessionId)}stopSweep(){this.sweepTimer!==void 0&&(clearInterval(this.sweepTimer),this.sweepTimer=void 0)}openWithBarrier(command){let owner=this.writer.currentConnection();if(owner===void 0)return this.open(command);let resolveBarrier,barrier=new Promise(resolve=>{resolveBarrier=resolve}),opens=this.opensByConnection.get(owner)??new Set,inFlight=0;for(let pending of this.opensByConnection.values())inFlight+=pending.size;return opens.add(barrier),this.opensByConnection.set(owner,opens),command.id!==void 0&&this.writer.sendOpenQueued(owner,{type:"queued",for_request:command.id,position:inFlight+1,in_flight:inFlight}),this.open(command,owner).finally(()=>{resolveBarrier(),opens.delete(barrier),opens.size===0&&this.opensByConnection.delete(owner)})}async open(command,owner){let kindError=sessionKindError(command.kind);if(kindError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);let autoTitleError=sessionAutoTitleError(command.auto_title);if(autoTitleError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${autoTitleError}`);let opened;try{opened=await this.registry.openSession({cwd:command.cwd??this.defaults.cwd,sessionPath:command.sessionPath,permissionPreset:command.permissionPreset??this.defaults.permissionPreset,creationModel:command.provider&&command.modelId?{provider:command.provider,modelId:command.modelId}:this.defaults.creationModel,initialThinkingLevel:command.thinkingLevel??this.defaults.initialThinkingLevel,sessionKind:command.kind,sessionContext:this.defaults.hostContext?{...command.context,...this.defaults.hostContext}:command.context,...command.durableSessionId!==void 0?{durableSessionId:command.durableSessionId}:{},...typeof command.auto_title=="boolean"?{autoTitle:command.auto_title}:{}},{retainOnDisconnect:command.retain_on_disconnect===!0});let openedSession=opened,entry=this.registry.getForCommand(openedSession.sessionId,"open_session");if(this.writer.setSessionKind(openedSession.sessionId,entry.kind),owner!==void 0&&(this.writer.hasRegisteredConnectionCapabilities(owner)||this.writer.setConnectionCapabilities(owner,this.pendingCapabilities.get(owner)??this.connectionOptions?.capabilities??[]),this.writer.attachConnectionToSession(owner,openedSession.sessionId)),owner!==void 0){let owned=this.sessionsByConnection.get(owner)??new Map;owned.set(openedSession.sessionId,(owned.get(openedSession.sessionId)??0)+1),this.sessionsByConnection.set(owner,owned)}if(!this.bindings.has(openedSession.sessionId)){this.bindings.set(openedSession.sessionId,await this.createBinding(openedSession.sessionId,entry,this.writer,()=>{this.close({type:"close_session",sessionId:openedSession.sessionId})},{...this.connectionOptions,capabilities:owner!==void 0?this.pendingCapabilities.get(owner)??this.connectionOptions?.capabilities??[]:this.connectionOptions?.capabilities,sharedWidth:{getWidth:()=>{let widths=this.widths.get(openedSession.sessionId);return widths?.size?Math.min(...widths.values()):80},setWidth:(connectionId,width)=>{if(connectionId!==void 0){let widths=this.widths.get(openedSession.sessionId)??new Map;widths.set(connectionId,width),this.widths.set(openedSession.sessionId,widths)}},clearWidth:connectionId=>{let widths=this.widths.get(openedSession.sessionId);connectionId!==void 0&&widths?.delete(connectionId)},setCapabilities:(connectionId,capabilities)=>{if(connectionId!==void 0){this.writer.setConnectionCapabilities(connectionId,capabilities),this.pendingCapabilities.set(connectionId,[...capabilities]);for(let binding of this.bindings.values())binding.rerenderComponents?.()}},hasRenderedComponents:sessionId=>this.writer.hasCapableConnection(sessionId),connectionId:()=>this.writer.currentConnection(),onChange:()=>{for(let binding of this.bindings.values())binding.rerenderComponents?.()}}})),entry.worker&&(entry.worker.bindingReady=!0);let settled=()=>{this.draining&&queueMicrotask(()=>this.sweepDrain())};typeof entry.worker?.subscribeSettled=="function"?entry.worker.subscribeSettled(settled):typeof entry.runtime?.session.subscribe=="function"&&entry.runtime.session.subscribe(event=>{(event.type==="agent_settled"||event.type==="agent_idle")&&settled()}),entry.worker&&entry.worker.exited.then(async()=>{await this.finalizations.get(openedSession.sessionId)?.promise,this.bindings.delete(openedSession.sessionId),this.forgetSessionOwnership(openedSession.sessionId),this.writer.forgetSession(openedSession.sessionId)})}!this.draining&&owner!==void 0&&this.releasedConnections.has(owner)&&(this.releaseOwnerAttachment(owner,openedSession.sessionId),await this.releaseOwnedSession(openedSession.sessionId));let state=entry.worker?.snapshot?.state??(entry.runtime?buildRpcSessionState(entry.runtime.session):void 0);if(!state)throw new Error("Session state was not created");this.writer.enqueue(opened.sessionId,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:opened.sessionId,state,...opened.attached?{attached:!0}:{}}});return}catch(cause){if(opened)try{await this.registry.close(opened.sessionId)}catch{}return error(command.id,"open_session",this.code(cause),this.detail(cause))}}async releaseConnection(connectionId){this.releasedConnections.add(connectionId),this.writer.clearConnectionCapabilities(connectionId);for(let sessionId of this.sessionsByConnection.get(connectionId)?.keys()??[])this.writer.detachConnectionFromSession(connectionId,sessionId);for(let widths of this.widths.values())widths.delete(connectionId);for(let binding of this.bindings.values())binding.rerenderComponents?.();let opens=this.opensByConnection.get(connectionId),owned=this.sessionsByConnection.get(connectionId);if(this.sessionsByConnection.delete(connectionId),this.draining){opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId);return}if(owned===void 0){opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId);return}await Promise.all([...owned].map(async([sessionId,count])=>{for(let attachment=0;attachment<count;attachment++){let live=this.registry.peek(sessionId),retained=live?.retainOnDisconnect===!0,session=live?.state==="open"?live.runtime?.session:void 0;if(!retained&&live?.state==="open"&&live.worker?.snapshot?.streaming){let unsubscribe=live.worker.subscribeSettled(()=>{unsubscribe(),this.releaseOwnedSession(sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred worker release ${sessionId} failed: ${String(cause)}
|
|
7
|
+
`);return}}import{existsSync}from"node:fs";import{isAbsolute as isAbsolute2}from"node:path";function sessionIsWriting(entry){return entry.worker?.busy===!0||entry.runtime?.session.isSessionBusy===!0}function reportDetachedFailure(handle,cause){process.stderr.write(`senpi rpc session ${handle} teardown failed: ${String(cause)}
|
|
8
|
+
`)}function beginSessionClose(host,handle,onRole,options){let entry=host.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing")return onRole?.(!1),entry;if(entry.state!=="open")throw new RpcSessionRegistryError("unknown_session");return entry.attachments-=1,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry.reservationKey&&!sessionIsWriting(entry)&&host.markDetached(entry.reservationKey),entry):(entry.state="closing",onRole?.(!0),entry.closeCompletion=new Promise(resolve=>{entry.closeResolve=resolve}),entry)}function closeSession(host,handle){return beginSessionClose(host,handle).state!=="closing"?Promise.resolve():closeMarkedSession(host,handle)}function closeMarkedSession(host,handle){host.sync();let entry=host.get(handle);if(entry?.state!=="closing")throw new RpcSessionRegistryError("unknown_session");let completion=entry.closeCompletion;if(!completion)return Promise.resolve();if(entry.closeStarted)return completion;entry.closeStarted=!0;let previousLifecycle=entry.lifecycleMutex,releaseTimer,released=!1,disposePromise,scopeClosed=!1,disposeOnce=()=>disposePromise||(disposePromise=Promise.resolve(entry.runtime?.dispose()),disposePromise),closeScopeOnce=async()=>{scopeClosed||(scopeClosed=!0,await disposeOnce().catch(()=>{}),await entry.scope.close?.())},release=()=>{released||(released=!0,releaseTimer&&clearTimeout(releaseTimer),entry.state="closed",host.delete(handle),entry.reservationKey&&host.releaseReservation(entry.reservationKey))},graceful=(async()=>{await previousLifecycle;try{await entry.runtime?.session.abort()}catch(cause){reportDetachedFailure(handle,cause)}try{await entry.runtime?.session.waitForIdle()}catch(cause){reportDetachedFailure(handle,cause)}try{await disposeOnce()}catch(cause){reportDetachedFailure(handle,cause)}try{await closeScopeOnce()}catch(cause){reportDetachedFailure(handle,cause)}})(),settled=!1,finish=()=>{settled||(settled=!0,release(),entry.closeResolve?.())};return releaseTimer=setTimeout(()=>{disposeOnce().catch(cause=>reportDetachedFailure(handle,cause)),closeScopeOnce().catch(cause=>reportDetachedFailure(handle,cause)),graceful.catch(cause=>reportDetachedFailure(handle,cause)),finish()},host.closeGraceMs),graceful.then(finish,cause=>{reportDetachedFailure(handle,cause),finish()}),completion}var RpcSessionRegistryError=class extends Error{constructor(code,reason,detail){super(code==="open_failed"&&reason?`${code}: ${reason}`:code),this.code=code,this.name="RpcSessionRegistryError",detail&&(this.detail=detail)}};function frozenProfile(profile){return Object.freeze({...profile,...profile.creationModel?{creationModel:Object.freeze({...profile.creationModel})}:{},...profile.sessionContext?{sessionContext:Object.freeze({...profile.sessionContext})}:{}})}function sessionIdentity(profile){return{kind:profile.sessionKind??"interactive",context:profile.sessionContext??EMPTY_SESSION_CONTEXT}}var RpcSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new Set,this.nextHandle=0,options.createRuntime.prepare&&(this.warm=createRegistryWarm(options.createRuntime.prepare,{agentDir:options.agentDir,...options.mcpRegistry!==void 0?{mcpRegistry:options.mcpRegistry}:{}})),this.options=options.mcpRegistry===void 0?options:{...options,createRuntime:runtimeOptions=>options.createRuntime({...runtimeOptions,mcpRegistry:options.mcpRegistry})},this.now=options.now??Date.now,this.closeGraceMs=options.closeGraceMs??1e4,this.teardownHost={closeGraceMs:this.closeGraceMs,get:handle=>this.entries.get(handle),delete:handle=>this.entries.delete(handle),releaseReservation:key=>{this.reservations.delete(key),this.options.pathReservations?.release(key)},markDetached:key=>this.options.pathReservations?.setAttached(key,!1),sync:()=>this.syncRuntimeMetadata()}}get size(){return this.entries.size}async openSession(profile,options){this.validateProfile(profile),this.syncRuntimeMetadata();let sessionPath=profile.sessionPath?canonicalSessionPath(profile.sessionPath):void 0,requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){for(let entry2 of this.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(sessionPath!==void 0&&entry2.reservationKey===sessionPath))throw new RpcSessionRegistryError("session_id_in_use")}if(sessionPath&&await this.settleClosingReservation(sessionPath),sessionPath&&this.reservations.has(sessionPath)){let existing=[...this.entries].find(([,entry3])=>entry3.reservationKey===sessionPath&&entry3.state==="open");if(!existing)throw new RpcSessionRegistryError("session_path_in_use");let[handle2,entry2]=existing,wasParked=entry2.retainOnDisconnect===!0&&entry2.attachments===0;if(entry2.attachments+=1,this.options.pathReservations?.setAttached(sessionPath,!0),options?.retainOnDisconnect&&(entry2.retainOnDisconnect=!0),!entry2.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return entry2.lastCommandAt=this.now(),wasParked&&(entry2.lifecycleMutex=entry2.lifecycleMutex.then(()=>entry2.runtime?.emitAttachmentEvent("session_resumed")),await entry2.lifecycleMutex),{sessionId:handle2,durableSessionId:entry2.durableSessionId,sessionPath:entry2.sessionPath,attached:!0}}if(sessionPath){this.reservations.add(sessionPath);let holder=this.options.pathReservations?await this.options.pathReservations.claim(sessionPath):void 0;if(holder)throw this.reservations.delete(sessionPath),new RpcSessionRegistryError("session_path_in_use",void 0,{owner:holder,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}let isResume=sessionPath!==void 0&&existsSync(sessionPath),sessionStartEvent=isResume?{type:"session_start",reason:"resume"}:void 0,storedProfile=frozenProfile({...profile,...sessionPath?{sessionPath}:{}}),runtimeProfile=isResume?frozenProfile({...storedProfile,creationModel:void 0,initialThinkingLevel:void 0}):storedProfile,handle=`rpc-${++this.nextHandle}`,entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),sessionPath,reservationKey:sessionPath,cwd:storedProfile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve()};entry.switchSession=(sessionPath2,options2)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options2?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath2,options2);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,this.options.createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),runtime.releaseSessionHold(),entry.runtime=replacement,this.syncRuntimeMetadata(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation},requestedDurableId!==void 0&&(entry.durableSessionId=requestedDurableId),this.entries.set(handle,entry);try{let newSessionOptions=requestedDurableId!==void 0?{id:requestedDurableId}:void 0,manager=sessionPath?SessionManager.open(sessionPath,void 0,storedProfile.cwd,newSessionOptions):SessionManager.create(storedProfile.cwd,void 0,newSessionOptions);return entry.runtime=await runWithProviderScope(entry.scope,()=>createAgentSessionRuntime(this.options.createRuntime,{cwd:manager.getCwd(),agentDir:this.options.agentDir,sessionManager:manager,sessionStartEvent,launchProfile:runtimeProfile})),entry.durableSessionId=manager.getSessionId(),entry.sessionPath??=manager.getSessionFile(),entry.state="open",{sessionId:handle,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath}}catch(error2){try{await entry.runtime?.dispose()}catch{}finally{try{await entry.scope.close?.()}finally{this.entries.delete(handle),sessionPath&&(this.reservations.delete(sessionPath),this.options.pathReservations?.release(sessionPath))}}throw error2 instanceof RpcSessionRegistryError?error2:new RpcSessionRegistryError("open_failed",error2 instanceof Error?error2.message:void 0)}}async settleClosingReservation(sessionPath){let closing=[...this.entries.values()].find(entry=>entry.reservationKey===sessionPath&&entry.state==="closing");if(!closing?.closeCompletion)return;let deadline;try{await Promise.race([closing.closeCompletion,new Promise(resolve=>{deadline=setTimeout(resolve,this.closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}peek(handle){return this.entries.get(handle)}getForCommand(handle,command){let entry=this.entries.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(command))throw new RpcSessionRegistryError("session_closing");if(entry.state!=="open"&&entry.state!=="closing")throw new RpcSessionRegistryError("unknown_session");return entry.lastCommandAt=this.now(),entry}beginClose(handle,onRole,options){return beginSessionClose(this.teardownHost,handle,onRole,options)}async close(handle){return closeSession(this.teardownHost,handle)}async closeMarked(handle){return closeMarkedSession(this.teardownHost,handle)}list(){return this.syncRuntimeMetadata(),[...this.entries].map(([sessionId,entry])=>({sessionId,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,cwd:entry.cwd,name:entry.runtime?.session.sessionManager.getSessionName(),kind:entry.kind,context:entry.context,attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state}))}syncRuntimeMetadata(){for(let entry of this.entries.values()){let manager=entry.runtime?.session.sessionManager;if(!manager)continue;let currentPath=manager.getSessionFile(),currentKey=currentPath?canonicalSessionPath(currentPath):void 0;(currentPath!==entry.sessionPath||currentKey!==entry.reservationKey)&&(entry.reservationKey&&(this.reservations.delete(entry.reservationKey),this.options.pathReservations?.release(entry.reservationKey)),currentKey&&(this.reservations.add(currentKey),this.options.pathReservations?.claim(currentKey,entry.attachments>0)),entry.reservationKey=currentKey,entry.sessionPath=currentPath),entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}validateProfile(profile){if(!isAbsolute2(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute2(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");if(profile.durableSessionId!==void 0)try{assertValidSessionId(profile.durableSessionId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}}};function selectSweepEvictions(registry,now,idleEvictionMs){let idle=[],orphaned=[];for(let{sessionId,status,sessionPath}of registry.list()){if(status!=="open")continue;let entry=registry.peek(sessionId);if(entry){if(entry.attachments===0&&sessionPath!==void 0&&sessionDirectoryRemoved(sessionPath)){orphaned.push(sessionId);continue}if(Number.isFinite(idleEvictionMs)){if(entry.worker?.busy||entry.runtime?.session.isSessionBusy){entry.lastCommandAt=now;continue}now-entry.lastCommandAt>=idleEvictionMs&&idle.push(sessionId)}}}return{idle,orphaned}}var DRAIN_SWEEP_MS=50;function error(id,command,code,data){return{id,type:"response",command,success:!1,error:code,...data&&{errorCode:code,errorData:data}}}var SessionCommandRouter=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.opensByConnection=new Map,this.releasedConnections=new Set,this.widths=new Map,this.pendingCapabilities=new Map,this.finalizations=new Map,this.draining=!1,this.handoffParks=0,this.drainExitRequested=!1,this.handoffClosed=new Set,this.activeRequests=new Map,this.memoryPressure=!1,this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.onHandoffParked=idle?.onHandoffParked,this.canExitWhenEmpty=idle?.canExitWhenEmpty,Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>this.sweepIdleSessions(),tickMs),this.sweepTimer.unref?.()}}get sessionCount(){return this.registry.size}beginDrain(){this.draining=!0,this.stopSweep(),this.drainTimer===void 0&&!this.drainExitRequested&&(this.drainTimer=setInterval(()=>this.sweepDrain(),DRAIN_SWEEP_MS),this.drainTimer.unref?.()),this.sweepDrain()}sweepDrain(){if(this.activeRequests.has(void 0))return;let verdicts=readDrainVerdicts(this.registry,sessionId=>this.activeRequests.has(sessionId));if(verdicts){for(let sessionId of verdicts.gone)this.parkForHandoff(sessionId,"session_dir_removed");for(let sessionId of verdicts.park)this.parkForHandoff(sessionId,"handoff_parked");this.registry.size>0||this.handoffParks>0||this.finalizations.size>0||(this.drainTimer!==void 0&&(clearInterval(this.drainTimer),this.drainTimer=void 0),this.stopSweep(),!this.drainExitRequested&&(this.drainExitRequested=!0,this.onEmptyExit?.()))}}parkForHandoff(sessionId,reason){this.handoffClosed.add(sessionId),this.handoffParks++,this.evictIdleSession(sessionId,reason).catch(cause=>{process.stderr.write(`senpi rpc handoff park ${sessionId} failed: ${String(cause)}
|
|
9
|
+
`)}).finally(()=>{this.handoffParks--,this.sweepDrain()})}setMemoryPressure(pressure){this.memoryPressure=pressure}handle(command){let sessionId="sessionId"in command?command.sessionId:void 0;return this.draining&&sessionId!==void 0&&this.handoffClosed.has(sessionId)?Promise.resolve(void 0):this.draining&&command.type==="open_session"?Promise.resolve(error(command.id,command.type,"host_draining")):command.type==="warm"?answerWarm(command,{draining:this.draining,warm:this.registry.warm,cwd:this.defaults.cwd,hostContext:this.defaults.hostContext}):(this.activeRequests.set(sessionId,(this.activeRequests.get(sessionId)??0)+1),runWithSessionAttribution({sessionId},()=>this.dispatch(command)).finally(()=>{let remaining=(this.activeRequests.get(sessionId)??1)-1;remaining>0?this.activeRequests.set(sessionId,remaining):this.activeRequests.delete(sessionId),this.draining&&this.sweepDrain()}))}async dispatch(command){if(command.type==="get_protocol_info"){let capabilities=new Set(["multi_session",AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,...this.registry.warm?[WARM_CAPABILITY]:[],...this.connectionOptions?.capabilities??[]]);return{id:command.id,type:"response",command:"get_protocol_info",success:!0,data:{protocolVersion:1,serverVersion:VERSION,capabilities:[...capabilities],mode:"multi",...protocolIdentity(),memory_pressure:this.memoryPressure}}}if(command.type==="list_sessions"){let rows=this.registry.list(),sessions=command.include_workers===!0?rows:rows.filter(row=>row.kind!=="worker").map(({context:_context,...row})=>row);return{id:command.id,type:"response",command:"list_sessions",success:!0,data:{sessions}}}if(command.type==="open_session")return this.openWithBarrier(command);if(command.type==="close_session")return this.close(command);if(command.type==="set_client_info"&&!command.sessionId){let connection=this.writer.currentConnection();return connection!==void 0&&(this.pendingCapabilities.set(connection,command.capabilities??[]),this.writer.setConnectionCapabilities(connection,command.capabilities??[])),{id:command.id,type:"response",command:"set_client_info",success:!0}}if(!command.sessionId)return error(command.id,command.type,RPC_ERROR_MISSING_SESSION_ID);try{this.registry.getForCommand(command.sessionId,command.type);let binding=this.bindings.get(command.sessionId);if(!binding)return error(command.id,command.type,RPC_ERROR_UNKNOWN_SESSION);await binding.handle(command);return}catch(cause){return error(command.id,command.type,this.code(cause))}}async dispose(){this.drainExitRequested=!0,this.stopSweep(),this.drainTimer!==void 0&&clearInterval(this.drainTimer),await Promise.all([...this.bindings.entries()].map(async([sessionId,binding])=>{let claim=this.tryClaimClose(sessionId,{drainAttachments:!0});claim&&(claim.finalizer?await this.finalizeClose(sessionId,binding,()=>this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},"host_shutdown")):await this.finalizations.get(sessionId)?.promise,this.writer.forgetSession(sessionId))})),this.bindings.clear()}sweepIdleSessions(){let now=this.idleNow(),idleEvictionMs=this.memoryPressure?this.idleEvictionMs/2:this.idleEvictionMs,verdicts=selectSweepEvictions(this.registry,now,idleEvictionMs);for(let sessionId of verdicts.orphaned)this.evictIdleSession(sessionId,"session_dir_removed");for(let sessionId of verdicts.idle)this.evictIdleSession(sessionId);Number.isFinite(this.emptyExitMs)&&(this.registry.size===0&&(this.canExitWhenEmpty?.()??!0)?this.emptySince===void 0?this.emptySince=now:now-this.emptySince>=this.emptyExitMs&&(this.stopSweep(),this.onEmptyExit?.()):this.emptySince=void 0)}async evictIdleSession(sessionId,reason){let retained=this.registry.peek(sessionId),parkedPath=retained?.retainOnDisconnect===!0||reason==="handoff_parked"?retained?.sessionPath:void 0,handoff=reason==="handoff_parked"||reason==="session_dir_removed"&&this.draining,owners=handoff?[...this.sessionsByConnection].filter(([,owned])=>owned.has(sessionId)).map(([connection])=>connection):[],claim=this.tryClaimClose(sessionId,{drainAttachments:!0});if(!claim)return;let binding=this.bindings.get(sessionId);binding?.cancelPendingExtensionUiRequests?.(),handoff||this.forgetSessionOwnership(sessionId),claim.finalizer?await this.finalizeClose(sessionId,binding,()=>parkedPath!==void 0&&reason===void 0?this.writer.parkSession(sessionId,parkedPath):this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},reason??"idle_evicted",reason==="handoff_parked"?parkedPath:void 0)):await this.finalizations.get(sessionId)?.promise,handoff&&(this.forgetSessionOwnership(sessionId),await this.onHandoffParked?.(owners.filter(connection=>!this.sessionsByConnection.has(connection)))),this.writer.forgetSession(sessionId)}forgetSessionOwnership(sessionId){for(let[connection,owned]of this.sessionsByConnection)owned.delete(sessionId),owned.size===0&&this.sessionsByConnection.delete(connection);this.widths.delete(sessionId)}stopSweep(){this.sweepTimer!==void 0&&(clearInterval(this.sweepTimer),this.sweepTimer=void 0)}openWithBarrier(command){let owner=this.writer.currentConnection();if(owner===void 0)return this.open(command);let resolveBarrier,barrier=new Promise(resolve=>{resolveBarrier=resolve}),opens=this.opensByConnection.get(owner)??new Set,inFlight=0;for(let pending of this.opensByConnection.values())inFlight+=pending.size;return opens.add(barrier),this.opensByConnection.set(owner,opens),command.id!==void 0&&this.writer.sendOpenQueued(owner,{type:"queued",for_request:command.id,position:inFlight+1,in_flight:inFlight}),this.open(command,owner).finally(()=>{resolveBarrier(),opens.delete(barrier),opens.size===0&&this.opensByConnection.delete(owner)})}async open(command,owner){let kindError=sessionKindError(command.kind);if(kindError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);let autoTitleError=sessionAutoTitleError(command.auto_title);if(autoTitleError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${autoTitleError}`);let opened;try{opened=await this.registry.openSession({cwd:command.cwd??this.defaults.cwd,sessionPath:command.sessionPath,permissionPreset:command.permissionPreset??this.defaults.permissionPreset,creationModel:command.provider&&command.modelId?{provider:command.provider,modelId:command.modelId}:this.defaults.creationModel,initialThinkingLevel:command.thinkingLevel??this.defaults.initialThinkingLevel,sessionKind:command.kind,sessionContext:this.defaults.hostContext?{...command.context,...this.defaults.hostContext}:command.context,...command.durableSessionId!==void 0?{durableSessionId:command.durableSessionId}:{},...typeof command.auto_title=="boolean"?{autoTitle:command.auto_title}:{}},{retainOnDisconnect:command.retain_on_disconnect===!0});let openedSession=opened,entry=this.registry.getForCommand(openedSession.sessionId,"open_session");if(this.writer.setSessionKind(openedSession.sessionId,entry.kind),owner!==void 0&&(this.writer.hasRegisteredConnectionCapabilities(owner)||this.writer.setConnectionCapabilities(owner,this.pendingCapabilities.get(owner)??this.connectionOptions?.capabilities??[]),this.writer.attachConnectionToSession(owner,openedSession.sessionId)),owner!==void 0){let owned=this.sessionsByConnection.get(owner)??new Map;owned.set(openedSession.sessionId,(owned.get(openedSession.sessionId)??0)+1),this.sessionsByConnection.set(owner,owned)}if(!this.bindings.has(openedSession.sessionId)){this.bindings.set(openedSession.sessionId,await this.createBinding(openedSession.sessionId,entry,this.writer,()=>{this.close({type:"close_session",sessionId:openedSession.sessionId})},{...this.connectionOptions,capabilities:owner!==void 0?this.pendingCapabilities.get(owner)??this.connectionOptions?.capabilities??[]:this.connectionOptions?.capabilities,sharedWidth:{getWidth:()=>{let widths=this.widths.get(openedSession.sessionId);return widths?.size?Math.min(...widths.values()):80},setWidth:(connectionId,width)=>{if(connectionId!==void 0){let widths=this.widths.get(openedSession.sessionId)??new Map;widths.set(connectionId,width),this.widths.set(openedSession.sessionId,widths)}},clearWidth:connectionId=>{let widths=this.widths.get(openedSession.sessionId);connectionId!==void 0&&widths?.delete(connectionId)},setCapabilities:(connectionId,capabilities)=>{if(connectionId!==void 0){this.writer.setConnectionCapabilities(connectionId,capabilities),this.pendingCapabilities.set(connectionId,[...capabilities]);for(let binding of this.bindings.values())binding.rerenderComponents?.()}},hasRenderedComponents:sessionId=>this.writer.hasCapableConnection(sessionId),connectionId:()=>this.writer.currentConnection(),onChange:()=>{for(let binding of this.bindings.values())binding.rerenderComponents?.()}}})),entry.worker&&(entry.worker.bindingReady=!0);let settled=()=>{this.draining&&queueMicrotask(()=>this.sweepDrain())};typeof entry.worker?.subscribeSettled=="function"?entry.worker.subscribeSettled(settled):typeof entry.runtime?.session.subscribe=="function"&&entry.runtime.session.subscribe(event=>{(event.type==="agent_settled"||event.type==="agent_idle")&&settled()}),entry.worker&&entry.worker.exited.then(async()=>{await this.finalizations.get(openedSession.sessionId)?.promise,this.bindings.delete(openedSession.sessionId),this.forgetSessionOwnership(openedSession.sessionId),this.writer.forgetSession(openedSession.sessionId)})}!this.draining&&owner!==void 0&&this.releasedConnections.has(owner)&&(this.releaseOwnerAttachment(owner,openedSession.sessionId),await this.releaseOwnedSession(openedSession.sessionId));let state=entry.worker?.snapshot?.state??(entry.runtime?buildRpcSessionState(entry.runtime.session):void 0);if(!state)throw new Error("Session state was not created");this.writer.enqueue(opened.sessionId,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:opened.sessionId,state,...opened.attached?{attached:!0}:{}}});return}catch(cause){if(opened)try{await this.registry.close(opened.sessionId)}catch{}return error(command.id,"open_session",this.code(cause),this.detail(cause))}}async releaseConnection(connectionId){this.releasedConnections.add(connectionId),this.writer.clearConnectionCapabilities(connectionId);for(let sessionId of this.sessionsByConnection.get(connectionId)?.keys()??[])this.writer.detachConnectionFromSession(connectionId,sessionId);for(let widths of this.widths.values())widths.delete(connectionId);for(let binding of this.bindings.values())binding.rerenderComponents?.();let opens=this.opensByConnection.get(connectionId),owned=this.sessionsByConnection.get(connectionId);if(this.sessionsByConnection.delete(connectionId),this.draining){opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId);return}if(owned===void 0){opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId);return}await Promise.all([...owned].map(async([sessionId,count])=>{for(let attachment=0;attachment<count;attachment++){let live=this.registry.peek(sessionId),retained=live?.retainOnDisconnect===!0,session=live?.state==="open"?live.runtime?.session:void 0;if(!retained&&live?.state==="open"&&live.worker?.snapshot?.streaming){let unsubscribe=live.worker.subscribeSettled(()=>{unsubscribe(),this.releaseOwnedSession(sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred worker release ${sessionId} failed: ${String(cause)}
|
|
10
10
|
`)})});continue}if(!retained&&session?.isStreaming){let released=!1,unsubscribe=session.subscribe(event=>{event.type!=="agent_settled"&&event.type!=="agent_idle"||released||(released=!0,unsubscribe(),this.releaseOwnedSession(sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred release for session ${sessionId} failed: ${String(cause)}
|
|
11
11
|
`)}))});continue}await this.releaseOwnedSession(sessionId)}})),opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId)}async releaseOwnedSession(sessionId){let live=this.registry.peek(sessionId),parks=live?.state==="open"&&live.retainOnDisconnect===!0&&live.attachments===1,claim=this.tryClaimClose(sessionId,{drainAttachments:!1,detach:!0});if(!claim)return;if(!claim.finalizer){parks&&live.runtime&&(live.lifecycleMutex=live.lifecycleMutex.then(()=>live.runtime?.emitAttachmentEvent("session_parked")),await live.lifecycleMutex),await this.finalizations.get(sessionId)?.promise;return}let binding=this.bindings.get(sessionId);binding?.cancelPendingExtensionUiRequests?.(),await this.finalizeClose(sessionId,binding)}claimClose(sessionId,options){let finalizer=!0,onRole=isFinalizer=>{finalizer=isFinalizer,isFinalizer&&!this.finalizations.has(sessionId)&&this.finalizations.set(sessionId,this.createFinalization())},entry=this.registry.beginClose(sessionId,onRole,{detach:options.detach});for(;options.drainAttachments&&entry.state==="open";)entry=this.registry.beginClose(sessionId,onRole);return{finalizer:finalizer&&entry.state==="closing"}}tryClaimClose(sessionId,options){try{return this.claimClose(sessionId,options)}catch{return}}async close(command){let response={id:command.id,type:"response",command:"close_session",success:!0,data:{}},owner=this.writer.currentConnection();if(owner!==void 0&&this.sessionsByConnection.get(owner)?.has(command.sessionId)!==!0)return error(command.id,"close_session",RPC_ERROR_UNKNOWN_SESSION);let reply=this.writer.reserveCloseResponse(command.sessionId,response);if(!reply)return;let claim;try{claim=this.claimClose(command.sessionId,{drainAttachments:!1})}catch(cause){return reply.release(),error(command.id,"close_session",this.code(cause))}try{owner!==void 0&&this.releaseOwnerAttachment(owner,command.sessionId),claim.finalizer?await this.finalizeClose(command.sessionId,this.bindings.get(command.sessionId),()=>reply.complete(!0,"client_close")):(await this.finalizations.get(command.sessionId)?.promise,reply.complete(!1));return}finally{reply.release()}}releaseOwnerAttachment(owner,sessionId){this.widths.get(sessionId)?.delete(owner),this.writer.detachConnectionFromSession(owner,sessionId);for(let binding of this.bindings.values())try{binding.rerenderComponents?.()}catch(cause){process.stderr.write(`senpi rpc rerender after close of session ${sessionId} failed: ${String(cause)}
|
|
12
12
|
`)}let owned=this.sessionsByConnection.get(owner),count=owned?.get(sessionId);!owned||count===void 0||(count===1?owned.delete(sessionId):owned.set(sessionId,count-1),owned.size===0&&this.sessionsByConnection.delete(owner))}async finalizeClose(sessionId,binding,terminal){let finalization=this.finalizations.get(sessionId)??this.createFinalization();this.finalizations.set(sessionId,finalization);try{try{await binding?.dispose()}catch(cause){process.stderr.write(`senpi rpc binding dispose for session ${sessionId} failed: ${String(cause)}
|
|
13
13
|
`)}this.bindings.delete(sessionId);try{await this.registry.closeMarked(sessionId)}catch(cause){process.stderr.write(`senpi rpc close for session ${sessionId} failed: ${String(cause)}
|
|
14
|
-
`)}await this.registry.peek(sessionId)?.closeCompletion,terminal?.()}finally{finalization.resolve(),this.finalizations.delete(sessionId)}}createFinalization(){let resolveFinalization;return{promise:new Promise(resolve=>{resolveFinalization=resolve}),resolve:()=>resolveFinalization?.()}}detail(cause){return cause instanceof RpcSessionRegistryError?cause.detail:void 0}code(cause){return cause instanceof RpcSessionRegistryError?cause.code===RPC_ERROR_OPEN_FAILED?cause.message:cause.code:cause instanceof Error&&[RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_SESSION_CLOSING].includes(cause.message)?cause.message:cause instanceof Error&&cause.message?`${RPC_ERROR_OPEN_FAILED}: ${cause.message}`:RPC_ERROR_UNKNOWN_SESSION}};function socketSink(socket){let needsDrain=!1,cut=!1;return{writeRaw(chunk){!cut&&!socket.destroyed&&(needsDrain=!socket.write(chunk))},close(){if(cut||(cut=!0,socket.destroyed))return;socket.end();let grace=setTimeout(()=>socket.destroy(),5e3);grace.unref(),socket.once("close",()=>clearTimeout(grace))},waitForBackpressure(){return socket.destroyed||!needsDrain?Promise.resolve():(needsDrain=!1,new Promise(resolve=>{let done=()=>{socket.off("drain",done),socket.off("close",done),resolve()};socket.once("drain",done),socket.once("close",done)}))}}}import{isAbsolute as isAbsolute2}from"node:path";var SESSION_WORKER_LIMITS={workers:20,requests:64,controlRequests:4,controlBytes:1048576,requestBytes:16777216,outputBytes:16777216,reservations:64,openMs:3e4,controlMs:5e3},WORKER_CREDIT_CODES={granted:1,conflict:2,limit:3};var RESERVATION_DENIAL_CODES={conflict:"session_path_in_use",limit:"session_reservation_limit"},SessionPathReservations=class{constructor(){this.owners=new Map}owner(path){return this.owners.get(path)}count(handle){let count=0;for(let owner of this.owners.values())owner===handle&&count++;return count}reserve(handle,path,live){let owner=this.owners.get(path);return owner?owner===handle?"granted":"conflict":this.count(handle)>=SESSION_WORKER_LIMITS.reservations&&(!live||(this.reconcile(handle,live),this.count(handle)>=SESSION_WORKER_LIMITS.reservations))?"limit":(this.owners.set(path,handle),"granted")}reconcile(handle,live){for(let[path,owner]of this.owners)owner!==handle||path===live.sessionPath||live.livePaths.includes(path)||this.owners.delete(path)}releaseAll(handle){for(let[path,owner]of this.owners)owner===handle&&this.owners.delete(path)}};import{fileURLToPath}from"node:url";import{Worker}from"node:worker_threads";var SessionWorkerRequests=class{constructor(send,timeout){this.pending=new Map,this.serial=0,this.closed=!1,this.send=send,this.timeout=timeout}remainingOpenMs(){let now=Date.now();return this.openingDeadline===void 0&&(this.openingDeadline=now+SESSION_WORKER_LIMITS.openMs),Math.max(0,this.openingDeadline-now)}get activeCount(){return this.pending.size}request(message){if(this.closed)return Promise.reject(new Error("session_closing"));let control=message.type==="command"&&"type"in message.command&&typeof message.command.type=="string"&&["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(message.command.type),bytes=Buffer.byteLength(JSON.stringify(message)),count=0,pendingBytes=0;for(let pending of this.pending.values())pending.control===control&&(count++,pendingBytes+=pending.bytes);let maxCount=control?SESSION_WORKER_LIMITS.controlRequests:SESSION_WORKER_LIMITS.requests,maxBytes=control?SESSION_WORKER_LIMITS.controlBytes:SESSION_WORKER_LIMITS.requestBytes;if(count>=maxCount||pendingBytes+bytes>maxBytes)return Promise.reject(new Error("session_worker_request_limit"));let request=++this.serial;return new Promise((resolve,reject)=>{let timer=message.type==="command"&&!control?void 0:setTimeout(this.timeout,control?SESSION_WORKER_LIMITS.controlMs:this.remainingOpenMs());this.pending.set(request,{resolve,reject,bytes,control,timer});try{this.send({...message,request})}catch(cause){this.pending.delete(request),clearTimeout(timer),reject(cause instanceof Error?cause:new Error(String(cause)))}})}receive(message){let pending=this.pending.get(message.request);pending&&(clearTimeout(pending.timer),this.pending.delete(message.request),message.type==="result"&&message.error?pending.reject(new Error(message.error)):pending.resolve(message))}close(error2){this.closed=!0;for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(error2);this.pending.clear()}};function acknowledgeGrant(signal,grant){let state=new Int32Array(signal);Atomics.store(state,0,WORKER_CREDIT_CODES[grant]),Atomics.notify(state,0)}function acknowledge(signal,granted){acknowledgeGrant(signal,granted?"granted":"conflict")}function respondDisplay(signal,display){let values=new Float64Array(signal);values[1]=display.width,values[2]=display.revision,Atomics.store(new Int32Array(signal),1,display.rendered?1:0),acknowledge(signal,!0)}var compiledWorkerEntry=typeof SENPI_RPC_SESSION_WORKER_ENTRY=="string"?SENPI_RPC_SESSION_WORKER_ENTRY:"./src/modes/rpc/session-worker.ts",SessionWorkerClient=class{constructor(callbacks){this.webviewBroker=createWebViewBroker(),this.worker=new Worker(isBunBinary?fileURLToPath(new URL(compiledWorkerEntry,import.meta.url)).replaceAll("\\","/"):new URL(import.meta.url.endsWith(".ts")?"./session-worker.ts":"./session-worker.js",import.meta.url),this.webviewBroker?{workerData:{webviewBroker:this.webviewBroker.port},transferList:[this.webviewBroker.port]}:{}),this.bindingReady=!1,this.requests=new SessionWorkerRequests(message=>this.worker.postMessage(message),()=>this.fail("session_worker_request_timeout")),this.stopped=!1,this.displayRevision=0,this.options={},this.listeners=new Set,this.controls=new Set,this.callbacks=callbacks,this.exited=new Promise(resolve=>{this.worker.once("exit",()=>{!this.stopped&&!this.closeTimer&&this.fail("session_worker_exited"),this.stopped=!0,this.closeTimer&&clearTimeout(this.closeTimer),this.requests.close(new Error("session_worker_exited")),this.webviewBroker?.dispose(),this.listeners.clear(),callbacks.exit(),this.publishTerminalFailure(),resolve()})}),this.worker.on("message",message=>this.receive(message)),this.worker.on("error",error2=>this.fail(error2 instanceof Error?error2.message:String(error2)))}async prepare(configuration,profile){let result=await this.request({type:"prepare",configuration,profile});if(result.type!=="prepared")throw new Error("Invalid worker prepare response");return result.sessionPath}async commit(){let result=await this.request({type:"commit"});if(result.type!=="ready")throw new Error("Invalid worker commit response");return this.snapshot=result.snapshot,result.snapshot}async bind(sessionId,writer,requestClose,options){return this.sessionId=sessionId,this.writer=writer,this.requestClose=requestClose,this.options=options,await this.request({type:"bind",sessionId,display:this.display(),connection:writer.currentConnection()}),{handle:async command=>{await this.request({type:"command",command,connection:writer.currentConnection(),display:this.display()})},cancelPendingExtensionUiRequests:()=>this.post({type:"cancel_ui"}),rerenderComponents:()=>this.post({type:"display",display:this.display()}),dispose:async()=>{this.post({type:"cancel_ui"})}}}get busy(){return this.requests.activeCount>0||this.snapshot?.busy===!0}get handoffBusy(){return this.requests.activeCount>0||(this.snapshot?.handoffBusy??this.snapshot?.busy)===!0}subscribeSettled(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}close(graceMs){return this.stopped||this.closeTimer?this.exited:(this.post({type:"close"}),this.closeTimer=setTimeout(()=>this.quarantine(),graceMs),this.exited)}quarantine(){this.stopped=!0,this.requests.close(new Error("session_closing")),this.worker.terminate()}display(){return{revision:++this.displayRevision,width:this.options.sharedWidth?.getWidth()??80,rendered:this.options.sharedWidth?.hasRenderedComponents?.(this.sessionId??"")??!1,capabilities:this.options.capabilities??[]}}request(message){return this.requests.request(message)}post(message){if(!this.stopped){if(message.type==="display"||message.type==="cancel_ui"){if(this.controls.has(message.type)){message.type==="display"&&(this.latestDisplay=message);return}this.controls.add(message.type)}this.worker.postMessage(message)}}receive(message){if(this.stopped){"signal"in message&&acknowledge(message.signal,!1);return}switch(message.type){case"prepared":case"ready":case"result":{this.requests.receive(message);return}case"reserve":acknowledgeGrant(message.signal,this.callbacks.reserve(message.path));return;case"snapshot":if(this.snapshot=message.snapshot,this.callbacks.reconcile(message.snapshot.liveSessionPaths),acknowledge(message.signal,!0),message.settled)for(let listener of[...this.listeners])listener();return;case"control_done":{if(this.controls.delete(message.control),message.control==="display"&&this.latestDisplay){let latest=this.latestDisplay;this.latestDisplay=void 0,this.post(latest)}return}case"output":{let writer=this.writer,sessionId=this.sessionId;if(!writer||!sessionId||this.stopped){acknowledge(message.signal,!1);return}message.snapshot?(this.snapshot=message.snapshot,this.callbacks.reconcile(message.snapshot.liveSessionPaths)):this.snapshot&&(this.snapshot={...this.snapshot,...message.activity,state:{...this.snapshot.state,isStreaming:message.activity.streaming}});let enqueue=()=>writer.enqueue(sessionId,message.record)?writer.waitForSessionBackpressure(sessionId):(acknowledge(message.signal,!1),this.fail("session_output_overflow_or_closed"),Promise.reject(new Error("session_output_overflow_or_closed")));(message.connection===void 0?enqueue():writer.withConnection(message.connection,enqueue)).then(()=>acknowledge(message.signal,!0),cause=>{acknowledge(message.signal,!1),this.fail(cause instanceof Error?cause.message:String(cause))});return}case"width":this.options.sharedWidth?.setWidth(message.connection,message.width),this.options.sharedWidth?.onChange?.(),respondDisplay(message.signal,this.display());return;case"capabilities":this.options.sharedWidth?.setCapabilities?.(message.connection,message.capabilities),respondDisplay(message.signal,this.display());return;case"request_close":this.requestClose?.();return;case"failure":this.fail(message.error);return}}fail(error2){this.stopped||(this.callbacks.failure(error2),this.terminalFailure=error2,this.writer&&this.sessionId&&this.writer.enqueue(this.sessionId,{type:"session_error",error:error2}),this.quarantine())}publishTerminalFailure(){let error2=this.terminalFailure,writer=this.writer,sessionId=this.sessionId;error2===void 0||!writer||!sessionId||(this.terminalFailure=void 0,writer.closeSession(sessionId,{type:"response",command:"close_session",success:!1,error:error2},"error"))}};var WorkerSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new SessionPathReservations,this.serial=0,this.options=options,this.closeGraceMs=options.closeGraceMs,this.now=options.now,this.createWorker=options.createWorker??(callbacks=>new SessionWorkerClient(callbacks))}get size(){return this.entries.size}async openSession(profile,options){if(!isAbsolute2(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute2(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");let requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){try{assertValidSessionId(requestedDurableId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}let requestedKey=profile.sessionPath?this.knownReservationKey(profile.sessionPath):void 0;for(let entry2 of this.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(requestedKey!==void 0&&entry2.reservationKey===requestedKey))throw new RpcSessionRegistryError("session_id_in_use")}if(profile.sessionPath){let key=this.knownReservationKey(profile.sessionPath),owner=key?this.reservations.owner(key):void 0;if(key&&owner)return this.attach(owner,key,options)}if(this.size>=SESSION_WORKER_LIMITS.workers)throw new Error("too_many_sessions");let handle=`rpc-${++this.serial}`,storedProfile=frozenProfile(profile),entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),cwd:profile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve(),...requestedDurableId!==void 0?{durableSessionId:requestedDurableId}:{}},workerFailure,worker=this.createWorker({reserve:path=>this.reserve(handle,path),reconcile:livePaths=>this.reconcile(handle,livePaths),exit:()=>{this.entries.get(handle)===entry&&(entry.state="closed",this.entries.delete(handle),this.reservations.releaseAll(handle),entry.closeResolve?.())},failure:error2=>{workerFailure=error2,entry.state="quarantined",process.stderr.write(`senpi rpc session ${handle} quarantined: ${error2}
|
|
14
|
+
`)}await this.registry.peek(sessionId)?.closeCompletion,terminal?.()}finally{finalization.resolve(),this.finalizations.delete(sessionId)}}createFinalization(){let resolveFinalization;return{promise:new Promise(resolve=>{resolveFinalization=resolve}),resolve:()=>resolveFinalization?.()}}detail(cause){return cause instanceof RpcSessionRegistryError?cause.detail:void 0}code(cause){return cause instanceof RpcSessionRegistryError?cause.code===RPC_ERROR_OPEN_FAILED?cause.message:cause.code:cause instanceof Error&&[RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_SESSION_CLOSING].includes(cause.message)?cause.message:cause instanceof Error&&cause.message?`${RPC_ERROR_OPEN_FAILED}: ${cause.message}`:RPC_ERROR_UNKNOWN_SESSION}};function socketSink(socket){let needsDrain=!1,cut=!1;return{writeRaw(chunk){!cut&&!socket.destroyed&&(needsDrain=!socket.write(chunk))},close(){if(cut||(cut=!0,socket.destroyed))return;socket.end();let grace=setTimeout(()=>socket.destroy(),5e3);grace.unref(),socket.once("close",()=>clearTimeout(grace))},waitForBackpressure(){return socket.destroyed||!needsDrain?Promise.resolve():(needsDrain=!1,new Promise(resolve=>{let done=()=>{socket.off("drain",done),socket.off("close",done),resolve()};socket.once("drain",done),socket.once("close",done)}))}}}import{isAbsolute as isAbsolute3}from"node:path";var SESSION_WORKER_LIMITS={workers:20,requests:64,controlRequests:4,controlBytes:1048576,requestBytes:16777216,outputBytes:16777216,reservations:64,openMs:3e4,controlMs:5e3},WORKER_CREDIT_CODES={granted:1,conflict:2,limit:3};var RESERVATION_DENIAL_CODES={conflict:"session_path_in_use",limit:"session_reservation_limit"},SessionPathReservations=class{constructor(){this.owners=new Map}owner(path){return this.owners.get(path)}count(handle){let count=0;for(let owner of this.owners.values())owner===handle&&count++;return count}reserve(handle,path,live){let owner=this.owners.get(path);return owner?owner===handle?"granted":"conflict":this.count(handle)>=SESSION_WORKER_LIMITS.reservations&&(!live||(this.reconcile(handle,live),this.count(handle)>=SESSION_WORKER_LIMITS.reservations))?"limit":(this.owners.set(path,handle),"granted")}reconcile(handle,live){for(let[path,owner]of this.owners)owner!==handle||path===live.sessionPath||live.livePaths.includes(path)||this.owners.delete(path)}releaseAll(handle){for(let[path,owner]of this.owners)owner===handle&&this.owners.delete(path)}};import{fileURLToPath}from"node:url";import{Worker}from"node:worker_threads";var SessionWorkerRequests=class{constructor(send,timeout){this.pending=new Map,this.serial=0,this.closed=!1,this.send=send,this.timeout=timeout}remainingOpenMs(){let now=Date.now();return this.openingDeadline===void 0&&(this.openingDeadline=now+SESSION_WORKER_LIMITS.openMs),Math.max(0,this.openingDeadline-now)}get activeCount(){return this.pending.size}request(message){if(this.closed)return Promise.reject(new Error("session_closing"));let control=message.type==="command"&&"type"in message.command&&typeof message.command.type=="string"&&["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(message.command.type),bytes=Buffer.byteLength(JSON.stringify(message)),count=0,pendingBytes=0;for(let pending of this.pending.values())pending.control===control&&(count++,pendingBytes+=pending.bytes);let maxCount=control?SESSION_WORKER_LIMITS.controlRequests:SESSION_WORKER_LIMITS.requests,maxBytes=control?SESSION_WORKER_LIMITS.controlBytes:SESSION_WORKER_LIMITS.requestBytes;if(count>=maxCount||pendingBytes+bytes>maxBytes)return Promise.reject(new Error("session_worker_request_limit"));let request=++this.serial;return new Promise((resolve,reject)=>{let timer=message.type==="command"&&!control?void 0:setTimeout(this.timeout,control?SESSION_WORKER_LIMITS.controlMs:this.remainingOpenMs());this.pending.set(request,{resolve,reject,bytes,control,timer});try{this.send({...message,request})}catch(cause){this.pending.delete(request),clearTimeout(timer),reject(cause instanceof Error?cause:new Error(String(cause)))}})}receive(message){let pending=this.pending.get(message.request);pending&&(clearTimeout(pending.timer),this.pending.delete(message.request),message.type==="result"&&message.error?pending.reject(new Error(message.error)):pending.resolve(message))}close(error2){this.closed=!0;for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(error2);this.pending.clear()}};function acknowledgeGrant(signal,grant){let state=new Int32Array(signal);Atomics.store(state,0,WORKER_CREDIT_CODES[grant]),Atomics.notify(state,0)}function acknowledge(signal,granted){acknowledgeGrant(signal,granted?"granted":"conflict")}function respondDisplay(signal,display){let values=new Float64Array(signal);values[1]=display.width,values[2]=display.revision,Atomics.store(new Int32Array(signal),1,display.rendered?1:0),acknowledge(signal,!0)}var compiledWorkerEntry=typeof SENPI_RPC_SESSION_WORKER_ENTRY=="string"?SENPI_RPC_SESSION_WORKER_ENTRY:"./src/modes/rpc/session-worker.ts",SessionWorkerClient=class{constructor(callbacks){this.webviewBroker=createWebViewBroker(),this.worker=new Worker(isBunBinary?fileURLToPath(new URL(compiledWorkerEntry,import.meta.url)).replaceAll("\\","/"):new URL(import.meta.url.endsWith(".ts")?"./session-worker.ts":"./session-worker.js",import.meta.url),this.webviewBroker?{workerData:{webviewBroker:this.webviewBroker.port},transferList:[this.webviewBroker.port]}:{}),this.bindingReady=!1,this.requests=new SessionWorkerRequests(message=>this.worker.postMessage(message),()=>this.fail("session_worker_request_timeout")),this.stopped=!1,this.displayRevision=0,this.options={},this.listeners=new Set,this.controls=new Set,this.callbacks=callbacks,this.exited=new Promise(resolve=>{this.worker.once("exit",()=>{!this.stopped&&!this.closeTimer&&this.fail("session_worker_exited"),this.stopped=!0,this.closeTimer&&clearTimeout(this.closeTimer),this.requests.close(new Error("session_worker_exited")),this.webviewBroker?.dispose(),this.listeners.clear(),callbacks.exit(),this.publishTerminalFailure(),resolve()})}),this.worker.on("message",message=>this.receive(message)),this.worker.on("error",error2=>this.fail(error2 instanceof Error?error2.message:String(error2)))}async prepare(configuration,profile){let result=await this.request({type:"prepare",configuration,profile});if(result.type!=="prepared")throw new Error("Invalid worker prepare response");return result.sessionPath}async commit(){let result=await this.request({type:"commit"});if(result.type!=="ready")throw new Error("Invalid worker commit response");return this.snapshot=result.snapshot,result.snapshot}async bind(sessionId,writer,requestClose,options){return this.sessionId=sessionId,this.writer=writer,this.requestClose=requestClose,this.options=options,await this.request({type:"bind",sessionId,display:this.display(),connection:writer.currentConnection()}),{handle:async command=>{await this.request({type:"command",command,connection:writer.currentConnection(),display:this.display()})},cancelPendingExtensionUiRequests:()=>this.post({type:"cancel_ui"}),rerenderComponents:()=>this.post({type:"display",display:this.display()}),dispose:async()=>{this.post({type:"cancel_ui"})}}}get busy(){return this.requests.activeCount>0||this.snapshot?.busy===!0}get handoffBusy(){return this.requests.activeCount>0||(this.snapshot?.handoffBusy??this.snapshot?.busy)===!0}subscribeSettled(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}close(graceMs){return this.stopped||this.closeTimer?this.exited:(this.post({type:"close"}),this.closeTimer=setTimeout(()=>this.quarantine(),graceMs),this.exited)}quarantine(){this.stopped=!0,this.requests.close(new Error("session_closing")),this.worker.terminate()}display(){return{revision:++this.displayRevision,width:this.options.sharedWidth?.getWidth()??80,rendered:this.options.sharedWidth?.hasRenderedComponents?.(this.sessionId??"")??!1,capabilities:this.options.capabilities??[]}}request(message){return this.requests.request(message)}post(message){if(!this.stopped){if(message.type==="display"||message.type==="cancel_ui"){if(this.controls.has(message.type)){message.type==="display"&&(this.latestDisplay=message);return}this.controls.add(message.type)}this.worker.postMessage(message)}}receive(message){if(this.stopped){"signal"in message&&acknowledge(message.signal,!1);return}switch(message.type){case"prepared":case"ready":case"result":{this.requests.receive(message);return}case"reserve":acknowledgeGrant(message.signal,this.callbacks.reserve(message.path));return;case"snapshot":if(this.snapshot=message.snapshot,this.callbacks.reconcile(message.snapshot.liveSessionPaths),acknowledge(message.signal,!0),message.settled)for(let listener of[...this.listeners])listener();return;case"control_done":{if(this.controls.delete(message.control),message.control==="display"&&this.latestDisplay){let latest=this.latestDisplay;this.latestDisplay=void 0,this.post(latest)}return}case"output":{let writer=this.writer,sessionId=this.sessionId;if(!writer||!sessionId||this.stopped){acknowledge(message.signal,!1);return}message.snapshot?(this.snapshot=message.snapshot,this.callbacks.reconcile(message.snapshot.liveSessionPaths)):this.snapshot&&(this.snapshot={...this.snapshot,...message.activity,state:{...this.snapshot.state,isStreaming:message.activity.streaming}});let enqueue=()=>writer.enqueue(sessionId,message.record)?writer.waitForSessionBackpressure(sessionId):(acknowledge(message.signal,!1),this.fail("session_output_overflow_or_closed"),Promise.reject(new Error("session_output_overflow_or_closed")));(message.connection===void 0?enqueue():writer.withConnection(message.connection,enqueue)).then(()=>acknowledge(message.signal,!0),cause=>{acknowledge(message.signal,!1),this.fail(cause instanceof Error?cause.message:String(cause))});return}case"width":this.options.sharedWidth?.setWidth(message.connection,message.width),this.options.sharedWidth?.onChange?.(),respondDisplay(message.signal,this.display());return;case"capabilities":this.options.sharedWidth?.setCapabilities?.(message.connection,message.capabilities),respondDisplay(message.signal,this.display());return;case"request_close":this.requestClose?.();return;case"failure":this.fail(message.error);return}}fail(error2){this.stopped||(this.callbacks.failure(error2),this.terminalFailure=error2,this.writer&&this.sessionId&&this.writer.enqueue(this.sessionId,{type:"session_error",error:error2}),this.quarantine())}publishTerminalFailure(){let error2=this.terminalFailure,writer=this.writer,sessionId=this.sessionId;error2===void 0||!writer||!sessionId||(this.terminalFailure=void 0,writer.closeSession(sessionId,{type:"response",command:"close_session",success:!1,error:error2},"error"))}};var WorkerSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new SessionPathReservations,this.serial=0,this.options=options,this.closeGraceMs=options.closeGraceMs,this.now=options.now,this.createWorker=options.createWorker??(callbacks=>new SessionWorkerClient(callbacks))}get size(){return this.entries.size}async openSession(profile,options){if(!isAbsolute3(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute3(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");let requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){try{assertValidSessionId(requestedDurableId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}let requestedKey=profile.sessionPath?this.knownReservationKey(profile.sessionPath):void 0;for(let entry2 of this.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(requestedKey!==void 0&&entry2.reservationKey===requestedKey))throw new RpcSessionRegistryError("session_id_in_use")}if(profile.sessionPath){let key=this.knownReservationKey(profile.sessionPath),owner=key?this.reservations.owner(key):void 0;if(key&&owner)return this.attach(owner,key,options)}if(this.size>=SESSION_WORKER_LIMITS.workers)throw new Error("too_many_sessions");let handle=`rpc-${++this.serial}`,storedProfile=frozenProfile(profile),entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),cwd:profile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve(),...requestedDurableId!==void 0?{durableSessionId:requestedDurableId}:{}},workerFailure,worker=this.createWorker({reserve:path=>this.reserve(handle,path),reconcile:livePaths=>this.reconcile(handle,livePaths),exit:()=>{this.entries.get(handle)===entry&&(entry.state="closed",this.entries.delete(handle),this.reservations.releaseAll(handle),entry.closeResolve?.())},failure:error2=>{workerFailure=error2,entry.state="quarantined",process.stderr.write(`senpi rpc session ${handle} quarantined: ${error2}
|
|
15
15
|
`)}});entry.worker=worker,this.entries.set(handle,entry);try{let path=await worker.prepare(this.options.configuration,profile),owner=this.reservations.owner(path);if(owner){let attached=this.attach(owner,path,options);return entry.state="quarantined",worker.quarantine(),attached}let grant=this.reserve(handle,path);if(grant!=="granted")throw new RpcSessionRegistryError(RESERVATION_DENIAL_CODES[grant]);entry.reservationKey=path,entry.requestedPathKey=profile.sessionPath?path:void 0,entry.sessionPath=path;let snapshot=await worker.commit();if(entry.state!=="opening")throw workerFailure===void 0?new RpcSessionRegistryError("session_closing"):new RpcSessionRegistryError("open_failed",workerFailure);return entry.durableSessionId=snapshot.state.sessionId,entry.cwd=snapshot.state.cwd,entry.state="open",this.openResult(handle,entry)}catch(cause){throw entry.state="quarantined",worker.quarantine(),cause}}peek(handle){return this.entries.get(handle)}getForCommand(handle,command){let entry=this.entries.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="quarantined"||entry.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(command))throw new RpcSessionRegistryError("session_closing");if(entry.state!=="open"&&entry.state!=="closing")throw new RpcSessionRegistryError("unknown_session");return entry.lastCommandAt=this.now(),entry}beginClose(handle,onRole,options){let entry=this.entries.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing"||entry.state==="quarantined")return onRole?.(!1),entry;if(entry.state!=="open"&&entry.state!=="opening")throw new RpcSessionRegistryError("unknown_session");return entry.attachments--,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry):(entry.state="closing",entry.closeCompletion=new Promise(resolve=>{entry.closeResolve=resolve}),onRole?.(!0),entry)}close(handle){return this.beginClose(handle).state==="closing"?this.closeMarked(handle):Promise.resolve()}async closeMarked(handle){let entry=this.entries.get(handle);if(entry?.state!=="closing"||!entry.worker)throw new RpcSessionRegistryError("unknown_session");if(entry.closeStarted)return entry.closeCompletion;entry.closeStarted=!0;let timer;await Promise.race([entry.worker.close(this.closeGraceMs),new Promise(resolve=>{timer=setTimeout(()=>{entry.state!=="closed"&&(entry.state="quarantined"),resolve()},this.closeGraceMs)})]),timer&&clearTimeout(timer)}list(){return[...this.entries].map(([sessionId,entry])=>{let state=entry.worker?.snapshot?.state;return{sessionId,durableSessionId:state?.sessionId??entry.durableSessionId,sessionPath:state?.sessionFile??entry.sessionPath,cwd:state?.cwd??entry.cwd,name:state?.sessionName,kind:entry.kind,context:entry.context,attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state}})}knownReservationKey(path){if(this.reservations.owner(path))return path;for(let entry of this.entries.values()){if(entry.profile.sessionPath===path&&entry.requestedPathKey&&this.reservations.owner(entry.requestedPathKey))return entry.requestedPathKey;let snapshot=entry.worker?.snapshot;if(snapshot?.state.sessionFile===path)return snapshot.sessionPath}}attach(owner,path,options){let entry=this.entries.get(owner);if(entry?.state!=="open"||!entry.worker?.bindingReady||entry.worker.snapshot?.sessionPath!==path)throw new RpcSessionRegistryError("session_path_in_use");let result=this.openResult(owner,entry);return entry.attachments++,options?.retainOnDisconnect&&(entry.retainOnDisconnect=!0),entry.lastCommandAt=this.now(),{...result,attached:!0}}reservationCount(handle){return this.reservations.count(handle)}reserve(handle,path){let entry=this.entries.get(handle);return entry?this.reservations.owner(path)===handle?"granted":entry.state!=="opening"&&entry.state!=="open"?"conflict":this.reservations.reserve(handle,path,this.liveWorkerPaths(entry)):"conflict"}reconcile(handle,livePaths){let entry=this.entries.get(handle);if(entry?.state!=="open")return;let sessionPath=entry.worker?.snapshot?.sessionPath;this.reservations.reconcile(handle,{livePaths,sessionPath}),sessionPath&&(entry.reservationKey=sessionPath,entry.sessionPath=sessionPath)}liveWorkerPaths(entry){let snapshot=entry.state==="open"?entry.worker?.snapshot:void 0;if(snapshot)return{livePaths:snapshot.liveSessionPaths,sessionPath:snapshot.sessionPath}}openResult(handle,entry){let state=entry.worker?.snapshot?.state;if(!state)throw new RpcSessionRegistryError("open_failed");return{sessionId:handle,durableSessionId:state.sessionId,sessionPath:state.sessionFile}}};var WINDOWS_SHUTDOWN_HARD_EXIT_MS=2e3;function startHostObservers(router,writer,options={}){let loopLag=new LoopLagWatchdog({emit:record=>writer.broadcastHostRecord(record)}),memory=new HostMemorySampler({emit:record=>writer.broadcastHostRecord(record),sessions:()=>router.sessionCount,onPressure:pressure=>router.setMemoryPressure(pressure),...options.onIdlePressure?{onIdlePressure:options.onIdlePressure}:{}});return loopLag.start(),memory.start(),{stop:()=>{loopLag.stop(),memory.stop()}}}async function runMultiSessionHost(options){return runAsHostGenerationProcess(()=>options.listen===void 0||options.listen==="stdio://"?runStdioHost(options):runSocketHost(options,resolveSocketPath(options.listen,options.agentDir)))}function createHostCore(options,writer,capabilities=parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")),idle={},hostContext){let policy=resolveHostIdlePolicy(process.env,idle),router=new SessionCommandRouter(options.workerConfiguration?new WorkerSessionRegistry({configuration:options.workerConfiguration,now:policy.now,closeGraceMs:idle.closeGraceMs??parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV])??1e4}):new RpcSessionRegistry({agentDir:options.agentDir,createRuntime:options.createRuntime,mcpRegistry:new HostMcpRegistry,now:policy.now,closeGraceMs:idle.closeGraceMs??parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV])??1e4,pathReservations:createEndpointReservations({agentDir:options.agentDir,socket:listenSocketPath(options),instanceId:hostInstanceId(),onFailure:hostLog})}),writer,hostContext?{...options,hostContext}:options,options.createBinding,{capabilities},{now:policy.now,idleEvictionMs:policy.idleEvictionMs,emptyExitMs:policy.emptyExitMs,onEmptyExit:idle.onEmptyExit,onHandoffParked:idle.onHandoffParked,canExitWhenEmpty:idle.canExitWhenEmpty});return{router,handle:async line=>{let parsed;try{parsed=JSON.parse(line)}catch(cause){await writer.enqueueControl(parseError(`Failed to parse command: ${errorMessage(cause)}`));return}let shapeError=rpcCommandShapeError(parsed);if(shapeError){await writer.enqueueControl(parseError(shapeError));return}let response=await router.handle(parsed);response&&await writer.enqueueControl(response)}}}async function runStdioHost(options){takeOverStdout();let sink={writeRaw:writeRawStdout,waitForBackpressure:waitForRawStdoutBackpressure},writer=new SessionEventWriter(sink.writeRaw,sink.waitForBackpressure),{router,handle}=createHostCore(options,writer,void 0,{onEmptyExit:()=>{shutdown(0)}}),observers=startHostObservers(router,writer),shuttingDown=!1,shutdown=async(exitCode=0)=>{shuttingDown&&process.exit(exitCode),shuttingDown=!0,observers.stop(),detach(),await router.dispose(),await writer.flush(),await flushRawStdout(),process.exit(exitCode)},onEnd=()=>{shutdown()};process.stdin.on("end",onEnd);let reportInputFailure=cause=>{process.stderr.write(`senpi rpc stdio request failed: ${errorMessage(cause)}
|
|
16
16
|
`)},detachReader=attachJsonlLineReader(process.stdin,line=>{handle(line).catch(reportInputFailure)},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>{writer.enqueueControl(parseError(oversizedLineError())).catch(reportInputFailure)}}),detach=()=>{detachReader(),process.stdin.off("end",onEnd)};return registerShutdownSignals(shutdown),new Promise(()=>{})}async function runSocketHost(options,socketPath){await prepareSocketPath(socketPath);let writer=new SessionEventWriter(()=>{}),connections=new Map,occupancy=new ClientOccupancy(()=>{}),draining=!1,handoffAnnounced=!1,hostContext=hostSessionContext(socketPath),{router,handle}=createHostCore(options,writer,[...parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")).filter(capability=>capability!=="rendered_components"),GENERATION_HANDOFF_CAPABILITY],{onEmptyExit:()=>{shutdown(0)},canExitWhenEmpty:()=>draining||occupancy.attachedCount===0&&occupancy.unclassifiedCount===0,onHandoffParked:async ids=>{await Promise.all(ids.map(async id=>{await writer.flushConnection(id),connections.get(id)?.close()}))}},hostContext),observers=startHostObservers(router,writer,{onIdlePressure:({footprintMb,measure,rssMb})=>{hostLog(`memory pressure with no sessions: footprintMb=${footprintMb} (${measure}) rssMb=${rssMb}`),endpointSuperseded().then(superseded=>{superseded&&drainForHandoff()},noop)}}),nextConnection=0,shuttingDown=!1,secret=process.platform==="win32"?await ensureSocketSecret(process.env[SOCKET_SECRET_FILE_ENV]??socketSecretPath(socketPath)):void 0,watchdogConfig=readHostWatchdogConfigFromBrandEnv(),crashCleanupPaths=[...watchdogConfig?.cleanupPaths??[]],supervisorPublicSocketPath=process.platform==="win32"||socketPath.startsWith("\0")?void 0:watchdogConfig?.publicSocket,supervisorPublicOwnerFile=supervisorPublicSocketPath&&watchdogConfig?.scratchDir?join(watchdogConfig.scratchDir,PUBLIC_SOCKET_IDENTITY_FILE):void 0,boundIdentity,supervisorPublicIdentity,server=createServer(socket=>{let accept=()=>{if(draining||shuttingDown){socket.destroy();return}let id=`socket-${++nextConnection}`,sink=socketSink(socket);writer.registerConnection(id,sink),occupancy.admit(socket);let detachReader=attachJsonlLineReader(socket,line=>{writer.withConnection(id,()=>handle(line)).catch(cause=>{process.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}
|
|
17
17
|
`)})},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>{writer.withConnection(id,()=>writer.enqueueControl(parseError(oversizedLineError()))).catch(cause=>process.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}
|
|
@@ -19,5 +19,5 @@ import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,b
|
|
|
19
19
|
`)}))};connections.set(id,{id,sink,detach,close:()=>socket.destroy()}),socket.once("close",detach),socket.once("error",()=>detach())};secret?authenticateSocket(socket,secret,accept):accept()});server.on("error",cause=>{shuttingDown||process.stderr.write(`senpi rpc socket listener failed: ${errorMessage(cause)}
|
|
20
20
|
`)});let stopChildReaper=await startHostChildReaper(hostLog),shutdown=async(exitCode=0,watchdogCleanup)=>{shuttingDown&&process.exit(exitCode),shuttingDown=!0,observers.stop(),stopChildReaper();try{await router.dispose(),await writer.flush();for(let connection of connections.values())connection.detach(),connection.close();await shieldSocketDuringClose(socketPath,()=>process.platform==="win32"?Promise.race([closeServer(server),delay(WINDOWS_SHUTDOWN_HARD_EXIT_MS)]):closeServer(server)),await unlinkOwnedSocket(socketPath,boundIdentity,hostLog),supervisorPublicSocketPath&&await unlinkOwnedSocket(supervisorPublicSocketPath,supervisorPublicIdentity,hostLog),watchdogCleanup&&await watchdogCleanup}finally{process.exit(exitCode)}},drainForHandoff=()=>{if(!shuttingDown){if(draining){handoffAnnounced&&router.beginDrain();return}draining=!0,crashCleanupPaths.length=0,hostLog("draining for a generation handoff"),endpointSuperseded().then(superseded=>{writer.broadcastHostRecord({type:"host_superseded",instanceId:hostInstanceId(),generation:hostGeneration(process.env),successor:superseded?{socket:supervisorPublicSocketPath??socketPath}:null})}).catch(cause=>{hostLog(`handoff announcement failed: ${String(cause)}`)}).finally(()=>{handoffAnnounced=!0,router.beginDrain()})}},endpointSuperseded=()=>supervisorPublicSocketPath===void 0?socketEntryReplaced(socketPath,boundIdentity):socketEntryReplaced(supervisorPublicSocketPath,supervisorPublicIdentity);registerShutdownSignals(shutdown),process.platform!=="win32"&&process.on("SIGUSR1",drainForHandoff);let watchdog=watchdogConfig&&supervisorPublicOwnerFile?{...watchdogConfig,cleanupPaths:crashCleanupPaths,beforeCleanup:async()=>{supervisorPublicIdentity??=await readSocketIdentityFile(supervisorPublicOwnerFile)}}:watchdogConfig&&{...watchdogConfig,cleanupPaths:crashCleanupPaths};return armHostWatchdog(watchdog,(reason,cleanup)=>{process.stderr.write(`senpi rpc host: ${reason}; shutting down
|
|
21
21
|
`),shutdown(0,cleanup),setImmediate(killTrackedDetachedChildren)}),boundIdentity=await listen(server,socketPath,secret),supervisorPublicOwnerFile&&(supervisorPublicIdentity=await waitForSocketIdentityFile(supervisorPublicOwnerFile)),process.stderr.write(`senpi rpc listening on ${formatSocketAddress(socketPath)}
|
|
22
|
-
`),new Promise(()=>{})}function delay(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function noop(){}function parseError(error2){return{type:"response",command:"parse",success:!1,error:error2}}function oversizedLineError(){return`RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}function hostSessionContext(socketPath){let supervised=readHostWatchdogConfigFromBrandEnv(),endpoint=supervised===void 0?socketPath:supervised.publicSocket;if(endpoint===void 0||endpoint.startsWith("\0"))return{host_instance:hostInstanceId()};let directory=canonicalSessionPath(dirname(endpoint));return{host_socket:join(directory,basename(endpoint)),host_instance:hostInstanceId()}}function listenSocketPath(options){if(!(options.listen===void 0||options.listen==="stdio://"))return resolveSocketPath(options.listen,options.agentDir)}function resolveSocketPath(value,agentDir){if(value==="unix://")return join(agentDir,"rpc","rpc.sock");if(value.startsWith("unix://")){let path=value.slice(7);return path.length===0?join(agentDir,"rpc","rpc.sock"):path.startsWith("@")&&process.platform==="linux"?`\0${path.slice(1)}`:path}return value}function formatSocketAddress(socketPath){return socketPath.startsWith("\0")?`unix://@${socketPath.slice(1)}`:`unix://${socketPath}`}async function prepareSocketPath(socketPath){if(!(process.platform==="win32"||socketPath.startsWith("\0"))){await mkdir(dirname(socketPath),{recursive:!0,mode:448});try{await
|
|
22
|
+
`),new Promise(()=>{})}function delay(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function noop(){}function parseError(error2){return{type:"response",command:"parse",success:!1,error:error2}}function oversizedLineError(){return`RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}function hostSessionContext(socketPath){let supervised=readHostWatchdogConfigFromBrandEnv(),endpoint=supervised===void 0?socketPath:supervised.publicSocket;if(endpoint===void 0||endpoint.startsWith("\0"))return{host_instance:hostInstanceId()};let directory=canonicalSessionPath(dirname(endpoint));return{host_socket:join(directory,basename(endpoint)),host_instance:hostInstanceId()}}function listenSocketPath(options){if(!(options.listen===void 0||options.listen==="stdio://"))return resolveSocketPath(options.listen,options.agentDir)}function resolveSocketPath(value,agentDir){if(value==="unix://")return join(agentDir,"rpc","rpc.sock");if(value.startsWith("unix://")){let path=value.slice(7);return path.length===0?join(agentDir,"rpc","rpc.sock"):path.startsWith("@")&&process.platform==="linux"?`\0${path.slice(1)}`:path}return value}function formatSocketAddress(socketPath){return socketPath.startsWith("\0")?`unix://@${socketPath.slice(1)}`:`unix://${socketPath}`}async function prepareSocketPath(socketPath){if(!(process.platform==="win32"||socketPath.startsWith("\0"))){await mkdir(dirname(socketPath),{recursive:!0,mode:448});try{await access2(socketPath)}catch(cause){if(isNodeErrorCode(cause,"ENOENT"))return;throw cause}if(await probeSocket(socketPath))throw new Error(`${socketPath}: address already in use by a live server.`);await unlink(socketPath)}}function probeSocket(socketPath){return new Promise(resolve=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform)),settle=live=>{socket.destroy(),resolve(live)};socket.once("connect",()=>settle(!0)),socket.once("error",()=>settle(!1)),socket.setTimeout(1e3,()=>settle(!1))})}function listen(server,socketPath,secret){return new Promise((resolve,reject)=>{server.once("error",reject),server.listen(resolveSocketTransportAddress(socketPath,process.platform,secret),async()=>{server.off("error",reject);try{if(process.platform!=="win32"&&!socketPath.startsWith("\0"))return await chmod(socketPath,384),resolve(await statSocketIdentity(socketPath));resolve(void 0)}catch(cause){reject(cause)}})})}function closeServer(server){return new Promise((resolve,reject)=>{server.close(cause=>cause?reject(cause):resolve())})}function hostLog(message){process.stderr.write(`senpi rpc host: ${message}
|
|
23
23
|
`)}function isNodeErrorCode(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}function registerShutdownSignals(shutdown){for(let signal of process.platform==="win32"?["SIGTERM"]:["SIGTERM","SIGHUP"])process.on(signal,()=>{killTrackedDetachedChildren(),shutdown(signal==="SIGHUP"?129:143)})}export{DEFAULT_HOST_EMPTY_EXIT_MS,DEFAULT_SESSION_IDLE_EVICTION_MS,RPC_HOST_EMPTY_EXIT_MS_ENV,RPC_SESSION_IDLE_EVICTION_MS_ENV,createHostCore,resolveHostIdlePolicy,runMultiSessionHost};
|
package/dist/bundle/chunks/{package-manager-cli-SNVT3VKW.js → package-manager-cli-MJCRY2JU.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
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 = () => {}; } }
|
|
2
|
-
import{DefaultResourceLoader,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-
|
|
2
|
+
import{DefaultResourceLoader,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-56COAYOU.js";import"./chunk-FAV4DX74.js";import{DefaultPackageManager,DynamicBorder,appendHiddenTuiStdout,keyHint,rawKeyHint}from"./chunk-VW3QZSX3.js";import"./chunk-YJUO37UX.js";import"./chunk-TFA3YAJK.js";import"./chunk-F2YU5BZG.js";import"./chunk-NZRVAZL2.js";import"./chunk-U5KVIAHJ.js";import"./chunk-DB2X7SOZ.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-3HCYHGK2.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-6BWCPOCV.js";import"./chunk-AIM2YESB.js";import{SettingsManager}from"./chunk-CXVI2YV7.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-JASECXGC.js";import"./chunk-LM2UMEX6.js";import"./chunk-CEMOA3TF.js";import"./chunk-Y4CH7LYI.js";import"./chunk-E5F5SVZF.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-SQUUL72H.js";import"./chunk-JK5LVAOU.js";import{killProcessTree}from"./chunk-ASAQQ6VM.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-B32PXL7U.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-Y5A6TKBN.js";import"./chunk-L4OOEWAT.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-TOCWAEQB.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-UDTWLXSQ.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-J5TMX734.js";import"./chunk-LHYG7TK7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TJV2LFKM.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-7X4ZMME4.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
|
|
3
3
|
`)}return hash.digest("hex")}import{spawn}from"node:child_process";import{closeSync,mkdirSync,openSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{fileURLToPath}from"node:url";function omoLocalUpdateWorkerLogPath(agentDir){return join2(agentDir,"omo-local-update","worker.log")}function workerCommandArgs(force){let updateArgs=["update","--omo-local-update-worker",...force?["--force"]:[]];if(detectInstallMethod()==="bun-binary")return updateArgs;let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",cliMainPath=resolve(dirname(modulePath),"..",`cli-main${extension}`);return[...process.execArgv,cliMainPath,...updateArgs]}var defaultSpawnWorker=request=>{let logPath=omoLocalUpdateWorkerLogPath(request.agentDir);try{mkdirSync(dirname(logPath),{recursive:!0});let logFd=openSync(logPath,"w");try{let child=spawn(process.execPath,workerCommandArgs(request.force),{detached:!0,env:process.env,stdio:["ignore",logFd,logFd]});return child.unref(),{ok:!0,pid:child.pid,logPath}}finally{closeSync(logFd)}}catch(error){return{ok:!1,message:error instanceof Error?error.message:String(error)}}};async function defaultRun(command,args,options){let child=spawnProcess(command,args,{cwd:options.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env,...options.env},detached:process.platform!=="win32",windowsHide:!0}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()});let abort=new AbortController,timedOut=!1,pid=child.pid,timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,pid!==void 0&&killProcessTree(pid),abort.abort()},options.timeoutMs);try{return{code:await waitForChildProcess(child,{signal:abort.signal}),stdout,stderr,timedOut}}finally{timer!==void 0&&clearTimeout(timer)}}function isKillSwitched(env){return env.SENPI_OMO_LOCAL_UPDATE==="0"}function defaultReadJson(path){try{return JSON.parse(readFileSync(path,"utf-8"))}catch{return}}function packageNameOf(json){if(typeof json!="object"||json===null)return;let name=json.name;return typeof name=="string"?name:void 0}function homeDir(){return process.env.HOME||homedir()}async function detectOmoLocalInstall(options){let readJson=options.readJson??defaultReadJson,exists=options.exists??existsSync2;if(options.packages)for(let entry of options.packages){let source=typeof entry=="string"?entry:entry.source;if(!isLocalPath(source))continue;let pluginPath=resolvePath(source,options.agentDir,{homeDir:homeDir(),trim:!0});if(packageNameOf(readJson(join3(pluginPath,"package.json")))!=="@code-yeongyu/omo-senpi")continue;let repoRoot=resolve2(pluginPath,"..","..",".."),omoSenpiPkgPath=join3(repoRoot,"packages","omo-senpi","package.json"),senpiTaskPkgPath=join3(repoRoot,"packages","senpi-task","package.json");if(!exists(omoSenpiPkgPath)||packageNameOf(readJson(omoSenpiPkgPath))!=="@oh-my-opencode/omo-senpi"||!exists(senpiTaskPkgPath)||packageNameOf(readJson(senpiTaskPkgPath))!=="@oh-my-opencode/senpi-task")continue;let topLevel;try{let result=await options.run("git",["-C",repoRoot,"rev-parse","--show-toplevel"],{});if(result.code!==0)continue;topLevel=result.stdout.trim()}catch{continue}if(!(topLevel===""||canonicalizePath(topLevel)!==canonicalizePath(repoRoot)))return{pluginPath,repoRoot}}}function omoLocalUpdateStampPath(agentDir){return join3(agentDir,"omo-local-update-state.json")}function readStamp(agentDir){let json=defaultReadJson(omoLocalUpdateStampPath(agentDir));if(typeof json!="object"||json===null)return;let candidate=json;if(typeof candidate.repoRoot!="string"||typeof candidate.sha!="string"||typeof candidate.omoSenpiTree!="string"||typeof candidate.senpiTaskTree!="string"||typeof candidate.buildInputsHash!="string"||typeof candidate.installedAt!="string"||!Array.isArray(candidate.artifacts))return;let artifacts=[];for(let artifact of candidate.artifacts){if(typeof artifact!="string")return;artifacts.push(artifact)}return{repoRoot:candidate.repoRoot,sha:candidate.sha,omoSenpiTree:candidate.omoSenpiTree,senpiTaskTree:candidate.senpiTaskTree,buildInputsHash:candidate.buildInputsHash,installedAt:candidate.installedAt,artifacts}}function writeStamp(agentDir,stamp){mkdirSync2(agentDir,{recursive:!0}),writeFileSync(omoLocalUpdateStampPath(agentDir),`${JSON.stringify(stamp,null,2)}
|
|
4
4
|
`,"utf-8")}function shouldSkipUpdate(options){if(options.force)return!1;let stamp=options.stamp;return!stamp||stamp.repoRoot!==options.repoRoot||stamp.sha!==options.remoteSha&&stamp.buildInputsHash!==options.remoteBuildInputsHash||stamp.artifacts.length===0?!1:options.stampArtifactsExist}var OmoLocalStepError=class extends Error{constructor(stage,message,output){super(message),this.name="OmoLocalStepError",this.stage=stage,this.output=output}};function firstErrorLine(result){for(let text of[result.stderr,result.stdout])for(let line of text.split(`
|
|
5
5
|
`)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}async function computeRemoteState(options){let{repoRoot,run}=options,git=(args,timeoutMs)=>run("git",args,{cwd:repoRoot,timeoutMs}),requireOk=async(args,timeoutMs)=>{let result=await git(args,timeoutMs);if(result.timedOut)throw new OmoLocalStepError("fetch",`git ${args.join(" ")} timed out`);if(result.code!==0)throw new OmoLocalStepError("fetch",`git ${args.join(" ")}: ${firstErrorLine(result)}`,`${result.stdout}${result.stderr}`);return result.stdout.trim()};await requireOk(["fetch","origin","dev"],12e4);let sha=await requireOk(["rev-parse","origin/dev"]);if(sha==="")throw new OmoLocalStepError("fetch","git rev-parse origin/dev: empty output");let subject=await requireOk(["log","-1","--format=%s","origin/dev"]),omoSenpiTree=await requireOk(["rev-parse","origin/dev:packages/omo-senpi"]),senpiTaskTree=await requireOk(["rev-parse","origin/dev:packages/senpi-task"]),buildInputsHash=computeBuildInputsHashFromLsTree(await requireOk(["ls-tree","-z","origin/dev"]));return{sha,subject,omoSenpiTree,senpiTaskTree,buildInputsHash}}function omoLocalUpdateLockPath(agentDir){return join3(agentDir,"omo-local-update.lock")}function omoLocalUpdateBuildWorktreePath(agentDir){return join3(agentDir,"omo-local-update","build-worktree")}function readLockFile(path){try{let json=JSON.parse(readFileSync(path,"utf-8"));return typeof json.pid!="number"||typeof json.nonce!="string"?void 0:{pid:json.pid,nonce:json.nonce}}catch{return}}function pidIsAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function acquireOmoLocalLock(agentDir,log){mkdirSync2(agentDir,{recursive:!0});let path=omoLocalUpdateLockPath(agentDir),lock={path,pid:process.pid,nonce:randomUUID()},payload=JSON.stringify({pid:lock.pid,nonce:lock.nonce,startedAt:new Date().toISOString()}),tryCreate=()=>{try{return writeFileSync(path,payload,{flag:"wx"}),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}},reportBusy=()=>{let existing2=readLockFile(path);log(source_default.dim(`OMO local plugin update already running (pid ${existing2?.pid??"unknown"}); skipping.`))};if(tryCreate())return lock;let existing=readLockFile(path);if(existing!==void 0&&pidIsAlive(existing.pid))return reportBusy();try{rmSync(path)}catch{}return tryCreate()?lock:reportBusy()}function releaseOmoLocalLock(lock){try{let existing=readLockFile(lock.path);existing!==void 0&&existing.pid===lock.pid&&existing.nonce===lock.nonce&&rmSync(lock.path)}catch{}}var OmoLocalBunMissingError=class extends Error{constructor(){super("bun not found on PATH"),this.name="OmoLocalBunMissingError"}};async function runBunStep(stage,args,worktree,run,timeoutMs){let result;try{result=await run("bun",args,{cwd:worktree,timeoutMs})}catch(error){throw error.code==="ENOENT"?new OmoLocalBunMissingError:new OmoLocalStepError(stage,`bun ${args.join(" ")} failed to start: ${error instanceof Error?error.message:String(error)}`)}let output=`${result.stdout}${result.stderr}`;if(result.timedOut)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} timed out after ${Math.round(timeoutMs/1e3)}s`,output);if(result.code!==0)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} exited with code ${result.code??"unknown"}`,output)}async function ensureBuildWorktree(options){let{worktree,repoRoot,sha,run}=options;if(existsSync2(worktree)){let commonDir=await run("git",["-C",worktree,"rev-parse","--git-common-dir"],{});if(commonDir.code===0&&commonDir.stdout.trim()!==""&&canonicalizePath(resolve2(worktree,commonDir.stdout.trim()))===canonicalizePath(join3(repoRoot,".git"))){let checkout=await run("git",["-C",worktree,"checkout","--detach","--force",sha],{});if(checkout.code!==0)throw new OmoLocalStepError("worktree",`git checkout --detach --force: ${firstErrorLine(checkout)}`,`${checkout.stdout}${checkout.stderr}`);return}((await run("git",["-C",repoRoot,"worktree","remove","--force",worktree],{})).code!==0||existsSync2(worktree))&&rmSync(worktree,{recursive:!0,force:!0})}mkdirSync2(dirname2(worktree),{recursive:!0});let add=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(add.code===0)return;await run("git",["-C",repoRoot,"worktree","prune"],{});let retry=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(retry.code!==0)throw new OmoLocalStepError("worktree",`git worktree add: ${firstErrorLine(retry)}`,`${add.stdout}${add.stderr}${retry.stdout}${retry.stderr}`)}var defaultFsSeam={cpSync:(source,destination)=>{cpSync(source,destination,{recursive:!0})},renameSync:(oldPath,newPath)=>{renameSync(oldPath,newPath)},rmSync:path=>{rmSync(path,{recursive:!0,force:!0})}},swapCounter=0;function swapPluginDir(options){let seam=options.fs??defaultFsSeam;swapCounter+=1;let tag=`${Date.now()}-${process.pid}-${swapCounter}`,staging=`${options.pluginPath}.staging-${tag}`,prev=`${options.pluginPath}.prev-${tag}`;seam.cpSync(options.sourceDir,staging),seam.renameSync(options.pluginPath,prev);try{seam.renameSync(staging,options.pluginPath)}catch(error){throw seam.renameSync(prev,options.pluginPath),seam.rmSync(staging),error}seam.rmSync(prev)}function firstLine(text){for(let line of text.split(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
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 = () => {}; } }
|
|
2
|
-
import{runRpcMode}from"./chunk-
|
|
2
|
+
import{runRpcMode}from"./chunk-DB2X7SOZ.js";import"./chunk-3HCYHGK2.js";import"./chunk-6BWCPOCV.js";import"./chunk-AIM2YESB.js";import"./chunk-CXVI2YV7.js";import"./chunk-YU2P3CAR.js";import"./chunk-CEMOA3TF.js";import"./chunk-E5F5SVZF.js";import"./chunk-HB35RBP4.js";import"./chunk-JK5LVAOU.js";import"./chunk-ASAQQ6VM.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-Y5A6TKBN.js";import"./chunk-L4OOEWAT.js";import"./chunk-26UBFF6N.js";import"./chunk-TOCWAEQB.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-UDTWLXSQ.js";import"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-J5TMX734.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TJV2LFKM.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-7X4ZMME4.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{runRpcMode};
|