@code-yeongyu/senpi 2026.10.24-2 → 2026.10.24-4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/dist/bundle/chunks/{args-6T5EQVY3.js → args-JXULI4EH.js} +1 -1
- package/dist/bundle/chunks/{chunk-VUKNGMDT.js → chunk-3LNSLJ7N.js} +1 -1
- package/dist/bundle/chunks/chunk-3VOG6WFU.js +27 -0
- package/dist/bundle/chunks/{chunk-HHYSXDYP.js → chunk-42OY5SZZ.js} +2 -2
- package/dist/bundle/chunks/chunk-7IRLFYNM.js +23 -0
- package/dist/bundle/chunks/{chunk-FIBIVBQK.js → chunk-7UUOGZKR.js} +1 -1
- package/dist/bundle/chunks/chunk-BMYNMUVZ.js +7 -0
- package/dist/bundle/chunks/{chunk-JAXZOEJE.js → chunk-BWA4FVFW.js} +1 -1
- package/dist/bundle/chunks/{chunk-AGQSRWNN.js → chunk-EHQXLHRB.js} +1 -1
- package/dist/bundle/chunks/chunk-EWOEVVQT.js +4 -0
- package/dist/bundle/chunks/{chunk-YJA2B7FQ.js → chunk-FDL4CF6F.js} +1 -1
- package/dist/bundle/chunks/{chunk-RQHK4QZ5.js → chunk-FWXMMMCV.js} +1 -1
- package/dist/bundle/chunks/{chunk-OA5INWHI.js → chunk-GVJ76VQI.js} +102 -42
- package/dist/bundle/chunks/{chunk-HCF5M6NA.js → chunk-GXY5JEI5.js} +1 -1
- package/dist/bundle/chunks/{chunk-VZAYN5SB.js → chunk-HKUXKTFW.js} +1 -1
- package/dist/bundle/chunks/chunk-II22E3CV.js +3 -0
- package/dist/bundle/chunks/{chunk-ONLNXGO3.js → chunk-IUHU5PEC.js} +1 -1
- package/dist/bundle/chunks/{chunk-LR6Z6V54.js → chunk-NQC7MI2G.js} +1 -1
- package/dist/bundle/chunks/{chunk-IELM5U6I.js → chunk-PXKF2RHD.js} +2 -2
- package/dist/bundle/chunks/{chunk-BRXN5R2F.js → chunk-QH2HSCMX.js} +1 -1
- package/dist/bundle/chunks/{chunk-QQSCUEYJ.js → chunk-RHHBXIRN.js} +2 -5
- package/dist/bundle/chunks/chunk-RVYSJBZ7.js +7 -0
- package/dist/bundle/chunks/chunk-SGDOZT6B.js +8 -0
- package/dist/bundle/chunks/{chunk-BZ75DRZB.js → chunk-U67ML6CQ.js} +4 -2
- package/dist/bundle/chunks/{chunk-3N2PQEQV.js → chunk-UT6AJHPK.js} +1 -1
- package/dist/bundle/chunks/{chunk-RAIZG6HA.js → chunk-V3CK2AVC.js} +1 -1
- package/dist/bundle/chunks/{chunk-CZR7C6CY.js → chunk-VOBD6FQG.js} +1 -1
- package/dist/bundle/chunks/{chunk-HRPMLI7O.js → chunk-VRDU425E.js} +2 -2
- package/dist/bundle/chunks/{chunk-OUPD5LWY.js → chunk-XUFUKDKJ.js} +3 -3
- package/dist/bundle/chunks/{chunk-SGATKHO4.js → chunk-Y5OTHMXO.js} +1 -1
- package/dist/bundle/chunks/{chunk-QEQG42HL.js → chunk-ZGAB7WQA.js} +1 -1
- package/dist/bundle/chunks/cli-main-UH3MAREK.js +3 -0
- package/dist/bundle/chunks/{dispatch-KQEGIXQW.js → dispatch-DEP4PEDZ.js} +3 -2
- package/dist/bundle/chunks/{help-fast-path-6PVN7WI5.js → help-fast-path-ZHZGXAUG.js} +1 -1
- package/dist/bundle/chunks/host-command-OQR4RDTM.js +2 -0
- package/dist/bundle/chunks/host-lifecycle-U36U7JTE.js +3 -0
- package/dist/bundle/chunks/host-lifecycle.js +26 -21
- package/dist/bundle/chunks/host-session-command-IGB27ZPJ.js +20 -0
- package/dist/bundle/chunks/{host-socket-request-KKGH3JHV.js → host-socket-request-ZDJGSSZO.js} +1 -1
- package/dist/bundle/chunks/interactive-mode-R5RCSJ2F.js +2 -0
- package/dist/bundle/chunks/{list-tips-BO5RP34W.js → list-tips-CREX4IXZ.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-O5GZQSRL.js → multi-session-host-YZEMYUFY.js} +12 -12
- package/dist/bundle/chunks/{package-manager-cli-LC5GAGTW.js → package-manager-cli-5FOXDKUA.js} +1 -1
- package/dist/bundle/chunks/{role-4G43UDOC.js → role-M2MTVACJ.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-RXMCJJUL.js → rotation-stream-U7YQMC7H.js} +1 -1
- package/dist/bundle/chunks/rpc-mode-6K62CZBW.js +2 -0
- package/dist/bundle/chunks/rpc-monitor-source-OL5KU6NO.js +3 -0
- package/dist/bundle/chunks/{schedule-command-QNCVE4HM.js → schedule-command-XBW4EOG5.js} +1 -1
- package/dist/bundle/chunks/session-control-endpoint-54TMCS7Q.js +3 -0
- package/dist/bundle/chunks/{session-picker-HIC5ZTE6.js → session-picker-P2VUU2MQ.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +437 -368
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/host-supervisor.js +26 -21
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/cli/args.d.ts +2 -0
- package/dist/cli/args.js +27 -0
- package/dist/cli/host-command-args.d.ts +33 -0
- package/dist/cli/host-command-args.js +145 -0
- package/dist/cli/host-command.d.ts +1 -30
- package/dist/cli/host-command.js +5 -137
- package/dist/cli/host-session-command.d.ts +1 -0
- package/dist/cli/host-session-command.js +5 -3
- package/dist/core/agent-session.js +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/index.js +4 -2
- package/dist/core/extensions/builtin/anthropic-subscription/options.js +2 -1
- package/dist/core/extensions/builtin/anthropic-subscription/sdk-boundary.js +9 -2
- package/dist/core/extensions/builtin/anthropic-subscription/session-cwd.d.ts +3 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-cwd.js +9 -0
- package/dist/core/extensions/builtin/anthropic-subscription/settings.d.ts +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/settings.js +3 -1
- package/dist/core/extensions/builtin/anthropic-subscription/stream.js +4 -1
- package/dist/core/extensions/builtin/btw/index.js +4 -1
- package/dist/core/extensions/builtin/compaction/lane-policy.js +3 -1
- package/dist/core/extensions/builtin/look-at/runner.js +1 -0
- package/dist/core/extensions/builtin/mcp/connection-types.d.ts +2 -0
- package/dist/core/extensions/builtin/mcp/connection.js +3 -0
- package/dist/core/extensions/builtin/mcp/elicitation.d.ts +5 -2
- package/dist/core/extensions/builtin/mcp/elicitation.js +57 -11
- package/dist/core/extensions/builtin/mcp/index.js +1 -1
- package/dist/core/extensions/builtin/mcp/modern/dispatch.js +6 -9
- package/dist/core/extensions/builtin/mcp/service-connection.d.ts +1 -0
- package/dist/core/extensions/builtin/mcp/service-connection.js +1 -0
- package/dist/core/extensions/builtin/mcp/service.js +1 -0
- package/dist/core/extensions/builtin/mcp/transport-sdk.d.ts +1 -0
- package/dist/core/extensions/builtin/mcp/transport-sdk.js +5 -5
- package/dist/core/extensions/builtin/mcp/transport.d.ts +1 -0
- package/dist/core/extensions/builtin/mcp/transport.js +1 -0
- package/dist/core/extensions/builtin/prompt-preset/contract.js +6 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3-1.d.ts +3 -0
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3-1.js +93 -0
- package/dist/core/extensions/builtin/prompt-preset/matchers.d.ts +2 -0
- package/dist/core/extensions/builtin/prompt-preset/matchers.js +9 -0
- package/dist/core/extensions/builtin/prompt-preset/presets.js +3 -0
- package/dist/core/extensions/builtin/prompt-preset/settings.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/settings.js +1 -0
- package/dist/core/extensions/builtin/terminal/rpc-monitor-observer.d.ts +2 -1
- package/dist/core/extensions/builtin/terminal/rpc-monitor-observer.js +12 -4
- package/dist/core/external-admission.d.ts +4 -1
- package/dist/core/external-admission.js +18 -2
- package/dist/core/lifecycle-session-binding.js +20 -0
- package/dist/core/sdk.js +1 -0
- package/dist/core/session-spawned-by.d.ts +4 -0
- package/dist/core/session-spawned-by.js +16 -0
- package/dist/main.js +7 -2
- package/dist/modes/rpc/host-admission-proxy.d.ts +2 -1
- package/dist/modes/rpc/host-admission-proxy.js +10 -9
- package/dist/modes/rpc/host-cli-entry.d.ts +2 -0
- package/dist/modes/rpc/host-cli-entry.js +13 -1
- package/dist/modes/rpc/host-ensure-client.d.ts +5 -1
- package/dist/modes/rpc/host-ensure-client.js +8 -0
- package/dist/modes/rpc/host-ensure-types.d.ts +1 -0
- package/dist/modes/rpc/host-ensure.js +6 -11
- package/dist/modes/rpc/host-gc-pass.js +3 -0
- package/dist/modes/rpc/host-gc.js +3 -0
- package/dist/modes/rpc/host-internal-transport.d.ts +16 -5
- package/dist/modes/rpc/host-internal-transport.js +40 -9
- package/dist/modes/rpc/host-lifecycle-proxy.d.ts +4 -8
- package/dist/modes/rpc/host-lifecycle-proxy.js +9 -21
- package/dist/modes/rpc/host-lifecycle-shutdown.d.ts +2 -0
- package/dist/modes/rpc/host-lifecycle-shutdown.js +3 -0
- package/dist/modes/rpc/host-lifecycle.js +9 -16
- package/dist/modes/rpc/host-observe-request.js +1 -1
- package/dist/modes/rpc/host-probe.d.ts +8 -6
- package/dist/modes/rpc/host-probe.js +13 -13
- package/dist/modes/rpc/host-request-key-root.d.ts +8 -0
- package/dist/modes/rpc/host-request-key-root.js +14 -0
- package/dist/modes/rpc/host-runner.d.ts +3 -1
- package/dist/modes/rpc/host-runner.js +6 -1
- package/dist/modes/rpc/host-socket-bind.d.ts +6 -0
- package/dist/modes/rpc/host-socket-bind.js +42 -0
- package/dist/modes/rpc/host-socket-request.d.ts +3 -2
- package/dist/modes/rpc/host-socket-request.js +55 -10
- package/dist/modes/rpc/host-status.d.ts +3 -2
- package/dist/modes/rpc/host-status.js +5 -0
- package/dist/modes/rpc/host-supervisor-log.d.ts +1 -0
- package/dist/modes/rpc/host-supervisor-log.js +3 -0
- package/dist/modes/rpc/host-watchdog.d.ts +8 -1
- package/dist/modes/rpc/host-watchdog.js +37 -12
- package/dist/modes/rpc/internal-channel.js +14 -14
- package/dist/modes/rpc/multi-session-host.js +18 -46
- package/dist/modes/rpc/rpc-auth-client.d.ts +13 -0
- package/dist/modes/rpc/rpc-auth-client.js +142 -0
- package/dist/modes/rpc/rpc-auth-proof.d.ts +12 -0
- package/dist/modes/rpc/rpc-auth-proof.js +27 -0
- package/dist/modes/rpc/rpc-client-socket.d.ts +5 -0
- package/dist/modes/rpc/rpc-client-socket.js +30 -0
- package/dist/modes/rpc/rpc-client.d.ts +2 -0
- package/dist/modes/rpc/rpc-client.js +2 -24
- package/dist/modes/rpc/rpc-host-command-types.d.ts +4 -0
- package/dist/modes/rpc/rpc-protocol-info-types.d.ts +6 -0
- package/dist/modes/rpc/rpc-public-auth.d.ts +41 -0
- package/dist/modes/rpc/rpc-public-auth.js +237 -0
- package/dist/modes/rpc/rpc-public-key.d.ts +28 -0
- package/dist/modes/rpc/rpc-public-key.js +193 -0
- package/dist/modes/rpc/session-router-open-profile.js +2 -10
- package/dist/modes/rpc/socket-ownership.d.ts +7 -0
- package/dist/modes/rpc/socket-ownership.js +17 -0
- package/docs/rpc.md +108 -2
- package/docs/settings.md +1 -1
- package/docs/usage.md +14 -0
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-3474DPZK.js +0 -2
- package/dist/bundle/chunks/chunk-64CFJHKT.js +0 -7
- package/dist/bundle/chunks/chunk-B6NJHBLH.js +0 -21
- package/dist/bundle/chunks/chunk-HZTQHE5O.js +0 -26
- package/dist/bundle/chunks/chunk-IBDADH5Z.js +0 -4
- package/dist/bundle/chunks/chunk-OJZD7CO7.js +0 -8
- package/dist/bundle/chunks/cli-main-4JNPG6LB.js +0 -3
- package/dist/bundle/chunks/host-command-I3ZMWQQ3.js +0 -2
- package/dist/bundle/chunks/host-lifecycle-QEO422VW.js +0 -3
- package/dist/bundle/chunks/host-session-command-INULKX6E.js +0 -20
- package/dist/bundle/chunks/interactive-mode-SYWJVPKK.js +0 -2
- package/dist/bundle/chunks/rpc-mode-JMCYSP4P.js +0 -2
- package/dist/bundle/chunks/rpc-monitor-source-34AQDTZ6.js +0 -3
- package/dist/bundle/chunks/session-control-endpoint-IW5X56WN.js +0 -3
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{CHILD_KILL_EXIT_TIMEOUT_MS,CHILD_STALLED_STOP_MAX_MS_ENV,CHILD_STOP_TIMEOUT_MS,DEFAULT_HANDOFF_GRACE_MS,HANDOFF_GRACE_MS_ENV,IdleExitDecider,STOP_STALL_EVIDENCE_MAX_AGE_MS,acquireOwnershipSafeLock,childStalledStopMaxMs,clearStopProgress,consumeStopIntent,errorMessage,hostLoopStalled,layeredSupervisorIntent,parseIdleExitMs,readStopIntent,recentStall,releaseGeneration,resolveHostPolicy,supervisorLog,watchDrainRequest,writeDrainRequest,writeDrainWatch,writeHostReady,writeStderrLine,writeStopIntent,writeStopProgress}from"./chunk-XUFUKDKJ.js";import{HOST_DAEMON_DIR_ENV,createHostDaemonPaths,generationPaths,hostOwnerGone,readHostOwner,sameHostOwner,writeJsonAtomic}from"./chunk-RHHBXIRN.js";import{require_signal_exit}from"./chunk-U3VOXCGP.js";import{HOST_INSTANCE_ID_ENV,MAX_RPC_LINE_CHARACTERS,OBSERVE_REQUEST_FIELD,RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RpcPublicEndpoint,attachJsonlLineReader,authRecord,isObservingRequest,requestOriginHostInstance,rpcAuthProof,rpcProofMatches,serializeJsonLine}from"./chunk-RVYSJBZ7.js";import{MAX_SOCKET_PATH_BYTES,PUBLIC_SOCKET_IDENTITY_FILE,adoptPublicSocket,classifyEndpointOwnership,shieldSocketDuringClose,socketEntryListenerState,statSocketIdentity,unlinkOwnedSocket,writeSocketIdentityFile}from"./chunk-VRDU425E.js";import{SOCKET_HANDSHAKE_TIMEOUT_MS,SOCKET_SECRET_FILE_ENV,authenticateSocket,createSocketSecret,ensureSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{DISPLAY_VERSION,VERSION,brandEnvNames,envValue,getAgentDir,isBunBinary,isBundledNode}from"./chunk-7YO7VQZW.js";import{processIsLive,processStartTimeMs,readProcessIdentity,readProcessStartTime,sameProcessStartMs,waitForStartTime}from"./chunk-7ASLQ243.js";import{__toESM}from"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{join as join6}from"node:path";var HostAdmission=class{constructor(info){this.stopped=!1,this.listeners=new Set,this.replies=Promise.resolve(),this.info=info}get stopping(){return this.stopped}protocol(){return{...this.info,lifecycle:this.stopped?"stopping":"ready"}}observe(info){this.info=info}stop(){this.stopped||(this.stopped=!0,this.replies=Promise.all([...this.listeners].map(listener=>listener())).then(()=>{}))}async flush(){let timer;try{await Promise.race([this.replies,new Promise(resolve2=>{timer=setTimeout(resolve2,2e3)})])}finally{clearTimeout(timer)}}onStop(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}};function hostStoppingResponse(id,command,admission){return{...typeof id=="string"?{id}:{},type:"response",command,success:!1,error:"host_stopping",errorCode:"host_stopping",errorData:{instanceId:admission.protocol().instanceId}}}var import_signal_exit=__toESM(require_signal_exit(),1);import{appendFileSync,mkdirSync,readdirSync,readFileSync,renameSync,rmSync,statSync,utimesSync,writeFileSync}from"node:fs";import{join}from"node:path";var PROCESS_CRASH_RECORD_LIMIT=50,PROCESS_MARKER_HEARTBEAT_MS=6e4,FILE_MODE=384,DIR_MODE=448,MARKER_SUFFIX=".json";function processCrashPaths(agentDir){let dir=join(agentDir,"process-crashes");return{dir,liveDir:join(dir,"live"),recordsFile:join(dir,"crashes.jsonl")}}function crashingRuntimeVersions(){return{...process.versions.bun===void 0?{}:{bunVersion:process.versions.bun},senpiVersion:VERSION,...DISPLAY_VERSION===VERSION?{}:{productVersion:DISPLAY_VERSION}}}function recordProcessLifetime(agentDir,kind,options){return sweepDeadProcessMarkers(agentDir,options),options.supervised?()=>{}:installProcessLifetimeMarker(agentDir,kind,options)}function installProcessLifetimeMarker(agentDir,kind,options={}){let pid=options.pid??process.pid,now=options.now??Date.now,file=join(processCrashPaths(agentDir).liveDir,`${pid}${MARKER_SUFFIX}`),marker={kind,pid,startedAt:now(),...crashingRuntimeVersions()};try{mkdirSync(processCrashPaths(agentDir).liveDir,{recursive:!0,mode:DIR_MODE}),writeFileSync(file,`${JSON.stringify(marker)}
|
|
3
|
+
`,{mode:FILE_MODE})}catch{return()=>{}}let heartbeat=setInterval(()=>{try{let at=new Date(now());utimesSync(file,at,at)}catch{}},options.heartbeatMs??PROCESS_MARKER_HEARTBEAT_MS);heartbeat.unref();let disposed=!1,dispose=()=>{disposed||(disposed=!0,clearInterval(heartbeat),process.off("exit",onProcessExit),removeSignalHook(),rmSync(file,{force:!0}))},onProcessExit=()=>{try{dispose()}catch{}};process.on("exit",onProcessExit);let removeSignalHook=(0,import_signal_exit.default)(onProcessExit);return dispose}function sweepDeadProcessMarkers(agentDir,options={}){let paths=processCrashPaths(agentDir),selfPid=options.pid??process.pid,isAlive=options.isAlive??isProcessAlive,names;try{names=readdirSync(paths.liveDir)}catch{return 0}let recorded=0;for(let name of names){if(!name.endsWith(MARKER_SUFFIX))continue;let pid=Number(name.slice(0,-MARKER_SUFFIX.length));if(!Number.isSafeInteger(pid)||pid<=0||pid===selfPid||isAlive(pid))continue;let claimed=join(paths.liveDir,`${name}.${selfPid}.sweep`);try{renameSync(join(paths.liveDir,name),claimed)}catch{continue}try{let record2=crashRecordFromMarker(readFileSync(claimed,"utf8"),statSync(claimed).mtimeMs);record2!==void 0&&(appendProcessCrashRecord(paths,record2),recorded+=1)}catch{}finally{rmSync(claimed,{force:!0})}}return recorded}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function crashRecordFromMarker(raw,lastHeartbeatMs){let value=JSON.parse(raw);if(typeof value!="object"||value===null)return;let kind=Reflect.get(value,"kind"),startedAt=Reflect.get(value,"startedAt"),senpiVersion=Reflect.get(value,"senpiVersion"),bunVersion=Reflect.get(value,"bunVersion"),productVersion=Reflect.get(value,"productVersion");if(!(typeof kind!="string"||typeof startedAt!="number"||typeof senpiVersion!="string"))return{at:new Date(lastHeartbeatMs).toISOString(),kind,detection:"unclean_exit",uptimeMs:Math.max(0,Math.round(lastHeartbeatMs-startedAt)),...typeof bunVersion=="string"?{bunVersion}:{},senpiVersion,...typeof productVersion=="string"?{productVersion}:{}}}function appendProcessCrashRecord(paths,record2){mkdirSync(paths.dir,{recursive:!0,mode:DIR_MODE}),appendFileSync(paths.recordsFile,`${JSON.stringify(record2)}
|
|
4
|
+
`,{mode:FILE_MODE});let records=readProcessCrashRecordsFrom(paths.recordsFile);if(records.length<=PROCESS_CRASH_RECORD_LIMIT)return;let kept=records.slice(records.length-PROCESS_CRASH_RECORD_LIMIT);writeFileSync(paths.recordsFile,`${kept.join(`
|
|
5
|
+
`)}
|
|
6
|
+
`,{mode:FILE_MODE})}function readProcessCrashRecordsFrom(file){return readFileSync(file,"utf8").split(`
|
|
7
|
+
`).filter(line=>line.trim()!=="")}import{appendFileSync as appendFileSync2,mkdirSync as mkdirSync2,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join2}from"node:path";var HOST_CRASH_RECORD_LIMIT=50,CRASH_RECORD_FILE_MODE=384,TERMINAL_RECORD_LOCK_WAIT_MS=500;function hostCrashRecordFile(daemonDir){return join2(daemonDir,"crashes.jsonl")}function isHostCrash(record2){return record2.kind!=="rpc-host-watchdog"&&record2.detection!=="engine_stop"}function recordHostCrash(daemonDir,record2){try{mkdirSync2(daemonDir,{recursive:!0,mode:448}),appendFileSync2(hostCrashRecordFile(daemonDir),`${JSON.stringify(record2)}
|
|
8
|
+
`,{mode:CRASH_RECORD_FILE_MODE}),pruneHostCrashRecords(daemonDir)}catch{}}async function recordTerminalHostRecord(daemonDir,record2){let release=await acquireRecordLock(daemonDir);try{(!(record2.generation!==void 0&&readHostCrashRecords(daemonDir).some(existing=>existing.kind==="rpc-host"&&existing.generation===record2.generation))||release===void 0)&&recordHostCrash(daemonDir,{...record2,kind:"rpc-host"})}finally{await release?.().catch(()=>{})}}async function acquireRecordLock(daemonDir){try{return mkdirSync2(daemonDir,{recursive:!0,mode:448}),await acquireOwnershipSafeLock(join2(daemonDir,"crashes.lock"),{retries:{retries:Math.ceil(TERMINAL_RECORD_LOCK_WAIT_MS/50),minTimeout:20,maxTimeout:50}})}catch{return}}function readHostCrashRecords(daemonDir){let raw;try{raw=readFileSync2(hostCrashRecordFile(daemonDir),"utf8")}catch{return[]}let records=[];for(let line of raw.split(`
|
|
9
|
+
`))if(line.trim()!=="")try{let value=JSON.parse(line);typeof value=="object"&&value!==null&&typeof Reflect.get(value,"at")=="string"&&records.push(value)}catch{}return records}function pruneHostCrashRecords(daemonDir){let records=readHostCrashRecords(daemonDir);if(records.length<=HOST_CRASH_RECORD_LIMIT)return;let kept=records.slice(records.length-HOST_CRASH_RECORD_LIMIT);writeFileSync2(hostCrashRecordFile(daemonDir),`${kept.map(r=>JSON.stringify(r)).join(`
|
|
10
|
+
`)}
|
|
11
|
+
`,{mode:CRASH_RECORD_FILE_MODE})}function classifyChildExit(code,signal){return code===0&&signal===null?{reason:"rpc host exited on its own idle policy",exitCode:0}:{reason:`rpc host process exited unexpectedly (${code??signal})`,exitCode:1}}async function noteChildExit(context){let now=context.now??Date.now(),intent=await consumeStopIntent(context.generation,now).catch(()=>{}),outcome=describeExit(context,intent);if(outcome===void 0)return;let stall=await recentStall(context.generation,now,STOP_STALL_EVIDENCE_MAX_AGE_MS).catch(()=>{});await recordTerminalHostRecord(context.daemonDir,{at:new Date(now).toISOString(),...context.signal===null?{code:context.code??void 0}:{signal:context.signal},uptimeMs:Math.max(0,now-context.childStartedAt),kind:"rpc-host",generation:context.instanceId,...outcome,...stall?{stall:{driftMs:stall.driftMs,at:stall.at,attributedSessionId:stall.sessionId}}:{},...crashingRuntimeVersions()}).catch(()=>{})}function describeExit(context,intent){return intent!==void 0?{detection:"engine_stop",sender:intent.sender,...intent.chain?{chain:intent.chain}:{},reason:intent.reason,stopIntent:!0}:context.shutdown!==void 0?{detection:"engine_stop",sender:context.shutdown.supervisor,reason:context.shutdown.reason,stopIntent:!1}:classifyChildExit(context.code,context.signal).exitCode===0?void 0:{detection:context.signal===null||SELF_INFLICTED_SIGNALS.has(context.signal)?"supervisor":"external",stopIntent:!1}}var SELF_INFLICTED_SIGNALS=new Set(["SIGSEGV","SIGBUS","SIGABRT","SIGILL","SIGFPE","SIGTRAP","SIGSYS"]);async function noteEscalatedStop(daemonDir,instanceId,intent,now=Date.now()){await recordTerminalHostRecord(daemonDir,{at:new Date(now).toISOString(),signal:"SIGKILL",kind:"rpc-host",generation:instanceId,detection:"engine_stop",sender:intent.sender,...intent.chain?{chain:intent.chain}:{},reason:`${intent.reason}; supervisor_escalated`,stopIntent:!0}).catch(()=>{})}function hostCrashCleanupPaths(targets){let publicEntry=targets.platform==="win32"?[targets.publicSocket]:[];return targets.successor?publicEntry:[targets.generationPidFile,targets.settingsFile,...publicEntry,targets.pointerFile]}import{existsSync,readFileSync as readFileSync3,realpathSync}from"node:fs";import{access,readFile}from"node:fs/promises";import{dirname,resolve}from"node:path";import{fileURLToPath}from"node:url";function isCliModuleEntry(moduleUrl){let entry=process.argv[1];if(!entry)return!1;try{return fileURLToPath(moduleUrl)===realpathSync(entry)}catch{return!1}}function resolveCliMainPath(modulePath=fileURLToPath(import.meta.url),bundled=isBundledNode){let declared=bundled?resolveDeclaredCliEntry(modulePath):void 0;if(declared!==void 0)return declared;let extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve(dirname(modulePath),"..","..",`cli-main${extension}`);return existsSync(unbundled)?unbundled:resolveDeclaredCliEntry(modulePath)??unbundled}function resolveDeclaredCliEntry(modulePath){let dir=dirname(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve(dir,"package.json");if(existsSync(manifestPath)){try{let declared=JSON.parse(readFileSync3(manifestPath,"utf8")).bin,candidates=typeof declared=="string"?[declared]:Object.values(declared??{});for(let candidate of candidates){let entry=resolve(dir,candidate);if(existsSync(entry))return entry}}catch{}return}let parent=dirname(dir);if(parent===dir)return;dir=parent}}var existsAsync=path=>access(path).then(()=>!0,()=>!1);async function resolveCliMainPathAsync(modulePath=fileURLToPath(import.meta.url),bundled=isBundledNode){let declared=bundled?await resolveDeclaredCliEntryAsync(modulePath):void 0;if(declared!==void 0)return declared;let extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve(dirname(modulePath),"..","..",`cli-main${extension}`);return await existsAsync(unbundled)?unbundled:await resolveDeclaredCliEntryAsync(modulePath)??unbundled}async function resolveDeclaredCliEntryAsync(modulePath){let dir=dirname(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve(dir,"package.json");if(await existsAsync(manifestPath)){try{let declaredBin=JSON.parse(await readFile(manifestPath,"utf8")).bin,candidates=typeof declaredBin=="string"?[declaredBin]:Object.values(declaredBin??{});for(let candidate of candidates){let entry=resolve(dir,candidate);if(await existsAsync(entry))return entry}}catch{}return}let parent=dirname(dir);if(parent===dir)return;dir=parent}}import{watch}from"node:fs";import{createConnection,Socket}from"node:net";var MAX_CLASSIFIED_LINE_BYTES=64*1024,NEWLINE=10,ClientOccupancy=class{constructor(onAttach,ownInstance){this.clients=new Set,this.observers=new Set,this.attached=new Set,this.dependents=new Set,this.closed=!1,this.onAttach=onAttach,this.ownInstance=ownInstance}get attachedCount(){return this.attached.size}get unclassifiedCount(){return this.clients.size-this.observers.size-this.attached.size-this.dependents.size}admit(client){if(this.closed)return client.destroy(),!1;this.clients.add(client);let pending=Buffer.alloc(0),attach=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.attached.add(client),this.onAttach()},depend=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.dependents.add(client)},classify=chunk=>{pending=Buffer.concat([pending,chunk]);for(let newline=pending.indexOf(NEWLINE);newline!==-1;newline=pending.indexOf(NEWLINE)){let line=pending.subarray(0,newline).toString("utf8");if(pending=pending.subarray(newline+1),!isObservingRequest(line)){this.ownInstance!==void 0&&requestOriginHostInstance(line)===this.ownInstance?depend():attach();return}this.observers.add(client)}pending.length>MAX_CLASSIFIED_LINE_BYTES&&attach()};return client.on("data",classify),!0}release(client){let unclassified=this.clients.has(client)&&!this.observers.has(client)&&!this.attached.has(client)&&!this.dependents.has(client);return this.clients.delete(client),this.observers.delete(client),this.attached.delete(client),this.dependents.delete(client),unclassified}destroyAll(){this.closed=!0;for(let client of this.clients)client.destroy()}};var SessionRunActivity=class{#running=new Set;observe(line){let event=parseHostEvent(line);if(event===void 0)return!1;if(event.type==="agent_start")this.#running.add(event.sessionId);else if(event.type==="agent_settled"||event.type==="session_closed")this.#running.delete(event.sessionId);else return!1;return!0}get busySessions(){return this.#running.size}};function parseHostEvent(line){let event;try{event=JSON.parse(line)}catch{return}if(typeof event!="object"||event===null)return;let{type,sessionId}=event;return typeof sessionId=="string"?{type,sessionId}:void 0}import{randomBytes}from"node:crypto";import{hkdfSync}from"node:crypto";import{Duplex}from"node:stream";import{createCipheriv,createDecipheriv}from"node:crypto";var INTERNAL_RECORD_MAX=64*1024,RECORD_LIMIT=1n<<32n,InternalRecordCipher=class{constructor(key,direction,counter=0n){this.key=key,this.direction=direction,this.counter=counter}parameters(){if(this.counter<0n||this.counter>=RECORD_LIMIT)throw new Error("internal_record_counter_exhausted");let count=Buffer.alloc(8);return count.writeBigUInt64BE(this.counter),{nonce:Buffer.concat([Buffer.alloc(4),count]),aad:Buffer.concat([Buffer.from(this.direction),count])}}seal(plaintext){if(plaintext.length<1||plaintext.length>INTERNAL_RECORD_MAX)throw new Error("internal_record_length");let{nonce:nonce2,aad}=this.parameters(),cipher=createCipheriv("aes-256-gcm",this.key,nonce2);cipher.setAAD(aad);let body=Buffer.concat([cipher.update(plaintext),cipher.final(),cipher.getAuthTag()]),length=Buffer.alloc(4);return length.writeUInt32BE(body.length),this.counter++,Buffer.concat([length,body])}open(body){if(body.length<17||body.length>INTERNAL_RECORD_MAX+16)throw new Error("internal_record_length");let{nonce:nonce2,aad}=this.parameters(),decipher=createDecipheriv("aes-256-gcm",this.key,nonce2);decipher.setAAD(aad),decipher.setAuthTag(body.subarray(-16));let plaintext=decipher.update(body.subarray(0,-16)),final=decipher.final();return this.counter++,Buffer.concat([plaintext,final])}};function createInternalRecordStream(wire,key,clientNonce,serverNonce,role){let salt=Buffer.concat([clientNonce,serverNonce]),cipher=direction=>new InternalRecordCipher(Buffer.from(hkdfSync("sha256",key,salt,`senpi-rpc-internal ${direction}`,32)),direction);return new InternalRecordStream(wire,cipher(role==="client"?"c2s":"s2c"),cipher(role==="client"?"s2c":"c2s"))}var InternalRecordStream=class extends Duplex{constructor(wire,sender,receiver){super(),this.header=Buffer.alloc(4),this.headerUsed=0,this.bodyUsed=0,this.offset=0,this.wireDone=!1,this.wireClosed=!1,this.ended=!1,this.wire=wire,this.sender=sender,this.receiver=receiver,this.once("error",error=>{error.message.startsWith("internal_record")&&process.stderr.write(`senpi rpc: internal hop closed: ${error.message}
|
|
12
|
+
`)}),this.on("error",()=>{}),wire.on("data",chunk=>{wire.pause(),this.pending=chunk,this.offset=0,this.consume()}),wire.once("end",()=>{this.wireDone=!0,this.pending===void 0&&this.finish()}),wire.once("error",error=>this.destroy(error)),wire.once("close",()=>{this.wireDone=!0,this.wireClosed=!0,this.ended&&this.readableEnded?this.destroy():this.pending===void 0&&this.finish()}),this.once("end",()=>{this.wireClosed&&this.destroy()})}finish(){this.ended||(this.ended=!0,this.headerUsed!==0||this.body!==void 0?this.destroy(new Error("internal_record_truncated")):this.push(null))}consume(){try{let chunk=this.pending;if(!chunk)return;for(;this.offset<chunk.length;){if(!this.body){let n2=Math.min(4-this.headerUsed,chunk.length-this.offset);if(chunk.copy(this.header,this.headerUsed,this.offset,this.offset+n2),this.headerUsed+=n2,this.offset+=n2,this.headerUsed!==4)break;let length=this.header.readUInt32BE();if(length<17||length>INTERNAL_RECORD_MAX+16)throw new Error("internal_record_length");this.headerUsed=0,this.body=Buffer.alloc(length)}let n=Math.min(this.body.length-this.bodyUsed,chunk.length-this.offset);if(chunk.copy(this.body,this.bodyUsed,this.offset,this.offset+n),this.bodyUsed+=n,this.offset+=n,this.bodyUsed===this.body.length){let plaintext=this.receiver.open(this.body);if(this.body=void 0,this.bodyUsed=0,!this.push(plaintext)){this.offset===chunk.length&&(this.pending=void 0,this.wireDone&&this.finish());return}}}this.pending=void 0,this.wireDone?this.finish():this.wire.resume()}catch(cause){this.destroy(cause instanceof Error&&cause.message.startsWith("internal_record")?cause:new Error("internal_record_unverified",{cause}))}}_read(){this.pending?this.consume():this.wire.resume()}_write(chunk,_encoding,callback){let offset=0,next=error=>{if(error){callback(error);return}if(this.destroyed){callback(new Error("internal_hop_lost"));return}if(offset===chunk.length){callback();return}try{let end=Math.min(chunk.length,offset+INTERNAL_RECORD_MAX),record2=this.sender.seal(chunk.subarray(offset,end));offset=end,this.wire.write(record2,next)}catch(cause){callback(cause instanceof Error?cause:new Error("internal_record_invalid"))}};next()}_final(callback){this.wire.end(callback)}_destroy(error,callback){this.wire.destroy(),callback(error)}};var INTERNAL_LAUNCH_ID="internal";function proof(key,label,first,second){return rpcAuthProof(key,label,INTERNAL_LAUNCH_ID,first,second)}function matches(actual,expected){return rpcProofMatches(expected,actual)}function object(value){if(!isObject(value))throw new Error("auth_failed");return value}function isObject(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function nonce(value){if(typeof value!="string"||!RPC_AUTH_HEX.test(value))throw new Error("auth_failed");return value}var HOST_PRE_AUTH_BUDGET={maxBytes:8192,timeoutMs:2e3};async function handshake(socket,budget,run){let readBytes=0,ended=!1,rejectPending,fail=error=>{ended=!0,rejectPending?.(error),socket.destroy()},timer=budget.timeoutMs===void 0?void 0:setTimeout(()=>fail(new Error("internal_auth_timeout")),budget.timeoutMs);timer?.unref();let onError=error=>fail(error),onClose=()=>fail(new Error("internal_hop_lost"));socket.on("error",onError),socket.once("close",onClose);let read=()=>new Promise((resolve2,reject)=>{if(ended)return reject(new Error("internal_hop_lost"));let buffer=Buffer.alloc(0);rejectPending=cause=>{socket.off("data",data),reject(cause)};let data=chunk=>{let newline=chunk.indexOf(10),used=newline===-1?chunk.length:newline+1;if(readBytes+=used,readBytes>budget.maxBytes)return fail(new Error("internal_auth_oversized"));if(buffer=Buffer.concat([buffer,chunk.subarray(0,used)]),newline!==-1){socket.pause(),socket.off("data",data),rejectPending=void 0,used<chunk.length&&socket.unshift(chunk.subarray(used));try{resolve2(object(JSON.parse(buffer.toString("utf8"))))}catch{reject(new Error("auth_failed"))}}};socket.on("data",data),socket.resume()});try{return await run(read,frame=>new Promise((resolve2,reject)=>{socket.write(`${JSON.stringify(frame)}
|
|
13
|
+
`,error=>error?reject(error):resolve2())}))}catch(cause){throw socket.destroy(),cause}finally{timer&&clearTimeout(timer),socket.off("error",onError),socket.off("close",onClose)}}function connectInternalConnection(socket,key,options={}){return handshake(socket,{maxBytes:MAX_RPC_LINE_CHARACTERS,timeoutMs:options.timeoutMs},async(read,send)=>{let clientNonce=randomBytes(32).toString("hex"),[response]=await Promise.all([read(),send({id:"internal-protocol",type:"get_protocol_info",observe:!0,auth:{client_nonce:clientNonce}})]),data=response.data;if(!isObject(data)||!isObject(data.auth))throw new Error("host_identity_unproven");let auth=data.auth,serverNonce=nonce(auth.server_nonce);if(response.id!=="internal-protocol"||response.success!==!0||auth.launch_id!==INTERNAL_LAUNCH_ID||!matches(auth.server_proof,proof(key,"server",clientNonce,serverNonce)))throw new Error("host_identity_unproven");let[result]=await Promise.all([read(),send({id:"internal-auth",type:"authenticate",client_proof:proof(key,"client",serverNonce,clientNonce)})]);if(result.id!=="internal-auth"||result.command!=="authenticate"||result.success!==!0)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"client")})}function acceptInternalConnection(socket,key,protocol={}){return handshake(socket,HOST_PRE_AUTH_BUDGET,async(read,send)=>{let refuse=async frame2=>{throw await send({id:frame2.id,type:"response",command:frame2.type,success:!1,error:"auth_required",errorCode:"auth_required"}),new Error("auth_required")},first=await read(),offered=isObject(first.auth)?first.auth.client_nonce:void 0;if(first.type!=="get_protocol_info"||typeof offered!="string"||!RPC_AUTH_HEX.test(offered))return refuse(first);let clientNonce=offered,serverNonce=randomBytes(32).toString("hex"),[frame]=await Promise.all([read(),send({id:first.id,type:"response",command:first.type,success:!0,data:{...protocol,capabilities:[...Array.isArray(protocol.capabilities)?protocol.capabilities:[],"socket_auth"],auth:{launch_id:INTERNAL_LAUNCH_ID,server_nonce:serverNonce,server_proof:proof(key,"server",clientNonce,serverNonce)}}})]);if(frame.type!=="authenticate")return refuse(frame);let valid=matches(frame.client_proof,proof(key,"client",serverNonce,clientNonce));if(await send({id:frame.id,type:"response",command:"authenticate",success:valid,...valid?{}:{error:"auth_failed",errorCode:"auth_failed"}}),!valid)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"server")})}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}var INTERNAL_OBSERVER_HANDSHAKE_MS=5e3,SupervisorActivity=class{constructor(options){this.runs=new SessionRunActivity,this.options=options,this.decider=new IdleExitDecider(options.idleExitMs),this.clients=new ClientOccupancy(()=>this.refresh(),options.instanceId),this.observerLink=createObserverLink({open:()=>this.connectObserver(),settled:options.settled,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}})}current(){return{connections:this.clients.attachedCount,activeTurns:activeTurnsForIdleDecision({healthy:this.observerLink.healthy(),unhealthySince:this.observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:this.decider.idleExitMs,observedBusy:this.runs.busySessions})}}refresh(){let current=this.current();return(current.connections>0||current.activeTurns>0||this.clients.unclassifiedCount>0)&&this.options.onActivity?.(),this.decider.update(current)}quiescent(){return this.observerLink.healthy()&&this.runs.busySessions===0&&this.clients.attachedCount===0&&this.clients.unclassifiedCount===0}openObserver(){return this.observerLink.open()}stopObserver(){this.observerLink.stop(),this.observerSocket?.destroy()}async connectObserver(){let secret=this.options.internalSecret,next=createConnection(resolveSocketTransportAddress(this.options.internalSocket,process.platform,secret));secret&&sendSocketHandshake(next,secret);let stream;try{this.options.internalKey?stream=await connectInternalConnection(next,this.options.internalKey,{timeoutMs:INTERNAL_OBSERVER_HANDSHAKE_MS}):(await waitForConnect(next,5e3),stream=next)}catch(cause){throw next.destroy(),cause}return this.observerSocket=stream,attachJsonlLineReader(stream,line=>this.observeHostEvent(line),{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{let lost=()=>{handler(),this.options.onActivity?.()};stream.once("close",lost),stream.once("error",lost)}}}observeHostEvent(line){this.runs.observe(line)&&this.refresh()}},OWNER_EXIT_GRACE_MS=2e3,OWNER_PROBE_MAX_INTERVAL_MS=5e3,SupervisorOwner=class{constructor(generationDir){this.watchFailed=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.gone=!1,this.revision=0,this.stopped=!1,this.idle=new IdleExitDecider(OWNER_EXIT_GRACE_MS,()=>performance.now()),this.generationDir=generationDir}async start(fd){if(await this.reload(),!(fd===void 0||this.owner==null))try{let pipe=new Socket({fd,readable:!0,writable:!1});this.pipe=pipe;let bound=this.owner,failed=!1,eof=()=>{!failed&&!this.stopped&&sameHostOwner(this.owner,bound)&&(this.gone=!0)};pipe.once("end",eof),process.platform==="win32"&&pipe.once("close",eof),pipe.once("error",()=>{failed=!0,this.pipe===pipe&&(this.pipe=void 0),pipe.destroy()}),pipe.resume()}catch{this.pipe=void 0}}async reload(){let revision=++this.revision,next=await readHostOwner(this.generationDir);if(!(this.stopped||revision!==this.revision)){if(sameHostOwner(this.owner,next)||(this.pipe?.destroy(),this.pipe=void 0,this.gone=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.activity()),this.owner=next,next==null)this.watcher?.close(),this.watcher=void 0;else if(!this.watcher&&!this.watchFailed)try{this.watcher=watch(this.generationDir,(_event,filename)=>{filename?.toString()==="owner.json"&&this.reload()}),this.watcher.once("error",()=>{this.watchFailed=!0,this.watcher?.close(),this.watcher=void 0})}catch{this.watchFailed=!0}}}activity(){this.idle.update({connections:1,activeTurns:0})}async shouldExit(activity){this.watcher||await this.reload();let owner=this.owner,revision=this.revision;if(owner!=null&&!this.pipe&&!this.gone&&performance.now()>=this.nextProbeAt){let gone=await hostOwnerGone(owner);if(this.stopped||revision!==this.revision)return!1;this.gone=gone,this.nextProbeAt=performance.now()+this.probeIntervalMs,this.probeIntervalMs=Math.min(OWNER_PROBE_MAX_INTERVAL_MS,this.probeIntervalMs*2)}let quiet=this.gone&&owner!=null&&activity.quiescent();if(this.idle.update({connections:quiet?0:1,activeTurns:0})!=="exit")return!1;let current=await readHostOwner(this.generationDir);return!this.stopped&&revision===this.revision&&sameHostOwner(owner,current)&&activity.quiescent()}stop(){this.stopped=!0,this.watcher?.close(),this.pipe?.destroy()}};function waitForConnect(socket,timeoutMs){return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve2()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}import{readFile as readFile2}from"node:fs/promises";var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3,REPLACED_CONFIRMATIONS=3,IDENTITY_PROBE_TIMEOUT_MS=2e3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0)return endpoint.pointer===void 0?()=>{}:watchPointerSupersession(endpoint,endpoint.pointer,onLost);let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function watchPointerSupersession(endpoint,pointer,onLost){let probe=endpoint.probeInstanceId??probeAnsweringInstance,readPointer=endpoint.readPointerInstanceId??pointerInstanceId,agreeingPolls=0,observing=!1,lost=!1,observe=async()=>{let named=await readPointer(pointer.file);return named===void 0||named===pointer.instanceId?!1:await probe(endpoint.path)===named},timer=setInterval(()=>{lost||observing||endpoint.settled?.()===!0||(observing=!0,observe().then(replaced=>{lost||endpoint.settled?.()===!0||(agreeingPolls=replaced?agreeingPolls+1:0,!(agreeingPolls<REPLACED_CONFIRMATIONS)&&(lost=!0,clearInterval(timer),onLost("replaced")))},()=>{agreeingPolls=0}).finally(()=>{observing=!1}))},SUPERSESSION_POLL_MS);return timer.unref?.(),()=>clearInterval(timer)}async function pointerInstanceId(file){try{let parsed=JSON.parse(await readFile2(file,"utf8")),instanceId=typeof parsed=="object"&&parsed!==null?Reflect.get(parsed,"instance_id"):void 0;return typeof instanceId=="string"&&instanceId!==""?instanceId:void 0}catch{return}}async function probeAnsweringInstance(path){let{isRecord:isRecord2,requestOnSocket}=await import("./host-socket-request-ZDJGSSZO.js"),answer=await requestOnSocket(path,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},IDENTITY_PROBE_TIMEOUT_MS).catch(()=>{});return isRecord2(answer)&&typeof answer.instanceId=="string"?answer.instanceId:void 0}function ignore(){}var SupervisorDrain=class{constructor(child,shuttingDown,beginStopping=()=>{},relay){this.draining=!1,this.child=child,this.shuttingDown=shuttingDown,this.beginStopping=beginStopping,this.relay=relay}get active(){return this.draining}drain(){if(this.draining||this.shuttingDown())return;this.draining=!0,this.beginStopping(),supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??6e5;this.graceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),this.requestChildDrain()},graceMs),this.graceTimer.unref(),this.requestChildDrain()}stop(){this.graceTimer&&clearTimeout(this.graceTimer)}async acceptRequests(generation){let stop=watchDrainRequest(generation.drainRequestFile,request=>{supervisorLog(`drain requested (${request.reason})`),this.drain()});return await writeDrainWatch(generation.drainWatchFile,{pid:process.pid}).catch(cause=>{supervisorLog(`cannot advertise the drain request: ${errorMessage(cause)}`)}),stop}requestChildDrain(){let{child,relay}=this;if(!(child.pid===void 0||child.exitCode!==null||child.signalCode!==null)&&(relay&&writeDrainRequest(relay.file,{sender:relay.sender,reason:"supervisor_drain"}).catch(cause=>{supervisorLog(`could not relay the drain to the host: ${errorMessage(cause)}`)}),process.platform!=="win32"))try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage(cause)}`)}}};function drainOnPublicSocketLoss(path,identity,settled,drain,onReplaced,pointer){return watchForSupersession({path,identity,settled,...pointer&&{pointer}},loss=>{loss==="replaced"&&onReplaced(),supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drain.drain()})}async function watchWin32ChildIdentity(child,shuttingDown,onGone){let pid=child.pid;if(pid===void 0)return()=>{};let childStartTime=await readProcessStartTime(pid,process.platform,1e3).catch(()=>{}),missingIdentityChecks=0,checking=!1,timer=setInterval(()=>{shuttingDown()||checking||child.exitCode!==null||child.signalCode!==null||(checking=!0,readProcessStartTime(pid,process.platform,1e3).then(currentStartTime=>{currentStartTime===void 0&&!processIsLive(pid)?missingIdentityChecks++:currentStartTime!==void 0&&(missingIdentityChecks=0),(childStartTime!==void 0&¤tStartTime!==void 0&¤tStartTime!==childStartTime||missingIdentityChecks>=2)&&onGone()}).catch(()=>{}).finally(()=>{checking=!1}))},500);return timer.unref?.(),()=>clearInterval(timer)}import{randomBytes as randomBytes2}from"node:crypto";import{readFile as readFile4}from"node:fs/promises";import{join as join5}from"node:path";import{readFileSync as readFileSync4}from"node:fs";function readProcessStartTicks(pid,platform=process.platform){if(platform==="linux")try{let stat2=readFileSync4(`/proc/${pid}/stat`,"utf8"),ticks=stat2.slice(stat2.lastIndexOf(")")+2).split(" ")[19];return ticks!==void 0&&/^\d+$/.test(ticks)?ticks:void 0}catch{return}}async function compareRecordedStart(pid,recorded,platform,probe){if(platform==="linux"){if(recorded.ticks===void 0)return"unknown";let observed2=probe.ticks(pid);return observed2===void 0?"unknown":observed2===recorded.ticks?"same":"changed"}if(recorded.time===void 0)return"unknown";let observed=await probe.time(pid),recordedMs=processStartTimeMs(recorded.time),observedMs=observed===void 0?void 0:processStartTimeMs(observed);return recordedMs===void 0||observedMs===void 0?"unknown":sameProcessStartMs(recordedMs,observedMs)?"same":"changed"}import{randomUUID}from"node:crypto";import{realpathSync as realpathSync2}from"node:fs";import{mkdir,readFile as readFile3,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join3}from"node:path";var INTERNAL_HOST_DIR_PREFIX="senpi-rpc-host-internal-",SHORT_TEMP_ROOT="/tmp";function internalHostDirRoots(){let primary=tmpdir();return canonicalPath(primary)!==canonicalPath(SHORT_TEMP_ROOT)?[primary,SHORT_TEMP_ROOT]:[Buffer.byteLength(primary)<Buffer.byteLength(SHORT_TEMP_ROOT)?primary:SHORT_TEMP_ROOT]}function canonicalPath(path){try{return realpathSync2(path)}catch{return path}}function internalHostDirRoot(name){for(let root of internalHostDirRoots())if(Buffer.byteLength(join3(root,name,"host.sock"))<=MAX_SOCKET_PATH_BYTES)return root;let tried=internalHostDirRoots().map(root=>join3(root,name,"host.sock"));throw new Error(`internal_socket_path_too_long: every candidate exceeds ${MAX_SOCKET_PATH_BYTES} bytes (${tried.join(", ")}); set TMPDIR to a shorter directory`)}async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join3(baseDir,`internal-${randomUUID()}`);return await mkdir(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID()}`,dir:dir2,secretPath:join3(dir2,"secret")}}let name=`${INTERNAL_HOST_DIR_PREFIX}${randomUUID().slice(0,8)}`,dir=join3(internalHostDirRoot(name),name);return await mkdir(dir,{recursive:!1,mode:448}),await writeFile(join3(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join3(dir,"host.sock"),dir,secretPath:join3(dir,".secret")}}var CHILD_START_TIME_WAIT_MS=1e4,CHILD_START_TIME_UNHURRIED_MS=15e3;async function readChildStartTime(pid,timeoutMs){let identity=await readProcessIdentity(pid,process.platform,timeoutMs,void 0,"UTC");if(identity.kind==="error")throw identity.error;return identity.kind==="present"?identity.identity:void 0}async function recordChildPid(file,pid,running){try{await writeJsonAtomic(file,{pid,processStartTime:null});let processStartTime=await waitForStartTime(pid,CHILD_START_TIME_WAIT_MS,p=>readChildStartTime(p,1e3)).catch(()=>{})??await readChildStartTime(pid,CHILD_START_TIME_UNHURRIED_MS).catch(()=>{});if(processStartTime===void 0){supervisorLog(`host child pid ${pid} start time unreadable at recording`);return}if(!running())return;await writeJsonAtomic(file,{pid,processStartTime})}catch(cause){supervisorLog(`could not record the host child pid: ${errorMessage(cause)}`)}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile3(settingsFile,"utf8"))}catch{return}}import{execFileSync}from"node:child_process";import{closeSync as closeSync2,constants,fstatSync,openSync,rmSync as rmSync2}from"node:fs";import{join as join4}from"node:path";import{closeSync}from"node:fs";import{Socket as Socket2}from"node:net";function watchHostLifetime(fd,gone,unavailable){let stopped=!1,bun=Reflect.get(globalThis,"Bun");if(typeof bun=="object"&&bun!==null&&typeof Reflect.get(bun,"file")=="function"){let reader=Reflect.get(bun,"file")(fd).stream().getReader();return(async()=>{try{for(;!stopped;){let{done}=await reader.read();if(done){stopped||gone();return}}}catch{stopped||unavailable()}})(),()=>{stopped||(stopped=!0,reader.cancel().catch(()=>{}).finally(()=>closeSync(fd)))}}let socket=new Socket2({fd,readable:!0,writable:!1});return socket.once("end",()=>{stopped||gone()}),socket.once("error",()=>{stopped||unavailable()}),socket.unref(),socket.resume(),()=>{stopped=!0,socket.destroy()}}var HOST_WATCH_LIFETIME_FIFO_ENV="SENPI_RPC_HOST_LIFETIME_FIFO";function prepareLifetimeBinding(hopDir,platform=process.platform){if(platform!=="linux")return{};let path=join4(hopDir,"lifetime.fifo");try{return rmSync2(path,{force:!0}),execFileSync("mkfifo",["-m","600",path],{stdio:"ignore"}),openSync(path,constants.O_RDWR),{lifetimeFifo:path}}catch{return{}}}function armLifetimeBinding(binding,gone,unavailable,platform=process.platform){if(platform==="win32")return;let fifo=platform==="linux"?openFifoReadEnd(binding.lifetimeFifo):void 0;if(fifo!==void 0)return binding.lifetimeFd!==void 0&&closeSync2(binding.lifetimeFd),watchHostLifetime(fifo,()=>gone("supervisor lifetime FIFO closed"),unavailable);if(binding.lifetimeFd!==void 0)return watchHostLifetime(binding.lifetimeFd,()=>gone("supervisor stdin lifetime closed"),unavailable)}function openFifoReadEnd(path){if(path===void 0)return;let fd;try{fd=openSync(path,constants.O_RDONLY|constants.O_NONBLOCK|constants.O_NOFOLLOW)}catch{return}let stat2=fstatSync(fd),owned=typeof process.getuid!="function"||stat2.uid===process.getuid();if(stat2.isFIFO()&&owned&&(stat2.mode&511)===384)return fd;closeSync2(fd)}async function recordedOwnerStartTime(dir){if(dir!==void 0)try{let owner=JSON.parse(await readFile4(join5(dir,".owner"),"utf8")),start=owner!==null&&typeof owner=="object"?Reflect.get(owner,"processStartTime"):void 0;return typeof start=="string"?start:void 0}catch{return}}async function prepareInternalHop(daemonDir){let created=await createInternalSocketPath(daemonDir),internal={...created,secretPath:created.secretPath??socketSecretPath(created.socket)},internalSecret=process.platform==="win32"?await createSocketSecret(internal.secretPath):void 0,internalKey=process.platform==="win32"?void 0:randomBytes2(32);return{internal,internalSocket:internal.socket,internalSecret,internalKey,...internalKey&&internal.dir!==void 0?prepareLifetimeBinding(internal.dir):{},supervisorStart:internalKey?{time:await recordedOwnerStartTime(internal.dir),ticks:readProcessStartTicks(process.pid)}:void 0,transport:{...internalSecret?{internalSecret}:{},...internalKey?{internalKey}:{}}}}import{spawn}from"node:child_process";import{Socket as Socket4}from"node:net";import{extname}from"node:path";function runtimeExecArgv(execArgv=process.execArgv,bun=process.versions.bun!==void 0){let args=[];for(let index=0;index<execArgv.length;index++){let arg=execArgv[index];if(bun){if(arg==="-e"||arg==="--eval"||arg==="-p"||arg==="--print"||arg==="-pe"){index++;continue}if(arg.startsWith("-e")||arg.startsWith("-p"))continue}if(arg==="-e"||arg==="--eval"||arg==="-pe"||arg==="--input-type"||arg==="--input_type"){index++;continue}if(arg==="-p"||arg==="--print"){execArgv[index+1]!==void 0&&!execArgv[index+1].startsWith("-")&&index++;continue}arg==="-i"||arg==="--interactive"||arg.startsWith("--interactive=")||arg.startsWith("--eval=")||arg.startsWith("--print=")||arg.startsWith("--input-type=")||arg.startsWith("--input_type=")||args.push(arg)}return args}import{rmSync as rmSync3}from"node:fs";import{rm}from"node:fs/promises";import{Socket as Socket3}from"node:net";var HOST_WATCH_BACKSTOP_INTERVAL_MS=3e4,HOST_WATCH_PPID_INTERVAL_MS=250,HOST_WATCH_PPID_BACKUP_INTERVAL_MS=5e3,HOST_WATCH_IDENTITY_INTERVAL_MS=5e3,HOST_WATCH_IDENTITY_ONLY_INTERVAL_MS=1e3,HOST_WATCH_SPAWNING_IDENTITY_INTERVAL_MS=6e4;function supervisorPoll(ppid,recorded,fire,stopped){let stopPpid,ppidIntervalMs;return{arm(intervalMs){stopped()||ppid===void 0||ppidIntervalMs===intervalMs||(stopPpid?.(),ppidIntervalMs=intervalMs,stopPpid=watchPpid(ppid,recorded,fire,intervalMs))},soleInterval:recorded.ticks!==void 0||recorded.time!==void 0?HOST_WATCH_IDENTITY_ONLY_INTERVAL_MS:HOST_WATCH_PPID_INTERVAL_MS,stop:()=>stopPpid?.()}}function watchPpid(supervisorPid,recorded,fire,intervalMs){if(supervisorPid===process.pid)return()=>{};let linux=process.platform==="linux",comparable=linux?recorded.ticks!==void 0:recorded.time!==void 0,identityEveryTicks=Math.max(1,Math.round((linux?HOST_WATCH_IDENTITY_INTERVAL_MS:HOST_WATCH_SPAWNING_IDENTITY_INTERVAL_MS)/intervalMs)),probe={ticks:pid=>readProcessStartTicks(pid),time:pid=>readProcessStartTime(pid,process.platform,1e3)},ticks=0,stopped=!1,probing=!1,timer=setInterval(()=>{if(!stopped){if(!processAlive(supervisorPid)){fire(`supervisor pid ${supervisorPid} is gone`);return}ticks+=1,!(!comparable||probing||ticks%identityEveryTicks!==0)&&(probing=!0,compareRecordedStart(supervisorPid,recorded,process.platform,probe).then(result=>{!stopped&&result==="changed"&&fire(`supervisor pid ${supervisorPid} start time changed`)},()=>{}).finally(()=>{probing=!1}))}},intervalMs);return timer.unref?.(),()=>{stopped=!0,clearInterval(timer)}}function processAlive(pid){try{return process.kill(pid,0),!0}catch(cause){return!(cause instanceof Error&&"code"in cause&&cause.code==="ESRCH")}}var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID",HOST_WATCH_PSTART_ENV="SENPI_RPC_HOST_WATCH_PSTART",HOST_WATCH_PSTART_TICKS_ENV="SENPI_RPC_HOST_WATCH_PSTART_TICKS",HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function readHostWatchdogConfig(env=process.env){let ppid=parsePositiveInteger(env[HOST_WATCH_PPID_ENV]),fd=process.platform!=="win32"&&ppid!==void 0?void 0:parsePositiveInteger(env[HOST_WATCH_FD_ENV]);if(fd===void 0&&ppid===void 0)return;let scratchDir=env[HOST_SCRATCH_DIR_ENV],cleanupPaths=env[HOST_CLEANUP_PATHS_ENV]?.split(`
|
|
14
|
+
`).filter(Boolean),publicSocket=env[HOST_PUBLIC_SOCKET_ENV],daemonDir=env[HOST_DAEMON_DIR_ENV],instanceId=env[HOST_INSTANCE_ID_ENV];return{fd,ppid,...env[HOST_WATCH_PSTART_ENV]?{processStartTime:env[HOST_WATCH_PSTART_ENV]}:{},...env[HOST_WATCH_PSTART_TICKS_ENV]?{processStartTicks:env[HOST_WATCH_PSTART_TICKS_ENV]}:{},...env[HOST_WATCH_LIFETIME_FIFO_ENV]?{lifetimeFifo:env[HOST_WATCH_LIFETIME_FIFO_ENV]}:{},scratchDir:scratchDir===void 0||scratchDir===""?void 0:scratchDir,cleanupPaths,publicSocket:publicSocket===""?void 0:publicSocket,...daemonDir&&instanceId?{daemonDir,instanceId}:{}}}function readHostWatchdogConfigFromBrandEnv(env=process.env){return readHostWatchdogConfig({[HOST_WATCH_FD_ENV]:env[HOST_WATCH_FD_ENV]??envValue("RPC_HOST_WATCH_FD",env),[HOST_WATCH_PPID_ENV]:env[HOST_WATCH_PPID_ENV]??envValue("RPC_HOST_WATCH_PPID",env),[HOST_WATCH_PSTART_ENV]:env[HOST_WATCH_PSTART_ENV]??envValue("RPC_HOST_WATCH_PSTART",env),[HOST_WATCH_PSTART_TICKS_ENV]:env[HOST_WATCH_PSTART_TICKS_ENV]??envValue("RPC_HOST_WATCH_PSTART_TICKS",env),[HOST_WATCH_LIFETIME_FIFO_ENV]:env[HOST_WATCH_LIFETIME_FIFO_ENV]??envValue("RPC_HOST_LIFETIME_FIFO",env),[HOST_SCRATCH_DIR_ENV]:env[HOST_SCRATCH_DIR_ENV]??envValue("RPC_HOST_SCRATCH_DIR",env),[HOST_PUBLIC_SOCKET_ENV]:env[HOST_PUBLIC_SOCKET_ENV]??envValue("RPC_HOST_PUBLIC_SOCKET",env),[HOST_CLEANUP_PATHS_ENV]:env[HOST_CLEANUP_PATHS_ENV]??envValue("RPC_HOST_CLEANUP_PATHS",env),[HOST_DAEMON_DIR_ENV]:env[HOST_DAEMON_DIR_ENV],[HOST_INSTANCE_ID_ENV]:env[HOST_INSTANCE_ID_ENV]})}var WATCH_ENV_SUFFIXES=["RPC_HOST_WATCH_FD","RPC_HOST_WATCH_PPID","RPC_HOST_WATCH_PSTART","RPC_HOST_WATCH_PSTART_TICKS","RPC_HOST_LIFETIME_FIFO","RPC_HOST_SCRATCH_DIR","RPC_HOST_PUBLIC_SOCKET","RPC_HOST_CLEANUP_PATHS"];function consumeHostWatchdogEnv(env=process.env){let config=readHostWatchdogConfigFromBrandEnv(env);return scrubHostWatchdogEnv(env),config}function scrubHostWatchdogEnv(env=process.env){for(let suffix of WATCH_ENV_SUFFIXES)for(let name of[`SENPI_${suffix}`,...brandEnvNames(suffix)])delete env[name]}function armHostWatchdog(config,onSupervisorGone){if(!config)return()=>{};let stopped=!1,fired=!1,fire=reason=>{if(stopped||fired)return;fired=!0,disarm(),config.daemonDir!==void 0&&config.instanceId!==void 0&&recordHostCrash(config.daemonDir,{at:new Date().toISOString(),uptimeMs:Math.round(process.uptime()*1e3),kind:"rpc-host-watchdog",generation:config.instanceId,reason});let captured=captureBeforeCleanup(config);if(process.platform==="win32"){let cleanup=captured.then(()=>cleanupWatchdogPaths(config));onSupervisorGone(reason,cleanup)}else captured.then(()=>cleanupWatchdogPaths(config)).finally(()=>onSupervisorGone(reason))},disarmers=[],disarm=()=>{stopped=!0;for(let stop of disarmers.splice(0))stop()},poll=supervisorPoll(config.ppid,{ticks:config.processStartTicks,time:config.processStartTime},fire,()=>stopped);disarmers.push(()=>poll.stop());let pollWanted=!1,pipeLive=!1;config.fd!==void 0&&(pipeLive=watchFdForEof(config.fd,fire,disarmers,()=>{pipeLive=!1,pollWanted&&poll.arm(poll.soleInterval)}));let fallback=()=>{pollWanted=!0,poll.arm(pipeLive?HOST_WATCH_PPID_BACKUP_INTERVAL_MS:poll.soleInterval)},stopLifetime;try{stopLifetime=armLifetimeBinding(config,fire,fallback)}catch{stopLifetime=void 0}return stopLifetime!==void 0?(disarmers.push(stopLifetime),poll.arm(HOST_WATCH_BACKSTOP_INTERVAL_MS)):fallback(),disarm}function watchFdForEof(fd,fire,disarmers,onUnavailable){let stream,streamFailed=!1,fired=!1,fireOnce=reason=>{fired||(fired=!0,fire(reason))};try{stream=new Socket3({fd,readable:!0,writable:!1})}catch{return!1}stream.resume();let onEnd=()=>fireOnce(`supervisor pipe fd ${fd} closed`),onClose=()=>{streamFailed||onEnd()},onError=()=>{streamFailed=!0,onUnavailable()};return stream.once("end",onEnd),process.platform==="win32"&&stream.once("close",onClose),stream.once("error",onError),disarmers.push(()=>{stream.off("end",onEnd),stream.off("close",onClose),stream.off("error",onError),stream.destroy()}),!0}function captureBeforeCleanup(config){return config.beforeCleanup===void 0?Promise.resolve():Promise.resolve().then(config.beforeCleanup).catch(()=>{})}async function cleanupWatchdogPaths(config){let paths=[...config.cleanupPaths??[],...config.scratchDir?[config.scratchDir]:[]];for(let path of paths)try{process.platform==="win32"?rmSync3(path,{recursive:!0,force:!0,maxRetries:10,retryDelay:100}):await rm(path,{recursive:!0,force:!0})}catch{}}var INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,ownerFd,bindSocket,replaceIdentity;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--owner-fd"&&index+1<argv.length){if(ownerFd=Number(argv[++index]),!Number.isSafeInteger(ownerFd)||ownerFd<3)return;continue}if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}hostArgs.push(arg)}return socket===void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,ownerFd,bindSocket,replaceIdentity}}var OWNER_WATCH_FD=3,ownerPipes=new Set;function keepOwnerPipe(child){let pipe=child.stdio[OWNER_WATCH_FD];if(!(pipe instanceof Socket4))throw new Error("RPC owner pipe was not inherited");ownerPipes.add(pipe),pipe.on("error",()=>{}),pipe.unref(),child.once("exit",()=>{ownerPipes.delete(pipe),pipe.destroy()})}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...runtimeExecArgv(),resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}var HOST_CHILD_WATCH_FD=3;function spawnHostChild(options){let{launch,internalSocket,internal,internalSecret,publicSocket}=options,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),child=spawn(childLaunch.command,childLaunch.args,{env:{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:options.daemonDir,[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_WATCH_FD_ENV]:String(HOST_CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),[HOST_WATCH_PSTART_ENV]:options.supervisorStart?.time,[HOST_WATCH_PSTART_TICKS_ENV]:options.supervisorStart?.ticks,[HOST_WATCH_LIFETIME_FIFO_ENV]:options.lifetimeFifo,...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},[SOCKET_SECRET_FILE_ENV]:process.platform==="win32"&&internalSecret?internal.secretPath:void 0,SENPI_RPC_INTERNAL_KEY_STDIN:options.internalKey?"1":void 0,[HOST_CLEANUP_PATHS_ENV]:options.cleanupPaths.join(`
|
|
15
|
+
`),...process.platform==="win32"?{}:{[HOST_PUBLIC_SOCKET_ENV]:publicSocket}},shell:childLaunch.shell,stdio:[process.platform==="win32"?"ignore":"pipe","ignore","inherit","pipe"],windowsHide:!0});return options.internalKey&&(child.stdin?.on("error",()=>{}),child.stdin?.write(options.internalKey)),child}import{chmod,mkdir as mkdir2,stat,unlink}from"node:fs/promises";import{createConnection as createConnection2,createServer}from"node:net";import{dirname as dirname2}from"node:path";import{StringDecoder}from"node:string_decoder";function proxyWithAdmission(client,internal,admission,auth){let reply=chunk=>write(client,auth?auth.response(chunk.toString()):chunk),pending=[],refused=new Set,protocols=0,refusals=Promise.resolve(),unsubscribe=admission.onStop(()=>(refusals=refusePending(),refusals));async function refusePending(){let ids=pending.splice(0);for(let id of ids)refused.add(id);try{for(let id of ids)await reply(serializeJsonLine(hostStoppingResponse(id,"open_session",admission)))}catch{fail()}}client.once("close",()=>{unsubscribe(),internal?.destroy()});let fail=()=>{internal?.destroy(),client.destroy()};client.once("error",fail),internal?.once("error",()=>{admission.stopping||fail()}),requests().catch(()=>{admission.stopping||fail()}),internal&&responses(internal).catch(()=>{admission.stopping||fail()});async function requests(){for await(let line of lines(auth?.input??client,MAX_RPC_LINE_CHARACTERS)){if(line===void 0){await reply(serializeJsonLine({type:"response",command:"parse",success:!1,error:`RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`}));continue}let request=record(line);admission.stopping&&request?.type==="get_protocol_info"?await reply(serializeJsonLine({id:request.id,type:"response",command:request.type,success:!0,data:admission.protocol()})):admission.stopping&&(request?.type==="open_session"||!internal)?await reply(serializeJsonLine(hostStoppingResponse(request?.id,String(request?.type??"parse"),admission))):internal&&(request?.type==="open_session"&&pending.push(request.id),request?.type==="get_protocol_info"&&protocols++,await write(internal,`${line}
|
|
16
|
+
`))}internal?.end()}async function responses(source){let fragments=[];for await(let chunk of source){let newline=chunk.lastIndexOf(10);if(newline===-1){fragments.push(chunk);continue}let complete=chunk.subarray(0,newline+1);if(!auth&&pending.length===0&&protocols===0&&refused.size===0){client.cork();let written;try{for(let fragment of fragments)client.write(fragment);written=write(client,complete)}finally{client.uncork()}await written}else{let batch=fragments.length>0?Buffer.concat([...fragments,complete]):complete;await reply(filterReplies(batch))}fragments=newline+1<chunk.length?[chunk.subarray(newline+1)]:[]}fragments.length>0&&await reply(filterReplies(Buffer.concat(fragments))),await refusals,client.end(()=>client.destroy())}function filterReplies(batch){if(pending.length===0&&protocols===0&&refused.size===0)return batch;let output=[],changed=!1;for(let start=0;start<batch.length;){let newline=batch.indexOf(10,start),end=newline===-1?batch.length:newline+1,line=batch.subarray(start,end);start=end;let response=line.includes('"open_session"')||line.includes('"get_protocol_info"')?record(line.toString("utf8")):void 0;if(response?.type==="response"&&response.command==="open_session"){if(refused.has(response.id)){changed=!0;continue}let index=pending.indexOf(response.id);index!==-1&&pending.splice(index,1)}if(response?.type==="response"&&response.command==="get_protocol_info"&&(protocols=Math.max(0,protocols-1),response.success===!0)){isRecord(response.data)&&admission.observe(response.data),output.push(Buffer.from(serializeJsonLine({...response,data:admission.protocol()}))),changed=!0;continue}output.push(line)}return changed?Buffer.concat(output):batch}}async function write(socket,line){await new Promise((resolve2,reject)=>{socket.write(line,error=>error?reject(error):resolve2())})}async function*lines(socket,limit){let decoder=new StringDecoder("utf8"),buffer="",discarding=!1;for await(let chunk of socket){let text=typeof chunk=="string"?chunk:decoder.write(chunk),offset=0;for(;offset<text.length;){let newline=text.indexOf(`
|
|
17
|
+
`,offset),end=newline===-1?text.length:newline;if(discarding||(buffer.length+end-offset>limit?(buffer="",discarding=!0,yield void 0):buffer+=text.slice(offset,end)),newline===-1)break;discarding||(yield buffer),buffer="",discarding=!1,offset=newline+1}}buffer+=decoder.end(),!discarding&&buffer.length>0&&(yield buffer)}function record(line){try{let value=JSON.parse(line);return isRecord(value)?value:void 0}catch{return}}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{randomBytes as randomBytes3}from"node:crypto";import{Duplex as Duplex2,PassThrough}from"node:stream";var PREAUTH_BYTES=8*1024,PublicRpcConnection=class{get stream(){return this.view??=this.duplex(),this.view}constructor(socket,endpoint,requireToken=process.env.SENPI_RPC_REQUIRE_TOKEN==="1"){this.input=new PassThrough,this.raw=new PassThrough,this.bytes=0,this.active=!1,this.failed=!1,this.first=!0,this.protocolPending=!1,this.socket=socket,this.endpoint=endpoint,this.requireToken=requireToken,socket.pause(),this.timer=setTimeout(()=>{this.requireToken?this.drop("pre-auth deadline"):!this.active&&!this.failed&&this.challenge===void 0&&this.grace()},SOCKET_HANDSHAKE_TIMEOUT_MS);let detach=attachJsonlLineReader(this.raw,line=>this.line(line),{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>this.active?socket.destroy():this.drop("first frame over the line limit")});socket.on("error",()=>socket.destroy()),socket.once("close",()=>{!this.active&&!this.failed&&!this.requireToken&&!this.first&&this.grace(),clearTimeout(this.timer),detach(),this.raw.destroy(),this.input.end()}),socket.once("end",()=>this.raw.end()),this.input.on("drain",()=>socket.resume()),socket.on("data",chunk=>{for(let offset=0;offset<chunk.length&&!this.failed;){let newline=chunk.indexOf(10,offset),end=newline===-1?chunk.length:newline+1,segment=chunk.subarray(offset,end);if(this.active||(this.bytes+=segment.length),!this.active&&this.requireToken&&this.bytes>PREAUTH_BYTES){this.drop("pre-auth budget exceeded");return}this.raw.write(segment),offset=end}}),endpoint.ready.then(()=>{socket.destroyed||socket.resume()},()=>this.drop("key publication failed"))}duplex(){let input=this.input,stream=new Duplex2({read:()=>input.resume(),write:(chunk,_encoding,callback)=>{let output=this.response(chunk.toString());output===""?callback():this.socket.write(output,callback)},final:callback=>this.socket.end(callback),destroy:(error,callback)=>{this.socket.destroy(),callback(error)}});return input.on("data",chunk=>{stream.push(chunk)||input.pause()}),input.once("end",()=>{stream.push(null),stream.destroy()}),input.readableEnded&&stream.destroy(),stream}line(line){if(this.failed||this.socket.destroyed)return;let request;try{request=authRecord(JSON.parse(line))}catch{}if(!this.active){if(this.first&&request?.type==="get_protocol_info"){this.first=!1,this.protocolPending=!0;let nonce2=authRecord(request.auth)?.client_nonce;if(nonce2!==void 0){if(typeof nonce2!="string"||!RPC_AUTH_HEX.test(nonce2)){this.refuse(request,"auth_failed");return}this.challenge={id:request.id,client:nonce2,server:randomBytes3(32).toString("hex")}}else if(this.requireToken){this.refuse(request,"auth_required");return}else this.grace();this.forward(line);return}if(this.first=!1,request?.type==="authenticate"){let c=this.challenge;if(!c||!rpcProofMatches(rpcAuthProof(this.endpoint.key,"client",this.endpoint.launchId,c.server,c.client),request.client_proof)){this.refuse(request,"auth_failed");return}this.active=!0,clearTimeout(this.timer),this.socket.write(serializeJsonLine({id:request.id,type:"response",command:"authenticate",success:!0}));return}if(this.requireToken){this.refuse(request,"auth_required");return}this.grace()}this.forward(line)}forward(line){this.input.write(`${line}
|
|
18
|
+
`)||this.socket.pause()}grace(){this.active=!0,clearTimeout(this.timer),process.stderr.write(`senpi rpc host: served a client that did not prove the endpoint key on ${this.endpoint.endpoint} (deprecated, refused from the next release; see docs/rpc.md#authentication)
|
|
19
|
+
`)}logDrop(reason){process.stderr.write(`senpi rpc host: dropped an unauthenticated connection on ${this.endpoint.endpoint}: ${reason}
|
|
20
|
+
`)}drop(reason){this.failed||(this.failed=!0,clearTimeout(this.timer),this.logDrop(reason),this.socket.destroy())}refuse(request,code){this.failed=!0,clearTimeout(this.timer),this.logDrop(code),this.socket.end(serializeJsonLine({id:request?.id,type:"response",command:request?.type??"parse",success:!1,error:code,errorCode:code}),()=>this.socket.destroy())}response(chunk){if(this.failed)return"";if(this.active&&!this.protocolPending)return chunk;let output="";for(let line of chunk.split(`
|
|
21
|
+
`)){if(!line)continue;let record2=authRecord(JSON.parse(line));if(record2?.type==="response"&&record2.command==="get_protocol_info"&&record2.success===!0){this.protocolPending=!1;let data=authRecord(record2.data)??{},capabilities=Array.isArray(data.capabilities)?data.capabilities:[],c=this.challenge;output+=serializeJsonLine({...record2,data:{...data,capabilities:[...new Set([...capabilities,RPC_AUTH_CAPABILITY])],...c&&record2.id===c.id?{auth:{launch_id:this.endpoint.launchId,server_nonce:c.server,server_proof:rpcAuthProof(this.endpoint.key,"server",this.endpoint.launchId,c.client,c.server)}}:{}}})}else(this.active||!this.requireToken)&&(output+=`${line}
|
|
22
|
+
`)}return output}};function createPublicProxy(options){let{internalSocket,internalSecret,publicSecret,clients}=options;return createServer(client=>{let auth=options.publicEndpoint?new PublicRpcConnection(client,options.publicEndpoint):void 0,accept=async()=>{if(!clients.admit(client))return;client.pause();let internal=options.admission.stopping?void 0:createConnection2(resolveSocketTransportAddress(internalSocket,process.platform,internalSecret));internal&&internalSecret&&sendSocketHandshake(internal,internalSecret);let detach=()=>{clients.release(client)&&options.onAdmit?.(),options.onDetach(),internal?.destroy(),client.destroy()};client.once("close",detach),client.once("error",detach);try{let hop=internal&&options.internalKey?await connectInternalConnection(internal,options.internalKey):internal;if(client.destroyed){hop?.destroy();return}proxyWithAdmission(client,hop,options.admission,auth),auth||client.resume()}catch{detach()}};publicSecret?authenticateSocket(client,publicSecret,()=>{accept()}):accept()})}async function ensurePublicSocketSecret(publicSocket){let secretPath=socketSecretPath(publicSocket);try{return await ensureSocketSecret(secretPath)}catch(cause){throw new Error(`senpi rpc host supervisor: cannot provision public socket secret ${secretPath}`,{cause})}}var INTERNAL_READINESS_PROBE_MS=1e4;async function waitForListener(socketPath,timeoutMs,secret,internalKey){let deadline=performance.now()+timeoutMs;for(;performance.now()<=deadline;){let probeMs=Math.max(1,Math.min(INTERNAL_READINESS_PROBE_MS,deadline-performance.now())),probe=await canConnect(socketPath,secret,internalKey,probeMs);if(probe==="ready")return;if(probe==="silent")throw new Error(`${socketPath}: host accepted the internal hop but did not answer within ${Math.round(probeMs)}ms`);if(probe!=="refused")throw new Error(`${socketPath}: ${probe.unproven}`);await new Promise(resolveDelay=>setTimeout(resolveDelay,50))}throw new Error(`${socketPath}: host did not start listening within ${timeoutMs}ms`)}async function canConnect(socketPath,secret,internalKey,probeMs){if(internalKey){let socket=createConnection2(resolveSocketTransportAddress(socketPath,process.platform,secret)),accepted=!1,expired=!1;socket.once("connect",()=>{accepted=!0});let timer=setTimeout(()=>{expired=!0,socket.destroy()},probeMs);timer.unref();let outcome=ready=>ready?"ready":accepted&&expired?"silent":"refused";try{let stream=await connectInternalConnection(socket,internalKey);return outcome(await new Promise(resolve2=>{let settle=ready=>{stream.destroy(),resolve2(ready)};stream.once("error",()=>settle(!1)),stream.once("close",()=>settle(!1)),attachJsonlLineReader(stream,line=>{try{let response=JSON.parse(line);response.id==="internal-ready"&&settle(response.success===!0)}catch{settle(!1)}},{maxLineLength:MAX_RPC_LINE_CHARACTERS}),stream.write(`{"id":"internal-ready","type":"get_protocol_info","observe":true}
|
|
23
|
+
`)}))}catch(cause){socket.destroy();let reason=cause instanceof Error?cause.message:"";return reason==="host_identity_unproven"||reason==="auth_failed"?{unproven:reason}:outcome(!1)}finally{clearTimeout(timer)}}return new Promise(resolve2=>{let socket=createConnection2(resolveSocketTransportAddress(socketPath,process.platform,secret));secret&&sendSocketHandshake(socket,secret);let settle=connected=>{socket.destroy(),resolve2(connected?"ready":"refused")};socket.once("connect",()=>settle(!0)),socket.once("error",()=>settle(!1))})}async function stampOf(socketPath){try{let entry=await stat(socketPath,{bigint:!0});return{dev:entry.dev,ino:entry.ino,ctimeNs:entry.ctimeNs,socket:entry.isSocket()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause}}var sameStamp=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.ctimeNs===b.ctimeNs;async function prepareSocketPath(socketPath,hooks={}){if(process.platform==="win32"||socketPath.startsWith("\0"))return;if(Buffer.byteLength(socketPath)>MAX_SOCKET_PATH_BYTES)throw new Error(`${socketPath}: socket path is ${Buffer.byteLength(socketPath)} bytes, over the ${MAX_SOCKET_PATH_BYTES}-byte limit.`);await mkdir2(dirname2(socketPath),{recursive:!0,mode:448});let probed=await stampOf(socketPath);if(probed===void 0)return;let inUse=evidence=>new Error(`${socketPath}: address already in use by a live server (${evidence}).`);if(!probed.socket)throw inUse("the entry is not a socket");let state=await(hooks.listenerState??socketEntryListenerState)(socketPath);if(state.verdict==="gone")return;if(state.verdict==="live")throw inUse(state.evidence);await hooks.afterStaleProbe?.();let current=await stampOf(socketPath);if(current!==void 0){if(!sameStamp(probed,current))throw inUse("the entry changed after it was probed");try{await unlink(socketPath)}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause}}}function listen(server,socketPath,secret){return new Promise((resolve2,reject)=>{server.once("error",reject),server.listen({path:resolveSocketTransportAddress(socketPath,process.platform,secret),readableAll:!1,writableAll:!1},async()=>{server.off("error",reject);try{process.platform!=="win32"&&!socketPath.startsWith("\0")&&await chmod(socketPath,384),resolve2()}catch(cause){reject(cause)}})})}function closeServer(server){return new Promise(resolve2=>{server.close(()=>resolve2())})}import{rm as rm2}from"node:fs/promises";var LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_ERROR_MS=5e3;function loopLagErrorMs(env=process.env){return parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}var STALL_WAIT_SLICE_MS=5e3;async function waitOutStalledChild(options){let{child,generation,signalledAt}=options,maxMs=childStalledStopMaxMs(),untilAt=signalledAt+maxMs,stalled=()=>hostLoopStalled(generation,{now:Date.now(),errorMs:loopLagErrorMs(),windowMs:STOP_STALL_EVIDENCE_MAX_AGE_MS}).catch(()=>!1),waited=0;try{for(;Date.now()<untilAt&&await stalled();){waited===0&&supervisorLog(`host child is stalled; waiting up to ${maxMs}ms (${CHILD_STALLED_STOP_MAX_MS_ENV})`),await writeStopProgress(generation,{at:new Date().toISOString(),phase:"waiting_stalled_child",untilAt:new Date(untilAt).toISOString()}).catch(()=>{});let slice=Math.min(STALL_WAIT_SLICE_MS,untilAt-Date.now()),exited=await options.waitForExit(child,slice);if(waited+=slice,exited)break}}finally{await clearStopProgress(generation)}return waited}var WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS=2e3;function supervisorSender(instanceId){return{pid:process.pid,kind:"supervisor",generation:instanceId}}function childExited(child){return child.exitCode!==null||child.signalCode!==null}async function performShutdown(context,reason,exitCode){let{state,child}=context;state.shuttingDown=!0,state.shutdownReason=reason,context.admission.stop();let childStopStarted=!1,hardExit;try{context.stopWatchers(),context.drain.stop(),writeStderrLine(`senpi rpc host supervisor: ${reason} shutdown`),childStopStarted=!0,await stopChild(context,reason),await state.childExitRecorded,await context.admission.flush(),context.activity.clients.destroyAll(),process.platform==="win32"&&(hardExit=setTimeout(()=>process.exit(exitCode),WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS)),context.drain.active||await shieldSocketDuringClose(context.publicSocket,()=>closeServer(context.server)),context.internalDir&&await rm2(context.internalDir,{recursive:!0,force:!0}),context.activity.stopObserver(),state.publicSocketOwned&&process.platform!=="win32"&&await unlinkOwnedSocket(context.publicSocket,state.publicSocketIdentity,supervisorLog),await releaseGeneration(context.paths,{instanceId:context.instanceId,pid:process.pid,superseded:state.endpointReplaced})}catch(cause){supervisorLog(`shutdown failed for host child pid ${child.pid??"unknown"}: ${errorMessage(cause)}`),exitCode=1;try{childStopStarted||await reapChildAfterFailure(child),await state.childExitRecorded}catch(reapCause){supervisorLog(`shutdown recovery failed for host child pid ${child.pid??"unknown"}: ${errorMessage(reapCause)}`)}}finally{await context.publicEndpoint?.dispose().catch(cause=>{supervisorLog(`endpoint key cleanup failed: ${errorMessage(cause)}`)}),hardExit&&clearTimeout(hardExit),process.exit(exitCode)}}async function stopChild(context,reason){let{child,generation}=context,pid=child.pid;if(childExited(child)||pid===void 0)return;let termAttempted=!1,killAttempted=!1;try{let outer=await readStopIntent(generation).catch(cause=>{supervisorLog(`cannot read child stop intent: ${errorMessage(cause)}`)}),at=new Date().toISOString(),intent=layeredSupervisorIntent(outer,supervisorSender(context.instanceId),{targetPid:pid,reason,at});await writeStopIntent(generation,intent,supervisorLog);let signalledAt=Date.now();if(termAttempted=!0,signalChild(pid,"SIGTERM"),await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS))return;let stallWaitMs=await waitOutStalledChild({child,generation,signalledAt,waitForExit:waitForChildExit});if(childExited(child))return;if(stallWaitMs>0){let escalated={...intent,reason:`${intent.reason}; escalated_after_stall_wait=${stallWaitMs}`};await writeStopIntent(generation,escalated,supervisorLog)}if(killAttempted=!0,signalChild(pid,"SIGKILL"),!await waitForChildExit(child,CHILD_KILL_EXIT_TIMEOUT_MS))throw new Error(`host child pid ${pid} exit unobserved ${CHILD_KILL_EXIT_TIMEOUT_MS}ms after SIGKILL`)}catch(cause){throw killAttempted||await reapChildAfterFailure(child,termAttempted),cause}}async function reapChildAfterFailure(child,termAttempted=!1){let pid=child.pid;if(!(childExited(child)||pid===void 0)&&!(!termAttempted&&(signalChild(pid,"SIGTERM"),await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS)))&&(signalChild(pid,"SIGKILL"),!await waitForChildExit(child,CHILD_KILL_EXIT_TIMEOUT_MS)))throw new Error(`host child pid ${pid} exit unobserved ${CHILD_KILL_EXIT_TIMEOUT_MS}ms after recovery SIGKILL`)}function signalChild(pid,signal){try{return process.kill(pid,signal),!0}catch{return!1}}function waitForChildExit(child,timeoutMs){return childExited(child)?Promise.resolve(!0):new Promise(resolve2=>{let timer=setTimeout(()=>{child.off("exit",onExit2),resolve2(!1)},timeoutMs),onExit2=()=>{clearTimeout(timer),resolve2(!0)};child.once("exit",onExit2)})}function registerSupervisorSignals(shutdown,drain){for(let signal of process.platform==="win32"?["SIGTERM"]:["SIGTERM","SIGHUP"])process.on(signal,()=>{shutdown(`signal:${signal}`,signal==="SIGHUP"?129:143)});process.platform!=="win32"&&process.on("SIGUSR1",drain)}function startSupervisorTicker(options){let{activity,owner,draining,shuttingDown,shutdown}=options,tickIntervalMs=Math.max(20,Math.min(1e3,options.idleExitMs/4)),ownerCheck=!1,ticker=setInterval(()=>{!draining()&&activity.refresh()==="exit"&&activity.clients.unclassifiedCount===0&&shutdown("idle",0),!ownerCheck&&!shuttingDown()&&!draining()&&(ownerCheck=!0,owner.shouldExit(activity).then(exit=>{exit&&!shuttingDown()&&!draining()&&shutdown("owner_gone",0)}).finally(()=>{ownerCheck=!1}))},tickIntervalMs);return()=>{clearInterval(ticker),owner.stop()}}async function runHostSupervisor(launch){let paths=createHostDaemonPaths({socket:launch.socket,agentDir:launch.agentDir??getAgentDir()}),told=process.env[HOST_INSTANCE_ID_ENV],instanceId=told!==void 0&&told.trim()!==""?told:randomUUID2(),generation=generationPaths(paths,instanceId),policy=resolveHostPolicy(await readSettingsFile(paths.settingsFile),process.env),publicSocket=launch.socket,publicEndpoint=process.platform==="win32"?void 0:new RpcPublicEndpoint(launch.agentDir??getAgentDir(),publicSocket),bindSocket=launch.bindSocket??publicSocket,successor=launch.bindSocket!==void 0,publicSecret=process.platform==="win32"?await ensurePublicSocketSecret(publicSocket):void 0,hop=await prepareInternalHop(paths.dir),{internal,internalSocket,internalSecret,internalKey}=hop,state={shuttingDown:!1,shutdownReason:void 0,childExitRecorded:Promise.resolve(),publicSocketOwned:!1,publicSocketIdentity:void 0,endpointReplaced:!1},owner=new SupervisorOwner(generation.dir),activity=new SupervisorActivity({idleExitMs:policy.coldStart==="persistent"?Number.POSITIVE_INFINITY:policy.idleExitMs,internalSocket,...hop.transport,instanceId,settled:()=>state.shuttingDown,onActivity:()=>owner.activity()}),watchers=[],child=spawnHostChild({launch,internalSocket,internal,...hop.transport,supervisorStart:hop.supervisorStart,lifetimeFifo:hop.lifetimeFifo,daemonDir:paths.dir,instanceId,cleanupPaths:hostCrashCleanupPaths({pointerFile:paths.pointerFile,generationPidFile:generation.pidFile,settingsFile:paths.settingsFile,publicSocket,successor:!!successor,platform:process.platform}),publicSocket}),childStartedAt=Date.now();child.stdio[HOST_CHILD_WATCH_FD]?.on("error",()=>{}),child.pid!==void 0&&recordChildPid(generation.childPidFile,child.pid,()=>child.exitCode===null&&child.signalCode===null),child.once("exit",(code,signal)=>{let reason=state.shutdownReason;if(state.childExitRecorded=noteChildExit({daemonDir:paths.dir,generation,instanceId,code,signal,childStartedAt,...state.shuttingDown&&reason!==void 0?{shutdown:{reason,supervisor:supervisorSender(instanceId)}}:{}}),state.shuttingDown)return;let verdict=classifyChildExit(code,signal);state.childExitRecorded.then(()=>shutdown(verdict.reason,verdict.exitCode))});let admission=new HostAdmission({protocolVersion:1,serverVersion:VERSION,capabilities:[],instanceId}),drain=new SupervisorDrain(child,()=>state.shuttingDown,()=>admission.stop(),{file:generation.childDrainRequestFile,sender:supervisorSender(instanceId)}),server=createPublicProxy({internalSocket,...hop.transport,...publicSecret?{publicSecret}:{},...publicEndpoint?{publicEndpoint}:{},clients:activity.clients,admission,onDetach:()=>activity.refresh(),onAdmit:()=>owner.activity()});server.once("error",cause=>{state.shuttingDown||shutdown(`public socket listener failed: ${errorMessage(cause)}`,1)}),watchers.push(startSupervisorTicker({idleExitMs:policy.idleExitMs,activity,owner,draining:()=>drain.active,shuttingDown:()=>state.shuttingDown,shutdown}));let teardown={paths,generation,instanceId,publicSocket,server,internalDir:internal.dir,child,activity,drain,admission,state,...publicEndpoint?{publicEndpoint}:{},stopWatchers:()=>{for(let stop of watchers.splice(0))stop()}},shutdownPromise;function shutdown(reason,exitCode){return shutdownPromise??=performShutdown(teardown,reason,exitCode),shutdownPromise}registerSupervisorSignals(shutdown,()=>drain.drain());try{(launch.ownerFd!==void 0||await readSettingsFile(generation.settingsFile))&&await owner.start(launch.ownerFd),await waitForListener(internalSocket,3e4,internalSecret,internalKey),await activity.openObserver(),await prepareSocketPath(bindSocket),await listen(server,bindSocket,publicSecret),await publicEndpoint?.publish(),state.publicSocketOwned=!0,successor&&await adoptPublicSocket(bindSocket,publicSocket,launch.replaceIdentity),state.publicSocketIdentity=await statSocketIdentity(publicSocket),state.publicSocketIdentity&&internal.dir&&await writeSocketIdentityFile(join6(internal.dir,PUBLIC_SOCKET_IDENTITY_FILE),state.publicSocketIdentity),watchers.push(drainOnPublicSocketLoss(publicSocket,state.publicSocketIdentity,()=>state.shuttingDown||drain.active,drain,()=>{state.endpointReplaced=!0},{file:paths.pointerFile,instanceId})),watchers.push(await drain.acceptRequests(generation))}catch(cause){await shutdown(`startup failed: ${errorMessage(cause)}`,1)}process.platform==="win32"&&watchers.push(await watchWin32ChildIdentity(child,()=>state.shuttingDown,()=>{shutdown("rpc host child exit observed by identity watchdog",0)})),writeHostReady(publicSocket,policy.coldStart,policy.idleExitMs),await new Promise(()=>{})}if(!isBundledNode&&isCliModuleEntry(import.meta.url)){let launch=parseSupervisorArgs(process.argv.slice(2));launch||(writeStderrLine("usage: host-lifecycle.ts --socket <path> [host cli args...]"),process.exit(2)),runHostSupervisor(launch)}export{runtimeExecArgv,loopLagErrorMs,recordProcessLifetime,isHostCrash,readHostCrashRecords,classifyChildExit,noteEscalatedStop,resolveCliMainPath,resolveCliMainPathAsync,ClientOccupancy,acceptInternalConnection,INTERNAL_HOST_DIR_PREFIX,internalHostDirRoots,createInternalSocketPath,consumeHostWatchdogEnv,scrubHostWatchdogEnv,armHostWatchdog,INTERNAL_SUPERVISOR_FLAG,findInternalSupervisorArgs,parseSupervisorArgs,OWNER_WATCH_FD,keepOwnerPipe,resolveHostChildLaunch,spawnableChildLaunch,PublicRpcConnection,prepareSocketPath,runHostSupervisor};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{listHostEndpoints}from"./chunk-
|
|
2
|
+
import{listHostEndpoints}from"./chunk-FWXMMMCV.js";import{randomBytes}from"node:crypto";var MONITOR_ID_ALPHABET="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function allocateMonitorId(){let id="mon_",buffer=0,bits=0;for(let byte of randomBytes(10))for(buffer=buffer<<8|byte,bits+=8;bits>=5;)bits-=5,id+=MONITOR_ID_ALPHABET[buffer>>bits&31];return id}var STATUS_KINDS=new Set(["session_status","effect_status"]);function parseRpcTarget(target,selfDurableId){let trimmed=target.trim();return trimmed===""?{error:'target is empty; pass "children", "all" or a session id, path or st_ task id'}:trimmed==="children"?selfDurableId===void 0?{error:'target "children" needs a session with a durable id; save the session first, or watch "all"'}:{kind:"children",parent:selfDurableId}:trimmed==="all"?{kind:"all"}:trimmed.startsWith("st_")?{kind:"task",taskId:trimmed}:{kind:"id",id:trimmed}}function defaultEvents(target){return target.kind==="children"?["session_status","effect_status"]:["session_status"]}function subscriptionFor(target,events){let sessions=target.kind==="children"?{childrenOf:target.parent}:target.kind==="id"?{ids:[target.id]}:"all",content=events==="all"?"all":events.filter(kind=>!STATUS_KINDS.has(kind)),mirror=content==="all"?"all":content.length===0?void 0:content;return{sessions,include_workers:!0,include_context:target.kind==="children"||target.kind==="task",effects:events==="all"||events.includes("effect_status"),...mirror===void 0?{}:{mirror}}}function wantsRecord(events,exclude,type){return exclude.includes(type)?!1:events==="all"||events.includes(type)}function matchesTask(target,row){return target.kind!=="task"?!0:row.context?.task_id===target.taskId}async function endpointSockets(agentDir){return(await listHostEndpoints(agentDir)).map(endpoint=>endpoint.socket).filter(socket=>socket!==null)}export{allocateMonitorId,parseRpcTarget,defaultEvents,subscriptionFor,wantsRecord,matchesTask,endpointSockets};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import{listHostEndpoints}from"./chunk-FWXMMMCV.js";import{parseArgs,resolveSessionRuntime}from"./chunk-U67ML6CQ.js";import{PROBE_REQUEST_ID,connectAndAsk,isRecord as isRecord2,readAnswer,requestOnSocket}from"./chunk-EWOEVVQT.js";import{acquireOwnershipSafeLock,claimOwnerIsLive,hostChildAlive,isGenerationId,logUnknownHostIdentity,provenOwner,readDrainWatch,readGenerationRegistration,readHostRegistration,readSessionPathClaims,releaseGeneration,resolveHostPolicy,writeDrainRequest,writeStopIntent}from"./chunk-XUFUKDKJ.js";import{HOST_DAEMON_LAYOUT,canonicalEndpointPath,createHostDaemonPaths,generationPaths,hostDaemonDirectoryPaths,isRecord,parseJson,readFileOrUndefined,sameEndpoint,writeStateFile}from"./chunk-RHHBXIRN.js";import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV,OBSERVE_REQUEST_FIELD,gcRpcPublicKeys}from"./chunk-RVYSJBZ7.js";import{readSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{APP_NAME,VERSION,getAgentDir,isBunBinary}from"./chunk-7YO7VQZW.js";import{ProcessIdentityUnreadableError,parseDaemonPidFile,processIsLive,processMatchesPidFile,processStartTimeMs,readProcessStartTime}from"./chunk-7ASLQ243.js";var CALVER=/^(\d+)\.(\d+)\.(\d+)(?:-(\d+))?/;function engineBuildIdentityFrom(build){let match=CALVER.exec(build.version),epoch=Number.isSafeInteger(build.epoch)&&build.epoch!==void 0&&build.epoch>0?build.epoch:0,sha7=build.sha7??"";return{text:epoch===0?build.version:`${build.version}+${epoch}${sha7===""?"":`.${sha7}`}`,ordinal:[match?Number(match[1]):0,match?Number(match[2]):0,match?Number(match[3]):0,match?.[4]?Number(match[4]):0,epoch],scheme:epoch===0?"nodef":"epoch"}}var BUILT=engineBuildIdentityFrom({version:VERSION,epoch:typeof SENPI_BUILD_EPOCH=="number"?SENPI_BUILD_EPOCH:0,sha7:typeof SENPI_BUILD_SHA7=="string"?SENPI_BUILD_SHA7:""});function engineBuildIdentity(){return BUILT}function compareEngineOrdinal(a,b){for(let index=0;index<4;index++)if(a.ordinal[index]!==b.ordinal[index])return a.ordinal[index]>b.ordinal[index]?1:-1;return a.scheme!=="epoch"||b.scheme!=="epoch"||a.ordinal[4]===b.ordinal[4]?0:a.ordinal[4]>b.ordinal[4]?1:-1}import*as crypto from"node:crypto";var CUSTOM_UNSUPPORTED_CAPABILITY="custom_unsupported",EXTENSION_EVENTS_CAPABILITY="extension_events",EVAL_CELLS_CAPABILITY="eval_cells",AUTO_TITLE_SESSIONS_CAPABILITY="auto_title_sessions",CONTINUE_FROM_LEAF_CAPABILITY="continue_from_leaf",SESSION_HELD_CAPABILITY="session_held",RESUME_SESSION_CAPABILITY="resume_session",ATTENDED_CAPABILITY="attended",MEDIA_PLACEHOLDERS_CAPABILITY="media_placeholders",QUESTION_CAPABILITY="question",TOOL_BARRIER_CAPABILITY="tool_barrier",SESSION_RELOCATION_CAPABILITY="session_relocation",RETAIN_ON_DISCONNECT_CAPABILITY="retain_on_disconnect",DETACH_CONNECTION_CAPABILITY="detach_connection",INTERACTIVE_USER_CAPABILITY="interactive_user",TASK_PARENT_CAPABILITY="task_parent",SESSION_CONTEXT_CAPABILITY="session_context",SESSION_KIND_CAPABILITY="session_kind",SESSION_STATUS_CAPABILITY="session_status",AUTO_TITLE_PER_SESSION_CAPABILITY="auto_title_per_session",WARM_CAPABILITY="warm",DURABLE_SESSION_ID_CAPABILITY="durable_session_id",MOVED_PATH_GUARD_CAPABILITY="moved_path_guard",PROMPT_SURFACE_CAPABILITY="prompt_surface",BROWSER_ENGINE_CAPABILITY="browser_engine",RETRY_FALLBACK_PROFILE_CAPABILITY="retry_fallback_profile",RETRY_FALLBACK_COMMAND_CAPABILITY="retry_fallback_command",PROMPT_SURFACE_CHAT_CAPABILITY="prompt_surface_chat",RPC_CLIENT_CAPABILITIES_ENV="SENPI_RPC_CLIENT_CAPABILITIES";function parseClientCapabilities(value){return value?value.split(",").map(part=>part.trim()).filter(part=>part.length>0):[]}var DEFAULT_CUSTOM_EXTENSION_LABEL="custom UI component";function buildCustomUnsupportedRequest(capabilities,extensionName){if(!capabilities?.includes(CUSTOM_UNSUPPORTED_CAPABILITY))return;let name=extensionName.trim()||DEFAULT_CUSTOM_EXTENSION_LABEL;return{type:"extension_ui_request",id:crypto.randomUUID(),method:"custom_unsupported",extensionName:name}}var AUTH_KEY_VERIFY_CAPABILITY="auth_key_verify",QUEUED_MESSAGE_REVISION_CAPABILITY="queued_message_revision";import{createHash}from"node:crypto";import{existsSync}from"node:fs";import{readdir,readFile,realpath,stat}from"node:fs/promises";import{basename,dirname,join,relative,sep}from"node:path";import{fileURLToPath}from"node:url";var RUNTIME_IDENTITY_HANDOVER_CAPABILITY="runtime_identity_handover",RUNTIME_BUILD_ID=/^sha256:[0-9a-f]{64}$/,EXCLUDED_FILE=/\.(?:d\.[cm]?ts|map)$/,EXCLUDED_NAMES=new Set(["node_modules","runtime-manifest.json","runtime-snapshot.json"]),READ_CONCURRENCY=32;function parseRuntimeBuildId(value){return typeof value=="string"&&RUNTIME_BUILD_ID.test(value)?value:void 0}async function computeRuntimeBuildId(input){let source=input.source??loadedRuntimeSource(),plugins=await Promise.all(input.profile.extensions.map(path=>extensionDigest(path))),manifest={schema:1,flavour:source.flavour,platform:input.platform??process.platform,arch:input.arch??process.arch,engine:input.engine??engineBuildIdentity().text,runtime:await treeDigest(source.root),plugins:plugins.sort(),profile:{multi_session:input.profile.multi_session,session_runtime:input.profile.session_runtime}};return`sha256:${sha256(JSON.stringify(manifest))}`}function loadedRuntimeSource(){if(isBunBinary)return{flavour:"compiled",root:process.execPath};let moduleDir=dirname(fileURLToPath(import.meta.url)),packageRoot=nearestPackageRoot(moduleDir),[top,next]=relative(packageRoot,moduleDir).split(sep);return top==="dist"?{flavour:"packaged",root:join(packageRoot,next==="bundle"?join("dist","bundle"):"dist")}:{flavour:"dev",root:join(packageRoot,top??"")}}function nearestPackageRoot(start){for(let dir=start;;dir=dirname(dir)){if(existsSync(join(dir,"package.json")))return dir;if(dirname(dir)===dir)return start}}function extensionDigest(path){let name=basename(path);return name.startsWith(BUILTIN_PATH_PREFIX)?Promise.resolve(sha256(name)):treeDigest(path)}async function treeDigest(root){let files=[];(await stat(root)).isFile()?files.push(["",root]):await collect(await realpath(root),"",files,new Set);let digests=await mapLimited(files,READ_CONCURRENCY,async([path,file])=>[path,sha256(await readFile(file))]);return digests.sort(([a],[b])=>a<b?-1:a>b?1:0),sha256(JSON.stringify(digests))}async function collect(dir,prefix,files,seen){if(seen.has(dir))return;seen.add(dir);let entries=(await readdir(dir,{withFileTypes:!0})).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);for(let entry of entries){if(entry.name.startsWith(".")||EXCLUDED_NAMES.has(entry.name))continue;let path=join(dir,entry.name),name=prefix===""?entry.name:`${prefix}/${entry.name}`,kind=entry.isSymbolicLink()?await stat(path).catch(()=>{}):entry;kind!==void 0&&(kind.isDirectory()?await collect(await realpath(path),name,files,seen):kind.isFile()&&!EXCLUDED_FILE.test(entry.name)&&files.push([name,path]))}}async function mapLimited(items,limit,map){let results=new Array(items.length),next=0,worker=async()=>{for(let index=next++;index<items.length;index=next++)results[index]=await map(items[index])};return await Promise.all(Array.from({length:Math.min(limit,items.length)},worker)),results}function sha256(data){return createHash("sha256").update(data).digest("hex")}function parseHostProtocolInfo(data){if(!isRecord3(data)||typeof data.serverVersion!="string"||!Array.isArray(data.capabilities)||!data.capabilities.every(entry=>typeof entry=="string"))return;let ordinal=parseOrdinal(data.engineOrdinal),launchProfile=parseLaunchProfile(data.launch_profile),runtimeBuildId=parseRuntimeBuildId(data.runtimeBuildId);return{protocolVersion:typeof data.protocolVersion=="number"?data.protocolVersion:0,serverVersion:data.serverVersion,capabilities:data.capabilities,...(data.lifecycle==="ready"||data.lifecycle==="stopping")&&{lifecycle:data.lifecycle},...typeof data.instanceId=="string"&&{instanceId:data.instanceId},...typeof data.generation=="number"&&Number.isSafeInteger(data.generation)&&{generation:data.generation},...typeof data.engineVersion=="string"&&{engineVersion:data.engineVersion},...ordinal&&{engineOrdinal:ordinal},...launchProfile&&{launch_profile:launchProfile},...typeof data.memory_pressure=="boolean"&&{memory_pressure:data.memory_pressure},...runtimeBuildId!==void 0&&{runtimeBuildId},...typeof data.agentDir=="string"&&data.agentDir!==""&&{agentDir:data.agentDir},...isRecord3(data.handover)&&{handover:data.handover}}}function parseOrdinal(value){if(!(!Array.isArray(value)||value.length!==5||!value.every(part=>typeof part=="number")))return[value[0],value[1],value[2],value[3],value[4]]}function parseLaunchProfile(value){if(!isRecord3(value)||typeof value.profile_id!="string"||!isRecord3(value.core))return;let{extensions,multi_session,session_runtime}=value.core;if(!(!Array.isArray(extensions)||!extensions.every(entry=>typeof entry=="string"))&&typeof multi_session=="boolean"&&!(session_runtime!=="in-process"&&session_runtime!=="worker"))return{profile_id:value.profile_id,core:{extensions,multi_session,session_runtime}}}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function describeHostHolder(holder){let engine=holder.engineVersion===null?"an unrecorded engine":`engine ${holder.engineVersion}`,profile=holder.launchProfileId===null?"":`, launch profile ${holder.launchProfileId}`,writer=holder.writerPid===null||holder.writerPid===holder.pid?"":`, started by pid ${holder.writerPid}`;return`pid ${holder.pid}, ${engine}${profile}${writer}`}var HOST_PROTOCOL_VERSION=1,GENERATION_HANDOFF_CAPABILITY="generation_handoff",REQUIRED_HOST_CAPABILITIES=["multi_session",EXTENSION_EVENTS_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY],HostEnsureRefusedError=class extends Error{constructor(socket,reason,host,detail,holder){let heldBy=holder?` (held by ${describeHostHolder(holder)})`:"";super(`RPC socket ${socket} refused: ${reason} - ${refusalDetail(reason,host)}${detail?`: ${detail}`:""}${heldBy}`),this.name="HostEnsureRefusedError",this.socket=socket,this.reason=reason,this.detail=detail,this.holder=holder}};function refusalDetail(reason,host){switch(reason){case"protocol":return`the running host speaks protocol version ${host?.protocolVersion??"unknown"}, this build speaks ${HOST_PROTOCOL_VERSION}`;case"capability":{let missing=REQUIRED_HOST_CAPABILITIES.filter(capability=>!host?.capabilities.includes(capability));return`the running host is missing ${JSON.stringify(missing)}; it owns the socket, so no second host is started`}case"foreign_writer":return"another process registered the host on this socket; it accepts connections but did not answer as a host, and this one may not signal it - stop that host explicitly (host stop --force), then ensure again";case"legacy_host":return"a host from before the per-socket daemon directory is still running; it is drained and replaced only while it holds no session, and no second host is started beside it";case"host_busy":return"its socket accepts connections but did not answer inside the probe budget: a live host under load, which is never ended to make room for a replacement";case"host_stopping":return"this generation is stopping; wait for its exit before launching a successor";case"endpoint_occupied":return"another process accepts connections on this socket but does not answer as a host, and no host registration names it; it is never removed while it listens, so quit the process holding it and ensure again";case"host_stalled":return"nothing reaches its socket, but its process is alive and its own loop-lag watchdog measured a recent stall: a stalled host is still serving its sessions, so it is neither stopped nor replaced";default:return assertNever(reason)}}function decideHostAction(client,host,policy){if(host===void 0)return{action:"start",reason:client.startedByUs?"restart_own_host":"no_host",upgradeable:!1};if(host.lifecycle==="stopping")return{action:"refuse",reason:"host_stopping",upgradeable:!1};if(host.protocolVersion!==client.protocolVersion)return{action:"refuse",reason:"protocol",upgradeable:!1};if(!client.requiredCapabilities.every(capability=>host.capabilities.includes(capability)))return policy==="fallback"?{action:"fallback",reason:"capability",upgradeable:!1}:{action:"refuse",reason:"capability",upgradeable:!1};let upgradeable=client.platform!=="win32"&&host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY);if(policy==="fallback"&&host.engineVersion!==client.identity.text)return{action:"fallback",reason:"engine_mismatch",upgradeable};let warning=profileWarning(client,host);return client.platform==="win32"?{action:"reuse",reason:"win32_attach_only",upgradeable:!1,...warning&&{warning}}:upgradeable?policy==="upgrade"&&client.launchProfile&&host.launch_profile&&supersedes(client,host)?{action:"handoff",reason:sameRelease(client.identity.ordinal,host.engineOrdinal)?"profile":"newer_engine",upgradeable:!0}:{action:"reuse",reason:"compatible",upgradeable,...warning&&{warning}}:{action:"reuse",reason:"handoff_unsupported",upgradeable:!1,...warning&&{warning}}}function supersedes(client,host){if(host.engineOrdinal===void 0)return!1;let hostIdentity={text:host.engineVersion??"",ordinal:host.engineOrdinal,scheme:host.engineOrdinal[4]>0?"epoch":"nodef"};return compareEngineOrdinal(client.identity,hostIdentity)<=0?!1:covers(client.launchProfile,host.launch_profile)}function profileWarning(client,host){if(client.launchProfile===void 0||host.launch_profile===void 0)return"profile_mismatch_attached";if(client.launchProfile.profile_id===host.launch_profile.profile_id)return;let clientCoversHost=covers(client.launchProfile,host.launch_profile);if(!(clientCoversHost&&covers(host.launch_profile,client.launchProfile)))return clientCoversHost?"profile_mismatch_attached":"profile_narrower_attached"}function extensionRole(extension){let segments=extension.split(/[\\/]+/),pluginAt=segments.lastIndexOf("plugin");return pluginAt<0?extension:segments.slice(pluginAt).join("/")}function covers(candidate,running){if(candidate===void 0||running===void 0)return!1;let candidateRoles=new Set(candidate.core.extensions.map(extensionRole));return running.core.extensions.every(extension=>candidateRoles.has(extensionRole(extension)))}function sameRelease(candidate,running){return running!==void 0&&candidate.slice(0,4).every((part,index)=>part===running[index])}function assertNever(value){throw new Error(`unreachable host decision: ${JSON.stringify(value)}`)}import{createHash as createHash2,randomUUID as randomUUID2}from"node:crypto";import{resolve}from"node:path";var INSTANCE_ID=resolveInstanceId(process.env[HOST_INSTANCE_ID_ENV]);function resolveInstanceId(value){return value!==void 0&&value.trim()!==""?value:randomUUID2()}function hostInstanceId(){return INSTANCE_ID}var cachedProfile;function hostGeneration(env){let value=env[HOST_GENERATION_ENV];return value!==void 0&&/^\d+$/.test(value)?Number(value):0}function hostLaunchProfile(argv,cwd){let parsed=parseArgs([...argv],{grokNeoEnabled:!1}),core={extensions:[...new Set((parsed.extensions??[]).map(path=>resolve(cwd,path)))].sort(),multi_session:parsed.multiSession===!0,session_runtime:resolveSessionRuntime(parsed)},canonical=JSON.stringify({extensions:core.extensions,multi_session:core.multi_session,session_runtime:core.session_runtime});return{profile_id:createHash2("sha256").update(canonical).digest("hex"),core}}function socketHostLaunchProfile(hostArgs,cwd){return hostLaunchProfile(["--mode","rpc","--multi-session","--listen","unix://",...hostArgs],cwd)}function protocolIdentity(agentDir=resolve(getAgentDir())){cachedProfile??=hostLaunchProfile(process.argv.slice(2),process.cwd());let build=engineBuildIdentity();return{instanceId:INSTANCE_ID,generation:hostGeneration(process.env),engineVersion:build.text,engineOrdinal:build.ordinal,launch_profile:cachedProfile,agentDir}}function holdAttachment(socket){return socket.removeAllListeners("data"),socket.resume(),socket.on("error",()=>socket.destroy()),socket.unref(),{release:()=>socket.destroy()}}var DEFAULT_PROBE_TIMEOUT_MS=1e4;function probeHost(options){return probeProtocolInfo(options.socket,options.timeoutMs??DEFAULT_PROBE_TIMEOUT_MS,options)}async function probeProtocolInfo(socketPath,timeoutMs,options={}){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info"},timeoutMs,options);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function observeProtocolInfo(socketPath,timeoutMs,options={}){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},timeoutMs,options);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function holdProtocolInfo(socketPath,timeoutMs,options={}){let outcome=await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"get_protocol_info"},timeoutMs,!0,options),info=outcome.answer===void 0?void 0:parseHostProtocolInfo(outcome.answer);if(outcome.kept===void 0)return;let hold=holdAttachment(outcome.kept);if(info!==void 0)return{info,hold};hold.release()}async function probeSocketReachable(socketPath,timeoutMs,options={}){return(await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"get_protocol_info"},timeoutMs,!1,options)).connected}async function probeSessionCount(socketPath,timeoutMs,options={}){return sessionCountOf(await requestOnSocket(socketPath,{type:"list_sessions",include_workers:!0},timeoutMs,options))}async function holdSessionCount(socketPath,timeoutMs,options={}){let outcome=await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"list_sessions",include_workers:!0},timeoutMs,!0,options),kept=outcome.kept;if(kept===void 0)return;let sessions=sessionCountOf(outcome.answer);if(sessions===void 0){kept.destroy();return}let asked=0;return{sessions,recount:recountTimeoutMs=>askAgain(kept,`${PROBE_REQUEST_ID}-recount-${++asked}`,recountTimeoutMs),close:()=>kept.destroy()}}function askAgain(socket,id,timeoutMs){return new Promise(resolveCount=>{let buffer="",finish=count=>{clearTimeout(timeout),socket.off("data",onData),socket.off("close",onClose),resolveCount(count)},onClose=()=>finish(void 0),onData=chunk=>{buffer+=chunk.toString("utf8");for(let newline=buffer.indexOf(`
|
|
3
|
+
`);newline!==-1;newline=buffer.indexOf(`
|
|
4
|
+
`)){let answer=readAnswer(buffer.slice(0,newline),id);if(buffer=buffer.slice(newline+1),answer!==void 0){finish(sessionCountOf(answer));return}}},timeout=setTimeout(()=>finish(void 0),timeoutMs);if(socket.destroyed){finish(void 0);return}socket.on("data",onData),socket.once("close",onClose),socket.write(`${JSON.stringify({id,type:"list_sessions",include_workers:!0})}
|
|
5
|
+
`)})}function sessionCountOf(reply){return isRecord2(reply)&&Array.isArray(reply.sessions)?reply.sessions.length:void 0}import{createHash as createHash3}from"node:crypto";import{mkdir,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{dirname as dirname2,join as join2}from"node:path";var LOCK_BUSY_WAIT_MS=100;function hostEnsureLockTarget(socket){return join2(tmpdir(),"senpi-rpc-host-locks",createSocketLockName(socket))}async function acquireHostEnsureLock(socket,waitMs){let lockTarget=hostEnsureLockTarget(socket);return await mkdir(dirname2(lockTarget),{recursive:!0}),await writeFile(lockTarget,"",{flag:"a",mode:384}),acquireOwnershipSafeLock(`${lockTarget}.lock`,hostEnsureLockOptions(waitMs))}function hostEnsureLockOptions(waitMs){return{retries:{retries:Math.ceil(waitMs/LOCK_BUSY_WAIT_MS),minTimeout:20,maxTimeout:LOCK_BUSY_WAIT_MS}}}function createSocketLockName(socket){return createHash3("sha256").update(socketLockAddress(socket),"utf8").digest("hex").slice(0,32)}function socketLockAddress(socket){return process.platform==="win32"||socket.startsWith("\0")?resolveSocketTransportAddress(socket,process.platform):canonicalEndpointPath(socket)}import{randomUUID as randomUUID3}from"node:crypto";import{access,link,readdir as readdir2,rm}from"node:fs/promises";async function electPointer(paths,options={}){let text=await readFileOrUndefined(paths.pointerFile).catch(()=>{});if(text!==void 0){let instanceId=parseJson(text)?.instance_id;return typeof instanceId=="string"?{state:"current",instanceId,candidates:[]}:{state:"missing",instanceId:null,candidates:[]}}let candidates=await provenLiveGenerations(paths),ids=candidates.map(candidate=>candidate.instanceId),[only]=candidates;return only===void 0||candidates.length>1||options.write===!1?{state:"missing",instanceId:null,candidates:ids}:await linkPointer(paths,only)?{state:"elected",instanceId:only.instanceId,candidates:ids}:electPointer(paths,{write:!1})}async function provenLiveGenerations(paths){let found=[];for(let instanceId of(await readdir2(paths.generationsDir).catch(()=>[])).sort()){let generation=generationPaths(paths,instanceId);if(await exists(generation.stopIntentFile)||await exists(generation.drainRequestFile))continue;let text=await readFileOrUndefined(generation.pidFile).catch(()=>{}),record=text===void 0?void 0:parseDaemonPidFile(text),parsed=parseJson(text);if(record===void 0||record.processStartTime===null||parsed?.instance_id!==instanceId||typeof parsed.socket!="string"||!sameEndpoint(parsed.socket,paths.socket))continue;let identity={pid:record.pid,processStartTime:record.processStartTime};await processMatchesPidFile(identity,readProcessStartTime).catch(()=>!1)&&found.push({instanceId,writer:parsed.writer})}return found}async function linkPointer(paths,candidate){let staged=`${paths.pointerFile}.elect-${process.pid}-${randomUUID3()}.tmp`;try{return await writeStateFile(staged,{layout:HOST_DAEMON_LAYOUT,instance_id:candidate.instanceId,generation_dir:generationPaths(paths,candidate.instanceId).relativeDir,...isRecord(candidate.writer)&&{writer:candidate.writer}}),await link(staged,paths.pointerFile),!0}catch{return!1}finally{await rm(staged,{force:!0}).catch(()=>{})}}async function exists(path){return access(path).then(()=>!0,()=>!1)}import{dirname as dirname3,join as join3}from"node:path";var LEGACY_PROBE_TIMEOUT_MS=1e4,DRAIN_POLL_MS=50;async function retireIdleLegacyHost(paths,probe,drainTimeoutMs=LEGACY_PROBE_TIMEOUT_MS){let judged=await judgeLegacyHost(paths,probe);if(judged.verdict==="absent")return;if(judged.verdict==="held")return judged.detail;let{record,socket}=judged.host;if(!await drainAndWait(record,probe,drainTimeoutMs))return`pid ${record.pid} (${socket}) was asked to drain and is still running after ${drainTimeoutMs}ms; retry once it exits`}async function readLegacyHost(paths){let text=await readFileOrUndefined(paths.legacyPidFile),record=text===void 0?void 0:parseDaemonPidFile(text);if(record===void 0)return;let stamped=parseJson(text)?.socket;return{record,socket:typeof stamped=="string"?stamped:join3(dirname3(paths.flatDir),"rpc","rpc.sock")}}async function provenLegacyOwner(paths,socket){let legacy=await readLegacyHost(paths),startTime=legacy?.record.processStartTime;if(!legacy||startTime===null||startTime===void 0||!sameEndpoint(legacy.socket,socket))return;let identity={pid:legacy.record.pid,processStartTime:startTime};return await processMatchesPidFile(identity,readProcessStartTime).catch(error=>(error instanceof ProcessIdentityUnreadableError&&logUnknownHostIdentity("legacy_host.pid",identity.pid),!1))?identity:void 0}async function judgeLegacyHost(paths,probe,platform=process.platform){let host=await readLegacyHost(paths);if(host===void 0)return{verdict:"absent"};let{pid}=host.record,identity=await processMatchesPidFile(host.record,probe).then(owns=>owns?"proven":"gone",error=>{if(error instanceof ProcessIdentityUnreadableError)return"unreadable";throw error});if(identity==="gone")return{verdict:"absent"};let where=`pid ${pid} (${host.socket})`;if(identity==="unreadable")return logUnknownHostIdentity("legacy_host.pid",pid),{verdict:"held",detail:`${where} cannot be proven to be the process its record names; stop it by hand`};if(platform==="win32")return{verdict:"held",detail:`${where} cannot be drained on win32; it exits once idle, then retry`};let protocol=await probeProtocolInfo(host.socket,LEGACY_PROBE_TIMEOUT_MS);if(!protocol?.capabilities.includes(GENERATION_HANDOFF_CAPABILITY))return{verdict:"held",detail:`${where} ${protocol?"cannot drain":"does not answer"}; it is never signalled - stop it by hand, then retry`};let sessions=await probeSessionCount(host.socket,LEGACY_PROBE_TIMEOUT_MS);return sessions===0?{verdict:"idle",host}:{verdict:"held",detail:busyLegacyHostDetail(pid,host.socket,sessions)}}function busyLegacyHostDetail(pid,socket,sessions){return`pid ${pid} (${socket}) holds ${describeSessions(sessions)}; run \`${APP_NAME} host stop --drain --socket ${socket}\` to let it finish that work and exit, then retry`}function describeSessions(sessions){return sessions===void 0?"an unknown number of sessions":`${sessions} open session${sessions===1?"":"s"}`}async function drainAndWait(record,probe,timeoutMs){try{process.kill(record.pid,"SIGUSR1")}catch(error){if(!(error instanceof Error&&"code"in error&&error.code==="ESRCH"))throw error}let stillRunning=()=>processMatchesPidFile(record,probe,processIsLive,{attempts:1}).catch(error=>{if(error instanceof ProcessIdentityUnreadableError)return!0;throw error}),deadline=Date.now()+timeoutMs;for(;await stillRunning();){if(Date.now()>deadline)return!1;await new Promise(resolve2=>setTimeout(resolve2,DRAIN_POLL_MS))}return!0}var EXIT_POLL_MS=100;async function drainHost(paths,options){let named=options.instanceId;if(named!==void 0&&!isGenerationId(named))return{action:"refuse",reason:"unknown_owner"};let registered=named===void 0?await readHostRegistration(paths):await readGenerationRegistration(paths,named),owner=await provenOwner(registered,options.socket);if(owner!==void 0){let generation=generationPaths(paths,owner.instanceId);if((await readDrainWatch(generation.drainWatchFile))?.pid===owner.pid)return await writeDrainRequest(generation.drainRequestFile,{sender:{pid:process.pid,kind:"stop"},reason:"operator_drain"}).catch(cause=>{if(cause.code!=="ENOENT")throw cause}),drained({...owner},options.waitMs)}if(named!==void 0&&owner===void 0)return{action:"refuse",reason:"unknown_owner"};let pid=owner?.pid??(await provenLegacyOwner(paths,options.socket))?.pid;if(pid===void 0)return{action:"refuse",reason:"unknown_owner"};let host=await probeProtocolInfo(options.socket,options.timeoutMs??1e4),answersAsTarget=named===void 0||host?.instanceId===named;return!host?.capabilities.includes(GENERATION_HANDOFF_CAPABILITY)||!answersAsTarget||process.platform==="win32"?{action:"refuse",reason:"drain_unsupported"}:(signalDrain(pid),drained(owner??{pid,processStartTime:void 0},options.waitMs))}async function drained(owner,waitMs){let base={action:"drained",pid:owner.pid,...owner.instanceId&&{instanceId:owner.instanceId}};return waitMs===void 0?base:{...base,exited:await waitForExit(owner,waitMs)}}async function waitForExit(owner,waitMs){let deadline=Date.now()+waitMs;for(;;){if(await exitedNow(owner))return!0;if(Date.now()>=deadline)return!1;await new Promise(resolve2=>setTimeout(resolve2,EXIT_POLL_MS))}}async function exitedNow(owner){if(!processIsLive(owner.pid))return!0;if(owner.processStartTime===void 0)return!1;let identity={pid:owner.pid,processStartTime:owner.processStartTime};return processMatchesPidFile(identity,readProcessStartTime).then(same=>!same,error=>{if(error instanceof ProcessIdentityUnreadableError)return!1;throw error})}function signalDrain(pid){try{process.kill(pid,"SIGUSR1")}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ESRCH")return;throw error}}import{stat as stat2}from"node:fs/promises";function processStartTimeIsUnreadable(){return process.platform==="win32"}var STOP_START_TIME_BUDGET_MS=1e4;function readLiveStartTime(pid){return readProcessStartTime(pid,process.platform,STOP_START_TIME_BUDGET_MS)}async function startedBeforeRegistration(pid,registrationFile){let live=await readLiveStartTime(pid).catch(()=>{}),startedMs=live===void 0?void 0:processStartTimeMs(live);if(startedMs===void 0)return!1;let written=await stat2(registrationFile).catch(()=>{});return written!==void 0&&startedMs<=written.mtimeMs}function parseHostStopGeneration(text){let value=parseJson(text);if(!(!value||typeof value.instanceId!="string"||value.instanceId.length===0||typeof value.generation!="number"||!Number.isSafeInteger(value.generation)||value.generation<0||typeof value.pid!="number"||!Number.isSafeInteger(value.pid)||value.pid<=0||!(value.processStartTime===null||typeof value.processStartTime=="string"&&value.processStartTime.length>0)))return{instanceId:value.instanceId,generation:value.generation,pid:value.pid,processStartTime:value.processStartTime}}function compareStopGeneration(registered,expected){if(registered?.instanceId!==expected.instanceId||registered.generation!==expected.generation||registered.record.pid!==expected.pid)return"stale";let recorded=registered.record.processStartTime;return recorded!==null&&expected.processStartTime!==null?recorded===expected.processStartTime?"proven":"stale":recorded===null&&expected.processStartTime===null&&processStartTimeIsUnreadable()?"bound_without_start_time":"unprovable"}async function stopHost(options){if(options.expectedGeneration!==void 0&&options.drain===!0)throw new TypeError("stopHost: expectedGeneration binds a hard stop and cannot be combined with drain");if(options.expectedGeneration===void 0)return stopHostLocked(options);let release=await acquireHostEnsureLock(options.socket,3e4);try{return await stopHostLocked(options)}finally{await release()}}async function stopHostLocked(options){let paths=createHostDaemonPaths({socket:options.socket,...options.agentDir?{agentDir:options.agentDir}:{}});await electPointer(paths);let expected=options.expectedGeneration;if(expected!==void 0){let refusal=generationRefusal(compareStopGeneration(await readHostRegistration(paths),expected));if(refusal!==void 0)return refusal}if(options.drain===!0)return drainHost(paths,{socket:options.socket,...options.instanceId!==void 0&&{instanceId:options.instanceId},...options.waitMs!==void 0&&{waitMs:options.waitMs},...options.timeoutMs!==void 0&&{timeoutMs:options.timeoutMs}});let owner=expected===void 0?await provenOwner(await readHostRegistration(paths),options.socket):void 0;if(expected===void 0&&!owner)return{action:"refuse",reason:"unknown_owner"};let host=await probeProtocolInfo(options.socket,options.timeoutMs??1e4),sessions=await probeSessionCount(options.socket,options.timeoutMs??1e4);if(options.force!==!0&&host!==void 0&&sessions!==void 0&&sessions>0)return{action:"refuse",reason:"sessions_live"};if(options.requireAnswer===!0&&(host===void 0||sessions===void 0))return{action:"refuse",reason:"sessions_live"};let target=expected===void 0?owner:await recheckedTarget(paths,options.socket,expected,host);return target===void 0?{action:"refuse",reason:"unknown_owner"}:"action"in target?target:(await writeStopIntent(generationPaths(paths,target.instanceId),{sender:{pid:process.pid,kind:"stop"},targetPid:target.pid,reason:"operator_stop",signal:"SIGTERM",at:new Date().toISOString()}),signalGeneration(target.pid,"SIGTERM")||await releaseGeneration(paths,{instanceId:target.instanceId,pid:target.pid}),{action:"stopped",pid:target.pid})}function generationRefusal(match){if(match==="stale")return{action:"refuse",reason:"stale_generation"};if(match==="unprovable")return{action:"refuse",reason:"unknown_owner"}}async function staleStopGeneration(socket,agentDir,expected){let paths=createHostDaemonPaths({socket,...agentDir?{agentDir}:{}});return generationRefusal(compareStopGeneration(await readHostRegistration(paths),expected))}async function recheckedTarget(paths,socket,expected,host){let current=await readHostRegistration(paths),match=compareStopGeneration(current,expected),refusal=generationRefusal(match);if(refusal!==void 0)return refusal;if(!(match==="proven"&&!await provenOwner(current,socket))){if(match==="bound_without_start_time"){if(current?.socket!==void 0&&!sameEndpoint(current.socket,socket)||!await startedBeforeRegistration(expected.pid,generationPaths(paths,expected.instanceId).pidFile))return;if(host?.instanceId!==void 0&&host.instanceId!==expected.instanceId)return{action:"refuse",reason:"stale_generation"}}return{pid:expected.pid,instanceId:expected.instanceId}}}function signalGeneration(pid,signal){try{return process.kill(pid,signal),!0}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ESRCH")return!1;throw error}}import{lstat as lstat2,rm as rm2}from"node:fs/promises";import{dirname as dirname5,join as join6}from"node:path";import{lstat,readdir as readdir3}from"node:fs/promises";import{createConnection}from"node:net";import{basename as basename2,dirname as dirname4,join as join4}from"node:path";var SOCKET_PROBE_TIMEOUT_MS=2e3;async function endpointInUse(paths,socket){if(await anyGenerationLive(paths))return{inUse:"live_generation"};for(let claim of await readSessionPathClaims(paths.reservationsDir))if(await claimOwnerIsLive(claim.owner))return{inUse:"live_claim"};let silence=await socketSilence(socket);if(silence===void 0)return{inUse:"reachable"};let successors=(await socketSiblings(socket)).filter(name=>name.startsWith(`${basename2(socket)}.next-`));for(let successor of successors)if(await socketSilence(join4(dirname4(socket),successor))===void 0)return{inUse:"reachable"};return{inUse:void 0,silence}}async function socketSiblings(socket){let name=basename2(socket);return(await readdir3(dirname4(socket)).catch(()=>[])).filter(entry=>entry.startsWith(`${name}.next-`)||entry.startsWith(`${name}.shield-`))}async function anyGenerationLive(paths){for(let instanceId of await readdir3(paths.generationsDir).catch(()=>[])){if(await hostChildAlive(generationPaths(paths,instanceId)))return!0;let record=generationRecord(await readFileOrUndefined(generationPaths(paths,instanceId).pidFile));if(record!==void 0&&await recordIsLive(record))return!0}return!1}function generationRecord(text){if(text===void 0)return;let record=parseDaemonPidFile(text);if(record!==void 0)return record;let pid=parseJson(text)?.pid;return typeof pid=="number"&&Number.isInteger(pid)&&pid>0?{pid,processStartTime:null}:void 0}async function recordIsLive(record){try{return await processMatchesPidFile(record)}catch(error){if(error instanceof ProcessIdentityUnreadableError)return!0;throw error}}async function socketSilence(socket){let secret;return process.platform==="win32"&&(secret=await readSocketSecret(socketSecretPath(socket)).catch(()=>{}),secret===void 0)?"socket_absent":new Promise(resolveProbe=>{let connection=createConnection(resolveSocketTransportAddress(socket,process.platform,secret)),finish=value=>{clearTimeout(timeout),connection.destroy(),resolveProbe(value)},timeout=setTimeout(()=>finish(void 0),SOCKET_PROBE_TIMEOUT_MS);connection.once("connect",()=>finish(void 0)),connection.once("error",error=>{error.code==="ECONNREFUSED"?refusedBySocket(socket).then(finish):error.code==="ENOENT"?finish("socket_absent"):finish(void 0)})})}async function refusedBySocket(socket){if(process.platform==="win32"||socket.startsWith("\0"))return"socket_refused";try{return(await lstat(socket)).isSocket()?"socket_refused":void 0}catch(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"?"socket_absent":void 0}}import{execFile}from"node:child_process";import{readdir as readdir4,readFile as readFile2,readlink,realpath as realpath2}from"node:fs/promises";import{join as join5}from"node:path";var LSOF_TIMEOUT_MS=2e3,LINUX_ACCEPTCON_FLAG=65536;async function countPublicClients(supervisorPid,socket){let names=new Set([socket,await realpath2(socket).catch(()=>socket)]),descriptors=process.platform==="darwin"?await darwinDescriptors(supervisorPid,names):process.platform==="linux"?await linuxDescriptors(supervisorPid,names):void 0;if(!(descriptors===void 0||descriptors.listeners===0))return descriptors.total-descriptors.listeners}function darwinDescriptors(pid,names){return new Promise(resolve2=>{execFile("lsof",["-a","-p",String(pid),"-U","-w","-F","n"],{timeout:LSOF_TIMEOUT_MS},(error,stdout)=>{if(error)return resolve2(void 0);let total=stdout.split(`
|
|
6
|
+
`).filter(line=>line.startsWith("n")&&names.has(line.slice(1))).length;resolve2({total,listeners:total>0?1:0})})})}async function linuxDescriptors(pid,names){try{let inodes=new Set;for(let fd of await readdir4(join5("/proc",String(pid),"fd"))){let target=await readlink(join5("/proc",String(pid),"fd",fd)).catch(()=>""),inode=/^socket:\[(\d+)\]$/.exec(target)?.[1];inode!==void 0&&inodes.add(inode)}let total=0,listeners=0;for(let line of(await readFile2("/proc/net/unix","utf8")).split(`
|
|
7
|
+
`).slice(1)){let fields=line.trim().split(/\s+/),[flags,inode,path]=[fields[3],fields[6],fields[7]];inode===void 0||path===void 0||!inodes.has(inode)||!names.has(path)||(total+=1,(Number.parseInt(flags??"0",16)&LINUX_ACCEPTCON_FLAG)!==0&&(listeners+=1))}return{total,listeners}}catch{return}}var STALE_ENGINE_GRACE_MS=10*6e4,PROBE_TIMEOUT_MS=2e3;async function judgeStaleEngine(socket,agentDir,client,options={}){let paths=createHostDaemonPaths({socket,agentDir}),owner=await provenOwner(await readHostRegistration(paths),socket);if(owner===void 0)return keep("stale_unproven_owner");let clients=await countPublicClients(owner.pid,socket),info=await observeProtocolInfo(socket,PROBE_TIMEOUT_MS);if(info===void 0)return keep("stale_unreachable");let hostOrdinal=info.engineOrdinal,hostIdentity=hostOrdinal===void 0?void 0:{text:info.engineVersion??"",ordinal:hostOrdinal,scheme:hostOrdinal[4]>0?"epoch":"nodef"};if(hostIdentity===void 0||compareEngineOrdinal(hostIdentity,client)!==-1)return keep("stale_not_older");let policy=resolveHostPolicy(parseJson(await readFileOrUndefined(paths.settingsFile)),{});if(policy.coldStart==="persistent")return keep("stale_persistent");if(await observedSessionCount(socket)!==0)return keep("stale_sessions");if((await readSessionPathClaims(paths.reservationsDir)).length>0)return keep("stale_claims");let startedAt=processStartTimeMs(owner.processStartTime),now=(options.now??Date.now)();return startedAt===void 0||now-startedAt<policy.idleExitMs+(options.graceMs??STALE_ENGINE_GRACE_MS)?keep("stale_young"):clients!==0?keep("stale_clients"):{stale:!0,pid:owner.pid}}function keep(reason){return{stale:!1,reason}}async function observedSessionCount(socket){let reply=await requestOnSocket(socket,{type:"list_sessions",include_workers:!0,[OBSERVE_REQUEST_FIELD]:!0},PROBE_TIMEOUT_MS);if(typeof reply!="object"||reply===null)return;let sessions=Reflect.get(reply,"sessions");return Array.isArray(sessions)?sessions.length:void 0}var GC_LOCK_WAIT_MS=2e3;async function gcHostEndpoints(agentDir,options={}){process.platform!=="win32"&&await gcRpcPublicKeys(agentDir);let removed=[],stopped=[],kept=[],wanted=kind=>options.kinds===void 0||options.kinds.includes(kind),legacy=wanted("rpc_host")?await legacyFlatDirectory(agentDir):void 0;legacy!==void 0&&kept.push({socket:null,dir:legacy,reason:"legacy_layout"});for(let endpoint of await listHostEndpoints(agentDir)){if(!wanted(endpoint.endpoint_kind))continue;if(endpoint.socket===null){kept.push({socket:null,dir:endpoint.dir,reason:"unknown_identity"});continue}let entry={socket:endpoint.socket,dir:endpoint.dir};try{let outcome=await gcEndpoint(endpoint.socket,endpoint.dir,options);"stopped"in outcome?stopped.push({...entry,reason:"stale_old_engine",pid:outcome.pid}):outcome.removed?outcome.skipped.length===0?removed.push({...entry,reason:outcome.reason}):removed.push({...entry,reason:outcome.reason,skipped:outcome.skipped}):kept.push({...entry,reason:outcome.reason})}catch(error){kept.push({...entry,reason:"failed",error:error instanceof Error?error.message:String(error)})}}return stopped.length===0?{removed,kept}:{removed,stopped,kept}}async function gcEndpoint(socket,dir,options){let release=await acquireEnsureLock(socket);if(release===void 0)return{removed:!1,reason:"locked"};try{await options._test?.afterLockAcquired?.(socket);let evidence=await endpointInUse(hostDaemonDirectoryPaths(dir),socket);if(evidence.inUse==="live_claim"||evidence.inUse!==void 0&&options.staleEngine===void 0)return{removed:!1,reason:evidence.inUse};if(evidence.inUse!==void 0)return await stopIfStale(socket,dir,evidence.inUse,options.staleEngine??{});let skipped=await removeEndpoint(socket,dir);return{removed:!0,reason:evidence.silence,skipped}}finally{await release()}}var NOT_A_CANDIDATE=new Set(["stale_unproven_owner","stale_unreachable","stale_not_older"]),STALE_STOP_TIMEOUT_MS=2e3;async function stopIfStale(socket,dir,inUse,options){let agentDir=dirname5(dirname5(dir)),verdict=await judgeStaleEngine(socket,agentDir,options.client??engineBuildIdentity(),options);if(!verdict.stale)return{removed:!1,reason:NOT_A_CANDIDATE.has(verdict.reason)?inUse:verdict.reason};let result=await stopHost({socket,agentDir,timeoutMs:STALE_STOP_TIMEOUT_MS,requireAnswer:!0});return result.action==="refuse"?{removed:!1,reason:result.reason==="unknown_owner"?"stale_unproven_owner":"stale_sessions"}:{removed:!1,stopped:!0,pid:result.pid}}async function removeEndpoint(socket,dir){let skipped=[];for(let sibling of await socketSiblings(socket)){let path=join6(dirname5(socket),sibling),entry=await lstat2(path).catch(error=>{if(!(error instanceof Error&&"code"in error&&error.code==="ENOENT"))throw error});entry?.isDirectory()?skipped.push({path,type:"directory"}):entry!==void 0&&await rm2(path,{force:!0})}return await rm2(socket,{force:!0}),await rm2(dir,{recursive:!0,force:!0}),skipped}async function acquireEnsureLock(socket){return acquireHostEnsureLock(socket,GC_LOCK_WAIT_MS).catch(()=>{})}async function legacyFlatDirectory(agentDir){let flatDir=join6(agentDir,"rpc-host-daemon");return parseJson(await readFileOrUndefined(join6(flatDir,"layout.json")).catch(()=>{}))?.layout===HOST_DAEMON_LAYOUT?void 0:await readFileOrUndefined(join6(flatDir,"host.pid")).catch(()=>{})!==void 0?flatDir:void 0}export{engineBuildIdentityFrom,engineBuildIdentity,compareEngineOrdinal,CUSTOM_UNSUPPORTED_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,EVAL_CELLS_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,SESSION_HELD_CAPABILITY,RESUME_SESSION_CAPABILITY,ATTENDED_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,QUESTION_CAPABILITY,TOOL_BARRIER_CAPABILITY,SESSION_RELOCATION_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,DETACH_CONNECTION_CAPABILITY,INTERACTIVE_USER_CAPABILITY,TASK_PARENT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_STATUS_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,WARM_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,PROMPT_SURFACE_CAPABILITY,BROWSER_ENGINE_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RETRY_FALLBACK_COMMAND_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,RPC_CLIENT_CAPABILITIES_ENV,parseClientCapabilities,DEFAULT_CUSTOM_EXTENSION_LABEL,buildCustomUnsupportedRequest,AUTH_KEY_VERIFY_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,computeRuntimeBuildId,parseHostProtocolInfo,HOST_PROTOCOL_VERSION,GENERATION_HANDOFF_CAPABILITY,REQUIRED_HOST_CAPABILITIES,HostEnsureRefusedError,decideHostAction,hostInstanceId,hostGeneration,hostLaunchProfile,socketHostLaunchProfile,protocolIdentity,DEFAULT_PROBE_TIMEOUT_MS,probeHost,probeProtocolInfo,observeProtocolInfo,holdProtocolInfo,probeSocketReachable,holdSessionCount,hostEnsureLockTarget,acquireHostEnsureLock,hostEnsureLockOptions,anyGenerationLive,judgeStaleEngine,electPointer,retireIdleLegacyHost,provenLegacyOwner,busyLegacyHostDetail,describeSessions,parseHostStopGeneration,stopHost,staleStopGeneration,signalGeneration,gcHostEndpoints,gcEndpoint};
|