@code-yeongyu/senpi 2026.11.10-3 → 2026.11.11
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 +29 -0
- package/dist/bundle/chunks/{chunk-Z2C5N2LM.js → chunk-5F2XC6UC.js} +2 -2
- package/dist/bundle/chunks/{chunk-H3VJVKUK.js → chunk-5PIZWSNG.js} +2 -2
- package/dist/bundle/chunks/{chunk-DEQLHN2J.js → chunk-BPEA5SWW.js} +1 -1
- package/dist/bundle/chunks/{chunk-DIHIEJFV.js → chunk-BUDJLVMF.js} +1 -1
- package/dist/bundle/chunks/{chunk-47T6YMI2.js → chunk-IBDAV2AL.js} +1 -1
- package/dist/bundle/chunks/{chunk-O5WJVIEU.js → chunk-J4ADZ2OK.js} +1 -1
- package/dist/bundle/chunks/{chunk-T2SMQPRE.js → chunk-K3GAGIPX.js} +1 -1
- package/dist/bundle/chunks/{chunk-HZDKQOWB.js → chunk-L6DF5G6K.js} +1 -1
- package/dist/bundle/chunks/{chunk-E266ORGA.js → chunk-LJFQYCFH.js} +1 -1
- package/dist/bundle/chunks/{chunk-DHAAWL2H.js → chunk-NRZAJUUO.js} +1 -1
- package/dist/bundle/chunks/{chunk-R2Z7CX77.js → chunk-OSNR3IRD.js} +1 -1
- package/dist/bundle/chunks/{chunk-AC6MDRAE.js → chunk-PUZDKFRT.js} +81 -81
- package/dist/bundle/chunks/{chunk-6Q7Y2G5A.js → chunk-SANWO37B.js} +1 -1
- package/dist/bundle/chunks/{chunk-NN7NESW2.js → chunk-SS5VTBAV.js} +1 -1
- package/dist/bundle/chunks/{chunk-JSD6O3RJ.js → chunk-XUDKT4UH.js} +1 -1
- package/dist/bundle/chunks/{cli-main-ZTT3N4DO.js → cli-main-7II7GCIR.js} +1 -1
- package/dist/bundle/chunks/{credential-accounts-5KHVGSCY.js → credential-accounts-N3B5YJS7.js} +1 -1
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{hand-entry-UV5XPMBF.js → hand-entry-ONOLRMVB.js} +1 -1
- package/dist/bundle/chunks/{host-command-BZN7WYYV.js → host-command-KWMJLPBS.js} +1 -1
- package/dist/bundle/chunks/{host-lifecycle-TNHASSFJ.js → host-lifecycle-4WQDCN3Y.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +4 -4
- package/dist/bundle/chunks/{host-session-command-O5WYHZXH.js → host-session-command-ZDYEKCUB.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-OCU4NDPC.js → interactive-mode-EPE4M32G.js} +1 -1
- package/dist/bundle/chunks/{main-CNDP6HCF.js → main-OM7BKVZG.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-ODGJAGJP.js → multi-session-host-DB6XMY53.js} +2 -2
- package/dist/bundle/chunks/{package-manager-cli-HSPUG4RJ.js → package-manager-cli-GLU5Q2KV.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-KOZPXU3U.js → rpc-mode-SDJVBT36.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-SG44FE23.js → schedule-command-5SQD7M5N.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-5A24JYPE.js → session-control-endpoint-R25A2QGS.js} +1 -1
- package/dist/bundle/chunks/{session-picker-73YRS3GE.js → session-picker-GZM5CVQL.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +88 -88
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/host-supervisor.js +4 -4
- 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/core/agent-session.d.ts +2 -0
- package/dist/core/credential-accounts.d.ts +2 -0
- package/dist/core/credential-accounts.js +10 -1
- package/dist/core/dynamic-prompt/intent-gate.js +2 -2
- package/dist/core/dynamic-prompt/style.js +2 -2
- package/dist/core/dynamic-prompt/verification.js +2 -2
- package/dist/core/extensions/builtin/anthropic-subscription/accounts.d.ts +3 -0
- package/dist/core/extensions/builtin/anthropic-subscription/claude-cli-account-test.js +3 -1
- package/dist/core/extensions/builtin/anthropic-subscription/claude-cli-connection-test.d.ts +3 -1
- package/dist/core/extensions/builtin/anthropic-subscription/claude-cli-connection-test.js +47 -16
- package/dist/core/extensions/builtin/anthropic-subscription/claude-cli-login-slots.d.ts +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/claude-cli-login-slots.js +4 -2
- package/dist/core/extensions/builtin/anthropic-subscription/errors.d.ts +1 -0
- package/dist/core/extensions/builtin/anthropic-subscription/errors.js +14 -5
- package/dist/core/extensions/builtin/anthropic-subscription/oauth-login.js +3 -3
- package/dist/core/extensions/builtin/goal/continuation.d.ts +6 -0
- package/dist/core/extensions/builtin/goal/continuation.js +3 -2
- package/dist/core/extensions/builtin/goal/index.js +10 -26
- package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts +0 -6
- package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +3 -37
- package/dist/core/extensions/builtin/goal/monitor-continuation.js +66 -7
- package/dist/core/extensions/builtin/goal/provider-retry.d.ts +9 -0
- package/dist/core/extensions/builtin/goal/provider-retry.js +16 -0
- package/dist/core/extensions/builtin/goal/reload-reengagement.d.ts +3 -2
- package/dist/core/extensions/builtin/goal/reload-reengagement.js +4 -4
- package/dist/core/extensions/builtin/goal/session-start-continuation.d.ts +28 -0
- package/dist/core/extensions/builtin/goal/session-start-continuation.js +75 -0
- package/dist/core/extensions/builtin/goal/store.d.ts +1 -0
- package/dist/core/extensions/builtin/goal/store.js +1 -1
- package/dist/core/extensions/builtin/handoff-hint/index.js +15 -11
- package/dist/core/extensions/builtin/handoff-hint/replacement-relay.d.ts +16 -0
- package/dist/core/extensions/builtin/handoff-hint/replacement-relay.js +17 -0
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-2.js +5 -4
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/claude-haiku-5-5.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-5-5.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-5.js +4 -4
- package/dist/core/extensions/builtin/prompt-preset/claude-sonnet-5-5.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/deepseek-v4-1-flash.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.5.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js +2 -2
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/grok-4.5.js +1 -1
- package/dist/core/extensions/builtin/prompt-preset/grok-4.6.js +4 -4
- package/dist/core/extensions/builtin/prompt-preset/grok-4.7.js +5 -5
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3-1.js +4 -4
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3.js +7 -6
- package/dist/core/resource-loader.js +19 -3
- package/dist/core/retry-fallback/controller-types.d.ts +2 -0
- package/dist/core/retry-fallback/controller.js +9 -2
- package/dist/core/retry-fallback/cooldown.d.ts +7 -0
- package/dist/core/retry-fallback/cooldown.js +13 -1
- package/dist/core/retry-fallback/credential-recovery.d.ts +7 -0
- package/dist/core/retry-fallback/credential-recovery.js +24 -0
- package/dist/core/retry-fallback/settings.d.ts +8 -5
- package/dist/core/retry-fallback/settings.js +9 -6
- package/dist/modes/rpc/delegation-declaration.js +1 -1
- package/dist/modes/rpc/host-gc-evidence.d.ts +1 -1
- package/dist/modes/rpc/host-gc-evidence.js +9 -3
- package/dist/modes/rpc/host-gc.js +4 -1
- package/dist/modes/rpc/rpc-session-state-types.d.ts +2 -0
- package/dist/modes/rpc/session-attachment-gate.js +3 -0
- package/dist/private-fd-startup-fillers.d.ts +2 -2
- package/dist/private-fd-startup-fillers.js +34 -4
- package/docs/rpc.md +2 -1
- package/docs/settings.md +1 -1
- package/native/socket-secret/prebuilds/win32-arm64/senpi_socket_secret.win32-arm64.node +0 -0
- package/native/socket-secret/prebuilds/win32-x64/senpi_socket_secret.win32-x64.node +0 -0
- package/package.json +6 -6
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,exitAfterOutput,isPackageCommandArgv}from"./chunk-
|
|
2
|
+
import{CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,exitAfterOutput,isPackageCommandArgv}from"./chunk-SANWO37B.js";import{APP_NAME,CONFIG_DIR_NAME,CONFIG_FLAT_LAYOUT,ENV_PREFIX,brandEnvNames,getAgentDir}from"./chunk-SODMQEHO.js";import{homedir}from"node:os";try{process.cwd()}catch{let fallback=homedir();process.chdir(fallback),console.error(`the current working directory no longer exists; continuing from ${fallback}`)}import{homedir as homedir2}from"node:os";import{join}from"node:path";async function dispatchAgentDirectoryCommand(args){if(!(args[0]!=="config"||args[1]!=="agent-dir")){(args.length!==3||args[2]!=="--json")&&await exitAfterOutput(`${JSON.stringify({version:1,ok:!1,code:"invalid_arguments",message:`Usage: ${APP_NAME} config agent-dir --json`})}
|
|
3
3
|
`,2);try{let dir=getAgentDir(),selector=brandEnvNames("CODING_AGENT_DIR").find(name=>process.env[name]!==void 0),explicit=selector!==void 0&&process.env[selector]?selector:void 0,homeDefault=CONFIG_FLAT_LAYOUT?join(homedir2(),CONFIG_DIR_NAME):join(homedir2(),CONFIG_DIR_NAME,"agent"),rule=explicit!==void 0?"environment":dir===homeDefault?"home-default":"project-local";await exitAfterOutput(`${JSON.stringify({version:1,ok:!0,dir,source:explicit??(rule==="project-local"?"project-local":"default"),rule,brandedPrefix:ENV_PREFIX})}
|
|
4
4
|
`,0)}catch(error){await exitAfterOutput(`${JSON.stringify({version:1,ok:!1,code:"selection_failed",message:error instanceof Error?error.message:"Unable to resolve the agent directory."})}
|
|
5
5
|
`,1)}}}import*as nodeModule from"node:module";async function enableStartupCompileCache(){let enable=nodeModule.enableCompileCache;if(typeof enable!="function")return;let args=process.argv.slice(2);if(!isPackageCommandArgv(args)&&args[0]!==CONFIG_COMMAND_ARGV&&(args.includes("--version")||args.includes("-v")))return;let scheduleWatch=!1;if(args[0]===SCHEDULE_COMMAND_ARGV&&args[1]==="run")for(let index=2;index<args.length;index++){let arg=args[index];arg==="--watch"?scheduleWatch=!0:["--exec","--poll-seconds","--timeout-seconds","--concurrency"].includes(arg??"")&&index++}if(!(isPackageCommandArgv(args)||args[0]===HOST_COMMAND_ARGV||args[0]===SCHEDULE_COMMAND_ARGV&&!scheduleWatch)){if(!scheduleWatch&&args.some(arg=>["--help","-h","--export","--list-models","--list-tips"].includes(arg)))try{let{parseArgs}=await import("./args-HFYB6URH.js"),parsed=parseArgs(args);if(parsed.version||parsed.export||parsed.listModels!==void 0||parsed.listTips||parsed.help&&!(parsed.mode==="rpc"&&parsed.multiSession))return}catch{}try{let result=enable();result.directory!==void 0&&process.env.NODE_COMPILE_CACHE===void 0&&(process.env.NODE_COMPILE_CACHE=result.directory)}catch{}}}export{dispatchAgentDirectoryCommand,enableStartupCompileCache};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{COMPACT_LEAF_CODE_UNITS,CatalogNodeWriter,CompactComponentRoots,CompactContentStore,CompactReadError,CompactReadLease,CompactSelection,CompactValues,CompactWriteError,DEFAULT_TRANSCRIPT_ANCESTRY_BYTES,EVENT_RESYNC_CAPABILITY,ExtensionTransportOwner,FRAGMENT_MAX_BYTES,McpPresenterAuthority,SECRET_INPUT_FEATURE,SEQUENCED,SocketPeerRecovery,StagedReadError,TransferStaging,TransferStagingError,answerSealedFrame,applyContextPatch,assertRange,attachMcpGrantPresentation,baseRef,catalogDigest,catalogDigester,catalogRootRef,checkSealedAnswer,childRef,createAuthority,declarationReply,decodeCatalogNode,effectStatusRecord,features,isCorrelatedReply,maskOfRoles,nextIncarnation,observeLifecycleDelivery,openFrozenBytes,parseBoundedId,parseContentDigest,parseContentRef,parseDeclaration,parsePageRef,privateRootStat,producePage,protocolId,publishedSessionContext,readAuthority,readRootMarker,refSteps,remoteOriginField,rolesOfMask,rootOwnerState,samePrincipal,secretBinding,secretRequestHash,secretRequestTranscript,sessionQuestionBridges,startAtOrBefore,storeNarrowed,storeRetired,storedBytes,unvouchedCall,withReceipt}from"./chunk-
|
|
2
|
+
import{COMPACT_LEAF_CODE_UNITS,CatalogNodeWriter,CompactComponentRoots,CompactContentStore,CompactReadError,CompactReadLease,CompactSelection,CompactValues,CompactWriteError,DEFAULT_TRANSCRIPT_ANCESTRY_BYTES,EVENT_RESYNC_CAPABILITY,ExtensionTransportOwner,FRAGMENT_MAX_BYTES,McpPresenterAuthority,SECRET_INPUT_FEATURE,SEQUENCED,SocketPeerRecovery,StagedReadError,TransferStaging,TransferStagingError,answerSealedFrame,applyContextPatch,assertRange,attachMcpGrantPresentation,baseRef,catalogDigest,catalogDigester,catalogRootRef,checkSealedAnswer,childRef,createAuthority,declarationReply,decodeCatalogNode,effectStatusRecord,features,isCorrelatedReply,maskOfRoles,nextIncarnation,observeLifecycleDelivery,openFrozenBytes,parseBoundedId,parseContentDigest,parseContentRef,parseDeclaration,parsePageRef,privateRootStat,producePage,protocolId,publishedSessionContext,readAuthority,readRootMarker,refSteps,remoteOriginField,rolesOfMask,rootOwnerState,samePrincipal,secretBinding,secretRequestHash,secretRequestTranscript,sessionQuestionBridges,startAtOrBefore,storeNarrowed,storeRetired,storedBytes,unvouchedCall,withReceipt}from"./chunk-5PIZWSNG.js";import{RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_RESPONSE_UNWRITABLE,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-3IYEGHBI.js";import{carriesMedia,normalizeJsonValue,omitNormalInlineMedia}from"./chunk-XI6THO4F.js";import{BaseContentHash,compactUpdatesEnabled,fingerprintLine,parseSessionEntryLine}from"./chunk-J2I56WLK.js";import{bindPrivateMcpForms,isRecord}from"./chunk-MOVB6H22.js";import{COMPACT_EVENTS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RAISER_NOTICE_CAPABILITY,RPC_METHOD_CLASS,RPC_METHOD_CLASSES_DIGEST,RPC_METHOD_CLASSES_VERSION,classifyRpcMethod,hostGeneration,hostInstanceId}from"./chunk-5F2XC6UC.js";import{PRESENTER_EXCHANGE_MS,PRESENTER_PARKING_MS}from"./chunk-7WYJAYHH.js";import{RPC_LAUNCH_PROOF_RECORD}from"./chunk-VUY4BZDI.js";import{LegacyRecordDepthError,attachJsonlLineReader,isStackOverflow,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{randomUUID}from"node:crypto";import{tmpdir}from"node:os";import{join}from"node:path";var SKIPPED=new Set(["undefined","function","symbol"]),isRecord2=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function jsonSize(value){let bytes=0,units=0;for(let piece of walk(value))bytes+=Buffer.byteLength(piece),units+=piece.length;return{bytes,units}}function*jsonChunks(value,size){let pending="";for(let piece of walk(value))for(pending+=piece;pending.length>=size;)yield pending.slice(0,size),pending=pending.slice(size);pending.length>0&&(yield pending)}function*walk(value){let stack=[],pending={value};for(;;){if(pending){let current=pending.value;if(pending=void 0,Array.isArray(current))yield"[",stack.push({entries:current,array:!0,index:0});else if(isRecord2(current)){yield"{";let members=Object.entries(current).filter(([,child])=>!SKIPPED.has(typeof child));stack.push({entries:members,array:!1,index:0})}else yield JSON.stringify(current)??"null"}let frame=stack.at(-1);if(!frame)return;if(frame.index===frame.entries.length){stack.pop(),yield frame.array?"]":"}";continue}frame.index>0&&(yield",");let entry=frame.entries[frame.index++];if(frame.array)pending={value:entry};else{let[key,child]=entry;yield`${JSON.stringify(key)}:`,pending={value:child}}}}function stageRecord(staging,record,content){let kind=protocolId("event"),id=protocolId("record");if(typeof content=="string")return staging.stage(kind,id,content.slice(0,-1));let chunks2="chunks"in content?content.chunks:()=>jsonChunks(record,FRAGMENT_MAX_BYTES/2),units="units"in content?content.units:0;if("chunks"in content)for(let chunk of chunks2())units+=chunk.length;let transfer=staging.begin(kind,id,units*2);try{for(let chunk of chunks2())transfer.append(chunk);return transfer.commit()}catch(cause){throw transfer.abort(),cause}}function assertNever(value){throw new Error(`unexpected recovery failure: ${JSON.stringify(value)}`)}function refusalReason(failure){switch(failure.kind){case"storage_unavailable":return failure.kind;case"repair_needed":return failure.reason;default:return assertNever(failure)}}var recovered=value=>({ok:!0,value}),repairNeeded=reason=>({kind:"repair_needed",reason}),storageUnavailable=reason=>({kind:"storage_unavailable",reason}),RecoveryRefusedError=class extends Error{constructor(failure){super(`recovery refused (${failure.kind}: ${failure.reason})`),this.name="RecoveryRefusedError",this.failure=failure}};var COMPACT_RECORD_MAX_BYTES=2*FRAGMENT_MAX_BYTES,PEER_EVENT_LEASES_MAX=32,RELEASED_LEASES_REMEMBERED=256,EVENT_RECORD_COMPONENT="record",EventLeases=class{constructor(peerLimit=PEER_EVENT_LEASES_MAX){this.peers=new Map,this.shared=new WeakMap,this.ended=new Set,this.refusals=new Map,this.open=0,this.minted=0,this.released=0,this.duplicates=0,this.abandoned=0,this.contentBytes=0,this.peerLimit=peerLimit}onLeaseEnd(listener){this.ended.add(listener)}mint(caller,at,record,content){let peer=this.peers.get(caller.socketEpoch)??{held:new Map,released:new Map};if(peer.held.size>=this.peerLimit)return this.refuse("lease_limit");let shared=this.stage(record,content);if(!shared)return this.refuse("storage_unavailable");let{entry}=shared.content.ref,lease=Object.freeze({kind:"event",id:protocolId(`event:${caller.socketEpoch}:${++this.minted}`),admissionId:caller.admissionId,...at,componentRef:EVENT_RECORD_COMPONENT,length:entry.length,digest:entry.digest});shared.holders+=1;let held={lease,sessionId:caller.sessionId,shared,admissions:new Set([caller.admissionId]),reads:new CompactReadLease(()=>this.dispose(peer,held))};return peer.held.set(lease.id,held),this.peers.set(caller.socketEpoch,peer),this.open+=1,{ok:!0,value:lease}}claim(caller,leaseId,admissionId){let held=this.peers.get(caller.socketEpoch)?.held.get(leaseId);return!held||held.sessionId!==caller.sessionId||!held.admissions.has(admissionId)?{ok:!1,failure:repairNeeded("unknown_token")}:recovered(held)}async page(held,componentRef,offset,signal){let staging=this.staging;if(componentRef!==EVENT_RECORD_COMPONENT||!staging)return{ok:!1,failure:storageUnavailable("range")};try{return staging.store.health.needsRecovery&&await staging.store.repair(),recovered(await held.reads.run(async()=>{held.shared.opened??=staging.open(held.shared.content);let bytes=await held.shared.opened;if(signal?.aborted)throw new CompactReadError("aborted");return producePage(bytes,offset,()=>held.reads.assert())}))}catch(cause){if(held.shared.opened=void 0,cause instanceof StagedReadError)return{ok:!1,failure:storageUnavailable("integrity")};if(!(cause instanceof CompactReadError))throw cause;return{ok:!1,failure:cause.reason==="released"?repairNeeded("released"):storageUnavailable(cause.reason)}}}release(caller,leaseId,admissionId){let peer=this.peers.get(caller.socketEpoch),receipt=(outcome,remaining)=>recovered({lease:{kind:"event",id:leaseId},outcome,remaining});if(!peer)return{ok:!1,failure:repairNeeded("unknown_token")};let held=peer.held.get(leaseId);if(held?.sessionId===caller.sessionId&&held.admissions.delete(admissionId))return this.remember(peer,held,admissionId),held.admissions.size>0?receipt("held",held.admissions.size):(this.released+=1,held.reads.release(),receipt("released",0));let done=peer.released.get(leaseId);return done?.sessionId===caller.sessionId&&done.admissions.has(admissionId)?(this.duplicates+=1,receipt("duplicate",held?.admissions.size??0)):{ok:!1,failure:repairNeeded("unknown_token")}}abandon(socketEpoch,leaseId){let held=this.peers.get(socketEpoch)?.held.get(leaseId);!held||!held.reads.release()||(this.abandoned+=1)}forgetAdmission(caller,admissionId){for(let held of this.peers.get(caller.socketEpoch)?.held.values()??[])held.sessionId!==caller.sessionId||!held.admissions.delete(admissionId)||held.admissions.size===0&&this.abandon(caller.socketEpoch,held.lease.id)}forgetPeer(socketEpoch){let peer=this.peers.get(socketEpoch);this.peers.delete(socketEpoch);for(let held of peer?.held.values()??[])held.reads.release()}status(){return{open:this.open,peers:this.peers.size,minted:this.minted,released:this.released,duplicates:this.duplicates,abandoned:this.abandoned,contentBytes:this.contentBytes,refused:Object.fromEntries(this.refusals)}}stage(record,content){let existing=this.shared.get(record);if(existing&&existing.holders>0)return existing;this.staging??=new TransferStaging(new CompactContentStore({dir:join(tmpdir(),`senpi-event-leases-${randomUUID()}`)}));try{let staged=stageRecord(this.staging,record,content);this.staging.adopt(staged);let shared={content:staged,holders:0};return this.contentBytes+=staged.ref.entry.length,this.shared.set(record,shared),shared}catch(cause){if(cause instanceof TransferStagingError||cause instanceof CompactWriteError||cause instanceof CompactReadError){process.stderr.write(`senpi rpc event lease: record not staged (${cause.message})
|
|
3
3
|
`);return}throw cause}}remember(peer,held,admissionId){let admissions=new Set([...peer.released.get(held.lease.id)?.admissions??[],admissionId]);peer.released.set(held.lease.id,{sessionId:held.sessionId,admissions});for(let oldest of peer.released.keys()){if(peer.released.size<=RELEASED_LEASES_REMEMBERED)break;peer.released.delete(oldest)}}dispose(peer,held){peer.held.delete(held.lease.id),this.open-=1,held.shared.holders-=1,held.shared.holders===0&&this.staging&&(this.staging.release(held.shared.content),this.contentBytes-=held.shared.content.ref.entry.length);for(let listener of this.ended)listener(held.lease.id)}refuse(reason){return this.refusals.set(reason,(this.refusals.get(reason)??0)+1),{ok:!1,reason}}};var MESSAGE_KEY="message",COMPACT_DELTA_TYPES=new Set(["text_delta","thinking_delta","toolcall_delta"]);function compactDelta(value){if(value.type!=="message_update"||!Object.hasOwn(value,"message"))return;let event=value.assistantMessageEvent;if(typeof event!="object"||event===null)return;let{type,contentIndex,delta}=event;if(!(typeof type!="string"||!COMPACT_DELTA_TYPES.has(type)||typeof contentIndex!="number"||typeof delta!="string"))return{type,contentIndex,delta}}function demoteToDeltaOnly(value){let event=value.assistantMessageEvent;return{...value,message:null,assistantMessageEvent:{...event,partial:null}}}function toolUpdateKey(value){return value.type==="tool_execution_update"&&typeof value.toolCallId=="string"?`tool:${value.toolCallId}`:void 0}import{AsyncLocalStorage}from"node:async_hooks";var requests=new AsyncLocalStorage;function captureAdmissionReply(){let scope=requests.getStore();return scope&&{id:scope.command.id,admissionId:scope.command.admissionId,peer:scope.peer}}function withAdmissionReply(scope,action){return scope===void 0?action():requests.run({command:scope,peer:scope.peer},action)}function withAdmissionRequest(command,peer,action){return compactUpdatesEnabled()?requests.run({command,peer},action):action()}function replyAdmission(id,peer,routes){let request=requests.getStore();if(!request||request.command.id!==id||request.peer!==peer)return null;let admissionId=request.command.admissionId;return admissionId===void 0?void 0:routes.find(route=>route===admissionId)??null}var BaselineBarrier=class{constructor(cursor,live){this.cancelled=!1,this.ended=!1,this.cursor=cursor,this.live=live}get active(){return!this.cancelled&&!this.ended&&this.live()}cancel(){this.cancelled=!0,this.end()}end(){this.ended||(this.ended=!0,this.cursor.release())}async deliver(write,head){try{if(!this.active)return;let line=await this.cursor.next();for(head!==void 0&&this.active&&await write(head);line!==void 0&&this.active;)await write(line),line=await this.cursor.next()}finally{this.end()}}};var blockedMsTotal=0;function recordLoopBlockedMs(driftMs){driftMs>0&&(blockedMsTotal+=driftMs)}function loopBlockedMark(){return blockedMsTotal}function loopBlockedMsSince(mark){return blockedMsTotal-mark}var SocketEventQueueStallError=class extends Error{constructor(pendingBytes,stallMs){super(`socket event queue stalled: peer did not drain ${pendingBytes} queued bytes within ${stallMs}ms`),this.name="SocketEventQueueStallError",this.pendingBytes=pendingBytes,this.stallMs=stallMs}},SocketEventQueueOverflowError=class extends Error{constructor(queuedBytes,incomingBytes,maxQueueBytes,incomingPreview){super(`socket event queue overflow: ${queuedBytes} queued + ${incomingBytes} incoming > ${maxQueueBytes} (incoming: ${incomingPreview})`),this.name="SocketEventQueueOverflowError",this.queuedBytes=queuedBytes,this.incomingBytes=incomingBytes,this.maxQueueBytes=maxQueueBytes,this.incomingPreview=incomingPreview}};function waitForDrainOrStall(peer,writtenBytes){return new Promise((resolve2,reject)=>{let timer,blockedMark=loopBlockedMark(),cleanup=()=>{clearTimeout(timer),peer.stopped.removeEventListener("abort",onStop)},onStop=()=>{cleanup(),resolve2()},onDeadline=()=>{let blockedMs=loopBlockedMsSince(blockedMark);if(blockedMs>0){blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,Math.min(blockedMs,peer.stallMs));return}try{if(peer.shedAndPing()){blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,peer.stallMs);return}}catch(cause){cleanup(),reject(cause);return}let stall=new SocketEventQueueStallError(peer.queuedBytes()+writtenBytes,peer.stallMs);try{peer.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"stalled, resync required"})}
|
|
4
4
|
`)}catch{}cleanup(),reject(stall)};timer=setTimeout(onDeadline,peer.stallMs),peer.stopped.addEventListener("abort",onStop,{once:!0}),peer.sink.waitForBackpressure().then(()=>{cleanup(),resolve2()},cause=>{cleanup(),reject(cause)})})}var isBarrier=item=>"kind"in item,SocketEventQueue=class{constructor(){this.items=[],this.charged=0}get bytes(){return this.charged}get length(){return this.items.length}push(item){this.items.push(item),isBarrier(item)||(this.charged+=item.bytes)}shift(){let item=this.items.shift();return item!==void 0&&!isBarrier(item)&&(this.charged-=item.bytes),item}insertBefore(before,entry){let at=this.items.indexOf(before);at<0?this.items.push(entry):this.items.splice(at,0,entry),this.charged+=entry.bytes}supersede(key){let existing=this.items.find(item=>!isBarrier(item)&&item.key===key);existing===void 0||isBarrier(existing)||(existing.demotedLine!==void 0&&(this.charged-=existing.bytes,existing.line=existing.demotedLine,existing.bytes=Buffer.byteLength(existing.line),this.charged+=existing.bytes,existing.demotedLine=void 0,existing.onWritten?.(!1),existing.onWritten=void 0),existing.key=void 0)}retain(keep){let kept=[];for(let item of this.items)keep(item)?kept.push(item):isBarrier(item)?item.barrier.cancel():item.onWritten?.(!1);this.items=kept,this.charged=kept.reduce((bytes,item)=>isBarrier(item)?bytes:bytes+item.bytes,0)}clear(){for(let item of this.items)isBarrier(item)&&item.barrier.cancel();this.items.length=0,this.charged=0}};var SocketPeerShed=class{constructor(queue,mode){this.queue=queue,this.mode=mode}get isPending(){return this.pending!==void 0}get dropsRecords(){return this.pending!==void 0&&(this.mode==="drop"||this.pending.stale)}cut(reason,snapshot,live){this.queue.retain(item=>!isBarrier(item)&&item.reply);let cut=snapshot(reason);this.pending={kind:"recovery",reason,sessions:cut.sessions,barrier:new BaselineBarrier(cut,live),stale:!1},this.queue.push(this.pending)}supersede(){if(!this.pending||this.pending.stale)return;let recovery=this.pending;this.queue.retain(item=>isBarrier(item)?item===recovery:item.reply),recovery.barrier.cancel(),recovery.stale=!0}admitReply(entry){this.pending&&this.mode==="drop"?this.queue.insertBefore(this.pending,entry):this.queue.push(entry)}take(entry,snapshot,live){return entry.stale&&snapshot&&(entry.barrier=new BaselineBarrier(snapshot(entry.reason,entry.sessions),live)),this.pending===entry&&(this.pending=void 0),entry.barrier}clear(){this.pending=void 0}};var DEFAULT_QUEUE_BYTES=64*1024*1024,DEFAULT_STALL_MS=3e4,SocketEventSinkActor=class{constructor(sink,onFailure,maxQueueBytes=DEFAULT_QUEUE_BYTES,stallMs=DEFAULT_STALL_MS,shedMode="drop"){this.queue=new SocketEventQueue,this.closed=!1,this.recoveryEnabled=!1,this.frameBytes=0,this.stopped=new AbortController,this.sink=sink,this.onFailure=onFailure,this.maxQueueBytes=maxQueueBytes,this.shed=new SocketPeerShed(this.queue,shedMode),this.stallPeer={sink,stallMs,stopped:this.stopped.signal,queuedBytes:()=>this.queue.bytes,shedAndPing:()=>!this.recovery||!this.recoveryEnabled?!1:(this.cutOnce("stall"),this.recovery.ping(),!0)}}enableRecovery(snapshot){this.recoveryEnabled=!0,this.snapshot=snapshot,this.recovery??=new SocketPeerRecovery(line=>this.sink.writeRaw(line)),this.recovery.acknowledge()}disableRecovery(){this.recoveryEnabled=!1,this.recovery?.pending||(this.recovery=void 0)}installBaseline(cursor,live){if(this.closed||cursor.empty||this.shed.dropsRecords){cursor.release();return}this.queue.push({kind:"attach",barrier:new BaselineBarrier(cursor,live)}),this.drain()}enqueue(line,key,onWritten,demotedLine,reply=!1,held,current){if(this.closed)return;let bytes=Buffer.byteLength(line);if(this.shed.dropsRecords){reply?this.admitReply({line,bytes,onWritten,reply,current}):onWritten?.(!1);return}if(key!==void 0&&this.queue.supersede(key),!this.fits(bytes)){if(this.recovery&&this.recoveryEnabled){this.shed.isPending?this.shed.supersede():this.cut("overflow"),reply?this.admitReply({line,bytes,onWritten,reply,current}):onWritten?.(!1),this.drain();return}this.failOverflow(bytes,line);return}this.queue.push({line,bytes,key,demotedLine,onWritten,reply,held:this.shed.isPending?held:void 0,current}),this.drain()}async flush(){for(;this.draining;)await this.draining;if(this.failure!==void 0)throw this.failure}waitForAcceptance(){return Promise.resolve()}close(){this.closed=!0,this.dropQueue(),this.stopped.abort()}fits(bytes){return this.queue.bytes+this.frameBytes+bytes<=this.maxQueueBytes}admitReply(entry){if(!this.fits(entry.bytes)){this.recovery?.loseReply(),entry.onWritten?.(!1);return}this.shed.admitReply(entry),this.drain()}failOverflow(bytes,line){let overflow=new SocketEventQueueOverflowError(this.queue.bytes+this.frameBytes,bytes,this.maxQueueBytes,line.slice(0,120));this.closed=!0,this.dropQueue();try{this.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"overflow, resync required"})}
|
|
5
5
|
`)}catch(cause){this.onFailure(cause)}this.onFailure(overflow)}dropQueue(){this.queue.clear(),this.attempt?.cancel(),this.shed.clear()}cutOnce(reason){this.recovery?.pending||this.cut(reason)}cut(reason){!this.recovery||!this.snapshot||(this.attempt?.cancel(),this.recovery.shed(reason),this.shed.cut(reason,this.snapshot,()=>!this.closed))}async write(line){this.sink.writeRaw(line),await waitForDrainOrStall(this.stallPeer,Buffer.byteLength(line))}async writeFrame(line){let bytes=Buffer.byteLength(line);if(!this.fits(bytes)){this.recovery&&this.recoveryEnabled?this.cutOnce("overflow"):this.failOverflow(bytes,line);return}this.frameBytes=bytes;try{await this.write(line)}finally{this.frameBytes=0}}async deliver(entry){if(entry.kind==="attach"){await this.stream(entry.barrier,line=>this.writeFrame(line));return}if(await waitForDrainOrStall(this.stallPeer,0),this.closed||!this.recovery)return;let barrier=this.shed.take(entry,this.snapshot,()=>!this.closed),gap=this.recovery.takeGap();this.recoveryEnabled||(this.recovery=void 0),await this.stream(barrier,line=>this.write(line),gap)}async stream(barrier,write,head){this.attempt=barrier;try{await barrier.deliver(write,head)}finally{barrier.end(),this.attempt===barrier&&(this.attempt=void 0)}}drain(){return this.draining?this.draining:(this.draining=(async()=>{try{for(;!this.closed&&this.queue.length>0;){let item=this.queue.shift();if(item===void 0)break;if(isBarrier(item)){try{await this.deliver(item)}finally{item.barrier.end()}continue}let written=(item.held?.()??!0)&&(item.current?.()??!0);written&&await this.write(item.line),item.onWritten?.(written)}}catch(cause){this.failure=cause,this.closed=!0,this.dropQueue(),this.onFailure(cause)}})().finally(()=>{this.draining=void 0,!this.closed&&this.queue.length>0&&this.drain()}),this.draining)}};var AdmissionRoutingActor=class extends SocketEventSinkActor{constructor(){super(...arguments),this.admissions=new Set,this.subscriptions=new Map,this.mirrorOwners=new Map,this.pendingMirrors=new Map,this.opened=new Map,this.retireAfterReply=new Map,this.terminal=new Map}close(){this.subscriptions.clear(),this.mirrorOwners.clear();for(let pending of this.pendingMirrors.values())pending.retire();this.pendingMirrors.clear(),this.admissions.clear(),this.opened.clear(),this.retireAfterReply.clear(),this.terminal.clear(),super.close()}remember(sessionId,checkpoints,socketEpoch){let stream=checkpoints.stream({socketEpoch,sessionId}),remembered=stream??this.terminal.get(sessionId),routes=remembered?.routes.filter(id=>this.admissions.has(id)||[...this.mirrorOwners.values()].includes(id))??[];return stream&&routes.length>0&&this.terminal.set(sessionId,{...stream,routes}),remembered?{...remembered,routes}:void 0}route(line,checkpoints,socketEpoch){if(this.admissions.size===0&&this.subscriptions.size===0&&this.mirrorOwners.size===0)return[line];let record=JSON.parse(line);if(typeof record.sessionId!="string"||record.admissionId!==void 0)return[line];if(typeof record.subscriptionId=="string"){let subscription=this.subscriptions.get(record.subscriptionId);return subscription===void 0?[line]:[serializeJsonLine({...record,admissionId:subscription,generation:0})]}let mirrors=record.type==="response"?[]:this.mirrorAdmissions?.(record.sessionId,String(record.type))??[],stream=this.remember(record.sessionId,checkpoints,socketEpoch),terminal=record.type==="session_closed"||record.type==="session_parked",routes=[...new Set([...(stream?.routes??[]).filter(id=>this.admissions.has(id)||terminal&&[...this.mirrorOwners.values()].includes(id)),...mirrors])];if(record.type==="response"&&typeof record.id=="string"){let admissionId=replyAdmission(record.id,this.peer,routes);return admissionId===null?[]:admissionId===void 0?[line]:[serializeJsonLine({...record,admissionId,generation:stream?.generation})]}return routes.length===0?[line]:routes.map(admissionId=>serializeJsonLine({...record,admissionId,generation:stream?.generation}))}deferRetire(id,retire){this.retireAfterReply.set(id,retire)}retireReplied(line){if(this.retireAfterReply.size===0)return;let record=JSON.parse(line);if(record.type!=="response"||typeof record.id!="string")return;let retire=this.retireAfterReply.get(record.id);this.retireAfterReply.delete(record.id),retire?.()}bind(checkpoints,socketEpoch,peer){this.peer=peer;let enqueue=super.enqueue.bind(this);this.enqueue=(line,key,written,demoted,reply,held)=>{let lines2=this.route(line,checkpoints,socketEpoch);if(this.retireReplied(line),lines2.length===0){written?.(!1);return}let replacements=demoted===void 0?void 0:this.route(demoted,checkpoints,socketEpoch),remaining=lines2.length,delivered=!1,receipt=ok=>{delivered||=ok,--remaining===0&&written?.(delivered)};for(let i=0;i<lines2.length;i++){let line2=lines2[i]??"",admissionId=Reflect.get(JSON.parse(line2),"admissionId"),pending=typeof admissionId=="string"?this.pendingMirrors.get(admissionId):void 0,deliver=()=>enqueue(lines2[i]??line2,key===void 0?void 0:`${key}:${i}`,receipt,replacements?.[i],reply,held);pending&&!reply?pending.enqueue(line2,deliver,()=>receipt(!1)):deliver()}}}};var CompactRequiredStreams=class{constructor(fanout,status){this.states=new WeakMap,this.fanout=fanout,this.status=status}sessions(peer){return this.status.requiredSessions(peer)}routes(peer,sessionId,type){let registered=this.fanout.get(peer),actor=registered?.actor;return!(actor instanceof AdmissionRoutingActor)||!registered?[]:[...new Set([...(this.fanout.checkpoints.stream({socketEpoch:registered.socketEpoch,sessionId})?.routes??[]).filter(id=>actor.admissions.has(id)),...this.status.mirrorAdmissions(peer,sessionId,type)])]}prepare(sessionId,record){let lane=this.fanout.acceptance.get(sessionId);if(!(!lane||lane.retired))for(let peer of this.fanout.connectionIds()){if(!this.fanout.connectionHas(peer,COMPACT_EVENTS_CAPABILITY))continue;let registered=this.fanout.get(peer),actor=registered?.actor;if(!(actor instanceof AdmissionRoutingActor)||!registered)continue;let routes=this.status.requiredAdmissions(peer,sessionId),caller={socketEpoch:registered.socketEpoch,sessionId};for(let admissionId of routes){if(this.fanout.checkpoints.stream(caller)?.routes.includes(admissionId))continue;let frozen=this.fanout.checkpoints.freeze({...caller,peer,admissionId,routeKind:"mirror"},lane,!0);if(!frozen.ok){registered.close("checkpoint_unavailable",frozen.failure.reason);continue}}let stream=this.fanout.checkpoints.stream(caller);if(!stream?.routes.length)continue;let states=this.states.get(actor)??new Map;this.states.set(actor,states);let state=states.get(sessionId);if(state?.epoch!==lane.sessionEpoch&&(state={epoch:lane.sessionEpoch,dirty:!1},states.set(sessionId,state),state.seed=this.fanout.checkpoints.tokens().find(t=>t.admission.socketEpoch===caller.socketEpoch&&t.admission.sessionId===sessionId)),!record)continue;let type=String(Reflect.get(record,"type"));if(!(stream.routes.some(id=>actor.admissions.has(id))||this.status.mirrorAdmissions(peer,sessionId,type).length>0)){state.dirty=!0;continue}if(state.dirty){let frozen=this.fanout.checkpoints.freeze({...caller,peer,admissionId:stream.routes[0],routeKind:routes.length?"mirror":"ordinary"},lane);if(!frozen.ok){registered.close("checkpoint_unavailable",frozen.failure.reason);continue}state.seed=frozen.value.token,state.dirty=!1}}}takeSeed(peer,sessionId){let actor=this.fanout.get(peer)?.actor,state=actor instanceof AdmissionRoutingActor?this.states.get(actor)?.get(sessionId):void 0,seed=state?.seed;return state&&(state.seed=void 0),seed}forgetSession(sessionId){for(let peer of this.fanout.connectionIds()){let actor=this.fanout.get(peer)?.actor;actor instanceof AdmissionRoutingActor&&this.states.get(actor)?.delete(sessionId)}}};function causeLine(cause){let text=cause instanceof Error?`${cause.name}: ${cause.message}`:String(cause);return text.split(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{hostChildStartupHandOff,relayHostStartupEvents,reportStartupMilestone,startupHandOff}from"./chunk-R2Z7CX77.js";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,childStalledStopMaxMs,classifyChildExit,clearStopProgress,errorMessage,hostEnsureLockOptions,hostEnsureLockTarget,hostLoopStalled,layeredSupervisorIntent,noteChildExit,parseIdleExitMs,readStopIntent,recordHostCrash,releaseGeneration,resolveHostPolicy,supervisorLog,watchDrainRequest,writeDrainRequest,writeDrainWatch,writeHostReady,writeStderrLine,writeStopIntent,writeStopProgress}from"./chunk-UCXBDE6R.js";import{HOST_DAEMON_DIR_ENV,HostDaemonStateError,createGenerationDirectory,createHostDaemonPaths,generationPaths,hostOwnerGone,readHostOwner,sameHostOwner,writeJsonAtomic}from"./chunk-YI6KRJDC.js";import{OBSERVE_REQUEST_FIELD,RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RPC_LAUNCH_PROOF_RECORD,RpcPublicEndpoint,authRecord,isObservingRequest,launchProofRecordRefusal,observingHoldChange,requestOriginHostInstance,rpcAuthProof,rpcProofMatches}from"./chunk-VUY4BZDI.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import{runtimeExecArgv,spawnWithPrivateFds}from"./chunk-E266ORGA.js";import{ADOPTION_GRANT_FILE,STARTUP_ATTEMPT_FILE,releaseStartupFillers,startupGrantLine,withStartupPipe}from"./chunk-T2SMQPRE.js";import{HOST_INSTANCE_ID_ENV,HOST_STARTUP_EVENTS_ENV,INTERNAL_KEY_STDIN_ENV}from"./chunk-RUGTHELO.js";import{BIND_SCRATCH_INFIX,BIND_SCRATCH_SOCKET,MAX_SOCKET_PATH_BYTES,PUBLIC_SOCKET_IDENTITY_FILE,adoptPublicSocket,classifyEndpointOwnership,parseSocketIdentity,shieldSocketDuringClose,socketEntryListenerState,statSocketIdentity,unlinkOwnedSocket,writeSocketIdentityFile}from"./chunk-5XHOHZIR.js";import{SOCKET_HANDSHAKE_TIMEOUT_MS,SOCKET_SECRET_FILE_ENV,acquireOwnershipSafeLock,authenticateSocket,createSocketSecret,ensureSocketSecret,isBusy,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-HW6AAS3R.js";import{VERSION,brandEnvNames,envValue,getAgentDir,isBunBinary,isBundledNode}from"./chunk-SODMQEHO.js";import{processStartTimeMs,readProcessIdentity,readProcessStartTime,sameProcessStartMs,waitForStartTime}from"./chunk-O5RYI3IW.js";import{randomUUID as randomUUID3}from"node:crypto";import{mkdir as mkdir5,rm as rm4}from"node:fs/promises";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}}}function hostCrashCleanupPaths(targets){let publicEntry=targets.platform==="win32"?[targets.publicSocket]:[];return targets.successor?publicEntry:[targets.generationPidFile,targets.settingsFile,...publicEntry,targets.pointerFile]}import{existsSync,readFileSync,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(readFileSync(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.held=new Set,this.dependents=new Set,this.closed=!1,this.onAttach=onAttach,this.ownInstance=ownInstance}get attachedCount(){return this.attached.size+this.held.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.held.delete(client),this.attached.add(client),this.onAttach()},depend=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.held.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);let hold=observingHoldChange(line);hold===!0&&!this.held.has(client)?(this.held.add(client),this.onAttach()):hold===!1&&this.held.delete(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.held.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;#settling=new Map;#settleHoldMs;#now;#onSettleHoldExpired;constructor(options={}){this.#settleHoldMs=options.settleHoldMs??Number.POSITIVE_INFINITY,this.#now=options.now??Date.now,this.#onSettleHoldExpired=options.onSettleHoldExpired}observe(line){let event=parseHostEvent(line);if(event===void 0)return!1;if(event.type==="agent_start")this.#running.add(event.sessionId),this.#settling.delete(event.sessionId);else if(event.type==="agent_settled"&&event.reason!=="session_closed")this.#running.delete(event.sessionId),this.#settling.set(event.sessionId,this.#now());else if(event.type==="agent_settled"||event.type==="agent_idle"||event.type==="session_closed")this.#running.delete(event.sessionId),this.#settling.delete(event.sessionId);else return!1;return!0}get busySessions(){return this.#running.size}get settlingSessions(){let now=this.#now();for(let[sessionId,settledAt]of this.#settling){let heldMs=now-settledAt;heldMs<this.#settleHoldMs||(this.#settling.delete(sessionId),this.#onSettleHoldExpired?.(sessionId,heldMs))}return this.#settling.size}};function holdIdleExitForSettling(decision,runs){return decision==="exit"&&runs.settlingSessions>0?"idle":decision}function parseHostEvent(line){let event;try{event=JSON.parse(line)}catch{return}if(typeof event!="object"||event===null)return;let{type,sessionId,reason}=event;return typeof sessionId=="string"?{type,sessionId,reason}: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}
|
|
2
|
+
import{hostChildStartupHandOff,relayHostStartupEvents,reportStartupMilestone,startupHandOff}from"./chunk-OSNR3IRD.js";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,childStalledStopMaxMs,classifyChildExit,clearStopProgress,errorMessage,hostEnsureLockOptions,hostEnsureLockTarget,hostLoopStalled,layeredSupervisorIntent,noteChildExit,parseIdleExitMs,readStopIntent,recordHostCrash,releaseGeneration,resolveHostPolicy,supervisorLog,watchDrainRequest,writeDrainRequest,writeDrainWatch,writeHostReady,writeStderrLine,writeStopIntent,writeStopProgress}from"./chunk-UCXBDE6R.js";import{HOST_DAEMON_DIR_ENV,HostDaemonStateError,createGenerationDirectory,createHostDaemonPaths,generationPaths,hostOwnerGone,readHostOwner,sameHostOwner,writeJsonAtomic}from"./chunk-YI6KRJDC.js";import{OBSERVE_REQUEST_FIELD,RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RPC_LAUNCH_PROOF_RECORD,RpcPublicEndpoint,authRecord,isObservingRequest,launchProofRecordRefusal,observingHoldChange,requestOriginHostInstance,rpcAuthProof,rpcProofMatches}from"./chunk-VUY4BZDI.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import{runtimeExecArgv,spawnWithPrivateFds}from"./chunk-LJFQYCFH.js";import{ADOPTION_GRANT_FILE,STARTUP_ATTEMPT_FILE,releaseStartupFillers,startupGrantLine,withStartupPipe}from"./chunk-K3GAGIPX.js";import{HOST_INSTANCE_ID_ENV,HOST_STARTUP_EVENTS_ENV,INTERNAL_KEY_STDIN_ENV}from"./chunk-RUGTHELO.js";import{BIND_SCRATCH_INFIX,BIND_SCRATCH_SOCKET,MAX_SOCKET_PATH_BYTES,PUBLIC_SOCKET_IDENTITY_FILE,adoptPublicSocket,classifyEndpointOwnership,parseSocketIdentity,shieldSocketDuringClose,socketEntryListenerState,statSocketIdentity,unlinkOwnedSocket,writeSocketIdentityFile}from"./chunk-5XHOHZIR.js";import{SOCKET_HANDSHAKE_TIMEOUT_MS,SOCKET_SECRET_FILE_ENV,acquireOwnershipSafeLock,authenticateSocket,createSocketSecret,ensureSocketSecret,isBusy,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-HW6AAS3R.js";import{VERSION,brandEnvNames,envValue,getAgentDir,isBunBinary,isBundledNode}from"./chunk-SODMQEHO.js";import{processStartTimeMs,readProcessIdentity,readProcessStartTime,sameProcessStartMs,waitForStartTime}from"./chunk-O5RYI3IW.js";import{randomUUID as randomUUID3}from"node:crypto";import{mkdir as mkdir5,rm as rm4}from"node:fs/promises";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}}}function hostCrashCleanupPaths(targets){let publicEntry=targets.platform==="win32"?[targets.publicSocket]:[];return targets.successor?publicEntry:[targets.generationPidFile,targets.settingsFile,...publicEntry,targets.pointerFile]}import{existsSync,readFileSync,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(readFileSync(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.held=new Set,this.dependents=new Set,this.closed=!1,this.onAttach=onAttach,this.ownInstance=ownInstance}get attachedCount(){return this.attached.size+this.held.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.held.delete(client),this.attached.add(client),this.onAttach()},depend=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.held.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);let hold=observingHoldChange(line);hold===!0&&!this.held.has(client)?(this.held.add(client),this.onAttach()):hold===!1&&this.held.delete(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.held.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;#settling=new Map;#settleHoldMs;#now;#onSettleHoldExpired;constructor(options={}){this.#settleHoldMs=options.settleHoldMs??Number.POSITIVE_INFINITY,this.#now=options.now??Date.now,this.#onSettleHoldExpired=options.onSettleHoldExpired}observe(line){let event=parseHostEvent(line);if(event===void 0)return!1;if(event.type==="agent_start")this.#running.add(event.sessionId),this.#settling.delete(event.sessionId);else if(event.type==="agent_settled"&&event.reason!=="session_closed")this.#running.delete(event.sessionId),this.#settling.set(event.sessionId,this.#now());else if(event.type==="agent_settled"||event.type==="agent_idle"||event.type==="session_closed")this.#running.delete(event.sessionId),this.#settling.delete(event.sessionId);else return!1;return!0}get busySessions(){return this.#running.size}get settlingSessions(){let now=this.#now();for(let[sessionId,settledAt]of this.#settling){let heldMs=now-settledAt;heldMs<this.#settleHoldMs||(this.#settling.delete(sessionId),this.#onSettleHoldExpired?.(sessionId,heldMs))}return this.#settling.size}};function holdIdleExitForSettling(decision,runs){return decision==="exit"&&runs.settlingSessions>0?"idle":decision}function parseHostEvent(line){let event;try{event=JSON.parse(line)}catch{return}if(typeof event!="object"||event===null)return;let{type,sessionId,reason}=event;return typeof sessionId=="string"?{type,sessionId,reason}: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}
|
|
3
3
|
`)}),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 read2=()=>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(read2,frame=>new Promise((resolve2,reject)=>{socket.write(`${JSON.stringify(frame)}
|
|
4
4
|
`,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(read2,send)=>{let clientNonce=randomBytes(32).toString("hex"),[response]=await Promise.all([read2(),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([read2(),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(read2,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 read2(),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([read2(),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.options=options,this.decider=new IdleExitDecider(options.idleExitMs,Date.now,startupHandOff()?.budgetMs),this.runs=new SessionRunActivity({settleHoldMs:options.idleExitMs,onSettleHoldExpired:(sessionId,heldMs)=>supervisorLog(`session ${sessionId} settled ${heldMs} ms ago and its agent_settled extension handlers have not finished; idle exit no longer waits for them`)}),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?.(),holdIdleExitForSettling(this.decider.update(current),this.runs)}quiescent(){return this.observerLink.healthy()&&this.runs.busySessions===0&&this.runs.settlingSessions===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||process.ppid!==owner.pid)&&!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?!1:sameHostOwner(owner,current)?activity.quiescent():(await this.reload(),!1)}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-QN4Q2P5E.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()})}var CHILD_IDENTITY_TICK_MS=500,CHILD_IDENTITY_READ_GAP_TICKS=10,CHILD_IDENTITY_READ_GAP_MAX_TICKS=120;function childLiveness(pid){try{return process.kill(pid,0),"alive"}catch(cause){return cause instanceof Error&&"code"in cause&&cause.code==="ESRCH"?"dead":"unknown"}}async function watchWin32ChildIdentity(child,shuttingDown,onGone){let pid=child.pid;if(pid===void 0)return()=>{};let readStartTime=()=>readProcessStartTime(pid,process.platform,1e3),baseline=await readStartTime().catch(()=>{}),adoptable=!0,suspect=!1,deadTicks=0,reading=!1,ended=!1,ticksUntilRead=0,readGapTicks=CHILD_IDENTITY_READ_GAP_TICKS,backOff=()=>{ticksUntilRead=readGapTicks,readGapTicks=Math.min(readGapTicks*2,CHILD_IDENTITY_READ_GAP_MAX_TICKS)},end=()=>{ended=!0,onGone()},settle=current=>{if(!ended){if(baseline===void 0){current!==void 0&&adoptable&&childLiveness(pid)==="alive"?baseline=current:backOff();return}if(current!==void 0&¤t!==baseline)return end();current===baseline&&(suspect=!1),backOff()}},timer=setInterval(()=>{if(ended||shuttingDown()||child.exitCode!==null||child.signalCode!==null)return;ticksUntilRead>0&&ticksUntilRead--;let liveness=childLiveness(pid);if(liveness==="dead"){if(deadTicks++,deadTicks>=2)return end();suspect=!0,adoptable=!1;return}(deadTicks>0||liveness==="unknown")&&(suspect=!0,adoptable=!1),deadTicks=0,!(!(baseline===void 0?adoptable:suspect)||reading||ticksUntilRead>0)&&(reading=!0,readStartTime().then(settle,()=>{ended||backOff()}).finally(()=>{reading=!1}))},CHILD_IDENTITY_TICK_MS);return timer.unref?.(),()=>{ended=!0,clearInterval(timer)}}import{randomBytes as randomBytes2}from"node:crypto";import{readFile as readFile4}from"node:fs/promises";import{join as join3}from"node:path";import{readFileSync as readFileSync2}from"node:fs";function readProcessStartTicks(pid,platform=process.platform){if(platform==="linux")try{let stat2=readFileSync2(`/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}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(join(root,name,"host.sock"))<=MAX_SOCKET_PATH_BYTES)return root;let tried=internalHostDirRoots().map(root=>join(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=join(baseDir,`internal-${randomUUID()}`);return await mkdir(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID()}`,dir:dir2,secretPath:join(dir2,"secret")}}let name=`${INTERNAL_HOST_DIR_PREFIX}${randomUUID().slice(0,8)}`,dir=join(internalHostDirRoot(name),name);return await mkdir(dir,{recursive:!1,mode:448}),await writeFile(join(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join(dir,"host.sock"),dir,secretPath:join(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}from"node:fs";import{join as join2}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=join2(hopDir,"lifetime.fifo");try{return rmSync(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(join3(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 childProcess from"node:child_process";import{Socket as Socket4}from"node:net";import{extname}from"node:path";import{read}from"node:fs";import{readFile as readFile6}from"node:fs/promises";import{join as join5}from"node:path";import{Readable}from"node:stream";import{randomUUID as randomUUID2}from"node:crypto";import{mkdir as mkdir2,readFile as readFile5,rename,rm,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname2}from"node:path";var ENDPOINT_FENCE_WAIT_MS=15e3;function endpointOwnerToken(endpoint,instanceId,generation){return{v:1,endpoint,instanceId,generation,pid:process.pid,nonce:randomUUID2()}}var ownerFile=socket=>`${hostEnsureLockTarget(socket)}.owner.json`;async function withEndpointFence(socket,run,hooks){let fence=`${hostEnsureLockTarget(socket)}.fence.lock`;await mkdir2(dirname2(fence),{recursive:!0});let release;try{release=await acquireOwnershipSafeLock(fence,{retries:{retries:0,minTimeout:1,maxTimeout:1}})}catch(cause){if(!isBusy(cause))throw cause;hooks?.onFenceBusy?.(),release=await acquireOwnershipSafeLock(fence,hostEnsureLockOptions(ENDPOINT_FENCE_WAIT_MS))}try{return await run()}finally{await release()}}async function readEndpointOwner(socket){let parsed;try{parsed=JSON.parse(await readFile5(ownerFile(socket),"utf8"))}catch{return}if(typeof parsed!="object"||parsed===null)return;let token=parsed;return token.v===1&&typeof token.instanceId=="string"&&typeof token.nonce=="string"?parsed:void 0}async function writeEndpointOwner(socket,token){let path=ownerFile(socket),staged=`${path}.${process.pid}.tmp`;await writeFile2(staged,`${JSON.stringify(token)}
|
|
5
5
|
`,{mode:384}),await rename(staged,path)}async function claimEndpoint(socket,token,bind){let claim=async()=>{await bind?.(),await writeEndpointOwner(socket,token)};if(await readEndpointOwner(socket)){await withEndpointFence(socket,claim);return}await mkdir2(dirname2(ownerFile(socket)),{recursive:!0}),await claim()}async function adoptEndpoint(options){let{publicSocket}=options;await withEndpointFence(publicSocket,async()=>{if(options.granted&&!await options.granted())throw new Error(`${publicSocket}: the launcher revoked this generation's adoption grant`);let current=await readEndpointOwner(publicSocket);if(options.expectedOwner!==void 0&¤t&¤t.instanceId!==options.expectedOwner)throw new Error(`${publicSocket}: owner token names ${current.instanceId}, not ${options.expectedOwner}; refusing to replace it`);await adoptPublicSocket(options.bindSocket,publicSocket,options.expected),await writeEndpointOwner(publicSocket,options.token)},options.hooks)}async function unlinkOwnedEndpoint(socket,identity,instanceId,log,hooks){await withEndpointFence(socket,async()=>{let current=await readEndpointOwner(socket);if(current&¤t.instanceId!==instanceId){log(`socket path ${socket} is owned by generation ${current.instanceId} now; leaving it`);return}await hooks?.afterValidate?.(),await unlinkOwnedSocket(socket,identity,log),current&&await rm(ownerFile(socket),{force:!0})})}async function closeShieldedEndpoint(socket,close){await withEndpointFence(socket,()=>shieldSocketDuringClose(socket,close))}async function settleCandidateAdoption(socket,candidate,revoke){return withEndpointFence(socket,async()=>(await revoke(),(await readEndpointOwner(socket))?.instanceId===candidate?"completed":"not_adopted"))}import{lstat as lstat2,mkdir as mkdir4,unlink}from"node:fs/promises";import{createConnection as createConnection2,createServer}from"node:net";import{dirname as dirname3}from"node:path";import{StringDecoder}from"node:string_decoder";function proxyWithAdmission(client,internal,admission,auth,launchProven=!1){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(){internal&&launchProven&&internal.write(`${JSON.stringify({type:RPC_LAUNCH_PROOF_RECORD})}
|
|
@@ -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{appendDebugLogEntry}from"./chunk-5H43O4MA.js";import{isRecoverableInspectorVmImportError}from"./chunk-
|
|
2
|
+
import{appendDebugLogEntry}from"./chunk-5H43O4MA.js";import{isRecoverableInspectorVmImportError}from"./chunk-SANWO37B.js";import{hasModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{isStaleExtensionContextError}from"./chunk-IHES3JES.js";function containStaleExtensionError(error,origin){if(!isStaleExtensionContextError(error))return!1;try{appendDebugLogEntry(`contained stale extension ctx (${origin})`,error.stack??error.message)}catch{}return!0}var installed=!1;function installStaleExtensionContainment(){installed||(installed=!0,process.on("uncaughtException",(error,origin)=>{containStaleExtensionError(error,origin??"uncaughtException")||hasModeCrashHandler("uncaughtException")||isRecoverableInspectorVmImportError(error,origin??"uncaughtException")||(console.error(error),process.exit(1))}))}export{containStaleExtensionError,installStaleExtensionContainment};
|
|
@@ -2,4 +2,4 @@ import { createRequire as __piCreateRequire } from "node:module"; const require
|
|
|
2
2
|
import{HOST_STARTUP_EVENTS_ENV}from"./chunk-RUGTHELO.js";import{isFifoMode}from"./chunk-42XRJQM6.js";var STARTUP_ATTEMPT_FILE="startup-attempt.json",ADOPTION_GRANT_FILE="adoption-grant.json";function encodeStartupHandOff(handOff){return JSON.stringify(handOff)}function parseStartupHandOff(value){if(value)try{let parsed=JSON.parse(value);if(typeof parsed!="object"||parsed===null)return;let{binding,role,budgetMs,fillers}=parsed;if(role!=="supervisor"&&role!=="host"||typeof budgetMs!="number"||!Number.isFinite(budgetMs)||budgetMs<=0||typeof binding!="object"||binding===null)return;let fields=binding;if(typeof fields.attempt!="string"||typeof fields.instanceId!="string")return;let slots=Array.isArray(fillers)?fillers.filter(slot=>Number.isInteger(slot)&&slot>=3&&slot<16):[];return{binding,role,budgetMs,fillers:slots}}catch{return}}function startupEventLine(binding,role,seq,milestone){return`${JSON.stringify({v:1,binding,role,seq,milestone})}
|
|
3
3
|
`}function startupGrantLine(attempt){return`${JSON.stringify({grant:"public_published",attempt})}
|
|
4
4
|
`}function relayStartupLine(line){return`${JSON.stringify({relay:"host",line})}
|
|
5
|
-
`}import{closeSync,fstatSync as fstatSync2}from"node:fs";import{isMainThread}from"node:worker_threads";var PRIVATE_FDS_TABLE_ENV="SENPI_PRIVATE_FDS",UNPARSEABLE_TABLE="unparseable";var NAME=/^[a-z][a-z0-9-]{0,63}$/,QUOTED_NAME=/"([a-z][a-z0-9-]{0,63})"\s*:/g;function decodePrivateFdTable(encoded){let value;try{value=encoded.length>4096?void 0:JSON.parse(encoded)}catch{value=void 0}if(typeof value!="object"||value===null||Array.isArray(value)){let names=[];for(let match of encoded.slice(0,4096).matchAll(QUOTED_NAME))match[1]!==void 0&&names.push(match[1]);return{parsed:!1,names}}return{parsed:!0,entries:Object.entries(value).filter(([name])=>NAME.test(name)),values:Object.values(value)}}import{fstatSync}from"node:fs";var clearInherit;function clearPrivateFdInherit(fd){try{if(fstatSync(fd),clearInherit===void 0){let ffi=process.getBuiltinModule("bun:ffi");if(ffi===void 0)return!1;let crt=ffi.dlopen("ucrtbase.dll",{_get_osfhandle:{args:[ffi.FFIType.i32],returns:ffi.FFIType.ptr}}),kernel=ffi.dlopen("kernel32.dll",{SetHandleInformation:{args:[ffi.FFIType.ptr,ffi.FFIType.u32,ffi.FFIType.u32],returns:ffi.FFIType.i32}}),invalidHandle=BigInt.asUintN(process.arch==="ia32"||process.arch==="arm"?32:64,-1n);clearInherit=descriptor=>{let handle=crt.symbols._get_osfhandle(descriptor);if(!handle)return!1;let pointer=BigInt(handle);return pointer===-1n||pointer===invalidHandle||handle===Number(invalidHandle)?!1:kernel.symbols.SetHandleInformation(handle,1,0)===1}}return clearInherit(fd)}catch{return!1}}var PRIVATE_FDS_FINAL_ENV="SENPI_PRIVATE_FDS_FINAL",STATE=Symbol.for("senpi.private-fds.v3"),WINDOWS_PRIVATE_FD_PAIR_PROVEN={bun:"1.4.4"};function isState(value){return typeof value=="object"&&value!==null&&"declared"in value&&value.declared instanceof Set&&"channels"in value&&value.channels instanceof Map&&"forward"in value&&value.forward instanceof Map}var ADOPTABLE_MAX=15;function ipcDescriptor(){let channel=Reflect.get(process,"channel");if(typeof channel!="object"||channel===null)return null;let fd=Reflect.get(channel,"fd");return typeof fd=="number"?fd:void 0}function isSocket(fd){try{return fstatSync2(fd).isSocket()}catch{return!1}}function isPipe(fd){try{return isFifoMode(fstatSync2(fd).mode)}catch{return!1}}function inRange(fd){return typeof fd=="number"&&Number.isSafeInteger(fd)&&fd>=5&&fd<=64}function inspectEntry(fd,shared,runtime,cleared){let{ipc}=runtime;return Array.isArray(fd)?runtime.platform!=="win32"||runtime.proven===!1||runtime.bun!==runtime.proven.bun||fd.length!==2||!inRange(fd[0])||!inRange(fd[1])||fd[0]===fd[1]||shared||ipc===void 0||fd[0]===ipc||fd[1]===ipc||!runtime.isPipe(fd[0])||!runtime.isPipe(fd[1])?{channel:null,discard:null}:{channel:cleared.get(fd[0])&&cleared.get(fd[1])?[fd[0],fd[1]]:null,discard:null}:inRange(fd)?runtime.platform==="win32"||ipc===void 0||fd===ipc||!runtime.isSocket(fd)?{channel:null,discard:null}:shared||fd>ADOPTABLE_MAX?{channel:null,discard:fd}:{channel:fd,discard:null}:{channel:null,discard:null}}function parseTable(encoded,inspection={}){let table=decodePrivateFdTable(encoded),entries=new Map;if(!table.parsed){for(let name of table.names)entries.set(name,null);return{entries,parsed:!1,discard:new Set}}let raw=table.entries,runtime={platform:process.platform,bun:process.versions.bun,proven:WINDOWS_PRIVATE_FD_PAIR_PROVEN,ipc:ipcDescriptor(),isSocket,isPipe,clearInherit:clearPrivateFdInherit,...inspection},cleared=new Map;if(runtime.platform==="win32")for(let fd of table.values)for(let number of Array.isArray(fd)?fd:[fd])inRange(number)&&!cleared.has(number)&&cleared.set(number,runtime.clearInherit(number));let counts=new Map;for(let[,fd]of raw)for(let number of Array.isArray(fd)?fd:[fd])typeof number=="number"&&counts.set(number,(counts.get(number)??0)+1);let discard=new Set;for(let[name,fd]of raw){let shared=(Array.isArray(fd)?fd:[fd]).some(number=>typeof number=="number"&&(counts.get(number)??0)>1),entry=inspectEntry(fd,shared,runtime,cleared);entries.set(name,entry.channel),entry.discard!==null&&discard.add(entry.discard)}for(let[fd,ok]of cleared)!ok&&fd!==runtime.ipc&&discard.add(fd);return{entries,parsed:!0,discard}}function closeDiscarded(fd,close=closeSync){try{close(fd)}catch(error){if(!(error instanceof Error&&"code"in error&&error.code==="EBADF"))throw error}}function capturedState(){let previous=Reflect.get(globalThis,STATE);if(isState(previous))return previous;let encoded=isMainThread?process.env[PRIVATE_FDS_TABLE_ENV]:void 0,final=isMainThread&&process.env[PRIVATE_FDS_FINAL_ENV]==="1";isMainThread&&(delete process.env[PRIVATE_FDS_TABLE_ENV],delete process.env[PRIVATE_FDS_FINAL_ENV]);let{entries,parsed,discard}=encoded?parseTable(encoded):{entries:new Map,parsed:!0,discard:new Set};for(let fd of discard)closeDiscarded(fd);let unparseable=!parsed&&entries.size===0,state2={present:!!encoded,declared:new Set(entries.keys()),unparseable,channels:new Map,forward:new Map,forwardUnparseable:unparseable&&!final};for(let[name,fd]of entries)fd!==null&&state2.channels.set(name,fd),final||state2.forward.set(name,fd);return Reflect.set(globalThis,STATE,state2),state2}var state=capturedState();function privateTablePresent(){return state.present}function takePrivateDescriptors(){if(state.forwardUnparseable)return{kind:"unparseable"};let entries=new Map(state.forward);for(let[name,fd]of entries)state.forward.set(name,null),fd!==null&&state.channels.delete(name);return{kind:"entries",entries}}import{closeSync as closeSync2}from"node:fs";function withStartupPipe(base){let stdio=[...base],fillers=[];for(let slot=3;slot<16;slot+=1){let entry=stdio[slot];(entry==null||entry==="ignore")&&(stdio[slot]="pipe",fillers.push(slot))}return stdio[16]="pipe",{stdio,fillers}}function releaseStartupFillers(child,fillers){for(let slot of fillers){let stream=child.stdio[slot];typeof stream=="object"&&stream!==null&&"destroy"in stream&&typeof stream.destroy=="function"&&stream.destroy()}}function namedPrivateSlots(encoded){let slots=new Set;if(!encoded)return slots;let table=decodePrivateFdTable(encoded);if(table.parsed){for(let entry of table.values)for(let fd of[entry].flat())typeof fd=="number"&&slots.add(fd);return slots}}function releaseInheritedStartupFillers(env){let handOff=parseStartupHandOff(env[HOST_STARTUP_EVENTS_ENV]);if(!handOff?.fillers?.length)return;let privateSlots=namedPrivateSlots(env[PRIVATE_FDS_TABLE_ENV]);if(privateSlots){for(let slot of handOff.fillers)if(!privateSlots.has(slot))try{closeSync2(slot)}catch{}}env[HOST_STARTUP_EVENTS_ENV]=encodeStartupHandOff({...handOff,fillers:[]})}export{STARTUP_ATTEMPT_FILE,ADOPTION_GRANT_FILE,encodeStartupHandOff,parseStartupHandOff,startupEventLine,startupGrantLine,relayStartupLine,UNPARSEABLE_TABLE,withStartupPipe,releaseStartupFillers,releaseInheritedStartupFillers,PRIVATE_FDS_FINAL_ENV,privateTablePresent,takePrivateDescriptors};
|
|
5
|
+
`}import{closeSync,fstatSync as fstatSync2}from"node:fs";import{isMainThread}from"node:worker_threads";var PRIVATE_FDS_TABLE_ENV="SENPI_PRIVATE_FDS",UNPARSEABLE_TABLE="unparseable";var NAME=/^[a-z][a-z0-9-]{0,63}$/,QUOTED_NAME=/"([a-z][a-z0-9-]{0,63})"\s*:/g;function decodePrivateFdTable(encoded){let value;try{value=encoded.length>4096?void 0:JSON.parse(encoded)}catch{value=void 0}if(typeof value!="object"||value===null||Array.isArray(value)){let names=[];for(let match of encoded.slice(0,4096).matchAll(QUOTED_NAME))match[1]!==void 0&&names.push(match[1]);return{parsed:!1,names}}return{parsed:!0,entries:Object.entries(value).filter(([name])=>NAME.test(name)),values:Object.values(value)}}import{fstatSync}from"node:fs";var clearInherit;function clearPrivateFdInherit(fd){try{if(fstatSync(fd),clearInherit===void 0){let ffi=process.getBuiltinModule("bun:ffi");if(ffi===void 0)return!1;let crt=ffi.dlopen("ucrtbase.dll",{_get_osfhandle:{args:[ffi.FFIType.i32],returns:ffi.FFIType.ptr}}),kernel=ffi.dlopen("kernel32.dll",{SetHandleInformation:{args:[ffi.FFIType.ptr,ffi.FFIType.u32,ffi.FFIType.u32],returns:ffi.FFIType.i32}}),invalidHandle=BigInt.asUintN(process.arch==="ia32"||process.arch==="arm"?32:64,-1n);clearInherit=descriptor=>{let handle=crt.symbols._get_osfhandle(descriptor);if(!handle)return!1;let pointer=BigInt(handle);return pointer===-1n||pointer===invalidHandle||handle===Number(invalidHandle)?!1:kernel.symbols.SetHandleInformation(handle,1,0)===1}}return clearInherit(fd)}catch{return!1}}var PRIVATE_FDS_FINAL_ENV="SENPI_PRIVATE_FDS_FINAL",STATE=Symbol.for("senpi.private-fds.v3"),WINDOWS_PRIVATE_FD_PAIR_PROVEN={bun:"1.4.4"};function isState(value){return typeof value=="object"&&value!==null&&"declared"in value&&value.declared instanceof Set&&"channels"in value&&value.channels instanceof Map&&"forward"in value&&value.forward instanceof Map}var ADOPTABLE_MAX=15;function ipcDescriptor(){let channel=Reflect.get(process,"channel");if(typeof channel!="object"||channel===null)return null;let fd=Reflect.get(channel,"fd");return typeof fd=="number"?fd:void 0}function isSocket(fd){try{return fstatSync2(fd).isSocket()}catch{return!1}}function isPipe(fd){try{return isFifoMode(fstatSync2(fd).mode)}catch{return!1}}function inRange(fd){return typeof fd=="number"&&Number.isSafeInteger(fd)&&fd>=5&&fd<=64}function inspectEntry(fd,shared,runtime,cleared){let{ipc}=runtime;return Array.isArray(fd)?runtime.platform!=="win32"||runtime.proven===!1||runtime.bun!==runtime.proven.bun||fd.length!==2||!inRange(fd[0])||!inRange(fd[1])||fd[0]===fd[1]||shared||ipc===void 0||fd[0]===ipc||fd[1]===ipc||!runtime.isPipe(fd[0])||!runtime.isPipe(fd[1])?{channel:null,discard:null}:{channel:cleared.get(fd[0])&&cleared.get(fd[1])?[fd[0],fd[1]]:null,discard:null}:inRange(fd)?runtime.platform==="win32"||ipc===void 0||fd===ipc||!runtime.isSocket(fd)?{channel:null,discard:null}:shared||fd>ADOPTABLE_MAX?{channel:null,discard:fd}:{channel:fd,discard:null}:{channel:null,discard:null}}function parseTable(encoded,inspection={}){let table=decodePrivateFdTable(encoded),entries=new Map;if(!table.parsed){for(let name of table.names)entries.set(name,null);return{entries,parsed:!1,discard:new Set}}let raw=table.entries,runtime={platform:process.platform,bun:process.versions.bun,proven:WINDOWS_PRIVATE_FD_PAIR_PROVEN,ipc:ipcDescriptor(),isSocket,isPipe,clearInherit:clearPrivateFdInherit,...inspection},cleared=new Map;if(runtime.platform==="win32")for(let fd of table.values)for(let number of Array.isArray(fd)?fd:[fd])inRange(number)&&!cleared.has(number)&&cleared.set(number,runtime.clearInherit(number));let counts=new Map;for(let[,fd]of raw)for(let number of Array.isArray(fd)?fd:[fd])typeof number=="number"&&counts.set(number,(counts.get(number)??0)+1);let discard=new Set;for(let[name,fd]of raw){let shared=(Array.isArray(fd)?fd:[fd]).some(number=>typeof number=="number"&&(counts.get(number)??0)>1),entry=inspectEntry(fd,shared,runtime,cleared);entries.set(name,entry.channel),entry.discard!==null&&discard.add(entry.discard)}for(let[fd,ok]of cleared)!ok&&fd!==runtime.ipc&&discard.add(fd);return{entries,parsed:!0,discard}}function closeDiscarded(fd,close=closeSync){try{close(fd)}catch(error){if(!(error instanceof Error&&"code"in error&&error.code==="EBADF"))throw error}}function capturedState(){let previous=Reflect.get(globalThis,STATE);if(isState(previous))return previous;let encoded=isMainThread?process.env[PRIVATE_FDS_TABLE_ENV]:void 0,final=isMainThread&&process.env[PRIVATE_FDS_FINAL_ENV]==="1";isMainThread&&(delete process.env[PRIVATE_FDS_TABLE_ENV],delete process.env[PRIVATE_FDS_FINAL_ENV]);let{entries,parsed,discard}=encoded?parseTable(encoded):{entries:new Map,parsed:!0,discard:new Set};for(let fd of discard)closeDiscarded(fd);let unparseable=!parsed&&entries.size===0,state2={present:!!encoded,declared:new Set(entries.keys()),unparseable,channels:new Map,forward:new Map,forwardUnparseable:unparseable&&!final};for(let[name,fd]of entries)fd!==null&&state2.channels.set(name,fd),final||state2.forward.set(name,fd);return Reflect.set(globalThis,STATE,state2),state2}var state=capturedState();function privateTablePresent(){return state.present}function takePrivateDescriptors(){if(state.forwardUnparseable)return{kind:"unparseable"};let entries=new Map(state.forward);for(let[name,fd]of entries)state.forward.set(name,null),fd!==null&&state.channels.delete(name);return{kind:"entries",entries}}import{closeSync as closeSync2,fstatSync as fstatSync3}from"node:fs";function withStartupPipe(base){let stdio=[...base],fillers=[];for(let slot=3;slot<16;slot+=1){let entry=stdio[slot];(entry==null||entry==="ignore")&&(stdio[slot]="pipe",fillers.push(slot))}return stdio[16]="pipe",{stdio,fillers}}function releaseStartupFillers(child,fillers){for(let slot of fillers){let stream=child.stdio[slot];typeof stream=="object"&&stream!==null&&"destroy"in stream&&typeof stream.destroy=="function"&&stream.destroy()}}function namedPrivateSlots(encoded){let slots=new Set;if(!encoded)return slots;let table=decodePrivateFdTable(encoded);if(table.parsed){for(let entry of table.values)for(let fd of[entry].flat())typeof fd=="number"&&slots.add(fd);return slots}}function statOf(fd){try{return fstatSync3(fd)}catch{return}}var sameFile=(a,b)=>a.dev===b.dev&&a.ino===b.ino;function inheritedFillerCheck(){if(process.platform==="win32")return()=>!0;let startup=statOf(16);if(!startup?.isSocket())return()=>!1;let kept=[startup,...[0,1,2].map(statOf).filter(stat=>stat!==void 0)];return slot=>{let stat=statOf(slot);return stat!==void 0&&stat.isSocket()&&!kept.some(other=>sameFile(stat,other))}}function releaseInheritedStartupFillers(env){let handOff=parseStartupHandOff(env[HOST_STARTUP_EVENTS_ENV]);if(!handOff?.fillers?.length)return;let privateSlots=namedPrivateSlots(env[PRIVATE_FDS_TABLE_ENV]);if(privateSlots){let inherited=inheritedFillerCheck();for(let slot of handOff.fillers)if(!(privateSlots.has(slot)||!inherited(slot)))try{closeSync2(slot)}catch{}}env[HOST_STARTUP_EVENTS_ENV]=encodeStartupHandOff({...handOff,fillers:[]})}export{STARTUP_ATTEMPT_FILE,ADOPTION_GRANT_FILE,encodeStartupHandOff,parseStartupHandOff,startupEventLine,startupGrantLine,relayStartupLine,UNPARSEABLE_TABLE,withStartupPipe,releaseStartupFillers,releaseInheritedStartupFillers,PRIVATE_FDS_FINAL_ENV,privateTablePresent,takePrivateDescriptors};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{CUSTOM_UNSUPPORTED_CAPABILITY,DEFAULT_PROBE_TIMEOUT_MS,DEFAULT_STOP_TIMEOUT_MS,ENDPOINT_OWNER_FENCE_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,RPC_CLIENT_CAPABILITIES_ENV,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SIGKILL_GRACE_MS,STARTUP_DECISION_BUDGET_MS,STOP_WAIT_BUDGET_MS,announceStop,anyGenerationLive,busyLegacyHostDetail,computeRuntimeBuildId,decideHostAction,delay,describeSessions,electPointer,engineBuildIdentity,ensureLockWaitDetail,ensureSender,gcEndpoint,gcHostEndpoints,holdProtocolInfo,holdSessionCount,hostLaunchProfile,isNodeErrorCode,judgeStaleEngine,matchesPidFileOrUnknown,observeProtocolInfo,parseHostStopGeneration,probeProtocolInfo,probeSocketReachable,provenLegacyOwner,recordEscalation,resolvePidFileOwnership,retireIdleLegacyHost,signalGeneration,signalPid,socketHostLaunchProfile,staleStopGeneration,startStartupController,startupEnvelope,startupTimeoutDetail,stopHost,stopManagedHost,stopSpawnedChild}from"./chunk-Z2C5N2LM.js";import{endpointKindOfSocket,listHostEndpoints}from"./chunk-DZQA5LVN.js";import{isSessionRuntimeKind,isToolRuntimeKind,toolRuntimeCapability}from"./chunk-IEY2SL46.js";import{requestOnSocket}from"./chunk-4JMGWVRH.js";import{rpcKeyRoot,withRpcKeyRoot}from"./chunk-E5O4SP5I.js";import{adoptedEngineTrustHandOff}from"./chunk-DX43FSQT.js";import{MCP_PRESENTER_BOOTSTRAP_FD,presenterBootstrapStream,relayPresenterBootstrap}from"./chunk-7WYJAYHH.js";import{ALIAS_LINK,ALIAS_OWNER,ALIAS_PREFIX,INTERNAL_HOST_DIR_PREFIX,INTERNAL_SUPERVISOR_FLAG,OWNER_WATCH_FD,bindAliasRoots,internalHostDirRoots,keepOwnerPipe,loopLagErrorMs,readAliasOwnerStartTime,resolveCliMainPath,settleCandidateAdoption}from"./chunk-47T6YMI2.js";import{DEFAULT_HOST_IDLE_EXIT_MS,acquireHostEnsureLock,childStalledStopMaxMs,claimOwnerIsLive,clearHostRegistration,hostChildAlive,hostEnsureLockOptions,hostEnsureLockTarget,hostLoopStalled,isHostCrash,provenOwner,pruneDeadGenerations,readGenerationRows,readHostCrashRecords,readHostProcessMetrics,readHostRegistration,readSessionPathClaims,releaseGeneration,stallRefusalWindowMs,writeGenerationRecord,writeHostRegistration,writtenByThisProcess}from"./chunk-UCXBDE6R.js";import{HOST_DAEMON_DIR_ENV,HOST_STATE_FILE_MODE,callerHostOwner,claimHostOwner,createDaemonDirectories,createHostDaemonPaths,ensureEndpointIdentity,generationPaths,hostDaemonDirectoryPaths,parseJson,parseShardSocket,readFileOrUndefined,readHostOwner,readHostSettings,readJsonObject,sameEndpoint,sameHostOwner,sessionDirectoryRemoved,shardKey,shardSocketPathForKey,writeHostOwner,writeHostSettings,writeJsonAtomic,writeStateFile}from"./chunk-YI6KRJDC.js";import{OBSERVE_REQUEST_FIELD,gcRpcPublicKeys}from"./chunk-VUY4BZDI.js";import{envSlotVarNames}from"./chunk-C4AHHZ6P.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{providerCredentialEnvNames}from"./chunk-Z6TEQEZO.js";import{runtimeExecArgv,spawnWithPrivateFds}from"./chunk-E266ORGA.js";import{ADOPTION_GRANT_FILE,STARTUP_ATTEMPT_FILE,encodeStartupHandOff,releaseStartupFillers,startupGrantLine,withStartupPipe}from"./chunk-T2SMQPRE.js";import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV,HOST_STARTUP_EVENTS_ENV}from"./chunk-RUGTHELO.js";import{MAX_SOCKET_PATH_BYTES,generationBindPath,socketEntryListenerState,statSocketIdentity}from"./chunk-5XHOHZIR.js";import{acquireOwnershipSafeLock,ensureSocketSecret,isBusy,socketSecretPath}from"./chunk-HW6AAS3R.js";import{APP_NAME,ENV_AGENT_DIR,envValue,getAgentDir,isBunBinary}from"./chunk-SODMQEHO.js";import{ProcessIdentityUnreadableError,processIsLive,processMatchesPidFile,readProcessStartTime,waitForStartTime}from"./chunk-O5RYI3IW.js";import{writeSync as writeSync2}from"node:fs";import{join as join9,resolve as resolve5}from"node:path";import{readFile,realpath,stat}from"node:fs/promises";import{dirname,isAbsolute,relative,resolve}from"node:path";var SPEC_ENV_NAME=/^(SENPI|OMO|PI)_[A-Z0-9_]+$/u,HostLaunchSpecError=class extends Error{constructor(reason,detail){super(`${reason}: ${detail}`),this.name="HostLaunchSpecError",this.reason=reason,this.detail=detail}},DEFAULT_HOST_LAUNCH_SPEC={hostArgs:[],policy:{},env:{}};async function loadHostLaunchSpec(specPath,platform=process.platform){let absolute=resolve(specPath);await assertTrustedFile(absolute,platform);let spec=parseHostLaunchSpec(await readSpecText(absolute)),env=trustedEnv(spec.env),extensions=await resolveExtensions(spec.core.extensions,dirname(absolute));return{hostArgs:["--session-runtime",spec.core.session_runtime,...extensions.flatMap(path=>["--extension",path])],policy:{...spec.tunables?.idleExitMs!==void 0&&{idleExitMs:spec.tunables.idleExitMs},...spec.tunables?.coldStart!==void 0&&{coldStart:spec.tunables.coldStart}},env}}function parseHostLaunchSpec(text){let parsed;try{parsed=JSON.parse(text)}catch(error){throw new HostLaunchSpecError("launch_spec_invalid",error instanceof Error?error.message:"not JSON")}if(!isRecord(parsed))throw new HostLaunchSpecError("launch_spec_invalid","the spec is not a JSON object");if(parsed.spec_version!==1)throw new HostLaunchSpecError("launch_spec_invalid",`unsupported spec_version ${String(parsed.spec_version)}`);let core=parsed.core;if(!isRecord(core))throw new HostLaunchSpecError("launch_spec_invalid","core must be an object");if(typeof core.session_runtime!="string"||!isSessionRuntimeKind(core.session_runtime))throw new HostLaunchSpecError("launch_spec_invalid","core.session_runtime must be in-process or worker");if(core.multi_session!==!0)throw new HostLaunchSpecError("launch_spec_invalid","core.multi_session must be true");if(!Array.isArray(core.extensions)||!core.extensions.every(entry=>typeof entry=="string"))throw new HostLaunchSpecError("launch_spec_invalid","core.extensions must be an array of strings");let tunables=parsedTunables(parsed.tunables);return{spec_version:1,core:{session_runtime:core.session_runtime,multi_session:!0,extensions:core.extensions},...tunables&&{tunables},...isRecord(parsed.env)&&{env:parsedEnv(parsed.env)}}}async function readSpecText(absolute){try{return await readFile(absolute,"utf8")}catch(error){throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}}async function assertTrustedFile(absolute,platform){if(platform==="win32")return;let stats=await stat(absolute).catch(error=>{throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}),uid=process.getuid?.();if(uid!==void 0&&stats.uid!==uid)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is owned by uid ${stats.uid}, not ${uid}`);if((stats.mode&18)!==0)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is group/world writable (mode ${(stats.mode&511).toString(8)})`)}function trustedEnv(env){for(let name of Object.keys(env??{}))if(!SPEC_ENV_NAME.test(name))throw new HostLaunchSpecError("launch_spec_env_denied",`${name} is outside ${SPEC_ENV_NAME.source}`);return env??{}}async function resolveExtensions(extensions,specDir){let rootReal=await realpath(specDir).catch(()=>specDir),resolved=[];for(let entry of extensions){let target=resolve(specDir,entry);if(escapes(specDir,target))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} resolves outside ${specDir}`);let real=await realpath(target).catch(()=>{});if(real===void 0)throw new HostLaunchSpecError("launch_spec_missing_extension",`${target} does not exist`);if(escapes(rootReal,real))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} links outside ${specDir}`);resolved.push(real)}return resolved}function escapes(root,target){let step=relative(root,target);return step.startsWith("..")||isAbsolute(step)}function parsedTunables(value){if(!isRecord(value))return;let idleExitMs=value.idleExitMs,coldStart=value.coldStart;return{...typeof idleExitMs=="number"&&Number.isFinite(idleExitMs)&&idleExitMs>0&&{idleExitMs},...(coldStart==="transient"||coldStart==="persistent")&&{coldStart}}}function parsedEnv(value){let env={};for(let[name,entry]of Object.entries(value)){if(typeof entry!="string")throw new HostLaunchSpecError("launch_spec_invalid",`env.${name} must be a string`);env[name]=entry}return env}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{join}from"node:path";var ALLOWED_ENV_NAMES=[/^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TERM|LANG)$/u,/^(LC|XDG)_/u,/^(SENPI|OMO|PI)_/u,/^BSK_(HOME|BIN)$/u,/^(HTTPS?_PROXY|NO_PROXY)$/u,/^[A-Z0-9_]+_API_KEY$/u,/^(ANTHROPIC|OPENAI|GOOGLE|GEMINI|AZURE|AWS|OPENROUTER|XAI|MISTRAL|DEEPSEEK|GROQ|CEREBRAS|MINIMAX)_/u],PROVIDER_CREDENTIAL_ENV_NAMES=new Set([...providerCredentialEnvNames(),...envSlotVarNames()]),WINDOWS_SYSTEM_ENV_NAMES=new Set(["SYSTEMROOT","SYSTEMDRIVE","WINDIR","COMSPEC","PATHEXT","TEMP","TMP","USERPROFILE","APPDATA","LOCALAPPDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","HOMEDRIVE","HOMEPATH","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"]),TRANSIENT_ENV_NAMES=new Set(["PI_SESSION_ID","PI_SESSION_FILE","PI_SESSION_CWD","PI_GOAL_STORE_FILE","PI_PROVIDER","PI_MODEL","PI_REASONING_LEVEL","OMO_BROWSER_ENGINE","PI_PROMPT_CACHE_SAFE_WAIT_SECONDS","SENPI_PY_KERNEL_PARENT_PID","SENPI_RPC_HOST_WATCH_FD","SENPI_RPC_HOST_WATCH_PPID","SENPI_RPC_HOST_SCRATCH_DIR","SENPI_RPC_HOST_CLEANUP_PATHS","SENPI_RPC_HOST_PUBLIC_SOCKET","SENPI_RPC_HOST_INSTANCE_ID","SENPI_RPC_HOST_GENERATION","SENPI_RPC_HOST_DAEMON_DIR","SENPI_RPC_HOST_EXPECTED_RUNTIME_BUILD_ID","SENPI_RPC_HOST_STARTUP_EVENTS","SENPI_RPC_INTERNAL_KEY_STDIN","SENPI_RPC_HOST_WATCH_PSTART","SENPI_RPC_HOST_WATCH_PSTART_TICKS","SENPI_RPC_HOST_LIFETIME_FIFO","SENPI_RPC_SOCKET_SECRET_FILE","SENPI_ENGINE_TRUST","SENPI_ENGINE_TRUST_HOP"]);function isTransientDaemonEnvName(name){return TRANSIENT_ENV_NAMES.has(name)}function daemonEnvIsAllowed(name,platform=process.platform){let upper=name.toUpperCase();return TRANSIENT_ENV_NAMES.has(platform==="win32"?upper:name)?!1:platform!=="win32"?PROVIDER_CREDENTIAL_ENV_NAMES.has(name)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(name)):WINDOWS_SYSTEM_ENV_NAMES.has(upper)||PROVIDER_CREDENTIAL_ENV_NAMES.has(upper)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(upper))}function daemonEnvOverrides(processEnv,specEnv={},platform=process.platform){let overrides={};for(let name of Object.keys(processEnv))daemonEnvIsAllowed(name,platform)||(overrides[name]=null);for(let[name,value]of Object.entries(specEnv))daemonEnvIsAllowed(name,platform)&&(overrides[name]=value);return overrides}function daemonEnvironment(processEnv,overrides={},forced={},platform=process.platform){let env={};for(let[name,value]of Object.entries(processEnv))value!==void 0&&daemonEnvIsAllowed(name,platform)&&(env[name]=value);for(let[name,value]of Object.entries(overrides))daemonEnvIsAllowed(name,platform)&&(deleteEnvironmentName(env,name,platform),value!==null&&(env[name]=value));for(let[name,value]of Object.entries(forced))deleteEnvironmentName(env,name,platform),env[name]=value;return env}function daemonEnvKeys(processEnv,specEnv={},platform=process.platform){let kept=Object.keys(processEnv).filter(name=>daemonEnvIsAllowed(name,platform)),explicit=Object.keys(specEnv).filter(name=>daemonEnvIsAllowed(name,platform));return[...new Set([...kept,...explicit])].sort()}async function writeDaemonEnvKeys(paths,keys){await writeStateFile(daemonEnvKeysFile(paths),{env_keys:keys})}async function readDaemonEnvKeys(paths){let keys=parseJson(await readFileOrUndefined(daemonEnvKeysFile(paths)))?.env_keys;return Array.isArray(keys)?keys.filter(key=>typeof key=="string"):[]}function daemonEnvKeysFile(paths){return join(paths.dir,"env-keys.json")}function deleteEnvironmentName(env,name,platform){if(platform!=="win32"){delete env[name];return}let upper=name.toUpperCase();for(let existing of Object.keys(env))existing.toUpperCase()===upper&&delete env[existing]}import{mkdir,writeFile as writeFile4}from"node:fs/promises";import{dirname as dirname4}from"node:path";var hostGenerationScopes=0;function isHostGenerationProcess(){return hostGenerationScopes>0}async function runAsHostGenerationProcess(action){hostGenerationScopes+=1;try{return await action()}finally{hostGenerationScopes-=1}}function decideEnsureAction(options,startedByUs,protocol){if(options.upgrade!=="if-engine-differs"||isHostGenerationProcess())return decideHostAction(ensureClient(options,startedByUs),protocol,"never");let decision=decideHostAction(ensureClient(options,startedByUs),protocol,"upgrade");return decision.action==="fallback"?{action:"reuse",reason:"compatible",upgradeable:!1}:decision}function ensureClient(options,startedByUs){return{protocolVersion:HOST_PROTOCOL_VERSION,requiredCapabilities:[...REQUIRED_HOST_CAPABILITIES,...requestedToolRuntime(options.hostArgs??[])],identity:engineBuildIdentity(),...options.upgrade==="if-engine-differs"?{launchProfile:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd())}:{},startedByUs,platform:process.platform}}function requestedToolRuntime(hostArgs){for(let index=0;index<hostArgs.length;index++){let arg=hostArgs[index]??"",value=arg==="--tool-runtime"?hostArgs[index+1]:arg.startsWith("--tool-runtime=")?arg.slice(15):void 0;if(value!==void 0&&isToolRuntimeKind(value))return[toolRuntimeCapability(value)]}return[]}function hostChildArgv(hostArgs){return["--mode","rpc","--multi-session",...hostArgs]}function isCompatible(protocol){return decideHostAction(ensureClient({socket:""},!1),protocol,"never").action==="reuse"}import{lstat}from"node:fs/promises";async function refuseIfStalled(paths,instanceId,socket,protocol){let generation=generationPaths(paths,instanceId);if(await hostLoopStalled(generation,{now:Date.now(),errorMs:loopLagErrorMs(),windowMs:stallRefusalWindowMs()})&&await hostChildAlive(generation)!==!1)throw new HostEnsureRefusedError(socket,"host_stalled",protocol)}async function refuseIfForeignHeld(paths,registered,socket,protocol){if(!await publicEndpointAccepts(socket))return;let holder=await readHostHolder(paths,registered);throw new HostEnsureRefusedError(socket,"foreign_writer",protocol,void 0,holder)}async function readHostHolder(paths,registered){let record=parseJson(await readFileOrUndefined(generationPaths(paths,registered.instanceId).pidFile))??{};return{pid:registered.record.pid,instanceId:registered.instanceId,generation:registered.generation,processStartTime:registered.record.processStartTime,engineVersion:typeof record.engineVersion=="string"?record.engineVersion:null,launchProfileId:typeof record.launchProfileId=="string"?record.launchProfileId:null,writerPid:registered.writer?.pid??null}}var FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS=2e3;async function publicEndpointAccepts(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!0;let entry=await statSocketIdentity(socket).then(identity=>identity===void 0?"absent":"present",()=>"unknown");return entry==="absent"?!1:entry==="unknown"?!0:probeSocketReachable(socket,FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS)}async function unregisteredEndpointHeld(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!1;let entry=await lstat(socket).then(found=>found.isSocket()?"socket":"not-socket",cause=>cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"?"absent":"unknown");return entry==="absent"?!1:entry!=="socket"?!0:(await socketEntryListenerState(socket)).verdict==="live"}import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{open,readFile as readFile2}from"node:fs/promises";import{existsSync}from"node:fs";import{basename,dirname as dirname2,join as join2,resolve as resolve2}from"node:path";import{fileURLToPath}from"node:url";var PINNED_HOST_CLIENT_CAPABILITIES=[EXTENSION_EVENTS_CAPABILITY,CUSTOM_UNSUPPORTED_CAPABILITY];function defaultHostLaunch(supervisorArgs,compiled=isBunBinary,sibling=resolveHostLifecycleEntryPath()??null,bundledSupervisor=resolveBundledSupervisorEntryPath()??null){return compiled?{command:process.execPath,args:[INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:sibling!==null?{command:process.execPath,args:[...runtimeExecArgv(),sibling,...supervisorArgs]}:bundledSupervisor!==null?{command:process.execPath,args:[...runtimeExecArgv(),bundledSupervisor,INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:{command:process.execPath,args:[...runtimeExecArgv(),resolveCliMainPath(),INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}}var BUNDLED_SUPERVISOR_ENTRY="host-supervisor.js";function resolveBundledSupervisorEntryPath(){let entry=join2(dirname2(resolveCliMainPath()),BUNDLED_SUPERVISOR_ENTRY);return existsSync(entry)?entry:void 0}function resolveHostLifecycleEntryPath(){let modulePath=fileURLToPath(import.meta.url);if(basename(dirname2(modulePath))==="chunks")return;let extension=modulePath.endsWith(".ts")?".ts":".js",sibling=resolve2(dirname2(modulePath),`host-lifecycle${extension}`);return existsSync(sibling)?sibling:void 0}import{randomBytes}from"node:crypto";var MAX_STARTUP_EVENTS_PER_PRODUCER=32,STARTUP_MILESTONE_PRODUCER={supervisor_bootstrap:"supervisor",supervisor_setup:"supervisor",host_opaque:"supervisor",host_bootstrap:"host",host_runtime:"host",internal_ready:"supervisor",observer_ready:"supervisor",public_published:"supervisor"};function newStartupAttempt(){return randomBytes(16).toString("hex")}function startupEventIngress(controller,binding,role){let lastSeq=0,records=0,failProtocol=reason=>(controller.fail(new Error(`RPC host startup protocol failure (${role}): ${reason}`)),"protocol_failure");return line=>{if(Buffer.byteLength(line,"utf8")>4096)return failProtocol("record exceeds 4096 bytes");let record=parseRecord(line);if(!record)return failProtocol("malformed record");if(!sameBinding(record.binding,binding))return"discarded";if(record.role!==role)return failProtocol(`record claims role ${String(record.role)}`);if(record.seq<=lastSeq)return"ignored";if(record.seq!==lastSeq+1)return failProtocol(`sequence gap after ${lastSeq}`);if(records+=1,records>MAX_STARTUP_EVENTS_PER_PRODUCER)return failProtocol("too many records");lastSeq=record.seq;let milestone=record.milestone;if(!isProducerMilestone(milestone))return failProtocol(`unknown milestone ${String(milestone)}`);if(STARTUP_MILESTONE_PRODUCER[milestone]!==role)return failProtocol(`${role} cannot report ${milestone}`);let verdict=milestone==="host_opaque"?controller.declareOpaqueHost():controller.complete(milestone);return verdict!=="rejected"?verdict:controller.terminal?"ignored":failProtocol(`${milestone} reported before its phase was granted`)}}function attachStartupEvents(stream,controller,binding){let supervisor=startupEventIngress(controller,binding,"supervisor"),host=startupEventIngress(controller,binding,"host"),maxLine=2*4096+64,pending="";stream.setEncoding("utf8"),stream.on("data",chunk=>{if(!controller.terminal){pending+=chunk;for(let newline=pending.indexOf(`
|
|
2
|
+
import{CUSTOM_UNSUPPORTED_CAPABILITY,DEFAULT_PROBE_TIMEOUT_MS,DEFAULT_STOP_TIMEOUT_MS,ENDPOINT_OWNER_FENCE_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,HOST_PROTOCOL_VERSION,HostEnsureRefusedError,REQUIRED_HOST_CAPABILITIES,RPC_CLIENT_CAPABILITIES_ENV,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SIGKILL_GRACE_MS,STARTUP_DECISION_BUDGET_MS,STOP_WAIT_BUDGET_MS,announceStop,anyGenerationLive,busyLegacyHostDetail,computeRuntimeBuildId,decideHostAction,delay,describeSessions,electPointer,engineBuildIdentity,ensureLockWaitDetail,ensureSender,gcEndpoint,gcHostEndpoints,holdProtocolInfo,holdSessionCount,hostLaunchProfile,isNodeErrorCode,judgeStaleEngine,matchesPidFileOrUnknown,observeProtocolInfo,parseHostStopGeneration,probeProtocolInfo,probeSocketReachable,provenLegacyOwner,recordEscalation,resolvePidFileOwnership,retireIdleLegacyHost,signalGeneration,signalPid,socketHostLaunchProfile,staleStopGeneration,startStartupController,startupEnvelope,startupTimeoutDetail,stopHost,stopManagedHost,stopSpawnedChild}from"./chunk-5F2XC6UC.js";import{endpointKindOfSocket,listHostEndpoints}from"./chunk-DZQA5LVN.js";import{isSessionRuntimeKind,isToolRuntimeKind,toolRuntimeCapability}from"./chunk-IEY2SL46.js";import{requestOnSocket}from"./chunk-4JMGWVRH.js";import{rpcKeyRoot,withRpcKeyRoot}from"./chunk-E5O4SP5I.js";import{adoptedEngineTrustHandOff}from"./chunk-DX43FSQT.js";import{MCP_PRESENTER_BOOTSTRAP_FD,presenterBootstrapStream,relayPresenterBootstrap}from"./chunk-7WYJAYHH.js";import{ALIAS_LINK,ALIAS_OWNER,ALIAS_PREFIX,INTERNAL_HOST_DIR_PREFIX,INTERNAL_SUPERVISOR_FLAG,OWNER_WATCH_FD,bindAliasRoots,internalHostDirRoots,keepOwnerPipe,loopLagErrorMs,readAliasOwnerStartTime,resolveCliMainPath,settleCandidateAdoption}from"./chunk-IBDAV2AL.js";import{DEFAULT_HOST_IDLE_EXIT_MS,acquireHostEnsureLock,childStalledStopMaxMs,claimOwnerIsLive,clearHostRegistration,hostChildAlive,hostEnsureLockOptions,hostEnsureLockTarget,hostLoopStalled,isHostCrash,provenOwner,pruneDeadGenerations,readGenerationRows,readHostCrashRecords,readHostProcessMetrics,readHostRegistration,readSessionPathClaims,releaseGeneration,stallRefusalWindowMs,writeGenerationRecord,writeHostRegistration,writtenByThisProcess}from"./chunk-UCXBDE6R.js";import{HOST_DAEMON_DIR_ENV,HOST_STATE_FILE_MODE,callerHostOwner,claimHostOwner,createDaemonDirectories,createHostDaemonPaths,ensureEndpointIdentity,generationPaths,hostDaemonDirectoryPaths,parseJson,parseShardSocket,readFileOrUndefined,readHostOwner,readHostSettings,readJsonObject,sameEndpoint,sameHostOwner,sessionDirectoryRemoved,shardKey,shardSocketPathForKey,writeHostOwner,writeHostSettings,writeJsonAtomic,writeStateFile}from"./chunk-YI6KRJDC.js";import{OBSERVE_REQUEST_FIELD,gcRpcPublicKeys}from"./chunk-VUY4BZDI.js";import{envSlotVarNames}from"./chunk-C4AHHZ6P.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{providerCredentialEnvNames}from"./chunk-Z6TEQEZO.js";import{runtimeExecArgv,spawnWithPrivateFds}from"./chunk-LJFQYCFH.js";import{ADOPTION_GRANT_FILE,STARTUP_ATTEMPT_FILE,encodeStartupHandOff,releaseStartupFillers,startupGrantLine,withStartupPipe}from"./chunk-K3GAGIPX.js";import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV,HOST_STARTUP_EVENTS_ENV}from"./chunk-RUGTHELO.js";import{MAX_SOCKET_PATH_BYTES,generationBindPath,socketEntryListenerState,statSocketIdentity}from"./chunk-5XHOHZIR.js";import{acquireOwnershipSafeLock,ensureSocketSecret,isBusy,socketSecretPath}from"./chunk-HW6AAS3R.js";import{APP_NAME,ENV_AGENT_DIR,envValue,getAgentDir,isBunBinary}from"./chunk-SODMQEHO.js";import{ProcessIdentityUnreadableError,processIsLive,processMatchesPidFile,readProcessStartTime,waitForStartTime}from"./chunk-O5RYI3IW.js";import{writeSync as writeSync2}from"node:fs";import{join as join9,resolve as resolve5}from"node:path";import{readFile,realpath,stat}from"node:fs/promises";import{dirname,isAbsolute,relative,resolve}from"node:path";var SPEC_ENV_NAME=/^(SENPI|OMO|PI)_[A-Z0-9_]+$/u,HostLaunchSpecError=class extends Error{constructor(reason,detail){super(`${reason}: ${detail}`),this.name="HostLaunchSpecError",this.reason=reason,this.detail=detail}},DEFAULT_HOST_LAUNCH_SPEC={hostArgs:[],policy:{},env:{}};async function loadHostLaunchSpec(specPath,platform=process.platform){let absolute=resolve(specPath);await assertTrustedFile(absolute,platform);let spec=parseHostLaunchSpec(await readSpecText(absolute)),env=trustedEnv(spec.env),extensions=await resolveExtensions(spec.core.extensions,dirname(absolute));return{hostArgs:["--session-runtime",spec.core.session_runtime,...extensions.flatMap(path=>["--extension",path])],policy:{...spec.tunables?.idleExitMs!==void 0&&{idleExitMs:spec.tunables.idleExitMs},...spec.tunables?.coldStart!==void 0&&{coldStart:spec.tunables.coldStart}},env}}function parseHostLaunchSpec(text){let parsed;try{parsed=JSON.parse(text)}catch(error){throw new HostLaunchSpecError("launch_spec_invalid",error instanceof Error?error.message:"not JSON")}if(!isRecord(parsed))throw new HostLaunchSpecError("launch_spec_invalid","the spec is not a JSON object");if(parsed.spec_version!==1)throw new HostLaunchSpecError("launch_spec_invalid",`unsupported spec_version ${String(parsed.spec_version)}`);let core=parsed.core;if(!isRecord(core))throw new HostLaunchSpecError("launch_spec_invalid","core must be an object");if(typeof core.session_runtime!="string"||!isSessionRuntimeKind(core.session_runtime))throw new HostLaunchSpecError("launch_spec_invalid","core.session_runtime must be in-process or worker");if(core.multi_session!==!0)throw new HostLaunchSpecError("launch_spec_invalid","core.multi_session must be true");if(!Array.isArray(core.extensions)||!core.extensions.every(entry=>typeof entry=="string"))throw new HostLaunchSpecError("launch_spec_invalid","core.extensions must be an array of strings");let tunables=parsedTunables(parsed.tunables);return{spec_version:1,core:{session_runtime:core.session_runtime,multi_session:!0,extensions:core.extensions},...tunables&&{tunables},...isRecord(parsed.env)&&{env:parsedEnv(parsed.env)}}}async function readSpecText(absolute){try{return await readFile(absolute,"utf8")}catch(error){throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}}async function assertTrustedFile(absolute,platform){if(platform==="win32")return;let stats=await stat(absolute).catch(error=>{throw new HostLaunchSpecError("launch_spec_unreadable",error instanceof Error?error.message:absolute)}),uid=process.getuid?.();if(uid!==void 0&&stats.uid!==uid)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is owned by uid ${stats.uid}, not ${uid}`);if((stats.mode&18)!==0)throw new HostLaunchSpecError("launch_spec_insecure",`${absolute} is group/world writable (mode ${(stats.mode&511).toString(8)})`)}function trustedEnv(env){for(let name of Object.keys(env??{}))if(!SPEC_ENV_NAME.test(name))throw new HostLaunchSpecError("launch_spec_env_denied",`${name} is outside ${SPEC_ENV_NAME.source}`);return env??{}}async function resolveExtensions(extensions,specDir){let rootReal=await realpath(specDir).catch(()=>specDir),resolved=[];for(let entry of extensions){let target=resolve(specDir,entry);if(escapes(specDir,target))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} resolves outside ${specDir}`);let real=await realpath(target).catch(()=>{});if(real===void 0)throw new HostLaunchSpecError("launch_spec_missing_extension",`${target} does not exist`);if(escapes(rootReal,real))throw new HostLaunchSpecError("launch_spec_path_escape",`${entry} links outside ${specDir}`);resolved.push(real)}return resolved}function escapes(root,target){let step=relative(root,target);return step.startsWith("..")||isAbsolute(step)}function parsedTunables(value){if(!isRecord(value))return;let idleExitMs=value.idleExitMs,coldStart=value.coldStart;return{...typeof idleExitMs=="number"&&Number.isFinite(idleExitMs)&&idleExitMs>0&&{idleExitMs},...(coldStart==="transient"||coldStart==="persistent")&&{coldStart}}}function parsedEnv(value){let env={};for(let[name,entry]of Object.entries(value)){if(typeof entry!="string")throw new HostLaunchSpecError("launch_spec_invalid",`env.${name} must be a string`);env[name]=entry}return env}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{join}from"node:path";var ALLOWED_ENV_NAMES=[/^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TERM|LANG)$/u,/^(LC|XDG)_/u,/^(SENPI|OMO|PI)_/u,/^BSK_(HOME|BIN)$/u,/^(HTTPS?_PROXY|NO_PROXY)$/u,/^[A-Z0-9_]+_API_KEY$/u,/^(ANTHROPIC|OPENAI|GOOGLE|GEMINI|AZURE|AWS|OPENROUTER|XAI|MISTRAL|DEEPSEEK|GROQ|CEREBRAS|MINIMAX)_/u],PROVIDER_CREDENTIAL_ENV_NAMES=new Set([...providerCredentialEnvNames(),...envSlotVarNames()]),WINDOWS_SYSTEM_ENV_NAMES=new Set(["SYSTEMROOT","SYSTEMDRIVE","WINDIR","COMSPEC","PATHEXT","TEMP","TMP","USERPROFILE","APPDATA","LOCALAPPDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","HOMEDRIVE","HOMEPATH","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"]),TRANSIENT_ENV_NAMES=new Set(["PI_SESSION_ID","PI_SESSION_FILE","PI_SESSION_CWD","PI_GOAL_STORE_FILE","PI_PROVIDER","PI_MODEL","PI_REASONING_LEVEL","OMO_BROWSER_ENGINE","PI_PROMPT_CACHE_SAFE_WAIT_SECONDS","SENPI_PY_KERNEL_PARENT_PID","SENPI_RPC_HOST_WATCH_FD","SENPI_RPC_HOST_WATCH_PPID","SENPI_RPC_HOST_SCRATCH_DIR","SENPI_RPC_HOST_CLEANUP_PATHS","SENPI_RPC_HOST_PUBLIC_SOCKET","SENPI_RPC_HOST_INSTANCE_ID","SENPI_RPC_HOST_GENERATION","SENPI_RPC_HOST_DAEMON_DIR","SENPI_RPC_HOST_EXPECTED_RUNTIME_BUILD_ID","SENPI_RPC_HOST_STARTUP_EVENTS","SENPI_RPC_INTERNAL_KEY_STDIN","SENPI_RPC_HOST_WATCH_PSTART","SENPI_RPC_HOST_WATCH_PSTART_TICKS","SENPI_RPC_HOST_LIFETIME_FIFO","SENPI_RPC_SOCKET_SECRET_FILE","SENPI_ENGINE_TRUST","SENPI_ENGINE_TRUST_HOP"]);function isTransientDaemonEnvName(name){return TRANSIENT_ENV_NAMES.has(name)}function daemonEnvIsAllowed(name,platform=process.platform){let upper=name.toUpperCase();return TRANSIENT_ENV_NAMES.has(platform==="win32"?upper:name)?!1:platform!=="win32"?PROVIDER_CREDENTIAL_ENV_NAMES.has(name)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(name)):WINDOWS_SYSTEM_ENV_NAMES.has(upper)||PROVIDER_CREDENTIAL_ENV_NAMES.has(upper)||ALLOWED_ENV_NAMES.some(pattern=>pattern.test(upper))}function daemonEnvOverrides(processEnv,specEnv={},platform=process.platform){let overrides={};for(let name of Object.keys(processEnv))daemonEnvIsAllowed(name,platform)||(overrides[name]=null);for(let[name,value]of Object.entries(specEnv))daemonEnvIsAllowed(name,platform)&&(overrides[name]=value);return overrides}function daemonEnvironment(processEnv,overrides={},forced={},platform=process.platform){let env={};for(let[name,value]of Object.entries(processEnv))value!==void 0&&daemonEnvIsAllowed(name,platform)&&(env[name]=value);for(let[name,value]of Object.entries(overrides))daemonEnvIsAllowed(name,platform)&&(deleteEnvironmentName(env,name,platform),value!==null&&(env[name]=value));for(let[name,value]of Object.entries(forced))deleteEnvironmentName(env,name,platform),env[name]=value;return env}function daemonEnvKeys(processEnv,specEnv={},platform=process.platform){let kept=Object.keys(processEnv).filter(name=>daemonEnvIsAllowed(name,platform)),explicit=Object.keys(specEnv).filter(name=>daemonEnvIsAllowed(name,platform));return[...new Set([...kept,...explicit])].sort()}async function writeDaemonEnvKeys(paths,keys){await writeStateFile(daemonEnvKeysFile(paths),{env_keys:keys})}async function readDaemonEnvKeys(paths){let keys=parseJson(await readFileOrUndefined(daemonEnvKeysFile(paths)))?.env_keys;return Array.isArray(keys)?keys.filter(key=>typeof key=="string"):[]}function daemonEnvKeysFile(paths){return join(paths.dir,"env-keys.json")}function deleteEnvironmentName(env,name,platform){if(platform!=="win32"){delete env[name];return}let upper=name.toUpperCase();for(let existing of Object.keys(env))existing.toUpperCase()===upper&&delete env[existing]}import{mkdir,writeFile as writeFile4}from"node:fs/promises";import{dirname as dirname4}from"node:path";var hostGenerationScopes=0;function isHostGenerationProcess(){return hostGenerationScopes>0}async function runAsHostGenerationProcess(action){hostGenerationScopes+=1;try{return await action()}finally{hostGenerationScopes-=1}}function decideEnsureAction(options,startedByUs,protocol){if(options.upgrade!=="if-engine-differs"||isHostGenerationProcess())return decideHostAction(ensureClient(options,startedByUs),protocol,"never");let decision=decideHostAction(ensureClient(options,startedByUs),protocol,"upgrade");return decision.action==="fallback"?{action:"reuse",reason:"compatible",upgradeable:!1}:decision}function ensureClient(options,startedByUs){return{protocolVersion:HOST_PROTOCOL_VERSION,requiredCapabilities:[...REQUIRED_HOST_CAPABILITIES,...requestedToolRuntime(options.hostArgs??[])],identity:engineBuildIdentity(),...options.upgrade==="if-engine-differs"?{launchProfile:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd())}:{},startedByUs,platform:process.platform}}function requestedToolRuntime(hostArgs){for(let index=0;index<hostArgs.length;index++){let arg=hostArgs[index]??"",value=arg==="--tool-runtime"?hostArgs[index+1]:arg.startsWith("--tool-runtime=")?arg.slice(15):void 0;if(value!==void 0&&isToolRuntimeKind(value))return[toolRuntimeCapability(value)]}return[]}function hostChildArgv(hostArgs){return["--mode","rpc","--multi-session",...hostArgs]}function isCompatible(protocol){return decideHostAction(ensureClient({socket:""},!1),protocol,"never").action==="reuse"}import{lstat}from"node:fs/promises";async function refuseIfStalled(paths,instanceId,socket,protocol){let generation=generationPaths(paths,instanceId);if(await hostLoopStalled(generation,{now:Date.now(),errorMs:loopLagErrorMs(),windowMs:stallRefusalWindowMs()})&&await hostChildAlive(generation)!==!1)throw new HostEnsureRefusedError(socket,"host_stalled",protocol)}async function refuseIfForeignHeld(paths,registered,socket,protocol){if(!await publicEndpointAccepts(socket))return;let holder=await readHostHolder(paths,registered);throw new HostEnsureRefusedError(socket,"foreign_writer",protocol,void 0,holder)}async function readHostHolder(paths,registered){let record=parseJson(await readFileOrUndefined(generationPaths(paths,registered.instanceId).pidFile))??{};return{pid:registered.record.pid,instanceId:registered.instanceId,generation:registered.generation,processStartTime:registered.record.processStartTime,engineVersion:typeof record.engineVersion=="string"?record.engineVersion:null,launchProfileId:typeof record.launchProfileId=="string"?record.launchProfileId:null,writerPid:registered.writer?.pid??null}}var FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS=2e3;async function publicEndpointAccepts(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!0;let entry=await statSocketIdentity(socket).then(identity=>identity===void 0?"absent":"present",()=>"unknown");return entry==="absent"?!1:entry==="unknown"?!0:probeSocketReachable(socket,FOREIGN_ENDPOINT_PROBE_TIMEOUT_MS)}async function unregisteredEndpointHeld(socket){if(process.platform==="win32"||socket.startsWith("\0"))return!1;let entry=await lstat(socket).then(found=>found.isSocket()?"socket":"not-socket",cause=>cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"?"absent":"unknown");return entry==="absent"?!1:entry!=="socket"?!0:(await socketEntryListenerState(socket)).verdict==="live"}import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{open,readFile as readFile2}from"node:fs/promises";import{existsSync}from"node:fs";import{basename,dirname as dirname2,join as join2,resolve as resolve2}from"node:path";import{fileURLToPath}from"node:url";var PINNED_HOST_CLIENT_CAPABILITIES=[EXTENSION_EVENTS_CAPABILITY,CUSTOM_UNSUPPORTED_CAPABILITY];function defaultHostLaunch(supervisorArgs,compiled=isBunBinary,sibling=resolveHostLifecycleEntryPath()??null,bundledSupervisor=resolveBundledSupervisorEntryPath()??null){return compiled?{command:process.execPath,args:[INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:sibling!==null?{command:process.execPath,args:[...runtimeExecArgv(),sibling,...supervisorArgs]}:bundledSupervisor!==null?{command:process.execPath,args:[...runtimeExecArgv(),bundledSupervisor,INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:{command:process.execPath,args:[...runtimeExecArgv(),resolveCliMainPath(),INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}}var BUNDLED_SUPERVISOR_ENTRY="host-supervisor.js";function resolveBundledSupervisorEntryPath(){let entry=join2(dirname2(resolveCliMainPath()),BUNDLED_SUPERVISOR_ENTRY);return existsSync(entry)?entry:void 0}function resolveHostLifecycleEntryPath(){let modulePath=fileURLToPath(import.meta.url);if(basename(dirname2(modulePath))==="chunks")return;let extension=modulePath.endsWith(".ts")?".ts":".js",sibling=resolve2(dirname2(modulePath),`host-lifecycle${extension}`);return existsSync(sibling)?sibling:void 0}import{randomBytes}from"node:crypto";var MAX_STARTUP_EVENTS_PER_PRODUCER=32,STARTUP_MILESTONE_PRODUCER={supervisor_bootstrap:"supervisor",supervisor_setup:"supervisor",host_opaque:"supervisor",host_bootstrap:"host",host_runtime:"host",internal_ready:"supervisor",observer_ready:"supervisor",public_published:"supervisor"};function newStartupAttempt(){return randomBytes(16).toString("hex")}function startupEventIngress(controller,binding,role){let lastSeq=0,records=0,failProtocol=reason=>(controller.fail(new Error(`RPC host startup protocol failure (${role}): ${reason}`)),"protocol_failure");return line=>{if(Buffer.byteLength(line,"utf8")>4096)return failProtocol("record exceeds 4096 bytes");let record=parseRecord(line);if(!record)return failProtocol("malformed record");if(!sameBinding(record.binding,binding))return"discarded";if(record.role!==role)return failProtocol(`record claims role ${String(record.role)}`);if(record.seq<=lastSeq)return"ignored";if(record.seq!==lastSeq+1)return failProtocol(`sequence gap after ${lastSeq}`);if(records+=1,records>MAX_STARTUP_EVENTS_PER_PRODUCER)return failProtocol("too many records");lastSeq=record.seq;let milestone=record.milestone;if(!isProducerMilestone(milestone))return failProtocol(`unknown milestone ${String(milestone)}`);if(STARTUP_MILESTONE_PRODUCER[milestone]!==role)return failProtocol(`${role} cannot report ${milestone}`);let verdict=milestone==="host_opaque"?controller.declareOpaqueHost():controller.complete(milestone);return verdict!=="rejected"?verdict:controller.terminal?"ignored":failProtocol(`${milestone} reported before its phase was granted`)}}function attachStartupEvents(stream,controller,binding){let supervisor=startupEventIngress(controller,binding,"supervisor"),host=startupEventIngress(controller,binding,"host"),maxLine=2*4096+64,pending="";stream.setEncoding("utf8"),stream.on("data",chunk=>{if(!controller.terminal){pending+=chunk;for(let newline=pending.indexOf(`
|
|
3
3
|
`);newline>=0;newline=pending.indexOf(`
|
|
4
4
|
`)){let line=pending.slice(0,newline);pending=pending.slice(newline+1);let relayed=unwrapStartupRelay(line);if(relayed===void 0?supervisor(line):host(relayed),controller.terminal)return}pending.length>maxLine&&supervisor(pending)}}),stream.on("error",()=>{}),"unref"in stream&&typeof stream.unref=="function"&&stream.unref()}function unwrapStartupRelay(line){if(line.startsWith('{"relay":'))try{let frame=JSON.parse(line);if(typeof frame!="object"||frame===null)return;let{relay,line:inner}=frame;return relay==="host"&&typeof inner=="string"?inner:void 0}catch{return}}function parseRecord(line){let value;try{value=JSON.parse(line)}catch{return}if(typeof value!="object"||value===null)return;let record=value;if(record.v===1&&!(typeof record.seq!="number"||!Number.isSafeInteger(record.seq)||record.seq<1))return{binding:record.binding,role:record.role,seq:record.seq,milestone:record.milestone}}function sameBinding(candidate,binding){if(typeof candidate!="object"||candidate===null)return!1;let other=candidate;return other.attempt===binding.attempt&&other.endpoint===binding.endpoint&&other.instanceId===binding.instanceId&&other.generation===binding.generation&&other.launchKind===binding.launchKind&&other.predecessor===binding.predecessor}function isProducerMilestone(value){return typeof value=="string"&&Object.hasOwn(STARTUP_MILESTONE_PRODUCER,value)}import{rm,stat as stat2}from"node:fs/promises";import{join as join3}from"node:path";var STARTUP_INTENT_FILE="startup-intent.json",STARTUP_INTENT_VERSION=1;function startupIntentPath(daemonDir){return join3(daemonDir,STARTUP_INTENT_FILE)}function writeStartupIntent(daemonDir,intent){return writeJsonAtomic(startupIntentPath(daemonDir),{version:STARTUP_INTENT_VERSION,...intent})}async function readStartupIntent(daemonDir){let modified=await stat2(startupIntentPath(daemonDir)).then(entry=>entry.mtimeMs,()=>{});if(modified===void 0)return;let record=await readJsonObject(startupIntentPath(daemonDir)),launcher=pidFileOf(record?.launcher),child=record?.child===void 0?void 0:pidFileOf(record.child);return!record||record.version!==STARTUP_INTENT_VERSION||typeof record.attempt!="string"||typeof record.instanceId!="string"||typeof record.generation!="number"||typeof record.writtenAt!="number"||!launcher||child===null?{unreadable:!0,writtenAt:modified}:{attempt:record.attempt,instanceId:record.instanceId,generation:record.generation,launcher,writtenAt:record.writtenAt,...child?{child}:{}}}function clearStartupIntent(daemonDir){return rm(startupIntentPath(daemonDir),{force:!0})}async function readStartupAttemptRecord(generationDir,attempt){let record=await readJsonObject(join3(generationDir,STARTUP_ATTEMPT_FILE));if(record?.attempt===attempt)return pidFileOf(record)??void 0}async function reconcileStartupIntent(intent,options){if(intent===void 0)return"none";let expiredOr=verdict=>options.now-intent.writtenAt>=options.expiryMs?"expired":verdict;if("unreadable"in intent)return expiredOr("unknown");let candidate=intent.child??await options.attemptRecord(intent.instanceId,intent.attempt);if(!candidate)return expiredOr("unknown");let live=await options.matches(candidate).catch(()=>{});return live===void 0?expiredOr("unknown"):live?"candidate_live":"candidate_gone"}async function settleStartupIntent(paths,socket,readStartTime=readProcessStartTime){let expiryMs=startupEnvelope(childStalledStopMaxMs()).settled,verdict=await reconcileStartupIntent(await readStartupIntent(paths.dir),{matches:record=>processMatchesPidFile(record,readStartTime),attemptRecord:(instanceId,attempt)=>readStartupAttemptRecord(generationPaths(paths,instanceId).dir,attempt),expiryMs,now:Date.now()});if(verdict==="none")return;if(verdict==="candidate_gone"||verdict==="expired")return clearStartupIntent(paths.dir);let detail=verdict==="candidate_live"?`a previous start of this endpoint is still running and never registered (${startupIntentPath(paths.dir)})`:`a previous start of this endpoint cannot be identified; ${startupIntentPath(paths.dir)} is kept until its candidate is proven gone or ${expiryMs}ms after it was written`;throw new HostEnsureRefusedError(socket,verdict==="candidate_live"?"host_stalled":"endpoint_occupied",void 0,detail)}function pidFileOf(value){if(typeof value!="object"||value===null)return null;let{pid,processStartTime}=value;return typeof pid!="number"||!Number.isInteger(pid)||pid<=0||processStartTime!==null&&typeof processStartTime!="string"?null:{pid,processStartTime}}import{Readable}from"node:stream";var SPAWNED_HOST_PROBE_TIMEOUT_MS=1e4;async function pollProtocolInfo(socket,timeoutMs,isCompatible2,childExit){let deadline=Date.now()+timeoutMs,lastProtocol;for(;Date.now()<=deadline;){let probe=holdProtocolInfo(socket,Math.min(SPAWNED_HOST_PROBE_TIMEOUT_MS,Math.max(1,deadline-Date.now()))),raced=childExit?await Promise.race([probe,childExit]):await probe;if(isChildExit(raced)){let held=await probe;if(!held)return{ready:!1,protocol:lastProtocol,exited:raced};if(lastProtocol=held.info,isCompatible2(held.info))return{ready:!0,protocol:held.info,hold:held.hold};held.hold.release()}else if(raced){if(lastProtocol=raced.info,isCompatible2(raced.info))return{ready:!0,protocol:raced.info,hold:raced.hold};raced.hold.release()}await delay2(50)}return{ready:!1,protocol:lastProtocol}}function isChildExit(value){return!!value&&"code"in value&&"signal"in value}function delay2(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function monotonicStartupClock(){return{now:()=>performance.now(),scheduleAt:(at,fire)=>setTimeout(fire,Math.max(0,at-performance.now())),cancel:handle=>clearTimeout(handle)}}function beginStartupAttempt(options){let successor=options.successorOf!==void 0,launchKind=options.coordinated?successor?"successor":"initial":"legacy",budgetMs=options.decisionBudgetMs??STARTUP_DECISION_BUDGET_MS,binding={attempt:options.attempt,endpoint:options.socket,instanceId:options.instanceId,generation:options.generation,launchKind:successor?"successor":"initial",predecessor:options.successorOf??null},controller=startStartupController({launchKind,clock:options.clock??monotonicStartupClock(),decisionBudgetMs:budgetMs}),coordinated=options.coordinated,fillers=[];return{controller,binding,coordinated,get env(){return coordinated?{[HOST_STARTUP_EVENTS_ENV]:encodeStartupHandOff({binding,role:"supervisor",budgetMs,fillers})}:{}},stdio(base){if(!coordinated)return[...base];let filled=withStartupPipe(base);return fillers=filled.fillers,filled.stdio},attach(child,childExit){releaseStartupFillers(child,fillers);let stream=child.stdio[16];coordinated&&stream instanceof Readable&&attachStartupEvents(stream,controller,binding),childExit.then(exit=>{!controller.terminal&&controller.phase!=="public_verified"&&controller.fail(new Error(exitMessage(exit)))})}}}function exitMessage(exit){return`RPC socket host exited with ${exitStatus(exit)} before answering get_protocol_info`}function exitStatus(exit){return`code ${exit.code??"null"}${exit.signal?` (${exit.signal})`:""}`}function answerMessage(protocol,exited){return protocol.lifecycle!=="stopping"?incompatibleMessage(protocol):`RPC socket host answered get_protocol_info with lifecycle "stopping": it began stopping before this start verified it${exited?`, and then exited with ${exitStatus(exited)}`:""}`}function incompatibleMessage(protocol){return`RPC socket host answered get_protocol_info with protocolVersion ${protocol.protocolVersion}, serverVersion ${protocol.serverVersion} and capabilities ${JSON.stringify(protocol.capabilities)}, but is incompatible with protocol version ${HOST_PROTOCOL_VERSION} and required capabilities ${JSON.stringify(REQUIRED_HOST_CAPABILITIES)}`}async function driveStartupToReady(options){let{controller}=options.attempt,failure=async()=>{let outcome=await controller.settled();if(outcome.kind==="ready")throw new Error("startup controller reported READY on a failure path");return{ready:!1,outcome}};if(options.attempt.coordinated&&(!await controller.whenPhase("presenter_resolved")||await Promise.race([(options.presenterEnrollment??Promise.resolve()).then(()=>"resolved"),controller.settled().then(()=>"terminal")])==="terminal"||controller.complete("presenter_resolved")!=="accepted"))return failure();let result=await pollProtocolInfo(options.socket,Math.max(1,controller.remainingMs()),options.isCompatible,options.childExit);if(result.ready)return controller.complete("public_verified")!=="accepted"?(result.hold.release(),failure()):(options.attempt.coordinated||await options.presenterEnrollment,{ready:!0,hold:result.hold});let explicit=result.protocol?new Error(answerMessage(result.protocol,result.exited)):result.exited?new Error(exitMessage(result.exited)):void 0;if(!explicit)return failure();controller.fail(explicit);let settled=await controller.settled();return{ready:!1,outcome:settled.kind==="failed"?settled:{kind:"failed",phase:"public_verified",cause:explicit,elapsedMs:settled.elapsedMs}}}function createStartupFinalizer(options){let settled;return outcome=>(settled??=finalize(outcome),settled);async function finalize(outcome){let{clock}=options,timer,expired=new Promise(resolveExpired=>{timer=clock.scheduleAt(clock.now()+options.cleanupBudgetMs,()=>resolveExpired("expired"))}),ran=options.cleanup().then(()=>"completed",error=>error instanceof Error?error:new Error(String(error))),result=await Promise.race([ran,expired]);clock.cancel(timer);let cleanup=result==="completed"?"completed":"incomplete",original=outcome.kind==="timeout"?startupTimeoutDetail(outcome,cleanup):outcome.cause.message,appended=result instanceof Error?`
|
|
5
5
|
cleanup failed: ${result.message}`:result==="expired"?`
|
|
@@ -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{PRIVATE_FDS_FINAL_ENV,UNPARSEABLE_TABLE,takePrivateDescriptors}from"./chunk-
|
|
2
|
+
import{PRIVATE_FDS_FINAL_ENV,UNPARSEABLE_TABLE,takePrivateDescriptors}from"./chunk-K3GAGIPX.js";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{closeSync}from"node:fs";var TABLE_ENV="SENPI_PRIVATE_FDS";function preparePrivateFdSpawn(options,hop={},forward=takePrivateDescriptors()){let env={...options.env??process.env};delete env[TABLE_ENV],delete env[PRIVATE_FDS_FINAL_ENV];let base=options.stdio??"pipe",stdio=typeof base=="string"?[base,base,base]:[...base],owned=[];if(forward.kind==="unparseable")env[TABLE_ENV]=UNPARSEABLE_TABLE;else if(forward.entries.size>0){let carries=!options.shell,table={};for(let[name,fd]of forward.entries){let descriptors=fd===null?[]:typeof fd=="number"?[fd]:fd;if(owned.push(...descriptors),fd!==null&&carries){for(let descriptor of descriptors){for(;stdio.length<=descriptor;)stdio.push("ignore");stdio[descriptor]=descriptor}table[name]=fd}else table[name]=null}env[TABLE_ENV]=JSON.stringify(table)}return env[TABLE_ENV]!==void 0&&hop.final&&(env[PRIVATE_FDS_FINAL_ENV]="1"),{options:{...options,env,stdio},close(){for(let fd of owned)closeSync(fd)}}}function spawnWithPrivateFds(spawn,command,args,options,hop={}){let transfer=preparePrivateFdSpawn(options,hop);try{return spawn(command,args,transfer.options)}finally{transfer.close()}}export{runtimeExecArgv,preparePrivateFdSpawn,spawnWithPrivateFds};
|