@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
38 lines • 111 kB
JavaScript
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
import{CUSTOM_UNSUPPORTED_CAPABILITY,DEFAULT_PROBE_TIMEOUT_MS,DEFAULT_STOP_TIMEOUT_MS,ENDPOINT_OWNER_FENCE_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SIGKILL_GRACE_MS,STARTUP_DECISION_BUDGET_MS,STOP_WAIT_BUDGET_MS,announceStop,anyGenerationLive,busyLegacyHostDetail,comparableEngines,computeRuntimeBuildId,decideHostAction,delay,describeSessions,electPointer,engineBuildIdentity,engineIdentityOf,ensureLockWaitDetail,ensureSender,gcEndpoint,gcHostEndpoints,holdProtocolInfo,holdSessionCount,hostLaunchProfile,isNodeErrorCode,judgeStaleEngine,matchesPidFileOrUnknown,observeProtocolInfo,olderEngineDetail,parseEngineOrdinal,parseHostStopGeneration,probeProtocolInfo,probeSocketReachable,provenLegacyOwner,recordEscalation,resolvePidFileOwnership,retireIdleLegacyHost,signalGeneration,signalPid,socketHostLaunchProfile,staleStopGeneration,startStartupController,startupEnvelope,startupTimeoutDetail,stopHost,stopManagedHost,stopSpawnedChild}from"./chunk-2JCYUXD3.js";import{endpointKindOfSocket,listHostEndpoints}from"./chunk-RVIBYQSJ.js";import{isSessionRuntimeKind,isToolRuntimeKind,toolRuntimeCapability}from"./chunk-2C4UHQNO.js";import{requestOnSocket}from"./chunk-SCO4TA5Q.js";import{rpcKeyRoot,withRpcKeyRoot}from"./chunk-INTQIW2O.js";import{adoptedEngineTrustHandOff}from"./chunk-AT5G5BUI.js";import{MCP_PRESENTER_BOOTSTRAP_FD,presenterBootstrapStream,relayPresenterBootstrap}from"./chunk-7WYJAYHH.js";import{ALIAS_LINK,ALIAS_OWNER,ALIAS_PREFIX,INTERNAL_HOST_DIR_PREFIX,INTERNAL_SUPERVISOR_FLAG,OWNER_WATCH_FD,bindAliasRoots,internalHostDirRoots,keepOwnerPipe,loopLagErrorMs,readAliasOwnerStartTime,resolveCliMainPath,settleCandidateAdoption}from"./chunk-RETVFKJZ.js";import{DEFAULT_HOST_IDLE_EXIT_MS,acquireHostEnsureLock,childStalledStopMaxMs,claimOwnerIsLive,clearHostRegistration,hostChildAlive,hostEnsureLockOptions,hostEnsureLockTarget,hostLoopStalled,isHostCrash,provenOwner,pruneDeadGenerations,readGenerationRows,readHostCrashRecords,readHostProcessMetrics,readHostRegistration,readSessionPathClaims,releaseGeneration,stallRefusalWindowMs,writeGenerationRecord,writeHostRegistration,writtenByThisProcess}from"./chunk-N6FVJRTO.js";import{HOST_DAEMON_DIR_ENV,HOST_STATE_FILE_MODE,callerHostOwner,claimHostOwner,createDaemonDirectories,createHostDaemonPaths,ensureEndpointIdentity,generationPaths,hostDaemonDirectoryPaths,parseJson,parseShardSocket,readFileOrUndefined,readHostOwner,readHostSettings,readJsonObject,sameEndpoint,sameHostOwner,sessionDirectoryRemoved,shardKey,shardSocketPathForKey,writeHostOwner,writeHostSettings,writeJsonAtomic,writeStateFile}from"./chunk-76ECBOPA.js";import{OBSERVE_REQUEST_FIELD,gcRpcPublicKeys}from"./chunk-APCZVDHX.js";import{envSlotVarNames}from"./chunk-OPWT74QF.js";import{external_exports}from"./chunk-36BLGKRO.js";import{ProcessIdentityUnreadableError,processIsLive,processMatchesPidFile,readProcessStartTime,waitForStartTime}from"./chunk-YWBNR4MT.js";import{providerCredentialEnvNames}from"./chunk-Z6TEQEZO.js";import{runtimeExecArgv,spawnWithPrivateFds}from"./chunk-6S66JQWD.js";import{ADOPTION_GRANT_FILE,STARTUP_ATTEMPT_FILE,encodeStartupHandOff,releaseStartupFillers,startupGrantLine,withStartupPipe}from"./chunk-GKBPYB3Q.js";import{MAX_SOCKET_PATH_BYTES,generationBindPath,socketEntryListenerState,statSocketIdentity}from"./chunk-5XHOHZIR.js";import{acquireOwnershipSafeLock,ensureSocketSecret,isBusy,socketSecretPath}from"./chunk-HW6AAS3R.js";import{HOST_GENERATION_ENV,HOST_HANDOFF_ENV_NAMES,HOST_INSTANCE_ID_ENV,HOST_STARTUP_EVENTS_ENV,ORIGIN_HOST_INSTANCE_ENV,RPC_CLIENT_CAPABILITIES_ENV,isHostHandoffEnvName}from"./chunk-IDTQWHTP.js";import{APP_NAME,ENV_AGENT_DIR,envValue,getAgentDir,isBunBinary}from"./chunk-QJTWAOBX.js";import{writeSync as writeSync2}from"node:fs";import{join as join10,resolve as resolve5}from"node:path";import{readFile,realpath,stat}from"node:fs/promises";import{dirname,isAbsolute,relative,resolve}from"node:path";var SPEC_ENV_NAME=/^(SENPI|OMO|PI)_[A-Z0-9_]+$/u,HostLaunchSpecError=class extends Error{constructor(reason,detail){super(`${reason}: ${detail}`),this.name="HostLaunchSpecError",this.reason=reason,this.detail=detail}},DEFAULT_HOST_LAUNCH_SPEC={hostArgs:[],policy:{},env:{}};async function loadHostLaunchSpec(specPath,platform=process.platform){let absolute=resolve(specPath);await assertTrustedFile(absolute,platform);let spec=parseHostLaunchSpec(await readSpecText(absolute)),env=trustedEnv(spec.env),extensions=await resolveExtensions(spec.core.extensions,dirname(absolute));return{hostArgs:["--session-runtime",spec.core.session_runtime,...extensions.flatMap(path=>["--extension",path])],policy:{...spec.tunables?.idleExitMs!==void 0&&{idleExitMs:spec.tunables.idleExitMs},...spec.tunables?.coldStart!==void 0&&{coldStart:spec.tunables.coldStart}},env}}function parseHostLaunchSpec(text){let parsed;try{parsed=JSON.parse(text)}catch(error){throw new HostLaunchSpecError("launch_spec_invalid",error instanceof Error?error.message:"not JSON")}if(!isRecord(parsed))throw new HostLaunchSpecError("launch_spec_invalid","the spec is not a JSON object");if(parsed.spec_version!==1)throw new HostLaunchSpecError("launch_spec_invalid",`unsupported spec_version ${String(parsed.spec_version)}`);let core=parsed.core;if(!isRecord(core))throw new HostLaunchSpecError("launch_spec_invalid","core must be an object");if(typeof core.session_runtime!="string"||!isSessionRuntimeKind(core.session_runtime))throw new HostLaunchSpecError("launch_spec_invalid","core.session_runtime must be in-process or worker");if(core.multi_session!==!0)throw new HostLaunchSpecError("launch_spec_invalid","core.multi_session must be true");if(!Array.isArray(core.extensions)||!core.extensions.every(entry=>typeof entry=="string"))throw new HostLaunchSpecError("launch_spec_invalid","core.extensions must be an array of strings");let tunables=parsedTunables(parsed.tunables);return{spec_version:1,core:{session_runtime:core.session_runtime,multi_session:!0,extensions:core.extensions},...tunables&&{tunables},...isRecord(parsed.env)&&{env:parsedEnv(parsed.env)}}}async function readSpecText(absolute){try{return await readFile(absolute,"utf8")}catch(error){throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}}async function assertTrustedFile(absolute,platform){if(platform==="win32")return;let stats=await stat(absolute).catch(error=>{throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}),uid=process.getuid?.();if(uid!==void 0&&stats.uid!==uid)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is owned by uid ${stats.uid}, not ${uid}`);if((stats.mode&18)!==0)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is group/world writable (mode ${(stats.mode&511).toString(8)})`)}function trustedEnv(env){for(let name of Object.keys(env??{}))if(!SPEC_ENV_NAME.test(name))throw new HostLaunchSpecError("launch_spec_env_denied",`${name} is outside ${SPEC_ENV_NAME.source}`);return env??{}}async function resolveExtensions(extensions,specDir){let rootReal=await realpath(specDir).catch(()=>specDir),resolved=[];for(let entry of extensions){let target=resolve(specDir,entry);if(escapes(specDir,target))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} resolves outside ${specDir}`);let real=await realpath(target).catch(()=>{});if(real===void 0)throw new HostLaunchSpecError("launch_spec_missing_extension",`${target} does not exist`);if(escapes(rootReal,real))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} links outside ${specDir}`);resolved.push(real)}return resolved}function escapes(root,target){let step=relative(root,target);return step.startsWith("..")||isAbsolute(step)}function parsedTunables(value){if(!isRecord(value))return;let idleExitMs=value.idleExitMs,coldStart=value.coldStart;return{...typeof idleExitMs=="number"&&Number.isFinite(idleExitMs)&&idleExitMs>0&&{idleExitMs},...(coldStart==="transient"||coldStart==="persistent")&&{coldStart}}}function parsedEnv(value){let env={};for(let[name,entry]of Object.entries(value)){if(typeof entry!="string")throw new HostLaunchSpecError("launch_spec_invalid",`env.${name} must be a string`);env[name]=entry}return env}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{join}from"node:path";var ALLOWED_ENV_NAMES=[/^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TERM|LANG)$/u,/^(LC|XDG)_/u,/^(SENPI|OMO|PI)_/u,/^BSK_(HOME|BIN)$/u,/^(HTTPS?_PROXY|NO_PROXY)$/u,/^[A-Z0-9_]+_API_KEY$/u,/^(ANTHROPIC|OPENAI|GOOGLE|GEMINI|AZURE|AWS|OPENROUTER|XAI|MISTRAL|DEEPSEEK|GROQ|CEREBRAS|MINIMAX)_/u],PROVIDER_CREDENTIAL_ENV_NAMES=new Set([...providerCredentialEnvNames(),...envSlotVarNames()]),WINDOWS_SYSTEM_ENV_NAMES=new Set(["SYSTEMROOT","SYSTEMDRIVE","WINDIR","COMSPEC","PATHEXT","TEMP","TMP","USERPROFILE","APPDATA","LOCALAPPDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","HOMEDRIVE","HOMEPATH","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"]),TRANSIENT_ENV_NAMES=new Set(["PI_SESSION_ID","PI_SESSION_FILE","PI_SESSION_CWD","PI_GOAL_STORE_FILE","PI_PROVIDER","PI_MODEL","PI_REASONING_LEVEL","OMO_BROWSER_ENGINE","PI_PROMPT_CACHE_SAFE_WAIT_SECONDS","SENPI_PY_KERNEL_PARENT_PID",...HOST_HANDOFF_ENV_NAMES,ORIGIN_HOST_INSTANCE_ENV,HOST_STARTUP_EVENTS_ENV,"SENPI_ENGINE_TRUST","SENPI_ENGINE_TRUST_HOP"]);function isTransientDaemonEnvName(name){return TRANSIENT_ENV_NAMES.has(name)}function daemonEnvIsAllowed(name,platform=process.platform){let upper=name.toUpperCase();return TRANSIENT_ENV_NAMES.has(platform==="win32"?upper:name)||isHostHandoffEnvName(name,platform)?!1:platform!=="win32"?PROVIDER_CREDENTIAL_ENV_NAMES.has(name)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(name)):WINDOWS_SYSTEM_ENV_NAMES.has(upper)||PROVIDER_CREDENTIAL_ENV_NAMES.has(upper)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(upper))}function daemonEnvOverrides(processEnv,specEnv={},platform=process.platform){let overrides={};for(let name of Object.keys(processEnv))daemonEnvIsAllowed(name,platform)||(overrides[name]=null);for(let[name,value]of Object.entries(specEnv))daemonEnvIsAllowed(name,platform)&&(overrides[name]=value);return overrides}function daemonEnvironment(processEnv,overrides={},forced={},platform=process.platform){let env={};for(let[name,value]of Object.entries(processEnv))value!==void 0&&daemonEnvIsAllowed(name,platform)&&(env[name]=value);for(let[name,value]of Object.entries(overrides))daemonEnvIsAllowed(name,platform)&&(deleteEnvironmentName(env,name,platform),value!==null&&(env[name]=value));for(let[name,value]of Object.entries(forced))deleteEnvironmentName(env,name,platform),env[name]=value;return env}function daemonEnvKeys(processEnv,specEnv={},platform=process.platform){let kept=Object.keys(processEnv).filter(name=>daemonEnvIsAllowed(name,platform)),explicit=Object.keys(specEnv).filter(name=>daemonEnvIsAllowed(name,platform));return[...new Set([...kept,...explicit])].sort()}async function writeDaemonEnvKeys(paths,keys){await writeStateFile(daemonEnvKeysFile(paths),{env_keys:keys})}async function readDaemonEnvKeys(paths){let keys=parseJson(await readFileOrUndefined(daemonEnvKeysFile(paths)))?.env_keys;return Array.isArray(keys)?keys.filter(key=>typeof key=="string"):[]}function daemonEnvKeysFile(paths){return join(paths.dir,"env-keys.json")}function deleteEnvironmentName(env,name,platform){if(platform!=="win32"){delete env[name];return}let upper=name.toUpperCase();for(let existing of Object.keys(env))existing.toUpperCase()===upper&&delete env[existing]}import{mkdir,writeFile as writeFile4}from"node:fs/promises";import{dirname as dirname4}from"node:path";var hostGenerationScopes=0;function isHostGenerationProcess(){return hostGenerationScopes>0}async function runAsHostGenerationProcess(action){hostGenerationScopes+=1;try{return await action()}finally{hostGenerationScopes-=1}}function decideEnsureAction(options,startedByUs,protocol){if(options.upgrade!=="if-engine-differs"||isHostGenerationProcess())return decideHostAction(ensureClient(options,startedByUs),protocol,"never");let client=ensureClient(options,startedByUs),decision=decideHostAction(client,protocol,"upgrade");return decision.action!=="handoff"&&reportUncomparableEngine(client.identity,protocol),decision.action==="fallback"?{action:"reuse",reason:"compatible",upgradeable:!1}:decision}function reportUncomparableEngine(client,host){if(host?.engineOrdinal===void 0)return;let running=engineIdentityOf(host.engineVersion??"",host.engineOrdinal);comparableEngines(client,running)||process.stderr.write(`senpi host: engine order uncomparable: this build ${client.text} [${client.ordinal.join(",")}], the running host ${running.text} [${running.ordinal.join(",")}]; only senpi CalVer ordinals are ordered, so the running host is kept
`)}function ensureClient(options,startedByUs){return{protocolVersion:HOST_PROTOCOL_VERSION,requiredCapabilities:[...REQUIRED_HOST_CAPABILITIES,...requestedToolRuntime(options.hostArgs??[])],identity:engineBuildIdentity(),...options.upgrade==="if-engine-differs"?{launchProfile:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd())}:{},startedByUs,platform:process.platform}}function requestedToolRuntime(hostArgs){for(let index=0;index<hostArgs.length;index++){let arg=hostArgs[index]??"",value=arg==="--tool-runtime"?hostArgs[index+1]:arg.startsWith("--tool-runtime=")?arg.slice(15):void 0;if(value!==void 0&&isToolRuntimeKind(value))return[toolRuntimeCapability(value)]}return[]}function hostChildArgv(hostArgs){return["--mode","rpc","--multi-session",...hostArgs]}function isCompatible(protocol){return decideHostAction(ensureClient({socket:""},!1),protocol,"never").action==="reuse"}import{lstat}from"node:fs/promises";async function refuseIfStalled(paths,instanceId,socket,protocol){let generation=generationPaths(paths,instanceId);if(await hostLoopStalled(generation,{now:Date.now(),errorMs:loopLagErrorMs(),windowMs:stallRefusalWindowMs()})&&await hostChildAlive(generation)!==!1)throw new HostEnsureRefusedError(socket,"host_stalled",protocol)}async function refuseIfForeignHeld(paths,registered,socket,protocol){if(!await publicEndpointAccepts(socket))return;let holder=await readHostHolder(paths,registered);throw new HostEnsureRefusedError(socket,"foreign_writer",protocol,void 0,holder)}async function readHostHolder(paths,registered){let record=parseJson(await readFileOrUndefined(generationPaths(paths,registered.instanceId).pidFile))??{};return{pid:registered.record.pid,instanceId:registered.instanceId,generation:registered.generation,processStartTime:registered.record.processStartTime,engineVersion:typeof record.engineVersion=="string"?record.engineVersion:null,launchProfileId:typeof record.launchProfileId=="string"?record.launchProfileId:null,writerPid:registered.writer?.pid??null}}var FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS=2e3;async function publicEndpointAccepts(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!0;let entry=await statSocketIdentity(socket).then(identity=>identity===void 0?"absent":"present",()=>"unknown");return entry==="absent"?!1:entry==="unknown"?!0:probeSocketReachable(socket,FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS)}async function unregisteredEndpointHeld(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!1;let entry=await lstat(socket).then(found=>found.isSocket()?"socket":"not-socket",cause=>cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"?"absent":"unknown");return entry==="absent"?!1:entry!=="socket"?!0:(await socketEntryListenerState(socket)).verdict==="live"}import{spawn as spawn2}from"node:child_process";import{randomUUID}from"node:crypto";import{open,readFile as readFile3}from"node:fs/promises";import{existsSync}from"node:fs";import{basename,dirname as dirname2,join as join2,resolve as resolve2}from"node:path";import{fileURLToPath}from"node:url";var PINNED_HOST_CLIENT_CAPABILITIES=[EXTENSION_EVENTS_CAPABILITY,CUSTOM_UNSUPPORTED_CAPABILITY];function defaultHostLaunch(supervisorArgs,compiled=isBunBinary,sibling=resolveHostLifecycleEntryPath()??null,bundledSupervisor=resolveBundledSupervisorEntryPath()??null){return compiled?{command:process.execPath,args:[INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:sibling!==null?{command:process.execPath,args:[...runtimeExecArgv(),sibling,...supervisorArgs]}:bundledSupervisor!==null?{command:process.execPath,args:[...runtimeExecArgv(),bundledSupervisor,INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:{command:process.execPath,args:[...runtimeExecArgv(),resolveCliMainPath(),INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}}var BUNDLED_SUPERVISOR_ENTRY="host-supervisor.js";function resolveBundledSupervisorEntryPath(){let entry=join2(dirname2(resolveCliMainPath()),BUNDLED_SUPERVISOR_ENTRY);return existsSync(entry)?entry:void 0}function resolveHostLifecycleEntryPath(){let modulePath=fileURLToPath(import.meta.url);if(basename(dirname2(modulePath))==="chunks")return;let extension=modulePath.endsWith(".ts")?".ts":".js",sibling=resolve2(dirname2(modulePath),`host-lifecycle${extension}`);return existsSync(sibling)?sibling:void 0}import{randomBytes}from"node:crypto";var MAX_STARTUP_EVENTS_PER_PRODUCER=32,STARTUP_MILESTONE_PRODUCER={supervisor_bootstrap:"supervisor",supervisor_setup:"supervisor",host_opaque:"supervisor",host_bootstrap:"host",host_runtime:"host",internal_ready:"supervisor",observer_ready:"supervisor",public_published:"supervisor"};function newStartupAttempt(){return randomBytes(16).toString("hex")}function startupEventIngress(controller,binding,role){let lastSeq=0,records=0,failProtocol=reason=>(controller.fail(new Error(`RPC host startup protocol failure (${role}): ${reason}`)),"protocol_failure");return line=>{if(Buffer.byteLength(line,"utf8")>4096)return failProtocol("record exceeds 4096 bytes");let record=parseRecord(line);if(!record)return failProtocol("malformed record");if(!sameBinding(record.binding,binding))return"discarded";if(record.role!==role)return failProtocol(`record claims role ${String(record.role)}`);if(record.seq<=lastSeq)return"ignored";if(record.seq!==lastSeq+1)return failProtocol(`sequence gap after ${lastSeq}`);if(records+=1,records>MAX_STARTUP_EVENTS_PER_PRODUCER)return failProtocol("too many records");lastSeq=record.seq;let milestone=record.milestone;if(!isProducerMilestone(milestone))return failProtocol(`unknown milestone ${String(milestone)}`);if(STARTUP_MILESTONE_PRODUCER[milestone]!==role)return failProtocol(`${role} cannot report ${milestone}`);let verdict=milestone==="host_opaque"?controller.declareOpaqueHost():controller.complete(milestone);return verdict!=="rejected"?verdict:controller.terminal?"ignored":failProtocol(`${milestone} reported before its phase was granted`)}}function attachStartupEvents(stream,controller,binding){let supervisor=startupEventIngress(controller,binding,"supervisor"),host=startupEventIngress(controller,binding,"host"),maxLine=2*4096+64,pending="";stream.setEncoding("utf8"),stream.on("data",chunk=>{if(!controller.terminal){pending+=chunk;for(let newline=pending.indexOf(`
`);newline>=0;newline=pending.indexOf(`
`)){let line=pending.slice(0,newline);pending=pending.slice(newline+1);let relayed=unwrapStartupRelay(line);if(relayed===void 0?supervisor(line):host(relayed),controller.terminal)return}pending.length>maxLine&&supervisor(pending)}}),stream.on("error",()=>{}),"unref"in stream&&typeof stream.unref=="function"&&stream.unref()}function unwrapStartupRelay(line){if(line.startsWith('{"relay":'))try{let frame=JSON.parse(line);if(typeof frame!="object"||frame===null)return;let{relay,line:inner}=frame;return relay==="host"&&typeof inner=="string"?inner:void 0}catch{return}}function parseRecord(line){let value;try{value=JSON.parse(line)}catch{return}if(typeof value!="object"||value===null)return;let record=value;if(record.v===1&&!(typeof record.seq!="number"||!Number.isSafeInteger(record.seq)||record.seq<1))return{binding:record.binding,role:record.role,seq:record.seq,milestone:record.milestone}}function sameBinding(candidate,binding){if(typeof candidate!="object"||candidate===null)return!1;let other=candidate;return other.attempt===binding.attempt&&other.endpoint===binding.endpoint&&other.instanceId===binding.instanceId&&other.generation===binding.generation&&other.launchKind===binding.launchKind&&other.predecessor===binding.predecessor}function isProducerMilestone(value){return typeof value=="string"&&Object.hasOwn(STARTUP_MILESTONE_PRODUCER,value)}import{rm,stat as stat2}from"node:fs/promises";import{join as join3}from"node:path";var STARTUP_INTENT_FILE="startup-intent.json",STARTUP_INTENT_VERSION=1;function startupIntentPath(daemonDir){return join3(daemonDir,STARTUP_INTENT_FILE)}function writeStartupIntent(daemonDir,intent){return writeJsonAtomic(startupIntentPath(daemonDir),{version:STARTUP_INTENT_VERSION,...intent})}async function readStartupIntent(daemonDir){let modified=await stat2(startupIntentPath(daemonDir)).then(entry=>entry.mtimeMs,()=>{});if(modified===void 0)return;let record=await readJsonObject(startupIntentPath(daemonDir)),launcher=pidFileOf(record?.launcher),child=record?.child===void 0?void 0:pidFileOf(record.child);return!record||record.version!==STARTUP_INTENT_VERSION||typeof record.attempt!="string"||typeof record.instanceId!="string"||typeof record.generation!="number"||typeof record.writtenAt!="number"||!launcher||child===null?{unreadable:!0,writtenAt:modified}:{attempt:record.attempt,instanceId:record.instanceId,generation:record.generation,launcher,writtenAt:record.writtenAt,...child?{child}:{}}}function clearStartupIntent(daemonDir){return rm(startupIntentPath(daemonDir),{force:!0})}async function readStartupAttemptRecord(generationDir,attempt){let record=await readJsonObject(join3(generationDir,STARTUP_ATTEMPT_FILE));if(record?.attempt===attempt)return pidFileOf(record)??void 0}async function reconcileStartupIntent(intent,options){if(intent===void 0)return"none";let expiredOr=verdict=>options.now-intent.writtenAt>=options.expiryMs?"expired":verdict;if("unreadable"in intent)return expiredOr("unknown");let candidate=intent.child??await options.attemptRecord(intent.instanceId,intent.attempt);if(!candidate)return expiredOr("unknown");let live=await options.matches(candidate).catch(()=>{});return live===void 0?expiredOr("unknown"):live?"candidate_live":"candidate_gone"}async function settleStartupIntent(paths,socket,readStartTime=readProcessStartTime){let expiryMs=startupEnvelope(childStalledStopMaxMs()).settled,verdict=await reconcileStartupIntent(await readStartupIntent(paths.dir),{matches:record=>processMatchesPidFile(record,readStartTime),attemptRecord:(instanceId,attempt)=>readStartupAttemptRecord(generationPaths(paths,instanceId).dir,attempt),expiryMs,now:Date.now()});if(verdict==="none")return;if(verdict==="candidate_gone"||verdict==="expired")return clearStartupIntent(paths.dir);let detail=verdict==="candidate_live"?`a previous start of this endpoint is still running and never registered (${startupIntentPath(paths.dir)})`:`a previous start of this endpoint cannot be identified; ${startupIntentPath(paths.dir)} is kept until its candidate is proven gone or ${expiryMs}ms after it was written`;throw new HostEnsureRefusedError(socket,verdict==="candidate_live"?"host_stalled":"endpoint_occupied",void 0,detail)}function pidFileOf(value){if(typeof value!="object"||value===null)return null;let{pid,processStartTime}=value;return typeof pid!="number"||!Number.isInteger(pid)||pid<=0||processStartTime!==null&&typeof processStartTime!="string"?null:{pid,processStartTime}}import{Readable}from"node:stream";var SPAWNED_HOST_PROBE_TIMEOUT_MS=1e4;async function pollProtocolInfo(socket,timeoutMs,isCompatible2,childExit){let deadline=Date.now()+timeoutMs,lastProtocol;for(;Date.now()<=deadline;){let probe=holdProtocolInfo(socket,Math.min(SPAWNED_HOST_PROBE_TIMEOUT_MS,Math.max(1,deadline-Date.now()))),raced=childExit?await Promise.race([probe,childExit]):await probe;if(isChildExit(raced)){let held=await probe;if(!held)return{ready:!1,protocol:lastProtocol,exited:raced};if(lastProtocol=held.info,isCompatible2(held.info))return{ready:!0,protocol:held.info,hold:held.hold};held.hold.release()}else if(raced){if(lastProtocol=raced.info,isCompatible2(raced.info))return{ready:!0,protocol:raced.info,hold:raced.hold};raced.hold.release()}await delay2(50)}return{ready:!1,protocol:lastProtocol}}function isChildExit(value){return!!value&&"code"in value&&"signal"in value}function delay2(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function monotonicStartupClock(){return{now:()=>performance.now(),scheduleAt:(at,fire)=>setTimeout(fire,Math.max(0,at-performance.now())),cancel:handle=>clearTimeout(handle)}}function beginStartupAttempt(options){let successor=options.successorOf!==void 0,launchKind=options.coordinated?successor?"successor":"initial":"legacy",budgetMs=options.decisionBudgetMs??STARTUP_DECISION_BUDGET_MS,binding={attempt:options.attempt,endpoint:options.socket,instanceId:options.instanceId,generation:options.generation,launchKind:successor?"successor":"initial",predecessor:options.successorOf??null},controller=startStartupController({launchKind,clock:options.clock??monotonicStartupClock(),decisionBudgetMs:budgetMs}),coordinated=options.coordinated,fillers=[];return{controller,binding,coordinated,get env(){return coordinated?{[HOST_STARTUP_EVENTS_ENV]:encodeStartupHandOff({binding,role:"supervisor",budgetMs,fillers})}:{}},stdio(base){if(!coordinated)return[...base];let filled=withStartupPipe(base);return fillers=filled.fillers,filled.stdio},attach(child,childExit){releaseStartupFillers(child,fillers);let stream=child.stdio[16];coordinated&&stream instanceof Readable&&attachStartupEvents(stream,controller,binding),childExit.then(exit=>{!controller.terminal&&controller.phase!=="public_verified"&&controller.fail(new Error(exitMessage(exit)))})}}}function exitMessage(exit){return`RPC socket host exited with ${exitStatus(exit)} before answering get_protocol_info`}function exitStatus(exit){return`code ${exit.code??"null"}${exit.signal?` (${exit.signal})`:""}`}function answerMessage(protocol,exited){return protocol.lifecycle!=="stopping"?incompatibleMessage(protocol):`RPC socket host answered get_protocol_info with lifecycle "stopping": it began stopping before this start verified it${exited?`, and then exited with ${exitStatus(exited)}`:""}`}function incompatibleMessage(protocol){return`RPC socket host answered get_protocol_info with protocolVersion ${protocol.protocolVersion}, serverVersion ${protocol.serverVersion} and capabilities ${JSON.stringify(protocol.capabilities)}, but is incompatible with protocol version ${HOST_PROTOCOL_VERSION} and required capabilities ${JSON.stringify(REQUIRED_HOST_CAPABILITIES)}`}async function driveStartupToReady(options){let{controller}=options.attempt,failure=async()=>{let outcome=await controller.settled();if(outcome.kind==="ready")throw new Error("startup controller reported READY on a failure path");return{ready:!1,outcome}};if(options.attempt.coordinated&&(!await controller.whenPhase("presenter_resolved")||await Promise.race([(options.presenterEnrollment??Promise.resolve()).then(()=>"resolved"),controller.settled().then(()=>"terminal")])==="terminal"||controller.complete("presenter_resolved")!=="accepted"))return failure();let result=await pollProtocolInfo(options.socket,Math.max(1,controller.remainingMs()),options.isCompatible,options.childExit);if(result.ready)return controller.complete("public_verified")!=="accepted"?(result.hold.release(),failure()):(options.attempt.coordinated||await options.presenterEnrollment,{ready:!0,hold:result.hold});let explicit=result.protocol?new Error(answerMessage(result.protocol,result.exited)):result.exited?new Error(exitMessage(result.exited)):void 0;if(!explicit)return failure();controller.fail(explicit);let settled=await controller.settled();return{ready:!1,outcome:settled.kind==="failed"?settled:{kind:"failed",phase:"public_verified",cause:explicit,elapsedMs:settled.elapsedMs}}}function createStartupFinalizer(options){let settled;return outcome=>(settled??=finalize(outcome),settled);async function finalize(outcome){let{clock}=options,timer,expired=new Promise(resolveExpired=>{timer=clock.scheduleAt(clock.now()+options.cleanupBudgetMs,()=>resolveExpired("expired"))}),ran=options.cleanup().then(()=>"completed",error=>error instanceof Error?error:new Error(String(error))),result=await Promise.race([ran,expired]);clock.cancel(timer);let cleanup=result==="completed"?"completed":"incomplete",original=outcome.kind==="timeout"?startupTimeoutDetail(outcome,cleanup):outcome.cause.message,appended=result instanceof Error?`
cleanup failed: ${result.message}`:result==="expired"?`
cleanup did not finish within ${options.cleanupBudgetMs}ms`:"";return{outcome,cleanup,detail:`${original}${appended}`}}}function finalizeFailedStart(outcome,cleanup){return createStartupFinalizer({clock:monotonicStartupClock(),cleanupBudgetMs:startupEnvelope(childStalledStopMaxMs()).cleanup,cleanup})(outcome)}var EXPECTED_RUNTIME_BUILD_ID_ENV="SENPI_RPC_HOST_EXPECTED_RUNTIME_BUILD_ID",NEW_WORK_COMMANDS=new Set(["prompt","steer","follow_up","send_custom_message","continue_from_leaf","resume_session","append_user_message","bash","compact","wake","admit_external_message","edit_assistant_message","edit_user_message"]),DEFAULT_POLL_MS=200,HostIdleHandover=class{constructor(options){this.options=options}view(){return this.operation?.view}admits(commandType){let state=this.operation?.view.state;return state===void 0||state==="handover_blocked"||!NEW_WORK_COMMANDS.has(commandType)}async begin(request){let current=this.operation;if(current!==void 0&¤t.view.operationId===request.operationId)return sameTerms(current.request,request)?answer(current):{kind:"refused",reason:"operation_conflict",detail:"this operation id names other terms"};if(current!==void 0&¤t.view.state!=="handover_blocked")return current.request.targetRuntimeBuildId===request.targetRuntimeBuildId&&!!current.request.mcpPresenterEnforcement==!!request.mcpPresenterEnforcement?answer(current):{kind:"refused",reason:"handover_in_progress",detail:current.view.operationId};let self=this.options.identity();if(self.instanceId!==request.ifInstanceId||self.generation!==request.ifGeneration)return{kind:"refused",reason:"stale_generation",detail:`this host is ${self.instanceId} generation ${self.generation}`};if(self.runtimeBuildId===request.targetRuntimeBuildId)return{kind:"refused",reason:"already_current",detail:self.runtimeBuildId};let downgrade=downgradeDetail(request,self.engine);if(downgrade!==void 0)return{kind:"refused",reason:"older_engine",detail:downgrade};let operation={request,view:{operationId:request.operationId,state:"handover_pending",targetRuntimeBuildId:request.targetRuntimeBuildId}};return this.operation=operation,this.options.log?.(`handover ${request.operationId} pending: no new work is admitted`),this.idleNow()?(await this.switchOver(operation),answer(operation)):(this.timer=setInterval(()=>this.observe(),this.options.pollMs??DEFAULT_POLL_MS),this.timer.unref?.(),answer(operation))}observe(){let operation=this.operation;operation?.view.state==="handover_pending"&&this.idleNow()&&this.switchOver(operation)}dispose(){this.stopTimer()}idleNow(){try{return this.options.isIdle()}catch(cause){return this.options.log?.(`handover idle check failed, waiting: ${String(cause)}`),!1}}async switchOver(operation){if(operation.view.state!=="handover_pending")return;this.stopTimer(),operation.view={...operation.view,state:"handover_switching"},this.options.holdNewWork?.();let outcome=await this.options.perform(operation.request).catch(cause=>({ok:!1,reason:`successor_unavailable: ${String(cause)}`}));operation.view=outcome.ok?{...operation.view,state:"handover_completed",successor:outcome.successor}:{...operation.view,state:"handover_blocked",reason:outcome.reason},outcome.ok||this.options.releaseNewWork?.(),this.options.log?.(`handover ${operation.view.operationId} ${operation.view.state}`)}stopTimer(){this.timer!==void 0&&clearInterval(this.timer),this.timer=void 0}};function sameTerms(a,b){return a.targetRuntimeBuildId===b.targetRuntimeBuildId&&!!a.mcpPresenterEnforcement==!!b.mcpPresenterEnforcement&&a.ifInstanceId===b.ifInstanceId&&a.ifGeneration===b.ifGeneration}function downgradeDetail(request,engine){if(!(request.allowDowngrade===!0||engine===void 0))return request.targetEngine===void 0?`the requesting CLI did not state its engine, so it predates the downgrade guard and is older than this host's ${engine.text}`:olderEngineDetail(request.targetEngine,engine)}function answer(operation){return{kind:"operation",view:operation.view}}function initialHostEnvironment(options){return daemonEnvironment(process.env,options.env,{...adoptedEngineTrustHandOff(),[ENV_AGENT_DIR]:options.agentDir??getAgentDir(),[RPC_CLIENT_CAPABILITIES_ENV]:PINNED_HOST_CLIENT_CAPABILITIES.join(","),[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_GENERATION_ENV]:String(options.generation),[HOST_DAEMON_DIR_ENV]:options.paths.dir})}function successorHostEnvironment(options){return daemonEnvironment(process.env,options.env,{...adoptedEngineTrustHandOff(),[RPC_CLIENT_CAPABILITIES_ENV]:PINNED_HOST_CLIENT_CAPABILITIES.join(","),...options.agentDir?{[ENV_AGENT_DIR]:options.agentDir}:{},[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_GENERATION_ENV]:String(options.generation),[HOST_DAEMON_DIR_ENV]:options.paths.dir,...options.expectedRuntimeBuildId!==void 0&&{[EXPECTED_RUNTIME_BUILD_ID_ENV]:options.expectedRuntimeBuildId}})}import{spawn}from"node:child_process";import{constants}from"node:fs";import{access,readFile as readFile2}from"node:fs/promises";import{delimiter,join as join4}from"node:path";var HOST_UNIT_PREFIX="senpi-host-",MANAGER_PROBE_TIMEOUT_MS=2e3;function managerAnswers(state){return["running","degraded","starting","initializing","maintenance"].includes(state)}function hostUnitName(instanceId){return`${HOST_UNIT_PREFIX}${instanceId}.scope`}function decideHostUnitPlacement(instanceId,probe){return probe.platform!=="linux"?{kind:"caller_unit",reason:"not_linux"}:probe.userManager?probe.systemdRun===void 0?{kind:"caller_unit",reason:"no_systemd_run"}:probe.scopeAccepted?{kind:"own_unit",unit:hostUnitName(instanceId),systemdRun:probe.systemdRun}:{kind:"caller_unit",reason:"scope_refused"}:{kind:"caller_unit",reason:"no_user_manager"}}function placedLaunch(launch,placement){return placement.kind==="caller_unit"?launch:{command:placement.systemdRun,args:["--user","--scope",`--unit=${placement.unit}`,"--collect","--quiet","--",launch.command,...launch.args]}}async function probeHostUnitPlacement(env,platform=process.platform){if(platform!=="linux"||!env.XDG_RUNTIME_DIR)return{platform,userManager:!1,systemdRun:void 0,scopeAccepted:!1};let[userManager,systemdRun]=await Promise.all([userManagerAnswers(env),onPath("systemd-run",env.PATH)]),scopeAccepted=userManager&&systemdRun!==void 0&&await scopeStarts(systemdRun,env);return{platform,userManager,systemdRun,scopeAccepted}}async function placeHostLaunch(launch,instanceId,env){return placedLaunch(launch,decideHostUnitPlacement(instanceId,await probeHostUnitPlacement(env)))}function probeEnv(env){return{PATH:env.PATH??"",XDG_RUNTIME_DIR:env.XDG_RUNTIME_DIR??""}}function scopeStarts(systemdRun,env){return new Promise(resolve6=>{let child=spawn(systemdRun,["--user","--scope","--collect","--quiet","--","true"],{env:probeEnv(env),stdio:"ignore",timeout:MANAGER_PROBE_TIMEOUT_MS});child.once("error",()=>resolve6(!1)),child.once("close",code=>resolve6(code===0))})}function userManagerAnswers(env){return new Promise(resolve6=>{let child=spawn("systemctl",["--user","is-system-running"],{env:probeEnv(env),stdio:["ignore","pipe","ignore"],timeout:MANAGER_PROBE_TIMEOUT_MS}),stdout="";child.stdout.setEncoding("utf8").on("data",chunk=>{stdout+=chunk}),child.once("error",()=>resolve6(!1)),child.once("close",()=>resolve6(managerAnswers(stdout.trim())))})}async function onPath(program,path){for(let dir of(path??"").split(delimiter)){if(!dir)continue;let candidate=join4(dir,program);if(await access(candidate,constants.X_OK).then(()=>!0,()=>!1))return candidate}}function withHostUnits(rows){return Promise.all(rows.map(async row=>({...row,unit:row.alive?await readHostUnit(row.pid,row.instanceId):null})))}async function hostUnitPayload(pid,instanceId){let unit=await readHostUnit(pid,instanceId);return unit!==null&&!unit.own&&unit.name!==null?{unit,lifetime_tied_to:unit.name}:{unit}}async function readHostUnit(pid,instanceId){if(process.platform!=="linux")return null;let table=await readFile2(`/proc/${pid}/cgroup`,"utf8").catch(()=>{});return table===void 0?null:hostUnitFromCgroupTable(table,instanceId)}function hostUnitFromCgroupTable(table,instanceId){let lines=table.split(`
`),entry=lines.find(line=>line.startsWith("0::"))??lines.find(line=>line.includes(":name=systemd:"));if(entry===void 0)return null;let cgroup=entry.slice(entry.indexOf(":",entry.indexOf(":")+1)+1),leaf=cgroup.slice(cgroup.lastIndexOf("/")+1),name=/\.(service|scope)$/u.test(leaf)?leaf:null;return{cgroup,name,own:name!==null&&instanceId!==void 0&&name===hostUnitName(instanceId)}}async function startHost(paths,socket,options,generation=0){let testOptions=options._test;await settleStartupIntent(paths,socket,testOptions?.readProcessStartTime);let lifetimeOwner=options.owner?await callerHostOwner():null,instanceId=randomUUID(),stopTarget=reason=>({daemonDir:paths.dir,generation:generationPaths(paths,instanceId),instanceId,sender:ensureSender(),reason});process.platform==="win32"&&await ensureSocketSecret(socketSecretPath(socket)),await writeHostSettings(paths,{socket,capabilities:PINNED_HOST_CLIENT_CAPABILITIES,coldStart:options.policy?.coldStart??"transient",idleExitMs:options.policy?.idleExitMs??9e5,generation,instanceId}),await writeHostOwner(generationPaths(paths,instanceId).dir,lifetimeOwner);let stderr=await open(paths.stderrLog,generation===0?"w":"a",384),pidFile,child,exitedEarly,childExit,presenterEnrollment,attempt;try{let supervisorArgs=["--socket",socket,...options.owner?["--owner-fd",String(OWNER_WATCH_FD)]:[],...options.presenterBootstrap?["--mcp-presenter-fd","4"]:[],...options.mcpPresenterEnforcement?["--mcp-presenter-enforcement"]:[],...options.hostArgs??[]],launch=testOptions?.spawn??testOptions?.launch?.(supervisorArgs)??{...defaultHostLaunch(supervisorArgs),reportsStartup:!0},nonce=newStartupAttempt();await writeStartupIntent(paths.dir,{attempt:nonce,instanceId,generation,launcher:{pid:process.pid,processStartTime:null},writtenAt:Date.now()}),attempt=beginStartupAttempt({socket,instanceId,generation,attempt:nonce,coordinated:"reportsStartup"in launch&&launch.reportsStartup===!0,...testOptions?.readinessTimeoutMs?{decisionBudgetMs:testOptions.readinessTimeoutMs}:{}});let base=options.presenterBootstrap?["ignore","ignore",stderr.fd,options.owner?"pipe":"ignore","pipe"]:options.owner?["ignore","ignore",stderr.fd,"pipe"]:["ignore","ignore",stderr.fd],stdio=attempt.stdio(base),env={...initialHostEnvironment({agentDir:options.agentDir,env:options.env,paths,instanceId,generation}),...attempt.env},placed=await placeHostLaunch(launch,instanceId,env);if(child=spawnWithPrivateFds(spawn2,placed.command,[...placed.args],{detached:!0,windowsHide:!0,env,stdio}),options.presenterBootstrap&&(presenterEnrollment=relayPresenterBootstrap(options.presenterBootstrap,child,{kind:"initial",predecessorHostInstance:null})),childExit=new Promise(resolveExit=>{child.once("exit",(code,signal)=>{exitedEarly={code,signal},resolveExit(exitedEarly)})}),attempt.attach(child,childExit),options.owner&&keepOwnerPipe(child),child.pid===void 0)throw new Error("failed to spawn RPC socket host");let probe=testOptions?.readProcessStartTime??readProcessStartTime,observedStartTime=await Promise.race([waitForStartTime(child.pid,1e4,probe),childExit.then(()=>{throw new Error("RPC socket host exited before its start time could be read")})]),unhurriedProbe=testOptions?.readProcessStartTime?testOptions.readProcessStartTime:pid=>readProcessStartTime(pid,process.platform,15e3),processStartTime=observedStartTime??await unhurriedProbe(child.pid).catch(()=>{});pidFile={pid:child.pid,processStartTime:processStartTime??null},await writeStartupIntent(paths.dir,{attempt:attempt.binding.attempt,instanceId,generation,launcher:{pid:process.pid,processStartTime:null},child:pidFile,writtenAt:Date.now()}),await testOptions?.beforePidFileWrite?.(),await writeHostRegistration(paths,{record:pidFile,socket,instanceId,generation,launchProfileId:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd()).profile_id,build:engineBuildIdentity()}),child.unref()}catch(error){let exitedBeforeCleanup=exitedEarly,cause=error instanceof Error?error:new Error(String(error));attempt?.controller.fail(cause);let spawned2=child,exit=childExit,report2=await finalizeFailedStart({kind:"failed",phase:"supervisor_bootstrap",cause,elapsedMs:0},()=>exitedBeforeCleanup||spawned2?.pid===void 0||!exit?Promise.resolve():stopUnregisteredStart(spawned2,exit,stopTarget("start_failed")));throw report2.cleanup==="completed"&&await clearStartupIntent(paths.dir),await clearHostRegistration(paths),exitedBeforeCleanup?new Error(await appendStderr(paths,exitMessage(exitedBeforeCleanup))):report2.cleanup==="completed"?error:new Error(report2.detail,{cause:error})}finally{await stderr.close()}let result=await driveStartupToReady({attempt,socket,childExit,presenterEnrollment,isCompatible});if(result.ready)return await clearStartupIntent(paths.dir),{pid:pidFile.pid,socket,reused:!1,release:result.hold.release};await testOptions?.beforeReadinessTeardown?.();let spawned=child,report=await finalizeFailedStart(result.outcome,()=>stopSpawnedChild(spawned,childExit,testOptions?.stopTimeoutMs??DEFAULT_STOP_TIMEOUT_MS,stopTarget("readiness_timeout"))),diagnostic=await appendStderr(paths,report.detail);throw report.cleanup==="completed"&&(await clearHostRegistration(paths),await clearStartupIntent(paths.dir)),new Error(diagnostic)}async function stopUnregisteredStart(child,childExit,target){let pid=child.pid,running=()=>child.exitCode===null&&child.signalCode===null;if(pid===void 0||!running())return;let announced=await announceStop(target,pid);try{signalPid(pid,"SIGTERM")}catch{}if(await Promise.race([childExit,delay(2e3)]),!running())return;try{signalPid(pid,"SIGKILL")}catch{}if(!await Promise.race([childExit.then(()=>!0),delay(SIGKILL_GRACE_MS).then(()=>!1)]))throw new Error(`RPC socket host pid ${pid} remained alive after SIGKILL`);await recordEscalation(target,announced)}async function appendStderr(paths,message){try{let stderr=(await readFile3(paths.stderrLog,"utf8")).trim();return stderr?`${message}
${stderr}`:message}catch(error){if(isNodeErrorCode(error,"ENOENT"))return message;throw error}}import{appendFile}from"node:fs/promises";import{basename as basename2,join as join6}from"node:path";import{readFile as readFile4,rename,writeFile}from"node:fs/promises";import{join as join5}from"node:path";var GC_SKIP_INITIAL_BACKOFF_MS=10*6e4,GC_SKIP_MAX_BACKOFF_MS=1440*6e4,skipEntrySchema=external_exports.object({skipUntil:external_exports.number(),backoffMs:external_exports.number()}),markerSchema=external_exports.object({completedAt:external_exports.number(),cursor:external_exports.string().nullable(),examined:external_exports.number(),removed:external_exports.number(),stoppedBy:external_exports.enum(["time","count","exhausted"]),skip:external_exports.record(external_exports.string(),skipEntrySchema)});function hostGcPassMarkerPath(agentDir){return join5(agentDir,"rpc-host-daemon","gc-last-run.json")}function parseHostGcPassMarker(text){try{let parsed=markerSchema.safeParse(JSON.parse(text));return parsed.success?parsed.data:void 0}catch(error){if(error instanceof SyntaxError)return;throw error}}async function readHostGcPassMarker(agentDir){let text=await readFile4(hostGcPassMarkerPath(agentDir),"utf8").catch(error=>{if(!(error instanceof Error&&"code"in error&&error.code==="ENOENT"))throw error});return text===void 0?void 0:parseHostGcPassMarker(text)}async function writeHostGcPassMarker(agentDir,marker){let path=hostGcPassMarkerPath(agentDir),staged=`${path}.${process.pid}.tmp`;await writeFile(staged,`${JSON.stringify(marker)}
`,{mode:384}),await rename(staged,path)}function nextSkip(previous,now){let backoffMs=previous===void 0?GC_SKIP_INITIAL_BACKOFF_MS:Math.min(previous.backoffMs*2,GC_SKIP_MAX_BACKOFF_MS);return{skipUntil:now+backoffMs,backoffMs}}var passesRunning=new Map;function opportunisticHostGcRunning(agentDir){return passesRunning.has(agentDir)}function trackOpportunisticHostGc(agentDir,pass){passesRunning.set(agentDir,pass),pass.finally(()=>{passesRunning.get(agentDir)===pass&&passesRunning.delete(agentDir)})}var OPPORTUNISTIC_GC_BUDGET={budgetMs:1500,maxEndpoints:32,minIntervalMs:3e5};async function gcHostEndpointsOpportunistically(options){let now=options.now??Date.now,budgetMs=options.budgetMs??OPPORTUNISTIC_GC_BUDGET.budgetMs,maxEndpoints=options.maxEndpoints??OPPORTUNISTIC_GC_BUDGET.maxEndpoints,minIntervalMs=options.minIntervalMs??OPPORTUNISTIC_GC_BUDGET.minIntervalMs,previous=await readHostGcPassMarker(options.agentDir),startedAt=now();if(previous!==void 0&&startedAt-previous.completedAt<minIntervalMs)return{ran:!1};process.platform!=="win32"&&await gcRpcPublicKeys(options.agentDir,{deadline:startedAt+budgetMs,maxRecords:maxEndpoints});let candidates=await gcCandidates(options),present=new Set(candidates.map(endpoint=>endpoint.name)),skip={};for(let[name,entry]of Object.entries(previous?.skip??{}))present.has(name)&&(skip[name]=entry);let cursor=previous?.cursor??null,examined=0,removed=0,stoppedBy="exhausted";for(let endpoint of rotateAfter(candidates,cursor)){if((skip[endpoint.name]?.skipUntil??0)>now())continue;if(examined>=maxEndpoints){stoppedBy="count";break}if(now()-startedAt>=budgetMs){stoppedBy="time";break}examined+=1,cursor=endpoint.name;let outcome=await gcEndpoint(endpoint.socket,endpoint.dir,{staleEngine:{}}).catch(()=>({removed:!1}));"stopped"in outcome?delete skip[endpoint.name]:outcome.removed?(removed+=1,delete skip[endpoint.name]):skip[endpoint.name]=nextSkip(skip[endpoint.name],now())}let marker={completedAt:now(),cursor,examined,removed,stoppedBy,skip};return await writeHostGcPassMarker(options.agentDir,marker),{ran:!0,marker}}function scheduleOpportunisticHostGc(options){if(opportunisticHostGcRunning(options.agentDir))return;let pass=new Promise(resolve6=>{setImmediate(()=>{gcHostEndpointsOpportunistically(options).then(()=>{},error=>recordPassFailure(options.agentDir,error)).finally(resolve6)}).unref()});trackOpportunisticHostGc(options.agentDir,pass)}async function gcCandidates(options){let targetName=basename2(createHostDaemonPaths({socket:options.exclude,agentDir:options.agentDir}).dir),candidates=[];for(let endpoint of await listHostEndpoints(options.agentDir)){let name=basename2(endpoint.dir);endpoint.socket===null||name===targetName||sameEndpoint(endpoint.socket,options.exclude)||candidates.push({...endpoint,socket:endpoint.socket,name})}return candidates}function rotateAfter(endpoints,cursor){if(cursor===null)return endpoints;let start=endpoints.findIndex(endpoint=>endpoint.name>cursor);return start<=0?endpoints:[...endpoints.slice(start),...endpoints.slice(0,start)]}async function recordPassFailure(agentDir,error){let line=`${new Date().toISOString()} gc pass failed: ${error instanceof Error?error.message:String(error)}
`;await appendFile(join6(agentDir,"rpc-host-daemon","gc-pass.log"),line,{mode:384}).catch(logError=>{logError instanceof Error&&"code"in logError&&logError.code==="ENOENT"||process.emitWarning(`host gc pass failed and could not be recorded: ${String(logError)}`)})}import{realpath as realpath2}from"node:fs/promises";import{basename as basename3,dirname as dirname3,resolve as resolve3}from"node:path";async function foreignAgentDirRefusal(socket,callerAgentDir,host){let hostAgentDir=host.agentDir??await layoutAgentDir(socket);if(hostAgentDir===void 0)return;let detail=await agentDirMismatch(socket,callerAgentDir,hostAgentDir);return detail===void 0?void 0:{action:"refuse",reason:"foreign_agent_dir",upgradeable:!1,detail}}async function agentDirMismatch(socket,callerAgentDir,hostAgentDir){let[ours,theirs]=await Promise.all([canonicalDirectory(callerAgentDir),canonicalDirectory(hostAgentDir)]);if(theirs!==ours)return`${socket} is served by the host of agent dir ${theirs}, and this client's agent dir is ${ours}; a host is only replaced by a client of its own agent dir - run with that agent dir to upgrade it, or use a socket of your own`}async function layoutAgentDir(socket){let rpcDirectory=dirname3(socket);if(basename3(socket)!=="rpc.sock"||basename3(rpcDirectory)!=="rpc")return;let agentDir=dirname3(rpcDirectory),paths=createHostDaemonPaths({socket,agentDir});return await provenOwner(await readHostRegistration(paths),socket)===void 0?void 0:agentDir}async function canonicalDirectory(path){return realpath2(path).catch(()=>resolve3(path))}import{spawn as spawn3}from"node:child_process";import{randomUUID as randomUUID2}from"node:crypto";import{open as open2}from"node:fs/promises";import{rm as rm2,writeFile as writeFile2}from"node:fs/promises";var SUCCESSOR_EXIT_WAIT_MS=5e3;async function abandonSuccessor(context){let{child,exited,paths,instanceId,bootSettings}=context,target={daemonDir:paths.dir,generation:generationPaths(paths,instanceId),instanceId,sender:{pid:process.pid,kind:"successor"},reason:context.reason},killed=child?.pid!==void 0&&child.exitCode===null&&child.signalCode===null?await announceStop(target,child.pid):void 0;killed!==void 0&&child?.pid!==void 0&&signalPid(child.pid,"SIGKILL");try{bootSettings===void 0?await rm2(paths.settingsFile,{force:!0}):await writeFile2(paths.settingsFile,bootSettings,{mode:HOST_STATE_FILE_MODE}),child?.pid===void 0?await rm2(generationPaths(paths,instanceId).dir,{recursive:!0,force:!0}):exited!==void 0&&await exitedWithin(exited,SUCCESSOR_EXIT_WAIT_MS)&&(killed!==void 0&&await recordEscalation(target,killed),await releaseGeneration(paths,{instanceId,pid:child.pid}));return}catch(cause){return`successor cleanup failed: ${cause instanceof Error?cause.message:String(cause)}`}}async function exitedWithin(exited,ms){let timer,timedOut=new Promise(resolve6=>{timer=setTimeout(()=>resolve6(!1),ms)});try{return await Promise.race([exited.then(()=>!0),timedOut])}finally{clearTimeout(timer)}}import{rm as rm3,writeFile as writeFile3}from"node:fs/promises";import{join as join7}from"node:path";async function driveSuccessorStartup(options){let{controller,coordinated}=options.attempt,terminal=controller.settled().then(()=>"terminal"),failure=async()=>{let outcome=await controller.settled();if(outcome.kind==="ready")throw new Error("startup controller reported READY on a failure path");return{ready:!1,outcome}};if(coordinated){if(!await controller.whenPhase("presenter_resolved")||options.presenter&&await Promise.race([options.presenter(),terminal])==="terminal"||controller.complete("presenter_resolved")!=="accepted")return failure();try{await options.attempt.grant()}catch(cause){return controller.fail(cause instanceof Error?cause:new Error(String(cause))),failure()}if(!await controller.whenPhase("public_verified"))return failure()}let answer2=await Promise.race([options.awaitAnswer(Math.max(1,controller.remainingMs())),terminal]);return answer2!=="terminal"&&answer2!==void 0&&controller.complete("public_verified")==="accepted"?{ready:!0,answer:answer2}:(controller.terminal||controller.fail(new Error("the successor never answered on the public socket")),failure())}function successorPresenter(bootstrap,child,predecessor,coordinated){if(bootstrap===void 0)return;let relay=async()=>{let stream=typeof bootstrap=="function"?await bootstrap():bootstrap;if(stream)return relayPresenterBootstrap(stream,child,{kind:"replacement",predecessorHostInstance:predecessor.instanceId});let channel=child.stdio[MCP_PRESENTER_BOOTSTRAP_FD];return typeof channel=="object"&&channel!==null&&"destroy"in channel&&typeof channel.destroy=="function"&&channel.destroy(),"closed"};if(typeof bootstrap!="function"||!coordinated){let started2=relay();return()=>started2}let started;return()=>(started??=relay(),started)}function failureDetail(outcome,cleanupFailure){return outcome.kind==="timeout"?startupTimeoutDetail(outcome,cleanupFailure?"incomplete":"completed"):outcome.cause.message}function adoptionGrant(attempt,generationDir,child){let file=join7(generationDir,ADOPTION_GRANT_FILE);return{async grant(){await writeFile3(file,`${JSON.stringify({attempt})}
`,{mode:384});let pipe=child.stdio[16];if(typeof pipe!="object"||pipe===null||!("write"in pipe)||typeof pipe.write!="function")throw new Error("the successor's startup pipe is gone");pipe.write(startupGrantLine(attempt))},revoke:()=>rm3(file,{force:!0})}}function predecessorOwnerArgs(host){return host.instanceId!==void 0&&host.capabilities.includes(ENDPOINT_OWNER_FENCE_CAPABILITY)?["--replace-owner",host.instanceId]:[]}async function startSuccessor(context){let{options,paths,host,owner,drainGate}=context,generation=(host.generation??0)+1,instanceId=randomUUID2(),bindSocket=generationBindPath(options.socket,generation);if(Buffer.byteLength(bindSocket)>MAX_SOCKET_PATH_BYTES)return{action:"refuse",reason:"socket_path_too_long",upgradeable:!0,detail:bindSocket};let replaced=await statSocketIdentity(options.socket);if(!replaced)return{action:"refuse",reason:"socket_replaced",upgradeable:!0};let running=await readHostSettings(paths),lifetimeOwner=host.instanceId?await readHostOwner(generationPaths(paths,host.instanceId).dir):null,inheritOwnerPipe=lifetimeOwner?.pid===process.pid&&sameHostOwner(lifetimeOwner,await callerHostOwner()),bootSettings=await readFileOrUndefined(paths.settingsFile);await writeHostSettings(paths,{socket:options.socket,capabilities:PINNED_HOST_CLIENT_CAPABILITIES,coldStart:options.policy?.coldStart??running?.coldStart??"transient",idleExitMs:options.policy?.idleExitMs??running?.idleExitMs??9e5,generation,instanceId});let child,exited;try{await writeHostOwner(generationPaths(paths,instanceId).dir,lifetimeOwner??null),await options._test?.beforeSpawn?.();let argv=["--socket",options.socket,"--bind",bindSocket,"--replace",`${replaced.dev}:${replaced.ino}`,...predecessorOwnerArgs(host),...inheritOwnerPipe?["--owner-fd",String(OWNER_WATCH_FD)]:[],...options.presenterBootstrap?["--mcp-presenter-fd","4"]:[],...options.mcpPresenterEnforcement||host.capabilities.includes("mcp_form_presenter_v1")?["--mcp-presenter-enforcement"]:[],...options.hostArgs??[]],launch=(options._test?.launch??options.launch)?.(argv)??{...defaultHostLaunch(argv),reportsStartup:!0},attempt=beginStartupAttempt({socket:options.socket,instanceId,generation,attempt:newStartupAttempt(),coordinated:launch.reportsStartup===!0,successorOf:host.instanceId??null,...options._test?.readinessTimeoutMs?{decisionBudgetMs:options._test.readinessTimeoutMs}:{}}),stderr=await open2(paths.stderrLog,"a",384),stdio=attempt.stdio(options.presenterBootstrap?["ignore","ignore",stderr.fd,inheritOwnerPipe?"pipe":"ignore","pipe"]:inheritOwnerPipe?["ignore","ignore",stderr.fd,"pipe"]:["ignore","ignore",stderr.fd]),env={...successorHostEnvironment({agentDir:options.agentDir,env:options.env,expectedRuntimeBuildId:options.expectedRuntimeBuildId,paths,generation,instanceId}),...attempt.env},placed=await placeHostLaunch(launch,instanceId,env),spawned=spawnWithPrivateFds(spawn3,placed.command,[...placed.args],{detached:!0,windowsHide:!0,env,stdio}),presenter=successorPresenter(options.presenterBootstrap,spawned,host,attempt.coordinated);child=spawned;let childExit=new Promise(resolve6=>spawned.once("exit",(code,signal)=>resolve6({code,signal})));if(exited=childExit.then(()=>{}),attempt.attach(spawned,childExit),await stderr.close(),inheritOwnerPipe&&keepOwnerPipe(spawned),child.pid===void 0)throw new Error("failed to spawn the successor generation");let processStartTime=await waitForStartTime(child.pid,1e4).catch(()=>{})??null,registration={record:{pid:child.pid,processStartTime},socket:options.socket,instanceId,generation,launchProfileId:hostLaunchProfile(["--mode","rpc","--multi-session",...options.hostArgs??[]],process.cwd()).profile_id};await writeGenerationRecord(paths,registration),await options._test?.afterSpawn?.(child.pid);let grant=adoptionGrant(attempt.binding.attempt,generationPaths(paths,instanceId).dir,spawned),childGone=exited,run=await driveSuccessorStartup({attempt:{controller:attempt.controller,coordinated:attempt.coordinated,grant:grant.grant},presenter:attempt.coordinated?presenter:void 0,awaitAnswer:budgetMs=>awaitSuccessor(options.socket,host,childGone,budgetMs)}),adopted=run.ready?run.answer:await settleCandidateAdoption(options.socket,instanceId,grant.revoke)==="completed"?await probeProtocolInfo(options.socket,2e3)??null:void 0;if(adopted===void 0){let reason=await abortReason(options.socket,replaced),cleanupFailure=await abandonSuccessor({child,exited,paths,instanceId,bootSettings,reason:"successor_readiness_timeout"}),detail=[run.ready?void 0:failureDetail(run.outcome,cleanupFailure),cleanupFailure].filter(Boolean).join("; ");return{action:"refuse",reason,upgradeable:!0,...detail&&{detail}}}return await options._test?.beforeRegistration?.(),await writeHostRegistration(paths,{...registration,...adopted?successorBuild(adopted):{}}),attempt.coordinated||await presenter?.(),child.unref(),owner!==void 0&&(drainGate===void 0||await drainGate())&&signalGeneration(owner.pid,"SIGUSR1"),{action:"handoff",pid:child.pid,socket:options.socket,generation:adopted?.generation??generation,instanceId:adopted?.instanceId??instanceId}}catch(cause){let cleanupFailure=await abandonSuccessor({child,exited,paths,instanceId,bootSettings,reason:"successor_start_failed"}),detail=cause instanceof Error?cause.message:String(cause);return{action:"refuse",reason:"successor_unavailable",upgradeable:!0,detail:cleanupFailure?`${detail}; ${cleanupFailure}`:detail}}}function successorBuild(answer2){return answer2.engineVersion===void 0||answer2.engineOrdinal===void 0?{}:{build:{text:answer2.engineVersion,ordinal:answer2.engineOrdinal}}}async function awaitSuccessor(socket,previous,exited,budgetMs){let deadline=Date.now()+budgetMs,childGone=!1;for(exited.then(()=>{childGone=!0});Date.now()<=deadline;){let answer2=await probeProtocolInfo(socket,Math.min(2e3,Math.max(1,deadline-Date.now())));if(answer2&&answer2.instanceId!==void 0&&answer2.instanceId!==previous.instanceId)return answer2;if(childGone)return;await delay3(50)}}async function abortReason(socket,replaced){let current=await statSocketIdentity(socket).catch(()=>{});return current===void 0||current.dev!==replaced.dev||current.ino!==replaced.ino?"socket_replaced":"successor_unavailable"}function delay3(ms){return new Promise(resolve6=>setTimeout(resolve6,ms))}var SESSION_COUNT_TIMEOUT_MS=1e4;async function handoffUnregisteredHost(options,paths,host){let counted=await holdSessionCount(options.socket,SESSION_COUNT_TIMEOUT_MS);try{let legacy=await provenLegacyOwner(paths,options.socket),sessions=counted?.sessions;if(sessions!==0)return legacy!==void 0?{action:"refuse",reason:"legacy_host",upgradeable:!0,detail:busyLegacyHostDetail(legacy.pid,options.socket,sessions)}:{action:"refuse",reason:"unknown_owner",upgradeable:!0,detail:`${options.socket} has no provable owner and holds ${describeSessions(sessions)}; it is never signalled - let that work finish, then retry`};let result=await startSuccessor({options,paths,host,owner:legacy,drainGate:async()=>await counted?.recount(SESSION_COUNT_TIMEOUT_MS)===0});return result.action==="handoff"&&legacy===void 0&&warnUnsignalledPredecessor(options.socket,host),result}finally{counted?.close()}}function warnUnsignalledPredecessor(socket,host){process.stderr.write(`generation handoff: no provable owner for ${socket}; the host it replaced (instance ${host.instanceId??"unknown"}, engine ${host.engineVersion??"unknown"}) listed 0 sessions and was not signalled; it drains itself on losing the public socket
`)}var HANDOFF_PROBE_TIMEOUT_MS=1e4;async function handoffHost(options){if(handoffUnsupported(options))return{action:"refuse",reason:"upgrade_unsupported",upgradeable:!1};let release=await acquireHostEnsureLock(options.socket,startupEnvelope(childStalledStopMaxMs()).lockWait);try{return await handoffHostLocked(options)}finally{await release()}}async function handoffHostLocked(requested){if(handoffUnsupported(requested))return{action:"refuse",reason:"upgrade_unsupported",upgradeable:!1};let options={...requested,agentDir:requested.agentDir||getAgentDir()},paths=createHostDaemonPaths({socket:options.socket,agentDir:options.agentDir});await createDaemonDirectories(paths);let host=await probeProtocolInfo(options.socket,HANDOFF_PROBE_TIMEOUT_MS);if(!host)return{action:"refuse",reason:"no_host",upgradeable:!1};if(!host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY))return{action:"refuse",reason:"handoff_unsupported",upgradeable:!1};let downgrade=downgradeRefusal(options,host);if(downgrade)return downgrade;let foreign=await foreignAgentDirRefusal(options.socket,options.agentDir,host);if(foreign)return foreign;await electPointer(paths);let registered=await readHostRegistration(paths),owner=await provenOwner(registered,options.socket);return owner?startSuccessor({options,paths,host,owner}):handoffUnregisteredHost(options,paths,host)}function downgradeRefusal(options,host){if(options.allowDowngrade===!0||host.engineOrdinal===void 0)return;let running=engineIdentityOf(host.engineVersion??"",host.engineOrdinal),detail=olderEngineDetail(options.successorEngine??engineBuildIdentity(),running);return detail===void 0?void 0:{action:"refuse",reason:"older_engine",upgradeable:!1,detail}}function handoffUnsupported(options){return(options._test?.platform??process.platform)==="win32"}import{lstat as lstat2,readdir,readFile as readFile5,rmdir,unlink}from"node:fs/promises";import{join as join8}from"node:path";var ALIAS_NAME=new RegExp(`^${ALIAS_PREFIX}[A-Za-z0-9]{6}$`),MIN_AGE_MS=6e4,MAX_ALIASES_PER_ROOT=64;async function reapOrphanedBindAliases(){await Promise.all([...new Set(bindAliasRoots())].map(root=>reapOrphanedBindAliasesIn(root)))}async function reapOrphanedBindAliasesIn(root){let candidates=(await readdir(root).catch(()=>[])).filter(name=>ALIAS_NAME.test(name)).slice(0,MAX_ALIASES_PER_ROOT);await Promise.all(candidates.map(name=>reapIfOrphaned(join8(root,name)).catch(()=>{})))}async function reapIfOrphaned(dir){let entry=await lstat2(dir),self=process.getuid?.();if(!entry.isDirectory()||self!==void 0&&entry.uid!==self||(entry.mode&511)!==448||entry.mtimeMs>Date.now()-MIN_AGE_MS)return;let contents=(await readdir(dir)).sort();contents.length!==2||contents[0]!==ALIAS_OWNER||contents[1]!==ALIAS_LINK||(await lstat2(join8(dir,ALIAS_LINK))).isSymbolicLink()&&await ownerIsDead(join8(dir,ALIAS_OWNER))&&(await unlink(join8(dir,ALIAS_LINK)),await unlink(join8(dir,ALIAS_OWNER)),await rmdir(dir))}async function ownerIsDead(file){let owner=JSON.parse(await readFile5(file,"utf8"));if(typeof owner!="object"||owner===null)return!1;let pid=Reflect.get(owner,"pid"),processStartTime=Reflect.get(owner,"processStartTime");return typeof pid!="number"||typeof processStartTime!="string"||processStartTime.length===0?!1:!await processMatchesPidFile({pid,processStartTime},readAliasOwnerStartTime).catch(error=>{if(error instanceof ProcessIdentityUnreadableError)return!0;throw error})}import{lstat as lstat3,readdir as readdir2,readFile as readFile6,rm as rm4}from"node:fs/promises";import{join as join9}from"node:path";async function reapOrphanedInternalHostDirs(){await Promise.all(internalHostDirRoots().map(root=>reapOrphanedInternalHostDirsIn(root)))}async function reapOrphanedInternalHostDirsIn(root){try{let entries=await readdir2(root,{withFileTypes:!0});await Promise.all(entries.filter(entry=>entry.isDirectory()&&entry.name.startsWith(INTERNAL_HOST_DIR_PREFIX)).map(async entry=>{try{let uid=process.getuid?.();if(uid!==void 0&&(await lstat3(join9(root,entry.name))).uid!==uid)return;let owner=JSON.parse(await readFile6(join9(root,entry.name,".owner"),"utf8"));typeof owner.pid=="number"&&typeof owner.processStartTime=="string"&&typeof owner.createdAt=="number"&&owner.processStartTime.length>0&&owner.createdAt<Date.now()-6e4&&(await readdir2(join9(root,entry.name))).length===1&&!await processMatchesPidFile({pid:owner.pid,processStartTime:owner.processStartTime}).catch(error=>{if(error instanceof ProcessIdentityUnreadableError)return!0;throw error})&&await rm4(join9(root,entry.name),{recursive:!0,force:!0})}catch{}}))}catch{}}var EXISTING_HOST_PROBE_TIMEOUT_MS=1e4;async function ensureHost(options){return withRpcKeyRoot(rpcKeyRoot(options,options.agentDir),()=>ensureHostInKeyRoot(options))}async function ensureHostInKeyRoot(options){let socket=normalizeSocketPath(options.socket),paths=createHostDaemonPaths({socket,...options.agentDir?{agentDir:options.agentDir}:{}});await createDaemonDirectories(paths);let lockTarget=hostEnsureLockTarget(socket);await mkdir(dirname4(lockTarget),{recursive:!0}),await writeFile4(lockTarget,"",{flag:"a",mode:384}),await Promise.all([reapOrphanedInternalHostDirs(),reapOrphanedBindAliases()]);let{lockWait}=startupEnvelope(childStalledStopMaxMs()),release=await acquireOwnershipSafeLock(`${lockTarget}.lock`,hostEnsureLockOptions(lockWait)).catch(error=>{throw isBusy(error)?new Error(ensureLockWaitDetail(lockWait),{cause:error}):error}),ensured;try{await options._test?.afterLockAcquired?.(),ensured=await ensureHostLocked(paths,socket,options)}finally{await release()}return scheduleOpportunisticHostGc({agentDir:options.agentDir??getAgentDir(),exclude:socket}),ensured}async function ensureHostLocked(paths,socket,options,stopDeadline=Date.now()+Math.min(options.stoppingTimeoutMs??STOP_WAIT_BUDGET_MS,STOP_WAIT_BUDGET_MS)){await ensureEndpointIdentity(paths,socket,{repair:!0});let testOptions=options._test,registered=await readHostRegistration(paths),registeredHere=registersSocket(registered,socket);if(registeredHere&®istered&&!processIsLive(registered.record.pid)&&await hostChildAlive(generationPaths(paths,registered.instanceId)))throw new HostEnsureRefusedError(socket,"host_stalled",void 0);let held=await holdProtocolInfo(socket,testOptions?.existingHostProbeTimeoutMs??EXISTING_HOST_PROBE_TIMEOUT_MS),protocol=held?.info;if(protocol?.lifecycle==="stopping"){if(held?.hold.release(),!registeredHere||!registered||registered.instanceId!==protocol.instanceId)throw new HostEnsureRefusedError(socket,"host_stopping",protocol,"no matching registered generation");let generation=generationPaths(paths,registered.instanceId);for(;;){if(await resolvePidFileOwnership(registered.record,testOptions?.readProcessStartTime)==="gone"&&!await hostChildAlive(generation))return ensureHostLocked(paths,socket,options,stopDeadline);let remaining=stopDeadline-Date.now();if(remaining<=0)throw new HostEnsureRefusedError(socket,"host_stopping",protocol,"generation exit exceeded stop budget");await delay(Math.min(50,remaining))}}let startedByUs=registeredHere&&await writtenByThisProcess(registered?.writer,testOptions?.readProcessStartTime),attachedPid=registeredHere?registered?.record.pid??0:0,decision=decideEnsureAction(options,startedByUs,protocol);if(options.owner&&held&&(decision.action==="reuse"||decision.action==="handoff"))try{if(!registeredHere||!registered||registered.instanceId!==held.info.instanceId)throw new Error("RPC host has no matching registered owner-lifetime generation");await claimHostOwner(generationPaths(paths,registered.instanceId).dir)}catch(cause){throw held.hold.release(),cause}if(decision.action==="reuse"&&held)return{pid:attachedPid,socket,reused:!0,release:held.hold.release};switch(held?.hold.release(),decision.action){case"reuse":throw new Error(`host at ${socket} was reused without answering its probe`);case"refuse":throw new HostEnsureRefusedError(socket,decision.reason,protocol);case"handoff":try{return await upgradeGeneration(paths,socket,options,attachedPid)}catch(cause){if(cause instanceof HostEnsureRefusedError&&cause.reason==="host_stopping")return ensureHostLocked(paths,socket,options,stopDeadline);throw cause}case"start":break;default:return assertNever(decision)}let probe=testOptions?.readProcessStartTime??readProcessStartTime,pidMatches=registeredHere&®istered?await matchesPidFileOrUnknown(registered.record,probe):!1,stranded;if(registered&&pidMatches)if(!startedByUs)await refuseIfForeignHeld(paths,registered,socket,protocol),await refuseIfStalled(paths,registered.instanceId,socket,protocol),stranded=registered;else{if(await probeSocketReachable(socket,EXISTING_HOST_PROBE_TIMEOUT_MS))throw new HostEnsureRefusedError(socket,"host_busy",protocol);await refuseIfStalled(paths,registered.instanceId,socket,protocol),await stopManagedHost(registered.record,testOptions?.stopTimeoutMs??DEFAULT_STOP_TIMEOUT_MS,{daemonDir:paths.dir,generation:generationPaths(paths,registered.instanceId),instanceId:registered.instanceId,sender:ensureSender(),reason:"replace_unreachable"},probe)}let legacyRefusal=await retireIdleLegacyHost(paths,probe,testOptions?.stopTimeoutMs);if(legacyRefusal!==void 0)throw new HostEnsureRefusedError(socket,"legacy_host",protocol,legacyRefusal);if(stranded!==void 0)return startHost(paths,socket,options,stranded.generation+1);if(await unregisteredEndpointHeld(socket))throw new HostEnsureRefusedError(socket,"endpoint_occupied",protocol,"no host registration names this socket and its listener did not answer get_protocol_info");return registeredHere&&await clearHostRegistration(paths),startHost(paths,socket,options)}async function upgradeGeneration(paths,socket,options,attachedPid){let result=await handoffHostLocked({socket,agentDir:options.agentDir??getAgentDir(),hostArgs:options.hostArgs??[],presenterBootstrap:options.presenterBootstrap,mcpPresenterEnforcement:options.mcpPresenterEnforcement,...options.env?{env:options.env}:{},...options.policy?{policy:options.policy}:{},_test:{...options._test?.launch?{launch:options._test.launch}:{},...options._test?.readinessTimeoutMs?{readinessTimeoutMs:options._test.readinessTimeoutMs}:{}}});return result.action==="handoff"?{pid:result.pid,socket,reused:!1,release:await holdEnsured(socket)}:(await appendStderr(paths,`generation handoff refused: ${result.reason}${result.detail?` (${result.detail})`:""}`),{pid:attachedPid,socket,reused:!0,release:await holdEnsured(socket)})}async function holdEnsured(socket){let held=await holdProtocolInfo(socket,EXISTING_HOST_PROBE_TIMEOUT_MS);if(!held)throw new Error(`RPC socket host at ${socket} stopped answering before this ensure could hold it`);if(held.info.lifecycle==="stopping")throw held.hold.release(),new HostEnsureRefusedError(socket,"host_stopping",held.info);return held.hold.release}function registersSocket(registered,socket){return registered===void 0?!1:registered.socket===void 0||sameEndpoint(registered.socket,socket)}function normalizeSocketPath(value){return value.startsWith("unix://")?value.slice(7):value}function assertNever(value){throw new Error(`unreachable host decision: ${JSON.stringify(value)}`)}function normalizeWaitItems(value,omitted){let byId=new Map;if(Array.isArray(value))for(let entry of value){if(typeof entry!="object"||entry===null||!("id"in entry)||typeof entry.id!="string"||entry.id.trim().length===0)continue;let item={id:entry.id,..."description"in entry&&typeof entry.description=="string"?{description:entry.description}:{},..."startedAtMs"in entry&&typeof entry.startedAtMs=="number"&&Number.isFinite(entry.startedAtMs)&&Math.abs(entry.startedAtMs)<=864e13?{startedAtMs:entry.startedAtMs}:{}},previous=byId.get(item.id);(!previous||JSON.stringify(item)<JSON.stringify(previous))&&byId.set(item.id,item)}let items=[...byId.values()].sort((a,b)=>a.id<b.id?-1:a.id>b.id?1:0),omittedItems=Math.max(0,items.length-32)+(typeof omitted=="number"&&Number.isSafeInteger(omitted)&&omitted>0?omitted:0);return{...items.length?{items:items.slice(0,32)}:{},...omittedItems?{omittedItems}:{}}}function wakeSourceItems(data){return("items"in data?data.items:void 0)??("monitors"in data?data.monitors:void 0)}function waitItemSignature(detail){return JSON.stringify([detail.items?.map(item=>[item.id,item.description]),detail.omittedItems])}function projectWaitItems(detail){return{...detail.items?{items:detail.items.map(item=>({id:item.id,...item.description===void 0?{}:{label:item.description},...item.startedAtMs===void 0?{}:{startedAt:new Date(item.startedAtMs).toISOString()}}))}:{},...detail.omittedItems?{omittedItems:detail.omittedItems}:{}}}function readWaitItems(value,omitted){let items=Array.isArray(value)?value.map(item=>typeof item!="object"||item===null?item:{..."id"in item?{id:item.id}:{},..."label"in item?{description:item.label}:{},..."startedAt"in item&&typeof item.startedAt=="string"?{startedAtMs:Date.parse(item.startedAt)}:{}}):void 0;return projectWaitItems(normalizeWaitItems(items,omitted))}var WakeSourceTracker=class{constructor(){this.counts=new Map}observe(data){if(typeof data!="object"||data===null||!("source"in data)||!("activeCount"in data))return;let{source,activeCount}=data;typeof source!="string"||source.length===0||typeof activeCount!="number"||!Number.isFinite(activeCount)||(activeCount>0?this.counts.set(source,{activeCount,kind:"kind"in data&&data.kind==="children"?"children":"background",...normalizeWaitItems(wakeSourceItems(data))}):this.counts.delete(source))}get hasActive(){return this.counts.size>0}get activeSources(){return[...this.counts.keys()]}get activeCounts(){let children=0,background=0;for(let record of this.counts.values())switch(record.kind){case"children":children+=record.activeCount;break;case"background":background+=record.activeCount;break;default:record.kind}return{children,background}}};function isSessionBusySnapshot(snapshot){return snapshot.isStreaming||snapshot.isBashRunning||snapshot.isCompacting||snapshot.hasSessionWork||snapshot.hasActiveWakeSource}function isHandoffBusy(snapshot){return isSessionBusySnapshot({...snapshot,hasActiveWakeSource:!1})}function selectDrainVerdicts(registry,inFlight,unreadable){let park=[],gone=[];for(let{sessionId,status,sessionPath}of registry.list()){if(status!=="open"||inFlight(sessionId))continue;let entry=registry.peek(sessionId);!entry||handoffBusy(entry,sessionId,unreadable)||(sessionPath!==void 0&&sessionDirectoryRemoved(sessionPath)?gone.push(sessionId):park.push(sessionId))}return{park,gone}}function handoffBusy(entry,sessionId,unreadable){try{let snapshot=entry.runtime?.session.activitySnapshot;return entry.worker?.handoffBusy===!0||snapshot!==void 0&&isHandoffBusy(snapshot)}catch(cause){return unreadable(sessionId,cause),!1}}function readDrainVerdicts(registry,inFlight){try{return selectDrainVerdicts(registry,inFlight,(sessionId,cause)=>{process.stderr.write(`senpi rpc handoff activity of ${sessionId} unreadable, parking: ${String(cause)}
`)})}catch(cause){process.stderr.write(`senpi rpc handoff drain pass failed, retrying: ${String(cause)}
`);return}}var BEGIN_HANDOVER_COMMAND="begin_handover",SUCCESSOR_PROBE_TIMEOUT_MS=1e4;function parseBeginHandover(record){let{operation_id,if_instance_id,if_generation,target_runtime_build_id,launch,host_args,env}=record;if(typeof operation_id!="string"||operation_id==="")return"operation_id must be a non-empty string";if(typeof if_instance_id!="string")return"if_instance_id must be a string";if(typeof if_generation!="number"||!Number.isSafeInteger(if_generation))return"if_generation must be an integer";if(typeof target_runtime_build_id!="string")return"target_runtime_build_id must be a string";if(!isRecord2(launch)||typeof launch.command!="string"||!isStringArray(launch.args))return"launch must be { command, args }";if(!isStringArray(host_args))return"host_args must be an array of strings";if(!isRecord2(env)||!Object.values(env).every(value=>typeof value=="string"))return"env must map names to strings";let policy=isRecord2(record.policy)?record.policy:void 0,{agent_dir}=record,mcpPresenterEnforcement=record.mcp_presenter_enforcement;if(mcpPresenterEnforcement!==void 0&&typeof mcpPresenterEnforcement!="boolean")return"mcp_presenter_enforcement must be a boolean";if(agent_dir!==void 0&&(typeof agent_dir!="string"||agent_dir===""))return"agent_dir must be a non-empty string";let targetEngine=parseTargetEngine(record.target_engine);if(targetEngine===null)return"target_engine must be { text, ordinal: [y, m, d, n, epoch] }";let allowDowngrade=record.allow_downgrade;return allowDowngrade!==void 0&&typeof allowDowngrade!="boolean"?"allow_downgrade must be a boolean":{operationId:operation_id,ifInstanceId:if_instance_id,ifGeneration:if_generation,targetRuntimeBuildId:target_runtime_build_id,launch:{command:launch.command,args:launch.args,...launch.reports_startup===!0&&{reportsStartup:!0}},hostArgs:host_args,env,...mcpPresenterEnforcement!==void 0&&{mcpPresenterEnforcement},...policy!==void 0&&{policy},...agent_dir!==void 0&&{agentDir:agent_dir},...targetEngine!==void 0&&{targetEngine},...allowDowngrade===!0&&{allowDowngrade}}}function parseTargetEngine(value){if(value===void 0)return;if(!isRecord2(value)||typeof value.text!="string")return null;let ordinal=parseEngineOrdinal(value.ordinal);return ordinal===void 0?null:engineIdentityOf(value.text,ordinal)}function beginHandoverResponse(id,answer2){let data=typeof answer2=="string"?{refused:"invalid_request",detail:answer2}:answer2.kind==="refused"?{refused:answer2.reason,...answer2.detail!==void 0&&{detail:answer2.detail}}:handoverWire(answer2.view);return{...typeof id=="string"&&{id},type:"response",command:BEGIN_HANDOVER_COMMAND,success:!0,data}}function handoverWire(view){return{operation_id:view.operationId,state:view.state,target_runtime_build_id:view.targetRuntimeBuildId,...view.reason!==void 0&&{reason:view.reason},...view.successor!==void 0&&{successor:view.successor}}}function handoverRefusal(command,view){return{...command.id!==void 0&&{id:command.id},type:"response",command:command.type,success:!1,error:`handover_pending: this host is handing over to runtime ${view.targetRuntimeBuildId} (operation ${view.operationId}); new work is admitted by its successor`}}function withHostIdentity(response,runtimeBuildId,handover){return response.command!=="get_protocol_info"||!response.success?response:{...response,data:{...response.data,...runtimeBuildId!==void 0&&{runtimeBuildId},...handover!==void 0&&{handover:handoverWire(handover)}}}}function isHostIdle(registry,inFlight){if((inFlight.get(void 0)??0)>0)return!1;let sessions=registry.list(),verdicts=selectDrainVerdicts(registry,sessionId=>(inFlight.get(sessionId)??0)>0,()=>{});return verdicts.park.length+verdicts.gone.length===sessions.length}async function performIdleHandover(context){let{request,socket,agentDir}=context,env={};for(let name of Object.keys(process.env))env[name]=null;Object.assign(env,request.env);let result=await handoffHost({presenterBootstrap:context.presenterBootstrap,mcpPresenterEnforcement:request.mcpPresenterEnforcement,socket,agentDir,hostArgs:request.hostArgs,env,expectedRuntimeBuildId:request.targetRuntimeBuildId,...request.targetEngine!==void 0&&{successorEngine:request.targetEngine},...request.allowDowngrade===!0&&{allowDowngrade:!0},...request.policy!==void 0&&{policy:request.policy},launch:argv=>({command:request.launch.command,args:[...request.launch.args,...argv],...request.launch.reportsStartup===!0&&{reportsStartup:!0}})});if(result.action==="refuse")return{ok:!1,reason:result.detail===void 0?result.reason:`${result.reason}: ${result.detail}`};await writeDaemonEnvKeys(createHostDaemonPaths({socket,agentDir}),Object.keys(request.env).sort()).catch(cause=>{process.stderr.write(`senpi rpc handover: could not record the daemon environment: ${String(cause)}
`)});let successor=await probeProtocolInfo(socket,SUCCESSOR_PROBE_TIMEOUT_MS);return{ok:!0,successor:{pid:result.pid,instanceId:result.instanceId,generation:result.generation,runtimeBuildId:successor?.runtimeBuildId??null}}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStringArray(value){return Array.isArray(value)&&value.every(entry=>typeof entry=="string")}var BYTES_PER_MB=1024*1024;function parseSessionRows(reply){return!isRecord3(reply)||!Array.isArray(reply.sessions)?[]:reply.sessions.flatMap(entry=>isRecord3(entry)?[{id:typeof entry.sessionId=="string"?entry.sessionId:"",kind:typeof entry.kind=="string"?entry.kind:"interactive",session_path:typeof entry.sessionPath=="string"?entry.sessionPath:null,cwd:typeof entry.cwd=="string"?entry.cwd:null,name:typeof entry.name=="string"?entry.name:null,attachments:typeof entry.attachments=="number"?entry.attachments:0,context:stringRecord(entry.context),memory:parseRowMemory(entry.memory)}]:[])}function parseRowMemory(value){if(!isRecord3(value))return{main_heap_mb:0,kernel_heap_mb:0,kernel_count:0};let toMb=bytes=>typeof bytes=="number"&&Number.isFinite(bytes)?Math.round(bytes/BYTES_PER_MB):0,count=value.kernel_count;return{main_heap_mb:toMb(value.main_heap_bytes),kernel_heap_mb:toMb(value.kernel_heap_bytes),kernel_count:typeof count=="number"&&Number.isFinite(count)?count:0}}async function readClaimRows(paths,generations){let rows=[];for(let claim of await readSessionPathClaims(paths.reservationsDir)){let owner=claim.owner;rows.push({session_path:owner.sessionPath,owner_pid:owner.pid,instance_id:owner.instanceId,generation:generations.find(row=>row.instanceId===owner.instanceId)?.generation??null,attached:owner.attached??null,live:await claimOwnerIsLive(owner)})}return rows.sort((left,right)=>left.session_path.localeCompare(right.session_path))}function stringRecord(value){return isRecord3(value)?Object.fromEntries(Object.entries(value).filter(entry=>typeof entry[1]=="string")):null}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var STATUS_PROBE_TIMEOUT_MS=1e4;async function readHostStatus(options,read={}){return(await probeHostStatus(options,read)).report}async function probeHostStatus(options,read={}){return withRpcKeyRoot(rpcKeyRoot({},options.agentDir),()=>probeHostStatusInKeyRoot(options,read))}async function probeHostStatusInKeyRoot(options,read){let paths=createHostDaemonPaths({socket:options.socket,...options.agentDir?{agentDir:options.agentDir}:{}}),prune=read.prune!==!1,includeWorkers=options.includeWorkers===!0,timeoutMs=read.timeoutMs??STATUS_PROBE_TIMEOUT_MS,host=await observeProtocolInfo(options.socket,timeoutMs);prune&&await pruneDeadGenerations(paths);let pointer=await electPointer(paths,{write:prune}),generations=await withHostUnits(await readGenerationRows(paths,{includeDead:!prune})),current=generations.find(row=>row.current&&row.alive),registered=await readHostRegistration(paths),metrics=current?await readHostProcessMetrics(current.pid):UNOBSERVED_METRICS,listing=host===void 0||host.lifecycle==="stopping"?[]:await readSessionListing(options.socket,includeWorkers,timeoutMs),claims=await readClaimRows(paths,generations);return{report:{reachable:host!==void 0,lifecycle:host?.lifecycle??null,socket:options.socket,pid:current?.pid??null,processStartTime:registered?.instanceId===current?.instanceId&®istered?.record.pid===current?.pid?registered?.record.processStartTime??null:null,instanceId:host?.instanceId??current?.instanceId??null,generation:host?.generation??current?.generation??null,engineVersion:host?.engineVersion??current?.engineVersion??null,capabilities:host?.capabilities??[],launchProfile:host?.launch_profile??null,runtimeBuildId:host?.runtimeBuildId??null,handover:host?.handover??null,sessions:countSessions(listing),zombies:metrics.zombies,rss_mb:metrics.rss_mb,host_rss_mb:metrics.host_rss_mb,host_footprint_mb:metrics.host_footprint_mb,open_fds:metrics.open_fds,memory_pressure:host?.memory_pressure??null,path_identity_resolver:host?.path_identity_resolver??null,env_keys:await readDaemonEnvKeys(paths),generations,pointer,crashes:readHostCrashRecords(paths.dir).filter(isHostCrash).length,shard:parseShardSocket(options.socket),session_rows:includeWorkers?listing:[],claims_live:claims.filter(claim=>claim.live).length,claims:includeWorkers?claims:[]},answered:host,listing}}async function readSessionCounts(socket,includeWorkers){return countSessions(await readSessionListing(socket,includeWorkers))}async function readSessionListing(socket,includeWorkers,timeoutMs=STATUS_PROBE_TIMEOUT_MS){let reply=await requestOnSocket(socket,{type:"list_sessions",[OBSERVE_REQUEST_FIELD]:!0,...includeWorkers?{include_workers:!0}:{}},timeoutMs);return parseSessionRows(reply)}function countSessions(rows){let attached=rows.filter(row=>row.attachments>0).length,retained=rows.length-attached;return{total:rows.length,interactive:rows.filter(row=>row.kind!=="worker").length,worker:rows.filter(row=>row.kind==="worker").length,retained,foreign_attached:attached,foreign_retained:retained}}function hostSummary(host){return host===void 0?null:{protocolVersion:host.protocolVersion,serverVersion:host.serverVersion,lifecycle:host.lifecycle??null,capabilities:host.capabilities,instanceId:host.instanceId??null,generation:host.generation??null,engineVersion:host.engineVersion??null,launchProfileId:host.launch_profile?.profile_id??null,pathIdentityResolver:host.path_identity_resolver??null}}var UNOBSERVED_METRICS={rss_mb:null,host_rss_mb:null,host_footprint_mb:null,open_fds:null,zombies:null};var HOST_EXIT_OK=0,HOST_EXIT_ERROR=1,HOST_EXIT_USAGE=2,HOST_EXIT_REFUSED=3,HOST_EXIT_FALLBACK=4;function identityPayload(socket,pid,host){return{socket,pid,lifecycle:host?.lifecycle??null,instanceId:host?.instanceId??null,generation:host?.generation??null,engineVersion:host?.engineVersion??null,engineOrdinal:host?.engineOrdinal??null,capabilities:host?.capabilities??[],launchProfileId:host?.launch_profile?.profile_id??null,runtimeBuildId:host?.runtimeBuildId??null,upgradeable:decideHostAction(decisionClient(),host,"upgrade").upgradeable}}async function clientRuntimeBuildId(spec){let profile=socketHostLaunchProfile(spec.hostArgs,process.cwd());return computeRuntimeBuildId({profile:profile.core}).catch(cause=>(process.stderr.write(`senpi host: runtime identity unreadable: ${String(cause)}
`),null))}function refusal(kind,host,body){return{exitCode:kind==="refuse"?HOST_EXIT_REFUSED:HOST_EXIT_FALLBACK,payload:{action:kind,...body,host:hostSummary(host)}}}function decisionClient(){return{protocolVersion:HOST_PROTOCOL_VERSION,requiredCapabilities:REQUIRED_HOST_CAPABILITIES,identity:engineBuildIdentity(),startedByUs:!1,platform:process.platform}}var PROBE_TIMEOUT_MS=1e4;async function idleHandoverOutcome(target,spec,terms,mcpPresenterEnforcement){let{socket}=target;if(process.platform==="win32")return refusal("refuse",void 0,{reason:"upgrade_unsupported",socket,operationId:terms.operationId});let before=await probeProtocolInfo(socket,PROBE_TIMEOUT_MS),refuse=(reason,extra={})=>refusal("refuse",before,{reason,socket,operationId:terms.operationId,...extra}),foreign=before===void 0?void 0:await foreignAgentDirRefusal(socket,target.agentDir,before);if(foreign)return refuse(foreign.reason,{detail:foreign.detail});let client=await clientRuntimeBuildId(spec);if(client!==terms.targetRuntimeBuildId)return refuse("target_build_mismatch",{detail:`this CLI launches ${client??"a runtime it cannot read"}`,clientRuntimeBuildId:client});if(before===void 0)return refuse("no_host");if(before.runtimeBuildId===terms.targetRuntimeBuildId)return answered(target,"handover_completed",before,terms,null);if(before.instanceId!==terms.ifInstanceId||before.generation!==terms.ifGeneration)return refuse("stale_generation",{detail:`the socket is served by ${before.instanceId??"an unnamed host"} generation ${before.generation??"?"}`});if(!before.capabilities.includes(RUNTIME_IDENTITY_HANDOVER_CAPABILITY))return refuse("handover_unsupported");let reply=await requestOnSocket(socket,beginHandoverCommand(target,spec,terms,mcpPresenterEnforcement),startupEnvelope(childStalledStopMaxMs()).handoverReply);return isRecord4(reply)?typeof reply.refused=="string"?refuse(reply.refused,typeof reply.detail=="string"?{detail:reply.detail}:{}):reply.state==="handover_blocked"?refuse("handover_blocked",{detail:reply.reason??null,handover:reply}):reply.state==="handover_completed"?answered(target,"handover_completed",await probeProtocolInfo(socket,PROBE_TIMEOUT_MS),terms,reply):answered(target,"handover_pending",before,terms,reply):reconcileLostReply(target,terms,before)}function beginHandoverCommand(target,spec,terms,mcpPresenterEnforcement){let env={};for(let[name,value]of Object.entries(daemonEnvironment(process.env,daemonEnvOverrides(process.env,spec.env))))value!==void 0&&(env[name]=value);let launch=defaultHostLaunch([]);return{type:BEGIN_HANDOVER_COMMAND,operation_id:terms.operationId,if_instance_id:terms.ifInstanceId,if_generation:terms.ifGeneration,target_runtime_build_id:terms.targetRuntimeBuildId,target_engine:{text:engineBuildIdentity().text,ordinal:engineBuildIdentity().ordinal},...terms.allowDowngrade===!0&&{allow_downgrade:!0},agent_dir:target.agentDir,launch:{command:launch.command,args:launch.args,reports_startup:!0},host_args:spec.hostArgs,env,...mcpPresenterEnforcement===!0&&{mcp_presenter_enforcement:!0},...spec.policy!==void 0&&{policy:spec.policy}}}async function reconcileLostReply(target,terms,before){let now=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS);return now?.runtimeBuildId===terms.targetRuntimeBuildId?answered(target,"handover_completed",now,terms,null):{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"handover_reply_lost",operationId:terms.operationId,...identityPayload(target.socket,await servingPid(target),now??before)}}}async function answered(target,action,host,terms,handover){return{exitCode:HOST_EXIT_OK,payload:{action,...identityPayload(target.socket,await servingPid(target),host),operationId:typeof handover?.operation_id=="string"?handover.operation_id:terms.operationId,clientRuntimeBuildId:terms.targetRuntimeBuildId,handover}}}async function servingPid(target){return(await readHostRegistration(createHostDaemonPaths(target)))?.record.pid??0}function isRecord4(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{readdir as readdir3}from"node:fs/promises";var TUI_PROBE_TIMEOUT_MS=1500;function endpointProbeTimeoutMs(kind,requestedMs){return kind==="tui"?Math.min(requestedMs??TUI_PROBE_TIMEOUT_MS,TUI_PROBE_TIMEOUT_MS):requestedMs??DEFAULT_PROBE_TIMEOUT_MS}async function classifyEndpointLiveness(entry,options={}){let host=entry.socket===null?void 0:await observeProtocolInfo(entry.socket,endpointProbeTimeoutMs(entry.endpoint_kind,options.timeoutMs));return judgeEndpointLiveness(hostDaemonDirectoryPaths(entry.dir),host===void 0?void 0:host.instanceId??null)}async function judgeEndpointLiveness(paths,answered2){return typeof answered2=="string"&&await recordsInstance(paths,answered2)?"routable":answered2!==void 0||await anyGenerationLive(paths)?"live_unresponsive":"dead"}async function recordsInstance(paths,instanceId){return(await readdir3(paths.generationsDir).catch(()=>[])).includes(instanceId)?await readFileOrUndefined(generationPaths(paths,instanceId).pidFile).catch(()=>{})!==void 0:!1}var STATUS_ALL_MAX_IN_FLIGHT=64;async function readAllHostStatus(options){let endpoints=await listHostEndpoints(options.agentDir),read=options._test?.readEndpoint??(endpoint=>endpointStatus(endpoint,options)),rows=new Array(endpoints.length),next=0,worker=async()=>{for(let index=next++;index<endpoints.length;index=next++){let endpoint=endpoints[index];endpoint!==void 0&&(rows[index]=await read(endpoint))}};return await Promise.all(Array.from({length:Math.min(STATUS_ALL_MAX_IN_FLIGHT,endpoints.length)},worker)),rows}async function endpointStatus(endpoint,options){let located={dir:endpoint.dir,identity:endpoint.identity,endpoint_kind:endpoint.endpoint_kind},paths=hostDaemonDirectoryPaths(endpoint.dir);if(endpoint.socket===null){let verdict2=livenessFields(await judgeEndpointLiveness(paths,void 0)),status=await unaddressableStatus(endpoint.dir),owner2=endpoint.endpoint_kind==="tui"?tuiOwner(status,[]):null;return{...status,socket:null,...located,...verdict2,owner:owner2,stale_old_engine:!1}}let{report,answered:answered2,listing}=await probeHostStatus({socket:endpoint.socket,agentDir:options.agentDir,includeWorkers:options.includeWorkers},{prune:!1,timeoutMs:endpointProbeTimeoutMs(endpoint.endpoint_kind,options.timeoutMs)}),verdict=await judgeEndpointLiveness(paths,answered2===void 0?void 0:answered2.instanceId??null),owner=endpoint.endpoint_kind==="tui"?tuiOwner(report,listing):null,stale=endpoint.endpoint_kind==="rpc_host"&&verdict==="routable"?await staleOldEngine(endpoint.socket,options):!1;return{...report,...located,...livenessFields(verdict),owner,stale_old_engine:stale}}async function staleOldEngine(socket,options){let staleEngine=options.staleEngine??{};return(await judgeStaleEngine(socket,options.agentDir,staleEngine.client??engineBuildIdentity(),staleEngine)).stale}function tuiOwner(status,listing){let row=listing[0];return{pid:status.generations.find(generation=>generation.current)?.pid??null,cwd:row?.cwd??null,session:row===void 0?null:{id:row.id,path:row.session_path,name:row.name}}}function livenessFields(verdict){return verdict==="routable"?{alive:!0,reason:null}:{alive:!1,reason:verdict}}async function unaddressableStatus(dir){let paths=hostDaemonDirectoryPaths(dir),generations=await withHostUnits(await readGenerationRows(paths,{includeDead:!0})),claims=await readClaimRows(paths,generations),current=generations.find(generation=>generation.current);return{reachable:!1,lifecycle:null,pid:null,processStartTime:null,instanceId:null,generation:null,engineVersion:null,capabilities:[],launchProfile:null,runtimeBuildId:null,handover:null,sessions:{total:0,interactive:0,worker:0,retained:0,foreign_attached:0,foreign_retained:0},zombies:null,rss_mb:null,host_rss_mb:null,host_footprint_mb:null,open_fds:null,memory_pressure:null,path_identity_resolver:null,env_keys:[],generations,pointer:current?{state:"current",instanceId:current.instanceId,candidates:[]}:{state:"missing",instanceId:null,candidates:[]},crashes:readHostCrashRecords(dir).filter(isHostCrash).length,shard:null,session_rows:[],claims_live:claims.filter(claim=>claim.live).length,claims:[]}}function hostRequestKeyRoot(request,explicit){return explicit!==void 0?explicit:request.action==="gc"?request.agentDir:rpcKeyRoot({},request.action==="shard_path"?void 0:request.target.agentDir)}var PROBE_TIMEOUT_MS2=1e4;async function runHostRequest(request,options={}){return withRpcKeyRoot(hostRequestKeyRoot(request,options.keyRoot),()=>runHostRequestInKeyRoot(request,options.presenterBootstrap,options.mcpPresenterEnforcement))}async function runHostRequestInKeyRoot(request,presenterBootstrap,mcpPresenterEnforcement){if(request.action==="ensure"||request.action==="handoff"||request.action==="stop"){let{socket,agentDir}=request.target;if(await endpointKindOfSocket(socket,agentDir)==="tui")return refusal("refuse",void 0,{reason:"unsupported_endpoint_kind",socket,endpoint_kind:"tui"})}switch(request.action){case"ensure":return ensureOutcome(request.target,request.spec,request.policy,presenterBootstrap,mcpPresenterEnforcement);case"status":return request.all===!0?statusAllOutcome(request.target,request.includeWorkers):statusOutcome(request.target,request.includeWorkers);case"stop":return stopOutcome(request);case"handoff":return request.handover===void 0?handoffOutcome(request,presenterBootstrap,mcpPresenterEnforcement):idleHandoverOutcome(request.target,request.spec,request.handover,mcpPresenterEnforcement);case"shard_path":return shardPathOutcome(request.kind,request.owner,request.root);case"gc":return{exitCode:HOST_EXIT_OK,payload:{...await gcHostEndpoints(request.agentDir,{staleEngine:{}})}};default:return assertNever2(request)}}async function ensureOutcome(target,spec,policy,presenterBootstrap,mcpPresenterEnforcement){let before=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS2);if(policy==="fallback"){let decision=decideHostAction(decisionClient(),before,"fallback");if(decision.action==="fallback")return refusal("fallback",before,{reason:decision.reason,socket:target.socket})}let ensured;try{ensured=await ensureHost({socket:target.socket,presenterBootstrap,mcpPresenterEnforcement,agentDir:target.agentDir,hostArgs:spec.hostArgs,env:daemonEnvOverrides(process.env,spec.env),policy:spec.policy,upgrade:policy==="upgrade"?"if-engine-differs":"never"})}catch(error){if(!(error instanceof HostEnsureRefusedError))throw error;return refusal("refuse",before,{reason:error.reason,socket:target.socket,...error.detail!==void 0&&{detail:error.detail},...error.holder!==void 0&&{holder:error.holder}})}let host=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS2).finally(ensured.release);return ensured.reused||await recordEnvScope(target,spec),{exitCode:HOST_EXIT_OK,payload:{action:ensureAction(ensured.reused,before,host),...identityPayload(target.socket,ensured.pid,host),...await hostUnitPayload(ensured.pid,host?.instanceId),clientRuntimeBuildId:await clientRuntimeBuildId(spec),reused:ensured.reused}}}function ensureAction(reused,before,after){return reused?"reuse":before!==void 0&&before.instanceId!==after?.instanceId?"handoff":"start"}async function statusOutcome(target,includeWorkers){let status=await readHostStatus({socket:target.socket,agentDir:target.agentDir,includeWorkers});return{exitCode:status.reachable?HOST_EXIT_OK:HOST_EXIT_REFUSED,payload:{...status}}}async function statusAllOutcome(target,includeWorkers){let endpoints=await readAllHostStatus({agentDir:target.agentDir,includeWorkers});return{exitCode:endpoints.some(endpoint=>endpoint.reachable)?HOST_EXIT_OK:HOST_EXIT_REFUSED,payload:{endpoints}}}function shardPathOutcome(kind,owner,root){let key=shardKey(kind,owner);return{exitCode:HOST_EXIT_OK,payload:{kind,key,socket:shardSocketPathForKey(root,kind,key)}}}async function stopOutcome(request){let{target,drain,force,instanceId,waitMs}=request;if(request.expectedGeneration!==void 0){let stale=await staleStopGeneration(target.socket,target.agentDir,request.expectedGeneration);if(stale!==void 0)return refusal("refuse",void 0,{reason:stale.reason,socket:target.socket})}let host=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS2),sessions=await readSessionCounts(target.socket,!0),occupied=sessions.foreign_attached+sessions.foreign_retained>0;if(!drain&&!force&&occupied)return refusal("refuse",host,{reason:"sessions_live",socket:target.socket,sessions});let result=await stopHost({socket:target.socket,agentDir:target.agentDir,drain,force,...request.expectedGeneration!==void 0&&{expectedGeneration:request.expectedGeneration},...instanceId!==void 0&&{instanceId},...waitMs!==void 0&&{waitMs}});return result.action==="refuse"?refusal("refuse",host,{reason:result.reason,socket:target.socket,sessions}):{exitCode:HOST_EXIT_OK,payload:{action:result.action,socket:target.socket,pid:result.pid,..."instanceId"in result&&result.instanceId!==void 0&&{instanceId:result.instanceId},..."exited"in result&&result.exited!==void 0&&{exited:result.exited},sessions}}}async function handoffOutcome(request,presenterBootstrap,mcpPresenterEnforcement){let{target,spec}=request,before=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS2),result=await handoffHost({socket:target.socket,presenterBootstrap,mcpPresenterEnforcement,agentDir:target.agentDir,hostArgs:spec.hostArgs,env:daemonEnvOverrides(process.env,spec.env),policy:spec.policy,...request.allowDowngrade===!0&&{allowDowngrade:!0}});if(result.action==="refuse")return refusal("refuse",before,{reason:upgradeRefusal(result.reason),socket:target.socket,detail:result.detail??result.reason,upgradeable:result.upgradeable});await recordEnvScope(target,spec);let host=await probeProtocolInfo(target.socket,PROBE_TIMEOUT_MS2);return{exitCode:HOST_EXIT_OK,payload:{action:"handoff",...identityPayload(target.socket,result.pid,host),...await hostUnitPayload(result.pid,host?.instanceId),clientRuntimeBuildId:await clientRuntimeBuildId(spec),reused:!1}}}function upgradeRefusal(reason){return reason==="handoff_unsupported"?"upgrade_unsupported":reason}async function recordEnvScope(target,spec){let paths=createHostDaemonPaths({socket:target.socket,agentDir:target.agentDir});await writeDaemonEnvKeys(paths,daemonEnvKeys(process.env,spec.env))}function assertNever2(value){throw new Error(`unreachable host request: ${JSON.stringify(value)}`)}import{resolve as resolve4}from"node:path";function handoverTerms(flags){let when=flags["--when"],operationId=flags["--operation"],ifInstanceId=flags["--if-instance"],generation=flags["--if-generation"],targetRuntimeBuildId=flags["--target-build"];if(when!=="idle")return`Error: "${APP_NAME} host handoff" supports only --when idle.`;if(!operationId||!ifInstanceId||!generation||!targetRuntimeBuildId)return`Error: "${APP_NAME} host handoff --when idle" needs --operation, --if-instance, --if-generation and --target-build.`;let ifGeneration=Number(generation);return!/^\d+$/.test(generation)||!Number.isSafeInteger(ifGeneration)?"Error: --if-generation must be a non-negative integer.":{operationId,ifInstanceId,ifGeneration,targetRuntimeBuildId}}var SUBCOMMANDS=["ensure","status","stop","handoff","shard-path","gc"],POLICIES=["upgrade","fallback","never"];function parseHostArgs(args){let[subcommand,...rest]=args;if(subcommand===void 0||!isSubcommand(subcommand))return`Error: unknown host command "${subcommand??""}".`;let specPath,policy="upgrade",socket,includeWorkers=!1,all=!1,drain=!1,force=!1,expectedGeneration,instanceId,waitMs,json=!1,kind,owner,root,agentDir,keyRoot,presenterBootstrapFd,mcpPresenterEnforcement,allowDowngrade=!1,handover={};for(let index=0;index<rest.length;index++){let flag=rest[index],value=rest[index+1];if(flag==="--mcp-presenter-fd"&&value==="4"&&(subcommand==="ensure"||subcommand==="handoff"))presenterBootstrapFd=4,index++;else if(flag==="--mcp-presenter-enforcement"&&(subcommand==="ensure"||subcommand==="handoff"))mcpPresenterEnforcement=!0;else if(flag==="--rpc-key-root"&&value!==void 0&&!value.startsWith("--"))keyRoot=resolve4(value),index++;else if(flag==="--allow-downgrade"&&subcommand==="handoff")allowDowngrade=!0;else if(flag==="--json")json=!0;else if(flag==="--include-workers")includeWorkers=!0;else if(flag==="--all"&&subcommand==="status")all=!0;else if(flag==="--kind"&&subcommand==="shard-path"&&(value==="p"||value==="i"))kind=value,index++;else if(flag==="--owner"&&subcommand==="shard-path"&&value!==void 0)owner=value,index++;else if(flag==="--root"&&subcommand==="shard-path"&&value!==void 0)root=value,index++;else if(flag==="--agent-dir"&&subcommand==="gc"&&value!==void 0)agentDir=value,index++;else if(subcommand==="handoff"&&value!==void 0&&HANDOVER_FLAGS.has(flag??""))handover[flag??""]=value,index++;else if(flag==="--expected-generation"&&subcommand==="stop"&&value!==void 0){if(expectedGeneration=parseHostStopGeneration(value),expectedGeneration===void 0)return"Error: --expected-generation needs instanceId, generation, pid and processStartTime (null where the platform records none).";index++}else if(flag==="--instance"&&subcommand==="stop"&&value!==void 0)instanceId=value,index++;else if(flag==="--wait-ms"&&subcommand==="stop"&&value!==void 0)waitMs=value,index++;else if(flag==="--drain")drain=!0;else if(flag==="--force")force=!0;else if(flag==="--launch-spec"&&value!==void 0)specPath=value,index++;else if(flag==="--socket"&&value!==void 0)socket=value,index++;else if(flag==="--policy"&&value!==void 0&&isPolicy(value))policy=value,index++;else return`Error: unknown option "${flag}" for "${APP_NAME} host ${subcommand}".`}if(subcommand==="shard-path"&&(kind===void 0||owner===void 0))return`Error: "${APP_NAME} host shard-path" needs --kind <p|i> and --owner <id>.`;if((instanceId!==void 0||waitMs!==void 0)&&!drain)return`Error: "${APP_NAME} host stop" takes --instance and --wait-ms only with --drain.`;let parsedWaitMs=waitMs===void 0?void 0:Number(waitMs);if(expectedGeneration!==void 0&&drain)return"Error: --expected-generation is for a hard stop, not --drain.";if(parsedWaitMs!==void 0&&(!Number.isSafeInteger(parsedWaitMs)||parsedWaitMs<=0))return`Error: "${APP_NAME} host stop --wait-ms" needs a positive whole number of milliseconds.`;let terms=Object.keys(handover).length===0?void 0:handoverTerms(handover);return typeof terms=="string"?terms:{...presenterBootstrapFd===void 0?{}:{presenterBootstrapFd},...mcpPresenterEnforcement===void 0?{}:{mcpPresenterEnforcement},subcommand,...specPath!==void 0&&{specPath},policy,...socket!==void 0&&{socket},includeWorkers,all,drain,force,...expectedGeneration!==void 0&&{expectedGeneration},...instanceId!==void 0&&{instanceId},...parsedWaitMs!==void 0&&{waitMs:parsedWaitMs},json,...kind!==void 0&&{kind},...owner!==void 0&&{owner},...root!==void 0&&{root},...agentDir!==void 0&&{agentDir},...keyRoot!==void 0&&{keyRoot},...terms!==void 0&&{handover:allowDowngrade?{...terms,allowDowngrade}:terms},...allowDowngrade&&{allowDowngrade}}}var HANDOVER_FLAGS=new Set(["--when","--operation","--if-instance","--if-generation","--target-build"]);function isSubcommand(value){return SUBCOMMANDS.includes(value)}function isPolicy(value){return POLICIES.includes(value)}import{writeSync}from"node:fs";function emit(payload){writeSync(1,`${JSON.stringify(payload)}
`)}var USAGE=`usage: ${APP_NAME} host <ensure|status|stop|handoff|shard-path|gc> [options]
ensure [--launch-spec <file>] [--policy upgrade|fallback|never] [--socket <path>]
status [--include-workers] [--all] [--socket <path>] (--all: every endpoint, ignores --socket)
stop [--drain [--instance <id>] [--wait-ms <n>]] [--force] [--expected-generation <json>] [--socket <path>]
handoff [--launch-spec <file>] [--socket <path>] [--allow-downgrade]
[--when idle --operation <id> --if-instance <id> --if-generation <n> --target-build <sha256:...>]
(--when idle: the running host hands over to THIS runtime at its next safe idle point)
(a host on a newer engine is refused older_engine unless --allow-downgrade)
shard-path --kind <p|i> --owner <id> [--root <dir>] [--json] (no host contact)
gc [--agent-dir <dir>] [--json] (removes provably dead endpoints only; ignores --socket)
session <open|close|model|prompt|steer|abort|read|state|list|wait> [...] (see "senpi host session")
--rpc-key-root <dir> endpoint credentials only; keeps this client's profile
--mcp-presenter-enforcement ensure/handoff deployment opt-in; default off for a new host
--mcp-presenter-fd 4 ensure/handoff private enrollment channel; never enrolls on reuse
--json the answer is one JSON line on stdout (always, except shard-path's bare path)`;async function runHostCommand(args){let parsed=parseHostArgs(args);if(typeof parsed=="string")return process.stderr.write(`${parsed}
${USAGE}
`),HOST_EXIT_USAGE;try{let request=await hostRequest(parsed),presenterBootstrap=parsed.presenterBootstrapFd===void 0?void 0:presenterBootstrapStream(parsed.presenterBootstrapFd),outcome=await runHostRequest(request,{keyRoot:parsed.keyRoot,presenterBootstrap,mcpPresenterEnforcement:parsed.mcpPresenterEnforcement}).finally(()=>presenterBootstrap?.destroy());return parsed.subcommand==="shard-path"&&!parsed.json?writeSync2(1,`${String(outcome.payload.socket)}
`):emit(outcome.payload),outcome.exitCode}catch(error){return error instanceof HostLaunchSpecError?(emit({action:"error",reason:error.reason,detail:error.detail}),HOST_EXIT_USAGE):(emit({action:"error",reason:"host_error",detail:error instanceof Error?error.message:String(error)}),HOST_EXIT_ERROR)}}async function hostRequest(parsed){let agentDir=getAgentDir(),target={socket:resolveHostSocket(parsed.socket,agentDir),agentDir};switch(parsed.subcommand){case"ensure":return{action:"ensure",target,spec:await launchSpec(parsed.specPath),policy:parsed.policy};case"status":return{action:"status",target,includeWorkers:parsed.includeWorkers,all:parsed.all};case"stop":return{action:"stop",target,drain:parsed.drain,force:parsed.force,...parsed.expectedGeneration!==void 0&&{expectedGeneration:parsed.expectedGeneration},...parsed.instanceId!==void 0&&{instanceId:parsed.instanceId},...parsed.waitMs!==void 0&&{waitMs:parsed.waitMs}};case"handoff":return{action:"handoff",target,spec:await launchSpec(parsed.specPath),...parsed.handover!==void 0&&{handover:parsed.handover},...parsed.allowDowngrade===!0&&{allowDowngrade:!0}};case"shard-path":return{action:"shard_path",kind:parsed.kind??"p",owner:parsed.owner??"",root:resolve5(parsed.root??join10(agentDir,"rpc","shards"))};case"gc":return{action:"gc",agentDir:resolve5(parsed.agentDir??agentDir)};default:return assertNever3(parsed.subcommand)}}function launchSpec(specPath){return specPath===void 0?DEFAULT_HOST_LAUNCH_SPEC:loadHostLaunchSpec(specPath)}function resolveHostSocket(explicit,agentDir){return explicit??envValue("RPC_SOCKET")??resolve5(agentDir,"rpc","rpc.sock")}function assertNever3(value){throw new Error(`unreachable host subcommand: ${JSON.stringify(value)}`)}export{HostLaunchSpecError,DEFAULT_HOST_LAUNCH_SPEC,loadHostLaunchSpec,parseHostLaunchSpec,isTransientDaemonEnvName,daemonEnvOverrides,daemonEnvKeys,writeDaemonEnvKeys,runAsHostGenerationProcess,PINNED_HOST_CLIENT_CAPABILITIES,EXPECTED_RUNTIME_BUILD_ID_ENV,HostIdleHandover,agentDirMismatch,handoffHost,ensureHost,normalizeWaitItems,wakeSourceItems,waitItemSignature,projectWaitItems,readWaitItems,WakeSourceTracker,isSessionBusySnapshot,isHandoffBusy,readDrainVerdicts,BEGIN_HANDOVER_COMMAND,parseBeginHandover,beginHandoverResponse,handoverRefusal,withHostIdentity,isHostIdle,performIdleHandover,readHostStatus,HOST_EXIT_OK,HOST_EXIT_ERROR,HOST_EXIT_USAGE,HOST_EXIT_REFUSED,HOST_EXIT_FALLBACK,refusal,TUI_PROBE_TIMEOUT_MS,endpointProbeTimeoutMs,classifyEndpointLiveness,readAllHostStatus,runHostRequest,parseHostArgs,emit,runHostCommand,resolveHostSocket};