UNPKG

@code-yeongyu/senpi

Version:

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

58 lines • 347 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
import{getInternalHostBootstrap}from"./chunk-2WYNNBIR.js";import{GeneratedFramesCursor,NOTHING_DROPPED,PRESENTER_CONTROL_INFO_COMMAND,SessionEventWriter,abortAndSettle,answerSetSessionContext,answerSubscribeSessions,answerUnsubscribeSessions,captureAdmissionReply,drainFacts,drainUntilQuiet,echoedRoles,enqueueLegacyRecord,fenceForClose,gracefulWaitMs,jsonChunks,notAttachedRefusal,presenterPipePath,recordGracefulClose,recordLoopBlockedMs,reopenAfterDrain,socketSink,startMcpPresenterControl,storageUnavailable,takeQueuedInput,withAdmissionReply,withAdmissionRequest}from"./chunk-NOJJLIHF.js";import{DEFAULT_LIMITS,EXTENSION_STATE_PAYLOAD,EXTENSION_STATE_PREFIX,HostMcpRegistry,MANIFEST_FILE,MOVE_BUNDLE_FORMAT,MachineOpError,MoveBundleInvalidError,MovePathTooDeepError,ProviderScope,RESOLUTION_TIMED_OUT,RPC_ERROR_INVALID_MOVE_REQUEST,RPC_ERROR_MOVE_FAILED,RPC_ERROR_MOVE_NOT_RELEASED,RPC_ERROR_SESSION_OPEN_HERE,RpcSessionRegistry,RpcSessionRegistryError,SESSION_BUNDLE_PATH,STATE_ATTEMPT_FIELD,SessionAcceptanceLane,SessionPendingInputs,StructuredLaneUnavailableError,answerWarm,applyAttachedProfile,attachLiveSession,bindToProviderScope,canonicalLoss,code,compactTransportDisabled,createLocalMachineOps,createMovedPathProbe,createRpcConnectionHandler,createWebViewBroker,curatedEnv,detail,error,frozenProfile,isMoveId,isPlainId,isSecurityNoticeState,isSessionFileName,leavesBundle,listedFiles,movedStateDir,multiSessionHostCapabilities,nestsTooDeep,opErrorCode,outgoingStateDir,parseManifest,parseMoveId,parsePlainId,pathExists,prepareOutgoingState,protocolClone,protocolDepthLimitOf,readCodemodeKernelRows,readKeptBundle,readMainThreadHeapBytes,readManifest,readRecordedRepositoryIdentity,readSessionCwd,rebindSessionFile,refreshesSessionActivity,releaseWithinGrace,routingIdOf,runSetModel,runSetPermissionPreset,runWithProviderScope,sealedOutgoingStateDir,sessionIdentity,sessionWorkerDataRegistry,sha256File,sharedPathIdentityResolver,shown,startHostChildReaper,startOpenTimer,structuredLaneEnabled,verifyBundle,withResolutionDeadline,withoutOpenTiming}from"./chunk-MDMF5VUG.js";import"./chunk-2NI6ZIXW.js";import{CONNECTION_ROLE_CAPABILITIES,CONNECTION_ROLE_FIXED,ClientAdmissions,CommandAuthority,CompactReadError,CompactStorageReadError,ConnectionRoles,DELEGATION_INCARNATION_STALE,EffectLedger,FRAGMENT_ENVELOPE_MAX_BYTES,FRAGMENT_MAX_BYTES,TRANSFER_STAGING_MAX_BYTES,TransferStagingError,advertisedCompactCapabilities,answerEffectFromTranscript,answeredUiRequestId,applyContextPatch,beginEffect,buildRpcSessionState,carriesExtensionOwner,clientNamedPreset,commandAuthority,drainSessionEffects,effectAnswer,installSessionEffectSink,isArgs,isEffectBegin,isGrantSelectRequest,latestSessionEffect,machineOpAnswer,machineOpConflict,machineOpMalformed,machineOpUnavailable,nonEmptyText,openReplyPermissionMode,originField,outsideCommand,parseBoundedId,parseMachineOp,parseOwnedOpLookup,parsePermissionPresetName,protocolId,publishedSessionContext,readAuthority,recoveryAgentDir,recoveryCarrier,refused,refusedExtensionUiResponse,registryStatusSource,remoteOriginDeclaration,requestId,roleConnection,rpcCommandShapeError,runSetThinkingLevel,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionDialogRequests,sessionKindError,sessionPromptSurfaceError,sessionRetryFallbackError,sessionRowStatusFields,setSessionRecoveryEpoch,takeRelayExec,withClientPreset}from"./chunk-VHOAN5G5.js";import"./chunk-SFBHMFSI.js";import{RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_ENV,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OWNER_CHANGED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_SESSION_HELD,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-ARIPHUYY.js";import{SessionHeldError,encodedSessionId,errorCode,foreignSessionHolders,liveSessionHolders,readProcessStartMs,serializeByKey,withSessionMoveLock}from"./chunk-PB5JAI6A.js";import"./chunk-PWGJGKPI.js";import"./chunk-R3F4JKFN.js";import{OPEN_AFTER_QUEUED_DEADLINE_MS}from"./chunk-XLJDXEBB.js";import"./chunk-TQHNFP77.js";import{liveToolMediaScope,toolMediaPersister}from"./chunk-WIPTRIAJ.js";import"./chunk-DEUEMEV3.js";import"./chunk-XI6THO4F.js";import{REPOSITORY_IDENTITY_ENTRY_TYPE,SESSION_MOVED,SESSION_MOVED_IN,SESSION_RECLAIMED,SESSION_RELEASED,SessionManager,SessionMovedAwayError,assertValidSessionId,compareRepositoryIdentities,getDefaultSessionDir,getDefaultSessionDirPath,headerSessionId,ownershipStep,parseRepositoryIdentity,readRepositoryIdentity,sessionFileNameId,sessionOwnership}from"./chunk-WZ4IZIR2.js";import{SessionLineSplitter,compactUpdatesEnabled,executionCallKey,loadEntriesFromFileAsync,parseSessionEntryLine}from"./chunk-4R7JSL3B.js";import"./chunk-KQYPGYFV.js";import"./chunk-7AEFFKBD.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-KAQBXCAT.js";import"./chunk-5QZIEDOI.js";import"./chunk-CSCNDNNU.js";import"./chunk-B4V35GCK.js";import"./chunk-3MCOVENJ.js";import"./chunk-3VN5RC6W.js";import"./chunk-4B5JSLLR.js";import"./chunk-UWUN3IBB.js";import"./chunk-MOVB6H22.js";import"./chunk-ETOGZ74E.js";import"./chunk-H4ELF6OO.js";import"./chunk-H4QOEVS5.js";import"./chunk-RNLFZ67U.js";import"./chunk-SOMFLLPD.js";import{readOwnFootprint}from"./chunk-MTQQ2VQH.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,HostIdleHandover,agentDirMismatch,beginHandoverResponse,handoverRefusal,isHandoffBusy,isHostIdle,isTransientDaemonEnvName,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-2EXKZR3F.js";import{ENDPOINT_OWNER_FENCE_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,HAND_SELECTION_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SESSION_RELOCATION_CAPABILITY,classifyRpcMethod,computeRuntimeBuildId,engineBuildIdentity,hostGeneration,hostInstanceId,parseClientCapabilities,pathIdentityResolverStatus,protocolIdentity}from"./chunk-OPUPPWQY.js";import"./chunk-QMRJYMNH.js";import"./chunk-BICMCIHT.js";import{isSpawnedBy}from"./chunk-2C4UHQNO.js";import"./chunk-26UBFF6N.js";import"./chunk-4SA7RJES.js";import{connectAuthenticatedRpcSocket}from"./chunk-E25CXSWH.js";import"./chunk-AT5G5BUI.js";import{presenterBootstrapStream}from"./chunk-7WYJAYHH.js";import{ClientOccupancy,DEFAULT_LOOP_LAG_ERROR_MS,PublicRpcConnection,acceptInternalConnection,armHostWatchdog,closeShieldedEndpoint,consumeHostWatchdogEnv,formatSocketAddress,listen,loopLagErrorMs,prepareSocketPath,resolveSocketPath,scrubHostWatchdogEnv,unlinkOwnedEndpoint}from"./chunk-YNF5MPCP.js";import{reportStartupMilestone}from"./chunk-Q5HNTEVZ.js";import{CHILD_STOP_TIMEOUT_MS,SESSION_PATH_RETRY_AFTER_MS,acquireHostEnsureLock,createEndpointReservations,holderGenerationEnded,hostChildAlive,hostChildDrainRequestFile,ownGenerationDir,parseIdleExitMs,readSessionPathClaims,watchDrainRequest,writeHeartbeat,writeStallEvidence}from"./chunk-O5NRXQZ2.js";import{HOST_DAEMON_DIR_ENV,canonicalSessionPath,createDaemonDirectories,createHostDaemonPaths,generationPaths,parseJson,readFileOrUndefined,readJsonObject,sessionDirectoryRemoved,writeJsonAtomic}from"./chunk-2ZYJNMJZ.js";import{HOST_OCCUPANCY_RECORD,RpcPublicEndpoint,authRecord,isHostOccupancyWatch}from"./chunk-YQHLIPNR.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import"./chunk-2JKFVGLS.js";import"./chunk-KMWFC44T.js";import{subscriptionLimits}from"./chunk-N7EA2JAR.js";import"./chunk-KLAX467B.js";import"./chunk-OPWT74QF.js";import"./chunk-PQGNLQCI.js";import{lockWithLossHandling}from"./chunk-ZZU4J6QP.js";import"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import{external_exports}from"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import{FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,isLockError}from"./chunk-7X72IACK.js";import"./chunk-WHTAR5IS.js";import"./chunk-WHQ2QPP5.js";import"./chunk-SY5HNH77.js";import"./chunk-WB4BUHOH.js";import"./chunk-NJ43NBSP.js";import"./chunk-KDUJCDLM.js";import"./chunk-6APXZK7W.js";import"./chunk-YU2P3CAR.js";import"./chunk-6QQL3SKM.js";import"./chunk-WB6WW5V6.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import{TerminalManager}from"./chunk-QELZQPCJ.js";import"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import{killTrackedDetachedChildren}from"./chunk-T4O3Z7IC.js";import"./chunk-DPNC7S74.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-OBXBNBXE.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-7K42R46I.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-QD45L5SP.js";import"./chunk-WDTJ6JKE.js";import"./chunk-AFDUWYAX.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-GM2CSWYR.js";import"./chunk-E5RLUYMN.js";import"./chunk-ZFIC2DZV.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-6S66JQWD.js";import{privateTablePresent}from"./chunk-GKBPYB3Q.js";import"./chunk-42XRJQM6.js";import"./chunk-REXE2FGU.js";import{PUBLIC_SOCKET_IDENTITY_FILE,readSocketIdentityFile,socketEntryReplaced,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-5XHOHZIR.js";import{SOCKET_HANDSHAKE_TIMEOUT_MS,SOCKET_SECRET_FILE_ENV,authenticateSocket,ensureSocketSecret,socketSecretPath}from"./chunk-HW6AAS3R.js";import{publishHostInstanceId}from"./chunk-IDTQWHTP.js";import{VERSION,envValue,isBunBinary,normalizePath,resolvePath}from"./chunk-QJTWAOBX.js";import"./chunk-ATQFN5HI.js";import"./chunk-4EGD7FGJ.js";import"./chunk-MIKPY3E7.js";import"./chunk-OXNWERO4.js";import{BOOT_INSTANT_TOLERANCE_MS,ownProcessStartedAtMs,processBootAtMs,sameBoot}from"./chunk-44BJPS5I.js";import"./chunk-5GCZFK4X.js";import{processIsLive,processStartTimeMs}from"./chunk-YWBNR4MT.js";import"./chunk-RFFMEA4B.js";import"./chunk-IKOFCODM.js";import{createServer as createServer2}from"node:net";import{rm as rm11}from"node:fs/promises";import{basename as basename2,dirname as dirname8,join as join19}from"node:path";function warmAtBootForPrivateFds(warm,profile,log){warm===void 0||!privateTablePresent()||warm(profile).catch(cause=>{log(`boot extension load failed: ${cause instanceof Error?cause.message:String(cause)}`)})}function relayExecRefusal(record){let object=typeof record=="object"&&record!==null?record:{},type=Reflect.get(object,"type");return refused(requestId(object),typeof type=="string"?type:"parse","delegation_malformed","relayExec must be a positive safe integer")}async function answerDelegation(writer,verdict,record){switch(verdict.kind){case"consumed":return;case"reply":await writer.enqueueControl(verdict.response);return;case"private":writer.writeMcpFormReply(verdict.id,{error:verdict.error});return;case"presenter":writer.handleMcpForm(record)||writer.writeMcpFormReply(verdict.id,{error:"presenter_not_authorized"});return;case"control_info":{let controlEndpoint=writer.mcpPresenterControlEndpoint;await writer.enqueueControl({...verdict.id===void 0?{}:{id:verdict.id},type:"response",command:PRESENTER_CONTROL_INFO_COMMAND,success:!0,data:controlEndpoint===void 0?{}:{controlEndpoint}});return}}}var HostCoreGate=class{constructor(registry,route,hooks){this.inFlight=new Map,this.answering=new Set,this.route=route,this.runtimeBuildId=hooks.runtimeBuildId,this.endpoint=hooks.endpoint,this.handover=hooks.handover===void 0?void 0:new HostIdleHandover({...hooks.handover,isIdle:()=>!(hooks.machineWork?.busy()??!1)&&isHostIdle(registry,this.inFlight),holdNewWork:()=>hooks.machineWork?.hold(),releaseNewWork:()=>hooks.machineWork?.release()})}async intercept(parsed2,deliver){if(!isRecord(parsed2)||parsed2.type!==BEGIN_HANDOVER_COMMAND)return!1;let answering=this.answerBegin(parsed2).then(deliver);this.answering.add(answering);try{await answering}finally{this.answering.delete(answering)}return!0}async answerBegin(parsed2){if(this.handover===void 0)return beginHandoverResponse(parsed2.id,{kind:"refused",reason:"handover_unsupported"});let request=parseBeginHandover(parsed2);if(typeof request=="string")return beginHandoverResponse(parsed2.id,request);let detail2=request.agentDir===void 0||this.endpoint===void 0?void 0:await agentDirMismatch(this.endpoint.socket,request.agentDir,this.endpoint.agentDir);return beginHandoverResponse(parsed2.id,detail2===void 0?await this.handover.begin(request):{kind:"refused",reason:"foreign_agent_dir",detail:detail2})}async answered(){for(;this.answering.size>0;)await Promise.allSettled([...this.answering])}async dispatch(command){let pending=this.handover?.view();if(pending!==void 0&&this.handover?.admits(command.type)===!1)return handoverRefusal(command,pending);let key="sessionId"in command?command.sessionId:void 0;this.inFlight.set(key,(this.inFlight.get(key)??0)+1);let response;try{response=await this.route(command)}finally{let remaining=(this.inFlight.get(key)??1)-1;remaining>0?this.inFlight.set(key,remaining):this.inFlight.delete(key),this.handover?.observe()}return response===void 0?void 0:withHostIdentity(response,this.runtimeBuildId,this.handover?.view())}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var REGISTRATION_LOCK_WAIT_MS=1e4;async function bindRegisteredEndpoint(registration,bind){if(registration.socket.startsWith("\0"))return bind();let release=await acquireHostEnsureLock(registration.socket,REGISTRATION_LOCK_WAIT_MS).catch(cause=>{registration.log(`endpoint ensure lock unavailable, registering without it: ${messageOf(cause)}`)});try{return await createDaemonDirectories(createHostDaemonPaths({socket:registration.socket,agentDir:registration.agentDir})).catch(cause=>registration.log(`endpoint registry record not written: ${messageOf(cause)}`)),await bind()}finally{await release?.()}}function messageOf(cause){return cause instanceof Error?cause.message:String(cause)}var HandoffAnnouncement=class{begin(superseded,identity,publicSocket,log){return this.record=superseded.then(replaced=>({type:"host_superseded",...identity,successor:replaced?{socket:publicSocket}:null}),cause=>{log(`handoff announcement failed: ${String(cause)}`)}),this.record}deliverLate(stream,arrivedBeforeDrain){let record=this.record;return!arrivedBeforeDrain||record===void 0?!1:(record.then(announced=>announced===void 0?stream.destroy():stream.end(`${JSON.stringify(announced)}
`)),!0)}};import{existsSync as existsSync2}from"node:fs";import{readdir as readdir2}from"node:fs/promises";import{createHash}from"node:crypto";import{existsSync,renameSync}from"node:fs";import{mkdir,readdir,readFile,rm,writeFile}from"node:fs/promises";import{join}from"node:path";var CALLER_ENV_NAMES_ENV="SENPI_RPC_CALLER_ENV_NAMES",DEFAULT_CALLER_ENV_NAMES=Object.freeze(["OMOCAT_LANE"]),MAX_SESSION_ENV_ENTRIES=16,MAX_SESSION_ENV_VALUE_LENGTH=4096,ENV_NAME=/^[A-Z_][A-Z0-9_]*$/u,MAX_ECHOED_NAME_LENGTH=64;function callerEnvPassableNames(hostEnv=process.env){let names=new Set(DEFAULT_CALLER_ENV_NAMES);for(let raw of(hostEnv[CALLER_ENV_NAMES_ENV]??"").split(",")){let name=raw.trim();ENV_NAME.test(name)&&!isTransientDaemonEnvName(name)&&names.add(name)}return names}function sessionEnvShapeError(value){if(value===void 0)return;if(!isPlainRecord(value))return"env must be an object of strings.";let entries=Object.entries(value);if(entries.length>MAX_SESSION_ENV_ENTRIES)return`env allows at most ${MAX_SESSION_ENV_ENTRIES} entries.`;for(let[name,entry2]of entries){if(!ENV_NAME.test(name))return`env name "${echoedName(name)}" must match ${ENV_NAME.source}.`;if(typeof entry2!="string")return`env.${echoedName(name)} must be a string.`;if(entry2.includes("\0"))return`env.${echoedName(name)} must not contain NUL.`;if(entry2.length>MAX_SESSION_ENV_VALUE_LENGTH)return`env.${echoedName(name)} must be at most ${MAX_SESSION_ENV_VALUE_LENGTH} characters.`}}function sessionEnvError(value,hostEnv=process.env){let shape=sessionEnvShapeError(value);if(shape!==void 0||!isPlainRecord(value))return shape;let passable=callerEnvPassableNames(hostEnv);for(let name of Object.keys(value))if(!passable.has(name))return`env.${echoedName(name)} is not a caller-passable name (passable: ${[...passable].sort().join(", ")}).`}function inheritedSessionEnv(parent,requested){let merged={...parent,...requested};return Object.keys(merged).length===0?void 0:merged}function echoedName(name){return name.length>MAX_ECHOED_NAME_LENGTH?`${name.slice(0,MAX_ECHOED_NAME_LENGTH)}...`:name}function isPlainRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{hostname}from"node:os";var realWriterProbes={pidAlive:pid=>{try{return process.kill(pid,0),!0}catch(error2){return errorCode(error2)==="EPERM"}},readProcessStartMs,bootAtMs:()=>processBootAtMs(),host:()=>hostname(),self:()=>({pid:process.pid,processStartedAtMs:ownProcessStartedAtMs()})};function currentResidentWriter(probes=realWriterProbes){let self=probes.self();return{host:probes.host(),pid:self.pid,bootAtMs:probes.bootAtMs(),processStartedAtMs:self.processStartedAtMs}}function isResidentWriter(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;let record=value;return typeof record.host=="string"&&Number.isInteger(record.pid)&&typeof record.bootAtMs=="number"&&typeof record.processStartedAtMs=="number"}function residentWriterProbe(probes=realWriterProbes){let gone=new Set,verified=new Set;return async writer=>{let key=`${writer.host}:${writer.pid}:${writer.processStartedAtMs}`;if(gone.has(key))return!1;if(writer.host!==probes.host())return!0;if(!sameBoot(probes.bootAtMs(),writer.bootAtMs)||!probes.pidAlive(writer.pid))return gone.add(key),!1;if(verified.has(key))return!0;let startedAtMs=await probes.readProcessStartMs(writer.pid);return startedAtMs!==void 0&&Math.abs(startedAtMs-writer.processStartedAtMs)>BOOT_INSTANT_TOLERANCE_MS?(gone.add(key),!1):(verified.add(key),!0)}}var recordDir=daemonDir=>join(daemonDir,"handover-parked"),entryFile=(daemonDir,sessionPath)=>join(recordDir(daemonDir),`${createHash("sha256").update(sessionPath,"utf8").digest("hex").slice(0,16)}.json`),mutationChain=Promise.resolve();function enqueueMutation(mutation){let next=mutationChain.then(mutation,mutation);return mutationChain=next.catch(()=>{}),next}function isHandoverParkedEntry(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;let record=value;return typeof record.sessionPath=="string"&&typeof record.retainOnDisconnect=="boolean"&&(record.durableSessionId===void 0||typeof record.durableSessionId=="string")&&(record.cwd===void 0||typeof record.cwd=="string")&&(record.parkedBy===void 0||typeof record.parkedBy=="string")&&(record.residentWriter===void 0||isResidentWriter(record.residentWriter))&&(record.live===void 0||record.live===!0)&&(record.thinkingLevel===void 0||typeof record.thinkingLevel=="string")&&(record.permissionPreset===void 0||typeof record.permissionPreset=="string"&&parsePermissionPresetName(record.permissionPreset)!==void 0)&&sessionPromptSurfaceError(record.promptSurface)===void 0&&sessionBrowserEngineError(record.browserEngine)===void 0&&sessionKindError(record.sessionKind)===void 0&&sessionContextError(record.sessionContext)===void 0&&(record.contextOverlay===void 0||!("refusal"in applyContextPatch(void 0,record.contextOverlay)))&&sessionAutoTitleError(record.autoTitle)===void 0&&sessionRetryFallbackError(record.retryFallback)===void 0&&sessionEnvShapeError(record.sessionEnv)===void 0&&(record.model===void 0||typeof record.model=="object"&&record.model!==null&&typeof record.model.provider=="string"&&typeof record.model.modelId=="string")}async function writeEntryFile(daemonDir,entry2){await mkdir(recordDir(daemonDir),{recursive:!0,mode:448});let file=entryFile(daemonDir,entry2.sessionPath),tmp=`${file}.${process.pid}.${Math.random().toString(16).slice(2,10)}.tmp`;await writeFile(tmp,`${JSON.stringify(entry2,null,2)}
`,{mode:384}),renameSync(tmp,file)}function recordHandoverParkedSession(daemonDir,entry2){return enqueueMutation(()=>writeEntryFile(daemonDir,entry2))}async function readHandoverParkedSessions(daemonDir){let names;try{names=(await readdir(recordDir(daemonDir))).filter(name=>name.endsWith(".json"))}catch{return[]}let entries=[];for(let name of names){let file=join(recordDir(daemonDir),name);try{let parsed2=JSON.parse(await readFile(file,"utf8"));isHandoverParkedEntry(parsed2)&&entries.push(parsed2)}catch(cause){cause instanceof SyntaxError&&(process.stderr.write(`senpi rpc handover-parked entry ${name} is corrupt; dropping it
`),await rm(file,{force:!0}))}}return entries}function clearHandoverParkedSession(daemonDir,sessionPath){return enqueueMutation(()=>rm(entryFile(daemonDir,sessionPath),{force:!0}))}function clearInheritedParkedSession(daemonDir,sessionPath,holder){return enqueueMutation(async()=>{let file=entryFile(daemonDir,sessionPath);if(holder!==void 0){let recorded=await readFile(file,"utf8").then(text4=>JSON.parse(text4),()=>{});if(isHandoverParkedEntry(recorded)&&recorded.parkedBy===holder)return}await rm(file,{force:!0})})}function dropHandoverParkedSessionIfFileGone(daemonDir,sessionPath){return existsSync(sessionPath)?Promise.resolve():clearHandoverParkedSession(daemonDir,sessionPath)}var HANDOVER_PARKED_REOPEN_BUDGET_MS=12e4,HANDOVER_PARKED_REOPEN_POLL_MS=250,HANDOVER_PARKED_REOPEN_MAX_ATTEMPTS=8,HANDOVER_PARKED_REOPEN_QUIET_STREAK=8,HANDOVER_PARKED_PREDECESSOR_POLL_MS=2e3;async function reopenHandoverParkedSessions(open5,agentDir,socket,holder){let paths=createHostDaemonPaths({socket,agentDir}),daemonDir=paths.dir,deadline=Date.now()+HANDOVER_PARKED_REOPEN_BUDGET_MS,reopenAttempts=new Map,heldPolls=new Map,writerAlive=residentWriterProbe(),report=async pending=>{if(holder?.onProgress===void 0)return;let predecessorDraining=await predecessorAlive(paths,holder.hostInstance);holder.onProgress(pending>0||predecessorDraining?{pending,predecessorDraining}:void 0)},done=()=>holder?.onProgress?.(void 0),emptyStreak=0,sawAnyPark=!1,waitedOnPredecessor=!1,finalPass=!1;for(;;){if(holder?.shouldReopen!==void 0&&!holder.shouldReopen())return done();let parked=await inheritedParks(daemonDir,holder,writerAlive);await report(parked.length);for(let entry2 of parked)sawAnyPark=!0,await reopenOne(daemonDir,open5,entry2,reopenAttempts,heldPolls,holder);let remaining=(await inheritedParks(daemonDir,holder,writerAlive)).length;if(await report(remaining),holder?.shouldReopen!==void 0&&!holder.shouldReopen())return done();if(emptyStreak=remaining===0?emptyStreak+1:0,!(sawAnyPark&&emptyStreak>=HANDOVER_PARKED_REOPEN_QUIET_STREAK||Date.now()>=deadline)){await new Promise(resolve4=>setTimeout(resolve4,HANDOVER_PARKED_REOPEN_POLL_MS));continue}if(await predecessorAlive(paths,holder?.hostInstance)){waitedOnPredecessor=!0,await new Promise(resolve4=>setTimeout(resolve4,HANDOVER_PARKED_PREDECESSOR_POLL_MS));continue}if(waitedOnPredecessor&&!finalPass){finalPass=!0;continue}return done()}}async function predecessorAlive(paths,self){for(let instanceId of await readdir2(paths.generationsDir).catch(()=>[])){if(instanceId===self)continue;let generation=generationPaths(paths,instanceId),record=parseJson(await readFileOrUndefined(generation.pidFile).catch(()=>{}));if(typeof record?.pid=="number"&&processIsLive(record.pid)||await hostChildAlive(generation)===!0)return!0}return!1}async function inheritedParks(daemonDir,holder,writerAlive){let parked=await readHandoverParkedSessions(daemonDir),inherited=[];for(let entry2 of parked)entry2.parkedBy!==void 0&&entry2.parkedBy===holder?.hostInstance||entry2.residentWriter!==void 0&&await writerAlive(entry2.residentWriter)||inherited.push(entry2);return inherited}async function reopenOne(daemonDir,open5,entry2,attempts,heldPolls,holder){let taskStatus=entry2.contextOverlay&&Object.hasOwn(entry2.contextOverlay,"task_status")?entry2.contextOverlay.task_status:entry2.sessionContext?.task_status;if(typeof taskStatus=="string"&&["completed","cancelled","error","failed","lost","interrupted"].includes(taskStatus)){await clearHandoverParkedSession(daemonDir,entry2.sessionPath),process.stderr.write(`senpi rpc successor dropped a terminal parked session (${taskStatus}): ${entry2.sessionPath}
`);return}if(await dropHandoverParkedSessionIfFileGone(daemonDir,entry2.sessionPath),!existsSync2(entry2.sessionPath)){process.stderr.write(`senpi rpc successor dropped a parked session whose file is gone: ${entry2.sessionPath}
`);return}try{if(await open5(entry2),holder?.shouldReopen!==void 0&&!holder.shouldReopen())return;await clearInheritedParkedSession(daemonDir,entry2.sessionPath,holder?.hostInstance)}catch(cause){if(cause instanceof RpcSessionRegistryError&&cause.code==="session_path_in_use"){let polls=(heldPolls?.get(entry2.sessionPath)??0)+1;heldPolls?.set(entry2.sessionPath,polls),(polls===1||polls%40===0)&&process.stderr.write(`senpi rpc successor reopen parked session ${entry2.sessionPath} waiting on the holder: ${String(cause)}
`);return}let tried=(attempts.get(entry2.sessionPath)??0)+1;if(attempts.set(entry2.sessionPath,tried),tried>=HANDOVER_PARKED_REOPEN_MAX_ATTEMPTS){process.stderr.write(`senpi rpc successor gave up reopening parked session ${entry2.sessionPath} after ${tried} attempts: ${String(cause)}
`),await clearHandoverParkedSession(daemonDir,entry2.sessionPath);return}process.stderr.write(`senpi rpc successor reopen parked session ${entry2.sessionPath} failed: ${String(cause)}
`)}}import{rm as rm2}from"node:fs/promises";import{createServer}from"node:net";import{dirname,join as join2}from"node:path";async function listenForSuccessor(agentDir,childSocket,generationDir,accept){let path=join2(dirname(childSocket),"route"),endpoint=new RpcPublicEndpoint(agentDir,path),server=createServer(socket=>accept(new PublicRpcConnection(socket,endpoint,!0).stream)),record=join2(generationDir,"route.json"),identity=await listen(server,path),unpublish=()=>unlinkOwnedSocket(path,identity,message=>process.stderr.write(`senpi rpc: ${message}
`));try{await endpoint.publish(),await writeJsonAtomic(record,{socket:path,launchId:endpoint.launchId})}catch(cause){throw server.close(),await endpoint.dispose(),await unpublish(),cause}return async()=>{server.close(),await endpoint.dispose(),await rm2(record,{force:!0}),await unpublish()}}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(env2,overrides={}){return{now:overrides.now??Date.now,idleEvictionMs:overrides.idleEvictionMs??parseIdleExitMs(env2[RPC_SESSION_IDLE_EVICTION_MS_ENV])??DEFAULT_SESSION_IDLE_EVICTION_MS,emptyExitMs:overrides.emptyExitMs??parseIdleExitMs(env2[RPC_HOST_EMPTY_EXIT_MS_ENV])??DEFAULT_HOST_EMPTY_EXIT_MS}}var binding;function hostWatchdogBinding(){return binding??={config:consumeHostWatchdogEnv()},binding.config}function internalHostTransport(configured,secret,endpoint){let bootstrap=getInternalHostBootstrap();scrubHostWatchdogEnv();let watchdogConfig=configured&&{...configured,...bootstrap?.lifetimeFd===void 0?{}:{lifetimeFd:bootstrap.lifetimeFd}},publicEndpoint=endpoint!==void 0&&process.platform!=="win32"&&bootstrap===void 0?new RpcPublicEndpoint(endpoint.agentDir,endpoint.socket):void 0;return{watchdogConfig,admit(socket,accept){bootstrap?acceptInternalConnection(socket,bootstrap.key,{protocolVersion:1,serverVersion:VERSION}).then(hop=>accept(hop,"in_band")).catch(cause=>{process.stderr.write(`senpi rpc host: internal connection refused: ${cause instanceof Error?cause.message:"unknown"}
`),socket.destroy()}):secret?authenticateSocket(socket,secret,()=>accept(void 0,"proven")):publicEndpoint?accept(new PublicRpcConnection(socket,publicEndpoint).stream,"in_band"):accept()},async publish(onFailure){try{await publicEndpoint?.publish()}catch(cause){endpoint?.log(cause instanceof Error?cause.message:String(cause)),await onFailure()}},async dispose(){await publicEndpoint?.dispose().catch(cause=>{endpoint?.log(`endpoint key cleanup failed: ${cause instanceof Error?cause.message:String(cause)}`)})}}}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 parsed2=Number(value.trim());return Number.isFinite(parsed2)&&parsed2>0?parsed2:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.idleReported=!1;let env2=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.readKernels=options.readKernels??readCodemodeKernelRows,this.readMainHeap=options.readMainHeap??readMainThreadHeapBytes,this.warnMb=parsePositiveInteger(env2[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),main:{heapBytes:this.readMainHeap()},kernels:this.readKernels()};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,main:reading.main,kernels:reading.kernels});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)
`))}};var ZERO_SESSION_TRIM_TICK_MS=1e3,ZERO_SESSION_TRIM_MIN_INTERVAL_MS=6e4,DECLINE_TRIM_FLOOR_BYTES=2*1024*1024*1024,DECLINE_TRIM_PAUSE_FACTOR=100,BYTES_PER_MEGABYTE2=1024*1024,ZeroSessionTrimmer=class{constructor(options){this.heldSessions=!1,this.lastSessionCount=0,this.declined=!1,this.zeroPending=!1,this.lastPauseMs=0,this.started=!1,this.options=options,this.now=options.now??Date.now}start(){this.started=!0,this.arm()}stop(){this.started=!1,this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}observe(size){size>0&&(this.heldSessions=!0),size<this.lastSessionCount&&(this.declined=!0),this.lastSessionCount=size,this.arm()}check(){this.evaluate(),this.arm()}owesTick(){return this.pending!==void 0||this.declined||this.zeroPending||this.heldSessions&&this.lastSessionCount===0}arm(){!this.started||this.timer!==void 0||!this.owesTick()||(this.timer=setTimeout(()=>{this.timer=void 0,this.check()},ZERO_SESSION_TRIM_TICK_MS),this.timer.unref?.())}evaluate(){this.pending!==void 0&&this.report(this.pending);let sessions=this.options.sessions();if(sessions<this.lastSessionCount&&(this.declined=!0),this.lastSessionCount=sessions,sessions>0){if(this.heldSessions=!0,this.zeroPending=!1,!this.declined||!this.busyIntervalElapsed())return;this.declined=!1,this.readFootprint().bytes>=DECLINE_TRIM_FLOOR_BYTES&&this.trim(sessions);return}if(this.declined=!1,!(!this.heldSessions&&!this.zeroPending)){if(this.heldSessions=!1,!this.intervalElapsed(ZERO_SESSION_TRIM_MIN_INTERVAL_MS)){this.zeroPending=!0;return}this.zeroPending=!1,this.trim(0)}}intervalElapsed(minimumMs){return this.lastTrimAt===void 0||this.now()-this.lastTrimAt>=minimumMs}busyIntervalElapsed(){return this.intervalElapsed(Math.max(ZERO_SESSION_TRIM_MIN_INTERVAL_MS,this.lastPauseMs*DECLINE_TRIM_PAUSE_FACTOR))}trim(sessions){let beforeBytes=this.readFootprint().bytes,monotonicNow=this.options.monotonicNow??performance.now.bind(performance),startedAt=monotonicNow(),collected=(this.options.collect??collectFully)();this.lastPauseMs=Math.round(monotonicNow()-startedAt),this.lastTrimAt=this.now(),this.pending={beforeBytes,collected,sessions,pauseMs:this.lastPauseMs}}report(pending){this.pending=void 0;let after2=this.readFootprint();this.options.emit({type:"host_trimmed",footprintBeforeMb:Math.round(pending.beforeBytes/BYTES_PER_MEGABYTE2),footprintAfterMb:Math.round(after2.bytes/BYTES_PER_MEGABYTE2),measure:after2.measure,collected:pending.collected,sessions:pending.sessions,pauseMs:pending.pauseMs})}readFootprint(){return(this.options.readFootprint??readOwnFootprint)()}};function collectFully(){let bun=Reflect.get(globalThis,"Bun"),bunGc=typeof bun=="object"&&bun!==null?Reflect.get(bun,"gc"):void 0;if(typeof bunGc=="function")return Reflect.apply(bunGc,bun,[!0]),!0;let nodeGc=Reflect.get(globalThis,"gc");return typeof nodeGc!="function"?!1:(Reflect.apply(nodeGc,globalThis,[]),!0)}import{AsyncLocalStorage}from"node:async_hooks";var attributionStore=new AsyncLocalStorage,sequence=0,openActivities=new Map,activityStartListeners=new Set;function onSessionActivityStart(listener){return activityStartListeners.add(listener),()=>activityStartListeners.delete(listener)}function notifyActivityStarted(){for(let listener of activityStartListeners)listener()}var lastFinished;function runWithSessionAttribution(attribution,task){let mark=++sequence;openActivities.set(mark,attribution),notifyActivityStarted();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(),sessionId=attribution.sessionId??ambient?.sessionId,merged={...sessionId!==void 0?{sessionId}:{},...attribution.tool!==void 0?{tool:attribution.tool}:{},...attribution.job!==void 0?{job:attribution.job}:{}},mark=++sequence;return openActivities.set(mark,merged),notifyActivityStarted(),()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution:merged})}}function describeAttribution(attribution){if(attribution?.sessionId===void 0&&attribution?.tool===void 0&&attribution?.job===void 0)return"no attributed session";let tool=attribution.tool?` tool=${attribution.tool}`:"",job=attribution.job?` job=${attribution.job}`:"";return`sessionId=${attribution.sessionId??"unknown"}${tool}${job}`}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 close2 of spans.values())close2();spans.clear()};return{closeAll,observe:record=>{let parsed2=toolRecord(record);if(parsed2!==void 0){if(parsed2.type==="tool_execution_start"&&parsed2.toolCallId!==void 0){spans.get(parsed2.toolCallId)?.(),spans.set(parsed2.toolCallId,openSessionAttributionSpan({sessionId,tool:parsed2.toolName}));return}if(parsed2.type==="tool_execution_end"&&parsed2.toolCallId!==void 0){spans.get(parsed2.toolCallId)?.(),spans.delete(parsed2.toolCallId);return}(parsed2.type==="agent_settled"||parsed2.type==="agent_idle")&&closeAll()}}}}var LOOP_LAG_WARN_MS_ENV="SENPI_RPC_LOOP_LAG_WARN_MS",DEFAULT_LOOP_LAG_WARN_MS=500,LOOP_LAG_TICK_MS=200,LOOP_LAG_IDLE_TICK_MS=1e3,LOOP_LAG_IDLE_AFTER_MS=2e3,LOOP_LAG_WARN_INTERVAL_MS=1e4,HEARTBEAT_THRESHOLD_FRACTION=5,HEARTBEAT_EARLY_TOLERANCE_MS=LOOP_LAG_TICK_MS/2,BYTES_PER_MB=1024*1024;function describeWindow(processCpuMs,heapDeltaMb){return`cpu=${processCpuMs}ms heap=${heapDeltaMb>=0?"+":""}${heapDeltaMb}MB`}var LoopLagWatchdog=class{constructor(options){this.intervalMs=LOOP_LAG_TICK_MS,this.quietMs=0,this.activityMark=0,this.cpuMicrosAtTick=0,this.heapBytesAtTick=0,this.heartbeatInFlight=!1,this.launchParentPid=process.ppid,this.evidenceFailureLogged=!1;let env2=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.writeHeartbeat=options.writeHeartbeat??writeHeartbeat,this.warnMs=parseIdleExitMs(env2[LOOP_LAG_WARN_MS_ENV])??DEFAULT_LOOP_LAG_WARN_MS,this.errorMs=loopLagErrorMs(env2),this.heartbeatIntervalMs=Math.max(LOOP_LAG_TICK_MS,Math.floor(this.errorMs/HEARTBEAT_THRESHOLD_FRACTION)),this.idleIntervalMs=Math.min(LOOP_LAG_IDLE_TICK_MS,this.heartbeatIntervalMs),this.evidenceDir=ownGenerationDir(env2)}start(){if(this.timer!==void 0)return;this.intervalMs=LOOP_LAG_TICK_MS,this.quietMs=0,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.unsubscribeActivity=onSessionActivityStart(()=>this.wake()),this.schedule()}wake(){this.quietMs=0,!(this.timer===void 0||this.intervalMs===LOOP_LAG_TICK_MS)&&(clearTimeout(this.timer),this.intervalMs=LOOP_LAG_TICK_MS,this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.schedule())}schedule(){this.timer=setTimeout(()=>{this.tick(),this.timer!==void 0&&this.schedule()},this.intervalMs),this.timer.unref?.()}stop(){this.unsubscribeActivity?.(),this.unsubscribeActivity=void 0,this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0,this.expectedTickAt=void 0)}tick(){let now=this.now(),expectedAt=this.expectedTickAt??now,previousMark=this.activityMark;this.activityMark=sessionActivityMark();let quiet=this.activityMark===previousMark&&sessionActivitySince(previousMark)===void 0;this.quietMs=quiet?this.quietMs+this.intervalMs:0,this.intervalMs=this.quietMs>=LOOP_LAG_IDLE_AFTER_MS?this.idleIntervalMs:LOOP_LAG_TICK_MS,this.expectedTickAt=now+this.intervalMs;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){this.beat(now);return}let attribution=sessionActivitySince(previousMark),processCpuMs=Math.round((cpuMicros-previousCpuMicros)/1e3),heapDeltaMb=Math.round((heapBytes-previousHeapBytes)/BYTES_PER_MB);if(driftMs>this.errorMs){let record={type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool,processCpuMs,heapDeltaMb};this.emit(record),this.persistStall(now,record)}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)})
`))}beat(now){if(!this.ownsEvidenceDir()||this.evidenceDir===void 0||this.heartbeatInFlight)return;let due=this.heartbeatIntervalMs-HEARTBEAT_EARLY_TOLERANCE_MS;this.lastHeartbeatAt!==void 0&&now-this.lastHeartbeatAt<due||(this.lastHeartbeatAt=now,this.heartbeatInFlight=!0,this.writeHeartbeat(this.evidenceDir,new Date(now).toISOString()).catch(cause=>this.evidenceFailed(cause)).finally(()=>{this.heartbeatInFlight=!1}))}persistStall(now,record){!this.ownsEvidenceDir()||this.evidenceDir===void 0||writeStallEvidence(this.evidenceDir,{at:new Date(now).toISOString(),driftMs:record.driftMs,processCpuMs:record.processCpuMs??0,heapDeltaMb:record.heapDeltaMb??0,...record.sessionId?{sessionId:record.sessionId}:{},...record.tool?{tool:record.tool}:{}}).catch(cause=>this.evidenceFailed(cause))}ownsEvidenceDir(){return process.ppid===this.launchParentPid}evidenceFailed(cause){this.evidenceFailureLogged||(this.evidenceFailureLogged=!0,this.log(`senpi rpc host stall evidence not written: ${cause instanceof Error?cause.message:String(cause)}
`))}};function startHostObservers(router,writer,options){let loopLag=new LoopLagWatchdog({emit:record=>writer.broadcastHostRecord(record)}),kernels=readCodemodeKernelRows,memory=new HostMemorySampler({emit:record=>writer.broadcastHostRecord(record),sessions:()=>router.sessionCount,onPressure:pressure=>router.setMemoryPressure(pressure),readKernels:kernels,...options.onIdlePressure?{onIdlePressure:options.onIdlePressure}:{}});router.setHostMemoryView({mainHeapBytes:readMainThreadHeapBytes,kernels});let{trim}=options;return loopLag.start(),memory.start(),trim.start(),{stop:()=>{loopLag.stop(),memory.stop(),trim.stop()}}}function createZeroSessionTrim(writer,sessions){return new ZeroSessionTrimmer({emit:record=>writer.broadcastHostRecord(record),sessions})}var HostOccupancyWatch=class{constructor(ports){this.watchers=new Set,this.inFlight=new Map,this.heldOnce=new Set,this.ports=ports}get watching(){return this.watchers.size>0}watch(connection2){this.watchers.add(connection2),this.reported=this.holders(),this.ports.send(connection2,{type:HOST_OCCUPANCY_RECORD,holders:this.reported})}begin(connection2){this.inFlight.set(connection2,(this.inFlight.get(connection2)??0)+1),this.refresh()}end(connection2){this.ports.holdsSessions(connection2)&&this.heldOnce.add(connection2);let left=(this.inFlight.get(connection2)??0)-1;left>0?this.inFlight.set(connection2,left):this.inFlight.delete(connection2),this.refresh()}forget(connection2){this.watchers.delete(connection2),this.inFlight.delete(connection2),this.heldOnce.delete(connection2),this.refresh()}refresh(){if(this.watchers.size===0)return;let holders=this.holders();if(holders!==this.reported){this.reported=holders;for(let watcher of this.watchers)this.ports.send(watcher,{type:HOST_OCCUPANCY_RECORD,holders})}}holders(){let holders=0;for(let connection2 of this.ports.connections()){if(this.watchers.has(connection2)||!this.ports.attached(connection2))continue;let holding=this.ports.holdsSessions(connection2);holding&&this.heldOnce.add(connection2),(holding||this.inFlight.has(connection2)||!this.heldOnce.has(connection2))&&holders++}return holders}};var HOST_EXIT_RESERVE_MS=3e3,HOST_SHUTDOWN_BUDGET_MS=CHILD_STOP_TIMEOUT_MS-HOST_EXIT_RESERVE_MS;async function closeHostConnections(connections,drain,startedAt,log){let deadline=startedAt+HOST_SHUTDOWN_BUDGET_MS;await Promise.all(connections.map(async connection2=>{await beforeDeadline(drain(connection2.id),deadline),await beforeDeadline(connection2.close("host_shutdown"),deadline)}));for(let connection2 of connections)connection2.detach();let force=setTimeout(()=>{let open5=connections.filter(({socket})=>!socket.destroyed);if(open5.length!==0){log(`shutdown budget spent after ${Date.now()-startedAt} ms; destroying ${open5.length} open connection(s)`);for(let{socket}of open5)socket.destroy()}},Math.max(0,deadline-Date.now()));return()=>clearTimeout(force)}function beforeDeadline(work,deadline){let timer,expired=new Promise(resolve4=>{timer=setTimeout(resolve4,Math.max(0,deadline-Date.now()))});return Promise.race([work.then(()=>{}),expired]).finally(()=>clearTimeout(timer))}import{mkdir as mkdir2}from"node:fs/promises";import{join as join4}from"node:path";var MachineOpAnswerCache=class{constructor(options={}){this.slots=new Map,this.now=options.now??Date.now}get size(){return this.expire(),this.slots.size}settled(opId){this.expire();let slot=this.slots.get(opId);return slot!==void 0&&"value"in slot?slot.value:void 0}ownerOf(opId){return this.expire(),this.slots.get(opId)?.owner}answer(opId,owner,run2){this.expire();let slot=this.slots.get(opId);if(slot!==void 0)return"running"in slot?slot.running:Promise.resolve(slot.value);let running=run2().then(value=>(this.slots.delete(opId),this.slots.set(opId,{owner,value,settledAt:this.now()}),this.trim(),value),error2=>{throw this.slots.delete(opId),error2});return this.slots.set(opId,{owner,running}),running}expire(){let oldest=this.now()-864e5;for(let[opId,slot]of this.slots)"settledAt"in slot&&slot.settledAt<oldest&&this.slots.delete(opId)}trim(){for(let[opId,slot]of this.slots){if(this.slots.size<=4096)return;"settledAt"in slot&&this.slots.delete(opId)}}};import{resolve as resolve2}from"node:path";import{lstat,realpath}from"node:fs/promises";import{dirname as dirname2,isAbsolute,join as join3,parse,relative,resolve,sep}from"node:path";async function bounded(operation){try{let value=await withResolutionDeadline(operation);return value===RESOLUTION_TIMED_OUT?{kind:"timeout"}:{kind:"ok",value}}catch{return{kind:"missing"}}}var linkKind=path=>bounded(lstat(path).then(info=>info.isSymbolicLink()?"link":"plain"));async function realPathUnder(base,raw){let root=isAbsolute(raw)?parse(raw).root:base,start=await bounded(realpath(root));if(start.kind!=="ok")return;let cur=start.value,missing=!1;for(let seg of raw.slice(isAbsolute(raw)?root.length:0).split(sep==="\\"?/[\\/]/:"/")){if(seg===""||seg===".")continue;if(/^[A-Za-z]:/.test(seg))return;if(seg===".."){cur=dirname2(cur);continue}let next=join3(cur,seg);if(missing){cur=next;continue}let kind=await linkKind(next);if(kind.kind==="timeout")return;if(kind.kind==="missing"){missing=!0,cur=next;continue}if(kind.value!=="link"){cur=next;continue}let target=await bounded(realpath(next));if(target.kind!=="ok")return;cur=target.value}return cur}var within=(root,target)=>{let rel=relative(root,target);return rel===""||rel!==".."&&!rel.startsWith(`..${sep}`)&&!isAbsolute(rel)};async function spawnPathIn(root,raw,confined){let real=await realPathUnder(root,raw);if(!confined)return real??resolve(root,raw);let realRoot=await realPathUnder(root,".");if(realRoot===void 0||real===void 0||!within(realRoot,real))throw new MachineOpError("policy_denied",`${raw} does not resolve inside ${root}`);return real}var utf8=new TextDecoder,applied=response=>({state:"applied",response}),shellOutcome=r=>r.aborted?{state:"cancelled",error:{code:"aborted",message:"the op was cancelled"}}:r.timedOut?{state:"timed_out",error:{code:"timed_out",message:`timed out after ${r.durationMs} ms`}}:applied({exitCode:r.exitCode,signal:r.signal,stdout:utf8.decode(r.stdout),stderr:utf8.decode(r.stderr),timedOut:!1,durationMs:r.durationMs,truncated:r.stdoutTruncated||r.stderrTruncated}),chunkedReadHint=(error2,limit)=>error2 instanceof MachineOpError&&error2.code==="limit_exceeded"?new MachineOpError("limit_exceeded",`read it in chunks: fs.read {path, offset, limit_bytes} with limit_bytes at most ${limit} (${error2.message})`):error2,runRead=async(req,c)=>{let r=await c.ops.files.read(req,c.ctx).catch(error2=>{throw chunkedReadHint(error2,c.ctx.limits.readMaxBytes)});return applied({path:r.path,bytes:Buffer.from(r.bytes).toString("base64"),size:r.size,offset:r.offset})},runWrite=async(req,c)=>{let r=await c.ops.files.write(req,c.ctx);return applied({path:r.path,writtenBytes:r.writtenBytes})},runEdit=async(req,c)=>{let r=await c.ops.files.edit(req,c.ctx);return applied({path:r.path,replacements:r.replacements,writtenBytes:r.writeResult.writtenBytes})},runGlob=async(req,c)=>{let r=await c.ops.files.glob(req,c.ctx);return applied({entries:r.entries.map(e=>e.path),truncated:r.truncated})},runGrep=async(req,c)=>{let r=await c.ops.files.grep(req,c.ctx);return applied({matches:r.matches.map(m=>({...m})),truncated:r.truncated})},runStat=async(req,c)=>{let r=await c.ops.files.stat(req,c.ctx);return applied({path:r.path,type:r.type,size:r.size,mtimeMs:Math.floor(r.mtimeMs),mode:r.mode})},runList=async(req,c)=>{let r=await c.ops.files.list(req,c.ctx);return applied({path:r.path,entries:r.entries.map(e=>({...e}))})},runShell=async(req,c)=>{let cwd=req.cwd===void 0?c.root:await spawnPathIn(c.root,req.cwd,c.confined);return shellOutcome(await c.ops.process.exec({...req,cwd,env:{...req.env,...c.envOverlay}},c.ctx))},processNotFound=message=>({state:"failed",error:{code:"process_not_found",message}}),runProcessInfo=async(req,c,pidOfHandle)=>{let pid=req.handleId===void 0?req.pid:pidOfHandle(req.handleId);if(req.handleId!==void 0&&pid===void 0)return processNotFound(`no handle ${req.handleId}`);try{return applied({...await c.ops.info.processInfo(pid===void 0?{}:{pid})})}catch(error2){if(error2 instanceof MachineOpError&&error2.code==="not_found")return processNotFound(error2.message);throw error2}},runMeshMessage=async(req,c)=>{let r=await c.ops.info.message(req,c.ctx);return applied({accepted:r.accepted,seq:r.seq,inboxPath:r.inboxPath})};var ArgsError=class extends Error{},bad=detail2=>{throw new ArgsError(detail2)},keys=(a,required,optional=[])=>{for(let k of required)a[k]===void 0&&bad(`${k} is required`);let allowed=new Set([...required,...optional]);for(let k of Object.keys(a))allowed.has(k)||bad(`unknown argument ${k}`)},text=(v,name)=>typeof v=="string"?v:bad(`${name} must be a string`),nonEmpty=(v,name)=>text(v,name).length>0?text(v,name):bad(`${name} must not be empty`),uint=(v,name)=>typeof v=="number"&&Number.isSafeInteger(v)&&v>=0?v:bad(`${name} must be a non-negative integer`),opt=(v,f,name)=>v===void 0?void 0:f(v,name),flag=(v,name)=>typeof v=="boolean"?v:bad(`${name} must be a boolean`),bytes=(v,name)=>v instanceof Uint8Array?v:typeof v=="string"&&/^[A-Za-z0-9+/]*={0,2}$/.test(v)&&v.length%4===0?new Uint8Array(Buffer.from(v,"base64")):bad(`${name} must be bytes or base64`),map=(v,name)=>typeof v=="object"&&v!==null&&!Array.isArray(v)&&!(v instanceof Uint8Array)?v:bad(`${name} must be a map`),env=(v,name)=>{let m=map(v,name);return Object.fromEntries(Object.entries(m).map(([k,x])=>[k,text(x,`${name}.${k}`)]))},some=o=>Object.fromEntries(Object.entries(o).filter(([,v])=>v!==void 0)),readArgs=a=>(keys(a,["path"],["offset","limit_bytes"]),some({path:nonEmpty(a.path,"path"),offset:opt(a.offset,uint,"offset"),limitBytes:opt(a.limit_bytes,uint,"limit_bytes")})),readRangeArgs=a=>{keys(a,["path","offset","length"]);let length=uint(a.length,"length");return length>1048576&&bad("length is above 1048576"),{path:nonEmpty(a.path,"path"),offset:uint(a.offset,"offset"),limitBytes:length}},writeArgs=a=>(keys(a,["path","bytes"],["create_parent_dirs"]),some({path:nonEmpty(a.path,"path"),bytes:bytes(a.bytes,"bytes"),createParentDirs:opt(a.create_parent_dirs,flag,"create_parent_dirs")})),writeRangeArgs=a=>(keys(a,["path","offset","bytes","total"]),{path:nonEmpty(a.path,"path"),offset:uint(a.offset,"offset"),bytes:bytes(a.bytes,"bytes"),total:uint(a.total,"total")}),editArgs=a=>(keys(a,["path","exact","replacement"]),{path:nonEmpty(a.path,"path"),exact:text(a.exact,"exact"),replacement:text(a.replacement,"replacement")}),globArgs=a=>(keys(a,["pattern"],["cwd","limit"]),some({pattern:nonEmpty(a.pattern,"pattern"),cwd:opt(a.cwd,nonEmpty,"cwd"),limit:opt(a.limit,uint,"limit")})),grepArgs=a=>(keys(a,["path","pattern"],["limit"]),some({path:nonEmpty(a.path,"path"),pattern:nonEmpty(a.pattern,"pattern"),limit:opt(a.limit,uint,"limit")})),statArgs=a=>(keys(a,["path"]),{path:nonEmpty(a.path,"path")}),listArgs=a=>(keys(a,["path"]),{path:nonEmpty(a.path,"path")}),shellArgs=a=>{keys(a,["command"],["kind","cwd","env","timeoutMs"]),a.kind!==void 0&&a.kind!=="shell"&&bad("kind must be shell");let timeoutMs=opt(a.timeoutMs,uint,"timeoutMs");return timeoutMs===0&&bad("timeoutMs must be positive"),some({command:nonEmpty(a.command,"command"),cwd:opt(a.cwd,nonEmpty,"cwd"),env:opt(a.env,env,"env"),timeoutMs})},processInfoArgs=a=>(keys(a,[],["pid","handleId"]),a.pid!==void 0&&a.handleId!==void 0&&bad("pid and handleId are exclusive"),some({pid:opt(a.pid,uint,"pid"),handleId:opt(a.handleId,nonEmpty,"handleId")})),meshMessageArgs=a=>(keys(a,["topic","body"]),{topic:nonEmpty(a.topic,"topic"),body:a.body});import{readFile as readFile2}from"node:fs/promises";var OUTPUT_SETTLE_MS=800,RETAINED_OUTPUT_BYTES=1024*1024,MACHINE_LIFECYCLES=["starting","running","waiting_input","exited","killed","lost"],ENDED=["exited","killed","lost"],ended=state=>ENDED.includes(state),PASTE_ON="\x1B[?2004h",PASTE_OFF="\x1B[?2004l";async function foregroundOf(pid){if(pid===void 0||process.platform!=="linux")return null;try{let stat6=await readFile2(`/proc/${pid}/stat`,"utf8"),fields=stat6.slice(stat6.lastIndexOf(")")+2).split(" ");return Number(fields[5])===pid}catch{return null}}function createLiveHandle(init){let session=init.runtime.session,pid=session.pid,listeners=new Set,done=Promise.withResolvers(),early=new Uint8Array(session.rawTail),chunks=early.byteLength===0?[]:[early],retained=early.byteLength,produced=session.rawOutputBytes,state="running",exit=null,killed=!1,quiet=!1,paste=!1,pasteCarry="",cancelSettle=()=>{},emit=e=>{for(let listener of[...listeners])listener(e)},setState=next=>{next!==state&&(state=next,emit({kind:"state",state:next}))},armSettle=()=>{if(cancelSettle(),exit!==null)return;let at=produced;cancelSettle=init.after(OUTPUT_SETTLE_MS,()=>{foregroundOf(pid).then(foreground=>{exit!==null||produced!==at||(quiet=!0,foreground!==!1&&setState("waiting_input"),emit({kind:"idle",foreground}))})})},keep=bytes2=>{for(chunks.push(bytes2),retained+=bytes2.byteLength;retained>RETAINED_OUTPUT_BYTES;){let first=chunks[0]??new Uint8Array(0),cut=retained-RETAINED_OUTPUT_BYTES;first.byteLength<=cut?chunks.shift():chunks[0]=first.subarray(cut),retained-=Math.min(cut,first.byteLength)}},trackPaste=bytes2=>{let seen=pasteCarry+Buffer.from(bytes2).toString("latin1"),on=seen.lastIndexOf(PASTE_ON),off=seen.lastIndexOf(PASTE_OFF);on!==off&&(paste=on>off),pasteCarry=seen.slice(-(PASTE_ON.length-1))},unsubscribeData=session.onData(chunk=>{let bytes2=new Uint8Array(chunk);produced+=bytes2.byteLength,keep(bytes2),trackPaste(bytes2),quiet=!1,state==="waiting_input"&&setState("running"),emit({kind:"output",seq:produced,bytes:bytes2}),armSettle()});return session.onExit(()=>{let result=session.exitResult;exit={exitCode:result?.exitCode??null,signal:result?.signal??null},cancelSettle(),unsubscribeData(),setState(killed?"killed":"exited"),done.resolve()}),armSettle(),{id:init.id,pid,sender:init.sender,startedMs:init.runtime.startedAtMs,state:()=>state,exit:()=>exit,produced:()=>produced,retainedFrom:()=>produced-retained,since:seq=>{let from=produced-retained,all=Buffer.concat(chunks,retained);return new Uint8Array(all.subarray(Math.max(0,Math.min(seq,produced)-from)))},quiet:()=>quiet,bracketedPaste:()=>paste,on:listener=>(listeners.add(listener),()=>{listeners.delete(listener)}),write:bytes2=>{session.write(bytes2)},markKilled:()=>{killed=!0},ended:done.promise,dispose:()=>{cancelSettle(),unsubscribeData(),listeners.clear()}}}var NAMED={enter:"\r",return:"\r",tab:"	",escape:"\x1B",esc:"\x1B",backspace:"\x7F",space:" ",up:"\x1B[A",down:"\x1B[B",right:"\x1B[C",left:"\x1B[D",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~",pageup:"\x1B[5~",pagedown:"\x1B[6~"},encoder=new TextEncoder,encodeKey=key=>{let k=key.toLowerCase(),ctrl=/^ctrl\+(.)$/.exec(k)?.[1];if(ctrl!==void 0){let code2=ctrl.charCodeAt(0);return code2>=64&&code2<=127?Uint8Array.of(code2&31):void 0}let alt=/^alt\+(.+)$/.exec(key)?.[1];if(alt!==void 0){let rest=encodeKey(alt);return rest===void 0?void 0:Uint8Array.of(27,...rest)}let named=NAMED[k];return named!==void 0?encoder.encode(named):[...key].length===1?encoder.encode(key):void 0},PASTE_START=encoder.encode("\x1B[200~"),PASTE_END=encoder.encode("\x1B[201~"),createInputQueues=after2=>{let queues=new Map,gap=()=>new Promise(resolve4=>after2(30,resolve4)),observe=(h,ms)=>{let seen=Promise.withResolvers(),cancel=after2(ms,()=>seen.resolve(!1)),off=h.on(e=>{e.kind==="output"&&seen.resolve(!0),e.kind==="state"&&e.state!=="running"&&e.state!=="waiting_input"&&seen.resolve(!1)});return{seen:seen.promise,stop:()=>{cancel(),off()}}},run2=async(h,input,expectMs)=>{let watch=expectMs===void 0?void 0:observe(h,expectMs),accepted=0,put=bytes2=>{h.write(bytes2),accepted+=bytes2.byteLength};try{if(input.data!==void 0&&input.data.byteLength>0){let bracket=input.paste===!0&&h.bracketedPaste();bracket&&h.write(PASTE_START),put(input.data),bracket&&h.write(PASTE_END)}for(let[i,key]of(input.keys??[]).entries())i>0&&await gap(),put(key);return watch===void 0?{acceptedBytes:accepted}:{acceptedBytes:accepted,observed:await watch.seen}}finally{watch?.stop()}};return{write:(h,input,expectMs)=>{let next=(queues.get(h.id)??Promise.resolve()).then(()=>run2(h,input,expectMs)),settled=next.catch(()=>{});return queues.set(h.id,settled),settled.then(()=>{queues.get(h.id)===settled&&queues.delete(h.id)}),next}}};var YIELD_MIN_MS=250,YIELD_MAX_MS=1e4,EXEC_YIELD_MS=1e3,WRITE_YIELD_MS=250,WAIT_YIELD_MS=1e3,only=(a,allowed,required=[])=>{for(let k of required)a[k]===void 0&&bad(`${k} is required`);for(let k of Object.keys(a))allowed.includes(k)||bad(`unknown argument ${k}`)},text2=(a,k)=>{let v=a[k];if(v!==void 0)return typeof v=="string"&&v.length>0?v:bad(`${k} must be a non-empty string`)},int=(a,k,min,max)=>{let v=a[k];if(v!==void 0)return typeof v=="number"&&Number.isSafeInteger(v)&&v>=min&&v<=max?v:bad(`${k} must be an integer in ${min}..${max}`)},isLifecycle=s=>MACHINE_LIFECYCLES.includes(s),untilOf=v=>{if(v===void 0)return;if(Array.isArray(v)){let states=v.filter(isLifecycle);return states.length===v.length?{states}:bad("until lists an unknown state")}if(typeof v!="object"||v===null)return bad("until must be a list of states or a map");let m=v;only(m,["output","idle"]),m.idle!==void 0&&m.idle!==!0&&bad("until.idle must be true");let output=text2(m,"output");return{...output===void 0?{}:{output},...m.idle===!0?{idle:!0}:{}}},keysOf=v=>{if(v!==void 0)return!Array.isArray(v)||v.length===0?bad("keys must be a non-empty list"):v.map(k=>typeof k=="string"?encodeKey(k)??bad(`unknown key ${k}`):bad("a key must be a string"))},common=a=>(a.lifecycleVersion!==void 0&&a.lifecycleVersion!==1&&bad("lifecycleVersion must be 1"),int(a,"last_seq",0,Number.MAX_SAFE_INTEGER)),execCommandArgs=a=>{common(a),only(a,["cmd","command","workdir","cwd","yield_ms","lifecycleVersion","cols","rows"]),"cmd"in a&&"command"in a&&bad("cmd and command are mutually exclusive"),"workdir"in a&&"cwd"in a&&bad("workdir and cwd are mutually exclusive");let command=text2(a,"cmd")??text2(a,"command")??bad("cmd or command is required"),cwd=text2(a,"workdir")??text2(a,"cwd"),cols=int(a,"cols",2,1e3),rows=int(a,"rows",2,1e3);return{command,yieldMs:int(a,"yield_ms",YIELD_MIN_MS,YIELD_MAX_MS)??EXEC_YIELD_MS,...cwd===void 0?{}:{cwd},...cols===void 0?{}:{cols},...rows===void 0?{}:{rows}}},writeStdinArgs=a=>{let seq=common(a);only(a,["handle_id","data","keys","paste","yield_ms","last_seq","expectActivityMs","lifecycleVersion"],["handle_id"]);let data2=a.data;data2!==void 0&&typeof data2!="string"&&bad("data must be a string"),a.paste!==void 0&&typeof a.paste!="boolean"&&bad("paste must be a boolean");let keys2=keysOf(a.keys),expectMs=int(a,"expectActivityMs",YIELD_MIN_MS,YIELD_MAX_MS);return{handle:text2(a,"handle_id")??bad("handle_id is required"),paste:a.paste===!0,yieldMs:int(a,"yield_ms",YIELD_MIN_MS,YIELD_MAX_MS)??WRITE_YIELD_MS,...typeof data2=="string"?{data:data2}:{},...keys2===void 0?{}:{keys:keys2},...seq===void 0?{}:{lastSeq:seq},...expectMs===void 0?{}:{expectMs}}},waitForCommandArgs=a=>{let seq=common(a);only(a,["handle_id","last_seq","yield_ms","until","lifecycleVersion"],["handle_id"]);let until=untilOf(a.until);return{handle:text2(a,"handle_id")??bad("handle_id is required"),yieldMs:int(a,"yield_ms",YIELD_MIN_MS,YIELD_MAX_MS)??WAIT_YIELD_MS,...seq===void 0?{}:{lastSeq:seq},...until===void 0?{}:{until}}},killTerminalArgs=a=>(common(a),only(a,["handle_id","lifecycleVersion"],["handle_id"]),{handle:text2(a,"handle_id")??bad("handle_id is required")});var decoded=(decode,a)=>{try{return{d:decode(a)}}catch(error2){if(error2 instanceof ArgsError)return{problem:error2.message};throw error2}},entry=(decode,run2,handleArg)=>({...handleArg===void 0?{}:{handleArg},decode:a=>{let r=decoded(decode,a);return"problem"in r?r.problem:void 0},run:(a,call)=>{let r=decoded(decode,a);return"problem"in r?Promise.resolve({state:"refused",error:{code:"malformed",message:r.problem}}):run2(r.d,call)}}),SERVED={"fs.read":entry(readArgs,runRead),"fs.read_range":entry(readRangeArgs,runRead),"fs.write":entry(writeArgs,runWrite),"fs.write_range":entry(writeRangeArgs,runWrite),"fs.edit":entry(editArgs,runEdit),"fs.glob":entry(globArgs,runGlob),"fs.grep":entry(grepArgs,runGrep),"fs.stat":entry(statArgs,runStat),"fs.list":entry(listArgs,runList),shell:entry(shellArgs,runShell),"process.info":entry(processInfoArgs,(d,call)=>runProcessInfo(d,call,call.pidOf),"handleId"),"mesh.message":entry(meshMessageArgs,runMeshMessage),exec_command:entry(execCommandArgs,(d,call)=>call.terminal.execCommand(d,call)),write_stdin:entry(writeStdinArgs,(d,call)=>call.terminal.writeStdin(d,call),"handle_id"),wait_for_command:entry(waitForCommandArgs,(d,call)=>call.terminal.waitForCommand(d,call),"handle_id"),kill_terminal:entry(killTerminalArgs,(d,call)=>call.terminal.killTerminal(d),"handle_id")},servedOp=name=>Object.hasOwn(SERVED,name)?SERVED[name]:void 0;var ERROR_MESSAGE_MAX=1024,OS_REFUSALS=new Set(["EACCES","EPERM","EROFS"]),osRefusal=error2=>{if(!(error2 instanceof Error)||error2 instanceof MachineOpError)return;let errno=Reflect.get(error2,"code");if(typeof errno!="string"||!OS_REFUSALS.has(errno))return;let path=Reflect.get(error2,"path"),syscall=Reflect.get(error2,"syscall"),what=typeof path=="string"?` ${path}`:"";return{code:"os_permission_denied",message:`${errno}: this device's OS user may not ${typeof syscall=="string"?syscall:"access"}${what}. Use a path that user can access, or change its permissions on that device.`.slice(0,ERROR_MESSAGE_MAX)}},anchored=(op,args,root)=>{if(!op.startsWith("fs."))return args;let{path,cwd}=args;return{...args,...typeof path=="string"?{path:resolve2(root,path)}:{},...op==="fs.glob"?{cwd:resolve2(root,typeof cwd=="string"?cwd:".")}:{}}},failure=(error2,confined)=>{let os=confined?void 0:osRefusal(error2);if(os!==void 0)return{state:"failed",error:os};let code2=opErrorCode(error2),message=(error2 instanceof Error?error2.message:String(error2)).slice(0,ERROR_MESSAGE_MAX);return code2==="aborted"?{state:"cancelled",error:{code:code2,message}}:{state:"failed",error:{code:code2,message}}},foreignHandle=(request,handleArg,deps)=>{let handle2=handleArg===void 0?void 0:request.args[handleArg];if(typeof handle2!="string"||request.crossOwner)return;let owner=deps.ownerOf(handle2);return owner!==void 0&&owner!==request.sender?handle2:void 0};async function runMachineOp(request,signal,deps){let entry2=servedOp(request.op);if(entry2===void 0)return{state:"refused",error:{code:"malformed",message:`unknown op ${request.op}`}};let foreign=foreignHandle(request,entry2.handleArg,deps);if(foreign!==void 0)return{state:"failed",error:{code:"not_owner",message:`handle ${foreign} belongs to another sender`}};let{root,confined}=request.scope,call={ctx:{scope:{id:`${request.sender}/omo`,...confined?{root}:{}},principal:{kind:"remote-device",id:request.sender},signal,limits:deps.ops.limits,policy:{}},ops:deps.ops,root,confined,envOverlay:request.envOverlay,sender:request.sender,signal,terminal:deps.terminal,pidOf:deps.pidOf};try{return await entry2.run(confined?request.args:anchored(request.op,request.args,root),call)}catch(error2){return failure(error2,confined)}}import{randomBytes}from"node:crypto";var MACHINE_TERMINALS_MAX=256,MACHINE_TERMINAL_KILL_WAIT_MS=5e3,FINISHED_KEPT=64,RETIRED_KEPT=4096,PTY_COLS=80,PTY_ROWS=24,shell=()=>process.platform==="win32"?[process.env.ComSpec??"cmd.exe","/d","/s","/c"]:[process.env.SHELL||"/bin/sh","-c"],MachineTerminals=class{constructor(after2){this.live=new Map,this.finished=[],this.retired=new Map,this.after=after2}async spawn(ask){this.manager??=new TerminalManager({maxSessions:MACHINE_TERMINALS_MAX,idScope:randomBytes(6).toString("hex")});let[path,...args]=shell(),{id,runtime}=await this.manager.create(path,{command:path,args:[...args,ask.command],cwd:ask.cwd,env:{...curatedEnv(process.env),TERM:"xterm-256color",...ask.env},cols:ask.cols??PTY_COLS,rows:ask.rows??PTY_ROWS}),handle2=createLiveHandle({id,sender:ask.sender,runtime,after:this.after});return this.live.set(id,handle2),handle2.ended.then(()=>this.retire(handle2)),handle2}get(id){return this.live.get(id)}record(id){return this.retired.get(id)}ownerOf(id){return this.live.get(id)?.sender??this.retired.get(id)?.sender}pidOf(id){let h=this.live.get(id);return h===void 0||ended(h.state())?void 0:h.pid}get running(){return[...this.live.values()].filter(h=>!ended(h.state())).length}async kill(h){h.exit()===null&&(h.markKilled(),await this.manager?.stop(h.id),await new Promise(resolve4=>{let cancel=this.after(MACHINE_TERMINAL_KILL_WAIT_MS,resolve4);h.ended.then(()=>{cancel(),resolve4()})}))}async dispose(){let manager=this.manager;this.manager=void 0;for(let h of this.live.values())h.exit()===null&&h.markKilled();await manager?.teardown();for(let h of this.live.values())h.dispose();this.live.clear()}retire(h){for(this.finished.push(h.id);this.finished.length>FINISHED_KEPT;){let id=this.finished.shift(),old=id===void 0?void 0:this.live.get(id);if(old!==void 0){old.dispose(),this.live.delete(old.id),this.retired.set(old.id,{sender:old.sender,state:old.state(),exitCode:old.exit()?.exitCode??null,startedMs:old.startedMs});for(let key of this.retired.keys()){if(this.retired.size<=RETIRED_KEPT)break;this.retired.delete(key)}}}}};import{constants}from"node:os";var WAIT_SEEN_MAX=64*1024,RESULT_OUTPUT_MAX=32*1024,replayGap=(h,lastSeq)=>lastSeq!==void 0&&lastSeq<h.retainedFrom()?`last_seq ${lastSeq} precedes retained output at ${h.retainedFrom()} (${h.retainedFrom()-lastSeq} bytes omitted)`:void 0,immediate=(h,ask)=>{let state=h.state();if(ended(state))return"exited";let until=ask.until;if(until?.states?.includes(state)===!0)return"state";if(until?.idle===!0&&h.quiet())return"idle";if(until===void 0&&ask.lastSeq!==void 0&&ask.lastSeq<h.produced())return"output"},waitForHandle=(h,ask,signal,after2)=>{let now=immediate(h,ask);if(now!==void 0)return Promise.resolve(now);if(signal.aborted)return Promise.reject(new MachineOpError("aborted","the wait was cancelled"));let until=ask.until;return new Promise((resolve4,reject)=>{let decoder=new TextDecoder,seen="",finish=reason=>{cancel(),unsubscribe(),signal.removeEventListener("abort",aborted),resolve4(reason)},aborted=()=>{cancel(),unsubscribe(),reject(new MachineOpError("aborted","the wait was cancelled"))},onEvent=e=>{if(e.kind==="state"){if(ended(e.state))return finish("exited");(until===void 0||until.states?.includes(e.state)===!0)&&finish("state");return}if(e.kind==="idle"){until?.idle===!0&&finish("idle");return}until?.output!==void 0&&(seen=(seen+decoder.decode(e.bytes,{stream:!0})).slice(-WAIT_SEEN_MAX),seen.includes(until.output)&&finish("matched"))},unsubscribe=h.on(onEvent),cancel=after2(ask.yieldMs,()=>finish("timeout"));signal.addEventListener("abort",aborted,{once:!0})})},exitCodeOf=exit=>{if(exit.exitCode!==null)return exit.exitCode;let signal=exit.signal;if(signal===null)return-1;let number=constants.signals[signal.startsWith("SIG")?signal:`SIG${signal}`]??(/^\d+$/.test(signal)?Number(signal):void 0);return number===void 0?-1:128+number},lifecycleOf=(state,exit,lostReason="exit_status_unavailable")=>{switch(state){case"starting":case"running":case"waiting_input":return{state,stdinOpen:!0,outputClosed:!1};case"exited":return{state,exitCode:exitCodeOf(exit??{exitCode:null,signal:null}),stdinOpen:!1,outputClosed:!0};case"killed":return{state,stdinOpen:!1,outputClosed:!0};case"lost":return{state,reason:lostReason,stdinOpen:!1,outputClosed:!0}}},terminalResult=(h,fromSeq,nowMs,extra={},window="oldest")=>{let retained=Math.min(Math.max(fromSeq,h.retainedFrom()),h.produced()),span=h.since(retained),skip=window==="newest"?Math.max(0,span.byteLength-RESULT_OUTPUT_MAX):0,boundaryLimit=skip+3;for(;skip>0&&skip<boundaryLimit&&skip<span.byteLength&&((span[skip]??0)&192)===128;)skip+=1;let from=retained+skip,all=span.subarray(skip),bytes2=all.subarray(0,RESULT_OUTPUT_MAX),state=h.state(),lifecycle=lifecycleOf(state,h.exit());return{handleId:h.id,output:new TextDecoder().decode(bytes2),state:ended(state)?"completed":"running",lifecycle,lastSeq:from+bytes2.byteLength,truncated:from>fromSeq||bytes2.byteLength<all.byteLength,omittedBytes:Math.max(0,from-fromSeq),totalBytes:h.produced(),...lifecycle.state==="exited"?{exitCode:lifecycle.exitCode}:{},startedAtMs:h.startedMs,elapsedMs:Math.max(0,nowMs-h.startedMs),...extra}};var fail=(code2,message)=>({state:"failed",error:{code:code2,message}}),applied2=response=>({state:"applied",response}),createTerminalOps=(terminals,after2)=>{let input=createInputQueues(after2),now=()=>Date.now(),gone=id=>{let r=terminals.record(id);return r===void 0?fail("unknown_handle",`no handle ${id} on this host`):applied2({handleId:id,output:"",state:ended(r.state)?"completed":"running",lifecycle:lifecycleOf(r.state,{exitCode:r.exitCode,signal:null},"agent_restarted"),lastSeq:0,truncated:!1,omittedBytes:0,totalBytes:0,...r.exitCode===null?{}:{exitCode:r.exitCode},startedAtMs:r.startedMs,reason:"exited"})};return{execCommand:async(d,call)=>{let cwd=d.cwd===void 0?call.root:await spawnPathIn(call.root,d.cwd,call.confined),h=await terminals.spawn({sender:call.sender,command:d.command,cwd,env:call.envOverlay,...d.cols===void 0?{}:{cols:d.cols},...d.rows===void 0?{}:{rows:d.rows}}),reason=await waitForHandle(h,{yieldMs:d.yieldMs,until:{states:ENDED}},call.signal,after2).catch(async error2=>{throw await terminals.kill(h),error2});return applied2(terminalResult(h,0,now(),{pid:h.pid,reason}))},writeStdin:async(d,call)=>{let h=terminals.get(d.handle);if(h===void 0)return gone(d.handle);if(ended(h.state()))return fail("stdin_closed",`handle ${d.handle} has ended`);let before=h.produced(),effect=await input.write(h,{...d.data===void 0?{}:{data:new TextEncoder().encode(d.data)},...d.keys===void 0?{}:{keys:d.keys},paste:d.paste},d.expectMs),reason=await waitForHandle(h,{yieldMs:d.yieldMs},call.signal,after2),observed=effect.observed??h.produced()>before;return applied2(terminalResult(h,d.lastSeq??before,now(),{stdinEffect:{acceptedBytes:effect.acceptedBytes,observed},reason}))},waitForCommand:async(d,call)=>{let h=terminals.get(d.handle);if(h===void 0)return gone(d.handle);let gap=replayGap(h,d.lastSeq);if(gap!==void 0)return fail("replay_gap",gap);let reason=await waitForHandle(h,{yieldMs:d.yieldMs,...d.lastSeq===void 0?{}:{lastSeq:d.lastSeq},...d.until===void 0?{}:{until:d.until}},call.signal,after2);return applied2(terminalResult(h,d.lastSeq??0,now(),{reason},d.lastSeq===void 0?"newest":"oldest"))},killTerminal:async d=>{let h=terminals.get(d.handle);if(h===void 0){let r=terminals.record(d.handle);return r===void 0?fail("unknown_handle",`no handle ${d.handle} on this host`):applied2({handleId:d.handle,state:"task-failed",reason:"killed",lifecycle:lifecycleOf(r.state,{exitCode:r.exitCode,signal:null},"agent_restarted")})}return await terminals.kill(h),applied2({handleId:h.id,state:"task-failed",reason:"killed",lifecycle:lifecycleOf(h.state(),h.exit())})}}};var RELAY_HOST_READ_MAX_BYTES=16772963,NO_PTY_HOLDER={spawn:()=>Promise.reject(new MachineOpError("invalid_argument","terminal spawn is not offered by this host")),close:async()=>{}},after=(ms,fn)=>{let timer=setTimeout(fn,ms);return()=>clearTimeout(timer)},MachineOpHandler=class{constructor(options){this.terminals=new MachineTerminals(after),this.terminalOps=createTerminalOps(this.terminals,after),this.cache=new MachineOpAnswerCache,this.stopping=new AbortController,this.running=new Map,this.held=!1,this.stateDir=options.agentDir}async answer(command,record,id){let fields=isArgs(record)?record:{};switch(command){case"machine_op":{let request=parseMachineOp(fields);if(typeof request=="string")return machineOpMalformed(id,command,request);if(this.held)return machineOpUnavailable(id,"the engine is handing over or shutting down; retry the op");let owner=this.cache.ownerOf(request.opId);if(owner!==void 0&&owner!==request.sender)return machineOpConflict(id,command);try{let outcome=await this.cache.answer(request.opId,request.sender,()=>this.run(request));return machineOpAnswer(id,command,outcome)}catch(cause){let detail2=cause instanceof Error?cause.message:String(cause);return machineOpUnavailable(id,`the engine's machine state could not be prepared: ${detail2}`)}}case"machine_op_cancel":{let lookup=parseOwnedOpLookup(fields);if(typeof lookup=="string")return machineOpMalformed(id,command,lookup);let running=this.running.get(lookup.opId);if(running!==void 0&&running.sender!==lookup.sender&&!lookup.crossOwner)return machineOpConflict(id,command);let cancelled=running!==void 0&&!running.abort.signal.aborted;return running?.abort.abort(),machineOpAnswer(id,command,{cancelled})}case"machine_op_result":{let lookup=parseOwnedOpLookup(fields);if(typeof lookup=="string")return machineOpMalformed(id,command,lookup);let owner=this.cache.ownerOf(lookup.opId);if(owner!==void 0&&owner!==lookup.sender&&!lookup.crossOwner)return machineOpConflict(id,command);let outcome=this.cache.settled(lookup.opId);return machineOpAnswer(id,command,outcome===void 0?{known:!1}:{known:!0,outcome})}case"machine_op_owner":{let handleId=nonEmptyText(fields,"handle_id");if(handleId===void 0)return machineOpMalformed(id,command,"handle_id must be a non-empty string");let sender=this.terminals.ownerOf(handleId);return machineOpAnswer(id,command,sender===void 0?{}:{sender})}case"machine_op_health":return machineOpAnswer(id,command,{ok:!0,terminals:this.terminals.running,cache:this.cache.size,version:VERSION})}}busy(){return this.running.size>0||this.terminals.running>0}hold(){this.held=!0}release(){this.held=!1}async dispose(){this.stopping.abort(),await this.terminals.dispose()}async run(request){let cancel=new AbortController;this.running.set(request.opId,{abort:cancel,sender:request.sender});let deadline=request.deadlineMs===void 0?[]:[AbortSignal.timeout(Math.max(0,request.deadlineMs-Date.now()))];try{return await runMachineOp(request,AbortSignal.any([this.stopping.signal,cancel.signal,...deadline]),{ops:await this.machineOps(),terminal:this.terminalOps,pidOf:handleId=>this.terminals.pidOf(handleId),ownerOf:handleId=>this.terminals.ownerOf(handleId)})}finally{this.running.delete(request.opId)}}machineOps(){return this.ops??=mkdir2(join4(this.stateDir,"machine"),{recursive:!0,mode:448}).then(()=>createLocalMachineOps({stateDir:this.stateDir,holder:NO_PTY_HOLDER,limits:{...DEFAULT_LIMITS,readMaxBytes:RELAY_HOST_READ_MAX_BYTES}}),cause=>{throw this.ops=void 0,cause}),this.ops}};function withOpenRetention(command,delegated,machineOwned){let retainedAgainst=asked=>delegated?asked!==!0:machineOwned&&asked===void 0;if(command.type==="open_session"||command.type==="claim_session")return retainedAgainst(command.retain_on_disconnect)?{...command,retain_on_disconnect:!0}:command;if(command.type!=="move_session"||command.op!=="import")return command;let{open:open5}=command,fields=open5===!0?{}:typeof open5=="object"&&open5!==null&&!Array.isArray(open5)?open5:void 0;return fields!==void 0&&retainedAgainst(fields.retain_on_disconnect)?{...command,open:{...fields,retain_on_disconnect:!0}}:command}function holdDrainedTurns(host){for(let{sessionId,status}of host.registry.list()){if(status!=="open"||host.drainHeldSessions.has(sessionId))continue;let session=host.registry.peek(sessionId)?.runtime?.session;if(session!==void 0){host.drainHeldSessions.add(sessionId);try{session.holdAutomaticTurns()}catch(cause){process.stderr.write(`senpi rpc handoff could not hold automatic turns of ${sessionId}: ${String(cause)}
`)}}}}var THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"],thinkingLevelOf=value=>THINKING_LEVELS.find(level=>level===value);function parkedEntryFromProfile(session,profile,hostContextKeys){let clientContext=profile?.sessionContext===void 0?void 0:Object.fromEntries(Object.entries(profile.sessionContext).filter(([key])=>!hostContextKeys.includes(key)));return{sessionPath:session.sessionPath,...session.durableSessionId!==void 0?{durableSessionId:session.durableSessionId}:{},retainOnDisconnect:!0,...session.contextOverlay!==void 0?{contextOverlay:session.contextOverlay}:{},...profile?.cwd!==void 0?{cwd:profile.cwd}:{},...profile?.creationModel!==void 0?{model:profile.creationModel}:{},...profile?.initialThinkingLevel!==void 0?{thinkingLevel:profile.initialThinkingLevel}:{},...profile?.permissionPreset!==void 0?{permissionPreset:profile.permissionPreset}:{},...profile?.promptSurface!==void 0?{promptSurface:profile.promptSurface}:{},...profile?.browserEngine!==void 0?{browserEngine:profile.browserEngine}:{},...profile?.sessionKind!==void 0?{sessionKind:profile.sessionKind}:{},...clientContext!==void 0&&Object.keys(clientContext).length>0?{sessionContext:clientContext}:{},...profile?.autoTitle!==void 0?{autoTitle:profile.autoTitle}:{},...profile?.retryFallback!==void 0?{retryFallback:profile.retryFallback}:{},...profile?.sessionEnv!==void 0?{sessionEnv:profile.sessionEnv}:{}}}function parkedOpenCommand(entry2){let thinkingLevel=thinkingLevelOf(entry2.thinkingLevel);return entry2.thinkingLevel!==void 0&&thinkingLevel===void 0&&process.stderr.write(`senpi rpc successor reopens ${entry2.sessionPath} without its unknown thinking level "${entry2.thinkingLevel}"
`),{type:"open_session",sessionPath:entry2.sessionPath,...entry2.cwd!==void 0?{cwd:entry2.cwd}:{},...entry2.durableSessionId!==void 0?{durableSessionId:entry2.durableSessionId}:{},...entry2.model!==void 0?{provider:entry2.model.provider,modelId:entry2.model.modelId}:{},...thinkingLevel!==void 0?{thinkingLevel}:{},...entry2.permissionPreset!==void 0?{permissionPreset:entry2.permissionPreset}:{},...entry2.promptSurface!==void 0?{promptSurface:entry2.promptSurface}:{},...entry2.browserEngine!==void 0?{browserEngine:entry2.browserEngine}:{},...entry2.sessionKind!==void 0?{kind:entry2.sessionKind}:{},...entry2.sessionContext!==void 0?{context:entry2.sessionContext}:{},...entry2.autoTitle!==void 0?{auto_title:entry2.autoTitle}:{},...entry2.retryFallback!==void 0?{retryFallback:entry2.retryFallback}:{},...entry2.sessionEnv!==void 0?{env:{...entry2.sessionEnv}}:{},retain_on_disconnect:entry2.retainOnDisconnect}}var reportRecordFailure=sessionId=>cause=>{process.stderr.write(`senpi rpc retained session record ${sessionId} failed: ${String(cause)}
`)};async function recordRetainedSession(host,retained,sessionPath,resident,live=resident){let dir=host.handoverParkedDir;if(dir===void 0)return;let previous=retained.recordedPath;retained.recordedPath=sessionPath,previous!==void 0&&previous!==sessionPath&&await clearHandoverParkedSession(dir,previous);let durableSessionId=retained.runtime?.session.sessionId??retained.durableSessionId;await recordHandoverParkedSession(dir,{...parkedEntryFromProfile({sessionPath,contextOverlay:retained.contextOverlay,...durableSessionId!==void 0?{durableSessionId}:{}},retained.profile,Object.keys(host.defaults.hostContext??{})),parkedBy:host.defaults.hostContext?.host_instance??hostInstanceId(),...resident?{residentWriter:currentResidentWriter()}:{},...live?{live:!0}:{}})}var currentPath=entry2=>entry2.runtime?.session.sessionFile??entry2.sessionPath;async function syncRetainedRecord(host,sessionId,requestedPath){let dir=host.handoverParkedDir;if(dir===void 0)return;let entry2=host.registry.peek(sessionId),sessionPath=entry2===void 0?void 0:currentPath(entry2);entry2?.retainOnDisconnect===!0&&sessionPath!==void 0&&(await recordRetainedSession(host,entry2,sessionPath,!0).catch(reportRecordFailure(sessionId)),requestedPath===void 0||requestedPath===sessionPath)||requestedPath!==void 0&&await clearHandoverParkedSession(dir,requestedPath).catch(()=>{})}function followRetainedRecord(host,sessionId){if(host.handoverParkedDir===void 0)return;let entry2=host.registry.peek(sessionId);if(entry2?.retainOnDisconnect!==!0||entry2.recordedPath===void 0||entry2.state!=="open")return;let sessionPath=currentPath(entry2);sessionPath===void 0||sessionPath===entry2.recordedPath||recordRetainedSession(host,entry2,sessionPath,!0).catch(reportRecordFailure(sessionId))}async function clearRetainedRecord(host,entry2){let dir=host.handoverParkedDir;if(dir===void 0||entry2===void 0)return;let keys2=new Set([entry2.recordedPath,entry2.sessionPath,entry2.runtime?.session.sessionFile]);entry2.recordedPath=void 0;for(let key of keys2)key!==void 0&&await clearHandoverParkedSession(dir,key).catch(()=>{})}var DETACHED_RETIREMENT_GRACE_MS=5e3;function selectSweepEvictions(registry,now,idleEvictionMs,hasPendingRequest=()=>!1){let idle=[],orphaned=[];for(let{sessionId,status,sessionPath}of registry.list()){if(status!=="open")continue;let entry2=registry.peek(sessionId);if(!entry2)continue;if(entry2.attachments===0&&sessionPath!==void 0&&sessionDirectoryRemoved(sessionPath)){orphaned.push(sessionId);continue}if(!Number.isFinite(idleEvictionMs)||hasPendingRequest(sessionId))continue;let session=entry2.runtime?.session;if(entry2.worker?.busy||session?.isSessionBusy){entry2.lastCommandAt=now;continue}if(entry2.attachments>0){now-entry2.lastCommandAt>=idleEvictionMs&&idle.push(sessionId);continue}if(entry2.kind==="worker"&&entry2.retainOnDisconnect&&session?.sessionManager.isTranscriptFlushed()){if(session.pendingMessageCount>0||session.externalAdmission.list().pending.length>0)continue;if(entry2.detachedAt!==void 0){if(now-entry2.detachedAt<DETACHED_RETIREMENT_GRACE_MS)continue;idle.push(sessionId);continue}}now-entry2.lastCommandAt>=idleEvictionMs&&idle.push(sessionId)}return{idle,orphaned}}var DRAIN_SWEEP_MS=50;function beginDrain(host){host.draining=!0,host.parks.stop().catch(cause=>{process.stderr.write(`senpi rpc park close failed during drain: ${String(cause)}
`)}).then(()=>sweepDrain(host)).catch(cause=>{process.stderr.write(`senpi rpc drain sweep failed after park close: ${String(cause)}
`)}),stopSweep(host),host.drainTimer===void 0&&!host.drainExitRequested&&(host.drainTimer=setInterval(()=>sweepDrain(host),DRAIN_SWEEP_MS),host.drainTimer.unref?.()),sweepDrain(host)}function sweepDrain(host){if(host.activeRequests.has(void 0))return;let verdicts=readDrainVerdicts(host.registry,sessionId=>host.activeRequests.has(sessionId));if(verdicts){holdDrainedTurns(host);for(let sessionId of verdicts.gone)parkForHandoff(host,sessionId,"session_dir_removed");for(let sessionId of verdicts.park)parkForHandoff(host,sessionId,"handoff_parked");host.registry.size>0||host.parks.size>0||host.handoffParks>0||host.finalizations.size>0||(host.drainTimer!==void 0&&(clearInterval(host.drainTimer),host.drainTimer=void 0),stopSweep(host),!host.drainExitRequested&&(host.drainExitRequested=!0,host.onEmptyExit?.()))}}function parkForHandoff(host,sessionId,reason){host.handoffClosed.add(sessionId),host.handoffParks++,evictIdleSession(host,sessionId,reason).catch(cause=>{process.stderr.write(`senpi rpc handoff park ${sessionId} failed: ${String(cause)}
`)}).finally(()=>{host.handoffParks--,sweepDrain(host)})}function sweepIdleSessions(host){let now=host.idleNow(),idleEvictionMs=host.memoryPressure?host.idleEvictionMs/2:host.idleEvictionMs,verdicts=selectSweepEvictions(host.registry,now,idleEvictionMs,sessionId=>host.activeRequests.has(sessionId)||(host.bindings.get(sessionId)?.pendingPrompts?.().length??0)>0);for(let sessionId of verdicts.orphaned)evictIdleSession(host,sessionId,"session_dir_removed");for(let sessionId of verdicts.idle)evictIdleSession(host,sessionId);Number.isFinite(host.emptyExitMs)&&(host.registry.size===0&&!host.inheritedHandover?.predecessorDraining&&(host.canExitWhenEmpty?.()??!0)?host.emptySince===void 0?host.emptySince=now:now-host.emptySince>=host.emptyExitMs&&(stopSweep(host),host.onEmptyExit?.()):host.emptySince=void 0)}async function evictIdleSession(host,sessionId,reason){let retained=host.registry.peek(sessionId),parkedPath=retained?.retainOnDisconnect===!0||reason==="handoff_parked"?retained?.sessionPath:void 0,handoff=reason==="handoff_parked"||reason==="session_dir_removed"&&host.draining,owners=handoff?[...host.sessionsByConnection].filter(([,owned])=>owned.has(sessionId)).map(([connection2])=>connection2):[],claim=tryClaimClose(host,sessionId,{drainAttachments:!0});if(!claim)return;host.handoverParkedDir!==void 0&&parkedPath!==void 0&&retained?.retainOnDisconnect===!0&&retained.sessionPath!==void 0&&await recordRetainedSession(host,retained,retained.sessionPath,!1,reason==="handoff_parked").catch(cause=>{process.stderr.write(`senpi rpc handover park record ${sessionId} failed: ${String(cause)}
`)});let binding2=host.bindings.get(sessionId);binding2?.cancelPendingExtensionUiRequests?.(),handoff||forgetSessionOwnership(host,sessionId),claim.finalizer?await finalizeClose(host,sessionId,binding2,()=>parkedPath!==void 0&&reason===void 0?host.writer.parkSession(sessionId,parkedPath,"idle"):host.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},reason??"idle_evicted",reason==="handoff_parked"?parkedPath:void 0)):await host.finalizations.get(sessionId)?.promise,handoff&&(forgetSessionOwnership(host,sessionId),await host.onHandoffParked?.(owners.filter(connection2=>!host.sessionsByConnection.has(connection2)))),host.writer.forgetSession(sessionId)}function stopSweep(host){host.sweepTimer!==void 0&&(clearInterval(host.sweepTimer),host.sweepTimer=void 0)}var HOST_SHUTDOWN_ABORT_BOUND_MS=1e4;async function abortForHostShutdownWithin(sessionId,entry2){let aborting=(async()=>{await entry2?.runtime?.session.abortForHostShutdown()})().catch(cause=>{process.stderr.write(`senpi rpc host shutdown abort ${sessionId} failed: ${String(cause)}
`)}),timer,bound=new Promise(resolve4=>{timer=setTimeout(resolve4,HOST_SHUTDOWN_ABORT_BOUND_MS),timer.unref?.()});try{await Promise.race([aborting,bound])}finally{clearTimeout(timer)}}function claimClose(host,sessionId,options){let finalizer=!0,onRole=isFinalizer=>{finalizer=isFinalizer,isFinalizer&&!host.finalizations.has(sessionId)&&host.finalizations.set(sessionId,createFinalization())},entry2=host.registry.beginClose(sessionId,onRole,{detach:options.detach});for(;options.drainAttachments&&entry2.state==="open";)entry2=host.registry.beginClose(sessionId,onRole);return{finalizer:finalizer&&entry2.state==="closing"}}function tryClaimClose(host,sessionId,options){try{return claimClose(host,sessionId,options)}catch{return}}async function close(host,command){let response={id:command.id,type:"response",command:"close_session",success:!0,data:{}},owner=host.writer.currentConnection();if(owner!==void 0&&host.sessionsByConnection.get(owner)?.has(command.sessionId)!==!0)return error(command.id,"close_session",RPC_ERROR_UNKNOWN_SESSION);let reply=host.writer.reserveCloseResponse(command.sessionId,response);if(!reply)return;let claim;try{claim=claimClose(host,command.sessionId,{drainAttachments:!1})}catch(cause){return reply.release(),error(command.id,"close_session",code(cause))}try{owner!==void 0&&releaseOwnerAttachment(host,owner,command.sessionId),claim.finalizer?(host.handoverParkedDir!==void 0&&await clearRetainedRecord(host,host.registry.peek(command.sessionId)),await finalizeClose(host,command.sessionId,host.bindings.get(command.sessionId),()=>reply.complete(!0,"client_close"))):(host.writer.status.publish(command.sessionId,"detach","client"),await host.finalizations.get(command.sessionId)?.promise,reply.complete(!1));return}finally{reply.release()}}async function finalizeClose(host,sessionId,binding2,terminal){let finalization=host.finalizations.get(sessionId)??createFinalization();host.finalizations.set(sessionId,finalization);try{try{await disposeWithinGrace(binding2,host.registry.closeGraceMs,sessionId)}catch(cause){process.stderr.write(`senpi rpc binding dispose for session ${sessionId} failed: ${String(cause)}
`)}host.bindings.delete(sessionId);try{await host.registry.closeMarked(sessionId)}catch(cause){process.stderr.write(`senpi rpc close for session ${sessionId} failed: ${String(cause)}
`)}await host.registry.peek(sessionId)?.closeCompletion,terminal?.()}finally{finalization.resolve(),host.finalizations.delete(sessionId)}}async function disposeWithinGrace(binding2,graceMs,sessionId){if(binding2===void 0)return;let timer,late=new Promise(resolve4=>{timer=setTimeout(()=>resolve4("late"),graceMs)}),disposed=binding2.dispose().then(()=>"disposed");try{if(await Promise.race([disposed,late])==="disposed")return}finally{clearTimeout(timer)}process.stderr.write(`senpi rpc binding dispose for session ${sessionId} did not settle within ${graceMs} ms; closing anyway
`),disposed.catch(cause=>process.stderr.write(`senpi rpc binding dispose for session ${sessionId} failed: ${String(cause)}
`))}function createFinalization(){let resolveFinalization;return{promise:new Promise(resolve4=>{resolveFinalization=resolve4}),resolve:()=>resolveFinalization?.()}}async function tearDownReleased(host,sessionId,sessionPath){let claim=tryClaimClose(host,sessionId,{drainAttachments:!0});if(!claim)return!1;let binding2=host.bindings.get(sessionId);return binding2?.cancelPendingExtensionUiRequests?.(),forgetSessionOwnership(host,sessionId),claim.finalizer?(host.handoverParkedDir!==void 0&&await clearRetainedRecord(host,host.registry.peek(sessionId)),await finalizeClose(host,sessionId,binding2,()=>host.writer.releaseSession(sessionId,sessionPath))):await host.finalizations.get(sessionId)?.promise,host.writer.forgetSession(sessionId),!0}async function tearDownUnloaded(host,sessionId,sessionPath){let unloaded=host.registry.peek(sessionId),claim=tryClaimClose(host,sessionId,{drainAttachments:!0});if(!claim)return!1;claim.finalizer&&unloaded?.retainOnDisconnect===!0&&unloaded.recordedPath!==void 0&&await recordRetainedSession(host,unloaded,unloaded.recordedPath,!1,!1).catch(cause=>{process.stderr.write(`senpi rpc unload park record ${sessionId} failed: ${String(cause)}
`)});let binding2=host.bindings.get(sessionId);return binding2?.cancelPendingExtensionUiRequests?.(),forgetSessionOwnership(host,sessionId),claim.finalizer?await finalizeClose(host,sessionId,binding2,()=>host.writer.parkSession(sessionId,sessionPath,"unloaded")):await host.finalizations.get(sessionId)?.promise,host.writer.forgetSession(sessionId),!0}async function dispose(host){host.stopLimitBroadcast(),host.drainExitRequested=!0,stopSweep(host),host.drainTimer!==void 0&&clearInterval(host.drainTimer),await host.parks.stop(),host.admissions&&await host.admissions.dispose(),await Promise.all([...host.bindings.entries()].map(async([sessionId,binding2])=>{let entry2=host.registry.peek(sessionId),parkedPath=host.handoverParkedDir!==void 0&&entry2?.retainOnDisconnect===!0?entry2.runtime?.session.sessionFile??entry2.sessionPath:void 0,claim=tryClaimClose(host,sessionId,{drainAttachments:!0});claim&&(claim.finalizer?(await abortForHostShutdownWithin(sessionId,entry2),entry2!==void 0&&parkedPath!==void 0&&await recordRetainedSession(host,entry2,parkedPath,!1,!0).catch(cause=>{process.stderr.write(`senpi rpc host shutdown park record ${sessionId} failed: ${String(cause)}
`)}),await finalizeClose(host,sessionId,binding2,()=>parkedPath!==void 0?host.writer.parkSession(sessionId,parkedPath,"host_shutdown"):host.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},"host_shutdown"))):await host.finalizations.get(sessionId)?.promise,host.writer.forgetSession(sessionId))})),host.bindings.clear(),host.uninstallEffectSink?.(),host.uninstallEffectSink=void 0}function relocationConnection(host,sessionId){return host.attachOrder.connections(sessionId).find(connection2=>host.sessionsByConnection.get(connection2)?.has(sessionId)===!0&&host.writer.getConnectionCapabilities(connection2)?.includes(SESSION_RELOCATION_CAPABILITY)===!0)}function connectionLeft(host,sessionId,connection2){host.attachOrder.detached(sessionId,connection2),host.bindings.get(sessionId)?.connectionDetached?.(connection2)}async function releaseDisconnectAttachment(host,sessionId){let live=host.registry.peek(sessionId),endsSession=live?.retainOnDisconnect!==!0&&(live?.attachments??0)<=1,session=live?.state==="open"?live.runtime?.session:void 0;if(endsSession&&live?.state==="open"&&live.worker?.snapshot?.streaming){let unsubscribe=live.worker.subscribeSettled(()=>{unsubscribe(),releaseOwnedSession(host,sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred worker release ${sessionId} failed: ${String(cause)}
`)})});return!0}if(endsSession&&session?.isStreaming){let released=!1,unsubscribe=session.subscribe(event=>{event.type==="agent_idle"&&(released||(released=!0,unsubscribe(),releaseOwnedSession(host,sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred release for session ${sessionId} failed: ${String(cause)}
`)})))});return!0}return await releaseOwnedSession(host,sessionId),!1}function recordAttachment(host,owner,sessionId){host.writer.attachConnectionToSession(owner,sessionId);let owned=host.sessionsByConnection.get(owner)??new Map;owned.set(sessionId,(owned.get(sessionId)??0)+1),host.sessionsByConnection.set(owner,owned),host.attachOrder.attached(sessionId,owner)}function releaseConnection(host,connectionId){return host.routes.release(connectionId),host.admissions?releaseAdmittedConnection(host,host.admissions,connectionId):releaseConnectionHolds(host,connectionId)}async function releaseAdmittedConnection(host,admissions,connectionId){admissions.endConnection(connectionId);try{return await releaseConnectionHolds(host,connectionId)}finally{await admissions.forgetConnection(connectionId)}}async function releaseConnectionHolds(host,connectionId){host.releasedConnections.add(connectionId),host.writer.clearConnectionCapabilities(connectionId),host.connectionRoles.release(connectionId);for(let sessionId of host.sessionsByConnection.get(connectionId)?.keys()??[])host.writer.detachConnectionFromSession(connectionId,sessionId),connectionLeft(host,sessionId,connectionId);host.writer.hasConnection(connectionId)||(host.pendingCapabilities.delete(connectionId),host.writer.delegations.forget(connectionId),host.connectionRoles.forget(connectionId));let opens=host.opensByConnection.get(connectionId),owned=host.sessionsByConnection.get(connectionId);if(host.sessionsByConnection.delete(connectionId),host.draining)return opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[...owned?.keys()??[]];if(owned===void 0)return opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[];let deferred=new Set;return await Promise.all([...owned].map(async([sessionId,count])=>{for(let attachment=0;attachment<count;attachment++)await releaseDisconnectAttachment(host,sessionId)&&deferred.add(sessionId)})),opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[...deferred]}async function releaseOwnedSession(host,sessionId){let live=host.registry.peek(sessionId),parks=live?.state==="open"&&live.retainOnDisconnect===!0&&live.attachments===1,claim=tryClaimClose(host,sessionId,{drainAttachments:!1,detach:!0});if(!claim)return;if(!claim.finalizer){host.writer.status.publish(sessionId,"detach","client"),parks&&live.runtime&&(live.lifecycleMutex=live.lifecycleMutex.then(()=>live.runtime?.emitAttachmentEvent("session_parked")),await live.lifecycleMutex),await host.finalizations.get(sessionId)?.promise;return}let binding2=host.bindings.get(sessionId);binding2?.cancelPendingExtensionUiRequests?.(),await finalizeClose(host,sessionId,binding2)}function releaseOwnerAttachment(host,owner,sessionId){let owned=host.sessionsByConnection.get(owner),count=owned?.get(sessionId);!owned||count===void 0||(count===1?(host.writer.detachConnectionFromSession(owner,sessionId),owned.delete(sessionId),connectionLeft(host,sessionId,owner)):owned.set(sessionId,count-1),owned.size===0&&host.sessionsByConnection.delete(owner))}function forgetSessionOwnership(host,sessionId){host.attachOrder.forgetSession(sessionId);for(let[connection2,owned]of host.sessionsByConnection)owned.delete(sessionId),owned.size===0&&host.sessionsByConnection.delete(connection2)}import{createHash as createHash2}from"node:crypto";import{mkdtemp,rm as rm4}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join7}from"node:path";var CompactAdmissionError=class extends Error{constructor(reason){super(reason),this.reason=reason,this.name="CompactAdmissionError"}};import{readFile as readFile3,writeFile as writeFile2}from"node:fs/promises";import{join as join5}from"node:path";var ADMISSION_LIMITS={entries:128,bytes:16*1024*1024,hot:16,row:131584,retired:4096},rowSchema=external_exports.object({fingerprint:external_exports.string().regex(/^[0-9a-f]{64}$/),state:external_exports.enum(["pending","complete","cancelled","failed"]),failure:external_exports.literal("storage_unavailable").optional(),answer:external_exports.string().max(65536).optional()});async function readAdmissionRow(epoch,key){let failure2=epoch.failures?.get(key);if(failure2)return failure2;try{let text4=await readFile3(join5(await epoch.directory,key),"utf8");if(Buffer.byteLength(text4)>ADMISSION_LIMITS.row)throw new CompactAdmissionError("storage_unavailable");return rowSchema.parse(JSON.parse(text4))}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause instanceof CompactAdmissionError?cause:new CompactAdmissionError("storage_unavailable")}}async function writeAdmissionRow(epoch,key,row){let text4=JSON.stringify(row);if(Buffer.byteLength(text4)>ADMISSION_LIMITS.row)throw new CompactAdmissionError("storage_unavailable");try{await writeFile2(join5(await epoch.directory,key),text4,{mode:384,flush:!0})}catch(cause){throw cause instanceof Error?new CompactAdmissionError("storage_unavailable"):cause}}function runAdmissionProducer(signal,produce,release){return new Promise((resolve4,reject)=>{let abort=()=>reject(signal.reason);if(signal.aborted)return abort();signal.addEventListener("abort",abort,{once:!0}),produce().then(async value=>{signal.aborted?await release(value):resolve4(value)},reject).finally(()=>signal.removeEventListener("abort",abort)).catch(()=>{})})}function recordProducerLoss(losses,kind,count,cause){if(count<=0)return;losses[kind]+=count;let detail2=cause===void 0?"":`: ${cause instanceof Error?cause.message:String(cause)}`;process.stderr.write(`senpi rpc admission producer ${kind} ${count}${detail2}
`)}var AdmissionProducerLifetime=class{constructor(){this.controller=new AbortController,this.signal=this.controller.signal}end(abandoned){this.timer??=setTimeout(()=>{abandoned(),this.controller.abort(new CompactAdmissionError("storage_unavailable"))},OPEN_AFTER_QUEUED_DEADLINE_MS),this.timer.unref()}close(){clearTimeout(this.timer)}};import{rm as rm3}from"node:fs/promises";import{join as join6}from"node:path";function retainDone(epoch,key,admissionId){epoch.hot.has(key)||(epoch.done.delete(key),epoch.done.set(key,admissionId))}async function reserveRow(epoch,capacity,routed,overflowed){for(let[key,admissionId]of epoch.done){if(epoch.hot.size+epoch.done.size<capacity)return!0;if(!routed(admissionId)){try{await rm3(join6(await epoch.directory,key),{force:!0})}catch{throw new CompactAdmissionError("storage_unavailable")}epoch.done.delete(key),epoch.failures.delete(key),epoch.retired.add(key);for(let oldest of epoch.retired){if(epoch.retired.size<=ADMISSION_LIMITS.retired)break;epoch.retired.delete(oldest),overflowed()}}}return epoch.hot.size+epoch.done.size<capacity}async function settleProducedAdmission(epoch,key,fingerprint,produced,serial){let value=produced.answer,cancelled=await serial(async()=>{let row=await readAdmissionRow(epoch,key),retired=epoch.ended||row?.state==="cancelled",persist=async()=>{let answer4=JSON.stringify(value);if(Buffer.byteLength(answer4)>65536)throw new CompactAdmissionError("storage_unavailable");await writeAdmissionRow(epoch,key,{state:retired?"cancelled":"complete",fingerprint,answer:answer4})};value=produced.refusal?.()??value,await persist();let refused4=produced.refusal?.();if(refused4&&JSON.stringify(refused4)!==JSON.stringify(value)&&(value=refused4,await persist()),retired||epoch.ended||refused4)return!0;try{produced.activate?.()}catch(cause){throw process.stderr.write(`senpi rpc admission activation failed; releasing subscription: ${cause instanceof Error?cause.message:String(cause)}
`),epoch.failures.set(key,{state:"failed",fingerprint,failure:"storage_unavailable"}),new CompactAdmissionError("storage_unavailable")}return!1});return{value,cancelled}}var CompactAdmissions=class{status(){return{...this.losses,retiredOverflow:this.retiredOverflow}}overflowRetired(){this.retiredOverflow++===0&&process.stderr.write(`senpi rpc admission retired-ID ring overflowed (${ADMISSION_LIMITS.retired} digests); older IDs are forgotten
`)}end(epoch){epoch.ended=!0,epoch.producer.end(()=>recordProducerLoss(this.losses,"abandoned",epoch.hot.size))}constructor(limits=ADMISSION_LIMITS,routed=()=>!1){this.epochs=new Map,this.losses={abandoned:0,releaseFailed:0},this.retiredOverflow=0,this.limits=limits,this.routed=routed}key(id){if(!parseBoundedId(id).ok)throw new CompactAdmissionError("malformed_request");return createHash2("sha256").update(id).digest("hex")}epoch(id,peer){let epoch=this.epochs.get(id);return epoch||(epoch={producer:new AdmissionProducerLifetime,peer,directory:mkdtemp(join7(tmpdir(),"senpi-admissions-")),hot:new Map,failures:new Map,done:new Map,retired:new Set,tail:Promise.resolve(),ended:!1,waiting:0},this.epochs.set(id,epoch)),epoch}async serial(epoch,action){if(epoch.waiting>=ADMISSION_LIMITS.hot)throw new CompactAdmissionError("admission_busy");epoch.waiting++;let previous=epoch.tail,done=Promise.withResolvers();epoch.tail=done.promise,await previous;try{return await action()}finally{epoch.waiting--,done.resolve()}}async run(identity,produce){let key=this.key(identity.admissionId),epoch=this.epoch(identity.socketEpoch,identity.peer),registered=await this.serial(epoch,async()=>{if(epoch.ended)throw new CompactAdmissionError("admission_retired");let row=await readAdmissionRow(epoch,key);if(row){if(row.fingerprint!==identity.fingerprint)throw new CompactAdmissionError("admission_conflict");switch(retainDone(epoch,key,identity.admissionId),row.state){case"complete":if(row.answer===void 0)throw new CompactAdmissionError("storage_unavailable");return{kind:"complete",answer:external_exports.record(external_exports.string(),external_exports.unknown()).parse(JSON.parse(row.answer))};case"cancelled":throw new CompactAdmissionError("admission_retired");case"failed":throw new CompactAdmissionError(row.failure??"admission_retired");case"pending":{let pending2=epoch.hot.get(key);if(!pending2)throw new CompactAdmissionError("storage_unavailable");return{kind:"join",pending:pending2}}}}if(identity.retry)throw new CompactAdmissionError("admission_unknown");if(epoch.retired.has(key))throw new CompactAdmissionError("admission_retired");if(epoch.hot.size>=ADMISSION_LIMITS.hot)throw new CompactAdmissionError("admission_busy");let capacity=Math.min(this.limits.entries,Math.floor(this.limits.bytes/ADMISSION_LIMITS.row));if(!await reserveRow(epoch,capacity,admissionId=>this.routed(identity.socketEpoch,admissionId),()=>this.overflowRetired()))throw new CompactAdmissionError("admission_limit");await writeAdmissionRow(epoch,key,{state:"pending",fingerprint:identity.fingerprint});let pending=Promise.withResolvers();return pending.promise.catch(()=>{}),epoch.hot.set(key,pending),{kind:"fresh",pending}});switch(registered.kind){case"complete":return registered.answer;case"join":return registered.pending.promise;case"fresh":break}let produced;try{produced=await runAdmissionProducer(epoch.producer.signal,()=>produce(epoch.producer.signal),value2=>value2.release().catch(cause=>recordProducerLoss(this.losses,"releaseFailed",1,cause)));let{value,cancelled}=await settleProducedAdmission(epoch,key,identity.fingerprint,produced,action=>this.serial(epoch,action));if(cancelled){let release=produced.release;produced=void 0,await release()}return registered.pending.resolve(value),value}catch(cause){let failure2=cause,row={state:"failed",fingerprint:identity.fingerprint,...cause instanceof CompactAdmissionError&&cause.reason==="storage_unavailable"?{failure:"storage_unavailable"}:{}};row.failure&&epoch.failures.set(key,row),produced&&await produced.release();try{await this.serial(epoch,()=>writeAdmissionRow(epoch,key,row))}catch(storageCause){process.stderr.write(`senpi rpc admission failure row write failed: ${storageCause instanceof Error?storageCause.message:String(storageCause)}
`),epoch.failures.set(key,{...row,failure:"storage_unavailable"}),failure2=new CompactAdmissionError("storage_unavailable")}finally{registered.pending.reject(failure2)}throw failure2}finally{epoch.hot.delete(key),retainDone(epoch,key,identity.admissionId)}}async pending(socketEpoch,admissionId){let key=this.key(admissionId),epoch=this.epochs.get(socketEpoch);return!epoch||epoch.ended?!1:this.serial(epoch,async()=>(await readAdmissionRow(epoch,key))?.state==="pending")}async cancel(socketEpoch,admissionId){let key=this.key(admissionId),epoch=this.epochs.get(socketEpoch);return epoch?this.serial(epoch,async()=>{let row=await readAdmissionRow(epoch,key);if(!row)return epoch.retired.has(key)?"already_complete":"unknown";switch(row.state){case"complete":case"failed":return"already_complete";case"cancelled":return"cancelled";case"pending":return await writeAdmissionRow(epoch,key,{...row,state:"cancelled"}),"cancelled"}}):"unknown"}async result(socketEpoch,admissionId){let key=this.key(admissionId),epoch=this.epochs.get(socketEpoch);if(epoch)return this.serial(epoch,async()=>{let row=await readAdmissionRow(epoch,key);if(row?.answer!==void 0)return{state:row.state,answer:external_exports.record(external_exports.string(),external_exports.unknown()).parse(JSON.parse(row.answer))}})}async forgetPeer(socketEpoch){let epoch=this.epochs.get(socketEpoch);epoch&&(this.end(epoch),await Promise.allSettled([...epoch.hot.values()].map(pending=>pending.promise)),await epoch.tail,epoch.producer.close(),await rm4(await epoch.directory,{recursive:!0,force:!0}),this.epochs.delete(socketEpoch))}endConnection(peer){for(let epoch of this.epochs.values())epoch.peer===peer&&this.end(epoch)}async forgetConnection(peer){for(let[id,epoch]of this.epochs)epoch.peer===peer&&await this.forgetPeer(id)}async dispose(){for(let epoch of this.epochs.values())this.end(epoch);for(let id of this.epochs.keys())await this.forgetPeer(id)}};import{randomUUID}from"node:crypto";var CONTROLS=new Set(["message_block_state","message_block_metadata","message_tool_arguments_reset"]),carried=new WeakMap,carriedRefusals=new WeakSet,CanonicalPairing=class{constructor(){this.pending=new WeakMap,this.refusals=new WeakSet}structured(record){let carrier=recoveryCarrier(record);if(!carrier)return;let canonical;try{canonical=protocolClone(record)}catch(cause){throw protocolDepthLimitOf(cause)!==void 0&&this.refusals.add(carrier),cause}if(CONTROLS.has(canonical.type))return{record:canonical,carrier};this.pending.set(carrier,canonical)}take(legacy){let carrier=recoveryCarrier(legacy),canonical=carrier&&this.pending.get(carrier);return carrier&&this.pending.delete(carrier),canonical}refused(legacy){let carrier=recoveryCarrier(legacy);return carrier!==void 0&&this.refusals.delete(carrier)}};function carryCanonical(legacy,canonical,refused4){canonical&&carried.set(legacy,canonical),refused4&&carriedRefusals.add(legacy)}function frameUnit(frame){let{ordinal,firstOrdinal,recovery,canonical}=frame;return canonical&&recovery&&ordinal!==void 0&&firstOrdinal!==void 0?{record:canonical,carrier:recovery,ordinal,firstOrdinal}:void 0}var CompactProducerStamp=class{constructor(){this.next=0,this.first=new Map,this.last={ordinal:-1}}stamp(carrier,canonical,legacy){let ordinal=this.next++;if(this.last={ordinal},!carrier)return{ordinal};let ends=canonical?.type==="message_end"||legacy!==void 0&&Reflect.get(legacy,"type")==="message_end",firstOrdinal=canonical?this.first.get(carrier.messageId)??ordinal:void 0;return ends?this.first.delete(carrier.messageId):firstOrdinal!==void 0&&this.first.set(carrier.messageId,firstOrdinal),this.last={ordinal,firstOrdinal,messageId:carrier.messageId},firstOrdinal===void 0?{ordinal}:{ordinal,firstOrdinal}}defer(prefix){let{ordinal,firstOrdinal,messageId}=this.last,moved=ordinal+prefix;return this.next+=prefix,firstOrdinal===void 0?{ordinal:moved}:firstOrdinal!==ordinal?{ordinal:moved,firstOrdinal}:(messageId!==void 0&&this.first.get(messageId)===ordinal&&this.first.set(messageId,moved),{ordinal:moved,firstOrdinal:moved})}forget(){this.first.clear()}};async function createRpcSessionBinding(sessionId,entry2,writer,requestClose,options={}){if(entry2.worker)return entry2.worker.bind(sessionId,writer,requestClose,options);if(!entry2.runtime)throw new Error("Session runtime was not created");let rpcBindingGeneration=randomUUID(),rpcOwnersByConnection=new Map,toolSpans=createToolAttributionSpans(sessionId),lane=entry2.acceptance;lane&&setSessionRecoveryEpoch(entry2.runtime.session,lane.recoveryEpoch),lane&&writer.registerAcceptance(sessionId,lane);let journaled=lane?entry2.runtime.session.sessionManager:void 0,structured=structuredLaneEnabled(),pairing=structured?new CanonicalPairing:void 0,stamp=new CompactProducerStamp,unit=(carrier,record,legacy)=>{let{ordinal,firstOrdinal}=stamp.stamp(carrier,record,legacy);return carrier&&record&&firstOrdinal!==void 0?{record,carrier,ordinal,firstOrdinal}:void 0},enqueueRecord=record=>{if(entry2.speculative)return;toolSpans.observe(record);let canonical=pairing?.take(record),refused4=pairing?.refused(record)===!0;if(lane&&"type"in record&&record.type==="session_replaced")journaled=entry2.runtime?.session.sessionManager,lane.bootstrap({transcript:journaled?.beginTranscriptJournal()??[]}),stamp.forget(),entry2.runtime&&setSessionRecoveryEpoch(entry2.runtime.session,lane.recoveryEpoch);else if(lane){lane.applyTranscript(journaled?.drainTranscript()??[]);let carrier=recoveryCarrier(record);lane.accept(record,carrier,unit(carrier,canonical,record),refused4,executionCallKey(record))}else carryCanonical(record,canonical,refused4);enqueueLegacyRecord(writer,sessionId,record)},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry2.switchSession)return entry2.switchSession;if(property==="setRebindSession")return callback=>{entry2.rebindSession=lane&&callback?async session=>{await lane.generations.bind(session.sessionId),await callback(session)}:callback,entry2.runtime?.setRebindSession(entry2.rebindSession)};let runtime=entry2.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}}),droppedAfterClose=!1,handler=await runWithProviderScope(entry2.scope,async()=>{let writeInScope=bindToProviderScope(enqueueRecord),dropAfterClose=()=>{droppedAfterClose||process.stderr.write(`senpi rpc host: dropped a record for closed session ${sessionId} at ${new Date().toISOString()}
`),droppedAfterClose=!0},writeRecord=record=>{if(entry2.scope.state==="closed")return dropAfterClose();writeInScope(record)},writeStructuredInScope=bindToProviderScope(record=>{if(entry2.speculative)return;writer.structuredLanes.accept(sessionId,record);let control=pairing?.structured(record);control&&lane?lane.acceptControl(unit(control.carrier,control.record)):control&&writer.enqueueCanonical(sessionId,control)}),taggedSink={writeRecord,...structured?{writeStructured:record=>{entry2.scope.state!=="closed"&&writeStructuredInScope(record)},structuredFailed:cause=>{lane?lane.compactUnavailable(cause):writer.canonicalUnavailable(sessionId,cause)}}:{},writeRaw:()=>{if(entry2.scope.state==="closed")return dropAfterClose();throw new Error("Shared session bindings deliver records through writeRecord, never writeRaw")},waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,rpcOwner:()=>{let owner=writer.connectionContext.owner,connection2=writer.currentConnection();return owner&&connection2&&rpcOwnersByConnection.set(connection2,owner),owner},retireRpcBinding:()=>{rpcBindingGeneration=randomUUID(),rpcOwnersByConnection.clear()},publishLoadedSurfacesChanged:(previous,digest)=>{!entry2.speculative&&entry2.scope.state!=="closed"&&writer.publishLoadedSurfacesChanged(sessionId,previous,digest)},...options,workerSecurityBridge:writer.workerSecurityBridge,secretInputRoute:writer.secretInputRoute(sessionId,!0),grantDialogSettled:id=>writer.settleGrantDialog(sessionId,id),grantDialogRaised:(id,title)=>writer.noticeGrantDialog(sessionId,id,title),bindSecurityPresentation:(session,ui)=>writer.bindSecurityPresentations(sessionId,session.sessionId,session.securityNotices,ui),bindMcpForms:(session,ui)=>writer.bindMcpForms(sessionId,session.sessionId,ui,()=>session.admitHumanAnswer()),clientInfo:options.clientInfo===void 0?void 0:{...options.clientInfo,hasCapability:(connection2,capability)=>writer.getConnectionCapabilities(connection2)?.includes(capability)===!0}})});return await handler.ready,{setClientCapabilities:capabilities=>runWithProviderScope(entry2.scope,()=>handler.setClientCapabilities(capabilities)),handle:command=>{if(writer.handleMcpForm(command))return Promise.resolve();let invoke=()=>runWithProviderScope(entry2.scope,()=>handler.handleInputLine(JSON.stringify(command)));return carriesExtensionOwner(command)?writer.connectionContext.withBinding(rpcBindingGeneration,invoke):invoke()},cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry2.scope,()=>handler.cancelPendingExtensionUiRequests()),pendingPrompts:()=>handler.pendingPrompts(),connectionDetached:connectionId=>{rpcOwnersByConnection.get(connectionId)?.retire(),rpcOwnersByConnection.delete(connectionId),runWithProviderScope(entry2.scope,()=>handler.connectionDetached(connectionId))},dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry2.scope,()=>handler.dispose()))}}var SessionAttachOrder=class{constructor(){this.next=0,this.order=new Map}attached(sessionId,connection2){let connections=this.order.get(sessionId)??new Map;connections.has(connection2)||connections.set(connection2,this.next++),this.order.set(sessionId,connections)}detached(sessionId,connection2){let connections=this.order.get(sessionId);connections?.delete(connection2),connections?.size===0&&this.order.delete(sessionId)}forgetSession(sessionId){this.order.delete(sessionId)}connections(sessionId){return[...(this.order.get(sessionId)??new Map).entries()].sort((left,right)=>left[1]-right[1]).map(([connection2])=>connection2)}};var HostParkLedger=class{constructor(close2){this.parks=new Map,this.replacements=new Map,this.stopped=!1,this.close=close2}get size(){return this.parks.size}async park(key,build){let existing=this.parks.get(key);if(existing&&!existing.claim&&!existing.closing)return await existing.ready,"already_parked";if(existing)return"full";let replacement=this.replacements.get(key);if(replacement!==void 0&&(clearTimeout(replacement),this.replacements.delete(key)),this.stopped)throw new Error("host_draining");if(this.parks.size+this.replacements.size>=4)return"full";let ready=Promise.withResolvers();ready.promise.catch(()=>{});let park={ready:ready.promise};this.parks.set(key,park);try{return park.opened=await build(),this.stopped||(park.expiry=setTimeout(()=>{this.retire(key,park)},6e4),park.expiry.unref?.()),ready.resolve(),this.stopped&&await this.retire(key,park),"parked"}catch(cause){throw this.parks.delete(key),ready.reject(cause),cause}}take(key){let park=this.parks.get(key);if(!(this.stopped||!park?.opened||park.claim||park.closing))return clearTimeout(park.expiry),park.claim=Promise.withResolvers(),park.opened}finish(key){let park=this.parks.get(key);this.parks.delete(key),park?.claim?.resolve()}replace(key,build){if(this.stopped||this.replacements.has(key))return;let timer=setTimeout(()=>{this.replacements.delete(key),this.park(key,build).catch(cause=>{process.stderr.write(`senpi rpc replacement park failed: ${String(cause)}
`)})},0);timer.unref?.(),this.replacements.set(key,timer)}async stop(){this.stopped=!0;for(let timer of this.replacements.values())clearTimeout(timer);this.replacements.clear(),await Promise.all([...this.parks].map(async([key,park])=>{await park.ready.catch(()=>{}),park.claim?await park.claim.promise:await this.retire(key,park)}))}retire(key,park){return clearTimeout(park.expiry),park.closing??=(async()=>{try{park.opened&&await this.close(park.opened)}finally{this.parks.get(key)===park&&this.parks.delete(key)}})(),park.closing}};import{stat as stat2}from"node:fs/promises";import{join as join9}from"node:path";function staleError(id,command,message){return{id,type:"response",command,success:!1,error:message,errorCode:"delegation_incarnation_stale"}}function declareSocketClient(host,command){let peer=host.writer.currentConnection(),selection=peer===void 0?void 0:host.writer.compactSelection(peer),connection2=roleConnection(peer),incarnation=commandAuthority.getStore()?.incarnation;if(host.connectionRoles.isStale(connection2,incarnation))return staleError(command.id,command.type,DELEGATION_INCARNATION_STALE);let role=caps=>host.connectionRoles.declare(connection2,caps,incarnation)==="declared",origin=remoteOriginDeclaration(command.remoteOrigin,declared=>host.connectionRoles.acceptsOrigin(roleConnection(peer),declared));if("refusal"in origin)return error(command.id,command.type,origin.refusal);let reason=selection?selection.declare(command.capabilities,selection.selected||host.compactAvailable(),role):command.capabilities!==void 0&&!role(command.capabilities)?"connection_role_fixed":void 0;if(reason)return error(command.id,command.type,reason==="connection_role_fixed"?CONNECTION_ROLE_FIXED:reason);if(origin.origin!==void 0&&host.connectionRoles.declareOrigin(roleConnection(peer),origin.origin),peer!==void 0){let caps=compactUpdatesEnabled()?selection?.capabilities??command.capabilities??host.pendingCapabilities.get(peer)??[]:command.capabilities??[];host.pendingCapabilities.set(peer,[...caps]),host.writer.setConnectionCapabilities(peer,caps)}else command.capabilities!==void 0&&host.writer.setSoleSecretCapabilities(command.capabilities);return{id:command.id,type:"response",command:"set_client_info",success:!0,...selection?.ack()?{data:selection.ack()}:{}}}function compactAdmissionGate(host,command){if(!compactUpdatesEnabled())return;let peer=host.writer.currentConnection(),selection=peer===void 0?void 0:host.writer.compactSelection(peer);if(!(command.type==="open_session"||command.type==="attach_session"||command.type==="reclaim_session"||command.type==="reset_stream"||command.type==="subscribe_sessions"&&(command.admissionId!==void 0||command.mirror!==void 0&&command.mirror!=="none")))return;let refuse=reason=>error(command.id,command.type,reason);if(selection?.refused)return refuse("compact_selection_refused");if(command.admissionId!==void 0&&!selection?.selected)return refuse("compact_not_negotiated");if(selection?.selected){if((command.type==="open_session"||command.type==="attach_session"||command.type==="subscribe_sessions")&&command.admissionId===void 0)return refuse("compact_admission_required");if(command.type==="open_session"&&host.registry.supportsCompact?.({...host.defaults,...command})!==!0||command.type==="attach_session"&&!host.writer.recoveryLane(command.sessionId)||command.type==="subscribe_sessions"&&host.registry.list().some(row=>row.status==="open"&&!host.writer.recoveryLane(row.sessionId)))return refuse("compact_endpoint_unsupported")}selection&&(selection.admitted=!0)}import{randomUUID as randomUUID2}from"node:crypto";var RouteDisconnected=class extends Error{constructor(sent){super(sent?"predecessor_delivery_outcome_unknown":"predecessor_not_sent"),this.sent=sent}},PREDECESSOR_REQUEST_TIMEOUT_MS=DEFAULT_LOOP_LAG_ERROR_MS,RouteTimedOut=class extends Error{constructor(){super("predecessor_request_timeout")}},PredecessorPeer=class _PredecessorPeer{constructor(socket,generation,onRecord,onEnd){this.pending=new Map,this.socket=socket,this.generation=generation;let detach=attachJsonlLineReader(socket,line=>{let value;try{value=authRecord(JSON.parse(line))}catch{socket.destroy();return}if(!value)return;let pending=typeof value.id=="string"&&value.type==="response"?this.pending.get(value.id):void 0;pending?pending.resolve(value):onRecord(value)},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>socket.destroy()});socket.on("error",()=>socket.destroy()),socket.once("close",()=>{detach();for(let pending of this.pending.values())pending.reject(new RouteDisconnected(!0));onEnd()})}static async connect(endpoint,onRecord,onEnd){let{socket,protocol}=await connectAuthenticatedRpcSocket(endpoint.socket,void 0,{keyRoot:endpoint.keyRoot,expectedLaunchId:endpoint.launchId}),data2=authRecord(protocol.data);if(data2?.instanceId!==endpoint.instanceId||typeof data2.generation!="number")throw socket.destroy(),new Error("predecessor_identity_mismatch");return new _PredecessorPeer(socket,data2.generation,onRecord,onEnd)}async request(command,deadlineMs){if(this.socket.destroyed)throw new RouteDisconnected(!1);let id=typeof command.id=="string"?command.id:randomUUID2();if(this.pending.has(id))throw new Error("duplicate_request_id");let pending=Promise.withResolvers();this.pending.set(id,pending);try{return this.socket.write(serializeJsonLine({...command,id})),await(deadlineMs===void 0?this.answerWhileAlive(pending.promise):within2(pending.promise,deadlineMs))}catch(cause){throw cause instanceof RouteTimedOut&&this.socket.destroy(),cause instanceof RouteDisconnected&&!cause.sent?new RouteDisconnected(!0):cause}finally{this.pending.delete(id)}}async answerWhileAlive(answer4){for(;;){let answered=await within2(answer4,PREDECESSOR_REQUEST_TIMEOUT_MS).catch(cause=>{if(!(cause instanceof RouteTimedOut))throw cause});if(answered!==void 0)return answered;await this.request({type:"get_protocol_info",observe:!0},PREDECESSOR_REQUEST_TIMEOUT_MS)}}send(record){this.socket.write(serializeJsonLine(record))}close(){this.socket.destroy()}};function within2(answer4,ms){let timer,late=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new RouteTimedOut),ms)});return Promise.race([answer4,late]).finally(()=>clearTimeout(timer))}import{stat}from"node:fs/promises";var SWITCH_RETRY_MS=250,SWITCH_PENDING="generation_switch_pending",RouteSwitchFailed=class extends Error{};function switchRoute(table,route){route.switching||!table.holds(route)||(route.switching=!0,recover(table,route).then(code2=>settle(table,route,code2),cause=>settle(table,route,cause instanceof Error?cause.message:String(cause))))}async function recover(table,route){for(;table.holds(route);){if(table.host.draining)return"host_draining";let dir=table.host.handoverParkedDir;if(!table.reopen||!dir)return"generation_route_gone";let entry2=(await readHandoverParkedSessions(dir)).find(r=>r.sessionPath===route.path&&r.parkedBy===route.endpoint.instanceId)??route.park??{sessionPath:route.path,durableSessionId:route.row?.durableSessionId,retainOnDisconnect:route.row?.retain_on_disconnect===!0,cwd:route.row?.cwd};if(!table.holds(route))return;if(!await stat(entry2.sessionPath).then(file=>file.isFile(),()=>!1))return"session_file_gone";let result=await table.reopen({...entry2,live:!0});if(result?.success)return;if(!result)return"generation_route_gone";if(result.error!=="session_path_in_use"&&result.error!=="session_held")return result.error;await new Promise(resolve4=>setTimeout(resolve4,SWITCH_RETRY_MS))}}function settle(table,route,code2){code2!==void 0&&route.local.reject(new RouteSwitchFailed(code2)),table.holds(route)&&table.forget(route)}async function awaitSwitch(table,route){let timer,pending=new Promise(resolve4=>{timer=setTimeout(()=>resolve4({kind:"pending"}),table.host.registry.closeGraceMs)});try{return await Promise.race([route.local.promise.then(()=>({kind:"switched"}),cause=>({kind:"failed",code:cause instanceof Error?cause.message:String(cause)})),pending])}finally{clearTimeout(timer)}}async function afterSwitch(table,route,command,local){let outcome=await awaitSwitch(table,route);return outcome.kind==="switched"?local():error(command.id,command.type,outcome.kind==="pending"?SWITCH_PENDING:outcome.code)}var ROW_STATES=["opening","open","closing"];function isRoutedSessionRow(value){let row=authRecord(value);return row!==void 0&&typeof row.sessionId=="string"&&typeof row.cwd=="string"&&ROW_STATES.includes(row.status)&&typeof row.attachments=="number"&&typeof row.retain_on_disconnect=="boolean"&&typeof row.kind=="string"&&authRecord(row.context)!==void 0&&(row.sessionPath===void 0||typeof row.sessionPath=="string")&&(row.durableSessionId===void 0||typeof row.durableSessionId=="string")}function routedAttachExtras(data2){let{routeRow,routePark}=data2;return{...isRoutedSessionRow(routeRow)?{row:routeRow}:{},...isHandoverParkedEntry(routePark)?{park:routePark}:{}}}function connection(table,route,caller){let existing=route.attachments.get(caller);if(existing)return existing;let host=table.host,attachment={count:0,peer:PredecessorPeer.connect(route.endpoint,record=>receive(table,route,caller,record),()=>{route.attachments.get(caller)===attachment&&!route.terminal&&switchRoute(table,route)}).then(async peer=>{try{let delegation=host.writer.delegations.recordOf(caller);if(!host.writer.hasConnection(caller)||route.attachments.get(caller)!==attachment)throw new Error("connection_closed");if(delegation){if(delegation.closed||delegation.current?.incarnation!==commandAuthority.getStore()?.incarnation)throw new Error("delegation_incarnation_stale");if(delegation.current&&(attachment.authority={incarnation:delegation.current.incarnation,epochOffset:readAuthority(delegation.current.authority).epoch-1}),!(await peer.request({type:"declare_delegation",principal:delegation.principal,granted:[...delegation.granted],...echoedRoles(delegation)})).success)throw new Error("delegation_refused")}let declared=host.connectionRoles.rolesOf(caller,delegation?.current?.incarnation),pending=host.pendingCapabilities.get(caller),capabilities=declared===void 0?void 0:[...(pending??[]).filter(c=>!CONNECTION_ROLE_CAPABILITIES.includes(c)),...declared],remoteOrigin=host.connectionRoles.originOf(caller);if((capabilities||remoteOrigin)&&!(await peer.request({type:"set_client_info",capabilities,remoteOrigin})).success)throw new Error("routed_client_declaration_refused");return route.generation=peer.generation,peer}catch(cause){throw peer.close(),cause}})};return route.attachments.set(caller,attachment),attachment}async function attach(table,route,caller,command){let host=table.host,attachment=connection(table,route,caller);try{let reply=await(await attachment.peer).request({...command,...command.type==="attach_session"?{sessionId:route.upstream}:{},expectedHostInstance:route.endpoint.instanceId});if(reply.success!==!0)return attachment.count||table.dropPeer(route,caller),{...reply,id:command.id};let data2=authRecord(reply.data);if(typeof data2?.sessionId!="string")throw new Error("invalid_routed_attach");route.upstream=data2.sessionId;let{routeRow:_row,routePark:_park,...visible}=data2,extras=routedAttachExtras(data2);return extras.row&&(route.row=extras.row),extras.park&&(route.park=extras.park),attachment.count++,!table.holds(route)&&host.registry.peek(route.id)?.state==="open"&&host.writer.hasConnection(caller)&&(host.registry.attachSession?.(route.id),recordAttachment(host,caller,route.id)),{...reply,id:command.id,...reply.sessionId===route.upstream&&{sessionId:route.id},data:{...visible,sessionId:route.id}}}catch(cause){attachment.count||table.dropPeer(route,caller),!route.attachments.size&&!route.row&&table.forget(route);let gone=cause instanceof Error&&"code"in cause&&(cause.code==="ENOENT"||cause.code==="ECONNREFUSED");return error(command.id,command.type,gone?"generation_route_gone":cause instanceof Error?cause.message:String(cause))}}function receive(table,route,caller,record){if(!(record.sessionId!==route.upstream||!route.upstream)){if(record.type==="session_closed"&&(record.reason==="handoff_parked"||record.reason==="host_shutdown")){switchRoute(table,route);return}record.type==="session_closed"&&(route.terminal=!0),!(record.type==="response"||!table.host.writer.hasConnection(caller))&&table.host.writer.enqueueControl({...record,sessionId:route.id},caller)}}import{join as join8}from"node:path";var PREDECESSOR_DISCOVERY_TIMEOUT_MS=SOCKET_HANDSHAKE_TIMEOUT_MS,GONE_CODES=["ENOENT","ECONNREFUSED","ECONNRESET","EPIPE"];async function discoverRoutes(table){let host=table.host,dir=host.handoverParkedDir,keyRoot=host.defaults.agentDir,self=host.defaults.hostContext?.host_instance;if(!dir||!keyRoot||!self||host.draining||!hostGeneration(process.env)||!host.inheritedHandover?.predecessorDraining&&!table.byId.size||(await readJsonObject(join8(dir,"host.pid")))?.instance_id!==self)return;let owners=new Map;for(let{owner}of await readSessionPathClaims(join8(dir,"reservations"))){if(owner.instanceId===self||!owner.strict_transfer||!/^[a-zA-Z0-9_-]+$/.test(owner.instanceId))continue;let paths=owners.get(owner.instanceId)??new Set;paths.add(owner.sessionPath),owners.set(owner.instanceId,paths)}await Promise.all([...owners].map(async([instanceId,paths])=>{let file=await readJsonObject(join8(dir,"generations",instanceId,"route.json"));typeof file?.socket!="string"||typeof file.launchId!="string"||await listPredecessor(table,{socket:file.socket,launchId:file.launchId,instanceId,keyRoot},paths)}));let unclaimed=[...table.byId.values()].filter(r=>!owners.get(r.endpoint.instanceId)?.has(r.path)&&!r.attachments.size&&!r.switching);if(unclaimed.length){let parked=new Set((await readHandoverParkedSessions(dir)).map(entry2=>canonicalSessionPath(entry2.sessionPath)));for(let route of unclaimed)!parked.has(route.path)&&!route.attachments.size&&table.holds(route)&&table.forget(route)}}async function listPredecessor(table,endpoint,paths){let peer;try{peer=await PredecessorPeer.connect(endpoint,()=>{},()=>{});let answer4=await peer.request({type:"list_sessions",include_workers:!0},PREDECESSOR_DISCOVERY_TIMEOUT_MS),rows=authRecord(answer4.data)?.sessions;if(!Array.isArray(rows))return;let localPaths=new Set(table.host.registry.list().flatMap(row=>row.sessionPath?[canonicalSessionPath(row.sessionPath)]:[]));for(let row of rows){if(!isRoutedSessionRow(row)||!row.sessionPath||row.status!=="open")continue;let path=canonicalSessionPath(row.sessionPath);if(!paths.has(path)||localPaths.has(path))continue;let route=table.route(path,endpoint);route.upstream=row.sessionId,route.row=row,route.generation=peer.generation}}catch(cause){if(unanswered(cause))return;process.stderr.write(`senpi rpc: predecessor ${endpoint.instanceId} gave no session list: ${cause instanceof Error?cause.message:String(cause)}
`)}finally{peer?.close()}}function unanswered(cause){return cause instanceof RouteDisconnected||cause instanceof RouteTimedOut||cause instanceof Error&&"code"in cause&&GONE_CODES.includes(cause.code)}var RouteTable=class{constructor(host){this.byPath=new Map,this.byId=new Map,this.host=host}holds(route){return this.byId.get(route.id)===route}route(path,endpoint){let existing=this.byPath.get(path);if(existing)return existing;let id=this.host.registry.reserveHandle?.();if(!id)throw new Error("registry_does_not_support_generation_routes");let route={path,id,endpoint,attachments:new Map,switching:!1,local:Promise.withResolvers()};return route.local.promise.catch(()=>{}),this.byPath.set(path,route),this.byId.set(route.id,route),route}forget(route){this.byId.delete(route.id),this.byPath.delete(route.path);for(let caller of[...route.attachments.keys()])this.dropPeer(route,caller);route.local.resolve()}dropPeer(route,caller){let attachment=route.attachments.get(caller);route.attachments.delete(caller),attachment?.peer.then(peer=>peer.close(),()=>{})}};var ATTACH_GATE_EXEMPT=new Set(["get_protocol_info","list_sessions","list_hands","subscribe_sessions","unsubscribe_sessions","get_subscription_limits","warm","park_session","claim_session","detach_connection","open_session","attach_session","reclaim_session","get_effect_status","get_state","get_snapshot","get_messages","get_entries","get_tree","get_fork_messages","get_last_assistant_text","get_media","get_commands","get_loaded_surfaces","get_project_trust","get_project_settings","read_project_file","get_project_mcp_servers","read_project_skill_file","read_user_skill_file","get_available_models","get_available_thinking_levels","get_fast_mode","get_session_stats","get_pending_inputs","get_steering_messages","get_follow_up_messages","get_auth_providers","get_provider_accounts","resolve_path","memory_report","eval_cells.list","eval_cells.peek","check_reload_veto"]);function logSafe(value){return JSON.stringify(value).slice(1,-1)}function attachmentGate(host,command){let owner=host.writer.currentConnection();if(!(owner===void 0||ATTACH_GATE_EXEMPT.has(command.type))&&!(!("sessionId"in command)||command.sessionId===void 0)&&!(host.writer.recoveryPages!==void 0&&(command.type==="get_recovery_page"||command.type==="release_recovery"))&&!(host.writer.recoveryPages!==void 0&&command.type==="reset_stream"&&host.writer.isCompactSubscription(owner,command.admissionId,command.sessionId))&&!(command.type==="close_session"||command.type==="set_session_context"||command.type==="release_attachment")&&!host.sessionsByConnection.get(owner)?.has(command.sessionId)&&!(command.type==="admit_external_message"&&host.connectionRoles.grantedByForwarder(owner,"peer_agent"))){if(process.env.SENPI_RPC_REQUIRE_ATTACH==="1")return error(command.id,command.type,"session_not_attached",{reason:"this connection is not attached to that session",action:"attach first with attach_session { sessionId, durableSessionId } or open_session { sessionPath }"});process.stderr.write(`senpi rpc host: ${command.type} on ${logSafe(command.sessionId)} from a connection not attached to it (refused from the next release)
`)}}var RETRY_ROUTED_OPEN="retry_routed_open",ROUTE_GONE_ERRORS=["session_not_held","session_closing","generation_session_parked","predecessor_not_sent","predecessor_delivery_outcome_unknown","generation_route_gone"],PredecessorRoutes=class{constructor(host){this.table=new RouteTable(host)}get host(){return this.table.host}set reopen(reopen){this.table.reopen=reopen}handleFor(path){return path?this.table.byPath.get(canonicalSessionPath(path))?.id:void 0}rows(){return Array.from(this.table.byId.values()).flatMap(r=>r.row?[{...r.row,sessionId:r.id,generation:r.generation,hostInstanceId:r.endpoint.instanceId}]:[])}discover(){return discoverRoutes(this.table)}async attachByIdentity(command,refusal4){let caller=this.host.writer.currentConnection();if(!caller||this.host.draining||!hostGeneration(process.env))return refusal4;await this.discover();let route=[...this.table.byId.values()].find(r=>r.upstream===command.sessionId&&r.row?.durableSessionId===command.durableSessionId&&(command.expectedHostInstance===void 0||command.expectedHostInstance===r.endpoint.instanceId));return route?attach(this.table,route,caller,command):refusal4}async attachPath(command,caller){if(!command.sessionPath)return;await this.discover();let route=this.table.byPath.get(canonicalSessionPath(command.sessionPath));return route&&attach(this.table,route,caller,command)}async open(command,caller,detail2){let claimant=authRecord(detail2?.owner),dir=this.host.handoverParkedDir,keyRoot=this.host.defaults.agentDir;if(!command.sessionPath||!dir||!keyRoot||claimant?.strict_transfer!==!0||claimant.current!==!1||typeof claimant.instanceId!="string"||!/^[a-zA-Z0-9_-]+$/.test(claimant.instanceId))return;let file=await readJsonObject(join9(dir,"generations",claimant.instanceId,"route.json"));if(!file||typeof file.socket!="string"||typeof file.launchId!="string"||(await readJsonObject(join9(dir,"host.pid")))?.instance_id!==this.host.defaults.hostContext?.host_instance)return;let route=this.table.route(canonicalSessionPath(command.sessionPath),{socket:file.socket,launchId:file.launchId,instanceId:claimant.instanceId,keyRoot});if(route.switching)return this.retryAfterSwitch(route,command);let reply=await attach(this.table,route,caller,command);return reply.success||!ROUTE_GONE_ERRORS.includes(reply.error)?reply:route.park?(switchRoute(this.table,route),this.retryAfterSwitch(route,command)):(await new Promise(resolve4=>setTimeout(resolve4,25)),RETRY_ROUTED_OPEN)}async retryAfterSwitch(route,command){let outcome=await awaitSwitch(this.table,route);return outcome.kind==="failed"?error(command.id,command.type,outcome.code):RETRY_ROUTED_OPEN}command(command,local){let route="sessionId"in command&&command.sessionId?this.table.byId.get(command.sessionId):void 0,caller=this.host.writer.currentConnection();if(!route||!caller)return;if(command.type==="set_client_info"){let declared=declareSocketClient(this.host,command);if(!declared.success)return Promise.resolve(declared)}if(route.switching)return afterSwitch(this.table,route,command,local);if(command.type==="attach_session")return command.expectedHostInstance!==void 0&&command.expectedHostInstance!==this.host.defaults.hostContext?.host_instance?Promise.resolve(error(command.id,command.type,"session_identity_mismatch")):attach(this.table,route,caller,command);let readOnly=ATTACH_GATE_EXEMPT.has(command.type)&&classifyRpcMethod(command)==="observe",attachment=readOnly?connection(this.table,route,caller):route.attachments.get(caller);return!attachment||!readOnly&&!attachment.count?Promise.resolve(error(command.id,command.type,"session_not_attached")):attachment.peer.then(async peer=>{if(route.switching)return afterSwitch(this.table,route,command,local);let wire={...command,sessionId:route.upstream,relayExec:commandAuthority.getStore()?.exec};if(wire.type==="extension_ui_response"||wire.type==="extension_ui_progress"||wire.type==="host_response"){peer.send(wire);return}let reply=await peer.request(wire);if(reply.success===!1&&reply.error==="generation_session_parked")return switchRoute(this.table,route),afterSwitch(this.table,route,command,local);reply.success&&(command.type==="close_session"||command.type==="release_attachment")&&--attachment.count===0&&this.table.dropPeer(route,caller),command.type==="close_session"&&!route.attachments.size&&this.table.forget(route);let payload=authRecord(reply.data),receipt=authRecord(reply.authority);return{...reply,...attachment.authority&&typeof receipt?.epoch=="number"&&{authority:{...receipt,incarnation:attachment.authority.incarnation,epoch:receipt.epoch+attachment.authority.epochOffset}},id:command.id,...reply.sessionId!==void 0&&{sessionId:route.id},...payload?.sessionId===route.upstream&&{data:{...payload,sessionId:route.id}}}}).catch(async cause=>cause instanceof RouteDisconnected&&(!cause.sent||classifyRpcMethod(command)==="observe")?(switchRoute(this.table,route),afterSwitch(this.table,route,command,local)):error(command.id,command.type,cause instanceof Error?cause.message:String(cause)))}async configure(caller,record){await Promise.all([...this.table.byId.values()].map(async route=>{let attachment=route.attachments.get(caller);if(!attachment||route.switching)return;let peer=await attachment.peer.catch(()=>{});if(!peer)return;await peer.request(record).then(reply=>reply.success===!0,()=>!1)||peer.close()}))}adopt(id){let route=this.table.byId.get(id);if(route){for(let[caller,attachment]of route.attachments)if(this.host.writer.hasConnection(caller))for(let i=0;i<attachment.count;i++)this.host.registry.attachSession?.(id),recordAttachment(this.host,caller,id);this.table.forget(route)}}release(caller){for(let route of this.table.byId.values())this.table.dropPeer(route,caller)}dispose(){for(let route of[...this.table.byId.values()])this.table.forget(route)}};import{createHash as createHash3}from"node:crypto";function admissionBaseline(reply,identity,live,routes){return new GeneratedFramesCursor(!1,async function*(){let answer4=await reply;if(answer4!==void 0&&(yield serializeJsonLine(answer4),live()))for(let admissionId of routes??[identity.admissionId])yield serializeJsonLine({type:"recovery_manifest",...identity,admissionId,componentRef:identity.componentRef??"manifest"})},()=>{})}var RouteAnnouncement=class _RouteAnnouncement{constructor(reason){this.reason=reason}static emit(reason,emit){return emit(),new _RouteAnnouncement(reason)}};var OpenRefused=class extends Error{constructor(response){super("compact open refused"),this.response=response,this.name="OpenRefused"}};async function compactOpen(host,command,physical){let peer=host.writer.currentConnection(),socketEpoch=peer===void 0?void 0:host.writer.socketEpochOf(peer),admissions=host.admissions;if(peer===void 0||socketEpoch===void 0||admissions===void 0)return error(command.id,command.type,"unsupported_transport");let{id:_request,admissionId,retry,...request}=command;if(admissionId===void 0)throw new CompactAdmissionError("malformed_request");let fingerprint=createHash3("sha256").update(JSON.stringify(Object.entries(request).sort(([a],[b])=>a.localeCompare(b)))).digest("hex"),delivery,baseline,completedOpen,accepted,announced,retireAfterReply,answerFinally=emit=>{announced=RouteAnnouncement.emit("open_ended",emit),retireAfterReply?.(announced),retireAfterReply=void 0},cancelledAnswer=async()=>{let result=await admissions.result(socketEpoch,admissionId);if(!(result?.state!=="cancelled"||typeof result.answer.generation!="number"))return{id:command.id,type:"response",command:command.type,success:!1,error:"attempt_cancelled",errorCode:"attempt_cancelled",code:"attempt_cancelled",admissionId,generation:result.answer.generation}};try{let identity={socketEpoch,peer,admissionId,fingerprint,retry:retry===!0},answer4=await admissions.run(identity,async signal=>{let result,physicalSucceeded=!1,response2=await physical(async opened=>{let sessionId=opened.sessionId,lane=host.writer.recoveryLane(sessionId);if(!lane)throw new CompactAdmissionError("storage_unavailable");let caller={socketEpoch,sessionId},checkpoints=host.writer.recoveryCheckpoints,frozen=checkpoints.freeze({...caller,peer,admissionId,routeKind:"ordinary"},lane,!0);if(!frozen.ok)throw new CompactAdmissionError("storage_unavailable");let token=frozen.value.token,identity2={sessionId,admissionId,generation:token.admission.generation,token:token.id},active=!0;delivery=Promise.withResolvers();let reply=delivery.promise;host.writer.registerAdmission(peer,admissionId,sessionId),baseline=()=>host.writer.installAdmissionBaseline(peer,admissionBaseline(reply,identity2,()=>active),()=>host.writer.socketEpochOf(peer)===socketEpoch),accepted={admissionId,generation:token.admission.generation};let retire=retirement=>{checkpoints.retireRoute(caller,admissionId,retirement),host.writer.unregisterAdmission(peer,admissionId)},release=async superseded=>{active&&(active=!1,superseded?retire("reopen_superseded"):announced?retire(announced):retireAfterReply=retire,physicalSucceeded&&(releaseOwnerAttachment(host,peer,sessionId),await releaseDisconnectAttachment(host,sessionId)))};completedOpen={sessionId,release:()=>release(!0)},result={answer:{type:"response",command:command.type,success:!0,sessionId,admissionId,generation:token.admission.generation,data:{sessionId,...opened.attached?{attached:!0}:{},recovery:{token:token.id,componentRef:"manifest"}}},release:()=>release(!1)}},signal).catch(async cause=>{throw await result?.release(),cause});if(response2!==void 0)throw await result?.release(),new OpenRefused(response2);if(result===void 0)throw new CompactAdmissionError("storage_unavailable");return physicalSucceeded=!0,result}),cancelled=await cancelledAnswer(),response=cancelled??{...answer4,id:command.id};if(delivery){(cancelled===void 0&&answer4.success===!0&&completedOpen?host.writer.supersedeOpen(peer,completedOpen.sessionId,admissionId,completedOpen.release):void 0)?.().catch(cause=>process.stderr.write(`senpi rpc superseded open release failed: ${String(cause)}
`));let reply=delivery,deliver=()=>{baseline?.(),reply.resolve(response)};cancelled?answerFinally(deliver):deliver()}else await host.writer.enqueueControl(response,peer);return}catch(cause){if(delivery?.resolve(void 0),!(cause instanceof OpenRefused)&&!(cause instanceof CompactAdmissionError)){let unexpected={...error(command.id,command.type,code(cause)),...accepted};throw accepted&&answerFinally(()=>{host.writer.enqueueControl(unexpected,peer).catch(written2=>{process.stderr.write(`senpi rpc failed open's refusal not written: ${String(written2)}
`)})}),cause}let refusal4=cause instanceof OpenRefused?cause.response:await cancelledAnswer()??error(command.id,command.type,`admission_${cause.reason}`,{kind:"request_refused",reason:cause.reason,hint:"new_request"});if(accepted===void 0)return refusal4;let ended2={...refusal4,...accepted},written;answerFinally(()=>{written=host.writer.enqueueControl(ended2,peer)}),await written;return}}import{execFile}from"node:child_process";var READ_ONLY_OR_CONTROL=new Set(["get_state","get_snapshot","get_effect_status","get_pending_inputs","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_model_thinking_level","get_fast_mode","get_session_stats","resolve_path","get_fork_messages","get_entries","get_tree","get_last_assistant_text","get_messages","get_media","get_commands","get_loaded_surfaces","get_auth_providers","get_provider_accounts","memory_report","eval_cells.list","eval_cells.peek","eval_cells.stop","export_html","export_jsonl","abort","interrupt","abort_compaction","abort_branch_summary","abort_retry","abort_bash","clear_queue","check_reload_veto","cleanup_bash_output","set_client_info","extension_ui_response","extension_ui_progress","host_response"]);function readProcessStarts(){let windows=process.platform==="win32",command=windows?"powershell.exe":"ps",args=windows?["-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { if ($null -ne $_.CreationDate) { "{0} {1}" -f $_.ProcessId, $_.CreationDate.ToUniversalTime().ToString("o") } }']:["-axo","pid=,lstart="];return new Promise(resolve4=>{execFile(command,args,{timeout:windows?5e3:1e3,maxBuffer:4*1024*1024,windowsHide:!0,...windows?{}:{env:{...process.env,LC_ALL:"C",LANG:"C"}}},(error2,stdout)=>{if(error2)return resolve4(void 0);let starts=new Map;for(let line of stdout.split(`
`)){let row=/^\s*(\d+)\s+(.+)$/.exec(line);if(!row)continue;let start=processStartTimeMs(row[2]);start!==void 0&&starts.set(Number(row[1]),start)}resolve4(starts)})})}function sessionHeldCheck(resolveDaemonPids){let daemonPids,processStarts,pidStarts=new Map,observedStarts=new Map;return async(sessionFile,sessionId)=>{let holders=await foreignSessionHolders(sessionFile,sessionId,{holderEnded:generation=>holderGenerationEnded(generation),readProcessStartMs:pid=>{let probe=pidStarts.get(pid);return probe||(probe=(async()=>{process.platform!=="linux"&&(processStarts??=readProcessStarts());let start=(await processStarts)?.get(pid)??await readProcessStartMs(pid);return observedStarts.set(pid,start),start})(),pidStarts.set(pid,probe)),probe}});if(holders.length===0)return;daemonPids??=resolveDaemonPids?.(observedStarts)??Promise.resolve([]);let family=await daemonPids,foreign=holders.filter(holder=>!family.includes(holder.pid));if(foreign.length>0)throw new RpcSessionRegistryError(RPC_ERROR_SESSION_HELD,void 0,{holders:foreign.map(({pid,cwd,host_socket,host_instance})=>({pid,...cwd===void 0?{}:{cwd},...host_socket===void 0?{}:{host_socket},...host_instance===void 0?{}:{host_instance}}))})}}async function dispatchSessionBinding(command,entry2,binding2,acknowledgePrompt2,daemonPids){if(!binding2)throw new RpcSessionRegistryError("unknown_session");if(!READ_ONLY_OR_CONTROL.has(command.type)){let assertSessionNotHeld=sessionHeldCheck(daemonPids),state=entry2.worker?.snapshot?.state;await assertSessionNotHeld(entry2.runtime?.session.sessionFile??state?.sessionFile??entry2.sessionPath,entry2.runtime?.session.sessionId??state?.sessionId??entry2.durableSessionId),"sessionPath"in command&&await assertSessionNotHeld(command.sessionPath)}command.type==="prompt"&&acknowledgePrompt2(),await binding2.handle(command)}import{isAbsolute as isAbsolute2}from"node:path";import{open}from"node:fs/promises";var SCAN_LIMIT_BYTES=1024*1024,CHUNK_BYTES=4096;function candidate(line){let entry2=parseSessionEntryLine(line);if(!entry2)return;if(entry2.type!=="session"||typeof entry2.id!="string")return{cwd:void 0};let{cwd}=entry2;return{cwd:typeof cwd=="string"&&cwd!==""?cwd:void 0}}async function readHeaderCwd(sessionFile){let handle2;try{handle2=await open(sessionFile,"r")}catch(error2){let{code:code2}=error2;if(code2==="ENOENT"||code2==="ENOTDIR")return;throw error2}try{let splitter=new SessionLineSplitter,buffer=Buffer.allocUnsafe(CHUNK_BYTES),scanned=0;for(;scanned<SCAN_LIMIT_BYTES;){let length=Math.min(buffer.length,SCAN_LIMIT_BYTES-scanned),{bytesRead}=await handle2.read(buffer,0,length,null);if(bytesRead===0)return candidate(splitter.finish())?.cwd;scanned+=bytesRead;for(let line of splitter.push(buffer.subarray(0,bytesRead))){let found=candidate(line);if(found)return found.cwd}}}finally{await handle2.close()}return headerCwdFromWholeFile(sessionFile)}async function headerCwdFromWholeFile(sessionFile){for(let entry2 of await loadEntriesFromFileAsync(sessionFile)){let found=candidate(JSON.stringify(entry2));if(found)return found.cwd}}async function openSessionFolder(command,hostDefault){if(command.cwd!==void 0&&command.cwd!==null)return command.cwd;let{sessionPath}=command;if(typeof sessionPath!="string"||!isAbsolute2(sessionPath))return hostDefault;let probe=createMovedPathProbe(),mapped=(await probe.resolve(sessionPath))?.mappedPath;if(probe.timedOut)throw new Error(`${sessionPath} could not be resolved: a filesystem step did not answer in time. Open it again, or name its folder with cwd.`);let recorded=await readHeaderCwd(mapped??sessionPath);return recorded!==void 0&&isAbsolute2(recorded)?recorded:hostDefault}function invalidSpawnedBy(command){let ancestry=command.spawnedBy;return ancestry!==void 0&&!isSpawnedBy(ancestry)}function validatedOpenProfile(host,command,options){let defaults=options?.defaults===!1?void 0:host.defaults,instanceId=host.defaults.hostContext?.host_instance??hostInstanceId();if(command.expectedHostInstance!==void 0){if(typeof command.expectedHostInstance!="string"||command.expectedHostInstance.trim()==="")return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: expectedHostInstance must be a non-empty string`,{reason:"invalid_expected_host_instance",action:"supply_host_instance"});if(command.expectedHostInstance!==instanceId)return error(command.id,"open_session",RPC_ERROR_OWNER_CHANGED,{reason:"host_instance_mismatch",action:"rediscover_holder",expectedHostInstance:command.expectedHostInstance,hostInstance:instanceId})}let kindError=sessionKindError(command.kind);if(command.attended!==void 0&&command.attended!==!1)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: attended must be false or omitted`);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 promptSurfaceError=sessionPromptSurfaceError(command.promptSurface);if(promptSurfaceError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${promptSurfaceError}`);let browserEngineError=sessionBrowserEngineError(command.browserEngine);if(browserEngineError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${browserEngineError}`);if(!command.provider!=!command.modelId)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: provider and modelId must be given together`);let retryFallbackError=sessionRetryFallbackError(command.retryFallback);if(retryFallbackError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${retryFallbackError}`);let envError=sessionEnvError(command.env);if(envError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_ENV}: ${envError}`);let sessionEnv=inheritedSessionEnv(parentSessionEnv(host,command.spawnedBy?.parentSessionId),command.env);return{cwd:command.cwd??host.defaults.cwd,...command.attended===!1?{attended:!1}:{},sessionPath:command.sessionPath,holderEndpoint:{host_instance:instanceId,...process.env[HOST_DAEMON_DIR_ENV]?{host_daemon_dir:process.env[HOST_DAEMON_DIR_ENV]}:{},...host.defaults.hostContext?.host_socket===void 0?{}:{host_socket:host.defaults.hostContext.host_socket}},permissionPreset:command.permissionPreset??defaults?.permissionPreset,...command.permissionPreset===void 0&&defaults?.permissionPreset!==void 0?{permissionPresetSource:"host_default"}:{},creationModel:command.provider&&command.modelId?{provider:command.provider,modelId:command.modelId}:defaults?.creationModel,initialThinkingLevel:command.thinkingLevel??defaults?.initialThinkingLevel,sessionKind:command.kind,sessionContext:host.defaults.hostContext?{...command.context,...host.defaults.hostContext}:command.context,...command.durableSessionId!==void 0?{durableSessionId:command.durableSessionId}:{},...typeof command.auto_title=="boolean"?{autoTitle:command.auto_title}:{},...command.promptSurface!==void 0?{promptSurface:command.promptSurface}:{},...command.browserEngine!==void 0?{browserEngine:command.browserEngine}:{},...command.retryFallback!==void 0?{retryFallback:command.retryFallback}:{},...sessionEnv!==void 0?{sessionEnv}:{}}}function parentSessionEnv(host,parentSessionId){if(parentSessionId===void 0)return;let parent=host.registry.list().find(row=>row.durableSessionId===parentSessionId||row.sessionId===parentSessionId);if(parent===void 0)return;let entry2=host.registry.peek(parent.sessionId);return entry2?.state==="open"&&host.bindings.has(parent.sessionId)?entry2.profile.sessionEnv:void 0}function holdOpenConnection(host,owner){let barrier=Promise.withResolvers(),opens=host.opensByConnection.get(owner)??new Set;return opens.add(barrier.promise),host.opensByConnection.set(owner,opens),()=>{barrier.resolve(),opens.delete(barrier.promise),opens.size===0&&host.opensByConnection.delete(owner)}}function ownOpen(host,opened,owner,compact=!1){if(owner===void 0)return;host.writer.hasRegisteredConnectionCapabilities(owner)||host.writer.setConnectionCapabilities(owner,host.pendingCapabilities.get(owner)??host.connectionOptions?.capabilities??[]),host.writer.attachConnectionToSession(owner,opened.sessionId,compact);let owned=host.sessionsByConnection.get(owner)??new Map;owned.set(opened.sessionId,(owned.get(opened.sessionId)??0)+1),host.sessionsByConnection.set(owner,owned),host.attachOrder.attached(opened.sessionId,owner)}function publishOpen(host,opened,entry2){opened.attached?host.writer.status.publish(opened.sessionId,"attach","client"):(host.writer.publishSessionOpened({type:"session_opened",sessionId:opened.sessionId,durableSessionId:opened.durableSessionId,...opened.sessionPath!==void 0?{sessionPath:opened.sessionPath}:{},kind:entry2.kind,cwd:entry2.cwd,context:entry2.context}),host.writer.status.publish(opened.sessionId,"open","client"))}function replyOpen(host,opened,entry2,command,reply=!0,beside={}){let state=entry2.worker?.snapshot?.state??(entry2.runtime?buildRpcSessionState(entry2.runtime.session):void 0);if(!state)throw new Error("Session state was not created");reply&&host.writer.enqueue(opened.sessionId,{id:command.id,type:"response",command:command.type,success:!0,data:{...beside,sessionId:opened.sessionId,state,...host.writer.currentConnection()?.startsWith("generation-route-")&&opened.sessionPath?{routeRow:host.registry.list().find(row=>row.sessionId===opened.sessionId),routePark:{...parkedEntryFromProfile({...opened,sessionPath:opened.sessionPath,contextOverlay:entry2.contextOverlay},entry2.profile,Object.keys(host.defaults.hostContext??{})),retainOnDisconnect:entry2.retainOnDisconnect===!0}}:{},...openReplyPermissionMode(state),...opened.attached?{attached:!0}:{},...host.defaults.sessionPresence?{presence:host.defaults.sessionPresence.view(state.sessionId)}:{}}})}function openWithBarrier(host,command,replyAs){return compactUpdatesEnabled()&&command.admissionId!==void 0?compactOpen(host,command,(accept,signal)=>openPhysicalWithBarrier(host,command,accept,signal)):openPhysicalWithBarrier(host,command,void 0,void 0,replyAs)}function openPhysicalWithBarrier(host,command,accept,signal,replyAs){let owner=host.writer.currentConnection();if(owner===void 0)return open2(host,command,void 0,{replyAs});let inFlight=0;for(let pending of host.opensByConnection.values())inFlight+=pending.size;let releaseBarrier=holdOpenConnection(host,owner);command.id!==void 0&&host.writer.sendOpenQueued(owner,{type:"queued",for_request:command.id,position:inFlight+1,in_flight:inFlight});let start=()=>open2(host,command,owner,accept===void 0?{replyAs}:{accept,signal});return(signal===void 0?start():runAdmissionProducer(signal,start,async()=>{})).finally(releaseBarrier)}function reopenParked(host,entry2){let command=parkedOpenCommand(entry2);return open2(host,entry2.live===!0?command:{...command,attended:!1},void 0,{reply:!1,defaults:!1,contextOverlay:entry2.contextOverlay,unattached:!0,...entry2.live===!0?{continued:!0}:{}})}async function open2(host,command,owner,options){let validated=validatedOpenProfile(host,command,options);if("type"in validated)return validated;let opened,timer=startOpenTimer(`host-open:${command.id??"-"}`),assertSessionNotHeld=sessionHeldCheck(observedStarts=>host.registry.holderPids?.(observedStarts)??Promise.resolve([]));try{let profile={...validated,cwd:await openSessionFolder(command,validated.cwd),...options?.continued===!0?{continued:!0}:{}};if((await stat2(profile.cwd).catch(()=>{}))?.isDirectory()===!1)return error(command.id,"open_session","session_cwd_not_directory",{cwd:profile.cwd});if(await assertSessionNotHeld(command.sessionPath),timer.mark("held_check"),options?.signal?.throwIfAborted(),invalidSpawnedBy(command))return error(command.id,"open_session","invalid_spawned_by");let ancestry=command.spawnedBy;opened=await host.registry.openSession(ancestry?{...profile,spawnedBy:ancestry}:profile,{routedHandle:host.routes.handleFor(command.sessionPath),retainOnDisconnect:command.retain_on_disconnect===!0,attachOnly:command.expectedHostInstance!==void 0,...options?.park?{speculative:!0}:{},...options?.unattached===!0?{unattached:!0}:{}}),timer.mark("registry_open"),options?.signal?.throwIfAborted();let openedSession=opened;if(host.writer.isSessionSealed(openedSession.sessionId))return await releaseOwnedSession(host,openedSession.sessionId),opened=void 0,error(command.id,"open_session","session_output_overflow",{sessionId:openedSession.sessionId,sessionPath:openedSession.sessionPath,action:"unload_and_reopen"});let entry2=host.registry.getForCommand(openedSession.sessionId,"open_session");!opened.attached&&options?.contextOverlay!==void 0&&(entry2.contextOverlay=options.contextOverlay);let state=entry2.worker?.snapshot?.state;await assertSessionNotHeld(entry2.runtime?.session.sessionFile??state?.sessionFile??entry2.sessionPath,entry2.runtime?.session.sessionId??state?.sessionId??entry2.durableSessionId),timer.mark("held_recheck"),host.writer.setSessionKind(openedSession.sessionId,entry2.kind),host.writer.setSessionMedia(openedSession.sessionId,toolMediaPersister(()=>liveToolMediaScope(entry2)));let lane=entry2.acceptance??entry2.worker?.acceptance;if(lane&&host.writer.registerAcceptance(openedSession.sessionId,lane),options?.accept&&await options.accept(openedSession),ownOpen(host,openedSession,owner,options?.accept!==void 0),!host.bindings.has(openedSession.sessionId)){host.bindings.set(openedSession.sessionId,await host.createBinding(openedSession.sessionId,entry2,host.writer,()=>{entry2.speculative?closePark(host,openedSession):close(host,{type:"close_session",sessionId:openedSession.sessionId})},{...host.connectionOptions,capabilities:owner!==void 0?host.pendingCapabilities.get(owner)??host.connectionOptions?.capabilities??[]:host.connectionOptions?.capabilities,connectionRoles:host.connectionRoles,clientInfo:{setCapabilities:(connectionId,capabilities)=>{connectionId!==void 0&&(host.writer.setConnectionCapabilities(connectionId,capabilities),host.pendingCapabilities.set(connectionId,[...capabilities]))},connectionId:()=>host.writer.currentConnection(),relocationConnection:()=>relocationConnection(host,openedSession.sessionId),deliverTo:(connection2,deliver)=>host.writer.withConnection(connection2,deliver)}})),timer.mark("binding"),entry2.worker&&(entry2.worker.bindingReady=!0);let settled=()=>{host.draining&&queueMicrotask(()=>sweepDrain(host))};typeof entry2.worker?.subscribeSettled=="function"?entry2.worker.subscribeSettled(settled):typeof entry2.runtime?.session.subscribe=="function"&&entry2.runtime.session.subscribe(event=>{event.type==="agent_idle"&&settled()}),entry2.worker&&entry2.worker.exited.then(async()=>{await host.finalizations.get(openedSession.sessionId)?.promise,host.bindings.delete(openedSession.sessionId),forgetSessionOwnership(host,openedSession.sessionId),host.writer.forgetSession(openedSession.sessionId)})}if(options?.signal?.throwIfAborted(),options?.park){options.park(openedSession);return}if(publishOpen(host,openedSession,entry2),host.routes.adopt(openedSession.sessionId),!options?.accept&&!host.draining&&owner!==void 0&&host.releasedConnections.has(owner)&&(releaseOwnerAttachment(host,owner,openedSession.sessionId),await releaseOwnedSession(host,openedSession.sessionId)),await syncRetainedRecord(host,openedSession.sessionId,command.sessionPath),options?.accept)return;timer.mark("reply"),replyOpen(host,opened,entry2,options?.replyAs?.command??command,options?.reply!==!1,options?.replyAs?.data);return}catch(cause){if(opened){if(!options?.park&&!opened.attached&&!options?.signal?.aborted){let entry2=host.registry.peek(opened.sessionId);(entry2?.runtime!==void 0||entry2?.worker!==void 0)&&host.writer.sealRolledBackOpen(opened.sessionId,entry2.sessionPath)}try{opened.attached?await releaseOwnedSession(host,opened.sessionId):await host.registry.close(opened.sessionId)}catch{}(!opened.attached||!compactUpdatesEnabled())&&host.writer.forgetSession(opened.sessionId)}if(cause instanceof CompactAdmissionError)throw cause;if(!opened&&owner&&command.expectedHostInstance&&!host.draining&&!options?.accept&&code(cause)==="session_not_held"&&!owner.startsWith("generation-route-")){let attached=await host.routes.attachPath(command,owner);if(attached)return attached}if(!opened&&owner&&!host.draining&&!options?.park&&!options?.accept&&code(cause)==="session_path_in_use"){let routed=await host.routes.open(command,owner,detail(cause));if(routed===RETRY_ROUTED_OPEN&&host.writer.hasConnection(owner)&&!host.draining){let routedSince=options?.routedSince??Date.now();return Date.now()-routedSince<=host.registry.closeGraceMs?open2(host,command,owner,{...options,routedSince}):error(command.id,"open_session",code(cause),detail(cause))}if(routed===RETRY_ROUTED_OPEN)return error(command.id,command.type,"host_draining");if(routed)return routed}return error(command.id,"open_session",code(cause),detail(cause))}}function profileKey(profile){return JSON.stringify([profile.cwd,profile.sessionKind??"interactive",Object.entries(profile.sessionContext??{}).sort(([a],[b])=>a.localeCompare(b))])}async function buildPark(host,command){let opened,response=await outsideCommand(()=>host.writer.connectionContext.outside(()=>withoutOpenTiming(()=>open2(host,{...command,type:"open_session"},void 0,{reply:!1,park:result=>{opened=result}}))));if(response&&!response.success)throw new Error(response.error);if(!opened)throw new Error("park_open_failed");return opened}async function closePark(host,opened){tryClaimClose(host,opened.sessionId,{drainAttachments:!0})?.finalizer?await finalizeClose(host,opened.sessionId,host.bindings.get(opened.sessionId)):await host.finalizations.get(opened.sessionId)?.promise,host.writer.forgetSession(opened.sessionId)}async function parkSession(host,command){if(!host.registry.supportsParkClaim)return error(command.id,command.type,"park_claim_unsupported");if(host.draining||host.drainExitRequested)return error(command.id,command.type,"host_draining");let profile=validatedOpenProfile(host,{...command,type:"open_session"});if("type"in profile)return{...profile,command:command.type};try{let state=await host.parks.park(profileKey(profile),()=>buildPark(host,command));return host.draining||host.drainExitRequested?error(command.id,command.type,"host_draining"):{id:command.id,type:"response",command:command.type,success:!0,data:{state}}}catch(cause){return error(command.id,command.type,code(cause))}}function claimSession(host,command){let owner=host.writer.currentConnection(),release=owner===void 0?void 0:holdOpenConnection(host,owner);return claimReady(host,command,owner).finally(release)}async function claimReady(host,command,owner){if(!host.registry.supportsParkClaim||!host.registry.claimPark)return error(command.id,command.type,"park_claim_unsupported");if(host.draining||host.drainExitRequested)return error(command.id,command.type,"host_draining");let miss=()=>({id:command.id,type:"response",command:"claim_session",success:!0,data:{claimed:!1}});if(command.sessionPath!==void 0||command.durableSessionId!==void 0||command.expectedHostInstance!==void 0||command.admissionId!==void 0||command.attended===!1||command.retry!==void 0||command.provider!==void 0!=(command.modelId!==void 0)||command.spawnedBy!==void 0||command.env!==void 0||command.auto_title!==void 0||command.retryFallback!==void 0||owner!==void 0&&host.writer.compactSelection(owner)?.selected)return miss();let profile=validatedOpenProfile(host,{...command,type:"open_session"});if("type"in profile)return{...profile,command:command.type};let key=profileKey(profile),opened=host.parks.take(key);if(!opened)return miss();let success=!1;try{let entry2=host.registry.peek(opened.sessionId);if(entry2?.state!=="open"||!entry2.runtime)return miss();let runtime=entry2.runtime,ctx={session:runtime.session,sessionId:opened.sessionId,by:{connectionId:owner??"host"}};if(await runWithProviderScope(entry2.scope,async()=>{let responses=[];command.provider!==void 0&&command.modelId!==void 0&&responses.push(await runSetModel(ctx,{type:"set_model",provider:command.provider,modelId:command.modelId,scope:"session"})),command.thinkingLevel!==void 0&&responses.push(await runSetThinkingLevel(ctx,{type:"set_thinking_level",level:command.thinkingLevel,scope:"turn"})),command.permissionPreset!==void 0&&responses.push(runSetPermissionPreset(runtime,{type:"set_permission_preset",permissionPreset:command.permissionPreset}));let refused4=responses.find(response=>!response.success);if(refused4&&!refused4.success)throw new Error(refused4.error);applyAttachedProfile(entry2,{...profile,permissionPreset:void 0,permissionPresetSource:void 0}),runtime.launchProfile&&(entry2.profile=runtime.launchProfile)}),host.draining||host.drainExitRequested||owner!==void 0&&host.releasedConnections.has(owner))return miss();let claimed=await host.registry.claimPark(opened.sessionId,command.retain_on_disconnect===!0);if(host.draining||host.drainExitRequested)return miss();entry2.acceptance?.applyTranscript(runtime.session.sessionManager.drainTranscript()),ownOpen(host,claimed,owner),host.bindings.get(claimed.sessionId)?.setClientCapabilities?.((owner===void 0?void 0:host.pendingCapabilities.get(owner))??host.connectionOptions?.capabilities??[]),publishOpen(host,claimed,entry2),await syncRetainedRecord(host,claimed.sessionId,void 0),replyOpen(host,claimed,entry2,command),success=!0,owner!==void 0&&host.releasedConnections.has(owner)&&(releaseOwnerAttachment(host,owner,claimed.sessionId),await releaseOwnedSession(host,claimed.sessionId));return}catch(cause){return error(command.id,command.type,code(cause))}finally{if(success||await closePark(host,opened),host.parks.finish(key),success){let replacement={type:"park_session",cwd:command.cwd,kind:command.kind,context:command.context};host.parks.replace(key,()=>buildPark(host,replacement))}}}var RouterContext=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.routes=new PredecessorRoutes(this),this.parks=new HostParkLedger(opened=>closePark(this,opened)),this.admissions=compactUpdatesEnabled()?new CompactAdmissions(ADMISSION_LIMITS,(socketEpoch,admissionId)=>this.writer.routesAdmission(socketEpoch,admissionId)):void 0,this.bindings=new Map,this.sessionsByConnection=new Map,this.attachOrder=new SessionAttachOrder,this.opensByConnection=new Map,this.releasedConnections=new Set,this.pendingCapabilities=new Map,this.connectionRoles=new ConnectionRoles,this.finalizations=new Map,this.draining=!1,this.handoffParks=0,this.drainExitRequested=!1,this.handoffClosed=new Set,this.drainHeldSessions=new Set,this.activeRequests=new Map,this.requestSettledListeners=new Map,this.memoryPressure=!1,this.inheritedHandover=void 0,this.releaseTeardown=(sessionId,sessionPath)=>tearDownReleased(this,sessionId,sessionPath),this.stopLimitBroadcast=subscriptionLimits.subscribe(limits=>writer.broadcastHostRecord({type:"subscription_limits",...limits})),this.registry=registry,this.writer=writer,writer.originOf=connection2=>this.connectionRoles.originOf(connection2),this.connectionRoles.useDelegations(connection2=>writer.delegations.viewOf(connection2)),this.defaults=defaults,this.awaitingPredecessorScan=idle?.handoverParkedDir!==void 0&&hostGeneration(process.env)>0,this.createBinding=createBinding,this.connectionOptions={...connectionOptions,capabilities:connectionOptions.capabilities&&advertisedCompactCapabilities(connectionOptions.capabilities,!1)},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.handoverParkedDir=idle?.handoverParkedDir,this.canExitWhenEmpty=idle?.canExitWhenEmpty,writer.status.setSource(registryStatusSource(registry)),writer.status.setLastEffectProvider(sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session===void 0)return;let latest=latestSessionEffect(session);return latest===void 0?void 0:{effectId:latest.effectId,kind:latest.kind,state:latest.state}}),writer.afterRecord=sessionId=>{followRetainedRecord(this,sessionId);let session=this.registry.peek(sessionId)?.runtime?.session;if(session!==void 0)for(let status of drainSessionEffects(session))this.writer.status.publishEffect(sessionId,status)},this.uninstallEffectSink=installSessionEffectSink({owns:session=>routingIdOf(this,session)!==void 0,flush:(session,statuses)=>{let sessionId=routingIdOf(this,session);if(sessionId!==void 0)for(let status of statuses)this.writer.status.publishEffect(sessionId,status)}}),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(()=>sweepIdleSessions(this),tickMs),this.sweepTimer.unref?.()}}compactAvailable(){return!this.awaitingPredecessorScan&&!this.inheritedHandover?.predecessorDraining&&this.registry.supportsCompact?.()===!0}};async function detachConnection(command,connectionId,release){if(connectionId===void 0)return{id:command.id,type:"response",command:"detach_connection",success:!1,error:"detach_connection needs a socket connection"};let deferred=await release(connectionId);return{id:command.id,type:"response",command:"detach_connection",success:!0,data:{deferred:[...deferred]}}}function invalidCompactAdmission(command){if(!compactUpdatesEnabled()||command.type!=="cancel_attempt"&&command.type!=="reset_stream"&&!("admissionId"in command))return;let id="admissionId"in command?command.admissionId:void 0;if(!(typeof id=="string"&&parseBoundedId(id).ok))return error(command.id,command.type,"admission_malformed_request",{kind:"request_refused",reason:"malformed_request",hint:"new_request"})}function unknownCompactAdmission(host,command){if(!host.admissions||command.admissionId===void 0||command.type==="open_session"||command.type==="claim_session"||command.type==="attach_session"||command.type==="subscribe_sessions"||command.type==="get_recovery_page"||command.type==="release_recovery")return;let admissionId=command.admissionId,peer=host.writer.currentConnection(),epoch=peer===void 0?void 0:host.writer.socketEpochOf(peer);if(peer!==void 0&&host.writer.holdsAdmission(peer,admissionId,"sessionId"in command?command.sessionId:void 0))return;let refusal4={id:command.id,type:"response",command:command.type,success:!1,error:"unknown_admission",errorCode:"unknown_admission",errorData:{code:"unknown_admission",admissionId},code:"unknown_admission",admissionId};return command.type==="cancel_attempt"&&epoch!==void 0?host.admissions.pending(epoch,admissionId).then(pending=>pending?void 0:refusal4,cause=>{if(!(cause instanceof CompactAdmissionError))throw cause;return error(command.id,command.type,`admission_${cause.reason}`,{kind:"request_refused",reason:cause.reason,hint:"new_request"})}):refusal4}import{createHash as createHash4}from"node:crypto";function statusSnapshot(events,socketEpoch,admissionId,sessionId,rows){let chunks=function*(){yield'{"seq":0,"snapshot":[';let comma="";for(let row of rows())yield comma,yield*jsonChunks(row,FRAGMENT_MAX_BYTES/2),comma=",";yield"]}"},minted=events.mint({socketEpoch,sessionId,admissionId},{sessionEpoch:hostInstanceId(),sequence:0},{},{chunks});if(!minted.ok)throw new CompactAdmissionError("storage_unavailable");return minted.value}async function compactSubscribe(host,command){let peer=host.writer.currentConnection(),socketEpoch=peer===void 0?void 0:host.writer.socketEpochOf(peer),events=host.writer.recoveryEvents,{admissionId,id,retry,...request}=command;if(peer===void 0||socketEpoch===void 0||!events||!host.admissions||admissionId===void 0)return error(id,command.type,"unsupported_transport");let fingerprint=createHash4("sha256").update(JSON.stringify(Object.entries(request).sort(([a],[b])=>a.localeCompare(b)))).digest("hex"),delivery,baseline,cancelledAnswer=async()=>(await host.admissions?.result(socketEpoch,admissionId))?.state==="cancelled"?{id,type:"response",command:command.type,success:!1,code:"attempt_cancelled",errorCode:"attempt_cancelled",error:"attempt_cancelled",admissionId,generation:0}:void 0;try{let identity={peer,socketEpoch,admissionId,fingerprint,retry:retry===!0},answer4=await host.admissions.run(identity,async()=>{let lease,subscribed=answerSubscribeSessions(command,peer,host.writer.status,(rows,subscriptionId2)=>{host.writer.registerSubscription(peer,admissionId,subscriptionId2),lease=statusSnapshot(events,socketEpoch,admissionId,subscriptionId2,rows)}),subscriptionId=subscribed.activate;if(!subscribed.answer.success||subscribed.answer.command!=="subscribe_sessions"||subscriptionId===void 0)return{answer:{...subscribed.answer},release:async()=>{}};if(lease===void 0)throw new CompactAdmissionError("storage_unavailable");let pending=host.writer.status.pendingBuffer(subscriptionId);if(!pending)throw new CompactAdmissionError("storage_unavailable");let eventLease=lease,identity2={sessionId:subscriptionId,admissionId,generation:0};delivery=Promise.withResolvers();let reply=delivery.promise,live=!0,installed=!1;baseline=()=>{installed||(installed=!0,host.writer.installAdmissionBaseline(peer,admissionBaseline(reply,{...identity2,eventLease,componentRef:"record"},()=>live),()=>host.writer.socketEpochOf(peer)===socketEpoch))};let{snapshot:_snapshot,...data2}=subscribed.answer.data;return{answer:{...subscribed.answer,...identity2,data:{...data2,recovery:eventLease}},activate:()=>{baseline?.(),host.writer.status.activate(subscriptionId)},refusal:()=>pending.reason===void 0?void 0:{...error(void 0,command.type,pending.reason,{kind:"request_refused",reason:pending.reason,hint:"new_request"}),admissionId,generation:0},release:async()=>{live&&(live=!1,host.writer.unregisterSubscription(peer,subscriptionId),host.writer.status.unsubscribe(peer,subscriptionId),events.abandon(socketEpoch,eventLease.id))}}});if(host.writer.socketEpochOf(peer)!==socketEpoch){delivery?.resolve(void 0);return}let response={...await cancelledAnswer()??answer4,id};delivery?(baseline?.(),delivery.resolve(response)):await host.writer.enqueueControl(response,peer);return}catch(cause){if(!(cause instanceof CompactAdmissionError))throw cause;let refusal4=await cancelledAnswer()??error(id,command.type,`admission_${cause.reason}`,{kind:"request_refused",reason:cause.reason,hint:"new_request"});if(delivery){baseline?.(),delivery.resolve({...refusal4});return}return refusal4}}async function resetStream(host,command){let peer=host.writer.currentConnection(),socketEpoch=peer===void 0?void 0:host.writer.socketEpochOf(peer),{sessionId,admissionId}=command,refused4=()=>error(command.id,command.type,"recovery_unknown_token",{kind:"repair_needed",reason:"unknown_token"});if(!host.admissions||peer===void 0||socketEpoch===void 0||sessionId===void 0)return refused4();let result=await host.admissions.result(socketEpoch,admissionId);if(result?.state!=="complete"||result.answer.sessionId!==sessionId&&!host.writer.isCompactSubscription(peer,admissionId,sessionId))return refused4();let checkpoints=host.writer.recoveryCheckpoints,caller={socketEpoch,sessionId},stream=checkpoints.stream(caller),lane=host.writer.recoveryLane(sessionId);if(!lane||!stream?.routes.includes(admissionId))return refused4();let routeKind=host.writer.isCompactSubscription(peer,admissionId,sessionId)?"mirror":"ordinary",frozen=checkpoints.freeze({...caller,peer,admissionId,routeKind},lane);if(!frozen.ok)return error(command.id,command.type,`recovery_${frozen.failure.kind}`,{...frozen.failure});let token=frozen.value.token,generation=token.admission.generation,answer4={id:command.id,type:"response",command:"reset_stream",success:!0,sessionId,admissionId,generation,data:{recovery:{token:token.id,componentRef:"manifest"}}};host.writer.installAdmissionBaseline(peer,admissionBaseline(Promise.resolve(answer4),{sessionId,admissionId,generation,token:token.id},()=>!0,stream.routes),()=>host.writer.socketEpochOf(peer)===socketEpoch)}import{createHmac,randomBytes as randomBytes2,randomInt}from"node:crypto";var repairAdviceKey=randomBytes2(32),tokenRetryAfterMs=token=>100+createHmac("sha256",repairAdviceKey).update(token,"utf8").digest().readUInt32BE(0)%1901,codeOf=failure2=>failure2.kind==="request_refused"?`recovery_${failure2.reason}`:`recovery_${failure2.kind}`;function callerOf(writer,command){let{id,type,sessionId}=command;if(sessionId===void 0)return error(id,type,RPC_ERROR_MISSING_SESSION_ID);let connection2=writer.currentConnection(),socketEpoch=connection2===void 0?void 0:writer.socketEpochOf(connection2);return socketEpoch===void 0?error(id,type,RPC_ERROR_UNSUPPORTED_TRANSPORT):{socketEpoch,sessionId}}function refused2(id,type,reason){let failure2={kind:"request_refused",reason,hint:"new_request"};return error(id,type,codeOf(failure2),{...failure2})}async function answerRecoveryPage(pages,writer,command){let caller=callerOf(writer,command);if("type"in caller)return caller;let{id,type}=command,lane=writer.recoveryLane(caller.sessionId),outcome;try{outcome=await pages.request(caller,command)}catch(cause){if(!(cause instanceof CompactStorageReadError||cause instanceof CompactReadError))throw cause;outcome={ok:!1,failure:storageUnavailable("unavailable")}}let source=!outcome.ok&&(outcome.failure.kind==="request_refused"||outcome.failure.reason==="unknown_token")?void 0:lane,healthRevision=null;try{source&&(healthRevision=await source.staging.store.health.revision())}catch(cause){if(!(cause instanceof Error))throw cause;outcome={ok:!1,failure:storageUnavailable("unavailable")}}let failure2=outcome.ok?void 0:outcome.failure;if(failure2?.kind==="request_refused")return error(id,type,codeOf(failure2),{...failure2});let repair={state:failure2?.kind??"ok",healthRevision,source:source?{sessionEpoch:source.sessionEpoch,sequence:source.acceptedSequence}:null,hint:"restart_from_catalog",retryAfterMs:outcome.ok?0:failure2?.reason==="unknown_token"?tokenRetryAfterMs("lease"in command?command.lease.id:command.token):randomInt(100,2001)},ordinary=writer.ordinaryRoute(writer.currentConnection()??"",caller.sessionId),generation=outcome.ok&&"generation"in outcome.value?outcome.value.generation:ordinary?.routes.includes(command.admissionId)?ordinary.generation:writer.isCompactSubscription(writer.currentConnection()??"",command.admissionId,caller.sessionId)?0:void 0;return outcome.ok?{id,type:"response",command:type,success:!0,...generation!==void 0?{sessionId:caller.sessionId,admissionId:command.admissionId,generation}:{},data:{...outcome.value,repair}}:error(id,type,codeOf(outcome.failure),{...outcome.failure,repair})}function answerReleaseRecovery(events,writer,command){let caller=callerOf(writer,command);if("type"in caller)return caller;let{id,type,lease,admissionId}=command,kind=lease?.kind;if(kind==="checkpoint")return refused2(id,type,"lease_kind_unsupported");if(kind!=="event"||typeof lease?.id!="string"||typeof admissionId!="string")return refused2(id,type,"malformed_request");let outcome=events.release(caller,lease.id,admissionId);return outcome.ok?(writer.unregisterSubscription(writer.currentConnection()??"",caller.sessionId),{id,type:"response",command:type,success:!0,data:outcome.value}):error(id,type,codeOf(outcome.failure),{...outcome.failure})}var UNSUPPORTED="hand_selection_unsupported";function sessionOf(host,sessionId){return host.registry.peek(sessionId)?.runtime?.session}function answerListHands(host,command){let selection=host.defaults.handSelection;if(selection===void 0)return error(command.id,command.type,UNSUPPORTED);let hands=selection.hands().map(({device,label,platform,reachable})=>({device,label,platform,reachable}));if(command.sessionId===void 0)return{id:command.id,type:"response",command:"list_hands",success:!0,data:{hands}};let session=sessionOf(host,command.sessionId);return session===void 0?error(command.id,command.type,RPC_ERROR_UNKNOWN_SESSION):{id:command.id,type:"response",command:"list_hands",success:!0,data:{hands,selected:selection.selected(session.sessionId)}}}function answerSelectHand(host,command){let selection=host.defaults.handSelection;if(selection===void 0)return error(command.id,command.type,UNSUPPORTED);let session;try{session=host.registry.getForCommand(command.sessionId,command.type).runtime?.session}catch(cause){return error(command.id,command.type,code(cause),detail(cause))}if(session===void 0)return error(command.id,command.type,RPC_ERROR_UNKNOWN_SESSION);let outcome=selection.select(session.sessionId,session,command.device);return outcome.ok?{id:command.id,type:"response",command:"select_hand",success:!0,data:{sessionId:command.sessionId,selected:command.device}}:error(command.id,command.type,outcome.refusal,{device:command.device})}function afterCommitRefusal(host,command,owner){if(host.draining||host.drainExitRequested)return error(command.id,command.type,"session_busy_lifecycle",{reason:"host_draining"});if(!host.writer.hasConnection(owner)||host.releasedConnections.has(owner))return error(command.id,command.type,"session_not_attached",{reason:"no_connection"});if(host.registry.peek(command.sessionId)?.state!=="open"||!host.bindings.has(command.sessionId))return error(command.id,command.type,"unknown_session",{})}function takeOtherHolds(host,sessionId,owner){let taken=[];for(let[connection2,owned]of[...host.sessionsByConnection]){let holds=connection2===owner?0:owned.get(sessionId)??0;for(let hold=0;hold<holds;hold++)releaseOwnerAttachment(host,connection2,sessionId);holds>0&&taken.push([connection2,holds])}return taken}async function takeOver(host,command,owner,attach3){let ledger=host.defaults.sessionTakeover;if(host.defaults.sessionOwner!=="machine"||ledger===void 0)return error(command.id,command.type,"takeover_unsupported",{reason:"only a headless engine with a takeover ledger takes sessions over"});if(typeof command.holder!="string"||command.holder.length===0)return error(command.id,command.type,"takeover_holder_required",{});let record;try{record=await ledger.takeOver(command.durableSessionId,command.holder)}catch(cause){return error(command.id,command.type,"takeover_failed",{reason:cause instanceof Error?cause.message:String(cause)})}let refused4=afterCommitRefusal(host,command,owner);if(refused4!==void 0)return refused4;try{attach3()}catch(cause){return error(command.id,command.type,code(cause),detail(cause)??{})}let taken=takeOtherHolds(host,command.sessionId,owner),released={type:"session_released",sessionId:command.sessionId,reason:"taken_over"};for(let[connection2,holds]of taken){host.writer.hasConnection(connection2)&&await host.writer.enqueueControl(released,connection2);for(let hold=0;hold<holds;hold++)await releaseDisconnectAttachment(host,command.sessionId)}return{id:command.id,type:"response",command:command.type,success:!0,data:{sessionId:command.sessionId,attached:!0,holder:record.holder,generation:record.generation,released:taken.length}}}function identityMatches(host,entry2,durableSessionId,expectedHostInstance){let durable=entry2.runtime?.session.sessionId??entry2.worker?.snapshot?.state.sessionId??entry2.durableSessionId;return typeof durableSessionId=="string"&&durableSessionId.length>0&&durableSessionId===durable&&(expectedHostInstance===void 0||expectedHostInstance===(host.defaults.hostContext?.host_instance??hostInstanceId()))}function hostStopping(host){return host.draining||host.drainExitRequested}function drainingRefusal(host,command){if(!(!hostStopping(host)||command.type==="attach_session"&&host.writer.currentConnection()?.startsWith("generation-route-")&&command.expectedHostInstance!==void 0))return error(command.id,command.type,"session_busy_lifecycle",{reason:"host_draining"})}function attach2(host,owner,sessionId){if(!host.registry.attachSession)throw new Error("live attachment is unavailable");host.registry.attachSession(sessionId),recordAttachment(host,owner,sessionId),host.writer.status.publish(sessionId,"attach","client")}function attachSession(host,command){let draining=drainingRefusal(host,command);if(draining)return draining;let entry2=host.registry.peek(command.sessionId);if(entry2?.state!=="open"||!host.bindings.has(command.sessionId))return error(command.id,command.type,"unknown_session",{});if(!identityMatches(host,entry2,command.durableSessionId,command.expectedHostInstance))return error(command.id,command.type,"session_identity_mismatch",{});let owner=host.writer.currentConnection();if(owner===void 0)return error(command.id,command.type,"session_not_attached",{reason:"no_connection"});if(command.takeover===!0)return takeOver(host,command,owner,()=>attach2(host,owner,command.sessionId));if(command.admissionId!==void 0&&host.admissions)return compactOpen(host,command,async(accept,signal)=>{signal.throwIfAborted(),attach2(host,owner,command.sessionId);try{await accept({sessionId:command.sessionId,durableSessionId:command.durableSessionId,attached:!0})}catch(cause){throw releaseOwnerAttachment(host,owner,command.sessionId),await releaseDisconnectAttachment(host,command.sessionId),cause}});try{return attach2(host,owner,command.sessionId),{id:command.id,type:"response",command:command.type,success:!0,data:{sessionId:command.sessionId,attached:!0}}}catch(cause){return error(command.id,command.type,code(cause),detail(cause)??{})}}async function releaseAttachment(host,command){let owner=host.writer.currentConnection();if(owner===void 0||!host.sessionsByConnection.get(owner)?.has(command.sessionId))return error(command.id,command.type,"session_not_attached",{reason:"not_attached"});releaseOwnerAttachment(host,owner,command.sessionId);let deferred=!hostStopping(host)&&await releaseDisconnectAttachment(host,command.sessionId);return{id:command.id,type:"response",command:command.type,success:!0,data:{deferred}}}async function reclaimSession(host,command){let draining=drainingRefusal(host,command);if(draining)return draining;if(typeof command.sessionPath!="string"||command.sessionPath.length===0)return error(command.id,command.type,"unknown_session",{});let key=canonicalSessionPath(command.sessionPath),row=host.registry.list().find(candidate2=>candidate2.sessionPath!==void 0&&canonicalSessionPath(candidate2.sessionPath)===key),entry2=row&&host.registry.peek(row.sessionId);if(!row||!entry2)return error(command.id,command.type,"unknown_session",{});if(entry2.state!=="open"||!host.bindings.has(row.sessionId))return error(command.id,command.type,"session_busy_lifecycle",{});if(typeof command.expectedHostInstance!="string"||!identityMatches(host,entry2,command.durableSessionId,command.expectedHostInstance))return error(command.id,command.type,"session_identity_mismatch",{});let owner=host.writer.currentConnection();if(owner===void 0)return error(command.id,command.type,"session_not_attached",{reason:"no_connection"});let own=host.sessionsByConnection.get(owner)?.get(row.sessionId)??0,elsewhere=Math.max(0,entry2.attachments-own);if(elsewhere>0)return error(command.id,command.type,"attached_elsewhere",{attachments:elsewhere});attach2(host,owner,row.sessionId);let claim=claimClose(host,row.sessionId,{drainAttachments:!0});if(host.sessionsByConnection.get(owner)?.delete(row.sessionId),host.sessionsByConnection.get(owner)?.size===0&&host.sessionsByConnection.delete(owner),connectionLeft(host,row.sessionId,owner),host.handoverParkedDir!==void 0&&await clearRetainedRecord(host,entry2),claim.finalizer){let binding2=host.bindings.get(row.sessionId);binding2?.cancelPendingExtensionUiRequests?.(),await finalizeClose(host,row.sessionId,binding2,()=>host.writer.sealLifecycle(row.sessionId,{type:"session_closed",sessionId:row.sessionId,reason:"client_close"},!0))}return host.writer.detachConnectionFromSession(owner,row.sessionId),host.writer.forgetSession(row.sessionId),{id:command.id,type:"response",command:command.type,success:!0,data:{reclaimed:!0,sessionId:row.sessionId}}}import{open as open3,readdir as readdir3}from"node:fs/promises";import{join as join10}from"node:path";var FIND_SESSION_FILE_LIMIT=2e4,HEADER_READ_BYTES=64*1024,READERS=16,FindSessionTooManyError=class extends Error{constructor(limit){super(`This device keeps more than ${limit} session files, so a lookup by durable id was not run. Open the session by its path instead.`),this.code="find_session_too_many",this.name="FindSessionTooManyError"}},isRecord2=value=>typeof value=="object"&&value!==null;async function headerOf(file){let handle2;try{handle2=await open3(file,"r")}catch{return}try{let buffer=Buffer.allocUnsafe(HEADER_READ_BYTES),{bytesRead}=await handle2.read(buffer,0,HEADER_READ_BYTES,0),data2=buffer.subarray(0,bytesRead),newline=data2.indexOf(10);if(newline===-1&&bytesRead===HEADER_READ_BYTES)return;let header=JSON.parse(data2.subarray(0,newline===-1?bytesRead:newline).toString("utf8"));return!isRecord2(header)||header.type!=="session"||typeof header.id!="string"?void 0:{id:header.id,cwd:typeof header.cwd=="string"?header.cwd:""}}catch{return}finally{await handle2.close()}}async function sessionFiles(agentDir){let root=join10(agentDir,"sessions"),entries=await readdir3(root,{withFileTypes:!0}).catch(()=>[]),files=[],add=(dir,name)=>{if(name.endsWith(".jsonl")){if(files.length>=FIND_SESSION_FILE_LIMIT)throw new FindSessionTooManyError(FIND_SESSION_FILE_LIMIT);files.push(join10(dir,name))}};for(let entry2 of entries){if(entry2.isFile()&&add(root,entry2.name),!entry2.isDirectory())continue;let folder=join10(root,entry2.name);for(let name of await readdir3(folder).catch(()=>[]))add(folder,name)}return files}var RPC_ERROR_FIND_SESSION_UNSUPPORTED="find_session_unsupported",RPC_ERROR_FIND_SESSION_TOO_MANY="find_session_too_many";function answer(id,data2){return{id,type:"response",command:"find_session",success:!0,data:data2}}function refusal(id,code2,detail2){return{id,type:"response",command:"find_session",success:!1,error:code2,errorCode:code2,errorData:{detail:detail2}}}async function findSession(port,command){let durableSessionId=command.durableSessionId;if(typeof durableSessionId!="string"||durableSessionId.trim()==="")return refusal(command.id,"invalid_argument","find_session needs durableSessionId, the session's own id.");if(port.agentDir===void 0)return refusal(command.id,RPC_ERROR_FIND_SESSION_UNSUPPORTED,"This host keeps no agent directory, so it holds no session files to look in.");try{return answer(command.id,await findSessionFile({agentDir:port.agentDir,durableSessionId,hosted:port.hosted()}))}catch(cause){if(cause instanceof FindSessionTooManyError)return refusal(command.id,RPC_ERROR_FIND_SESSION_TOO_MANY,cause.message);throw cause}}async function findSessionFile(options){let files=await sessionFiles(options.agentDir),byPath=new Map;for(let row of options.hosted)row.durableSessionId!==options.durableSessionId||row.sessionPath===void 0||byPath.set(canonicalSessionPath(row.sessionPath),{sessionPath:row.sessionPath,cwd:row.cwd??"",open:!0});for(let index=0;index<files.length;index+=READERS){let batch=files.slice(index,index+READERS),headers=await Promise.all(batch.map(file=>headerOf(file)));batch.forEach((file,offset)=>{let header=headers[offset];if(header?.id!==options.durableSessionId)return;let key=canonicalSessionPath(file);byPath.has(key)||byPath.set(key,{sessionPath:file,cwd:header.cwd,open:!1})})}let found=[...byPath.values()];return found.length===0?{unknown:!0}:found.length>1?{ambiguous:!0}:{found:found[0]}}import{join as join18}from"node:path";import{readdir as readdir4}from"node:fs/promises";var SessionCopyRefusal=class extends Error{constructor(code2,detail2){super(detail2),this.name="SessionCopyRefusal",this.code=code2}};async function idTaken(dir,sessionId){return(await readdir4(dir).catch(error2=>{if(error2.code==="ENOENT")return[];throw error2})).some(name=>sessionFileNameId(name)===sessionId)}async function copySessionAs(options){let entries=await loadEntriesFromFileAsync(options.sourceFile),cwd=entries.find(entry2=>entry2.type==="session")?.cwd;if(!cwd)throw new Error(`The session at ${options.sourceFile} has no working directory in its header.`);if(headerSessionId(entries)===options.sessionId)throw new SessionCopyRefusal("invalid_move_request","The copy needs a new session id: under the source's own id it would stay read-only.");let dir=options.sessionDir(cwd);return serializeByKey(`session-copy:${dir}:${options.sessionId}`,async()=>{if(await idTaken(dir,options.sessionId))throw new SessionCopyRefusal("move_target_occupied",`A session with id ${options.sessionId} already exists in ${dir}. Copy under another id.`);let sessionPath=SessionManager.forkFrom(options.sourceFile,cwd,dir,{id:options.sessionId}).getSessionFile();if(sessionPath===void 0)throw new Error("The copy was created without a session file.");return{session_id:options.sessionId,session_path:sessionPath}})}import{copyFile,mkdir as mkdir3,readdir as readdir5,rename,rm as rm5,writeFile as writeFile3}from"node:fs/promises";import{basename,dirname as dirname3,join as join11,posix,relative as relative2,sep as sep2}from"node:path";import{realpath as realpath2}from"node:fs/promises";import{resolve as resolve3}from"node:path";async function realSessionPath(path){let absolute=resolve3(path);try{return await realpath2(absolute)}catch{return absolute}}var lockKey=resolvedPath=>`session-move:${resolvedPath}`,pathChains=new Map;function orderedRealPath(path){let key=resolve3(path),next=(pathChains.get(key)??Promise.resolve("")).then(()=>realSessionPath(path));return pathChains.set(key,next),next.then(()=>{pathChains.get(key)===next&&pathChains.delete(key)}),next}var moveLockKey=async sessionFile=>lockKey(await orderedRealPath(sessionFile));async function withSessionMoveLock2(sessionFile,step,guard){let path=await orderedRealPath(sessionFile);return serializeByKey(lockKey(path),async()=>{await guard?.();let sessionId=headerSessionId(await loadEntriesFromFileAsync(path));return sessionId===void 0?step():withSessionMoveLock(path,sessionId,step)})}function exportSessionForMoveAndRead(options,read){return withSessionMoveLock2(options.sessionFile,async()=>(await options.lockedGuard?.(),{manifest:await writeMoveBundle(options),read:await read(options.bundleDir)}),options.guard)}var MovedStateMissingError=class extends Error{constructor(dir){super(`The extension state the move release staged is missing (${dir}); the session was not exported without it. Finish the move as declined to take the session back, then release it again.`),this.name="MovedStateMissingError"}};async function writeMoveBundle(options){let{sessionFile}=options,moveId=parseMoveId(options.moveId),entries=await loadEntriesFromFileAsync(sessionFile),sessionId=parsePlainId(headerSessionId(entries),"session id"),holders=await liveSessionHolders(sessionFile,sessionId);if(holders.length>0)throw new SessionHeldError(sessionFile,holders);let ownership=sessionOwnership(entries);if(!ownership.writable&&!(ownership.state==="moving"&&ownership.moveId===moveId))throw new SessionMovedAwayError(sessionFile,ownership);if(ownership.writable){let given=typeof options.extensionStateDir=="string"?options.extensionStateDir:void 0;await assertMoveFits(sessionFile,sessionId,given,!1),(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_RELEASED,{reason:"move",move_id:moveId,session_id:sessionId,target:options.target,released_at:new Date().toISOString()})}let stateDir=typeof options.extensionStateDir=="function"?await options.extensionStateDir():options.extensionStateDir;if(stateDir!==void 0&&!await pathExists(stateDir))throw new MovedStateMissingError(stateDir);await assertMoveFits(sessionFile,sessionId,stateDir,!0);let staging=`${options.bundleDir}.partial-${process.pid}`;await rm5(staging,{recursive:!0,force:!0}),await mkdir3(join11(staging,dirname3(SESSION_BUNDLE_PATH)),{recursive:!0}),await copyFile(sessionFile,join11(staging,SESSION_BUNDLE_PATH));let sidecars=await copySidecars(dirname3(sessionFile),sessionId,staging),stateFiles=await copyExtensionState(stateDir,staging),manifest={format:MOVE_BUNDLE_FORMAT,moveId,sessionId,sessionFileName:basename(sessionFile),sourceCwd:await readSessionCwd(sessionFile)??"",repository:await readRecordedRepositoryIdentity(sessionFile),session:{path:SESSION_BUNDLE_PATH,sha256:await sha256File(join11(staging,SESSION_BUNDLE_PATH))},sidecars,droppedUserMessages:[...options.droppedUserMessages],payloads:stateFiles.length>0?[{kind:EXTENSION_STATE_PAYLOAD,files:stateFiles}]:[]};return await writeFile3(join11(staging,MANIFEST_FILE),`${JSON.stringify(manifest,null,1)}
`),await rm5(options.bundleDir,{recursive:!0,force:!0}),await rename(staging,options.bundleDir),manifest}async function assertMoveFits(sessionFile,sessionId,stateDir,sealedAlready){let sessionDir=dirname3(sessionFile),paths=(await filesUnder(join11(sessionDir,"resident-blobs",sessionId))).map(source=>bundlePath("files",sessionDir,source));if(stateDir!==void 0)for(let source of await filesUnder(stateDir))paths.push(bundlePath("state",stateDir,source));let tooDeep=paths.find(nestsTooDeep);if(tooDeep!==void 0)throw new MovePathTooDeepError(tooDeep,sealedAlready)}async function copySidecars(sessionDir,sessionId,staging){let sources=[],extensions=join11(sessionDir,"extensions"),sidecarName=`${encodedSessionId(sessionId)}.json`;if(await pathExists(extensions))for(let extension of await readdir5(extensions,{withFileTypes:!0})){let file=join11(extensions,extension.name,sidecarName);extension.isDirectory()&&await pathExists(file)&&sources.push(file)}sources.push(...await filesUnder(join11(sessionDir,"resident-blobs",sessionId)));let files=[];for(let source of sources){let path=bundlePath("files",sessionDir,source);await mkdir3(dirname3(join11(staging,path)),{recursive:!0}),await copyFile(source,join11(staging,path)),files.push({path,sha256:await sha256File(join11(staging,path))})}return files}async function copyExtensionState(dir,staging){if(dir===void 0)return[];let files=[];for(let source of await filesUnder(dir)){let path=bundlePath("state",dir,source);await mkdir3(dirname3(join11(staging,path)),{recursive:!0}),await copyFile(source,join11(staging,path)),files.push({path,sha256:await sha256File(join11(staging,path))})}return files}function bundlePath(prefix,from,source){return posix.join(prefix,...relative2(from,source).split(sep2))}async function filesUnder(dir){if(!await pathExists(dir))return[];let files=[];for(let entry2 of await readdir5(dir,{withFileTypes:!0})){let path=join11(dir,entry2.name);files.push(...entry2.isDirectory()?await filesUnder(path):[path])}return files}import{rm as rm6}from"node:fs/promises";var hook;function moveStep(step){hook?.(step)}async function requeueInput(sessionFile,moveId,texts){if(texts.length===0)return;let sessionManager=await SessionManager.openAsync(sessionFile),next=0,inputs=new SessionPendingInputs({sessionManager,nextQueuedId:()=>`move-${moveId}-${next++}`});for(let[index,text4]of texts.entries())await inputs.admit({clientMessageId:`move:${moveId}:${index}`,text:text4,mode:"followUp"},()=>{})}var MoveMismatchError=class extends Error{constructor(expected,found,what){super(`The answer is about move ${expected}, but ${what} belongs to move ${found}; nothing was changed. Finish each move with its own answer and bundle.`),this.code="move_mismatch",this.name="MoveMismatchError"}},MoveAlreadyMovedError=class extends Error{constructor(moveId){super(`The receiver revoked its copy for move ${moveId}, but this session file was already marked moved by an earlier accepted answer; nothing was changed and no copy is writable. Copy the session to a new thread to keep working from it.`),this.code="move_already_moved",this.name="MoveAlreadyMovedError"}};function finishMove(options){return withSessionMoveLock2(options.sessionFile,()=>settleMove(options),options.guard)}async function settleMove(options){let{sessionFile,bundleDir,moveId,answer:answer4}=options;if(await pathExists(bundleDir)){let bundled=(await readKeptBundle(bundleDir)).moveId;if(bundled!==moveId)throw new MoveMismatchError(moveId,bundled,"the kept bundle")}let entries=await loadEntriesFromFileAsync(sessionFile),ownership=sessionOwnership(entries);if(ownership.writable){reclaimed(entries,moveId)&&await requeueDroppedInput(sessionFile,bundleDir),await discardMoveFiles(sessionFile,bundleDir,moveId);return}if(ownership.moveId!==moveId)throw new MoveMismatchError(moveId,ownership.moveId,"the session file");if(ownership.state==="moved"){if("revoked"in answer4)throw new MoveAlreadyMovedError(moveId);await discardMoveFiles(sessionFile,bundleDir,moveId);return}let sessionId=headerSessionId(entries)??"";switch(answer4.state){case"receiving":return;case"accepted":if("revoked"in answer4){await takeBack(sessionFile,bundleDir,{move_id:moveId,session_id:sessionId,reason:"revoked"});break}(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_MOVED,{move_id:moveId,session_id:sessionId,target:ownership.target,moved_at:new Date().toISOString()}),moveStep("finish:recorded");break;case"declined":case"failed":await takeBack(sessionFile,bundleDir,{move_id:moveId,session_id:sessionId,reason:answer4.state,detail:answer4.reason});break;default:{let unreachable=answer4;throw new Error(`Unknown move answer ${JSON.stringify(unreachable)}`)}}moveStep("finish:requeued"),await discardMoveFiles(sessionFile,bundleDir,moveId)}async function takeBack(sessionFile,bundleDir,data2){(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_RECLAIMED,{...data2,reclaimed_at:new Date().toISOString()}),moveStep("finish:recorded"),await requeueDroppedInput(sessionFile,bundleDir)}async function discardMoveFiles(sessionFile,bundleDir,moveId){await rm6(bundleDir,{recursive:!0,force:!0}),await rm6(outgoingStateDir(sessionFile,moveId),{recursive:!0,force:!0})}function reclaimed(entries,moveId){return entries.some(entry2=>entry2.type==="custom"&&entry2.customType===SESSION_RECLAIMED&&entry2.data?.move_id===moveId)}async function requeueDroppedInput(sessionFile,bundleDir){if(!await pathExists(bundleDir))return;let kept=await readKeptBundle(bundleDir);await requeueInput(sessionFile,kept.moveId,kept.droppedUserMessages)}import{constants as constants2}from"node:fs";import{open as open4,realpath as realpath3}from"node:fs/promises";import{dirname as dirname4}from"node:path";var SCAN_LIMIT_BYTES2=1024**3,MAX_LINE_BYTES=1024*1024,CHUNK_BYTES2=256*1024,NEWLINE=10,MARKER=Buffer.from(JSON.stringify(REPOSITORY_IDENTITY_ENTRY_TYPE)),READ_FLAGS=constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK,MoveIdentityUnreadableError=class extends Error{constructor(){super("No session file of this device is at that path, or it cannot be read; nothing was read."),this.name="MoveIdentityUnreadableError"}},MoveIdentityTooLargeError=class extends Error{constructor(){super(`This session file is larger than the ${SCAN_LIMIT_BYTES2} bytes this read scans, so its recorded repository was not read. The move can still be sent without the check.`),this.name="MoveIdentityTooLargeError"}},isRecord3=value=>typeof value=="object"&&value!==null;function parsed(line){try{return JSON.parse(line.toString("utf8"))}catch{return}}function isSessionHeader(line){let entry2=parsed(line);return isRecord3(entry2)&&entry2.type==="session"&&typeof entry2.id=="string"}function identityIn(line){if(line.indexOf(MARKER)===-1)return;let entry2=parsed(line);if(!(!isRecord3(entry2)||entry2.type!=="custom"||entry2.customType!==REPOSITORY_IDENTITY_ENTRY_TYPE))return parseRepositoryIdentity(entry2.data)}async function scan(handle2){let chunk=Buffer.allocUnsafe(CHUNK_BYTES2),carry=[],carried2=0,dropping=!1,header=!1,recorded,position=0,take=line=>{if(header)recorded=identityIn(line)??recorded;else if(line.length>0){if(!isSessionHeader(line))throw new MoveIdentityUnreadableError;header=!0}};for(;;){let{bytesRead}=await handle2.read(chunk,0,CHUNK_BYTES2,position);if(bytesRead===0)break;if(position+=bytesRead,position>SCAN_LIMIT_BYTES2)throw new MoveIdentityTooLargeError;let data2=chunk.subarray(0,bytesRead),start=0;for(;;){let newline=data2.indexOf(NEWLINE,start);if(newline===-1){let rest=data2.subarray(start);dropping||carried2+rest.length>MAX_LINE_BYTES?(carry=[],carried2=0,dropping=!0):rest.length>0&&(carry.push(Buffer.from(rest)),carried2+=rest.length);break}let piece=data2.subarray(start,newline);if(start=newline+1,dropping){if(dropping=!1,carry=[],carried2=0,!header)throw new MoveIdentityUnreadableError;continue}let line=carried2===0?piece:Buffer.concat([...carry,piece]);carry=[],carried2=0,take(line)}}if(carried2>0&&!dropping&&take(Buffer.concat(carry)),!header)throw new MoveIdentityUnreadableError;return recorded}async function sessionFileInside(sessionsRoot,sessionPath){let[root,file]=await Promise.all([realpath3(resolvePath(sessionsRoot)),realpath3(resolvePath(sessionPath))]).catch(()=>{throw new MoveIdentityUnreadableError});if(!file.endsWith(".jsonl")||dirname4(dirname4(file))!==root)throw new MoveIdentityUnreadableError;return file}async function readSessionRepositoryIdentity(sessionsRoot,sessionPath){let file=await sessionFileInside(sessionsRoot,sessionPath),handle2=await open4(file,READ_FLAGS).catch(()=>{throw new MoveIdentityUnreadableError});try{if(!(await handle2.stat()).isFile())throw new MoveIdentityUnreadableError;return await scan(handle2)}catch(cause){throw cause instanceof MoveIdentityTooLargeError||cause instanceof MoveIdentityUnreadableError?cause:new MoveIdentityUnreadableError}finally{await handle2.close()}}import{createHash as createHash5}from"node:crypto";import{mkdir as mkdir4,mkdtemp as mkdtemp2,readdir as readdir7,readFile as readFile4,rm as rm8,stat as stat4,writeFile as writeFile5}from"node:fs/promises";import{dirname as dirname6,join as join13,posix as posix2,relative as relative3,sep as sep3}from"node:path";import{randomBytes as randomBytes3}from"node:crypto";import{access,readdir as readdir6,rm as rm7,stat as stat3,writeFile as writeFile4}from"node:fs/promises";import{dirname as dirname5,join as join12}from"node:path";var EVERY_FOLDING={letterCase:!0,unicodeForm:!0},exists=path=>access(path).then(()=>!0,()=>!1);async function nearestFolder(path){let isFolder=await stat3(path).then(entry2=>entry2.isDirectory(),()=>!1),above=dirname5(path);return isFolder||above===path?path:nearestFolder(above)}var PROBE_FILE=/^\.name-probe-[0-9a-f]{12}-/,STALE_PROBE_MS=3600*1e3;async function sweepStaleProbes(folder){let names=await readdir6(folder).catch(()=>[]);for(let name of names.filter(entry2=>PROBE_FILE.test(entry2))){let file=join12(folder,name),modified=await stat3(file).then(entry2=>entry2.mtimeMs,()=>{});modified!==void 0&&Date.now()-modified>STALE_PROBE_MS&&await rm7(file,{force:!0}).catch(()=>{})}}async function probeNameFolding(path){let folder=await nearestFolder(path);await sweepStaleProbes(folder);let tag=`.name-probe-${randomBytes3(6).toString("hex")}-`,written=join12(folder,`${tag}A\xE9`);try{return await writeFile4(written,"",{flag:"wx"}),{letterCase:await exists(join12(folder,`${tag}a\xE9`)),unicodeForm:await exists(join12(folder,`${tag}Ae\u0301`))}}finally{await rm7(written,{force:!0})}}var segments=path=>path.split(/[\\/]/);function oneNameUnder(paths,folding){let spelled=path=>{let cased=folding.letterCase?path.toLowerCase():path;return folding.unicodeForm?cased.normalize("NFC"):cased},byName=new Map;for(let path of paths){let name=spelled(segments(path).join("/")),other=byName.get(name);if(other!==void 0&&other!==path)return`${shown(path)} and ${shown(other)} are one name`;byName.set(name,path)}for(let[name,path]of byName){let folder="";for(let segment of name.split("/").slice(0,-1)){folder=folder===""?segment:`${folder}/${segment}`;let file=byName.get(folder);if(file!==void 0&&!segments(path).join("/").startsWith(`${segments(file).join("/")}/`))return`${shown(file)} is a file where ${shown(path)} needs a folder`}}}async function refuseNamesThatFold(layouts,folder,probe=probeNameFolding){if(layouts.every(names=>oneNameUnder(names,EVERY_FOLDING)===void 0))return;let folding=await probe(folder);for(let names of layouts){let clash=oneNameUnder(names,folding);if(clash!==void 0)throw new MoveBundleInvalidError(`${clash} on the file system this host would write the bundle to`)}}var STAGING_PREFIX="inline-",STALE_STAGING_MS=60*6e4,MAX_SEGMENT_BYTES=255,MAX_PATH_BYTES=1024,sha256=bytes2=>createHash5("sha256").update(bytes2).digest("hex");async function readInlineBundle(bundleDir,limits){let found=(await filesUnder(bundleDir)).map(file=>posix2.join(...relative3(bundleDir,file).split(sep3)));if(found.length>limits.maxFiles)return;let paths=[MANIFEST_FILE,...found.filter(path=>path!==MANIFEST_FILE).sort()],bytes2=0;for(let path of paths)if(bytes2+=(await stat4(join13(bundleDir,path))).size,bytes2>limits.maxBytes)return;let files=[];for(let path of paths){let content=await readFile4(join13(bundleDir,path));files.push({path,sha256:sha256(content),base64:content.toString("base64")})}return files}var segmentsOf=path=>path.split(/[\\/]/);function staysInBundle(path){return leavesBundle(path)||path.includes("\0")||Buffer.byteLength(path)>MAX_PATH_BYTES?!1:segmentsOf(path).every(segment=>segment!==""&&segment!=="."&&Buffer.byteLength(segment)<=MAX_SEGMENT_BYTES)}function refuseFileAsFolder(sent){let files=new Set([...sent.keys()].map(path=>segmentsOf(path).join("/")));for(let path of files){let folder="";for(let segment of path.split("/").slice(0,-1))if(folder=folder===""?segment:`${folder}/${segment}`,files.has(folder))throw new MoveBundleInvalidError(`${shown(folder)} was sent as a file and as a folder`)}}function sentChecksums(files){let sent=new Map;for(let file of files){if(!staysInBundle(file.path))throw new MoveBundleInvalidError(`a sent path cannot be a file inside the bundle: ${shown(file.path)}`);if(sent.has(file.path))throw new MoveBundleInvalidError(`${shown(file.path)} was sent twice`);sent.set(file.path,file.sha256)}let manifest=files.find(file=>file.path===MANIFEST_FILE);if(manifest===void 0)throw new MoveBundleInvalidError("no manifest was sent");let text4=Buffer.from(manifest.base64,"base64");if(sha256(text4)!==manifest.sha256)throw new MoveBundleInvalidError("the manifest changed in transit");let listed=new Set([MANIFEST_FILE,...listedFiles(parseManifest(text4.toString("utf8"))).map(file=>file.path)]),unlisted=[...sent.keys()].find(path=>!listed.has(path));if(unlisted!==void 0)throw new MoveBundleInvalidError(`${shown(unlisted)} was sent but the manifest does not list it`);return refuseFileAsFolder(sent),sent}async function removeStaleStaging(incoming){for(let name of await readdir7(incoming)){if(!name.startsWith(STAGING_PREFIX))continue;let dir=join13(incoming,name),modified=await stat4(dir).then(entry2=>entry2.mtimeMs,()=>{});modified!==void 0&&Date.now()-modified>STALE_STAGING_MS&&await rm8(dir,{recursive:!0,force:!0})}}async function withStagedInlineBundle(files,incoming,use,probeFolding){let sent=sentChecksums(files);await refuseNamesThatFold([[...sent.keys()]],incoming,probeFolding),await mkdir4(incoming,{recursive:!0}),await removeStaleStaging(incoming);let dir=await mkdtemp2(join13(incoming,STAGING_PREFIX));try{for(let file of files){let to=join13(dir,...file.path.split("/"));await mkdir4(dirname6(to),{recursive:!0}),await writeFile5(to,Buffer.from(file.base64,"base64"))}return await use(dir,sent)}finally{await rm8(dir,{recursive:!0,force:!0})}}import{mkdir as mkdir5}from"node:fs/promises";import{hostname as hostname2,uptime}from"node:os";var MOVE_RECORD_LOCK_STALE_MS=1e4,LOCK_OPTIONS={realpath:!1,stale:MOVE_RECORD_LOCK_STALE_MS,update:2e3,retries:0},LOCK_WAIT_MS=15e3,MoveRecordUnlockedError=class extends Error{constructor(file){super(`Move record ${file} was written outside its lock; the write was refused.`),this.code="move_record_unlocked",this.name="MoveRecordUnlockedError"}},MoveRecordLocks=class{#held=new Map;async hold(file,fn){let held=await acquireMoveRecordLock(file);this.#held.set(file,held);try{return await fn()}finally{this.#held.delete(file),await held.release().catch(()=>{})}}assertHeld(file){let held=this.#held.get(file);if(held===void 0)throw new MoveRecordUnlockedError(file);held.assertHeld()}};async function acquireMoveRecordLock(file){let startedAt=Date.now();for(let attempt=0;;attempt+=1)try{return await lockWithLossHandling(file,{...LOCK_OPTIONS,lockfilePath:`${file}.lock`})}catch(error2){if(!isLockError(error2))throw error2;let waited=Date.now()-startedAt;if(waited>=LOCK_WAIT_MS)throw new Error(`Move record ${file} stayed locked for ${waited}ms`,{cause:error2});let delay2=Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS*2**attempt,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS);await new Promise(resolve4=>setTimeout(resolve4,delay2))}}var COMMIT_SETTLE_AFTER_MS=3*MOVE_RECORD_LOCK_STALE_MS,UPTIME_RESOLUTION_MS=2e3;function stampClock(options={}){return{now:options.now??Date.now,uptime:options.uptime??(()=>uptime()*1e3),host:options.host??hostname2()}}function stampFields(clock){return{up:Math.round(clock.uptime()),host:clock.host}}function wallAge(value,now){if(typeof value!="object"||value===null||!("at"in value)||typeof value.at!="string")return;let at=Date.parse(value.at);return Number.isNaN(at)?void 0:now-at}function machineAge(value,clock){if(typeof value!="object"||value===null||!("up"in value)||!("host"in value)||typeof value.up!="number"||value.host!==clock.host)return;let age=clock.uptime()-value.up;return age<-UPTIME_RESOLUTION_MS?void 0:Math.max(0,age)}function stampAge(value,clock){let machine=machineAge(value,clock);return machine!==void 0&&machine<COMMIT_SETTLE_AFTER_MS?machine:wallAge(value,clock.now())}function isCommitStamp(value,stamp){return typeof value!="object"||value===null||!("at"in value)?!1:value.at===stamp&&parseLanding(value).committing===!0}function parseLanding(value){if(typeof value!="object"||value===null)return{};let{target,cwd,committing}=value;return{...typeof target=="string"?{target}:{},...typeof cwd=="string"?{cwd}:{},...committing===!0?{committing:!0}:{}}}function settledAt(landing,target){return landing.cwd===void 0?{target}:{target,cwd:landing.cwd}}function moveFolder(cwd){return cwd===void 0?void 0:resolvePath(cwd)}function heldElsewhere(landing){return`it was readied for ${landing.cwd??"another folder"} and lands only there`}function settledLanding(record,committing,outcome,stampAge2){if(record?.state==="receiving"&&committing)return outcome==="absent"?stampAge2!==void 0&&stampAge2>=0&&stampAge2<COMMIT_SETTLE_AFTER_MS?void 0:{state:"failed",reason:"import_failed"}:outcome==="revoked"?{state:"accepted",revoked:!0}:{state:"accepted"};if(record?.state==="accepted"&&!("revoked"in record)&&outcome==="revoked")return{state:"accepted",revoked:!0}}function landsAt(record,landing,target){return record?.state==="receiving"&&landing.committing!==!0&&landing.target===target}function landedElsewhere(record,landing){let stored=landing.target;return record?.state==="accepted"&&"revoked"in record?"it was revoked here and never lands again":record?.state==="receiving"&&landing.committing===!0?"an import of it stopped mid-commit, and a move lands once; only the file it landed is accepted":record?.state==="accepted"?"it already landed here once, and a move lands once (a deleted copy is gone; copy the session to a new thread instead)":record?.state==="receiving"&&stored===void 0?"an older version started receiving it and where it landed is unknown; only its already landed file is accepted":stored===void 0?void 0:`it lands only as ${stored}`}import{readFile as readFile5,rename as renameFile,writeFile as writeFile6}from"node:fs/promises";import{join as join14}from"node:path";var MoveFencedError=class extends Error{constructor(moveId,record,detail2){super(`Move ${moveId} can no longer be imported here: ${detail2??`it was already answered (${record?.state??"no record"})`}.`),this.code="move_fenced",this.name="MoveFencedError",this.moveId=moveId,this.record=record}},DECLINE_REASONS=["no_record","expired","cancelled","chunk_without_ready","repository"],FAIL_REASONS=["bundle_invalid","import_failed"];function parseMoveStatus(value){let record=parseRecord(value);return record?.state==="ready"?void 0:record}function parseRecord(value){if(typeof value!="object"||value===null)return;let{state,reason}=value;if(state==="accepted"&&value.revoked===!0)return{state,revoked:!0};if(state==="receiving")return{state};if(state==="accepted")return{state};let{expiresAt}=value;if(state==="ready"&&typeof expiresAt=="string"&&!Number.isNaN(Date.parse(expiresAt)))return{state,expiresAt};let decline=DECLINE_REASONS.find(known=>known===reason);if(state==="declined"&&decline!==void 0)return{state,reason:decline};let fail3=FAIL_REASONS.find(known=>known===reason);if(state==="failed"&&fail3!==void 0)return{state,reason:fail3}}var MoveRecordFile=class{#locks;#stamp;constructor(dir,locks,stamp=()=>({})){this.dir=dir,this.#locks=locks,this.#stamp=stamp}path(moveId){return join14(this.dir,`${parseMoveId(moveId)}.json`)}async raw(moveId){try{return JSON.parse(await readFile5(this.path(moveId),"utf8"))}catch(error2){if(error2.code==="ENOENT")return;throw error2}}async read(moveId){return this.recordIn(moveId,await this.raw(moveId))}recordIn(moveId,value){if(value===void 0)return;let record=parseRecord(value);if(record===void 0)throw new Error(`Move record ${this.path(moveId)} is not a move record`);return record}async landing(moveId){return parseLanding(await this.raw(moveId))}async write(moveId,record,landing={}){let file=this.path(moveId),temp=`${file}.${process.pid}.tmp`,at=new Date().toISOString();return this.#locks.assertHeld(file),await writeFile6(temp,`${JSON.stringify({...record,...landing,at,...this.#stamp()})}
`),this.#locks.assertHeld(file),await renameFile(temp,file),at}async assertLandsAt(moveId,target){let stored=await this.raw(moveId),[record,landing]=[this.recordIn(moveId,stored),parseLanding(stored)];if(!landsAt(record,landing,target))throw new MoveFencedError(moveId,record,landedElsewhere(record,landing));return landing}async assertStampStands(moveId,stamp){this.#locks.assertHeld(this.path(moveId));let stored=await this.raw(moveId);if(isCommitStamp(stored,stamp))return;let record=parseRecord(stored),replaced=record?.state==="receiving"?"another import's commit took over its record":void 0;throw new MoveFencedError(moveId,record,replaced)}};var READY_TTL_MS=10*6e4,FINAL_STATES=["accepted","declined","failed"],MoveLedger=class{#locks=new MoveRecordLocks;#file;constructor(dir,options={}){this.dir=dir,this.clock=stampClock(options),this.#file=new MoveRecordFile(dir,this.#locks,()=>stampFields(this.clock))}prepare(moveId,folder){let cwd=moveFolder(folder);return this.locked(moveId,async()=>{let record=await this.current(moveId),landing=await this.#file.landing(moveId);if(cwd!==void 0&&landing.cwd!==void 0&&landing.cwd!==cwd)throw new MoveFencedError(moveId,record,heldElsewhere(landing));if(record===void 0){let ready={state:"ready",expiresAt:new Date(this.clock.now()+READY_TTL_MS).toISOString()};return await this.#file.write(moveId,ready,cwd===void 0?{}:{cwd}),ready}if(record.state!=="ready"&&record.state!=="receiving"&&record.state!=="accepted")throw new MoveFencedError(moveId,record);return cwd!==void 0&&landing.cwd===void 0&&landing.committing!==!0&&await this.#file.write(moveId,record,{...landing,cwd}),record})}async requireReadiedFor(moveId,cwd){let stored=await this.#file.raw(moveId),[record,landing]=[parseRecord(stored),parseLanding(stored)];if(record?.state==="ready"&&landing.cwd!==void 0&&landing.cwd!==moveFolder(cwd))throw new MoveFencedError(moveId,record,heldElsewhere(landing))}beginReceive(moveId,target,options={}){let cwd=moveFolder(options.cwd);return this.locked(moveId,async()=>{let record=await this.current(moveId),landing=await this.#file.landing(moveId),receiving=landsAt(record,landing,target);if((record?.state==="ready"||receiving)&&landing.cwd!==void 0&&landing.cwd!==cwd)throw new MoveFencedError(moveId,record,heldElsewhere(landing));if(record?.state==="ready"){await this.#file.write(moveId,{state:"receiving"},settledAt({cwd},target));return}if(receiving)return;if(record?.state==="receiving"||record?.state==="accepted")throw new MoveFencedError(moveId,record,landedElsewhere(record,landing));if(record!==void 0)throw new MoveFencedError(moveId,record);let declined={state:"declined",reason:"chunk_without_ready"};throw await this.#file.write(moveId,declined),new MoveFencedError(moveId,declined)})}expire(moveId){return this.locked(moveId,()=>this.current(moveId))}answerStatus(moveId,here){return this.locked(moveId,async()=>{let record=await this.reconcile(moveId,await this.current(moveId),here.landed);if(here.revoked===!0)return{state:"accepted",revoked:!0};if(record?.state==="accepted")return record;if(here.movedIn)return{state:"accepted"};if(record?.state==="ready")return{state:"receiving"};if(record!==void 0)return record;let declined={state:"declined",reason:"no_record"};return await this.#file.write(moveId,declined),declined})}assertHeld(moveId){this.#locks.assertHeld(this.#file.path(moveId))}decline(moveId,reason){return this.settle(moveId,{state:"declined",reason},["receiving"])}fail(moveId,reason,options={}){return this.locked(moveId,async()=>await options.unlessLanded?.()?this.current(moveId):this.settleLocked(moveId,{state:"failed",reason},[]))}commit(moveId,target,rename2,prepare){return this.locked(moveId,async()=>{await this.#file.assertLandsAt(moveId,target),await prepare?.();let landing=await this.#file.assertLandsAt(moveId,target),stamp=await this.#file.write(moveId,{state:"receiving"},{...settledAt(landing,target),committing:!0});moveStep("import:stamped");let stampStands=()=>this.#file.assertStampStands(moveId,stamp);await stampStands(),this.#locks.assertHeld(this.#file.path(moveId));let result=await rename2(stampStands);return moveStep("import:renamed"),await this.#file.write(moveId,{state:"accepted"},settledAt(landing,target)),result})}confirmLanded(moveId,target,revoked){return this.locked(moveId,async()=>{let record=await this.#file.read(moveId),landing=await this.#file.landing(moveId);if(!(record===void 0||record.state==="receiving"||record.state==="accepted")||landing.target!==void 0&&landing.target!==target)throw new MoveFencedError(moveId,record,landedElsewhere(record,landing));let marked=record?.state==="accepted"&&"revoked"in record;record?.state==="accepted"&&(marked||!revoked)||await this.#file.write(moveId,revoked?{state:"accepted",revoked:!0}:{state:"accepted"},settledAt(landing,target))})}async reconcile(moveId,record,landed){let stored=await this.#file.raw(moveId),{target,cwd,committing}=parseLanding(stored);if(landed===void 0||target===void 0)return record;let next=settledLanding(record,committing===!0,await landed(target),stampAge(stored,this.clock));return next===void 0?record:(await this.#file.write(moveId,next,settledAt({cwd},target)),next)}markRevoked(moveId){return this.locked(moveId,async()=>{let record=await this.#file.read(moveId);if(record!==void 0&&record.state!=="receiving"&&record.state!=="accepted"||record?.state==="accepted"&&"revoked"in record)return;let landing=await this.#file.landing(moveId);await this.#file.write(moveId,{state:"accepted",revoked:!0},landing.target===void 0?{}:settledAt(landing,landing.target))})}settle(moveId,next,keeps){return this.locked(moveId,()=>this.settleLocked(moveId,next,keeps))}async settleLocked(moveId,next,keeps){let record=await this.current(moveId);return record!==void 0&&(FINAL_STATES.includes(record.state)||keeps.includes(record.state))||record!==void 0&&(await this.#file.landing(moveId)).committing===!0?record:(await this.#file.write(moveId,next),next)}async current(moveId){let record=await this.#file.read(moveId);if(record?.state!=="ready"||this.clock.now()<Date.parse(record.expiresAt))return record;let expired={state:"declined",reason:"expired"};return await this.#file.write(moveId,expired),expired}locked(moveId,fn){let file=this.#file.path(moveId);return serializeByKey(file,async()=>(await mkdir5(this.dir,{recursive:!0}),this.#locks.hold(file,fn)))}};var MoveRefusedError=class extends Error{constructor(targetCwd,sourceCwd){super(`${targetCwd} is not the same repository the session was recorded in${sourceCwd===void 0?"":` (${sourceCwd})`}. Pick a checkout of the same repository, or copy the session into this folder instead.`),this.code="move_repository_mismatch",this.name="MoveRefusedError"}},MoveTargetMissingError=class extends Error{constructor(targetCwd){super(`${targetCwd} does not exist on this device. Clone the repository there, or pick a folder that holds it, then send the session again.`),this.code="workspace_missing",this.name="MoveTargetMissingError"}};async function checkoutVerdict(cwd,repository,read=readRepositoryIdentity){let folder=resolvePath(cwd);return compareRepositoryIdentities(repository,await read(folder))==="same"?"same":await pathExists(folder)?"other":"missing"}var checkoutRefusal=(verdict,targetCwd,sourceCwd)=>verdict==="missing"?new MoveTargetMissingError(targetCwd):new MoveRefusedError(targetCwd,sourceCwd);async function prepareMove(options){if(options.cwd===void 0)return options.ledger.prepare(options.moveId);let verdict=await checkoutVerdict(options.cwd,options.repository);if(verdict!=="same")throw checkoutRefusal(verdict,options.cwd);return options.ledger.prepare(options.moveId,options.cwd)}var RevokeMismatchError=class extends Error{constructor(moveId){super(`This session file is not the copy this device imported for move ${moveId}; nothing was changed. Revoke only the copy that move brought in, with that move's id.`),this.code="move_mismatch",this.name="RevokeMismatchError"}},REVOKED="revoked";function revokeImportedMove(options){return withSessionMoveLock2(options.sessionFile,async()=>{await seal(options.sessionFile,options.moveId),moveStep("revoke:sealed"),await options.ledger.markRevoked(options.moveId),moveStep("revoke:marked")},options.guard)}async function seal(sessionFile,moveId){let entries=await loadEntriesFromFileAsync(sessionFile),sessionId=headerSessionId(entries),ownership={writable:!0},latest;for(let entry2 of entries){let step=ownershipStep(ownership,entry2,sessionId);step.kind==="apply"&&(ownership=step.next,latest=entry2)}let ofThisMove=latest!==void 0&&data(latest,"move_id")===moveId;if(!(ofThisMove&&latest?.customType===SESSION_MOVED&&data(latest,"reason")===REVOKED)){if(!(ownership.writable&&ofThisMove&&latest?.customType===SESSION_MOVED_IN))throw new RevokeMismatchError(moveId);(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_MOVED,{move_id:moveId,session_id:sessionId??"",target:data(latest,"from")??"",reason:REVOKED,moved_at:new Date().toISOString()})}}function data(entry2,key){if(typeof entry2.data!="object"||entry2.data===null)return;let value=entry2.data[key];return typeof value=="string"?value:void 0}import{join as join16}from"node:path";import{copyFile as copyFile2,mkdir as mkdir6,readdir as readdir8,rm as rm9}from"node:fs/promises";import{dirname as dirname7,join as join15}from"node:path";function outcomeIn(entries,moveId){let outcome="absent";for(let entry2 of entries){if(entry2.type!=="custom")continue;let data2=entry2.data;data2?.move_id===moveId&&(entry2.customType===SESSION_MOVED_IN?outcome="moved_in":outcome==="moved_in"&&entry2.customType===SESSION_MOVED&&data2.reason===REVOKED&&(outcome="revoked"))}return outcome}async function readLanding(target,moveId){if(!await pathExists(target))return{outcome:"absent",file:"gone"};let entries=await loadEntriesFromFileAsync(target),outcome=outcomeIn(entries,moveId),header=entries.find(entry2=>entry2.type==="session");if(outcome==="absent"||header===void 0||!header.id||!header.cwd)return{outcome,file:"gone"};let ownership=sessionOwnership(entries);return{outcome,file:{sessionPath:target,sessionId:header.id,cwd:header.cwd,ownership}}}var STAGED_PAYLOADS=".payloads";function stagedName(manifest,item){return item===manifest.session?manifest.sessionFileName:item.path.replace(/^files\//,"")}function stagedNames(manifest){return[...[manifest.session,...manifest.sidecars].map(item=>stagedName(manifest,item)),...manifest.payloads.flatMap(payload=>payload.files).map(file=>`${STAGED_PAYLOADS}/${file.path}`)]}function stagedTwice(manifest){let staged=[...[manifest.session,...manifest.sidecars].map(item=>[stagedName(manifest,item),item.path]),...manifest.payloads.flatMap(payload=>payload.files).map(file=>[`${STAGED_PAYLOADS}/${file.path}`,file.path])],from=new Map;for(let[name,path]of staged){let other=from.get(name);if(other!==void 0&&other!==path)return`${shown(path)} and ${shown(other)} would be staged as one file`;from.set(name,path)}}var MoveTargetOccupiedError=class extends Error{constructor(target){super(`A session that can still be written already sits at ${target}; the moved session was not imported over it. Close or move that session first, then send it again.`),this.code="move_target_occupied",this.name="MoveTargetOccupiedError"}},movedInFor=async(file,moveId)=>(await loadEntriesFromFileAsync(file)).some(entry2=>entry2.type==="custom"&&entry2.customType===SESSION_MOVED_IN&&entry2.data?.move_id===moveId),importOutcome=async(file,moveId)=>outcomeIn(await loadEntriesFromFileAsync(file),moveId),StatusPathMismatchError=class extends Error{constructor(moveId,sessionFile){super(`${sessionFile} is not the copy this device imported for move ${moveId}; nothing was answered. Pass the session_path import returned for this move, or leave sessionPath out to answer from this device's record.`),this.code="move_mismatch",this.name="StatusPathMismatchError"}};async function answerMoveStatusAndLanding(ledger,moveId,asked){let seen={},landed=async target=>{let{outcome,file}=await readLanding(target,moveId);return seen.file=file,outcome},fromLedger=()=>ledger.answerStatus(moveId,{movedIn:!1,landed}),answer4=asked===void 0||!await pathExists(asked.file)?await fromLedger():await serializeByKey(await moveLockKey(asked.file),async()=>{let{outcome,file}=await readLanding(asked.file,moveId);if(outcome==="absent"){if(asked.as==="copy")throw new StatusPathMismatchError(moveId,asked.file);return fromLedger()}return asked.as==="landing"&&(seen.landing=file),ledger.answerStatus(moveId,{movedIn:!0,revoked:outcome==="revoked",landed})}),where=seen.file??seen.landing;return answer4.state==="accepted"&&where!==void 0?{answer:answer4,landed:where}:{answer:answer4}}async function importMovedSession(options){let manifest=await readManifest(options.bundleDir),targetCwd=resolvePath(options.targetCwd),sessionDir=options.sessionDir?normalizePath(options.sessionDir):getDefaultSessionDir(targetCwd),target=join15(sessionDir,manifest.sessionFileName),landed=async()=>await pathExists(target)&&await movedInFor(target,manifest.moveId),confirmLanded=async()=>{let revoked=await importOutcome(target,manifest.moveId)==="revoked";await options.ledger.confirmLanded(manifest.moveId,target,revoked);let landedFor=await readSessionCwd(target);if(landedFor!==void 0&&landedFor!==targetCwd)throw new MoveFencedError(manifest.moveId,revoked?{state:"accepted",revoked:!0}:{state:"accepted"},`it already landed here for ${landedFor}, and a move lands for one folder`);return{sessionFile:target}};if(await landed())return confirmLanded();await refuseNamesThatFold([listedFiles(manifest).map(file=>file.path),stagedNames(manifest)],sessionDir,options.probeNameFolding);try{let twice=stagedTwice(manifest);if(twice!==void 0)throw new MoveBundleInvalidError(twice);await verifyBundle(options.bundleDir,manifest,options.sent)}catch(error2){throw error2 instanceof MoveBundleInvalidError&&await options.ledger.fail(manifest.moveId,"bundle_invalid",{unlessLanded:landed}),error2}await options.ledger.requireReadiedFor(manifest.moveId,targetCwd);let verdict=await checkoutVerdict(targetCwd,manifest.repository,options.readIdentity);if(verdict!=="same")throw await landed()||await options.ledger.decline(manifest.moveId,"repository"),checkoutRefusal(verdict,targetCwd,manifest.sourceCwd);try{await options.ledger.beginReceive(manifest.moveId,target,{cwd:targetCwd})}catch(error2){if(error2 instanceof MoveFencedError&&await landed())return confirmLanded();throw error2}moveStep("import:received");let staging=join15(sessionDir,".move-staging",encodeURIComponent(manifest.moveId));try{let staged=await stage(options.bundleDir,manifest,staging,options.from??""),sessionFile=await options.ledger.commit(manifest.moveId,target,stampStands=>rebindSessionFile(staged,targetCwd,sessionDir,{beforeRename:stampStands}),async()=>{let assertHeld=()=>options.ledger.assertHeld(manifest.moveId);await replacePredecessor(target,manifest.sessionId,sessionDir,assertHeld),await placeExtensionState(staging,manifest,movedStateDir(target,manifest.moveId),assertHeld)});return moveStep("import:accepted"),await rm9(staging,{recursive:!0,force:!0}),{sessionFile}}catch(error2){if(error2 instanceof MoveFencedError&&await landed())return await rm9(staging,{recursive:!0,force:!0}).catch(()=>{}),confirmLanded();throw error2 instanceof MoveFencedError||await options.ledger.fail(manifest.moveId,error2 instanceof MoveBundleInvalidError?"bundle_invalid":"import_failed",{unlessLanded:landed}),error2}}async function replacePredecessor(target,sessionId,sessionDir,assertHeld){if(!await pathExists(target))return;let entries=await loadEntriesFromFileAsync(target);if(headerSessionId(entries)!==sessionId||sessionOwnership(entries).writable)throw new MoveTargetOccupiedError(target);let extensions=join15(sessionDir,"extensions");if(await pathExists(extensions))for(let extension of await readdir8(extensions,{withFileTypes:!0}))extension.isDirectory()&&(assertHeld(),await rm9(join15(extensions,extension.name,`${encodedSessionId(sessionId)}.json`),{force:!0}));assertHeld(),await rm9(join15(sessionDir,"resident-blobs",sessionId),{recursive:!0,force:!0}),assertHeld(),await rm9(target,{force:!0})}var extensionStateFiles=manifest=>manifest.payloads.filter(payload=>payload.kind===EXTENSION_STATE_PAYLOAD).flatMap(p=>p.files);async function stagePayloads(bundleDir,manifest,staging){for(let file of manifest.payloads.flatMap(payload=>payload.files)){let to=join15(staging,STAGED_PAYLOADS,file.path);if(await mkdir6(dirname7(to),{recursive:!0}),await copyFile2(join15(bundleDir,file.path),to),await sha256File(to)!==file.sha256)throw new MoveBundleInvalidError(`${file.path} changed in transit`)}}async function placeExtensionState(staging,manifest,dir,assertHeld){let files=extensionStateFiles(manifest);if(files.length!==0){assertHeld(),await rm9(dir,{recursive:!0,force:!0});for(let file of files){let to=join15(dir,file.path.slice(EXTENSION_STATE_PREFIX.length));assertHeld(),await mkdir6(dirname7(to),{recursive:!0}),assertHeld(),await copyFile2(join15(staging,STAGED_PAYLOADS,file.path),to)}}}async function stage(bundleDir,manifest,staging,from){let file=join15(staging,manifest.sessionFileName);if(!(await pathExists(file)&&await movedInFor(file,manifest.moveId))){await rm9(staging,{recursive:!0,force:!0});let listed=[manifest.session,...manifest.sidecars],stagedAt=item=>item===manifest.session?file:join15(staging,stagedName(manifest,item));for(let item of listed)await mkdir6(dirname7(stagedAt(item)),{recursive:!0}),await copyFile2(join15(bundleDir,item.path),stagedAt(item));await stagePayloads(bundleDir,manifest,staging);for(let item of listed)if(await sha256File(stagedAt(item))!==item.sha256)throw new MoveBundleInvalidError(`${item.path} changed in transit`);(await SessionManager.openAsync(file,staging)).appendCustomEntry(SESSION_MOVED_IN,{move_id:manifest.moveId,session_id:manifest.sessionId,from,bundle_sha256:manifest.session.sha256,moved_in_at:new Date().toISOString()})}return await requeueInput(file,manifest.moveId,manifest.droppedUserMessages),file}function wireLanded(landed){if(landed===void 0)return;if(landed==="gone")return{landed_file:"gone"};let{ownership}=landed,where={session_path:landed.sessionPath,session_id:landed.sessionId,cwd:landed.cwd};if(ownership.writable)return{...where,writable:!0};let sealed_by={move_id:ownership.moveId,state:ownership.state,...ownership.target===""?{}:{target:ownership.target}};return{...where,writable:!1,sealed_by}}function statusFile(named,agentDir){if(named!==void 0)switch(named.kind){case"path":return{file:named.sessionPath,as:"copy"};case"landing":{let sessionDir=named.sessionDir===void 0?getDefaultSessionDirPath(resolvePath(named.cwd),agentDir):normalizePath(named.sessionDir);return{file:join16(sessionDir,named.sessionFileName),as:"landing"}}}}async function statusAnswer(ledger,moveId,asked){let{answer:answer4,landed}=await answerMoveStatusAndLanding(ledger,moveId,asked);return answer4.state==="accepted"?{...answer4,...wireLanded(landed)}:answer4}async function landedWhenFenced(ledger,cause){if(!(cause instanceof MoveFencedError)||cause.record?.state!=="accepted")return;let read=await answerMoveStatusAndLanding(ledger,cause.moveId,void 0).catch(()=>{}),where=wireLanded(read?.landed);if(!(read===void 0||where===void 0))return"revoked"in read.answer?{...where,revoked:!0}:where}import{constants as constants3}from"node:fs";import{access as access2,stat as stat5}from"node:fs/promises";import{join as join17}from"node:path";async function sessionDirRefusal(sessionDir){if(sessionDir===void 0)return;let dir=normalizePath(sessionDir),code2=cause=>typeof cause=="object"&&cause!==null&&"code"in cause?String(cause.code):"unknown",found=await stat5(dir).then(entry2=>entry2.isDirectory()?"folder":"file",code2);if(found!=="ENOENT"){if(found==="folder"){let denied=await access2(dir,constants3.W_OK|constants3.X_OK).then(()=>{},code2);return denied===void 0?void 0:`sessionDir cannot be used (${denied}): this host cannot write there.`}return found==="file"||found==="ENOTDIR"?"sessionDir must be a folder: a file is in its place or above it.":`sessionDir cannot be used (${found}): this host could not look at it.`}}async function importMoved(parsed2,port,ledger,root){let cwd=resolvePath(parsed2.cwd),landing={targetCwd:cwd,ledger,sessionDir:parsed2.sessionDir===void 0?getDefaultSessionDir(cwd,port.agentDir):normalizePath(parsed2.sessionDir),from:parsed2.from},{sessionFile}="dir"in parsed2.bundle?await importMovedSession({...landing,bundleDir:normalizePath(parsed2.bundle.dir)}):await withStagedInlineBundle(parsed2.bundle.files,join17(root,"incoming"),(bundleDir,sent)=>importMovedSession({...landing,bundleDir,sent})),sessionId=headerSessionId(await loadEntriesFromFileAsync(sessionFile));if(sessionId===void 0)throw new Error(`The imported session at ${sessionFile} has no id in its header.`);return{session_id:sessionId,session_path:sessionFile}}async function openLanded(port,id,open5,cwd,landed){let failure2=await port.open({...open5===!0?{}:open5,type:"open_session",sessionPath:landed.session_path,cwd:resolvePath(cwd)},{command:{type:"move_session",id},data:landed}).catch(cause=>({error:cause instanceof Error?cause.message:String(cause)}));if(failure2===void 0||!("success"in failure2))return failure2;if(!failure2.success)return{error:failure2.error,...failure2.errorCode===void 0?{}:{errorCode:failure2.errorCode},...failure2.errorData===void 0?{}:{errorData:failure2.errorData}}}import{isAbsolute as isAbsolute3}from"node:path";function plainMoveId(value){try{return parseMoveId(value)}catch{return}}var text3=value=>typeof value=="string"&&value.trim()!=="",PLAIN_ID_RULE="a letter or digit, then letters, digits, '.', '_' or '-', at most 128 characters";function wellShapedRepository(value){return!isRecord4(value)||!Array.isArray(value.rootCommits)||!value.rootCommits.every(commit=>typeof commit=="string")?!1:value.originUrl===void 0||typeof value.originUrl=="string"}function parseIdentity(raw){let sessionPath=text3(raw.sessionPath)?raw.sessionPath:void 0,cwd=text3(raw.cwd)?raw.cwd:void 0;return sessionPath!==void 0&&cwd!==void 0?"identity takes sessionPath, a session file of this device, or cwd, a folder, never both.":sessionPath!==void 0?{op:"identity",sessionPath}:cwd===void 0?"identity needs sessionPath, a session file of this device, or cwd, a folder.":isAbsolute3(cwd)?{op:"identity",cwd}:"identity cwd must be an absolute path."}function parsePrepare(raw,moveId){let cwd=text3(raw.cwd)?raw.cwd:void 0;return raw.cwd!==void 0&&cwd===void 0?"prepare cwd must be a non-empty string.":cwd!==void 0&&!isAbsolute3(cwd)?"prepare cwd must be an absolute path.":raw.repository!==void 0&&cwd===void 0?"prepare needs cwd, the folder the move lands in, together with repository.":raw.repository===void 0?{op:"prepare",moveId,cwd,repository:void 0}:wellShapedRepository(raw.repository)?{op:"prepare",moveId,cwd,repository:parseRepositoryIdentity(raw.repository)}:"prepare repository must be { rootCommits: string[], originUrl?: string }, as the identity op answers it."}function parseCopy(raw){return text3(raw.sessionPath)?isPlainId(raw.sessionId)?raw.sessionDir!==void 0&&(!text3(raw.sessionDir)||!isAbsolute3(raw.sessionDir))?"sessionDir must be an absolute path.":{op:"copy",sessionPath:raw.sessionPath,sessionId:raw.sessionId,sessionDir:raw.sessionDir}:`sessionId must be a plain id: ${PLAIN_ID_RULE}.`:"copy needs sessionPath, the session file to copy."}function parseStatusFile(raw){let{sessionPath,landing}=raw;if(landing===void 0)return sessionPath===void 0?void 0:text3(sessionPath)?{kind:"path",sessionPath}:"sessionPath must be a non-empty string.";if(sessionPath!==void 0)return"status takes sessionPath or landing, not both.";if(typeof landing!="object"||landing===null||Array.isArray(landing))return"landing must be an object: cwd, sessionFileName and, if the import named one, sessionDir.";let cwd="cwd"in landing?landing.cwd:void 0,sessionFileName="sessionFileName"in landing?landing.sessionFileName:void 0,sessionDir="sessionDir"in landing?landing.sessionDir:void 0;return!text3(cwd)||!isAbsolute3(cwd)?"landing.cwd must be the absolute folder the import was given.":isSessionFileName(sessionFileName)?sessionDir!==void 0&&(!text3(sessionDir)||!isAbsolute3(sessionDir))?"landing.sessionDir must be an absolute path.":{kind:"landing",cwd,sessionFileName,sessionDir}:"landing.sessionFileName must be the session's plain file name, as the bundle's manifest names it."}var isRecord4=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),BASE64_CHARACTERS=/^[A-Za-z0-9+/]*={0,2}$/,isPaddedBase64=value=>value.length%4===0&&BASE64_CHARACTERS.test(value);function parseInlineFiles(value){if(!Array.isArray(value)||value.length>1024)return`files must be a list of at most ${1024} { path, sha256, base64 } entries.`;let files=[],bytes2=0;for(let item of value){if(!isRecord4(item))return"each file must be an object with path, sha256 and base64.";let{path,sha256:sha2562,base64}=item;if(typeof path!="string"||typeof sha2562!="string"||typeof base64!="string")return"each file needs path and sha256 as strings and base64 as padded base64.";if(bytes2+=Buffer.byteLength(base64,"base64"),bytes2>1048576)return`files hold more than the ${1048576} bytes an inline import takes; send the bundle folder instead.`;if(!isPaddedBase64(base64))return"each file needs path and sha256 as strings and base64 as padded base64.";files.push({path,sha256:sha2562,base64})}return files}var OPEN_FIELDS_THE_IMPORT_SETS=["id","type","sessionPath","cwd","admissionId"];function importBundle(raw){if(raw.files===void 0)return!text3(raw.bundleDir)||!text3(raw.cwd)||!isAbsolute3(raw.bundleDir)||!isAbsolute3(raw.cwd)?"import needs bundleDir and cwd as absolute paths.":{dir:raw.bundleDir};if(raw.bundleDir!==void 0)return"import takes bundleDir or files, not both.";let files=parseInlineFiles(raw.files);return typeof files=="string"?files:{files}}function parseImport(raw){let bundle=importBundle(raw);if(typeof bundle=="string")return bundle;if(!text3(raw.cwd)||!isAbsolute3(raw.cwd))return"import with files needs cwd as an absolute path.";let from=typeof raw.from=="string"?raw.from:void 0;if(raw.from!==void 0&&from===void 0)return"from must be a string.";if(raw.sessionDir!==void 0&&(!text3(raw.sessionDir)||!isAbsolute3(raw.sessionDir)))return"sessionDir must be an absolute path.";let{open:open5}=raw;return open5!==void 0&&open5!==!0&&!(isRecord4(open5)&&OPEN_FIELDS_THE_IMPORT_SETS.every(field=>!(field in open5)))?"open must be true or open_session fields other than id, type, sessionPath, cwd and admissionId.":{op:"import",bundle,cwd:raw.cwd,from:from??"",sessionDir:raw.sessionDir}}function parseMoveRequest(raw){let{op}=raw;if(op==="import")return parseImport(raw);if(op==="copy")return parseCopy(raw);if(op==="identity")return parseIdentity(raw);let id=plainMoveId(raw.moveId);if(id===void 0)return`moveId must be a plain id: ${PLAIN_ID_RULE}.`;switch(op){case"prepare":return parsePrepare(raw,id);case"cancel":return{op,moveId:id};case"status":{let named=parseStatusFile(raw);return typeof named=="string"?named:{op,moveId:id,named}}case"export":{let dropped=raw.droppedUserMessages??[];if(!text3(raw.sessionPath)||!text3(raw.target))return"export needs sessionPath and target.";if(!Array.isArray(dropped)||!dropped.every(item=>typeof item=="string"))return"droppedUserMessages must be the dropped.user_messages strings release_session returned.";if(raw.inline!==void 0&&raw.inline!==!0)return"inline must be true or omitted.";let cap=raw.inlineMaxBytes??1048576;if(typeof cap!="number"||!Number.isSafeInteger(cap)||cap<0)return"inlineMaxBytes must be a non-negative integer.";let inlineMaxBytes=raw.inline===!0?Math.min(cap,1048576):void 0;return{op,sessionPath:raw.sessionPath,moveId:id,target:raw.target,dropped,inlineMaxBytes}}case"finish":{let answer4=parseMoveStatus(raw.answer);return!text3(raw.sessionPath)||answer4===void 0?"finish needs sessionPath and the receiver's answer from status (receiving, accepted, declined or failed).":{op,sessionPath:raw.sessionPath,moveId:id,answer:answer4}}case"revoke":return text3(raw.sessionPath)?{op,sessionPath:raw.sessionPath,moveId:id}:"revoke needs sessionPath, the copy this host imported for the move.";default:return'op must be one of "prepare", "cancel", "status", "export", "import", "finish", "revoke", "copy" or "identity".'}}var CORE_CODES=new Set(["move_fenced","move_bundle_invalid","move_repository_mismatch","workspace_missing","move_target_occupied","move_mismatch","move_already_moved","session_moved_away","invalid_move_request"]),RENAMED_CODES={ESESSIONHELD:"session_held"},wireRecord=record=>record.state==="ready"?{state:"ready",expires_at:record.expiresAt}:record;async function moveSession(port,command){let raw={...command},parsed2=parseMoveRequest(raw);if(typeof parsed2=="string")return refusal2(command.id,RPC_ERROR_INVALID_MOVE_REQUEST,parsed2);let root=join18(port.agentDir,"session-moves"),ledger=new MoveLedger(join18(root,"ledger"));try{if(parsed2.op!=="import")return answer2(command.id,await run(parsed2,port,ledger,root));let notAFolder=await sessionDirRefusal(parsed2.sessionDir);if(notAFolder!==void 0)return refusal2(command.id,RPC_ERROR_INVALID_MOVE_REQUEST,notAFolder);let landed=await importMoved(parsed2,port,ledger,root),open5=command.op==="import"?command.open:void 0;if(open5===void 0)return answer2(command.id,landed);let open_error=await openLanded(port,command.id,open5,parsed2.cwd,landed);return open_error===void 0?void 0:answer2(command.id,{...landed,open_error})}catch(cause){if(cause instanceof MoveRefusal)return refusal2(command.id,cause.code,cause.message);let code2=typeof cause=="object"&&cause!==null&&"code"in cause?cause.code:void 0,detail2=cause instanceof Error?cause.message:String(cause);return refusal2(command.id,typeof code2=="string"?RENAMED_CODES[code2]??(CORE_CODES.has(code2)?code2:RPC_ERROR_MOVE_FAILED):RPC_ERROR_MOVE_FAILED,detail2,await landedWhenFenced(ledger,cause))}}async function run(parsed2,port,ledger,root){let outgoing=moveId=>join18(root,"outgoing",moveId);switch(parsed2.op){case"prepare":return wireRecord(await prepareMove({ledger,moveId:parsed2.moveId,cwd:parsed2.cwd,repository:parsed2.repository}));case"identity":{let repository="cwd"in parsed2?await readRepositoryIdentity(resolvePath(parsed2.cwd)):await readSessionRepositoryIdentity(join18(port.agentDir,"sessions"),parsed2.sessionPath);return repository===void 0?{}:{repository:{...repository,rootCommits:[...repository.rootCommits]}}}case"cancel":return wireRecord(await ledger.decline(parsed2.moveId,"cancelled"));case"status":return statusAnswer(ledger,parsed2.moveId,statusFile(parsed2.named,port.agentDir));case"export":{let sessionFile=await orderedRealPath(parsed2.sessionPath),bundleDir=outgoing(parsed2.moveId),{inlineMaxBytes}=parsed2,{manifest,read:inline}=await exportSessionForMoveAndRead({sessionFile,moveId:parsed2.moveId,target:parsed2.target,droppedUserMessages:parsed2.dropped,bundleDir,extensionStateDir:()=>sealedOutgoingStateDir(sessionFile,parsed2.moveId),guard:async()=>{await refuseOpenHere(port,sessionFile,"This session is open on this host. Release it with release_session reason move and this moveId first."),await refuseUnlessSealedFor(sessionFile,parsed2.moveId)},lockedGuard:()=>refuseUnlessSealedFor(sessionFile,parsed2.moveId)},async written=>inlineMaxBytes===void 0?void 0:readInlineBundle(written,{maxBytes:inlineMaxBytes,maxFiles:1024}));return{move_id:manifest.moveId,session_id:manifest.sessionId,bundle_dir:bundleDir,files:1+manifest.sidecars.length,...inline===void 0?{}:{inline_files:inline}}}case"finish":{let sessionFile=await orderedRealPath(parsed2.sessionPath);return await finishMove({sessionFile,bundleDir:outgoing(parsed2.moveId),moveId:parsed2.moveId,answer:parsed2.answer,guard:()=>refuseOpenHere(port,sessionFile,"This session is open on this host, so its runtime would not see the move end. Close it here, then finish the move.")}),ownershipOf(sessionFile)}case"revoke":{let sessionFile=await orderedRealPath(parsed2.sessionPath);return await revokeImportedMove({sessionFile,moveId:parsed2.moveId,ledger,guard:()=>refuseOpenHere(port,sessionFile,"This session is open on this host, so its runtime would not see the revoke. Close it here, then revoke the move.")}),ownershipOf(sessionFile)}case"copy":return copySessionAs({sourceFile:await orderedRealPath(parsed2.sessionPath),sessionId:parsed2.sessionId,sessionDir:cwd=>parsed2.sessionDir===void 0?getDefaultSessionDir(cwd,port.agentDir):normalizePath(parsed2.sessionDir)})}}async function ownershipOf(sessionFile){let ownership=sessionOwnership(await loadEntriesFromFileAsync(sessionFile));return{ownership:ownership.writable?"writable":ownership.state}}var MoveRefusal=class extends Error{constructor(code2,detail2){super(detail2),this.name="MoveRefusal",this.code=code2}};async function refuseUnlessSealedFor(sessionFile,moveId){let ownership=sessionOwnership(await loadEntriesFromFileAsync(sessionFile));if(ownership.writable||ownership.state!=="moving"||ownership.moveId!==moveId)throw new MoveRefusal(RPC_ERROR_MOVE_NOT_RELEASED,"This session file is not sealed for this move. Release it with release_session reason move and this moveId first; that also hands back its queued input.")}async function refuseOpenHere(port,sessionFile,detail2){if((await Promise.all(port.hostedPaths().map(path=>realSessionPath(path)))).includes(sessionFile))throw new MoveRefusal(RPC_ERROR_SESSION_OPEN_HERE,detail2)}function answer2(id,data2){return"refuse"in data2?refusal2(id,data2.refuse,data2.detail):{id,type:"response",command:"move_session",success:!0,data:data2}}function refusal2(id,code2,detail2,landed){return{id,type:"response",command:"move_session",success:!1,error:code2,errorCode:code2,errorData:{detail:detail2,...landed}}}function routeMoveSession(host,command){let agentDir=host.registry.agentDir;return agentDir===void 0?Promise.resolve(error(command.id,command.type,"move_unsupported: this host keeps no agent directory to move sessions in")):moveSession({agentDir,hostedPaths:()=>host.registry.list().flatMap(row=>row.sessionPath===void 0?[]:[row.sessionPath]),open:async(open5,reply)=>host.draining?error(open5.id,open5.type,"host_draining"):compactAdmissionGate(host,open5)??openWithBarrier(host,open5,reply)},command)}import{rm as rm10}from"node:fs/promises";var SESSION_RELEASED_ENTRY_TYPE="session_released",RELEASED_ADMISSION_CLOSED="release_session handed this session to another runtime; deliver there instead (admission is closed here)",RELEASE_QUEUED_HINT="queued user input is still owed a turn; release with interrupt: true to take it out and receive it in dropped.user_messages";async function releaseSession(port,command){let validMove=command.reason==="move"&&isMoveId(command.moveId);if(command.reason!=="takeover"&&!validMove)return refusal3(command.id,RPC_ERROR_INVALID_RELEASE_REASON);if(port.draining())return refusal3(command.id,RPC_ERROR_HOST_DRAINING);let first=releasable(port,command,void 0);if(!("session"in first))return first;if(command.reason==="move"&&!isPlainId(first.session.sessionManager.getSessionId()))return refusal3(command.id,RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"session_id_not_plain"});let busy=busySignals(port,command.sessionId,first.session),interrupted=busy.length>0;if(interrupted&&command.interrupt!==!0)return refusal3(command.id,busyCode(busy),{attachments:first.attachments,...busyData(busy)});let admission=first.session.externalAdmission,dropped=NOTHING_DROPPED,answer4,stagedState,sealed=!1;try{if(interrupted){admission.close(RELEASED_ADMISSION_CLOSED);let taken=takeQueuedInput(first.session),handedBack=await abortAndSettle(port,command.sessionId,first.session);dropped={...taken,deliveries:[...taken.deliveries,...handedBack]},await first.session.whenQueueClearRecorded()}let manager=first.session.sessionManager;if(manager.isTranscriptFlushed()||await manager.persistHeaderNow(),command.reason==="move"){let moveId=parseMoveId(command.moveId);stagedState=await prepareOutgoingState(first.sessionPath,moveId);let[failed]=await first.session.extensionRunner.emitSessionMove({type:"session_move_export",moveId,dir:stagedState.dir});if(failed!==void 0)throw new Error(`${failed.extensionPath} could not write its state for the move: ${failed.error}`);await assertMoveFits(first.sessionPath,manager.getSessionId(),stagedState.dir,!1)}return answer4=await claimAndRelease(port,command,interrupted,dropped,stagedState?.attempt,()=>{sealed=!0}),answer4}catch(cause){return cause instanceof SessionMovedAwayError?(answer4=refusal3(command.id,cause.code,{detail:cause.message,...interrupted?{interrupted:!0,dropped}:{}}),answer4):(answer4=refusal3(command.id,RPC_ERROR_RELEASE_FAILED,{detail:cause instanceof Error?cause.message:String(cause),...interrupted?{interrupted:!0,dropped}:{}}),answer4)}finally{answer4?.success!==!0&&(admission.reopen(),stagedState!==void 0&&!sealed&&await rm10(stagedState.dir,{recursive:!0,force:!0}))}}async function claimAndRelease(port,command,interrupted,dropped,stateAttempt,onSealed){let taken=interrupted?{interrupted:!0,dropped}:void 0,ready=releasable(port,command,taken);if(!("session"in ready))return ready;let stillBusy=busySignals(port,command.sessionId,ready.session);if(stillBusy.length>0)return refusal3(command.id,busyCode(stillBusy),{attachments:ready.attachments,...busyData(stillBusy),interrupted,...taken});let admission=ready.session.externalAdmission;admission.close(RELEASED_ADMISSION_CLOSED);try{ready.session.sessionManager.appendCustomEntry(SESSION_RELEASED_ENTRY_TYPE,{reason:command.reason,...command.reason==="move"?{move_id:command.moveId,...stateAttempt===void 0?{}:{[STATE_ATTEMPT_FIELD]:stateAttempt},target:command.target??"",session_id:ready.session.sessionManager.getSessionId()}:{},interrupted,attachments:ready.attachments,host_instance:port.hostInstance??null,released_at:new Date().toISOString()})}catch(cause){throw admission.reopen(),cause}return onSealed(),await port.tearDown(command.sessionId,ready.sessionPath)?{id:command.id,type:"response",command:"release_session",success:!0,data:{released:!0,session_path:ready.sessionPath,attachments:ready.attachments,dropped}}:refusal3(command.id,RPC_ERROR_SESSION_CLOSING,taken)}function busySignals(port,sessionId,session){let activity=session.activitySnapshot,signals=[];return activity.isStreaming&&signals.push("turn"),port.pendingPrompts(sessionId).length>0&&signals.push("prompt"),session.pendingMessageCount>0&&signals.push("queued"),session.externalAdmission.list().pending.length>0&&signals.push("delivery"),activity.isBashRunning&&signals.push("bash"),activity.isCompacting&&signals.push("compaction"),activity.hasSessionWork&&signals.push("session_work"),signals.length===0&&isHandoffBusy(activity)&&signals.push("activity"),port.otherRequests(sessionId)>0&&signals.push("request"),signals}function busyData(signals){return signals.includes("queued")?{busy:signals,retry_with:{interrupt:!0},hint:RELEASE_QUEUED_HINT}:{busy:signals}}function busyCode(signals){return signals.some(signal=>signal==="turn"||signal==="prompt"||signal==="queued"||signal==="delivery")?RPC_ERROR_TURN_ACTIVE:RPC_ERROR_SESSION_BUSY}function releasable(port,command,taken){let refuse=(code2,data2)=>refusal3(command.id,code2,data2||taken?{...data2,...taken}:void 0),entry2;try{entry2=port.lookup(command.sessionId)}catch(cause){return refuse(port.code(cause))}if(entry2.state!=="open")return refuse(RPC_ERROR_SESSION_CLOSING);let session=entry2.runtime?.session;if(session===void 0)return refuse(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"worker_runtime"});let sessionPath=entry2.sessionPath??session.sessionFile;if(sessionPath===void 0)return refuse(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"no_session_file"});let elsewhere=port.otherAttachments(command.sessionId);return elsewhere>0&&command.force!==!0?refuse(RPC_ERROR_ATTACHED,{attachments:elsewhere}):{session,sessionPath,attachments:entry2.attachments}}function refusal3(id,code2,data2){return{id,type:"response",command:"release_session",success:!1,error:code2,...data2&&{errorCode:code2,errorData:data2}}}function sessionMemory(host,sessionId){let view=host.hostMemoryView;if(view===void 0)return{main_heap_bytes:0,kernel_heap_bytes:0,kernel_count:0};let kernels=view.kernels().filter(kernel=>kernel.sessionId===sessionId),kernelHeapBytes=0;for(let kernel of kernels)kernelHeapBytes+=kernel.liveBytes;return{main_heap_bytes:view.mainHeapBytes(),kernel_heap_bytes:kernelHeapBytes,kernel_count:kernels.length}}function acknowledgePrompt(host,id,sessionId){let connection2=host.writer.currentConnection();if(id===void 0||connection2===void 0)return;let inFlight=Math.max(0,(host.activeRequests.get(sessionId)??1)-1);host.writer.sendOpenQueued(connection2,{type:"queued",for_request:id,position:inFlight+1,in_flight:inFlight})}function otherRequestsSettled(host,sessionId){return new Promise(resolve4=>{let listeners=host.requestSettledListeners.get(sessionId)??new Set,check=()=>{(host.activeRequests.get(sessionId)??0)>1||(listeners.delete(check),listeners.size===0&&host.requestSettledListeners.delete(sessionId),resolve4())};listeners.add(check),host.requestSettledListeners.set(sessionId,listeners),check()})}function answerProtocolInfo(host,command){let hostCapabilities=multiSessionHostCapabilities({warm:host.registry.warm!==void 0,parkClaim:host.registry.supportsParkClaim===!0,toolRuntime:host.defaults.toolRuntime??"in-process",negotiated:host.connectionOptions?.capabilities??[],mcpPresenters:host.writer.mcpPresenters!==void 0}),capabilities=host.defaults.handSelection===void 0?hostCapabilities:[...hostCapabilities,HAND_SELECTION_CAPABILITY];return{id:command.id,type:"response",command:"get_protocol_info",success:!0,data:{protocolVersion:1,serverVersion:VERSION,capabilities:advertisedCompactCapabilities(capabilities,host.writer.currentConnection()!==void 0&&host.compactAvailable()),mode:"multi",...protocolIdentity(host.defaults.agentDir),memory_pressure:host.memoryPressure,path_identity_resolver:pathIdentityResolverStatus(sharedPathIdentityResolver())}}}function answerSubscriptionLimits(command){return{id:command.id,type:"response",command:"get_subscription_limits",success:!0,data:{accounts:subscriptionLimits.snapshot()}}}function answerListSessions(host,command){let rows=host.registry.list(),presence=host.defaults.sessionPresence,withMemory=[...rows.map(row=>({...row,generation:hostGeneration(process.env),hostInstanceId:host.defaults.hostContext?.host_instance??hostInstanceId(),memory:sessionMemory(host,row.sessionId),...presence&&row.durableSessionId!==void 0?{presence:presence.view(row.durableSessionId)}:{}})),...host.routes.rows().filter(r=>!rows.some(row=>row.sessionId===r.sessionId))],sessions=command.include_workers===!0?withMemory:withMemory.filter(row=>row.kind!=="worker").map(({context:_context,...row})=>row);return{id:command.id,type:"response",command:"list_sessions",success:!0,data:{sessions,...host.inheritedHandover===void 0?{}:{handover:{pending:host.inheritedHandover.pending,predecessor_draining:host.inheritedHandover.predecessorDraining}}}}}var CHILD_TASK_SOURCE=/^senpi-task/,ACTIONS={extension_work:"let the named work finish, or unload with force: true (it is stopped, not resumed on reopen)",turn_active:"wait for the turn to end, or unload with interrupt: true to stop it first",work_pending:"wait for the work to finish, or unload with interrupt: true",work_pending_refused_deliveries:"the session's work would still read these deliveries: wait for it, or unload with interrupt: true and without deliveries to hand them back to their senders",children_live:'wait for the child tasks, or unload with children: "detach" to leave them running',attached:"ask the other clients to detach, or unload with force: true (they receive session_parked)",graceful_expired:"the session is still open and admitting again: retry with a longer waitMs, or unload with interrupt: true to stop the turn"};async function unloadSession(port,command){if(port.draining())return answer3(command,refused3({reason:"host_draining",detail:"this host is draining and parks every session itself"}));if(command.graceful===!0&&command.interrupt===!0)return answer3(command,refused3({reason:"unsupported",detail:"graceful and interrupt exclude each other",action:"send one of them"}));let first=loaded(port,command.sessionId);if("reason"in first)return answer3(command,refused3(first));let{effectId}=command;if(effectId!==void 0){let begun=await beginEffect({session:first.session,by:port.by,sessionId:command.sessionId},"unload",{...command,effectId});if(!isEffectBegin(begun))return begun;if("replay"in begun)return answer3(command,{outcome:begun.replay.state==="failed"?"refused":"unloaded",...refusalFields(begun.replay.outcome),...begun.replay.pending===void 0?{}:{pending:begun.replay.pending},...begun.replay.dropped===void 0?{}:{dropped:begun.replay.dropped},...effectAnswer(begun.replay,command.sessionId,!0)})}let blocked=blockers(port,command,first.session,first.durableSessionId);if(command.graceful===!0)return closeGracefully(port,command,first,blocked);let unread=blocked.find(refusal4=>refusal4.deliveries!==void 0);if(command.deliveries==="refuse"&&unread!==void 0&&blocked.some(refusal4=>refusal4.reason==="turn_active"))return fail2(command,first.session,{...unread,action:ACTIONS.work_pending_refused_deliveries});let standing=blocked.find(refusal4=>!interruptible(refusal4)||command.interrupt!==!0&&refusal4.parked!==!0);if(standing!==void 0)return fail2(command,first.session,standing);let handedBack=blocked.length>0?await abortAndSettle(port,command.sessionId,first.session):[];return claimAndUnload(port,command,handedBack)}async function closeGracefully(port,command,first,blocked){let standing=blocked.find(refusal4=>!interruptible(refusal4));if(standing!==void 0)return fail2(command,first.session,standing);let drain=fenceForClose(first.session),busy=()=>blockers(port,command,first.session,first.durableSessionId).filter(interruptible).map(refusal4=>refusal4.detail),settling=()=>[port.otherRequestsSettled(command.sessionId),...port.pendingPrompts(command.sessionId)];if(await drainUntilQuiet(first.session,{busy,settling},gracefulWaitMs(command.waitMs)))return claimAndUnload(port,command,drain.dropped.deliveries,drain);reopenAfterDrain(first.session);let facts=drainFacts(first.session,drain),expired={reason:"turn_active",detail:`still working after ${facts.waited_ms} ms: ${busy().join(", ")}`,action:ACTIONS.graceful_expired};return fail2(command,first.session,expired,droppedOf(drain.dropped.deliveries,drain),{timed_out:!0,open:!0,admission:"reopened",...facts})}function droppedOf(handedBack,drain){return drain!==void 0?{dropped:{deliveries:[...handedBack],user_messages:[...drain.dropped.user_messages]}}:handedBack.length===0?{}:{dropped:{deliveries:[...handedBack]}}}async function claimAndUnload(port,command,handedBack,drain){let dropped=droppedOf(handedBack,drain),ready=loaded(port,command.sessionId);if("reason"in ready)return answer3(command,{...refused3(ready),...dropped});let stillBlocked=blockers(port,command,ready.session,ready.durableSessionId);if(stillBlocked.length>0)return drain!==void 0&&reopenAfterDrain(ready.session),fail2(command,ready.session,stillBlocked[0],dropped);command.clearQueue===!0&&(ClientAdmissions.clearQueuedFor(ready.session),ready.session.clearQueue());let closed=drain===void 0?void 0:recordGracefulClose(ready.session,drain),effect=command.effectId===void 0?void 0:EffectLedger.forSession(ready.session).transition(command.effectId,"done",{disposition:"unloaded",...dropped});return await port.tearDown(command.sessionId,ready.sessionPath)?answer3(command,{outcome:"unloaded",sessionPath:ready.sessionPath,...dropped,...closed===void 0?{}:{graceful:{turn:closed.turn,waited_ms:closed.waited_ms,stopped:closed.stopped}},...effect===void 0?{}:effectAnswer(effect,command.sessionId)}):answer3(command,{outcome:"refused",reason:"session_closing",detail:"another close of this session finished first",...dropped})}function interruptible(refusal4){return refusal4.reason==="turn_active"||refusal4.reason==="work_pending"}function blockers(port,command,session,durableSessionId){let found=[],activity=session.activitySnapshot,running=[activity.isStreaming&&"an agent run",port.pendingPrompts(command.sessionId).length>0&&"a prompt about to start",activity.isCompacting&&"compaction",activity.hasSessionWork&&"session work"].filter(label=>typeof label=="string");activity.isStreaming&&!activity.isCompacting&&!activity.hasSessionWork&&session.toolDispatcher.executing===0&&(sessionDialogRequests.get(session)?.snapshot().length??0)>0?found.push({reason:"turn_active",detail:"an agent run waiting on an unanswered prompt",action:ACTIONS.turn_active,parked:!0}):running.length>0&&found.push({reason:"turn_active",detail:running.join(", "),action:ACTIONS.turn_active});let unwritten=session.externalAdmission.list().pending,pending=[activity.isBashRunning&&"a bash command",unwritten.length>0&&"an admitted delivery not yet written",port.otherRequests(command.sessionId)>0&&"another request for this session"].filter(label=>typeof label=="string");pending.length>0&&found.push({reason:"work_pending",detail:pending.join(", "),action:ACTIONS.work_pending,...unwritten.length===0?{}:{deliveries:[...unwritten]}});let sources=session.activeWakeSources,childSources=sources.filter(source=>CHILD_TASK_SOURCE.test(source)),otherSources=sources.filter(source=>!CHILD_TASK_SOURCE.test(source));otherSources.length>0&&command.force!==!0&&command.graceful!==!0&&found.push({reason:"extension_work",detail:`work published by ${otherSources.join(", ")}`,action:ACTIONS.extension_work});let childSessions=port.openChildSessions(durableSessionId);if(command.children!=="detach"&&(childSources.length>0||childSessions>0)){let what=childSessions>0?`${childSessions} child session(s) open on this host`:"child tasks still working";found.push({reason:"children_live",detail:what,action:ACTIONS.children_live})}let others=port.otherAttachments(command.sessionId);return others>0&&command.force!==!0&&found.push({reason:"attached",detail:`${others} other client(s) attached`,action:ACTIONS.attached}),found}function loaded(port,sessionId){let entry2;try{entry2=port.lookup(sessionId)}catch(cause){return{reason:"unsupported",detail:port.code(cause)}}if(entry2.state!=="open")return{reason:"session_closing",detail:"the session is already closing"};let session=entry2.runtime?.session;if(session===void 0)return{reason:"unsupported",detail:"a worker isolate owns this session's runtime"};let sessionPath=entry2.sessionPath??session.sessionFile;return sessionPath===void 0?{reason:"unsupported",detail:"the session has no file to reopen it by",action:"send a prompt first so the session is written, or close it instead"}:{session,sessionPath,durableSessionId:session.sessionManager.getSessionId()}}function fail2(command,session,refusal4,dropped={},expiry={}){if(command.effectId===void 0)return answer3(command,{...refused3(refusal4),...dropped,...expiry});let status=EffectLedger.forSession(session).transition(command.effectId,"failed",{...dropped,...pendingOf(refusal4),outcome:{kind:"refused",reason:refusal4.reason,detail:refusal4.detail,...refusal4.action===void 0?{}:{action:refusal4.action}}});return answer3(command,{...refused3(refusal4),...dropped,...expiry,...effectAnswer(status,command.sessionId)})}function refusalFields(outcome){return outcome?.reason===void 0?{}:{reason:outcome.reason,...outcome.detail===void 0?{}:{detail:outcome.detail},...outcome.action===void 0?{}:{action:outcome.action}}}function pendingOf(refusal4){return refusal4.deliveries===void 0?{}:{pending:{deliveries:[...refusal4.deliveries]}}}function refused3(refusal4){return{outcome:"refused",reason:refusal4.reason,detail:refusal4.detail,...refusal4.action===void 0?{}:{action:refusal4.action},...pendingOf(refusal4)}}function answer3(command,data2){return{id:command.id,type:"response",command:"unload_session",success:!0,data:data2}}function handle(host,command){let malformed=invalidCompactAdmission(command);if(malformed)return Promise.resolve(malformed);let ownership=unknownCompactAdmission(host,command);return ownership instanceof Promise?ownership.then(refusal4=>refusal4??admitted(host,command)):ownership?Promise.resolve(ownership):admitted(host,command)}function admitted(host,command){let routed=host.routes.command(command,()=>admitted(host,command));if(routed)return routed;if("sessionId"in command&&command.sessionId!==void 0&&host.registry.peek(command.sessionId)?.speculative)return Promise.resolve(error(command.id,command.type,"unknown_session"));if(command.type==="park_session")return parkSession(host,command);let refusal4=attachmentGate(host,command)??compactAdmissionGate(host,command);if(refusal4)return Promise.resolve(refusal4);if(command.type==="set_client_info"&&compactUpdatesEnabled()){let reply=declareSocketClient(host,command);if(!reply.success)return Promise.resolve(reply);let peer=host.writer.currentConnection();if(command.capabilities!==void 0&&peer!==void 0&&(command={...command,capabilities:[...host.pendingCapabilities.get(peer)??[]]}),command.id===void 0&&command.capabilities===void 0)return Promise.resolve(void 0)}let sessionId="sessionId"in command?command.sessionId:void 0;return host.draining&&sessionId!==void 0&&host.handoffClosed.has(sessionId)?Promise.resolve(host.writer.currentConnection()?.startsWith("generation-route-")?error(command.id,command.type,"generation_session_parked"):void 0):host.draining&&command.type==="open_session"&&!(host.writer.currentConnection()?.startsWith("generation-route-")&&command.expectedHostInstance!==void 0)?Promise.resolve(error(command.id,command.type,"host_draining")):command.type==="warm"?answerWarm(command,{draining:host.draining,warm:host.registry.warm,cwd:host.defaults.cwd,hostContext:host.defaults.hostContext}):(host.activeRequests.set(sessionId,(host.activeRequests.get(sessionId)??0)+1),withAdmissionRequest(command,host.writer.currentConnection(),()=>runWithSessionAttribution({sessionId},()=>dispatch(host,command)).finally(()=>{let remaining=(host.activeRequests.get(sessionId)??1)-1;if(remaining>0?host.activeRequests.set(sessionId,remaining):host.activeRequests.delete(sessionId),sessionId!==void 0)for(let listener of host.requestSettledListeners.get(sessionId)??[])listener();host.draining&&sweepDrain(host)})))}function otherAttachments(host,caller,sessionId){let own=caller===void 0?0:host.sessionsByConnection.get(caller)?.get(sessionId)??0;return Math.max(0,(host.registry.peek(sessionId)?.attachments??0)-own)}async function dispatch(host,command){if(command.type==="reset_stream"&&host.admissions)return resetStream(host,command);if(command.type==="cancel_attempt"&&host.admissions!==void 0){let peer=host.writer.currentConnection(),epoch=peer===void 0?void 0:host.writer.socketEpochOf(peer);if(epoch===void 0)return error(command.id,command.type,"unsupported_transport");let outcome=await host.admissions.cancel(epoch,command.admissionId);return{id:command.id,type:"response",command:"cancel_attempt",success:!0,data:{outcome}}}if((command.type==="reset_stream"||command.type==="cancel_attempt")&&host.admissions===void 0)return compactTransportDisabled(command);if(command.type==="get_protocol_info")return answerProtocolInfo(host,command);if(command.type==="get_subscription_limits")return answerSubscriptionLimits(command);if(command.type==="list_sessions"){if(!host.writer.currentConnection()?.startsWith("generation-route-"))try{await host.routes.discover()}catch(cause){return error(command.id,command.type,code(cause))}return answerListSessions(host,command)}if(command.type==="list_hands")return answerListHands(host,command);if(command.type==="select_hand")return answerSelectHand(host,command);if(command.type==="detach_connection")return detachConnection(command,host.writer.currentConnection(),id=>releaseConnection(host,id));if(command.type==="open_session")return openWithBarrier(host,command);if(command.type==="claim_session")return claimSession(host,command);if(command.type==="attach_session"){let reply=await attachSession(host,command);if(reply?.success===!1&&(reply.error==="unknown_session"||reply.error==="session_identity_mismatch"))try{return await host.routes.attachByIdentity(command,reply)}catch(cause){return error(command.id,command.type,code(cause))}return reply}if(command.type==="release_attachment")return releaseAttachment(host,command);if(command.type==="reclaim_session")return reclaimSession(host,command);if(command.type==="find_session")return findSession({agentDir:host.registry.agentDir??host.defaults.agentDir,hosted:()=>host.registry.list()},command);if(command.type==="close_session")return close(host,command);if(command.type==="release_session")return releaseSession({draining:()=>host.draining,hostInstance:host.defaults.hostContext?.host_instance,otherAttachments:sessionId2=>otherAttachments(host,host.writer.currentConnection(),sessionId2),lookup:sessionId2=>host.registry.getForCommand(sessionId2,"release_session"),code:cause=>code(cause),otherRequests:sessionId2=>Math.max(0,(host.activeRequests.get(sessionId2)??1)-1),otherRequestsSettled:sessionId2=>otherRequestsSettled(host,sessionId2),pendingPrompts:sessionId2=>host.bindings.get(sessionId2)?.pendingPrompts?.()??[],tearDown:(sessionId2,sessionPath)=>host.releaseTeardown(sessionId2,sessionPath)},command);if(command.type==="move_session")return routeMoveSession(host,command);if(command.type==="unload_session"){let caller=host.writer.currentConnection();return unloadSession({draining:()=>host.draining,by:{connectionId:caller??"host"},lookup:sessionId2=>host.registry.getForCommand(sessionId2,"unload_session"),code:cause=>code(cause),otherRequests:sessionId2=>Math.max(0,(host.activeRequests.get(sessionId2)??1)-1),otherRequestsSettled:sessionId2=>otherRequestsSettled(host,sessionId2),pendingPrompts:sessionId2=>host.bindings.get(sessionId2)?.pendingPrompts?.()??[],otherAttachments:sessionId2=>otherAttachments(host,caller,sessionId2),openChildSessions:durableSessionId=>host.registry.list().filter(row=>row.durableSessionId!==durableSessionId&&(row.context?.parent_session_id===durableSessionId||row.context?.root_session_id===durableSessionId)).length,tearDown:(sessionId2,sessionPath)=>tearDownUnloaded(host,sessionId2,sessionPath)},command)}if(command.type==="set_client_info"&&!command.sessionId)return command.id===void 0&&compactUpdatesEnabled()?void 0:declareSocketClient(host,command);if(command.type==="subscribe_sessions"){if(host.admissions&&command.admissionId!==void 0)return compactSubscribe(host,command);let connection2=host.writer.currentConnection(),{answer:answer4,activate}=answerSubscribeSessions(command,connection2,host.writer.status);if(activate!==void 0&&connection2!==void 0){(async()=>{await host.writer.enqueueControl(answer4,connection2),await new Promise(resolve4=>queueMicrotask(resolve4));try{host.writer.hasConnection(connection2)?host.writer.status.activate(activate):host.writer.status.unsubscribe(connection2,activate)}catch(cause){process.stderr.write(`senpi rpc subscription activation failed: ${String(cause)}
`)}})().catch(cause=>{host.writer.status.unsubscribe(connection2,activate),process.stderr.write(`senpi rpc subscribe answer could not be delivered: ${String(cause)}
`)});return}return answer4}if(command.type==="unsubscribe_sessions"){let peer=host.writer.currentConnection(),answer4=answerUnsubscribeSessions(command,peer,host.writer.status);return answer4.success&&peer!==void 0&&host.writer.unregisterSubscription(peer,command.subscriptionId),answer4}if(command.type==="get_effect_status"&&!command.sessionId&&command.sessionPath!==void 0)return answerEffectFromTranscript(command.id,command.sessionPath,command.effectId);if(command.type==="get_recovery_page"&&host.writer.recoveryPages!==void 0)return answerRecoveryPage(host.writer.recoveryPages,host.writer,command);if(command.type==="release_recovery"&&host.writer.recoveryEvents!==void 0)return answerReleaseRecovery(host.writer.recoveryEvents,host.writer,command);if(command.type==="get_recovery_page"||command.type==="release_recovery")return compactTransportDisabled(command);if(!command.sessionId)return error(command.id,command.type,RPC_ERROR_MISSING_SESSION_ID);let sessionId=command.sessionId;if(host.writer.isSessionSealed(sessionId)&&host.registry.peek(sessionId)?.state==="open")return error(command.id,command.type,"session_output_overflow",{sessionId,action:"unload_and_reopen"});if(command.type==="set_session_context")return setSessionContext(host,command);try{let entry2=host.registry.getForCommand(sessionId,command.type);await dispatchSessionBinding(command,entry2,host.bindings.get(sessionId),()=>acknowledgePrompt(host,command.id,sessionId),observedStarts=>host.registry.holderPids?.(observedStarts)??Promise.resolve([]));return}catch(cause){return error(command.id,command.type,code(cause),detail(cause))}}function setSessionContext(host,command){let owner=host.writer.currentConnection();if(owner!==void 0&&host.sessionsByConnection.get(owner)?.has(command.sessionId)!==!0)return notAttachedRefusal(command);try{let entry2=host.registry.getForCommand(command.sessionId,command.type),answered=answerSetSessionContext(command,entry2,host.writer.status);return answered.success&&syncRetainedRecord(host,command.sessionId,void 0),answered}catch(cause){return error(command.id,command.type,code(cause),detail(cause))}}var SessionCommandRouter=class{constructor(...args){this.context=new RouterContext(...args),this.context.routes.reopen=entry2=>this.reopenParked(entry2),this.context.releaseTeardown=(sessionId,sessionPath)=>this.tearDownReleased(sessionId,sessionPath)}tearDownReleased(sessionId,sessionPath){return tearDownReleased(this.context,sessionId,sessionPath)}get sessionCount(){return this.context.registry.size}handle(command){return handle(this.context,command)}configureRoutes(connection2,record){return this.context.routes.configure(connection2,record)}admitsRoutedRecord(connection2,value){let record=authRecord(value);if(!record)return!1;switch(record.type){case"get_protocol_info":case"list_sessions":case"launch_proven":case"declare_delegation":return!0;case"set_client_info":return record.sessionId===void 0||typeof record.sessionId=="string"&&this.context.sessionsByConnection.get(connection2)?.has(record.sessionId)===!0;case"open_session":return typeof record.sessionPath=="string"&&typeof record.expectedHostInstance=="string";case"attach_session":return typeof record.expectedHostInstance=="string"&&typeof record.durableSessionId=="string";case"park_session":case"claim_session":case"warm":case"move_session":case"select_hand":case"begin_handover":case"detach_connection":case"subscribe_sessions":case"unsubscribe_sessions":case"list_hands":case"find_session":return!1;default:return typeof record.sessionId=="string"&&(this.context.sessionsByConnection.get(connection2)?.has(record.sessionId)===!0||this.context.handoffClosed.has(record.sessionId)||ATTACH_GATE_EXEMPT.has(record.type)&&this.context.registry.peek(record.sessionId)?.state==="open")&&classifyRpcMethod(record)!==void 0}}beginDrain(){beginDrain(this.context)}setMemoryPressure(pressure){this.context.memoryPressure=pressure}setInheritedHandover(state){this.context.awaitingPredecessorScan=!1,this.context.inheritedHandover=state}sweepIdleSessions(){sweepIdleSessions(this.context)}dispose(){return this.context.routes.dispose(),dispose(this.context)}reopenParked(entry2){return reopenParked(this.context,entry2)}holdsSessions(connectionId){return(this.context.sessionsByConnection.get(connectionId)?.size??0)>0||(this.context.opensByConnection.get(connectionId)?.size??0)>0}releaseConnection(connectionId){return releaseConnection(this.context,connectionId)}setHostMemoryView(view){this.context.hostMemoryView=view}};var SESSION_WORKER_LIMITS={workers:20,requests:64,controlRequests:4,controlBytes:1024*1024,requestBytes:16*1024*1024,outputBytes:16*1024*1024,reservations:64,openMs:3e4,controlMs:5e3,secretFrameBytes:64*1024,secretInputs:64,secretIds:1088};var WORKER_CREDIT_CODES={granted:1,conflict:2,limit:3,stale:4};function typedWorkerRefusal(cause){let message=cause instanceof Error?cause.message:String(cause);throw message.startsWith("open_failed: ")?new RpcSessionRegistryError("open_failed",message.slice(13)):cause}function closedByWorkerDeath(cause){return cause instanceof RpcSessionRegistryError?cause.code==="session_closing":cause instanceof Error&&(cause.message==="session_closing"||cause.message==="session_worker_exited")}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(handle2){let count=0;for(let owner of this.owners.values())owner===handle2&&count++;return count}reserve(handle2,path,live){let owner=this.owners.get(path);return owner?owner===handle2?"granted":"conflict":this.count(handle2)>=SESSION_WORKER_LIMITS.reservations&&(!live||(this.reconcile(handle2,live),this.count(handle2)>=SESSION_WORKER_LIMITS.reservations))?"limit":(this.owners.set(path,handle2),"granted")}reconcile(handle2,live){for(let[path,owner]of this.owners)owner!==handle2||path===live.sessionPath||live.livePaths.includes(path)||this.owners.delete(path)}releaseAll(handle2){for(let[path,owner]of this.owners)owner===handle2&&this.owners.delete(path)}};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 workerCapabilities(options,message,writer){let connection2=roleConnection(message.connection);if(options.connectionRoles?.isStale(connection2,message.incarnation)===!0)return acknowledgeGrant(message.signal,"stale"),options;let current=message.connection===void 0||!compactUpdatesEnabled()?void 0:writer?.compactSelection(message.connection);if(current&&(current.refused||message.capabilities.length!==current.capabilities.length||!message.capabilities.every(cap=>current.capabilities.includes(cap))))return acknowledge(message.signal,!1),options;let verdict=options.connectionRoles?.declare(connection2,message.capabilities,message.incarnation);return verdict==="stale"?(acknowledgeGrant(message.signal,"stale"),options):verdict==="fixed"?(acknowledge(message.signal,!1),options):(message.connection===void 0&&(options={...options,capabilities:message.capabilities}),options.clientInfo?.setCapabilities(message.connection,message.capabilities),acknowledge(message.signal,!0),options)}var SessionWorkerRequests=class{constructor(send,timeout){this.pending=new Map,this.serial=0,this.closed=!1,this.progressDeadline=0,this.send=send,this.timeout=timeout}noteProgress(){if(!this.closed){this.progressDeadline=Date.now()+SESSION_WORKER_LIMITS.openMs;for(let pending of this.pending.values())pending.timer===void 0||pending.control||(clearTimeout(pending.timer),pending.timer=setTimeout(this.timeout,SESSION_WORKER_LIMITS.openMs))}}progressBudgetMs(){let now=Date.now(),owed=!1;for(let pending of this.pending.values())pending.timer!==void 0&&!pending.control&&(owed=!0);return owed||(this.progressDeadline=now+SESSION_WORKER_LIMITS.openMs),Math.max(0,this.progressDeadline-now)}get activeCount(){return this.pending.size}request(message){if(this.closed)return Promise.reject(new Error("session_closing"));let control=message.type==="secret_sealed_answer"||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),bytes2=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+bytes2>maxBytes)return Promise.reject(new Error("session_worker_request_limit"));let request=++this.serial;return new Promise((resolve4,reject)=>{let timer=message.type==="command"&&!control?void 0:setTimeout(this.timeout,control?SESSION_WORKER_LIMITS.controlMs:this.progressBudgetMs());this.pending.set(request,{resolve:resolve4,reject,bytes:bytes2,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()}};var WORKER_PERMIT_BYTES=FRAGMENT_ENVELOPE_MAX_BYTES,WORKER_CONTROL_SLOTS=1,PERMIT_WORD={credit:0,host:1,worker:2,wake:3},PERMIT_BLOCK_BYTES=Object.keys(PERMIT_WORD).length*Int32Array.BYTES_PER_ELEMENT,PERMIT_TAG={idle:0,granted:1,denied:2,closed:3,waiting:4},WorkerPermitLedger=class{constructor(capacity=TRANSFER_STAGING_MAX_BYTES){this.granted=0,this.waiting=new Set,this.ceiling=Math.floor(capacity/WORKER_PERMIT_BYTES)-WORKER_CONTROL_SLOTS}request(grant){return this.granted>=this.ceiling?(this.waiting.add(grant),!1):(this.granted+=1,grant(),!0)}release(){this.granted-=1;let[next]=this.waiting;next&&(this.waiting.delete(next),this.granted+=1,next())}withdraw(grant){this.waiting.delete(grant)}status(){return{granted:this.granted,waiting:this.waiting.size,ceiling:this.ceiling}}},hostWorkerPermits=new WorkerPermitLedger,HostPermits=class{constructor(ledger){this.block=new SharedArrayBuffer(PERMIT_BLOCK_BYTES),this.state=new Int32Array(this.block),this.holding=!1,this.closed=!1,this.grant=()=>{this.holding=!0,Atomics.add(this.state,PERMIT_WORD.credit,WORKER_PERMIT_BYTES),this.signal(PERMIT_TAG.granted)},this.ledger=ledger,this.request()}returned(){this.closed||!this.holding||Atomics.load(this.state,PERMIT_WORD.credit)>=WORKER_PERMIT_BYTES||(this.holding=!1,this.ledger.release(),this.request())}close(){this.closed||(this.closed=!0,this.signal(PERMIT_TAG.closed),this.holding?this.ledger.release():this.ledger.withdraw(this.grant),this.holding=!1)}request(){this.ledger.request(this.grant)||this.signal(PERMIT_TAG.denied)}signal(tag){Atomics.store(this.state,PERMIT_WORD.host,tag),Atomics.add(this.state,PERMIT_WORD.wake,1),Atomics.notify(this.state,PERMIT_WORD.wake)}};var PAID=new Set(["ready","snapshot","output","canonical","canonical_unavailable","fragment"]),FRAGMENT_KIND=protocolId("worker_frame"),WorkerIntake=class{constructor(staging,fail3,ledger=hostWorkerPermits){this.expected=0,this.serial=0,this.assembled=new WeakSet,this.staging=staging,this.fail=fail3,this.permits=new HostPermits(ledger)}get nextOrdinal(){return this.expected}get refusal(){return this.refused}received(message){PAID.has(message.type)&&!this.assembled.delete(message)&&this.permits.returned()}inOrder(message){if(message.ordinal===this.expected)return this.expected+=1,!0;message.signal&&acknowledge(message.signal,!1);let kind=(message.ordinal??Number.POSITIVE_INFINITY)<this.expected?"duplicate":"gap";return this.fail(`session_worker_frame_${kind}`),!1}fragment(frame){let end=frame.offset+frame.text.length*2,final=end===frame.length;if(frame.ordinal!==void 0&&!final&&!this.inOrder(frame))return this.refuse(frame);let fed=this.open?.fed??0;if(frame.offset!==fed)return this.refuse(frame,`session_worker_frame_${frame.offset<fed?"duplicate":"gap"}`);try{this.open??={transfer:this.staging.begin(FRAGMENT_KIND,protocolId(`t${++this.serial}`),frame.length),fed},this.open.transfer.append(frame.text),this.open.fed=end}catch(error2){let cause=error2 instanceof TransferStagingError?error2.reason:"failed",ordinal=frame.ordinal===void 0?void 0:frame.ordinal+Math.ceil((frame.length-frame.offset)/FRAGMENT_MAX_BYTES)-1;this.refused={cause,event:{type:frame.of,...ordinal===void 0?{}:{ordinal},length:frame.length}};let at=ordinal===void 0?"":` ordinal ${ordinal}`;return this.refuse(frame,`session_worker_transfer_${cause}: ${frame.of}${at} (${frame.length} stored bytes)`)}if(!final)return;let content=this.open.transfer.commit();return this.open=void 0,this.whole(content,frame)}refuse(frame,error2){this.open?.transfer.abort(),this.open=void 0,error2!==void 0&&(frame.signal&&acknowledge(frame.signal,!1),this.fail(error2))}async whole(content,frame){try{let text4="";for await(let chunk of this.staging.chunks(content))text4+=chunk;let message=JSON.parse(text4);return this.assembled.add(message),Object.assign(message,frame.ordinal===void 0?{}:{ordinal:frame.ordinal},frame.firstOrdinal===void 0?{}:{firstOrdinal:frame.firstOrdinal},frame.signal?{signal:frame.signal}:{},frame.epochSignal&&"bootstrap"in message?{bootstrap:{...message.bootstrap,epochSignal:frame.epochSignal}}:{})}finally{this.staging.abandon(content)}}};import{randomUUID as randomUUID3}from"node:crypto";var WorkerOwnerGates=class{constructor(){this.generation=randomUUID3(),this.issued=new Map}capture(context,connection2,command){let transport=context.transport;if(connection2===void 0||transport===void 0||!carriesExtensionOwner(command))return;let owner=transport.capture(this.generation);owner.retired&&(this.generation=randomUUID3(),owner=transport.capture(this.generation));let owners=this.issued.get(connection2)??new Set;return owners.add(owner),this.issued.set(connection2,owners),owner.wire}detach(context,connection2){let owners=this.issued.get(connection2);if(!owners)return[];this.issued.delete(connection2);let current=context.transportOf(connection2),kept=new Set,retired=[];for(let owner of owners)current!==void 0&&current.ownerId!==owner.wire.ownerId&&!owner.retired?kept.add(owner):(owner.retire(),retired.push({ownerId:owner.wire.ownerId,bindingGeneration:owner.wire.bindingGeneration}));return kept.size>0&&this.issued.set(connection2,kept),retired}retireAll(){let retired=[];for(let owners of this.issued.values())for(let owner of owners)owner.retire(),retired.push({ownerId:owner.wire.ownerId,bindingGeneration:owner.wire.bindingGeneration});return this.issued.clear(),this.generation=randomUUID3(),retired}};var SECRET_FRAME_TYPES=["extension_ui_request","secret_input_settled","secret_sealed_offer"];function secretFrameType(record){let type="type"in record?record.type:void 0;return SECRET_FRAME_TYPES.find(known=>known===type)}function isSealedOffer(record){if(!("type"in record)||record.type!=="secret_sealed_offer")return!1;let offer=record;return typeof offer.hpkePk=="string"&&/^[A-Za-z0-9_-]{43}$/.test(offer.hpkePk)&&typeof offer.title=="string"&&(offer.placeholder===void 0||typeof offer.placeholder=="string")&&Number.isSafeInteger(offer.deadlineAtMs)}var WorkerSecretIds=class{constructor(){this.sent=new Map}has(id){return this.sent.has(id)}ids(){return this.sent.keys()}admitsNew(){if(this.sent.size>=SESSION_WORKER_LIMITS.secretIds)return!1;let open5=0;for(let sent of this.sent.values())sent.has("secret_input_settled")||open5++;return open5<SESSION_WORKER_LIMITS.secretInputs}add(id){this.sent.has(id)||this.sent.set(id,new Set)}admitFrame(id,record){let sent=this.sent.get(id),type=secretFrameType(record);return!sent||type===void 0||sent.has(type)||Buffer.byteLength(JSON.stringify(record))>SESSION_WORKER_LIMITS.secretFrameBytes?!1:(sent.add(type),!0)}forget(id){this.sent.delete(id)}clear(){this.sent.clear()}};var SEALED_ANSWERS_PER_ID=5,OUTCOMES=new Set(["answered","cancelled","timed_out","unavailable"]),REPLY_ERRORS=new Set(["already_answered","unknown_extension_ui_request","secret_stepup_refused","invalid_secret_response","secret_answer_refused"]),isReplyError=error2=>REPLY_ERRORS.has(error2);function isolateReply(value){if(typeof value!="object"||value===null)return{error:"secret_answer_refused"};let disposition="disposition"in value?value.disposition:void 0;if(disposition==="applied"||disposition==="replay")return{disposition};let error2="error"in value?value.error:void 0;return typeof error2=="string"&&isReplyError(error2)?{error:error2}:{error:"secret_answer_refused"}}var WorkerHostSecrets=class{constructor(deps){this.ids=new WorkerSecretIds,this.queue=new Map,this.forwarded=new Map,this.settledIds=new Set,this.deps=deps}bind(sessionId,writer){this.writer=writer,this.route=writer.secretInputRoute(sessionId,!0),this.route.bindSealedResponder?.({settled:()=>{},respond:(answer4,claim)=>this.forward(answer4,claim)})}refuses(uiRequestId){return this.ids.has(uiRequestId)&&this.route?.accepts(uiRequestId)!==!0}exited(){this.route?.bindSealedResponder?.(void 0);for(let id of this.ids.ids())this.settledIds.has(id)||(this.route?.sealedOutcome?.(id,"unavailable",void 0),this.route?.settled(id));for(let id of this.ids.ids())this.route?.forget(id);this.ids.clear(),this.forwarded.clear(),this.settledIds.clear()}receive(message){switch(message.type){case"secret_select":return this.select(message),!0;case"secret_frame":if("type"in message.record&&message.record.type==="secret_sealed_offer"&&!isSealedOffer(message.record)||!this.ids.admitFrame(message.id,message.record))return acknowledge(message.signal,!1),!0;if(isSealedOffer(message.record)){let{hpkePk,title,placeholder,deadlineAtMs}=message.record;this.route?.offerSealed?.(message.id,{hpkePk,title,placeholder,deadlineAtMs})}else this.route?.send(message.id,message.record);return acknowledge(message.signal,!0),!0;case"secret_settled":return this.admitsSettle(message)?(this.settledIds.add(message.id),message.outcome!==void 0&&this.route?.sealedOutcome?.(message.id,message.outcome,message.winnerGrant),this.route?.settled(message.id),acknowledge(message.signal,!0),!0):(acknowledge(message.signal,!1),!0);case"secret_forget":return this.ids.forget(message.id),this.forwarded.delete(message.id),this.settledIds.delete(message.id),this.route?.forget(message.id),acknowledge(message.signal,!0),!0;case"secret_handshake":return this.writer?.setSoleSecretCapabilities(message.capabilities),acknowledge(message.signal,!0),!0;default:return!1}}select(message){if(!this.ids.has(message.id)&&!this.ids.admitsNew()){acknowledge(message.signal,!1);return}let select=()=>{let route=this.route,reason=route?.select(message.id,()=>this.deps.post({type:"cancel_secret",id:message.id}))??(route?void 0:"no_presenter");reason===void 0&&this.ids.add(message.id);let result=reason===void 0?{accepted:!0,connection:route?.presenter(message.id),raiser:route?.raiser?.(message.id)??!0,sealed:route?.sealed?.(message.id)??!1}:{accepted:!1,reason},encoded=new TextEncoder().encode(JSON.stringify(result));new Uint8Array(message.decision,4).set(encoded),Atomics.store(new Int32Array(message.decision,0,1),0,encoded.length),acknowledge(message.signal,!0)};message.connection!==void 0&&this.writer?this.writer.withConnection(message.connection,select):select()}admitsSettle(message){let{id,outcome,winnerGrant}=message;return!this.ids.has(id)||this.settledIds.has(id)||outcome!==void 0&&!OUTCOMES.has(outcome)?!1:winnerGrant===void 0||(outcome==="answered"||outcome==="cancelled")&&this.forwarded.get(id)?.has(winnerGrant)===!0}forward(answer4,claim){let id=answer4.uiRequestId,queued=this.queue.get(id);if(!this.ids.has(id)||(queued?.depth??0)>=SEALED_ANSWERS_PER_ID)return Promise.resolve({error:"secret_answer_refused"});let run2=async()=>{if(!claim.current())return{error:"secret_answer_refused"};let forwarded=this.forwarded.get(id)??new Set;forwarded.add(answer4.grantId),this.forwarded.set(id,forwarded);let reply=await this.deps.request({type:"secret_sealed_answer",answer:answer4});return reply.type==="secret_sealed_result"?isolateReply(reply.reply):{error:"secret_answer_refused"}},result=(queued?.tail??Promise.resolve()).then(run2).catch(()=>({error:"secret_answer_refused"})),entry2={tail:result.then(()=>{}),depth:(queued?.depth??0)+1};return this.queue.set(id,entry2),result.finally(()=>{let current=this.queue.get(id);current===entry2?this.queue.delete(id):current&&current.depth--}),result}};import{randomUUID as randomUUID4}from"node:crypto";import{fileURLToPath}from"node:url";import{Worker}from"node:worker_threads";var compiledWorkerEntry=typeof SENPI_RPC_SESSION_WORKER_ENTRY=="string"?SENPI_RPC_SESSION_WORKER_ENTRY:"./src/modes/rpc/session-worker.ts";function startSessionWorker(webviewBroker){return sessionWorkerDataRegistry.spawn(issued=>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),{workerData:{hostProcessStartedAtMs:ownProcessStartedAtMs(),extensionData:issued.extensionData,...webviewBroker?{webviewBroker:webviewBroker.port}:{}},transferList:[...webviewBroker?[webviewBroker.port]:[],...issued.transfer]}))}async function reconcileWorkerReplacement(message,lane,callbacks){message.snapshot&&(message.bootstrap&&compactUpdatesEnabled()&&await lane?.generations.bind(message.snapshot.state.sessionId),await callbacks.reconcile(message.snapshot.liveSessionPaths))}var SessionWorkerClient=class{constructor(callbacks,agentDir=recoveryAgentDir){this.secrets=new WorkerHostSecrets({post:message=>this.post(message),request:message=>this.request(message)}),this.privateOperations=new Map,this.webviewBroker=createWebViewBroker(),this.bindingReady=!1,this.request=message=>this.requests.request(message),this.requests=new SessionWorkerRequests(message=>this.worker.postMessage(message),()=>this.fail("session_worker_request_timeout")),this.stopped=!1,this.options={},this.listeners=new Set,this.cancelUiPending=!1,this.stopLimitMirror=()=>{},this.owners=new WorkerOwnerGates,this.callbacks=callbacks,this.agentDir=agentDir,this.spawned=startSessionWorker(this.webviewBroker),this.worker=this.spawned.result,this.exited=new Promise((resolve4,reject)=>{this.worker.once("exit",()=>{this.intake?.permits.close(),this.secrets.exited(),this.stopPrivateBinding?.(),this.privateBinding?.dispose(),this.owners.retireAll(),this.spawned.issued.dispose();for(let operation of this.privateOperations.values())operation.operation.abort();this.privateOperations.clear(),!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.stopLimitMirror(),this.listeners.clear();let released=callbacks.exit();released?released.then(()=>{this.publishTerminalFailure(),resolve4()},reject):(this.publishTerminalFailure(),resolve4())})}),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){this.stopLimitMirror(),this.stopLimitMirror=subscriptionLimits.subscribeMirror(limits=>this.post({type:"subscription_limits",accounts:[limits]}));let result=await this.request({type:"prepare",configuration,profile,subscriptionLimits:subscriptionLimits.mirrorSnapshot()});if(result.type!=="prepared")throw new Error("Invalid worker prepare response");return result.sessionPath}async setPromptSurface(surface){if((await this.request({type:"prompt_surface",surface})).type!=="result")throw new Error("Invalid worker prompt_surface response")}async setBrowserEngine(engine){if((await this.request({type:"browser_engine",engine})).type!=="result")throw new Error("Invalid worker browser_engine response")}async setPermissionPreset(preset){if((await this.request({type:"permission_preset",preset})).type!=="result")throw new Error("Invalid worker permission_preset response")}async commit(){if(!compactUpdatesEnabled()){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}let nonce=randomUUID4(),acceptance=new SessionAcceptanceLane(void 0,void 0,this.agentDir),intake=new WorkerIntake(acceptance.staging,error2=>this.fail(error2));this.acceptance=acceptance,this.intake=intake;let negotiated=!1;try{let result=await this.request({type:"commit",acceptance:!0,recoveryEpoch:nonce,permits:intake.permits.block});if(result.type!=="ready")throw new Error("Invalid worker commit response");if(!result.bootstrap)throw new StructuredLaneUnavailableError;return acceptance.bootstrap(result.bootstrap,nonce),negotiated=!0,this.snapshot=result.snapshot,result.snapshot}finally{negotiated||(intake.permits.close(),acceptance.retire("close"),this.acceptance=this.intake=void 0)}}async bind(sessionId,writer,requestClose,options){this.sessionId=sessionId,this.writer=writer,this.secrets.bind(sessionId,writer),this.acceptance&&writer.registerAcceptance(sessionId,this.acceptance),compactUpdatesEnabled()&&process.stderr.write(`senpi rpc worker ${sessionId}: bound mode=${this.acceptance?"acceptance":"legacy"}
`),this.requestClose=requestClose,this.options=options;let bound=writer.connectionContext.delegation;return await this.request({type:"bind",sessionId,capabilities:options.capabilities??[],connection:writer.currentConnection(),roles:options.connectionRoles?.rolesOf(roleConnection(writer.currentConnection()),bound?.incarnation),...bound===void 0?{}:{delegation:bound},mcpFormsEnforced:writer.mcpPresenters!==void 0}),{handle:async command=>{if(writer.handleMcpForm(command))return;let connection2=writer.currentConnection(),owner=this.owners.capture(writer.connectionContext,connection2,command),answered="type"in command&&command.type==="extension_ui_response"?answeredUiRequestId(command):void 0;if(answered!==void 0&&writer.acceptWorkerGrantResponse(sessionId,answered,connection2)===!1)return;if(answered!==void 0&&this.secrets.refuses(answered)){let response=command;writer.enqueue(sessionId,refusedExtensionUiResponse(response.id,"secret_answer_refused"));return}let delegation=writer.connectionContext.delegation,exec=commandAuthority.getStore()?.exec;await this.request({type:"command",admissionReply:captureAdmissionReply(),command,connection:connection2,roles:options.connectionRoles?.rolesOf(roleConnection(connection2),delegation?.incarnation),...originField(options.connectionRoles?.originOf(connection2)),...owner===void 0?{}:{owner},...delegation===void 0?{}:{delegation},...exec===void 0?{}:{exec}})},cancelPendingExtensionUiRequests:()=>this.post({type:"cancel_ui"}),connectionDetached:connection2=>this.postRetired(this.owners.detach(writer.connectionContext,connection2)),dispose:async()=>{this.postRetired(this.owners.retireAll()),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.intake?.permits.close(),this.stopped=!0,this.requests.close(new Error("session_closing")),this.worker.terminate()}postRetired(owners){owners.length>0&&this.post({type:"owners_retired",owners})}post(message){if(!this.stopped){if(message.type==="cancel_ui"){if(this.cancelUiPending)return;this.cancelUiPending=!0}this.worker.postMessage(message)}}receive(message){if(this.requests.noteProgress(),this.stopped){"signal"in message&&message.signal&&acknowledge(message.signal,!1);return}if(this.intake?.received(message),!this.secrets.receive(message))switch(message.type){case"mcp_form_bind":{this.stopPrivateBinding?.(),this.privateBinding?.dispose();let writer=this.writer,sessionId=this.sessionId;if(!writer?.mcpPresenters||!sessionId){this.fail("private_form_unavailable");return}let bound=writer.bindMcpForms(sessionId,message.durableId,{},()=>{});if(bound instanceof Promise){this.fail("private_form_unavailable");return}this.privateBinding=writer.getMcpFormBinding(sessionId);let binding2=this.privateBinding;if(!binding2){this.fail("private_form_unavailable");return}let unsubscribe=binding2.subscribe?.(()=>this.post({type:"mcp_form_availability",epoch:binding2.epoch,version:binding2.version?.()}));this.stopPrivateBinding=()=>{unsubscribe?.(),bound?.()},this.post({type:"mcp_form_bound",id:message.id,epoch:binding2.epoch,version:binding2.version?.()});return}case"mcp_form_ready":{let binding2=this.privateBinding;this.post({type:"mcp_form_availability",id:message.id,epoch:message.epoch,version:binding2?.epoch===message.epoch?binding2.version?.():void 0});return}case"mcp_form_release":this.privateBinding?.epoch===message.epoch&&this.stopPrivateBinding?.();return;case"mcp_form_cancel":{let operation=this.privateOperations.get(message.id);operation?.epoch===message.epoch&&operation[message.lifetime].abort();return}case"mcp_form_create":{let binding2=this.privateBinding,presenter=binding2?.epoch===message.epoch&&binding2.version?.()===message.version?binding2.capture():void 0,operation=new AbortController,presentation=new AbortController;this.privateOperations.set(message.id,{operation,presentation,epoch:message.epoch});let fence=new Int32Array(message.operationFence),result=presenter?.present({...message.input,operationSignal:operation.signal,presentationSignal:presentation.signal,operationCurrent:()=>Atomics.load(fence,0)===0});Promise.resolve(result).then(outcome=>{this.privateOperations.delete(message.id),this.post({type:"mcp_form_settlement",id:message.id,epoch:message.epoch,settlementId:randomUUID4(),outcome:outcome??{kind:"processing_failure",source:"host_termination",humanAdmission:!1}})});return}case"secret_sealed_result":this.requests.receive(message);return;case"prepared":case"ready":case"result":{this.requests.receive(message),this.snapshot&&Promise.resolve(this.callbacks.reconcile(this.snapshot.liveSessionPaths)).catch(()=>this.fail("session_claim_reconcile_failed"));return}case"reserve":Promise.resolve(this.callbacks.reserve(message.path)).then(grant=>acknowledgeGrant(message.signal,this.stopped?"conflict":grant),()=>acknowledgeGrant(message.signal,"conflict"));return;case"snapshot":this.snapshot=message.snapshot,Promise.resolve(this.callbacks.reconcile(message.snapshot.liveSessionPaths)).then(()=>{if(acknowledge(message.signal,!this.stopped),message.settled)for(let listener of[...this.listeners])listener()},()=>{acknowledge(message.signal,!1),this.fail("session_claim_reconcile_failed")});return;case"control_done":this.cancelUiPending=!1;return;case"output":{let writer=this.writer,sessionId=this.sessionId;if(!writer||!sessionId||this.stopped){acknowledge(message.signal,!1);return}let lane=this.acceptance;if(this.intake?.inOrder(message)===!1)return;message.snapshot?this.snapshot=message.snapshot:this.snapshot&&(this.snapshot={...this.snapshot,...message.activity,state:{...this.snapshot.state,isStreaming:message.activity.streaming}});let record=message.recordText===void 0?message.record:JSON.parse(message.recordText);if("type"in record&&record.type==="security_grant_settled"&&"id"in record&&typeof record.id=="string"){writer.settleGrantDialog(sessionId,record.id),acknowledge(message.signal,!0);return}if("type"in record&&record.type==="security_notice_snapshot"){if(!("snapshot"in record)||!isSecurityNoticeState(record.snapshot)){acknowledge(message.signal,!1),this.fail("invalid_security_notice_snapshot");return}writer.acceptWorkerSecuritySnapshot(sessionId,record.snapshot),acknowledge(message.signal,!0);return}let outputConnection=message.connection;if(isGrantSelectRequest(record)){let title=Reflect.get(record,"title"),target=writer.routeWorkerGrant(sessionId,record.id,message.connection,this.options.capabilities??[],()=>this.post({type:"cancel_grant",id:record.id}),typeof title=="string"?title:void 0);if(!target.accepted){acknowledge(message.signal,!0);return}outputConnection=target.connection}let enqueue=()=>withAdmissionReply(message.admissionReply,()=>(message.bootstrap?lane?.bootstrap(message.bootstrap):(lane?.applyTranscript(message.transitions??[]),lane?.accept(record,message.recovery,frameUnit(message),message.canonicalRefused===!0,message.callKey)),enqueueLegacyRecord(writer,sessionId,record)?writer.waitForSessionBackpressure(sessionId):(acknowledge(message.signal,!1),this.fail("session_output_overflow_or_closed"),Promise.reject(new Error("session_output_overflow_or_closed")))));reconcileWorkerReplacement(message,lane,this.callbacks).then(()=>outputConnection===void 0?enqueue():message.owner===void 0||outputConnection!==message.connection?writer.withConnection(outputConnection,enqueue):writer.connectionContext.runCaptured(outputConnection,message.owner,enqueue)).then(()=>acknowledge(message.signal,!0),cause=>{acknowledge(message.signal,!1),this.fail(cause instanceof Error?cause.message:String(cause))});return}case"canonical":case"canonical_unavailable":if(!this.writer||!this.sessionId||this.stopped){acknowledge(message.signal,!1);return}if(this.intake?.inOrder(message)===!1)return;message.type==="canonical"?this.acceptance?.acceptControl(frameUnit({...message,canonical:message.record})):this.acceptance?.compactUnavailable(canonicalLoss(message)),acknowledge(message.signal,!0);return;case"capabilities":this.options=workerCapabilities(this.options,message,this.writer);return;case"loaded_surfaces":{let writer=this.writer,sessionId=this.sessionId;if(!writer||!sessionId||this.stopped){acknowledge(message.signal,!1);return}writer.publishLoadedSurfacesChanged(sessionId,message.previous,message.digest),acknowledge(message.signal,!0);return}case"fragment":this.intake?.fragment(message)?.then(whole=>this.receive(whole),()=>this.fail("session_worker_transfer_unreadable"));return;case"request_close":this.requestClose?.();return;case"subscription_limits":subscriptionLimits.adopt(message.limits);return;case"failure":this.fail(message.error);return}}fail(error2){this.stopped||(this.acceptance?.retire("worker_failed"),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"))}};import{isAbsolute as isAbsolute4}from"node:path";var WorkerSessionClaims=class{constructor(reservations){this.paths=new Map,this.releases=new Set,this.closed=!1,this.reservations=reservations}async claim(path,attached=!0){if(this.closed)throw new RpcSessionRegistryError("session_closing");if(!this.reservations)return;let previous=this.paths.get(path);if(previous)return previous.ownership;let record={ownership:this.reservations.claim(path,attached),attached};this.paths.set(path,record);let owner=await record.ownership;return owner&&this.paths.get(path)===record&&this.paths.delete(path),owner}setAttached(attached){for(let[path,record]of this.paths)record.attached!==attached&&(record.attached=attached,record.ownership.then(owner=>{!owner&&this.paths.get(path)===record&&this.reservations?.setAttached(path,record.attached)}))}reconcile(livePaths,attached){let live=new Set(livePaths);for(let path of this.paths.keys())live.has(path)||this.release(path);this.setAttached(attached)}release(path){let record=this.paths.get(path);if(!record)return Promise.resolve();this.paths.delete(path);let removal=record.ownership.then(async owner=>{owner||await this.reservations?.release(path)});return this.releases.add(removal),removal.then(()=>this.releases.delete(removal),()=>this.releases.delete(removal)),removal}async close(){this.closed=!0,await Promise.all([...this.paths.keys()].map(path=>this.release(path)).concat([...this.releases]))}};async function openWorkerSession(host,profile,options){if(!isAbsolute4(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute4(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?host.knownReservationKey(profile.sessionPath):void 0;for(let entry3 of host.entries.values())if(entry3.state!=="closed"&&entry3.durableSessionId===requestedDurableId&&!(requestedKey!==void 0&&entry3.reservationKey===requestedKey))throw new RpcSessionRegistryError("session_id_in_use")}let knownKey=profile.sessionPath?host.knownReservationKey(profile.sessionPath):void 0;for(let entry3 of host.entries.values()){if(entry3.state!=="quarantined")continue;let samePath=profile.sessionPath!==void 0&&(entry3.sessionPath===profile.sessionPath||knownKey!==void 0&&entry3.reservationKey===knownKey),sameId=requestedDurableId!==void 0&&entry3.durableSessionId===requestedDurableId;if(!(!samePath&&!sameId))throw new RpcSessionRegistryError("session_path_in_use",void 0,{reason:"session_quarantined",action:"retry",retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}let owner=knownKey?host.reservations.owner(knownKey):void 0;if(knownKey&&owner)return host.attach(owner,knownKey,options,profile);if(options?.attachOnly)throw new RpcSessionRegistryError("session_not_held",void 0,{reason:"session_not_held",action:"rediscover_holder"});if(host.size>=SESSION_WORKER_LIMITS.workers)throw new Error("too_many_sessions");let handle2=options?.routedHandle??host.nextHandle(),claims=new WorkerSessionClaims(host.options.pathReservations);host.claims.set(handle2,claims);let storedProfile=frozenProfile(profile),entry2={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),cwd:profile.cwd,attachments:options?.unattached?0:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:host.now(),lifecycleMutex:Promise.resolve(),...requestedDurableId!==void 0?{durableSessionId:requestedDurableId}:{}},workerFailure,worker=host.createWorker({reserve:path=>host.reserve(handle2,path),reconcile:livePaths=>host.reconcile(handle2,livePaths),exit:()=>{if(host.entries.get(handle2)!==entry2)return;let finish=()=>{host.entries.get(handle2)===entry2&&(entry2.state="closed",host.entries.delete(handle2),host.claims.delete(handle2),host.reservations.releaseAll(handle2),entry2.closeResolve?.())};return releaseWithinGrace({closeGraceMs:host.closeGraceMs,releaseReservation:()=>claims.close()},handle2,entry2.reservationKey??handle2).then(finish)},failure:error2=>{workerFailure=error2,entry2.state="quarantined",process.stderr.write(`senpi rpc session ${handle2} quarantined: ${error2}
`)}});entry2.worker=worker,host.entries.set(handle2,entry2);let timer=startOpenTimer(`worker-open:${handle2}`);try{let path=await worker.prepare(host.options.configuration,profile).catch(typedWorkerRefusal);timer.mark("prepare");let owner2=host.reservations.owner(path);if(owner2){let attached=await host.attach(owner2,path,options,profile);return entry2.state="quarantined",worker.quarantine(),attached}let predecessor=await claims.claim(path);if(timer.mark("claim"),predecessor)throw new RpcSessionRegistryError("session_path_in_use",void 0,{owner:predecessor,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS});let grant=await host.reserve(handle2,path);if(timer.mark("reserve"),grant!=="granted")throw new RpcSessionRegistryError(RESERVATION_DENIAL_CODES[grant]);entry2.reservationKey=path,entry2.requestedPathKey=profile.sessionPath?path:void 0,entry2.sessionPath=path;let snapshot=await worker.commit();if(timer.mark("commit"),compactUpdatesEnabled()&&await worker.acceptance?.generations.bind(snapshot.state.sessionId),entry2.state!=="opening")throw workerFailure===void 0?new RpcSessionRegistryError("session_closing"):new RpcSessionRegistryError("open_failed",workerFailure.replace(/^open_failed: /,""));return entry2.durableSessionId=snapshot.state.sessionId,entry2.cwd=snapshot.state.cwd,entry2.state="open",host.openResult(handle2,entry2)}catch(cause){throw entry2.state="quarantined",worker.quarantine(),workerFailure!==void 0&&closedByWorkerDeath(cause)?new RpcSessionRegistryError("open_failed",workerFailure.replace(/^open_failed: /,"")):cause}}var WorkerSessionRegistry=class{constructor(options){this.supportsCompact=()=>!0,this.entries=new Map,this.reservations=new SessionPathReservations,this.claims=new Map,this.serial=0,this.options=options,this.closeGraceMs=options.closeGraceMs,this.now=options.now;let createWorker=options.createWorker??(callbacks=>new SessionWorkerClient(callbacks,options.configuration.agentDir));this.createWorker=callbacks=>outsideCommand(()=>createWorker(callbacks)),options.capacity?.track(()=>this.entries.size)}get size(){return this.entries.size}reserveHandle(){return`rpc-${++this.serial}`}holderPids(observedStarts){return this.options.pathReservations?.holderPids?.(observedStarts)??Promise.resolve([])}openSession(profile,options){return openWorkerSession({entries:this.entries,reservations:this.reservations,claims:this.claims,options:this.options,closeGraceMs:this.closeGraceMs,size:this.options.capacity?.inUse()??this.size,now:this.now,nextHandle:()=>this.reserveHandle(),knownReservationKey:path=>this.knownReservationKey(path),attach:(owner,path,options2,requested)=>this.attach(owner,path,options2,requested),reserve:(handle2,path)=>this.reserve(handle2,path),reconcile:(handle2,paths)=>this.reconcile(handle2,paths),openResult:(handle2,entry2)=>this.openResult(handle2,entry2),createWorker:this.createWorker},profile,options)}peek(handle2){return this.entries.get(handle2)}attachSession(handle2){return attachLiveSession(this.entries.get(handle2),this.now(),()=>this.claims.get(handle2)?.setAttached(!0))}getForCommand(handle2,command){let entry2=this.entries.get(handle2);if(!entry2)throw new RpcSessionRegistryError("unknown_session");if(entry2.state==="quarantined"||entry2.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(command))throw new RpcSessionRegistryError("session_closing");if(entry2.state!=="open"&&entry2.state!=="closing")throw new RpcSessionRegistryError("unknown_session");return(entry2.attachments>0||refreshesSessionActivity(command))&&(entry2.lastCommandAt=this.now()),entry2}beginClose(handle2,onRole,options){let entry2=this.entries.get(handle2);if(!entry2)throw new RpcSessionRegistryError("unknown_session");if(entry2.state==="closing"||entry2.state==="quarantined")return onRole?.(!1),entry2;if(entry2.state!=="open"&&entry2.state!=="opening")throw new RpcSessionRegistryError("unknown_session");return entry2.attachments--,entry2.attachments>0?entry2:options?.detach&&entry2.retainOnDisconnect?(entry2.attachments=0,entry2.detachedAt??=this.now(),entry2.worker?.busy||this.claims.get(handle2)?.setAttached(!1),entry2):(entry2.state="closing",entry2.closeCompletion=new Promise(resolve4=>{entry2.closeResolve=resolve4}),onRole?.(!0),entry2)}close(handle2){return this.beginClose(handle2).state==="closing"?this.closeMarked(handle2):Promise.resolve()}async closeMarked(handle2){let entry2=this.entries.get(handle2);if(entry2?.state!=="closing"||!entry2.worker)throw new RpcSessionRegistryError("unknown_session");if(entry2.closeStarted)return entry2.closeCompletion;entry2.closeStarted=!0;let timer;await Promise.race([entry2.worker.close(this.closeGraceMs),new Promise(resolve4=>{timer=setTimeout(()=>{entry2.state!=="closed"&&(entry2.state="quarantined"),resolve4()},this.closeGraceMs)})]),timer&&clearTimeout(timer)}list(){let now=this.now();return[...this.entries].map(([sessionId,entry2])=>{let state=entry2.worker?.snapshot?.state;return{sessionId,durableSessionId:state?.sessionId??entry2.durableSessionId,sessionPath:state?.sessionFile??entry2.sessionPath,cwd:state?.cwd??entry2.cwd,name:state?.sessionName,kind:entry2.kind,context:publishedSessionContext(entry2.context,entry2.contextOverlay),attachments:Math.max(0,entry2.attachments),retain_on_disconnect:entry2.retainOnDisconnect===!0,status:entry2.state==="quarantined"?"closing":entry2.state,idleMs:Math.max(0,now-entry2.lastCommandAt),tool_child:{state:"none"},...sessionRowStatusFields(entry2)}})}knownReservationKey(path){if(this.reservations.owner(path))return path;for(let entry2 of this.entries.values()){if(entry2.profile.sessionPath===path&&entry2.requestedPathKey&&this.reservations.owner(entry2.requestedPathKey))return entry2.requestedPathKey;let snapshot=entry2.worker?.snapshot;if(snapshot?.state.sessionFile===path)return snapshot.sessionPath}}async attach(owner,path,options,requested={cwd:""}){let{promptSurface,browserEngine}=requested,permissionPreset=clientNamedPreset(requested),entry2=this.entries.get(owner);if(entry2?.state!=="open"||!entry2.worker?.bindingReady||entry2.worker.snapshot?.sessionPath!==path)throw new RpcSessionRegistryError("session_path_in_use");promptSurface!==void 0&&promptSurface!==entry2.profile.promptSurface&&(entry2.profile=frozenProfile({...entry2.profile,promptSurface}),await entry2.worker.setPromptSurface(promptSurface)),browserEngine!==void 0&&browserEngine!==entry2.profile.browserEngine&&(entry2.profile=frozenProfile({...entry2.profile,browserEngine}),await entry2.worker.setBrowserEngine(browserEngine)),permissionPreset!==void 0&&(entry2.profile=frozenProfile(withClientPreset(entry2.profile,permissionPreset)),await entry2.worker.setPermissionPreset(permissionPreset));let result=this.openResult(owner,entry2);return options?.unattached===!0?{...result,attached:!0}:(entry2.attachments++,this.claims.get(owner)?.setAttached(!0),options?.retainOnDisconnect&&(entry2.retainOnDisconnect=!0),entry2.lastCommandAt=this.now(),{...result,attached:!0})}reservationCount(handle2){return this.reservations.count(handle2)}async reserve(handle2,path){let entry2=this.entries.get(handle2);if(!entry2)return"conflict";if(this.reservations.owner(path)===handle2)return"granted";if(entry2.state!=="opening"&&entry2.state!=="open")return"conflict";let grant=this.reservations.reserve(handle2,path,this.liveWorkerPaths(entry2));if(grant!=="granted")return grant;if(await this.claims.get(handle2)?.claim(path,entry2.attachments>0||entry2.worker?.busy===!0)||this.entries.get(handle2)!==entry2||entry2.state!=="opening"&&entry2.state!=="open"){let live=this.liveWorkerPaths(entry2);return this.reservations.reconcile(handle2,live??{livePaths:[],sessionPath:entry2.reservationKey}),"conflict"}return"granted"}async reconcile(handle2,livePaths){let entry2=this.entries.get(handle2);if(entry2?.state!=="open")return;let sessionPath=entry2.worker?.snapshot?.sessionPath,attached=entry2.attachments>0||entry2.worker?.busy===!0;if(sessionPath){if(await this.claims.get(handle2)?.claim(sessionPath,attached))throw new RpcSessionRegistryError("session_path_in_use");if(this.entries.get(handle2)!==entry2||entry2.state!=="open")return}this.reservations.reconcile(handle2,{livePaths,sessionPath}),this.claims.get(handle2)?.reconcile(sessionPath?[...livePaths,sessionPath]:livePaths,attached),sessionPath&&(entry2.reservationKey=sessionPath,entry2.sessionPath=sessionPath)}liveWorkerPaths(entry2){let snapshot=entry2.state==="open"?entry2.worker?.snapshot:void 0;if(snapshot)return{livePaths:snapshot.liveSessionPaths,sessionPath:snapshot.sessionPath}}openResult(handle2,entry2){let state=entry2.worker?.snapshot?.state;if(!state)throw new RpcSessionRegistryError("open_failed");return{sessionId:handle2,durableSessionId:state.sessionId,sessionPath:state.sessionFile}}};var WINDOWS_SHUTDOWN_HARD_EXIT_MS=2e3,WINDOWS_SHUTDOWN_DISPOSE_BOUND_MS=1e4;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,hooks={}){options.mcpPresenterEnforcement===!0&&writer.enableMcpPresenters();let machineOwned=options.sessionOwner==="machine",policy=resolveHostIdlePolicy(process.env,machineOwned?{...idle,emptyExitMs:Number.POSITIVE_INFINITY}:idle),endpointSocket=publicEndpointSocket(options),pathReservations=createEndpointReservations({agentDir:options.agentDir,socket:listenSocketPath(options),instanceId:hostInstanceId(),publicSocket:hostContext?.host_socket,onFailure:hostLog}),registry=options.workerConfiguration?new WorkerSessionRegistry({configuration:options.workerConfiguration,now:policy.now,closeGraceMs:idle.closeGraceMs??parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV])??1e4,pathReservations}):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,...hooks.onSessionCountChange?{onSizeChange:hooks.onSessionCountChange}:{},pathReservations}),machineOps=new MachineOpHandler({agentDir:options.agentDir}),router=new SessionCommandRouter(registry,writer,hostContext?{...options,hostContext}:options,options.createBinding,{capabilities},{now:policy.now,idleEvictionMs:policy.idleEvictionMs,emptyExitMs:policy.emptyExitMs,onEmptyExit:idle.onEmptyExit===void 0?void 0:()=>{machineOps.hold(),idle.onEmptyExit?.()},onHandoffParked:idle.onHandoffParked,...endpointSocket===void 0?{}:{handoverParkedDir:createHostDaemonPaths({socket:endpointSocket,agentDir:options.agentDir}).dir},canExitWhenEmpty:()=>(idle.canExitWhenEmpty?.()??!0)&&!machineOps.busy()});endpointSocket!==void 0&&reopenHandoverParkedSessions(async entry2=>{let refused4=await router.reopenParked(entry2);if(refused4?.success!==!1)return;let detail2=typeof refused4.errorData=="object"&&refused4.errorData!==null&&!Array.isArray(refused4.errorData)?Object.fromEntries(Object.entries(refused4.errorData)):void 0;throw refused4.error==="session_path_in_use"?new RpcSessionRegistryError("session_path_in_use",void 0,detail2):new RpcSessionRegistryError("open_failed",refused4.error)},options.agentDir,endpointSocket,{hostInstance:hostInstanceId(),hostSocket:endpointSocket,...hooks.shouldReopenParked!==void 0?{shouldReopen:hooks.shouldReopenParked}:{},onProgress:state=>router.setInheritedHandover(state)}).catch(cause=>{router.setInheritedHandover(void 0),process.stderr.write(`senpi rpc successor reopen parked set failed: ${String(cause)}
`)});let gate=new HostCoreGate(registry,command=>router.handle(command),{...hooks,machineWork:machineOps}),handle2=async line=>{let connection2=writer.currentConnection(),parsed2;try{parsed2=JSON.parse(line)}catch{await writer.enqueueControl(writer.delegations.unparsable(connection2,"Failed to parse command: invalid JSON"));return}let delegation=writer.connectionContext.delegation;if(delegation?.mode!=="host")return handleParsed(connection2,parsed2);let exec=takeRelayExec(parsed2);if(exec==="malformed"){await writer.enqueueControl(relayExecRefusal(parsed2));return}return commandAuthority.run(new CommandAuthority(connection2,delegation,exec),()=>handleParsed(connection2,parsed2))},handleParsed=async(connection2,parsed2)=>{if(connection2?.startsWith("generation-route-")&&!router.admitsRoutedRecord(connection2,parsed2)){let record=authRecord(parsed2);await writer.enqueueControl({type:"response",id:record?.id,command:record?.type,success:!1,error:"host_draining"});return}let delegation=writer.delegations.inspect(connection2,parsed2);if(delegation.kind==="machine_op"){await writer.enqueueControl(await machineOps.answer(delegation.command,parsed2,delegation.id));return}if(delegation.kind!=="pass"){let declaration=authRecord(parsed2);connection2&&declaration?.type==="declare_delegation"&&delegation.kind==="reply"&&delegation.response.success&&await router.configureRoutes(connection2,declaration),await answerDelegation(writer,delegation,parsed2);return}let delegated=writer.delegations.isDelegated(connection2);if(writer.handleMcpForm(parsed2)||await gate.intercept(parsed2,answer4=>writer.enqueueControl(answer4)))return;let shapeError=rpcCommandShapeError(parsed2);if(shapeError){await writer.enqueueControl(parseError(shapeError));return}let command=parsed2,response=await gate.dispatch(withOpenRetention(command,delegated,machineOwned));connection2&&command.type==="set_client_info"&&!command.sessionId&&authRecord(response)?.success===!0&&await router.configureRoutes(connection2,command),response&&await writer.enqueueControl(response),writer.delegations.lineAnswered(connection2)};return{router,handle:handle2,machineOps,handover:gate.handover,handoverAnswered:()=>gate.answered(),warm:"warm"in registry?registry.warm:void 0,peekSession:sessionId=>registry.peek(sessionId)}}async function runStdioHost(options){takeOverStdout();let sink={writeRaw:writeRawStdout,waitForBackpressure:waitForRawStdoutBackpressure},writer=new SessionEventWriter(sink.writeRaw,sink.waitForBackpressure),runtimeBuildId=await startupRuntimeBuildId(),trim=createZeroSessionTrim(writer,()=>router.sessionCount),{router,handle:handle2,warm,machineOps}=createHostCore(options,writer,void 0,{onEmptyExit:()=>{shutdown(0)}},void 0,{...runtimeBuildId===void 0?{}:{runtimeBuildId},onSessionCountChange:size=>trim.observe(size)}),observers=startHostObservers(router,writer,{trim}),shuttingDown=!1,shutdown=async(exitCode=0)=>{shuttingDown&&process.exit(exitCode),shuttingDown=!0,observers.stop(),detach(),await router.dispose(),await machineOps.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)}
`)},detachReader=attachJsonlLineReader(process.stdin,line=>{handle2(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),warmAtBootForPrivateFds(warm,{cwd:options.cwd},hostLog),new Promise(()=>{})}async function runSocketHost(options,socketPath){await prepareSocketPath(socketPath),publishHostInstanceId(hostInstanceId());let writer=new SessionEventWriter(()=>{}),connections=new Map,occupancy=new ClientOccupancy(()=>{},hostInstanceId()),draining=!1,handoffAnnounced=!1,handoff=new HandoffAnnouncement,hostContext=hostSessionContext(socketPath),runtimeBuildId=await startupRuntimeBuildId(),expected=process.env[EXPECTED_RUNTIME_BUILD_ID_ENV];expected!==void 0&&expected!==runtimeBuildId&&(hostLog(`runtime ${runtimeBuildId??"unreadable"} is not the handover target ${expected}; exiting`),process.exit(1));let canHandOver=runtimeBuildId!==void 0&&process.platform!=="win32",trim=createZeroSessionTrim(writer,()=>router.sessionCount),{router,handle:handle2,handover,handoverAnswered,warm,machineOps}=createHostCore(options,writer,[...parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")),GENERATION_HANDOFF_CAPABILITY,ENDPOINT_OWNER_FENCE_CAPABILITY,...canHandOver?[RUNTIME_IDENTITY_HANDOVER_CAPABILITY]:[]],{onEmptyExit:()=>{shutdown(0)},canExitWhenEmpty:()=>draining||occupancy.attachedCount===0&&occupancy.unclassifiedCount===0&&!occupancyWatch.watching,onHandoffParked:async ids=>{await Promise.all(ids.map(async id=>{await writer.flushConnection(id),await connections.get(id)?.close("host_handoff")}))}},hostContext,{onSessionCountChange:size=>{trim.observe(size),occupancyWatch.refresh()},shouldReopenParked:()=>!draining,...runtimeBuildId!==void 0&&{runtimeBuildId},...canHandOver&&{endpoint:{agentDir:options.agentDir,socket:hostWatchdogBinding()?.publicSocket??socketPath},handover:{identity:()=>({instanceId:hostInstanceId(),generation:hostGeneration(process.env),runtimeBuildId,engine:engineBuildIdentity()}),perform:async request=>performIdleHandover({presenterBootstrap:presenterControl?.successorBootstrapProvider(),request,socket:hostWatchdogBinding()?.publicSocket??socketPath,agentDir:options.agentDir}),log:hostLog}}}),occupancyWatch=new HostOccupancyWatch({connections:()=>connections.keys(),attached:id=>{let socket=connections.get(id)?.socket;return socket!==void 0&&occupancy.isAttached(socket)},holdsSessions:id=>router.holdsSessions(id),send:(id,record)=>{writer.enqueueControl(record,id).catch(cause=>hostLog(`host_occupancy to ${id} failed: ${errorMessage(cause)}`))}}),presenter=await startMcpPresenterControl(writer,{enforcement:options.mcpPresenterEnforcement,bootstrap:options.presenterBootstrapFd===void 0?void 0:presenterBootstrapStream(options.presenterBootstrapFd),account:options.presenterAccountAuthority}),presenterControl=presenter?.control,presenterDir=presenter?.dir,observers=startHostObservers(router,writer,{trim,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;writer.endExhaustedConnections(id=>connections.get(id)?.sink);let secret=process.platform==="win32"?await ensureSocketSecret(process.env[SOCKET_SECRET_FILE_ENV]??socketSecretPath(socketPath)):void 0,transport=internalHostTransport(hostWatchdogBinding(),secret,{agentDir:options.agentDir,socket:socketPath,log:hostLog}),{watchdogConfig,admit}=transport,crashCleanupPaths=[...watchdogConfig?.cleanupPaths??[]],supervisorPublicSocketPath=process.platform==="win32"||socketPath.startsWith("\0")?void 0:watchdogConfig?.publicSocket,supervisorPublicOwnerFile=supervisorPublicSocketPath&&watchdogConfig?.scratchDir?join19(watchdogConfig.scratchDir,PUBLIC_SOCKET_IDENTITY_FILE):void 0,boundIdentity,supervisorPublicIdentity,serve=(socket,arrivedBeforeDrain,launchProof,routed=!1)=>{if(!routed&&draining&&!shuttingDown&&handoff.deliverLate(socket,arrivedBeforeDrain))return;if(!routed&&draining||shuttingDown){socket.destroy();return}let id=`${routed?"generation-route":"socket"}-${++nextConnection}`,sink=socketSink(socket);writer.registerConnection(id,sink,launchProof===void 0?{}:{launchProof}),occupancy.admit(socket);let detachReader=attachJsonlLineReader(socket,line=>{if(isHostOccupancyWatch(line)){occupancyWatch.watch(id);return}occupancyWatch.begin(id),writer.withConnection(id,()=>handle2(line)).catch(cause=>{process.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}
`)}).finally(()=>occupancyWatch.end(id))},{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)}
`))}}),detached=!1,detach=()=>{detached||(detached=!0,detachReader(),writer.unregisterConnection(id),connections.delete(id),occupancy.release(socket),occupancyWatch.forget(id),router.releaseConnection(id).catch(cause=>{process.stderr.write(`senpi rpc connection ${id} release failed: ${errorMessage(cause)}
`)}))},close2=code2=>writer.closeConnection(id,code2,announced=>announced?sink.close?.():socket.destroy());connections.set(id,{id,sink,socket,detach,close:close2}),socket.once("close",detach),socket.once("error",()=>detach())},server=createServer2(socket=>{let arrivedBeforeDrain=!draining&&!shuttingDown;admit(socket,(stream=socket,proof)=>serve(stream,arrivedBeforeDrain,proof))}),stopRoute;server.on("error",cause=>{shuttingDown||process.stderr.write(`senpi rpc socket listener failed: ${errorMessage(cause)}
`)});let stopChildReaper=await startHostChildReaper(hostLog),shutdown=async(exitCode=0,watchdogCleanup)=>{shuttingDown&&process.exit(exitCode),shuttingDown=!0;let startedAt=Date.now();observers.stop(),handover?.dispose(),presenterControl?.dispose(),presenterDir&&await rm11(presenterDir,{recursive:!0,force:!0}),stopChildReaper(),await handoverAnswered();try{await(process.platform==="win32"?Promise.race([router.dispose(),delay(WINDOWS_SHUTDOWN_DISPOSE_BOUND_MS)]):router.dispose()),await machineOps.dispose();let open5=[...connections.values()],cancelForce=await closeHostConnections(open5,id=>writer.flushConnection(id),startedAt,hostLog);await closeShieldedEndpoint(socketPath,()=>process.platform==="win32"?Promise.race([closeServer(server),delay(WINDOWS_SHUTDOWN_HARD_EXIT_MS)]):closeServer(server)),cancelForce(),await unlinkOwnedEndpoint(socketPath,boundIdentity,hostInstanceId(),hostLog),supervisorPublicSocketPath&&await unlinkOwnedEndpoint(supervisorPublicSocketPath,supervisorPublicIdentity,hostInstanceId(),hostLog),watchdogCleanup&&await watchdogCleanup}finally{await stopRoute?.(),await transport.dispose(),process.exit(exitCode)}},drainForHandoff=()=>{if(shuttingDown)return;if(draining){handoffAnnounced&&router.beginDrain();return}draining=!0,crashCleanupPaths.length=0,hostLog("draining for a generation handoff");let identity={instanceId:hostInstanceId(),generation:hostGeneration(process.env)};handoff.begin(endpointSuperseded(),identity,supervisorPublicSocketPath??socketPath,hostLog).then(announced=>announced&&writer.broadcastHostRecord(announced)).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 drainRequestFile=hostChildDrainRequestFile();drainRequestFile!==void 0&&watchDrainRequest(drainRequestFile,drainForHandoff);let watchdog=watchdogConfig&&supervisorPublicOwnerFile?{...watchdogConfig,cleanupPaths:crashCleanupPaths,beforeCleanup:async()=>{supervisorPublicIdentity??=await readSocketIdentityFile(supervisorPublicOwnerFile)}}:watchdogConfig&&{...watchdogConfig,cleanupPaths:crashCleanupPaths};armHostWatchdog(watchdog,(reason,cleanup)=>{process.stderr.write(`senpi rpc host: ${reason}; shutting down
`),shutdown(0,cleanup),setImmediate(killTrackedDetachedChildren)}),reportStartupMilestone("host_runtime");let bind=()=>listen(server,socketPath,secret);boundIdentity=await(hostWatchdogBinding()===void 0?bindRegisteredEndpoint({agentDir:options.agentDir,socket:socketPath,log:hostLog},bind):bind()),await transport.publish(()=>shutdown(1));let drainFile=hostChildDrainRequestFile();return watchdogConfig&&drainFile&&process.platform!=="win32"&&(stopRoute=await listenForSuccessor(options.agentDir,socketPath,dirname8(drainFile),stream=>serve(stream,!1,"in_band",!0))),supervisorPublicOwnerFile&&(supervisorPublicIdentity=await waitForSocketIdentityFile(supervisorPublicOwnerFile)),process.stderr.write(`senpi rpc listening on ${formatSocketAddress(socketPath)}
`),warmAtBootForPrivateFds(warm,{cwd:options.cwd,sessionContext:hostContext},hostLog),new Promise(()=>{})}async function startupRuntimeBuildId(){try{return await computeRuntimeBuildId({profile:protocolIdentity().launch_profile.core})}catch(cause){hostLog(`runtime identity unreadable: ${errorMessage(cause)}`);return}}function delay(ms){return new Promise(resolve4=>setTimeout(resolve4,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,supervised=hostWatchdogBinding()){let endpoint=supervised===void 0?socketPath:supervised.publicSocket;if(endpoint===void 0||endpoint.startsWith("\0"))return{host_instance:hostInstanceId()};let directory=canonicalSessionPath(dirname8(endpoint));return{host_socket:join19(directory,basename2(endpoint)),host_instance:hostInstanceId()}}function listenSocketPath(options){if(!(options.listen===void 0||options.listen==="stdio://"))return resolveSocketPath(options.listen,options.agentDir)}function publicEndpointSocket(options){let supervised=hostWatchdogBinding();return supervised!==void 0?supervised.publicSocket:listenSocketPath(options)}function closeServer(server){return new Promise((resolve4,reject)=>{server.close(cause=>cause?reject(cause):resolve4())})}function hostLog(message){process.stderr.write(`senpi rpc host: ${message}
`)}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,hostSessionContext,presenterPipePath,resolveHostIdlePolicy,runMultiSessionHost};