@code-yeongyu/senpi 2026.10.25-3 → 2026.10.25-4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/bundle/chunks/{chunk-WLHNEUGD.js → chunk-2RB5EL4X.js} +1 -1
  3. package/dist/bundle/chunks/{chunk-MJ5NNWX4.js → chunk-3QCYBOKN.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-FFQOEC76.js → chunk-4MOZXOJX.js} +3 -3
  5. package/dist/bundle/chunks/{chunk-ODTGC6YU.js → chunk-5JJDR6XI.js} +1 -1
  6. package/dist/bundle/chunks/chunk-6VWIMHMH.js +2 -0
  7. package/dist/bundle/chunks/{chunk-SWJXRC2I.js → chunk-BZ7726QO.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-YRF4I43T.js → chunk-C2MQ4QXN.js} +12 -12
  9. package/dist/bundle/chunks/{chunk-7W7OJDIY.js → chunk-DODH3N6U.js} +4 -4
  10. package/dist/bundle/chunks/{chunk-EHQXLHRB.js → chunk-E6D4RIT7.js} +2 -2
  11. package/dist/bundle/chunks/{chunk-6O4SEW2W.js → chunk-J37GRED2.js} +1 -1
  12. package/dist/bundle/chunks/chunk-JMOUU75H.js +2 -0
  13. package/dist/bundle/chunks/{chunk-Z3UYNSVR.js → chunk-KKD4CYCI.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-JA2R2ZSE.js → chunk-KNVNKDER.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-CNL6QSUB.js → chunk-LOIF6PHI.js} +2 -2
  16. package/dist/bundle/chunks/{chunk-P3M2PF6K.js → chunk-N7IN46Q5.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-C5UFJ7B3.js → chunk-PT6JJUN2.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-O3Q2ET6W.js → chunk-SBGIXMX3.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-HVJI5T75.js → chunk-STMXIBXF.js} +2 -2
  20. package/dist/bundle/chunks/{chunk-H3HNMY2W.js → chunk-TBU6VYHN.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-UQNRW3VU.js → chunk-V2UYXTRR.js} +1 -1
  22. package/dist/bundle/chunks/chunk-XMJKZK5H.js +2 -0
  23. package/dist/bundle/chunks/cli-main-YYH3IBC6.js +3 -0
  24. package/dist/bundle/chunks/{dispatch-NYAULNVW.js → dispatch-MXG5YWLV.js} +1 -1
  25. package/dist/bundle/chunks/{host-command-Z3WPHJOW.js → host-command-TDLLHXVI.js} +1 -1
  26. package/dist/bundle/chunks/{host-lifecycle-ONQIMWMX.js → host-lifecycle-3VHHIGDL.js} +1 -1
  27. package/dist/bundle/chunks/host-lifecycle.js +1 -1
  28. package/dist/bundle/chunks/{host-session-command-J65ENSV5.js → host-session-command-56XF6ACS.js} +1 -1
  29. package/dist/bundle/chunks/{host-socket-request-3CWE4265.js → host-socket-request-QL2WEZTN.js} +1 -1
  30. package/dist/bundle/chunks/interactive-mode-OEPULLZK.js +2 -0
  31. package/dist/bundle/chunks/{multi-session-host-YI2WZOET.js → multi-session-host-Z2CW4SDM.js} +2 -2
  32. package/dist/bundle/chunks/{package-manager-cli-GHZPJMRF.js → package-manager-cli-N55U6PEO.js} +1 -1
  33. package/dist/bundle/chunks/rotation-stream-CBGCBYHV.js +2 -0
  34. package/dist/bundle/chunks/rpc-mode-ETXQWEB2.js +2 -0
  35. package/dist/bundle/chunks/{rpc-monitor-source-FFEQS744.js → rpc-monitor-source-AE3C6EQV.js} +1 -1
  36. package/dist/bundle/chunks/{schedule-command-YWG6D6ZF.js → schedule-command-VS7CZC2J.js} +1 -1
  37. package/dist/bundle/chunks/session-control-endpoint-4LEIDIVI.js +3 -0
  38. package/dist/bundle/chunks/session-picker-E4KUJDLO.js +2 -0
  39. package/dist/bundle/chunks/session-worker.js +45 -45
  40. package/dist/bundle/cli.js +2 -2
  41. package/dist/bundle/host-supervisor.js +1 -1
  42. package/dist/bundle/index.js +1 -1
  43. package/dist/bundle/rpc-entry.js +1 -1
  44. package/dist/bundle/runtime-manifest.json +1 -1
  45. package/dist/core/extensions/builtin/mcp/elicitation.js +2 -4
  46. package/dist/core/session-control-actions.js +0 -2
  47. package/dist/modes/interactive/session-control-attach.d.ts +20 -0
  48. package/dist/modes/interactive/session-control-attach.js +13 -0
  49. package/dist/modes/interactive/session-control-commands.js +16 -6
  50. package/dist/modes/interactive/session-control-registry.d.ts +2 -1
  51. package/dist/modes/interactive/session-control-registry.js +3 -2
  52. package/dist/modes/interactive/session-control-rpc-commands.d.ts +4 -2
  53. package/dist/modes/interactive/session-control-rpc-commands.js +114 -4
  54. package/dist/modes/interactive/session-control-server.js +9 -3
  55. package/dist/modes/rpc/connection-handler.js +6 -40
  56. package/dist/modes/rpc/custom-capability.d.ts +6 -0
  57. package/dist/modes/rpc/custom-capability.js +6 -0
  58. package/dist/modes/rpc/get-entries-command.d.ts +13 -0
  59. package/dist/modes/rpc/get-entries-command.js +61 -0
  60. package/dist/modes/rpc/get-entries-page.d.ts +22 -0
  61. package/dist/modes/rpc/get-entries-page.js +41 -2
  62. package/dist/modes/rpc/host-capabilities.js +4 -1
  63. package/dist/modes/rpc/host-observe-request.d.ts +2 -1
  64. package/dist/modes/rpc/host-observe-request.js +4 -1
  65. package/dist/modes/rpc/rpc-read-response-types.d.ts +2 -0
  66. package/dist/modes/rpc/rpc-session-command-types.d.ts +8 -1
  67. package/docs/rpc.md +43 -11
  68. package/package.json +6 -6
  69. package/dist/bundle/chunks/chunk-3LNSLJ7N.js +0 -2
  70. package/dist/bundle/chunks/chunk-MSQCTH6V.js +0 -2
  71. package/dist/bundle/chunks/cli-main-HEKFFB5S.js +0 -3
  72. package/dist/bundle/chunks/interactive-mode-DEPQC6TX.js +0 -2
  73. package/dist/bundle/chunks/rotation-stream-ZPVCFOVD.js +0 -2
  74. package/dist/bundle/chunks/rpc-mode-ORHBGBBV.js +0 -2
  75. package/dist/bundle/chunks/session-control-endpoint-36HAQSQO.js +0 -3
  76. package/dist/bundle/chunks/session-picker-25H5KNYP.js +0 -2
@@ -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{McpPresenterAuthority,attachMcpGrantPresentation,effectStatusRecord,sessionQuestionBridges}from"./chunk-7W7OJDIY.js";import{RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-GY5MR5KR.js";import{omitInlineMedia}from"./chunk-EHQXLHRB.js";import{bindPrivateMcpForms}from"./chunk-JPGT64RV.js";import{MEDIA_PLACEHOLDERS_CAPABILITY,hostGeneration,hostInstanceId}from"./chunk-HVJI5T75.js";import{serializeJsonLine}from"./chunk-YI7SPFDN.js";import{AsyncLocalStorage}from"node:async_hooks";var RpcSecurityPresentations=class{#sessions=new Map;#attachments=new Map;constructor(fanout,inConnection,flush){this.fanout=fanout,this.inConnection=inConnection,this.flush=flush}bind(sessionId,durableId,notices,select){let previous=this.#sessions.get(sessionId);this.#stop(previous);let state={durableId,select,snapshot:notices.snapshot,registrations:new Map,grants:new Map,replayed:previous?.durableId===durableId?previous.replayed:new Map};this.#sessions.set(sessionId,state),state.stop=notices.subscribe(snapshot=>this.acceptSnapshot(sessionId,snapshot));for(let id of this.fanout.attachedConnections(sessionId))this.#register(id,state);return()=>{this.#sessions.get(sessionId)===state&&(this.#stop(state),this.#sessions.delete(sessionId))}}acceptSnapshot(sessionId,snapshot){let state=this.#sessions.get(sessionId);state===void 0&&(state={snapshot,registrations:new Map,grants:new Map,replayed:new Map},this.#sessions.set(sessionId,state)),state.snapshot=snapshot;for(let id of this.fanout.attachedConnections(sessionId))this.#replay(sessionId,id,snapshot)}attach(id,sessionId){let attached=this.#attachments.get(id)??new Set;if(attached.has(sessionId))return;attached.add(sessionId),this.#attachments.set(id,attached);let state=this.#sessions.get(sessionId);state!==void 0&&(this.#register(id,state),this.#replay(sessionId,id,state.snapshot))}detach(id,sessionId){this.#attachments.get(id)?.delete(sessionId),this.#attachments.get(id)?.size===0&&this.#attachments.delete(id);let state=this.#sessions.get(sessionId);state?.registrations.get(id)?.(),state?.registrations.delete(id),state?.replayed.delete(id),state!==void 0&&this.#cancelFor(state,id)}dropConnection(id){for(let sessionId of[...this.#attachments.get(id)??[]])this.detach(id,sessionId)}capabilitiesChanged(id){for(let sessionId of this.#attachments.get(id)??[]){let state=this.#sessions.get(sessionId);state!==void 0&&(this.#register(id,state),this.fanout.connectionHas(id,"grant_select")||this.#cancelFor(state,id))}}routeWorkerGrant(sessionId,requestId,preferred,fallbackCapabilities,cancel){let attached=this.fanout.attachedConnections(sessionId),connection=attached.includes(preferred??"")&&this.fanout.connectionHas(preferred,"grant_select")?preferred:attached.find(id=>this.fanout.connectionHas(id,"grant_select"));if(!(connection!==void 0||this.fanout.isEmpty()&&fallbackCapabilities.includes("grant_select")))return cancel(),{accepted:!1};let state=this.#sessions.get(sessionId);return state===void 0&&(state={snapshot:{generation:0,notices:[]},registrations:new Map,grants:new Map,replayed:new Map},this.#sessions.set(sessionId,state)),state.grants.set(requestId,{connection,cancel}),{accepted:!0,connection}}acceptWorkerResponse(sessionId,requestId,connection){let state=this.#sessions.get(sessionId),pending=state?.grants.get(requestId);if(pending!==void 0)return pending.connection!==connection||connection!==void 0&&!this.fanout.connectionHas(connection,"grant_select")?!1:(state?.grants.delete(requestId),!0)}settleGrant(sessionId,requestId){this.#sessions.get(sessionId)?.grants.delete(requestId)}dropSession(sessionId){this.#stop(this.#sessions.get(sessionId)),this.#sessions.delete(sessionId);for(let[id,sessions]of this.#attachments)sessions.delete(sessionId),sessions.size===0&&this.#attachments.delete(id)}#register(id,state){if(!this.fanout.connectionHas(id,"grant_select")){state.registrations.get(id)?.(),state.registrations.delete(id);return}if(state.registrations.has(id)||state.select===void 0||state.durableId===void 0)return;let select=state.select;state.registrations.set(id,attachMcpGrantPresentation(state.durableId,(title,choices,opts)=>this.inConnection(id,()=>select(title,choices,opts))))}#replay(sessionId,id,snapshot){let target=this.fanout.get(id);if(target===void 0)return;let state=this.#sessions.get(sessionId),revision=JSON.stringify(snapshot);if(state?.replayed.get(id)!==revision){state?.replayed.set(id,revision);for(let notice of snapshot.notices)target.actor.enqueue(serializeJsonLine({type:"extension_ui_request",id:crypto.randomUUID(),sessionId,method:"notify",notifyType:"warning",message:notice.message}));this.flush()}}#cancelFor(state,id){for(let[requestId,pending]of state.grants)pending.connection===id&&(state.grants.delete(requestId),pending.cancel())}#stop(state){state?.stop?.();for(let stop of state?.registrations.values()??[])stop();for(let pending of state?.grants.values()??[])pending.cancel()}};var blockedMsTotal=0;function recordLoopBlockedMs(driftMs){driftMs>0&&(blockedMsTotal+=driftMs)}function loopBlockedMark(){return blockedMsTotal}function loopBlockedMsSince(mark){return blockedMsTotal-mark}var EVENT_RESYNC_CAPABILITY="event_resync";function isCorrelatedReply(value){return typeof value=="object"&&value!==null&&"type"in value&&value.type==="response"&&"id"in value&&typeof value.id=="string"}var SocketPeerLivenessError=class extends Error{constructor(){super("socket peer missed its liveness ping"),this.name="SocketPeerLivenessError"}},SocketPeerRecovery=class{constructor(write,snapshot){this.awaitingPing=!1,this.pingBuffered=!1,this.replyLost=!1,this.write=write,this.snapshot=snapshot,this.pingBuffered=!0,this.write(serializeJsonLine({type:"rpc_ping"}))}get pending(){return this.reason!==void 0}shed(reason){this.reason===void 0&&(this.reason=reason,this.readSnapshot=this.snapshot(reason))}acknowledge(){this.awaitingPing=!1}loseReply(){this.replyLost=!0}ping(){if(this.awaitingPing)throw new SocketPeerLivenessError;this.awaitingPing=!0,this.pingBuffered||(this.pingBuffered=!0,this.write(serializeJsonLine({type:"rpc_ping"})))}takeSnapshot(){let reason=this.reason;this.reason=void 0,this.awaitingPing=!1,this.pingBuffered=!1;let snapshot=this.readSnapshot;this.readSnapshot=void 0;let gap=reason===void 0?[]:[{type:"resync_required",reason,replyLost:this.replyLost}];return this.replyLost=!1,[...gap,...snapshot?.()??[]]}};var DEFAULT_QUEUE_BYTES=64*1024*1024,DEFAULT_STALL_MS=3e4,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}},SocketEventSinkActor=class{constructor(sink,onFailure,maxQueueBytes=DEFAULT_QUEUE_BYTES,stallMs=DEFAULT_STALL_MS){this.queue=[],this.queuedBytes=0,this.closed=!1,this.recoveryEnabled=!1,this.stopped=new AbortController,this.sink=sink,this.onFailure=onFailure,this.maxQueueBytes=maxQueueBytes,this.stallMs=stallMs}enableRecovery(snapshot){this.recoveryEnabled=!0,this.recovery??=new SocketPeerRecovery(line=>this.sink.writeRaw(line),snapshot),this.recovery.acknowledge()}disableRecovery(){this.recoveryEnabled=!1,this.recovery?.pending||(this.recovery=void 0)}enqueue(line,key,onWritten,demotedLine,reply=!1){if(this.closed)return;if(this.recovery?.pending&&!reply){onWritten?.();return}let bytes=Buffer.byteLength(line);if(this.recovery?.pending){this.queuedBytes+bytes<=this.maxQueueBytes?(this.queue.push({line,bytes,onWritten,reply}),this.queuedBytes+=bytes):(this.recovery.loseReply(),onWritten?.());return}if(key!==void 0){let existing=this.queue.find(entry=>entry.key===key);existing&&(existing.demotedLine!==void 0&&(this.queuedBytes-=existing.bytes,existing.line=existing.demotedLine,existing.bytes=Buffer.byteLength(existing.line),this.queuedBytes+=existing.bytes,existing.demotedLine=void 0),existing.key=void 0)}if(this.queuedBytes+bytes>this.maxQueueBytes){if(this.recovery&&this.recoveryEnabled){this.shed("overflow"),this.enqueue(line,void 0,onWritten,void 0,reply),this.drain();return}let overflow=new SocketEventQueueOverflowError(this.queuedBytes,bytes,this.maxQueueBytes,line.slice(0,120));this.closed=!0,this.queue.length=0,this.queuedBytes=0;try{this.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"overflow, resync required"})}
2
+ import{McpPresenterAuthority,attachMcpGrantPresentation,effectStatusRecord,sessionQuestionBridges}from"./chunk-DODH3N6U.js";import{RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-GY5MR5KR.js";import{omitInlineMedia}from"./chunk-E6D4RIT7.js";import{bindPrivateMcpForms}from"./chunk-JPGT64RV.js";import{MEDIA_PLACEHOLDERS_CAPABILITY,hostGeneration,hostInstanceId}from"./chunk-STMXIBXF.js";import{serializeJsonLine}from"./chunk-YI7SPFDN.js";import{AsyncLocalStorage}from"node:async_hooks";var RpcSecurityPresentations=class{#sessions=new Map;#attachments=new Map;constructor(fanout,inConnection,flush){this.fanout=fanout,this.inConnection=inConnection,this.flush=flush}bind(sessionId,durableId,notices,select){let previous=this.#sessions.get(sessionId);this.#stop(previous);let state={durableId,select,snapshot:notices.snapshot,registrations:new Map,grants:new Map,replayed:previous?.durableId===durableId?previous.replayed:new Map};this.#sessions.set(sessionId,state),state.stop=notices.subscribe(snapshot=>this.acceptSnapshot(sessionId,snapshot));for(let id of this.fanout.attachedConnections(sessionId))this.#register(id,state);return()=>{this.#sessions.get(sessionId)===state&&(this.#stop(state),this.#sessions.delete(sessionId))}}acceptSnapshot(sessionId,snapshot){let state=this.#sessions.get(sessionId);state===void 0&&(state={snapshot,registrations:new Map,grants:new Map,replayed:new Map},this.#sessions.set(sessionId,state)),state.snapshot=snapshot;for(let id of this.fanout.attachedConnections(sessionId))this.#replay(sessionId,id,snapshot)}attach(id,sessionId){let attached=this.#attachments.get(id)??new Set;if(attached.has(sessionId))return;attached.add(sessionId),this.#attachments.set(id,attached);let state=this.#sessions.get(sessionId);state!==void 0&&(this.#register(id,state),this.#replay(sessionId,id,state.snapshot))}detach(id,sessionId){this.#attachments.get(id)?.delete(sessionId),this.#attachments.get(id)?.size===0&&this.#attachments.delete(id);let state=this.#sessions.get(sessionId);state?.registrations.get(id)?.(),state?.registrations.delete(id),state?.replayed.delete(id),state!==void 0&&this.#cancelFor(state,id)}dropConnection(id){for(let sessionId of[...this.#attachments.get(id)??[]])this.detach(id,sessionId)}capabilitiesChanged(id){for(let sessionId of this.#attachments.get(id)??[]){let state=this.#sessions.get(sessionId);state!==void 0&&(this.#register(id,state),this.fanout.connectionHas(id,"grant_select")||this.#cancelFor(state,id))}}routeWorkerGrant(sessionId,requestId,preferred,fallbackCapabilities,cancel){let attached=this.fanout.attachedConnections(sessionId),connection=attached.includes(preferred??"")&&this.fanout.connectionHas(preferred,"grant_select")?preferred:attached.find(id=>this.fanout.connectionHas(id,"grant_select"));if(!(connection!==void 0||this.fanout.isEmpty()&&fallbackCapabilities.includes("grant_select")))return cancel(),{accepted:!1};let state=this.#sessions.get(sessionId);return state===void 0&&(state={snapshot:{generation:0,notices:[]},registrations:new Map,grants:new Map,replayed:new Map},this.#sessions.set(sessionId,state)),state.grants.set(requestId,{connection,cancel}),{accepted:!0,connection}}acceptWorkerResponse(sessionId,requestId,connection){let state=this.#sessions.get(sessionId),pending=state?.grants.get(requestId);if(pending!==void 0)return pending.connection!==connection||connection!==void 0&&!this.fanout.connectionHas(connection,"grant_select")?!1:(state?.grants.delete(requestId),!0)}settleGrant(sessionId,requestId){this.#sessions.get(sessionId)?.grants.delete(requestId)}dropSession(sessionId){this.#stop(this.#sessions.get(sessionId)),this.#sessions.delete(sessionId);for(let[id,sessions]of this.#attachments)sessions.delete(sessionId),sessions.size===0&&this.#attachments.delete(id)}#register(id,state){if(!this.fanout.connectionHas(id,"grant_select")){state.registrations.get(id)?.(),state.registrations.delete(id);return}if(state.registrations.has(id)||state.select===void 0||state.durableId===void 0)return;let select=state.select;state.registrations.set(id,attachMcpGrantPresentation(state.durableId,(title,choices,opts)=>this.inConnection(id,()=>select(title,choices,opts))))}#replay(sessionId,id,snapshot){let target=this.fanout.get(id);if(target===void 0)return;let state=this.#sessions.get(sessionId),revision=JSON.stringify(snapshot);if(state?.replayed.get(id)!==revision){state?.replayed.set(id,revision);for(let notice of snapshot.notices)target.actor.enqueue(serializeJsonLine({type:"extension_ui_request",id:crypto.randomUUID(),sessionId,method:"notify",notifyType:"warning",message:notice.message}));this.flush()}}#cancelFor(state,id){for(let[requestId,pending]of state.grants)pending.connection===id&&(state.grants.delete(requestId),pending.cancel())}#stop(state){state?.stop?.();for(let stop of state?.registrations.values()??[])stop();for(let pending of state?.grants.values()??[])pending.cancel()}};var blockedMsTotal=0;function recordLoopBlockedMs(driftMs){driftMs>0&&(blockedMsTotal+=driftMs)}function loopBlockedMark(){return blockedMsTotal}function loopBlockedMsSince(mark){return blockedMsTotal-mark}var EVENT_RESYNC_CAPABILITY="event_resync";function isCorrelatedReply(value){return typeof value=="object"&&value!==null&&"type"in value&&value.type==="response"&&"id"in value&&typeof value.id=="string"}var SocketPeerLivenessError=class extends Error{constructor(){super("socket peer missed its liveness ping"),this.name="SocketPeerLivenessError"}},SocketPeerRecovery=class{constructor(write,snapshot){this.awaitingPing=!1,this.pingBuffered=!1,this.replyLost=!1,this.write=write,this.snapshot=snapshot,this.pingBuffered=!0,this.write(serializeJsonLine({type:"rpc_ping"}))}get pending(){return this.reason!==void 0}shed(reason){this.reason===void 0&&(this.reason=reason,this.readSnapshot=this.snapshot(reason))}acknowledge(){this.awaitingPing=!1}loseReply(){this.replyLost=!0}ping(){if(this.awaitingPing)throw new SocketPeerLivenessError;this.awaitingPing=!0,this.pingBuffered||(this.pingBuffered=!0,this.write(serializeJsonLine({type:"rpc_ping"})))}takeSnapshot(){let reason=this.reason;this.reason=void 0,this.awaitingPing=!1,this.pingBuffered=!1;let snapshot=this.readSnapshot;this.readSnapshot=void 0;let gap=reason===void 0?[]:[{type:"resync_required",reason,replyLost:this.replyLost}];return this.replyLost=!1,[...gap,...snapshot?.()??[]]}};var DEFAULT_QUEUE_BYTES=64*1024*1024,DEFAULT_STALL_MS=3e4,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}},SocketEventSinkActor=class{constructor(sink,onFailure,maxQueueBytes=DEFAULT_QUEUE_BYTES,stallMs=DEFAULT_STALL_MS){this.queue=[],this.queuedBytes=0,this.closed=!1,this.recoveryEnabled=!1,this.stopped=new AbortController,this.sink=sink,this.onFailure=onFailure,this.maxQueueBytes=maxQueueBytes,this.stallMs=stallMs}enableRecovery(snapshot){this.recoveryEnabled=!0,this.recovery??=new SocketPeerRecovery(line=>this.sink.writeRaw(line),snapshot),this.recovery.acknowledge()}disableRecovery(){this.recoveryEnabled=!1,this.recovery?.pending||(this.recovery=void 0)}enqueue(line,key,onWritten,demotedLine,reply=!1){if(this.closed)return;if(this.recovery?.pending&&!reply){onWritten?.();return}let bytes=Buffer.byteLength(line);if(this.recovery?.pending){this.queuedBytes+bytes<=this.maxQueueBytes?(this.queue.push({line,bytes,onWritten,reply}),this.queuedBytes+=bytes):(this.recovery.loseReply(),onWritten?.());return}if(key!==void 0){let existing=this.queue.find(entry=>entry.key===key);existing&&(existing.demotedLine!==void 0&&(this.queuedBytes-=existing.bytes,existing.line=existing.demotedLine,existing.bytes=Buffer.byteLength(existing.line),this.queuedBytes+=existing.bytes,existing.demotedLine=void 0),existing.key=void 0)}if(this.queuedBytes+bytes>this.maxQueueBytes){if(this.recovery&&this.recoveryEnabled){this.shed("overflow"),this.enqueue(line,void 0,onWritten,void 0,reply),this.drain();return}let overflow=new SocketEventQueueOverflowError(this.queuedBytes,bytes,this.maxQueueBytes,line.slice(0,120));this.closed=!0,this.queue.length=0,this.queuedBytes=0;try{this.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"overflow, resync required"})}
3
3
  `)}catch(cause){this.onFailure(cause)}this.onFailure(overflow);return}this.queue.push({line,bytes,key,demotedLine,onWritten,reply}),this.queuedBytes+=bytes,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.queue.length=0,this.queuedBytes=0,this.stopped.abort()}shed(reason){if(this.recovery?.pending)return;let replies=[];for(let entry of this.queue)entry.reply?replies.push(entry):entry.onWritten?.();this.queue.length=0;for(let reply of replies)this.queue.push(reply);this.queuedBytes=replies.reduce((bytes,entry)=>bytes+entry.bytes,0),this.recovery?.shed(reason)}waitForDrainOrStall(writtenBytes){return new Promise((resolve,reject)=>{let timer,blockedMark=loopBlockedMark(),cleanup=()=>{clearTimeout(timer),this.stopped.signal.removeEventListener("abort",onStop)},onStop=()=>{cleanup(),resolve()},onDeadline=()=>{let blockedMs=loopBlockedMsSince(blockedMark);if(blockedMs>0){blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,Math.min(blockedMs,this.stallMs));return}if(this.recovery&&this.recoveryEnabled){try{this.shed("stall"),this.recovery.ping(),blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,this.stallMs)}catch(cause){cleanup(),reject(cause)}return}let stall=new SocketEventQueueStallError(this.queuedBytes+writtenBytes,this.stallMs);try{this.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"stalled, resync required"})}
4
4
  `)}catch{}cleanup(),reject(stall)};timer=setTimeout(onDeadline,this.stallMs),this.stopped.signal.addEventListener("abort",onStop,{once:!0}),this.sink.waitForBackpressure().then(()=>{cleanup(),resolve()},cause=>{cleanup(),reject(cause)})})}drain(){return this.draining?this.draining:(this.draining=(async()=>{try{for(;!this.closed&&(this.queue.length>0||this.recovery?.pending);){if(this.recovery?.pending&&this.queue.length===0){if(await this.waitForDrainOrStall(0),this.closed)break;let snapshot=this.recovery.takeSnapshot();this.recoveryEnabled||(this.recovery=void 0);for(let record of snapshot){if(this.closed||this.recovery?.pending)break;let line=serializeJsonLine(record);this.sink.writeRaw(line),await this.waitForDrainOrStall(Buffer.byteLength(line))}continue}let entry=this.queue.shift();this.queuedBytes-=entry.bytes,this.sink.writeRaw(entry.line),await this.waitForDrainOrStall(entry.bytes),entry.onWritten?.()}}catch(cause){this.failure=cause,this.closed=!0,this.queue.length=0,this.queuedBytes=0,this.onFailure(cause)}})().finally(()=>{this.draining=void 0,!this.closed&&(this.queue.length>0||this.recovery?.pending)&&this.drain()}),this.draining)}};var BROADCAST_LIFECYCLE_RECORDS=new Set(["agent_start","agent_settled","agent_idle","session_opened","session_closed","session_lifecycle"]);function snapshotPlaceholderLine(record){if(record.placeholderLine!==void 0)return record.placeholderLine;let redacted=record.source===void 0?void 0:omitInlineMedia(record.source);return record.placeholderLine=redacted===void 0||redacted===record.source?record.line:serializeJsonLine(redacted),record.placeholderLine}var SessionEventFanout=class{constructor(){this.connections=new Map,this.sessionSnapshots=new Map,this.lifecycleSnapshots=new Map,this.pendingQuestions=new Map,this.connectionCapabilities=new Map,this.connectionSessions=new Map,this.registeredCapabilityConnections=new Set}registerConnection(id,connection,options={}){let actor=new SocketEventSinkActor(connection,cause=>{this.connections.get(id)?.actor===actor&&(this.connections.delete(id),this.connectionCapabilities.delete(id),this.connectionSessions.delete(id),this.registeredCapabilityConnections.delete(id),this.onConnectionClosed?.(id)),process.stderr.write(`senpi rpc connection ${id} event queue failed; closing: ${cause instanceof Error?cause.message:String(cause)}
5
5
  `),connection.close?.()},options.maxQueueBytes,options.stallMs);this.connections.set(id,{connection,actor}),this.connectionCapabilities.set(id,new Set),this.connectionSessions.set(id,new Set)}unregisterConnection(id){let registered=this.connections.get(id);registered&&(registered.actor.close(),this.connections.delete(id),this.connectionCapabilities.delete(id),this.connectionSessions.delete(id),this.registeredCapabilityConnections.delete(id))}attachConnectionToSession(id,sessionId){if(!this.connections.has(id))return;let sessions=this.connectionSessions.get(id)??new Set;if(!sessions.has(sessionId)){sessions.add(sessionId),this.connectionSessions.set(id,sessions),this.replaySnapshot(id,sessionId);for(let frame of this.pendingQuestions.get(sessionId)?.values()??[])this.connections.get(id)?.actor.enqueue(serializeJsonLine({...frame,remainingMs:typeof frame.deadlineAtMs=="number"?Math.max(0,frame.deadlineAtMs-Date.now()):0}))}}detachConnectionFromSession(id,sessionId){this.connectionSessions.get(id)?.delete(sessionId)}setConnectionCapabilities(id,capabilities){let registered=this.connections.get(id);registered&&(this.connectionCapabilities.set(id,new Set(capabilities)),this.registeredCapabilityConnections.add(id),capabilities.includes(EVENT_RESYNC_CAPABILITY)?registered.actor.enableRecovery(reason=>{let attached=[...this.connectionSessions.get(id)??[]];return()=>this.resyncSnapshot(id,reason,attached)}):registered.actor.disableRecovery())}clearConnectionCapabilities(id){this.connections.has(id)&&(this.connectionCapabilities.set(id,new Set),this.registeredCapabilityConnections.delete(id))}hasRegisteredConnectionCapabilities(id){return this.registeredCapabilityConnections.has(id)}getConnectionCapabilities(id){if(this.registeredCapabilityConnections.has(id))return[...this.connectionCapabilities.get(id)??[]]}connectionHas(id,capability){return id===void 0?!1:this.connectionCapabilities.get(id)?.has(capability)??!1}targets(sessionId,targetId,isTargeted,recordType){return isTargeted?[targetId]:typeof recordType=="string"&&BROADCAST_LIFECYCLE_RECORDS.has(recordType)?this.connections.size>0?[...this.connections.keys()]:[void 0]:this.connections.size>0?[...this.connections.keys()].filter(id=>this.connectionSessions.get(id)?.has(sessionId)):[void 0]}get(id){return this.connections.get(id)}values(){return this.connections.values()}isEmpty(){return this.connections.size===0}broadcast(line){for(let{actor}of this.connections.values())actor.enqueue(line)}connectionIds(){return[...this.connections.keys()]}attachedConnections(sessionId){return[...this.connections.keys()].filter(id=>this.connectionSessions.get(id)?.has(sessionId))}pendingQuestionCount(sessionId){return this.pendingQuestions.get(sessionId)?.size??0}deliverToSession(sessionId,line){for(let[id,{actor}]of this.connections)this.connectionSessions.get(id)?.has(sessionId)&&actor.enqueue(line)}rememberSnapshot(sessionId,value,line,placeholderLine,source){if(value.type==="session_lifecycle"){this.lifecycleSnapshots.set(sessionId,{line,placeholderLine,source});return}if(value.type==="extension_ui_request"&&value.method==="question"&&typeof value.id=="string"){let pending=this.pendingQuestions.get(sessionId)??new Map;pending.set(value.id,{...value}),this.pendingQuestions.set(sessionId,pending);return}if(value.type==="question_resolved"&&typeof value.id=="string"){this.pendingQuestions.get(sessionId)?.delete(value.id);return}if(value.type==="question_updated"&&typeof value.id=="string"){let frame=this.pendingQuestions.get(sessionId)?.get(value.id);frame&&Object.assign(frame,{deadlineAtMs:value.deadlineAtMs,remainingMs:value.remainingMs});return}let event=value.assistantMessageEvent,record={line,placeholderLine,source};value.type==="message_start"||value.type==="message_update"&&event?.type==="text_start"?this.sessionSnapshots.set(sessionId,[record]):this.sessionSnapshots.has(sessionId)&&this.sessionSnapshots.get(sessionId)?.push(record),value.type==="message_end"&&this.sessionSnapshots.delete(sessionId)}forgetSession(sessionId){this.pendingQuestions.delete(sessionId),this.sessionSnapshots.delete(sessionId),this.lifecycleSnapshots.delete(sessionId)}replaySnapshot(id,sessionId){let actor=this.connections.get(id)?.actor;if(!actor)return;let placeholders=this.connectionHas(id,MEDIA_PLACEHOLDERS_CAPABILITY),lifecycle=this.lifecycleSnapshots.get(sessionId);lifecycle&&actor.enqueue(placeholders?snapshotPlaceholderLine(lifecycle):lifecycle.line);for(let record of this.sessionSnapshots.get(sessionId)??[])actor.enqueue(placeholders?snapshotPlaceholderLine(record):record.line)}resyncSnapshot(id,reason,attached){let placeholders=this.connectionHas(id,MEDIA_PLACEHOLDERS_CAPABILITY),current=this.connectionSessions.get(id)??new Set;return[...new Set([...attached,...current])].map(sessionId=>{let latest=(this.sessionSnapshots.get(sessionId)??[]).findLast(record2=>record2.source?.message!=null),frozen=latest===void 0?void 0:JSON.parse(latest.line),record={type:"resync_required",sessionId,reason,message:typeof frozen=="object"&&frozen!==null&&"message"in frozen?frozen.message:null,...current.has(sessionId)?{}:{closed:!0}};return placeholders?omitInlineMedia(record):record})}};var SessionOpenTurns=class{constructor(){this.open=new Map}note(sessionId,type){if(type==="agent_start")this.open.set(sessionId,(this.open.get(sessionId)??0)+1);else if(type==="agent_settled"){let left=(this.open.get(sessionId)??0)-1;left>0?this.open.set(sessionId,left):this.open.delete(sessionId)}}take(sessionId){let owed=this.open.get(sessionId)??0;return this.open.delete(sessionId),owed}};var SessionRecordAccounting=class{constructor(){this.count=0,this.bytes=0}append(queue,value,key,resolve,reject){let line=serializeJsonLine(value),byteLength=Buffer.byteLength(line),node={value,line,byteLength,key,previous:queue.tail,resolve,reject};return queue.tail?queue.tail.next=node:queue.head=node,queue.tail=node,this.count++,this.bytes+=byteLength,node}replace(node,value){let line=serializeJsonLine(value),byteLength=Buffer.byteLength(line);this.bytes+=byteLength-node.byteLength,node.value=value,node.line=line,node.byteLength=byteLength}unlink(queue,node){node.previous?node.previous.next=node.next:queue.head=node.next,node.next?node.next.previous=node.previous:queue.tail=node.previous,node.key&&queue.latestByKey.get(node.key)===node&&queue.latestByKey.delete(node.key),node.previous=void 0,node.next=void 0,this.count--,this.bytes-=node.byteLength}};function liveStatus(runtime,fanout){return fanout.pendingQuestions>0||runtime.pendingQuestions>0?"waiting_input":runtime.isCompacting?"compacting":runtime.isStreaming?"running":"idle"}function statusOf(entry,runtime,fanout,terminal){if(terminal!==void 0)return terminal.status;switch(entry.state){case"opening":return"opening";case"closing":case"quarantined":case"closed":return"closed";case"open":return runtime===void 0?"opening":liveStatus(runtime,fanout);default:{let exhaustive=entry.state;throw new Error(`unexpected session state ${String(exhaustive)}`)}}}function deriveSessionStatus(entry,runtime,fanout,terminal,cause){let status=statusOf(entry,runtime,fanout,terminal),reason=terminal?.reason??(status==="idle"&&cause==="abort"?"aborted":void 0);return{status,...reason!==void 0?{reason}:{},kind:entry.kind,cwd:entry.cwd,attachments:Math.max(0,entry.attachments),...entry.durableSessionId!==void 0?{durableSessionId:entry.durableSessionId}:{},...entry.sessionPath!==void 0?{sessionPath:entry.sessionPath}:{},...entry.name!==void 0?{name:entry.name}:{},...runtime?.model!==void 0?{model:{provider:runtime.model.provider,id:runtime.model.id}}:{},...runtime?.thinkingLevel!==void 0?{thinkingLevel:runtime.thinkingLevel}:{},pendingQueue:{steering:runtime?.steering??0,followUp:runtime?.followUp??0},context:entry.context}}function terminalOfLifecycle(record){let reason=typeof record.reason=="string"?record.reason:void 0;if(record.type==="session_parked")return{status:"unloaded",reason:reason==="unloaded"?"unload_session":"idle"};if(record.type==="session_closed")return reason==="handoff_parked"?{status:"unloaded",reason:"handoff"}:reason===void 0?{status:"closed"}:{status:"closed",reason}}function causeOfRecord(record){switch(record.type){case"agent_start":return"prompt";case"agent_end":return"agent_end";case"agent_idle":return"agent_idle";case"session_abort":return"abort";case"queue_update":return"queue";case"model_changed":case"thinking_level_changed":return"set_model";case"session_replaced":return"replace";case"session_parked":return"park";case"session_closed":return"close";case"question_resolved":return"question";case"extension_ui_request":return record.method==="question"?"question":void 0;case"compaction_start":case"compaction_end":return"compaction";default:return}}function sessionOpenedLines(record){let{context,...plain}=record;return{plain:serializeJsonLine(plain),withContext:serializeJsonLine(context===void 0?plain:{...plain,context})}}var RECORD_TYPE_PATTERN=/^[a-z][a-z0-9_]{0,63}$/;function refusal(reason,action){return{refusal:{reason,action}}}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseSelector(value){if(value===void 0||value==="all")return{selector:{kind:"all"}};let action='send sessions: "all", { ids: [<sessionId | durableSessionId | sessionPath>] } or { childrenOf: <durableSessionId> }';if(!isRecord(value))return refusal('sessions must be "all" or an object',action);if("ids"in value&&!("childrenOf"in value)){let ids=value.ids;return!Array.isArray(ids)||ids.length===0||ids.length>1024?refusal("sessions.ids must be a non-empty array of at most 1024 strings",action):ids.every(id=>typeof id=="string"&&id.length>0)?{selector:{kind:"ids",ids:new Set(ids)}}:refusal("every sessions.ids entry must be a non-empty string",action)}if("childrenOf"in value&&!("ids"in value)){let parent=value.childrenOf;return typeof parent!="string"||parent.length===0?refusal("sessions.childrenOf must be a non-empty durable session id",action):{selector:{kind:"childrenOf",parent}}}return refusal("sessions must name exactly one of ids or childrenOf",action)}function parseMirror(value){if(value===void 0||value==="none")return{mirror:{kind:"none"}};if(value==="all")return{mirror:{kind:"all"}};let action='send mirror: "none", "all" or an array of record types such as ["message_update"]';return!Array.isArray(value)||value.length===0||value.length>64?refusal('mirror must be "none", "all" or a non-empty array of at most 64 record types',action):value.every(type=>typeof type=="string"&&RECORD_TYPE_PATTERN.test(type))?{mirror:{kind:"types",types:new Set(value)}}:refusal(`every mirror entry must be a record type matching ${RECORD_TYPE_PATTERN.source}`,action)}function optionalBoolean(value,field){return value===void 0||typeof value=="boolean"?value:{reason:`${field} must be a boolean`,action:`send ${field}: true or false, or omit it`}}function parseSubscription(request){let selector=parseSelector(request.sessions);if("refusal"in selector)return selector;let mirror=parseMirror(request.mirror);if("refusal"in mirror)return mirror;let includeWorkers=optionalBoolean(request.include_workers,"include_workers");if(typeof includeWorkers=="object")return{refusal:includeWorkers};let includeContext=optionalBoolean(request.include_context,"include_context");if(typeof includeContext=="object")return{refusal:includeContext};let effects=optionalBoolean(request.effects,"effects");return typeof effects=="object"?{refusal:effects}:{options:{selector:selector.selector,includeWorkers:includeWorkers??selector.selector.kind==="childrenOf",includeContext:includeContext??!1,mirror:mirror.mirror,effects:effects??selector.selector.kind==="childrenOf"}}}function subscriptionMatches(options,sessionId,entry){if(entry.kind==="worker"&&!options.includeWorkers)return!1;let selector=options.selector;switch(selector.kind){case"all":return!0;case"ids":return selector.ids.has(sessionId)||entry.durableSessionId!==void 0&&selector.ids.has(entry.durableSessionId)||entry.sessionPath!==void 0&&selector.ids.has(entry.sessionPath);case"childrenOf":{let lineage=entry.openContext??entry.context;return(lineage.parent_session_id??lineage.root_session_id)===selector.parent}default:{let exhaustive=selector;throw new Error(`unexpected selector ${String(exhaustive)}`)}}}function mirrorsRecord(mirror,recordType){switch(mirror.kind){case"none":return!1;case"all":return!0;case"types":return mirror.types.has(recordType);default:{let exhaustive=mirror;throw new Error(`unexpected mirror ${String(exhaustive)}`)}}}var MAX_SUBSCRIPTIONS_PER_CONNECTION=64,SessionStatusStream=class{constructor(delivery){this.subscriptions=new Map,this.pendings=new Map,this.terminals=new Map,this.lastViews=new Map,this.lastChanges=new Map,this.nextSubscription=0,this.delivery=delivery}setSource(source){this.source=source}setLastEffectProvider(provider){this.lastEffect=provider}get size(){return this.subscriptions.size}connectionSize(connectionId){let count=0;for(let pending of this.pendings.values())pending.connectionId===connectionId&&count++;for(let subscription of this.subscriptions.values())subscription.connectionId===connectionId&&count++;return count}subscribe(connectionId,options){let pending={id:`sub-${++this.nextSubscription}`,connectionId,options,seq:0,lines:[]};this.pendings.set(pending.id,pending);let snapshot=[];for(let sessionId of this.source?.sessionIds()??[]){let view=this.currentView(sessionId);if(view===void 0||!subscriptionMatches(options,sessionId,view.entry))continue;let derived=this.derive(sessionId,view);snapshot.push(this.recordFor(pending,sessionId,derived,this.lastChangeOf(sessionId)))}return{subscriptionId:pending.id,snapshot,seq:pending.seq}}activate(subscriptionId){let pending=this.pendings.get(subscriptionId);if(pending===void 0)return;this.pendings.delete(subscriptionId);let subscription={id:pending.id,connectionId:pending.connectionId,options:pending.options,seq:pending.seq};this.subscriptions.set(subscription.id,subscription);for(let line of pending.lines)this.delivery.enqueue(subscription.connectionId,line);pending.lines.length=0}unsubscribe(connectionId,subscriptionId){let pending=this.pendings.get(subscriptionId);return pending!==void 0?pending.connectionId!==connectionId?!1:(this.pendings.delete(subscriptionId),!0):this.subscriptions.get(subscriptionId)?.connectionId!==connectionId?!1:(this.subscriptions.delete(subscriptionId),!0)}dropConnection(connectionId){for(let[id,pending]of this.pendings)pending.connectionId===connectionId&&this.pendings.delete(id);for(let[id,subscription]of this.subscriptions)subscription.connectionId===connectionId&&this.subscriptions.delete(id)}publish(sessionId,cause,by,contextOnly=!1){let change={at:(this.delivery.now?.()??new Date).toISOString(),cause,by};if(this.lastChanges.set(sessionId,change),this.subscriptions.size===0&&this.pendings.size===0)return;let view=this.currentView(sessionId);if(view===void 0)return;let derived=this.derive(sessionId,view,cause);for(let pending of this.pendings.values())contextOnly&&!pending.options.includeContext||subscriptionMatches(pending.options,sessionId,view.entry)&&(pending.seq+=1,pending.lines.push(serializeJsonLine(this.recordFor(pending,sessionId,derived,change))));for(let subscription of this.subscriptions.values()){if(contextOnly&&!subscription.options.includeContext||!subscriptionMatches(subscription.options,sessionId,view.entry))continue;subscription.seq+=1;let record=this.recordFor(subscription,sessionId,derived,change);this.delivery.enqueue(subscription.connectionId,serializeJsonLine(record))||this.subscriptions.delete(subscription.id)}}publishEffect(sessionId,status){if(this.subscriptions.size===0&&this.pendings.size===0)return;let view=this.currentView(sessionId);if(view===void 0)return;let at=status.updatedAt??status.acceptedAt??(this.delivery.now?.()??new Date).toISOString();for(let pending of this.pendings.values())!pending.options.effects||!subscriptionMatches(pending.options,sessionId,view.entry)||(pending.seq+=1,pending.lines.push(serializeJsonLine(effectStatusRecord(pending,sessionId,status,at))));for(let subscription of this.subscriptions.values()){if(!subscription.options.effects||!subscriptionMatches(subscription.options,sessionId,view.entry))continue;subscription.seq+=1;let line=serializeJsonLine(effectStatusRecord(subscription,sessionId,status,at));this.delivery.enqueue(subscription.connectionId,line)||this.subscriptions.delete(subscription.id)}}seal(sessionId,terminal,cause,by){this.terminals.set(sessionId,terminal),this.publish(sessionId,cause,by)}forget(sessionId){this.terminals.delete(sessionId),this.lastViews.delete(sessionId),this.lastChanges.delete(sessionId)}mirrorTargets(sessionId,recordType){let subscriptions=[...this.pendings.values(),...this.subscriptions.values()].filter(subscription=>mirrorsRecord(subscription.options.mirror,recordType));if(subscriptions.length===0)return[];let entry=this.source?.entryView(sessionId)??this.lastViews.get(sessionId)?.entry;if(entry===void 0)return[];let targets=new Set;for(let subscription of subscriptions)subscriptionMatches(subscription.options,sessionId,entry)&&targets.add(subscription.connectionId);return[...targets]}matchingConnections(sessionId){let view=this.currentView(sessionId),matches=new Map;if(view===void 0)return matches;for(let subscription of this.subscriptions.values())subscriptionMatches(subscription.options,sessionId,view.entry)&&matches.set(subscription.connectionId,(matches.get(subscription.connectionId)??!1)||subscription.options.includeContext);return matches}currentView(sessionId){let live=this.source?.view(sessionId);return live!==void 0&&this.lastViews.set(sessionId,live),live??this.lastViews.get(sessionId)}derive(sessionId,view,cause){return deriveSessionStatus(view.entry,view.runtime,{pendingQuestions:this.delivery.pendingQuestions(sessionId)},this.terminals.get(sessionId),cause)}lastChangeOf(sessionId){return this.lastChanges.get(sessionId)??{at:(this.delivery.now?.()??new Date).toISOString(),cause:"open",by:"host"}}recordFor(subscription,sessionId,derived,lastChange){let{context,...rest}=derived,lastEffect=this.lastEffect?.(sessionId);return{type:"session_status",subscriptionId:subscription.id,seq:subscription.seq,sessionId,...rest,...subscription.options.includeContext?{context}:{},...lastEffect!==void 0?{lastEffect}:{},lastChange}}};var SurfaceDigestDedupe=class{constructor(){this.connections=new Map}announce(connectionId,sessionId,previous,digest){let sessions=this.connections.get(connectionId);if(sessions===void 0&&(sessions=new Map,this.connections.set(connectionId,sessions)),previous===digest)return!1;let tell=!0;for(let[other,announced]of sessions)if(!(other===sessionId||announced.last!==digest)&&announced.previous===previous){tell=!1;break}return sessions.set(sessionId,{last:digest,previous}),tell}dropConnection(connectionId){this.connections.delete(connectionId)}forgetSession(sessionId){for(let sessions of this.connections.values())sessions.delete(sessionId)}};var settleActors=actors=>Promise.all(actors.map(actor=>actor.flush().catch(()=>{}))).then(()=>{}),acceptActors=actors=>Promise.all(actors.map(actor=>actor.waitForAcceptance())).then(()=>{}),MAX_SHARED_STDIO_QUEUE_BYTES=64*1024*1024,MAX_SHARED_STDIO_QUEUE_RECORDS=4096,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 typedEvent=event;if(!(typeof typedEvent.type!="string"||!COMPACT_DELTA_TYPES.has(typedEvent.type)||typeof typedEvent.contentIndex!="number"||typeof typedEvent.delta!="string"))return{type:typedEvent.type,contentIndex:typedEvent.contentIndex,delta:typedEvent.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}var SessionEventWriter=class{enableMcpPresenters(){return this.presenterAuthority??=new McpPresenterAuthority,this.presenterAuthority}get mcpPresenters(){return this.presenterAuthority}getMcpPresenterConnection(id){return this.presenterConnections.get(id)}findMcpPresenterConnection(nonce){return[...this.presenterConnections.values()].find(connection=>connection.nonce===nonce)}getMcpFormBinding(sessionId){return this.presenterBindings.get(sessionId)}bindMcpForms(sessionId,durableId,ui,admit){let authority=this.presenterAuthority;if(!authority)return;let binding=authority.bind(sessionId,durableId,admit);this.presenterBindings.set(sessionId,binding);for(let id of this.fanout.attachedConnections(sessionId)){let connection=this.presenterConnections.get(id);connection&&authority.attach(connection,binding)}return bindPrivateMcpForms(ui,binding),()=>{binding.dispose(),this.presenterBindings.get(sessionId)===binding&&this.presenterBindings.delete(sessionId)}}handleMcpForm(value){if(!this.presenterAuthority||typeof value!="object"||value===null||!("type"in value)||typeof value.type!="string"||!value.type.startsWith("mcp_form_")&&value.type!=="mcp_presenter_context")return!1;let id=this.currentConnection(),sender=id===void 0?void 0:this.presenterConnections.get(id),context=value.type==="mcp_presenter_context"&&"sessionId"in value&&typeof value.sessionId=="string"&&sender?this.presenterAuthority?.connectionContext(sender,value.sessionId):void 0,reply=value.type==="mcp_presenter_context"?context?{ok:!0,context}:{error:"presenter_not_authorized"}:sender&&this.presenterAuthority?this.presenterAuthority.receive(sender,value):{error:"presenter_not_authorized"},connection=id===void 0?void 0:this.fanout.get(id)?.connection;if(connection)try{connection.writeRaw(serializeJsonLine({type:"mcp_form_reply",..."id"in value&&typeof value.id=="string"?{id:value.id}:{},...reply}))}catch{sender&&this.presenterAuthority?.detach(sender)}return!0}get pendingCloseRecordCount(){return this.reservedCloseRecords}get pendingCloseByteLength(){return this.reservedCloseBytes}constructor(writeRaw,waitOrSchedule,scheduleFlush){this.presenterConnections=new Map,this.presenterBindings=new Map,this.records=new SessionRecordAccounting,this.queues=new Map,this.fanout=new SessionEventFanout,this.connectionContext=new AsyncLocalStorage,this.securityPresentations=new RpcSecurityPresentations(this.fanout,(id,task)=>this.withConnection(id,task),()=>this.requestFlush()),this.workerSecurityBridge=!1,this.controlQueue={latestByKey:new Map,ready:!1},this.readyQueues=[],this.sealedSessions=new Set,this.workerSessions=new Set,this.openTurns=new SessionOpenTurns,this.status=new SessionStatusStream({enqueue:(connectionId,line)=>{let actor=this.fanout.get(connectionId)?.actor;return actor===void 0?!1:(actor.enqueue(line),this.requestFlush(),!0)},pendingQuestions:sessionId=>this.fanout.pendingQuestionCount(sessionId)}),this.surfaceDedupe=new SurfaceDigestDedupe,this.mediaPersisters=new Map,this.flushScheduled=!1,this.controlOverflowReported=!1,this.closeOverflowReported=!1,this.closeOverflowActors=new WeakSet,this.reservedCloseRecords=0,this.reservedCloseBytes=0,this.fanout.onConnectionClosed=id=>{this.securityPresentations.dropConnection(id);let sender=this.presenterConnections.get(id);sender&&this.presenterAuthority?.detach(sender),this.presenterConnections.delete(id)},this.writeRaw=writeRaw,waitOrSchedule&&scheduleFlush===void 0&&waitOrSchedule.length>0?this.scheduleFlush=waitOrSchedule:(this.waitForBackpressure=waitOrSchedule,this.scheduleFlush=scheduleFlush??(flush=>queueMicrotask(()=>{flush()})))}get bufferedRecordCount(){return this.records.count+(this.inFlight?1:0)}get bufferedByteLength(){return this.records.bytes+(this.inFlight?.node.byteLength??0)}isSessionSealed(sessionId){return this.sealedSessions.has(sessionId)}registerConnection(id,connection,options={}){let previousPresenter=this.presenterConnections.get(id);if(previousPresenter&&this.presenterAuthority?.detach(previousPresenter),this.fanout.registerConnection(id,connection,options),this.presenterAuthority){let sender=this.presenterAuthority.connect(id,frame=>{if(!this.fanout.get(id))return!1;try{return connection.writeRaw(serializeJsonLine(frame)),connection.waitForBackpressure().catch(()=>this.presenterAuthority?.detach(sender)),!0}catch{return this.presenterAuthority?.detach(sender),!1}});this.presenterConnections.set(id,sender)}}unregisterConnection(id){let sender=this.presenterConnections.get(id);sender&&this.presenterAuthority?.detach(sender),this.presenterConnections.delete(id),this.securityPresentations.dropConnection(id),this.fanout.unregisterConnection(id),this.status.dropConnection(id),this.surfaceDedupe.dropConnection(id)}attachConnectionToSession(id,sessionId){this.fanout.attachConnectionToSession(id,sessionId),this.hasConnection(id)&&this.securityPresentations.attach(id,sessionId);let sender=this.presenterConnections.get(id),binding=this.presenterBindings.get(sessionId);sender&&binding&&this.presenterAuthority?.attach(sender,binding)}detachConnectionFromSession(id,sessionId){let sender=this.presenterConnections.get(id),binding=this.presenterBindings.get(sessionId);sender&&binding&&this.presenterAuthority?.detach(sender,binding),this.fanout.detachConnectionFromSession(id,sessionId),this.securityPresentations.detach(id,sessionId)}hasConnection(id){return this.fanout.get(id)!==void 0}setConnectionCapabilities(id,capabilities){if(this.fanout.setConnectionCapabilities(id,capabilities),this.securityPresentations.capabilitiesChanged(id),!capabilities.includes("interactive_user")||!capabilities.includes("mcp_form_presenter_v1")){let sender=this.presenterConnections.get(id);sender&&this.presenterAuthority?.withdraw(sender)}}clearConnectionCapabilities(id){let sender=this.presenterConnections.get(id);sender&&this.presenterAuthority?.withdraw(sender),this.fanout.clearConnectionCapabilities(id),this.securityPresentations.capabilitiesChanged(id)}bindSecurityPresentations(sessionId,durableId,notices,ui){if(!this.fanout.isEmpty())return this.securityPresentations.bind(sessionId,durableId,notices,ui.select)}acceptWorkerSecuritySnapshot(sessionId,snapshot){this.securityPresentations.acceptSnapshot(sessionId,snapshot)}routeWorkerGrant(sessionId,requestId,preferred,capabilities,cancel){return this.securityPresentations.routeWorkerGrant(sessionId,requestId,preferred,capabilities,cancel)}acceptWorkerGrantResponse(sessionId,id,connection){return this.securityPresentations.acceptWorkerResponse(sessionId,id,connection)}settleGrantDialog(sessionId,id){this.securityPresentations.settleGrant(sessionId,id)}hasRegisteredConnectionCapabilities(id){return this.fanout.hasRegisteredConnectionCapabilities(id)}getConnectionCapabilities(id){return this.fanout.getConnectionCapabilities(id)}setSessionMedia(sessionId,persister){persister===void 0?this.mediaPersisters.delete(sessionId):this.mediaPersisters.set(sessionId,persister)}setSessionKind(sessionId,kind){kind==="worker"?this.workerSessions.add(sessionId):this.workerSessions.delete(sessionId)}async flushConnection(id){let target=this.fanout.get(id);target&&await settleActors([target.actor])}withConnection(id,task){return this.connectionContext.run(id,task)}currentConnection(){return this.connectionContext.getStore()}enqueue(sessionId,value){if(this.sealedSessions.has(sessionId))return!1;let targetId=this.connectionContext.getStore(),record=value,isTargeted=record.type==="response"||record.type==="bash_execution_update"||record.type==="host_request"||record.type==="relocation_due"||record.type==="extension_ui_request"&&["select","confirm","input","editor"].includes(String(record.method)),tagged={...value,sessionId},line=serializeJsonLine(tagged);if(this.fanout.isEmpty()&&this.exceedsStdioCapacity(line))return this.closeSession(sessionId,{type:"response",command:"close_session",success:!1,error:"session_output_overflow, resync required"},"error"),!1;this.openTurns.note(sessionId,record.type);let attached=this.fanout.targets(sessionId,targetId,isTargeted,record.type),mirrors=isTargeted?[]:this.status.mirrorTargets(sessionId,String(record.type)),targets=mirrors.length===0?attached:[...new Set([...attached,...mirrors])],redacted=targets.some(target=>this.fanout.connectionHas(target,MEDIA_PLACEHOLDERS_CAPABILITY))?omitInlineMedia(tagged,this.mediaPersisters.get(sessionId)):tagged,placeholderLine=redacted===tagged?void 0:serializeJsonLine(redacted);isTargeted||this.fanout.rememberSnapshot(sessionId,tagged,line,placeholderLine,tagged);for(let target of targets){if(target!==void 0&&!this.fanout.get(target))continue;let registered=target===void 0?void 0:this.fanout.get(target),wants=placeholderLine!==void 0&&this.fanout.connectionHas(target,MEDIA_PLACEHOLDERS_CAPABILITY);if(registered){let keyed=compactDelta(tagged)!==void 0&&tagged.message!==null;registered.actor.enqueue(wants?placeholderLine:line,keyed?MESSAGE_KEY:void 0,void 0,keyed?serializeJsonLine(demoteToDeltaOnly(tagged)):void 0,isCorrelatedReply(tagged))}else this.appendSessionRecord(sessionId,wants?redacted:tagged,target)}let cause=isTargeted?void 0:causeOfRecord(record);return cause!==void 0&&this.status.publish(sessionId,cause,this.changeActor("agent")),this.afterRecord?.(sessionId),this.requestFlush(),!0}changeActor(fallback){return this.connectionContext.getStore()===void 0?fallback:"client"}publishSessionOpened(record){if(this.fanout.isEmpty()){let{context:_context,...wire}=record;this.appendSessionRecord(record.sessionId,{...wire}),this.requestFlush();return}let lines=sessionOpenedLines(record),subscribers=this.status.matchingConnections(record.sessionId),recipients=record.kind==="worker"?new Set([...this.fanout.attachedConnections(record.sessionId),...subscribers.keys()]):new Set(this.fanout.connectionIds());for(let id of recipients)this.fanout.get(id)?.actor.enqueue(subscribers.get(id)===!0?lines.withContext:lines.plain);this.requestFlush()}publishLoadedSurfacesChanged(sessionId,previous,digest){if(this.fanout.isEmpty()){this.enqueue(sessionId,{type:"loaded_surfaces_changed"});return}if(this.sealedSessions.has(sessionId))return;let line=serializeJsonLine({type:"loaded_surfaces_changed",sessionId});for(let id of this.fanout.attachedConnections(sessionId))this.surfaceDedupe.announce(id,sessionId,previous,digest)&&this.fanout.get(id)?.actor.enqueue(line);this.requestFlush()}waitForSessionBackpressure(sessionId){return this.fanout.isEmpty()?this.flush():acceptActors(this.sessionActors(sessionId))}sessionActors(sessionId){return[...new Set([...this.fanout.targets(sessionId,this.currentConnection(),!1,void 0),this.currentConnection()])].flatMap(target=>{let registered=target===void 0?void 0:this.fanout.get(target);return registered?[registered.actor]:[]})}enqueueControl(value,targetOverride){if(this.failure!==void 0)return Promise.reject(this.failure);let targetId=targetOverride??this.connectionContext.getStore(),registered=targetId===void 0?void 0:this.fanout.get(targetId);if(registered)return registered.actor.enqueue(serializeJsonLine(value),void 0,void 0,void 0,isCorrelatedReply(value)),this.requestFlush(),Promise.resolve();if(this.exceedsStdioCapacity(serializeJsonLine(value)))return this.controlOverflowReported||(this.controlOverflowReported=!0,this.records.append(this.controlQueue,{type:"overflow",error:"rpc_control_output_overflow, resync required"}),this.markReady(this.controlQueue),this.requestFlush()),Promise.reject(new Error("rpc_control_output_overflow, resync required"));let queue=targetId===void 0?this.controlQueue:this.connectionQueue(targetId),completion=new Promise((resolve,reject)=>{this.records.append(queue,{...value},void 0,resolve,reject)});return this.markReady(queue),this.requestFlush(),completion}sendOpenQueued(connection,record){let wire={type:"queued",for_request:record.for_request,position:record.position,in_flight:record.in_flight},target=this.fanout.get(connection);target!==void 0&&(target.actor.enqueue(serializeJsonLine(wire)),this.requestFlush())}broadcastHostRecord(record){let wire;switch(record.type){case"host_superseded":wire={type:"host_superseded",instanceId:record.instanceId,generation:record.generation,successor:record.successor};break;case"host_stalled":wire={type:"host_stalled",driftMs:record.driftMs,...record.sessionId!==void 0?{sessionId:record.sessionId}:{},...record.tool!==void 0?{tool:record.tool}:{}};break;case"host_memory_pressure":wire={type:"host_memory_pressure",rssMb:record.rssMb,...record.footprintMb!==void 0?{footprintMb:record.footprintMb}:{},...record.measure!==void 0?{measure:record.measure}:{},sessions:record.sessions,...record.main!==void 0?{main:record.main}:{},...record.kernels!==void 0?{kernels:record.kernels}:{}};break;case"host_trimmed":wire={type:"host_trimmed",footprintBeforeMb:record.footprintBeforeMb,footprintAfterMb:record.footprintAfterMb,measure:record.measure,collected:record.collected,sessions:record.sessions,pauseMs:record.pauseMs};break;case"subscription_limits":wire={type:"subscription_limits",provider:record.provider,account:record.account,windows:record.windows,reportedAt:record.reportedAt,...record.plan===void 0?{}:{plan:record.plan},...record.error===void 0?{}:{error:record.error}};break;default:{let exhaustive=record;throw new Error(`unexpected host record ${exhaustive}`)}}this.fanout.isEmpty()?(this.records.append(this.controlQueue,wire),this.markReady(this.controlQueue)):this.fanout.broadcast(serializeJsonLine(wire)),this.requestFlush()}closeSession(sessionId,response,reason,sessionPath){if(this.presenterBindings.get(sessionId)?.dispose(),this.presenterBindings.delete(sessionId),!this.settleBeforeSeal(sessionId))return;this.sealedSessions.add(sessionId),this.securityPresentations.dropSession(sessionId),this.fanout.forgetSession(sessionId),this.mediaPersisters.delete(sessionId);let targetId=this.connectionContext.getStore(),lifecycle={type:"session_closed",sessionId,...reason&&{reason},...sessionPath&&{sessionPath}};this.fanout.isEmpty()?this.appendSessionRecord(sessionId,lifecycle):this.workerSessions.has(sessionId)?this.fanout.deliverToSession(sessionId,serializeJsonLine(lifecycle)):this.fanout.broadcast(serializeJsonLine(lifecycle)),this.sealStatus(sessionId,lifecycle);let taggedResponse={...response,sessionId},registered=targetId===void 0?void 0:this.fanout.get(targetId);registered?registered.actor.enqueue(serializeJsonLine(taggedResponse),void 0,void 0,void 0,isCorrelatedReply(response)):this.appendSessionRecord(sessionId,taggedResponse,targetId),this.requestFlush()}parkSession(sessionId,sessionPath,reason){this.sealLifecycle(sessionId,{type:"session_parked",sessionId,sessionPath,reason})}releaseSession(sessionId,sessionPath){this.sealLifecycle(sessionId,{type:"session_closed",sessionId,reason:"released",sessionPath})}sealRolledBackOpen(sessionId,sessionPath){this.sealLifecycle(sessionId,{type:"session_closed",sessionId,reason:"error",...sessionPath!==void 0&&{sessionPath}})}sealLifecycle(sessionId,lifecycle,attachedOnly=!1){this.presenterBindings.get(sessionId)?.dispose(),this.presenterBindings.delete(sessionId),this.settleBeforeSeal(sessionId)&&(this.sealedSessions.add(sessionId),this.securityPresentations.dropSession(sessionId),this.fanout.forgetSession(sessionId),this.mediaPersisters.delete(sessionId),this.fanout.isEmpty()?this.appendSessionRecord(sessionId,lifecycle):attachedOnly||this.workerSessions.has(sessionId)?this.fanout.deliverToSession(sessionId,serializeJsonLine(lifecycle)):this.fanout.broadcast(serializeJsonLine(lifecycle)),this.sealStatus(sessionId,lifecycle),this.requestFlush())}sealStatus(sessionId,lifecycle){let terminal=terminalOfLifecycle(lifecycle),cause=causeOfRecord(lifecycle);terminal!==void 0&&cause!==void 0&&this.status.seal(sessionId,terminal,cause,this.changeActor("host"))}reserveCloseResponse(sessionId,response,records=2){let bytes=Buffer.byteLength(serializeJsonLine({...response,sessionId}))+(records===2?Buffer.byteLength(serializeJsonLine({type:"session_closed",sessionId,reason:"client_close"})):0);if(this.bufferedRecordCount+this.reservedCloseRecords+records>MAX_SHARED_STDIO_QUEUE_RECORDS||this.bufferedByteLength+this.reservedCloseBytes+bytes>MAX_SHARED_STDIO_QUEUE_BYTES){let overflow={type:"overflow",command:"close_session",error:"rpc_close_output_overflow, resync required"},targetId=this.currentConnection();if(targetId!==void 0){let actor=this.fanout.get(targetId)?.actor;actor&&!this.closeOverflowActors.has(actor)&&(this.closeOverflowActors.add(actor),actor.enqueue(serializeJsonLine(overflow),void 0,()=>this.closeOverflowActors.delete(actor)))}else this.closeOverflowReported||(this.closeOverflowReported=!0,this.records.append(this.controlQueue,overflow),this.markReady(this.controlQueue),this.requestFlush());return}this.reservedCloseRecords+=records,this.reservedCloseBytes+=bytes;let active=!0,release=()=>{active&&(active=!1,this.reservedCloseRecords-=records,this.reservedCloseBytes-=bytes)};return{release,complete:(terminal,reason)=>{active&&(release(),terminal&&!this.sealedSessions.has(sessionId)?this.closeSession(sessionId,response,reason):this.appendClosedResponse(sessionId,response))}}}enqueueClosedResponse(sessionId,response){this.reserveCloseResponse(sessionId,response,1)?.complete(!1)}appendClosedResponse(sessionId,response){let targetId=this.connectionContext.getStore(),taggedResponse={...response,sessionId},registered=targetId===void 0?void 0:this.fanout.get(targetId);registered?registered.actor.enqueue(serializeJsonLine(taggedResponse),void 0,void 0,void 0,isCorrelatedReply(response)):this.appendSessionRecord(sessionId,taggedResponse,targetId),this.requestFlush()}settleBeforeSeal(sessionId){if(this.sealedSessions.has(sessionId))return!1;for(let owed=this.openTurns.take(sessionId);owed>0;owed-=1)this.enqueue(sessionId,{type:"agent_settled",reason:"session_closed"});return!this.sealedSessions.has(sessionId)}forgetSession(sessionId){this.sealedSessions.delete(sessionId),this.openTurns.take(sessionId),this.workerSessions.delete(sessionId),this.fanout.forgetSession(sessionId),this.mediaPersisters.delete(sessionId),this.status.forget(sessionId),this.surfaceDedupe.forgetSession(sessionId)}flush(){if(this.failure!==void 0)return Promise.reject(this.failure);if(this.flushScheduled=!1,this.drainPromise)return this.drainPromise;if(this.readyQueues.length===0)return settleActors([...this.fanout.values()].map(({actor})=>actor));let resolveDrain,rejectDrain,drain=new Promise((resolve,reject)=>{resolveDrain=resolve,rejectDrain=reject});return this.drainPromise=drain,this.drainUntilEmpty().then(resolveDrain,rejectDrain),drain.then(()=>{this.drainPromise===drain&&(this.drainPromise=void 0),this.readyQueues.length>0&&this.requestFlush()},cause=>{this.drainPromise===drain&&(this.drainPromise=void 0),this.fail(cause)}),drain}async drainUntilEmpty(){do await this.drainReadyQueues();while(this.readyQueues.length>0);await settleActors([...this.fanout.values()].map(({actor})=>actor)),this.controlOverflowReported=!1,this.reservedCloseRecords===0&&(this.closeOverflowReported=!1)}async drainReadyQueues(){for(;this.readyQueues.length>0;){let queue=this.readyQueues.shift();queue.ready=!1;let node=queue.head;if(node){this.records.unlink(queue,node),this.inFlight={queue,node};try{let connection=queue.targetId?this.fanout.get(queue.targetId)?.connection:void 0,writeRaw=connection?.writeRaw??this.writeRaw,waitForBackpressure=connection?.waitForBackpressure??this.waitForBackpressure;!connection&&queue.targetId||(writeRaw(node.line),waitForBackpressure&&await waitForBackpressure()),node.resolve?.()}catch(cause){throw node.reject?.(cause),cause}finally{this.inFlight=void 0}if(queue.head)this.markReady(queue);else if(queue.sessionId||queue.targetId)for(let[key,candidate]of this.queues)candidate===queue&&this.queues.delete(key)}}}exceedsStdioCapacity(line){return this.bufferedRecordCount+this.reservedCloseRecords>=MAX_SHARED_STDIO_QUEUE_RECORDS||this.bufferedByteLength+this.reservedCloseBytes+Buffer.byteLength(line)>MAX_SHARED_STDIO_QUEUE_BYTES}connectionQueue(targetId){let key=`connection:${targetId}`,queue=this.queues.get(key);return queue||(queue={targetId,latestByKey:new Map,ready:!1},this.queues.set(key,queue)),queue}appendSessionRecord(sessionId,value,targetId){let key=`${targetId??"default"}:${sessionId}`,queue=this.queues.get(key);if(queue||(queue={sessionId,targetId,latestByKey:new Map,ready:!1},this.queues.set(key,queue)),compactDelta(value)){let previousFull=queue.latestByKey.get(MESSAGE_KEY);previousFull&&this.demoteAndMerge(queue,previousFull);let node=this.records.append(queue,value,MESSAGE_KEY);queue.latestByKey.set(MESSAGE_KEY,node),this.markReady(queue);return}let toolKey=toolUpdateKey(value);if(toolKey){let previous=queue.latestByKey.get(toolKey);previous&&this.records.unlink(queue,previous);let node=this.records.append(queue,value,toolKey);queue.latestByKey.set(toolKey,node),this.markReady(queue);return}queue.latestByKey.clear(),this.records.append(queue,value),this.markReady(queue)}demoteAndMerge(queue,node){this.records.replace(node,demoteToDeltaOnly(node.value));let current=compactDelta(node.value),preceding=node.previous,previous=preceding?compactDelta(preceding.value):void 0;if(preceding&&previous&&current&&preceding.value.message===null&&previous.type===current.type&&previous.contentIndex===current.contentIndex){let precedingEvent=preceding.value.assistantMessageEvent;this.records.replace(preceding,{...preceding.value,assistantMessageEvent:{...precedingEvent,delta:previous.delta+current.delta}}),this.records.unlink(queue,node)}}markReady(queue){queue.ready||this.inFlight?.queue===queue||!queue.head||(queue.ready=!0,this.readyQueues.push(queue))}requestFlush(){this.failure!==void 0||this.flushScheduled||this.drainPromise||(this.flushScheduled=!0,this.scheduleFlush(()=>this.flush()))}fail(cause){if(this.failure===void 0){this.failure=cause;for(let queue of this.allQueues())for(let node=queue.head;node;node=node.next)node.reject?.(cause)}}*allQueues(){yield*this.queues.values(),yield this.controlQueue}};function socketSink(socket){let needsDrain=!1,cut=!1;return{writeRaw(chunk){!cut&&!socket.destroyed&&(needsDrain=!socket.write(chunk))},close(){if(cut||(cut=!0,socket.destroyed))return;socket.end();let grace=setTimeout(()=>socket.destroy(),5e3);grace.unref(),socket.once("close",()=>clearTimeout(grace))},waitForBackpressure(){return socket.destroyed||!needsDrain?Promise.resolve():(needsDrain=!1,new Promise(resolve=>{let done=()=>{socket.off("drain",done),socket.off("close",done),resolve()};socket.once("drain",done),socket.once("close",done)}))}}}var SESSION_CONTEXT_PATCH_LIMITS={keyPattern:/^[a-z][a-z0-9_]{0,63}$/,valueChars:256,overlayBytes:4096},RESERVED_SESSION_CONTEXT_KEYS=new Set(["host_socket","host_instance","shard_key","tree_key","parent_session_id","root_session_id"]);function refuse(reason,action){return{refusal:{reason,action}}}function applyContextPatch(overlay,patch){let shape='send patch as an object of lowercase keys to string, number, boolean or null values, e.g. { "task_status": "running" }';if(typeof patch!="object"||patch===null||Array.isArray(patch))return refuse("patch must be an object",shape);let entries=Object.entries(patch);if(entries.length===0)return refuse("patch has no keys",shape);let merged={...overlay};for(let[key,value]of entries){if(!SESSION_CONTEXT_PATCH_LIMITS.keyPattern.test(key))return refuse(`key "${key}" must match ${SESSION_CONTEXT_PATCH_LIMITS.keyPattern.source}`,"rename the key to lowercase letters, digits and underscores");if(RESERVED_SESSION_CONTEXT_KEYS.has(key))return refuse(`key "${key}" is set by the host and cannot be patched`,"drop that key from the patch; the host keeps it current");if(typeof value=="string"&&value.length>SESSION_CONTEXT_PATCH_LIMITS.valueChars)return refuse(`value for "${key}" is ${value.length} characters, at most ${SESSION_CONTEXT_PATCH_LIMITS.valueChars} are accepted`,"shorten the value or store it elsewhere and publish a reference");if(typeof value=="number"&&!Number.isFinite(value))return refuse(`value for "${key}" must be a finite number`,shape);if(value!==null&&typeof value!="string"&&typeof value!="number"&&typeof value!="boolean")return refuse(`value for "${key}" must be a string, number, boolean or null`,shape);merged[key]=value}let bytes=Buffer.byteLength(JSON.stringify(merged));return bytes>SESSION_CONTEXT_PATCH_LIMITS.overlayBytes?refuse(`patched context would be ${bytes} bytes, at most ${SESSION_CONTEXT_PATCH_LIMITS.overlayBytes} are accepted`,"remove keys with null or shorten values before adding more"):{overlay:merged}}function publishedSessionContext(base,overlay){if(overlay===void 0)return base;let published={...base};for(let[key,value]of Object.entries(overlay))value===null?delete published[key]:published[key]=value;return published}function modelOf(model){return model===void 0?void 0:{provider:model.provider,id:model.id}}function sessionRuntimeView(session,pendingQuestions){let model=modelOf(session.model);return{isStreaming:session.isStreaming===!0,isCompacting:session.isCompacting===!0,...model!==void 0?{model}:{},...session.thinkingLevel!==void 0?{thinkingLevel:session.thinkingLevel}:{},steering:typeof session.getSteeringMessages=="function"?session.getSteeringMessages().length:0,followUp:typeof session.getFollowUpMessages=="function"?session.getFollowUpMessages().length:0,pendingQuestions:pendingQuestions??sessionQuestionBridges.get(session)?.pendingQuestions()?.length??0}}function runtimeView(entry){let session=entry.runtime?.session;if(session!==void 0)return sessionRuntimeView(session);let state=entry.worker?.snapshot?.state;if(state===void 0)return;let model=modelOf(state.model??void 0);return{isStreaming:state.isStreaming,isCompacting:state.isCompacting,...model!==void 0?{model}:{},...state.thinkingLevel!==void 0?{thinkingLevel:state.thinkingLevel}:{},steering:state.steering.length,followUp:state.followUp.length,pendingQuestions:state.pendingQuestions?.length??0}}function entryView(entry){let session=entry.runtime?.session,state=entry.worker?.snapshot?.state,durableSessionId=session?.sessionId??state?.sessionId??entry.durableSessionId,sessionPath=session?.sessionFile??state?.sessionFile??entry.sessionPath,name=session?.sessionManager.getSessionName()??state?.sessionName;return{state:entry.state,kind:entry.kind,cwd:entry.cwd,attachments:entry.attachments,...durableSessionId!==void 0?{durableSessionId}:{},...sessionPath!==void 0?{sessionPath}:{},...name!==void 0?{name}:{},context:publishedSessionContext(entry.context,entry.contextOverlay),openContext:entry.context}}function registryStatusSource(registry){return{sessionIds:()=>registry.list().map(row=>row.sessionId),entryView:sessionId=>{let entry=registry.peek(sessionId);return entry===void 0?void 0:entryView(entry)},view:sessionId=>{let entry=registry.peek(sessionId);if(entry===void 0)return;let runtime=runtimeView(entry);return runtime===void 0?{entry:entryView(entry)}:{entry:entryView(entry),runtime}}}}function refusal2(id,command,code,detail){return{id,type:"response",command,success:!1,error:`${code}: ${detail.reason}`,errorCode:code,errorData:{reason:detail.reason,action:detail.action}}}function answerSubscribeSessions(command,connectionId,stream){if(connectionId===void 0)return{answer:refusal2(command.id,command.type,RPC_ERROR_UNSUPPORTED_TRANSPORT,{reason:"stdio has no per-connection identity to deliver a subscription to",action:"connect to the host socket (senpi --mode rpc --listen) and subscribe there"})};if(stream.connectionSize(connectionId)>=MAX_SUBSCRIPTIONS_PER_CONNECTION)return{answer:refusal2(command.id,command.type,RPC_ERROR_SUBSCRIPTION_LIMIT,{reason:`this connection already holds ${MAX_SUBSCRIPTIONS_PER_CONNECTION} subscriptions`,action:"unsubscribe_sessions the ones you no longer read, then subscribe again"})};let parsed=parseSubscription(command);if("refusal"in parsed)return{answer:refusal2(command.id,command.type,RPC_ERROR_INVALID_SUBSCRIPTION,parsed.refusal)};let subscribed=stream.subscribe(connectionId,parsed.options);return{answer:{id:command.id,type:"response",command:"subscribe_sessions",success:!0,data:{subscriptionId:subscribed.subscriptionId,snapshot:subscribed.snapshot,seq:subscribed.seq,hostGeneration:String(hostGeneration(process.env)),hostInstanceId:hostInstanceId()}},activate:subscribed.subscriptionId}}function answerUnsubscribeSessions(command,connectionId,stream){return connectionId===void 0?refusal2(command.id,command.type,RPC_ERROR_UNSUPPORTED_TRANSPORT,{reason:"stdio has no per-connection identity holding any subscription",action:"connect to the host socket (senpi --mode rpc --listen) and manage subscriptions there"}):typeof command.subscriptionId=="string"&&stream.unsubscribe(connectionId,command.subscriptionId)?{id:command.id,type:"response",command:"unsubscribe_sessions",success:!0}:refusal2(command.id,command.type,RPC_ERROR_UNKNOWN_SUBSCRIPTION,{reason:"this connection holds no subscription with that id",action:"send the subscriptionId your subscribe_sessions answer returned, on the same connection"})}function notAttachedRefusal(command){return refusal2(command.id,command.type,RPC_ERROR_SESSION_NOT_ATTACHED,{reason:"this connection is not attached to that session",action:"attach first with open_session { sessionPath }, then patch its context"})}function answerSetSessionContext(command,entry,stream){let applied=applyContextPatch(entry.contextOverlay,command.patch);return"refusal"in applied?refusal2(command.id,command.type,RPC_ERROR_INVALID_SESSION_CONTEXT,applied.refusal):(entry.contextOverlay=applied.overlay,stream.publish(command.sessionId,"context","client",!0),{id:command.id,type:"response",command:"set_session_context",success:!0,data:{context:publishedSessionContext(entry.context,entry.contextOverlay)}})}export{applyContextPatch,publishedSessionContext,recordLoopBlockedMs,sessionRuntimeView,registryStatusSource,refusal2 as refusal,answerSubscribeSessions,answerUnsubscribeSessions,notAttachedRefusal,answerSetSessionContext,SessionEventWriter,socketSink};
@@ -0,0 +1,2 @@
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{usageLimitResetMs}from"./chunk-XMJKZK5H.js";import{rateLimitModelFamily}from"./chunk-6VWIMHMH.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{rememberResolvedReferenceValue}from"./chunk-DLAY7CIU.js";import{normalizeProviderError}from"./chunk-TAV6QZFM.js";import{extract429RetryAfterMs}from"./chunk-PELNNWGO.js";import{getShellConfig}from"./chunk-BWA4FVFW.js";import{Compile,getOverflowPatterns}from"./chunk-E6WYH3ZL.js";import{ConfigReferenceError,PROVIDER_NOT_CONFIGURED_PREFIX,USAGE_LIMIT_EXHAUSTION,isOAuthRefreshUnavailableError,listSlots}from"./chunk-6AOVUTUR.js";import{typebox_exports}from"./chunk-MIENF2YK.js";function rendezvousOrder(key,slots,hasher){return[...slots].map(slot=>({slot,score:hasher(`${key}\0${slot.name}`)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({slot})=>slot)}function applyAccountOrder(order,ranked){if(order===void 0||order.length===0)return[...ranked];let byName=new Map(ranked.map(slot=>[slot.name,slot])),front=[];for(let name of order){let slot=byName.get(name);slot!==void 0&&!front.includes(slot)&&front.push(slot)}return[...front,...ranked.filter(slot=>!front.includes(slot))]}function withoutOrderedAccount(credential,name){if(credential.order===void 0||!credential.order.includes(name))return credential;let order=credential.order.filter(entry=>entry!==name),next={...credential};return order.length===0?delete next.order:next.order=order,next}var PRE_COMMIT_EVENT_TYPES=new Set(["start","text_start","thinking_start","toolcall_start"]);function isCommittedRotationOutput(event){return!PRE_COMMIT_EVENT_TYPES.has(event.type)}function isRotationStreamStart(event){return event.type==="start"}function rotationErrorFromEvent(event){if(event.type!=="error")return;let failure=new Error(event.error.errorMessage??"provider stream error"),status=event.error.providerDiagnostic?.httpStatus;return status===void 0?failure:Object.assign(failure,{status})}var DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ACCOUNT_USAGE_LIMIT_TEXT=new RegExp([...USAGE_LIMIT_EXHAUSTION.markers.map(escapeRegExp),String.raw`\b(?:hit|reached)\s+your\b[^.]*?\blimit\b`,String.raw`\busage\s+limit\s+reached\b`,String.raw`\b(?:Go|Free)UsageLimitError\b`,String.raw`\bblocking_limit\b`,String.raw`\brapid_refill_breaker\b`,String.raw`\bquota\s+exceeded\b`].join("|"),"i");function isAccountUsageLimitText(text){return ACCOUNT_USAGE_LIMIT_TEXT.test(text)}var COOLDOWN_BASE_MS=DEFAULT_SLOT_BLOCK_MS,COOLDOWN_CAP_MS=MAX_SLOT_BLOCK_MS,RETRY_SAME_MAX_ATTEMPTS=2,ACCOUNT_POOL_REFUSAL_NOTE="No request was sent: the account pool refused it locally.";function rateLimitCooldown(failureCount,serverHintMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS,base=policy.baseMs??COOLDOWN_BASE_MS,backoff=Math.min(cap,base*2**Math.max(0,failureCount)),floored=serverHintMs===void 0?backoff:Math.max(backoff,serverHintMs);return{cooldownMs:Math.min(cap,floored),retryAfterWasCapped:floored>cap}}function usageLimitCooldown(resetMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS;return{cooldownMs:Math.min(cap,resetMs),retryAfterWasCapped:resetMs>cap}}var INVALID_KEY_TEXT=/invalid[ _-]?(?:api[ _-]?)?key|authentication[_ ]?error|invalid x-api-key|unauthorized/i,ACCOUNT_SCOPED_403_TEXT=/account|credential|token|api[ _-]?key|organization|subscription/i,RATE_LIMIT_TEXT=/rate[ _-]?limit|too many requests|resource_exhausted/i,BILLING_TEXT=/billing|credits?[ _-]?(?:required|exhausted|balance)|insufficient[ _-]?(?:funds|quota|credit)|payment[ _-]?required|quota[ _-]?exhausted/i,OVERLOAD_TEXT=/overloaded/i,NETWORK_TEXT=/econnreset|econnrefused|etimedout|enotfound|socket hang up|fetch failed|network error|request timed out/i,WEBSOCKET_REQUEST_FAULT_TEXT=/websocket closed 100[89]\b/i,WEBSOCKET_TRANSPORT_FAULT_TEXT=/websocket (?:closed|error|connect timeout|liveness timeout)/i,FAIL_FAST_TEXT=/context[ _-]?(?:length|window)|maximum context|invalid[ _-]?model|model[ _-]?not[ _-]?found|malformed[ _-]?stream|premature[ _-]?(?:close|stream)/i,ABORT_TEXT=/\baborted?\b/i,TEMPORARY_FAULT_TEXT=/time[ds]?[ _-]?out|timed out|disconnect|reset before|connection reset|gateway|temporarily|unavailable/i;function isAbort(error,message){return error instanceof Error&&error.name==="AbortError"?!0:ABORT_TEXT.test(message)}function isOverflowText(text){return getOverflowPatterns().some(pattern=>pattern.test(text))}function classifyCredentialFailure(error,context={}){if(isOAuthRefreshUnavailableError(error))return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};let normalized=normalizeProviderError(error),text=normalized.messageCarriesBody?normalized.message:`${normalized.message} ${normalized.body??""}`,status=normalized.status,failureCount=context.failureCount??0;if(isAbort(error,text))return{kind:"fail_request"};if(text.includes(ACCOUNT_POOL_REFUSAL_NOTE))return{kind:"fail_request"};let providerFault=status===408||status!==void 0&&status>=500&&status<600||status===void 0&&(TEMPORARY_FAULT_TEXT.test(text)||NETWORK_TEXT.test(text)||OVERLOAD_TEXT.test(text)),usageLimit=isAccountUsageLimitText(text)&&!isOverflowText(text),limitText=RATE_LIMIT_TEXT.test(text)||usageLimit;if(text.includes(PROVIDER_NOT_CONFIGURED_PREFIX))return{kind:"failover",block:{reason:"auth_error"}};if(status===401||!providerFault&&status!==429&&INVALID_KEY_TEXT.test(text))return{kind:"failover",block:{reason:"auth_error"}};if(status===403&&!limitText)return ACCOUNT_SCOPED_403_TEXT.test(text)?{kind:"failover",block:{reason:"auth_error"}}:{kind:"fail_request"};if(status===402||!providerFault&&BILLING_TEXT.test(text))return{kind:"failover",block:{reason:"account_disabled"}};if(status===429||limitText){let nowMs=context.nowMs??Date.now(),hint=extract429RetryAfterMs({status:status??429,bodyText:text},nowMs)??(usageLimit?normalized.retryAfterMs??usageLimitResetMs(text,nowMs):void 0),modelFamily=rateLimitModelFamily(text),policy={baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs};return{kind:"failover",block:{reason:"rate_limit",...usageLimit&&hint!==void 0&&hint>0?usageLimitCooldown(hint,policy):rateLimitCooldown(failureCount,hint,policy),...modelFamily===void 0?{}:{modelFamily}}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_REQUEST_FAULT_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_TRANSPORT_FAULT_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===529||OVERLOAD_TEXT.test(text)||status!==void 0&&status>=500&&status<600?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===408||NETWORK_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"}}var CredentialFailoverError=class extends Error{constructor(action,original,options={}){let detail=original instanceof Error?original.message:String(original);super(detail,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.retryAt=options.retryAt}};function isAvailable(slot,now){return!(slot.blockReason==="account_disabled"||slot.blockedUntil!==void 0&&slot.blockedUntil>now)}function coolingProbe(slots,attempted){if(attempted.size>0)return[];let soonest=slots.filter(slot=>slot.blockReason==="rate_limit"&&slot.blockedUntil!==void 0).reduce((best,slot)=>best===void 0||(slot.blockedUntil??0)<(best.blockedUntil??0)?slot:best,void 0);return soonest===void 0?[]:[soonest]}function noSlotsMessage(slots,now){let blocked=slots.map(slot=>{let reason=slot.blockReason??"blocked";return slot.blockedUntil!==void 0&&slot.blockedUntil>now?`${slot.name} (${reason} until ${new Date(slot.blockedUntil).toISOString()})`:reason==="account_disabled"?`${slot.name} (account_disabled until re-login)`:`${slot.name} (${reason})`});return blocked.length===0?"No credential slots available":`No credential slots available: ${blocked.join(", ")}`}function soonestRetryAt(slots,now){let deadlines=slots.map(slot=>slot.blockedUntil).filter(value=>value!==void 0&&value>now);return deadlines.length===0?void 0:Math.min(...deadlines)}async function settle(stream){let iterator=stream[Symbol.asyncIterator]();try{await iterator.return?.(void 0)}catch{}}async function*runCredentialFailover(options){let now=options.now??Date.now,classify=options.classify??classifyCredentialFailure,attempted=new Set,retriesBySlot=new Map,lastError,lastOriginal,lastTerminalEvent,startAnnounced=!1;for(;;){let slots=await options.listSlots(),available=slots.filter(slot2=>!attempted.has(slot2.name)&&isAvailable(slot2,now())),candidates=available.length>0?available:coolingProbe(slots,attempted);if(candidates.length===0){if(lastTerminalEvent!==void 0){yield lastTerminalEvent;return}let retryAt=soonestRetryAt(slots,now());throw lastError!==void 0&&lastOriginal!==void 0?new CredentialFailoverError(lastError.action,lastOriginal,retryAt===void 0?{}:{retryAt}):new CredentialFailoverError({kind:"fail_request"},new Error(noSlotsMessage(slots,now())),retryAt===void 0?{}:{retryAt})}let slot=options.select(candidates),committedOutput=!1,terminalEvent,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw terminalEvent=event,failure;if(options.isStreamStart?.(event)){if(startAnnounced)continue;startAnnounced=!0}committedOutput||=options.isCommittedOutput(event),yield event}await options.onSuccess?.(slot);return}catch(error){attemptStream&&await settle(attemptStream);let failureCount=(slot.failureCount??0)+(retriesBySlot.get(slot.name)??0),action=classify(error,{failureCount});if(lastOriginal=error,lastTerminalEvent=terminalEvent,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts)continue;if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}if(action.kind!=="failover"){if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}await options.persistBlock(slot,action.block),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error);if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput){if(terminalEvent!==void 0){yield terminalEvent;return}throw failure}}}}function slotKind(slot){return slot.access!==void 0||slot.refresh!==void 0?"oauth":slot.key!==void 0?"api_key":void 0}function unusedSlotKinds(credential){if(!credential||!Array.isArray(credential.accounts))return[];let kinds=new Set;for(let slot of listSlots(credential)){let kind=slotKind(slot);kind!==void 0&&kind!==credential.type&&kinds.add(kind)}return[...kinds]}function slotsOfOwnKind(credential){return listSlots(credential).filter(slot=>slotKind(slot)!==otherKind(credential.type))}var otherKind=kind=>kind==="oauth"?"api_key":"oauth";var FileReferenceSchema=typebox_exports.Object({$file:typebox_exports.String({minLength:1})},{additionalProperties:!1}),EnvReferenceSchema=typebox_exports.Object({$env:typebox_exports.String({pattern:"^[A-Za-z_][A-Za-z0-9_]*$"})},{additionalProperties:!1}),ConcatReferenceSchema=typebox_exports.Object({$concat:typebox_exports.Array(typebox_exports.Union([typebox_exports.String(),FileReferenceSchema,EnvReferenceSchema]))},{additionalProperties:!1}),ConfigReferenceSchema=typebox_exports.Union([FileReferenceSchema,EnvReferenceSchema,ConcatReferenceSchema]),ConfigValueSchema=typebox_exports.Union([typebox_exports.String(),ConfigReferenceSchema]),NonemptyConfigValueSchema=typebox_exports.Union([typebox_exports.String({minLength:1}),ConfigReferenceSchema]),validateReference=Compile(ConfigReferenceSchema);function isConfigReference(value){return validateReference.Check(value)}function assertConfigValue(value,field){if(typeof value!="string"&&!isConfigReference(value))throw new ConfigReferenceError(field,value,"malformed")}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Aborted"))})})}var warnedVariables=new Set;function warnOpaqueConfigEnvironment(name,value){value!==void 0&&/\{(?:file|env):/.test(value)&&!warnedVariables.has(name)&&(warnedVariables.add(name),console.warn(`${name}: environment value contains reference-looking text; inserted literally`))}function warnMissingConfigEnvironment(name){warnedVariables.has(name)||(warnedVariables.add(name),console.warn(`${name}: configuration environment variable is unset`))}import{dirname as dirname2}from"node:path";import{constants}from"node:fs";import{lstat,open,readlink}from"node:fs/promises";import{homedir}from"node:os";import{dirname,isAbsolute,join,parse,sep}from"node:path";var MAX_BYTES=65536,readableWarnings=new Set;function fail(input,reason){throw new ConfigReferenceError(input.field,input.reference,reason)}function checkOwner(input,stat){process.platform!=="win32"&&stat.uid!==0&&stat.uid!==process.getuid?.()&&fail(input,"unsafe-owner")}function checkWritable(input,stat,ancestor){process.platform==="win32"||stat.isSymbolicLink()||(stat.mode&18)===0||ancestor&&stat.isDirectory()&&(stat.mode&512)!==0||fail(input,"unsafe-permissions")}function sameFile(left,right){return left.dev===right.dev&&left.ino===right.ino}function absolutePath(input){let declared=input.reference.$file;return declared.startsWith("~/")||process.platform==="win32"&&declared.startsWith("~\\")?`${homedir()}${sep}${declared.slice(2)}`:isAbsolute(declared)?declared:`${input.baseDir}${sep}${declared}`}async function walk(input){let absolute=absolutePath(input),current=parse(absolute).root,pending=absolute.slice(current.length).split(sep).filter(Boolean),stat=await lstat(current),links=0;checkOwner(input,stat),checkWritable(input,stat,!0);for(let part=pending.shift();part!==void 0;part=pending.shift()){if(part===".")continue;stat.isDirectory()||fail(input,"non-regular");let next=part===".."?dirname(current):join(current,part),nextStat=await lstat(next);if(checkOwner(input,nextStat),process.platform!=="win32"&&(stat.mode&18)!==0&&!nextStat.isSymbolicLink()&&(nextStat.mode&18)!==0&&fail(input,"unsafe-permissions"),checkWritable(input,nextStat,pending.length>0),nextStat.isSymbolicLink()){++links>40&&fail(input,"unreadable");let target=await readlink(next);sameFile(nextStat,await lstat(next))||fail(input,"changed");let targetPath=isAbsolute(target)?target:`${current}${sep}${target}`;current=parse(targetPath).root,pending=[...targetPath.slice(current.length).split(sep).filter(Boolean),...pending],stat=await lstat(current),checkOwner(input,stat),checkWritable(input,stat,!0)}else current=next,stat=nextStat}return stat.isFile()||fail(input,"non-regular"),{path:current,stat}}async function readConfigReferenceFile(input){try{let walked=await walk(input),flags=constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0),handle=await open(walked.path,flags);try{let stat=await handle.stat();sameFile(walked.stat,stat)||fail(input,"changed"),stat.isFile()||fail(input,"non-regular"),checkOwner(input,stat),checkWritable(input,stat,!1),stat.size>MAX_BYTES&&fail(input,"oversize");let buffer=Buffer.alloc(MAX_BYTES+1),length=0;for(;length<buffer.length;){let{bytesRead}=await handle.read(buffer,length,buffer.length-length,length);if(bytesRead===0)break;length+=bytesRead}length>MAX_BYTES&&fail(input,"oversize");let value;try{value=new TextDecoder("utf-8",{fatal:!0}).decode(buffer.subarray(0,length)).trim()}catch{fail(input,"invalid-utf8")}return value.length===0&&fail(input,"empty"),process.platform!=="win32"&&(stat.mode&36)!==0&&!readableWarnings.has(walked.path)&&(readableWarnings.add(walked.path),console.warn(`${input.field}: reference file is readable by other users`)),value}finally{await handle.close()}}catch(error){if(error instanceof ConfigReferenceError)throw error;let code=Reflect.get(Object(error),"code");fail(input,code==="ENOENT"||code==="ENOTDIR"?"missing":"unreadable")}}var origins=new WeakMap;function rememberConfigReferenceOrigin(value,context){typeof value!="string"&&origins.set(value,context)}function configReferenceContext(value,context){return context??(typeof value=="string"?void 0:origins.get(value))}function assertConfigReferenceAuthority(value,context){if(typeof value=="string")return;let source=configReferenceContext(value,context);if(source?.authority!=="trusted")throw new ConfigReferenceError(source?.field??"configuration value",value,"forbidden");assertConfigValue(value,source.field)}async function resolveConfigReference(value,context,env){let source=configReferenceContext(value,context);if(assertConfigReferenceAuthority(value,source),source===void 0)throw new ConfigReferenceError("configuration value",value,"forbidden");if("$file"in value){let text=await readConfigReferenceFile({field:source.field,reference:value,baseDir:source.baseDir??dirname2(source.origin)});return rememberResolvedReferenceValue(text),text}if("$env"in value){let result2=(env??source.env??process.env)[value.$env];if(warnOpaqueConfigEnvironment(value.$env,result2),result2===void 0)throw new ConfigReferenceError(source.field,value,"unset");if(result2==="")throw new ConfigReferenceError(source.field,value,"empty");return rememberResolvedReferenceValue(result2),result2}let parts=[];for(let part of value.$concat)parts.push(typeof part=="string"?part:await resolveConfigReference(part,source,env));let result=parts.join("");if(result==="")throw new ConfigReferenceError(source.field,value,"empty");return rememberResolvedReferenceValue(result),result}import{spawn}from"child_process";var COMMAND_EXECUTION_MAX_ATTEMPTS=3,COMMAND_EXECUTION_BACKOFF_MS=[250,1e3],COMMAND_TIMEOUT_MS=1e4,COMMAND_MAX_OUTPUT_BYTES=1024*1024;function runCommandProcess(file,args,options){return new Promise(resolveOutcome=>{let spawnOptions={shell:options.shell,windowsHide:!0,...options.env===void 0?{}:{env:{...process.env,...options.env}}},child=options.stdin===void 0?spawn(file,[...args],{...spawnOptions,stdio:["ignore","pipe","ignore"]}):spawn(file,[...args],{...spawnOptions,stdio:["pipe","pipe","ignore"]}),stdout="",settled=!1,finish=outcome=>{settled||(settled=!0,clearTimeout(timer),resolveOutcome(outcome))},timer=setTimeout(()=>{signalSpawnedChild(child,"SIGTERM"),child.unref(),finish({executed:!0,value:void 0})},COMMAND_TIMEOUT_MS);child.stdout.setEncoding("utf-8"),child.stdout.on("data",chunk=>{stdout+=chunk,!(stdout.length<=COMMAND_MAX_OUTPUT_BYTES)&&(signalSpawnedChild(child,"SIGTERM"),finish({executed:!0,value:void 0}))}),child.on("error",error=>finish({executed:error.code!=="ENOENT",value:void 0})),child.on("close",code=>{let value=stdout.trim();finish({executed:!0,value:code===0&&value?value:void 0})}),child.stdin?.end(options.stdin)})}async function executeWithConfiguredShell(command,env){try{let{shell,args,commandTransport}=getShellConfig(),commandFromStdin=commandTransport==="stdin";return await runCommandProcess(shell,commandFromStdin?args:[...args,command],{shell:!1,...commandFromStdin?{stdin:command}:{},...env===void 0?{}:{env}})}catch{return{executed:!1,value:void 0}}}async function executeCommandOnce(command,env){if(process.platform==="win32"){let configured=await executeWithConfiguredShell(command,env);if(configured.executed)return configured.value}return(await runCommandProcess(command,[],{shell:!0,...env===void 0?{}:{env}})).value}async function runConfigCommand(commandConfig,env){let command=commandConfig.slice(1);for(let attempt=0;attempt<COMMAND_EXECUTION_MAX_ATTEMPTS;attempt++){let value=await executeCommandOnce(command,env);if(value!==void 0)return value;let backoffMs=COMMAND_EXECUTION_BACKOFF_MS[attempt];backoffMs!==void 0&&await sleep(backoffMs)}}var commandResultCache=new Map,ENV_VAR_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/,ENV_VAR_NAME_PREFIX_RE=/^[A-Za-z_][A-Za-z0-9_]*/;function appendLiteral(parts,value){if(!value)return;let previousPart=parts[parts.length-1];if(previousPart?.type==="literal"){previousPart.value+=value;return}parts.push({type:"literal",value})}function parseConfigValueTemplate(config){let parts=[],index=0;for(;index<config.length;){let dollarIndex=config.indexOf("$",index);if(dollarIndex<0){appendLiteral(parts,config.slice(index));break}appendLiteral(parts,config.slice(index,dollarIndex));let nextChar=config[dollarIndex+1];if(nextChar==="$"||nextChar==="!"){appendLiteral(parts,nextChar),index=dollarIndex+2;continue}if(nextChar==="{"){let endIndex=config.indexOf("}",dollarIndex+2);if(endIndex<0){appendLiteral(parts,"$"),index=dollarIndex+1;continue}let name=config.slice(dollarIndex+2,endIndex);ENV_VAR_NAME_RE.test(name)?parts.push({type:"env",name}):appendLiteral(parts,config.slice(dollarIndex,endIndex+1)),index=endIndex+1;continue}let match=config.slice(dollarIndex+1).match(ENV_VAR_NAME_PREFIX_RE);if(match){parts.push({type:"env",name:match[0]}),index=dollarIndex+1+match[0].length;continue}appendLiteral(parts,"$"),index=dollarIndex+1}return parts}function parseConfigValueReference(config){return config.startsWith("!")?{type:"command",config}:{type:"template",parts:parseConfigValueTemplate(config)}}function resolveEnvConfigValue(name,env){let value=env?.[name]||process.env[name]||void 0;return warnOpaqueConfigEnvironment(name,value),value}function getTemplateEnvVarNames(parts){let names=[];for(let part of parts)part.type!=="env"||names.includes(part.name)||names.push(part.name);return names}function resolveTemplate(parts,env){let resolved="";for(let part of parts){if(part.type==="literal"){resolved+=part.value;continue}let envValue=resolveEnvConfigValue(part.name,env);if(envValue===void 0){warnMissingConfigEnvironment(part.name);return}resolved+=envValue}return resolved}function getConfigValueEnvVarNames(config){if(typeof config!="string")return"$env"in config?[config.$env]:"$concat"in config?[...new Set(config.$concat.flatMap(part=>typeof part!="string"&&"$env"in part?[part.$env]:[]))]:[];let reference=parseConfigValueReference(config);return reference.type==="template"?getTemplateEnvVarNames(reference.parts):[]}function getMissingConfigValueEnvVarNames(config,env){return getConfigValueEnvVarNames(config).filter(name=>resolveEnvConfigValue(name,env)===void 0)}function isCommandConfigValue(config){return typeof config=="string"&&parseConfigValueReference(config).type==="command"}function isConfigValueConfigured(config,env){return typeof config!="string"||getMissingConfigValueEnvVarNames(config,env).length===0}function resolveConfigValue(config,env,context){if(typeof config!="string")return resolveConfigReference(config,context,env);let reference=parseConfigValueReference(config);return reference.type==="command"?env===void 0?executeCommand(reference.config):runConfigCommand(reference.config,env):Promise.resolve(resolveTemplate(reference.parts,env))}function executeCommand(commandConfig){let cached=commandResultCache.get(commandConfig);if(cached)return cached;let result=runConfigCommand(commandConfig);return commandResultCache.set(commandConfig,result),result}function resolveConfigValueUncached(config,env,context){if(typeof config!="string")return resolveConfigReference(config,context,env);let reference=parseConfigValueReference(config);return reference.type==="command"?runConfigCommand(reference.config,env):Promise.resolve(resolveTemplate(reference.parts,env))}async function resolveConfigValueOrThrow(config,description,env,context){if(typeof config!="string")return resolveConfigReference(config,context,env);let resolvedValue=await resolveConfigValueUncached(config,env,context);if(resolvedValue!==void 0)return resolvedValue;let reference=parseConfigValueReference(config);if(reference.type==="command")throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);if(reference.type==="template"){let missingEnvVars=getMissingConfigValueEnvVarNames(config,env);if(missingEnvVars.length===1)throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);if(missingEnvVars.length>1)throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`)}throw new Error(`Failed to resolve ${description}`)}async function resolveHeadersOrThrow(headers,description,env){if(!headers)return;for(let value of Object.values(headers))assertConfigReferenceAuthority(value);let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=await resolveConfigValueOrThrow(value,`${description} header "${key}"`,env);return Object.keys(resolved).length>0?resolved:void 0}export{slotKind,unusedSlotKinds,slotsOfOwnKind,rendezvousOrder,applyAccountOrder,withoutOrderedAccount,ConfigValueSchema,NonemptyConfigValueSchema,isConfigReference,warnOpaqueConfigEnvironment,warnMissingConfigEnvironment,rememberConfigReferenceOrigin,assertConfigReferenceAuthority,resolveConfigReference,sleep,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,isCommittedRotationOutput,isRotationStreamStart,rotationErrorFromEvent,MAX_SLOT_BLOCK_MS,ACCOUNT_POOL_REFUSAL_NOTE,classifyCredentialFailure,CredentialFailoverError,runCredentialFailover};
@@ -1,3 +1,3 @@
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{ORIGIN_HOST_INSTANCE_FIELD,RPC_AUTH_HEX,RPC_LAUNCH_ID,RpcEndpointAuthError,authRecord,originHostInstance,readRpcKeyRecord,rpcAuthProof,rpcProofMatches}from"./chunk-O3Q2ET6W.js";import{attachJsonlLineReader,serializeJsonLine}from"./chunk-YI7SPFDN.js";import{SOCKET_HANDSHAKE_TIMEOUT_MS}from"./chunk-ZGAB7WQA.js";import{getAgentDir}from"./chunk-7YO7VQZW.js";import{createHash}from"node:crypto";import{basename}from"node:path";var TUI_SOCKET_NAME=/^t-[0-9a-f]{16}\.sock$/;function tuiSocketName(instanceId){return`t-${createHash("sha256").update(instanceId,"utf8").digest("hex").slice(0,16)}.sock`}function isTuiControlSocket(socket){return TUI_SOCKET_NAME.test(basename(socket))}function socketNeedsHandshake(socket,platform=process.platform){return platform==="win32"||isTuiControlSocket(socket)}import{AsyncLocalStorage}from"node:async_hooks";import{randomBytes}from"node:crypto";import{createConnection}from"node:net";var keyRoots=new AsyncLocalStorage;function withRpcKeyRoot(root,operation){return keyRoots.run(root,operation)}function rpcKeyRoot(options={},defaultRoot){return options.keyRoot??keyRoots.getStore()??process.env.SENPI_RPC_KEY_ROOT??defaultRoot??getAgentDir()}async function connectAuthenticatedRpcSocket(path,first={type:"get_protocol_info",id:"rpc-auth-protocol",observe:!0,[ORIGIN_HOST_INSTANCE_FIELD]:originHostInstance()},options={},timeoutMs=SOCKET_HANDSHAKE_TIMEOUT_MS){let deadline=Date.now()+timeoutMs;for(let attempt=0;;attempt++){let socket=createConnection(path),earlyError,ignoreLateError=error=>{earlyError??=error};socket.on("error",ignoreLateError);let connected=!1;socket.once("connect",()=>{connected=!0});try{let protocol=await authenticate(socket,path,first,rpcKeyRoot(options),Math.max(1,deadline-Date.now()));return socket.off("error",ignoreLateError),{socket,protocol}}catch(cause){if(socket.destroy(),attempt===0&&cause instanceof RpcEndpointAuthError&&cause.code==="auth_failed")continue;let failure=!(cause instanceof RpcEndpointAuthError)&&earlyError!==void 0?earlyError:cause;throw failure instanceof Error&&Object.assign(failure,{rpcSocketConnected:connected}),failure}}}async function authenticate(socket,path,first,root,timeoutMs){let pending,reject=error=>pending?.reject(error),socketError,onClose=()=>setImmediate(()=>reject(socketError??new Error(`RPC socket closed during authentication: ${path}`))),onError=error=>{socketError??=error,reject(error)};socket.on("error",onError),socket.on("close",onClose);let detach=attachJsonlLineReader(socket,line=>{let response;try{response=authRecord(JSON.parse(line))}catch{return}if(!(response===void 0||pending===void 0||response.id!==pending.id))if(response.success===!0)pending?.resolve(response);else{let code=response.errorCode;reject(code==="auth_failed"||code==="auth_required"?new RpcEndpointAuthError(code,`${path}; set SENPI_RPC_KEY_ROOT to the host's agent dir (${root})`):new Error(`RPC authentication probe refused on ${path}: ${String(response.error)}`))}},{maxLineLength:1024*1024,onOversizedLine:()=>socket.destroy()}),exchange=request=>new Promise((resolve,reject2)=>{if(socket.destroyed){setImmediate(()=>reject2(socketError??new Error(`RPC socket closed during authentication: ${path}`)));return}pending={id:request.id,resolve,reject:reject2},socket.write(serializeJsonLine(request))}),timer=setTimeout(()=>{reject(new Error(`RPC authentication timed out on ${path}`)),socket.destroy()},timeoutMs);try{let nonce=randomBytes(32).toString("hex"),response=await exchange({...first,auth:{client_nonce:nonce}}),data=authRecord(response.data);if(data?.auth===void 0)return response;let auth=authRecord(data.auth);if(typeof auth?.launch_id!="string"||!RPC_LAUNCH_ID.test(auth.launch_id)||typeof auth.server_nonce!="string"||!RPC_AUTH_HEX.test(auth.server_nonce))throw new RpcEndpointAuthError("host_identity_unproven",path);let record=await readRpcKeyRecord(root,auth.launch_id);if(socket.destroyed)throw new Error(`RPC authentication timed out on ${path}`);if(record===void 0)return process.stderr.write(`senpi rpc client: no key record for launch ${auth.launch_id} under ${root}; continuing unauthenticated (refused from the next release; set SENPI_RPC_KEY_ROOT to the host's agent dir)
2
+ import{ORIGIN_HOST_INSTANCE_FIELD,RPC_AUTH_HEX,RPC_LAUNCH_ID,RpcEndpointAuthError,authRecord,originHostInstance,readRpcKeyRecord,rpcAuthProof,rpcProofMatches}from"./chunk-SBGIXMX3.js";import{attachJsonlLineReader,serializeJsonLine}from"./chunk-YI7SPFDN.js";import{SOCKET_HANDSHAKE_TIMEOUT_MS}from"./chunk-ZGAB7WQA.js";import{getAgentDir}from"./chunk-7YO7VQZW.js";import{createHash}from"node:crypto";import{basename}from"node:path";var TUI_SOCKET_NAME=/^t-[0-9a-f]{16}\.sock$/;function tuiSocketName(instanceId){return`t-${createHash("sha256").update(instanceId,"utf8").digest("hex").slice(0,16)}.sock`}function isTuiControlSocket(socket){return TUI_SOCKET_NAME.test(basename(socket))}function socketNeedsHandshake(socket,platform=process.platform){return platform==="win32"||isTuiControlSocket(socket)}import{AsyncLocalStorage}from"node:async_hooks";import{randomBytes}from"node:crypto";import{createConnection}from"node:net";var keyRoots=new AsyncLocalStorage;function withRpcKeyRoot(root,operation){return keyRoots.run(root,operation)}function rpcKeyRoot(options={},defaultRoot){return options.keyRoot??keyRoots.getStore()??process.env.SENPI_RPC_KEY_ROOT??defaultRoot??getAgentDir()}async function connectAuthenticatedRpcSocket(path,first={type:"get_protocol_info",id:"rpc-auth-protocol",observe:!0,[ORIGIN_HOST_INSTANCE_FIELD]:originHostInstance()},options={},timeoutMs=SOCKET_HANDSHAKE_TIMEOUT_MS){let deadline=Date.now()+timeoutMs;for(let attempt=0;;attempt++){let socket=createConnection(path),earlyError,ignoreLateError=error=>{earlyError??=error};socket.on("error",ignoreLateError);let connected=!1;socket.once("connect",()=>{connected=!0});try{let protocol=await authenticate(socket,path,first,rpcKeyRoot(options),Math.max(1,deadline-Date.now()));return socket.off("error",ignoreLateError),{socket,protocol}}catch(cause){if(socket.destroy(),attempt===0&&cause instanceof RpcEndpointAuthError&&cause.code==="auth_failed")continue;let failure=!(cause instanceof RpcEndpointAuthError)&&earlyError!==void 0?earlyError:cause;throw failure instanceof Error&&Object.assign(failure,{rpcSocketConnected:connected}),failure}}}async function authenticate(socket,path,first,root,timeoutMs){let pending,reject=error=>pending?.reject(error),socketError,onClose=()=>setImmediate(()=>reject(socketError??new Error(`RPC socket closed during authentication: ${path}`))),onError=error=>{socketError??=error,reject(error)};socket.on("error",onError),socket.on("close",onClose);let detach=attachJsonlLineReader(socket,line=>{let response;try{response=authRecord(JSON.parse(line))}catch{return}if(!(response===void 0||pending===void 0||response.id!==pending.id))if(response.success===!0)pending?.resolve(response);else{let code=response.errorCode;reject(code==="auth_failed"||code==="auth_required"?new RpcEndpointAuthError(code,`${path}; set SENPI_RPC_KEY_ROOT to the host's agent dir (${root})`):new Error(`RPC authentication probe refused on ${path}: ${String(response.error)}`))}},{maxLineLength:1024*1024,onOversizedLine:()=>socket.destroy()}),exchange=request=>new Promise((resolve,reject2)=>{if(socket.destroyed){setImmediate(()=>reject2(socketError??new Error(`RPC socket closed during authentication: ${path}`)));return}pending={id:request.id,resolve,reject:reject2},socket.write(serializeJsonLine(request))}),timer=setTimeout(()=>{reject(new Error(`RPC authentication timed out on ${path}`)),socket.destroy()},timeoutMs);try{let nonce=randomBytes(32).toString("hex"),response=await exchange({...first,auth:{client_nonce:nonce}}),data=authRecord(response.data);if(data?.auth===void 0)return response;let auth=authRecord(data.auth);if(typeof auth?.launch_id!="string"||!RPC_LAUNCH_ID.test(auth.launch_id)||typeof auth.server_nonce!="string"||!RPC_AUTH_HEX.test(auth.server_nonce))throw new RpcEndpointAuthError("host_identity_unproven",path);let record=await readRpcKeyRecord(root,auth.launch_id);if(socket.destroyed)throw new Error(`RPC authentication timed out on ${path}`);if(record===void 0)return process.stderr.write(`senpi rpc client: no key record for launch ${auth.launch_id} under ${root}; continuing unauthenticated (refused from the next release; set SENPI_RPC_KEY_ROOT to the host's agent dir)
3
3
  `),response;if(typeof record.key!="string")throw new RpcEndpointAuthError("unsafe_key_record",root);let key=Buffer.from(record.key,"hex");if(!rpcProofMatches(rpcAuthProof(key,"server",auth.launch_id,nonce,auth.server_nonce),auth.server_proof))throw new RpcEndpointAuthError("host_identity_unproven",path);return await exchange({id:"rpc-authenticate",type:"authenticate",client_proof:rpcAuthProof(key,"client",auth.launch_id,auth.server_nonce,nonce)}),response}finally{clearTimeout(timer),detach(),socket.off("error",onError),socket.off("close",onClose)}}export{tuiSocketName,isTuiControlSocket,socketNeedsHandshake,withRpcKeyRoot,rpcKeyRoot,connectAuthenticatedRpcSocket};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{connectAuthenticatedRpcSocket,socketNeedsHandshake}from"./chunk-Z3UYNSVR.js";import{RpcEndpointAuthError}from"./chunk-O3Q2ET6W.js";import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{createConnection}from"node:net";var PROBE_REQUEST_ID="ensure-host-probe";async function requestOnSocket(socketPath,command,timeoutMs,options={}){return(await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,...command},timeoutMs,!1,options)).answer}async function connectAndAsk(socketPath,request,timeoutMs,keep=!1,options={}){let secret;if(socketNeedsHandshake(socketPath))try{secret=await readSocketSecret(socketSecretPath(socketPath))}catch{return{connected:!1,answer:void 0}}let authenticated,deadline=Date.now()+timeoutMs;if(!socketNeedsHandshake(socketPath)){try{authenticated=await connectAuthenticatedRpcSocket(socketPath,request.type==="get_protocol_info"?request:void 0,options,timeoutMs)}catch(cause){if(cause instanceof RpcEndpointAuthError)throw cause;return{connected:cause instanceof Error&&"rpcSocketConnected"in cause&&cause.rpcSocketConnected===!0,answer:void 0}}if(request.type==="get_protocol_info"){let answer=authenticated.protocol.data??{};return keep?{connected:!0,answer,kept:authenticated.socket}:(authenticated.socket.destroy(),{connected:!0,answer})}}return new Promise((resolveProbe,rejectProbe)=>{let socket=authenticated?.socket??createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret)),buffer="",settled=!1,connected=authenticated!==void 0,finish=value=>{if(!settled){if(settled=!0,clearTimeout(timeout),socket.removeAllListeners("data"),keep&&value!==void 0&&!socket.destroyed){resolveProbe({connected,answer:value,kept:socket});return}socket.destroy(),resolveProbe({connected,answer:value})}},timeout=setTimeout(()=>finish(),Math.max(0,deadline-Date.now())),send=()=>{connected=!0,socket.write(`${JSON.stringify(request)}
2
+ import{connectAuthenticatedRpcSocket,socketNeedsHandshake}from"./chunk-KKD4CYCI.js";import{RpcEndpointAuthError}from"./chunk-SBGIXMX3.js";import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{createConnection}from"node:net";var PROBE_REQUEST_ID="ensure-host-probe";async function requestOnSocket(socketPath,command,timeoutMs,options={}){return(await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,...command},timeoutMs,!1,options)).answer}async function connectAndAsk(socketPath,request,timeoutMs,keep=!1,options={}){let secret;if(socketNeedsHandshake(socketPath))try{secret=await readSocketSecret(socketSecretPath(socketPath))}catch{return{connected:!1,answer:void 0}}let authenticated,deadline=Date.now()+timeoutMs;if(!socketNeedsHandshake(socketPath)){try{authenticated=await connectAuthenticatedRpcSocket(socketPath,request.type==="get_protocol_info"?request:void 0,options,timeoutMs)}catch(cause){if(cause instanceof RpcEndpointAuthError)throw cause;return{connected:cause instanceof Error&&"rpcSocketConnected"in cause&&cause.rpcSocketConnected===!0,answer:void 0}}if(request.type==="get_protocol_info"){let answer=authenticated.protocol.data??{};return keep?{connected:!0,answer,kept:authenticated.socket}:(authenticated.socket.destroy(),{connected:!0,answer})}}return new Promise((resolveProbe,rejectProbe)=>{let socket=authenticated?.socket??createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret)),buffer="",settled=!1,connected=authenticated!==void 0,finish=value=>{if(!settled){if(settled=!0,clearTimeout(timeout),socket.removeAllListeners("data"),keep&&value!==void 0&&!socket.destroyed){resolveProbe({connected,answer:value,kept:socket});return}socket.destroy(),resolveProbe({connected,answer:value})}},timeout=setTimeout(()=>finish(),Math.max(0,deadline-Date.now())),send=()=>{connected=!0,socket.write(`${JSON.stringify(request)}
3
3
  `)};socket.on("data",chunk=>{for(buffer+=chunk.toString("utf8");;){let newline=buffer.indexOf(`
4
4
  `);if(newline===-1)return;let line=buffer.slice(0,newline);buffer=buffer.slice(newline+1);let value;try{value=JSON.parse(line)}catch{continue}if(isRecord(value)&&value.id===request.id&&(value.errorCode==="auth_required"||value.errorCode==="auth_failed")){clearTimeout(timeout),settled=!0,socket.destroy(),rejectProbe(new RpcEndpointAuthError(value.errorCode,`${socketPath}; set SENPI_RPC_KEY_ROOT to the host's agent dir`));return}let answer=readAnswer(line,typeof request.id=="string"?request.id:PROBE_REQUEST_ID);if(answer!==void 0)return finish(answer)}}),socket.once("error",()=>finish()),socket.once("close",()=>finish()),secret&&sendSocketHandshake(socket,secret),authenticated?send():socket.once("connect",send)})}function readAnswer(text,id=PROBE_REQUEST_ID){let parsed;try{parsed=JSON.parse(text)}catch{return}if(!(!isRecord(parsed)||parsed.id!==id||parsed.success!==!0))return parsed.data??{}}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}export{PROBE_REQUEST_ID,requestOnSocket,connectAndAsk,readAnswer,isRecord};
@@ -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{CHILD_KILL_EXIT_TIMEOUT_MS,CHILD_STALLED_STOP_MAX_MS_ENV,CHILD_STOP_TIMEOUT_MS,DEFAULT_HANDOFF_GRACE_MS,HANDOFF_GRACE_MS_ENV,IdleExitDecider,STOP_STALL_EVIDENCE_MAX_AGE_MS,acquireOwnershipSafeLock,childStalledStopMaxMs,clearStopProgress,consumeStopIntent,errorMessage,hostLoopStalled,layeredSupervisorIntent,parseIdleExitMs,readStopIntent,recentStall,releaseGeneration,resolveHostPolicy,supervisorLog,watchDrainRequest,writeDrainRequest,writeDrainWatch,writeHostReady,writeStderrLine,writeStopIntent,writeStopProgress}from"./chunk-SWJXRC2I.js";import{HOST_DAEMON_DIR_ENV,createHostDaemonPaths,generationPaths,hostOwnerGone,readHostOwner,sameHostOwner,writeJsonAtomic}from"./chunk-4WZRVZNX.js";import{require_signal_exit}from"./chunk-U3VOXCGP.js";import{HOST_INSTANCE_ID_ENV,OBSERVE_REQUEST_FIELD,RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RpcPublicEndpoint,authRecord,isObservingRequest,requestOriginHostInstance,rpcAuthProof,rpcProofMatches}from"./chunk-O3Q2ET6W.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-YI7SPFDN.js";import{MAX_SOCKET_PATH_BYTES,PUBLIC_SOCKET_IDENTITY_FILE,adoptPublicSocket,classifyEndpointOwnership,shieldSocketDuringClose,socketEntryListenerState,statSocketIdentity,unlinkOwnedSocket,writeSocketIdentityFile}from"./chunk-VRDU425E.js";import{SOCKET_HANDSHAKE_TIMEOUT_MS,SOCKET_SECRET_FILE_ENV,authenticateSocket,createSocketSecret,ensureSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{DISPLAY_VERSION,VERSION,brandEnvNames,envValue,getAgentDir,isBunBinary,isBundledNode}from"./chunk-7YO7VQZW.js";import{processIsLive,processStartTimeMs,readProcessIdentity,readProcessStartTime,sameProcessStartMs,waitForStartTime}from"./chunk-O5RYI3IW.js";import{__toESM}from"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{join as join6}from"node:path";var HostAdmission=class{constructor(info){this.stopped=!1,this.listeners=new Set,this.replies=Promise.resolve(),this.info=info}get stopping(){return this.stopped}protocol(){return{...this.info,lifecycle:this.stopped?"stopping":"ready"}}observe(info){this.info=info}stop(){this.stopped||(this.stopped=!0,this.replies=Promise.all([...this.listeners].map(listener=>listener())).then(()=>{}))}async flush(){let timer;try{await Promise.race([this.replies,new Promise(resolve2=>{timer=setTimeout(resolve2,2e3)})])}finally{clearTimeout(timer)}}onStop(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}};function hostStoppingResponse(id,command,admission){return{...typeof id=="string"?{id}:{},type:"response",command,success:!1,error:"host_stopping",errorCode:"host_stopping",errorData:{instanceId:admission.protocol().instanceId}}}var import_signal_exit=__toESM(require_signal_exit(),1);import{appendFileSync,mkdirSync,readdirSync,readFileSync,renameSync,rmSync,statSync,utimesSync,writeFileSync}from"node:fs";import{join}from"node:path";var PROCESS_CRASH_RECORD_LIMIT=50,PROCESS_MARKER_HEARTBEAT_MS=6e4,FILE_MODE=384,DIR_MODE=448,MARKER_SUFFIX=".json";function processCrashPaths(agentDir){let dir=join(agentDir,"process-crashes");return{dir,liveDir:join(dir,"live"),recordsFile:join(dir,"crashes.jsonl")}}function crashingRuntimeVersions(){return{...process.versions.bun===void 0?{}:{bunVersion:process.versions.bun},senpiVersion:VERSION,...DISPLAY_VERSION===VERSION?{}:{productVersion:DISPLAY_VERSION}}}function recordProcessLifetime(agentDir,kind,options){return sweepDeadProcessMarkers(agentDir,options),options.supervised?()=>{}:installProcessLifetimeMarker(agentDir,kind,options)}function installProcessLifetimeMarker(agentDir,kind,options={}){let pid=options.pid??process.pid,now=options.now??Date.now,file=join(processCrashPaths(agentDir).liveDir,`${pid}${MARKER_SUFFIX}`),marker={kind,pid,startedAt:now(),...crashingRuntimeVersions()};try{mkdirSync(processCrashPaths(agentDir).liveDir,{recursive:!0,mode:DIR_MODE}),writeFileSync(file,`${JSON.stringify(marker)}
2
+ import{CHILD_KILL_EXIT_TIMEOUT_MS,CHILD_STALLED_STOP_MAX_MS_ENV,CHILD_STOP_TIMEOUT_MS,DEFAULT_HANDOFF_GRACE_MS,HANDOFF_GRACE_MS_ENV,IdleExitDecider,STOP_STALL_EVIDENCE_MAX_AGE_MS,acquireOwnershipSafeLock,childStalledStopMaxMs,clearStopProgress,consumeStopIntent,errorMessage,hostLoopStalled,layeredSupervisorIntent,parseIdleExitMs,readStopIntent,recentStall,releaseGeneration,resolveHostPolicy,supervisorLog,watchDrainRequest,writeDrainRequest,writeDrainWatch,writeHostReady,writeStderrLine,writeStopIntent,writeStopProgress}from"./chunk-BZ7726QO.js";import{HOST_DAEMON_DIR_ENV,createHostDaemonPaths,generationPaths,hostOwnerGone,readHostOwner,sameHostOwner,writeJsonAtomic}from"./chunk-4WZRVZNX.js";import{require_signal_exit}from"./chunk-U3VOXCGP.js";import{HOST_INSTANCE_ID_ENV,OBSERVE_REQUEST_FIELD,RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RpcPublicEndpoint,authRecord,isObservingRequest,requestOriginHostInstance,rpcAuthProof,rpcProofMatches}from"./chunk-SBGIXMX3.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-YI7SPFDN.js";import{MAX_SOCKET_PATH_BYTES,PUBLIC_SOCKET_IDENTITY_FILE,adoptPublicSocket,classifyEndpointOwnership,shieldSocketDuringClose,socketEntryListenerState,statSocketIdentity,unlinkOwnedSocket,writeSocketIdentityFile}from"./chunk-VRDU425E.js";import{SOCKET_HANDSHAKE_TIMEOUT_MS,SOCKET_SECRET_FILE_ENV,authenticateSocket,createSocketSecret,ensureSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{DISPLAY_VERSION,VERSION,brandEnvNames,envValue,getAgentDir,isBunBinary,isBundledNode}from"./chunk-7YO7VQZW.js";import{processIsLive,processStartTimeMs,readProcessIdentity,readProcessStartTime,sameProcessStartMs,waitForStartTime}from"./chunk-O5RYI3IW.js";import{__toESM}from"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{join as join6}from"node:path";var HostAdmission=class{constructor(info){this.stopped=!1,this.listeners=new Set,this.replies=Promise.resolve(),this.info=info}get stopping(){return this.stopped}protocol(){return{...this.info,lifecycle:this.stopped?"stopping":"ready"}}observe(info){this.info=info}stop(){this.stopped||(this.stopped=!0,this.replies=Promise.all([...this.listeners].map(listener=>listener())).then(()=>{}))}async flush(){let timer;try{await Promise.race([this.replies,new Promise(resolve2=>{timer=setTimeout(resolve2,2e3)})])}finally{clearTimeout(timer)}}onStop(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}};function hostStoppingResponse(id,command,admission){return{...typeof id=="string"?{id}:{},type:"response",command,success:!1,error:"host_stopping",errorCode:"host_stopping",errorData:{instanceId:admission.protocol().instanceId}}}var import_signal_exit=__toESM(require_signal_exit(),1);import{appendFileSync,mkdirSync,readdirSync,readFileSync,renameSync,rmSync,statSync,utimesSync,writeFileSync}from"node:fs";import{join}from"node:path";var PROCESS_CRASH_RECORD_LIMIT=50,PROCESS_MARKER_HEARTBEAT_MS=6e4,FILE_MODE=384,DIR_MODE=448,MARKER_SUFFIX=".json";function processCrashPaths(agentDir){let dir=join(agentDir,"process-crashes");return{dir,liveDir:join(dir,"live"),recordsFile:join(dir,"crashes.jsonl")}}function crashingRuntimeVersions(){return{...process.versions.bun===void 0?{}:{bunVersion:process.versions.bun},senpiVersion:VERSION,...DISPLAY_VERSION===VERSION?{}:{productVersion:DISPLAY_VERSION}}}function recordProcessLifetime(agentDir,kind,options){return sweepDeadProcessMarkers(agentDir,options),options.supervised?()=>{}:installProcessLifetimeMarker(agentDir,kind,options)}function installProcessLifetimeMarker(agentDir,kind,options={}){let pid=options.pid??process.pid,now=options.now??Date.now,file=join(processCrashPaths(agentDir).liveDir,`${pid}${MARKER_SUFFIX}`),marker={kind,pid,startedAt:now(),...crashingRuntimeVersions()};try{mkdirSync(processCrashPaths(agentDir).liveDir,{recursive:!0,mode:DIR_MODE}),writeFileSync(file,`${JSON.stringify(marker)}
3
3
  `,{mode:FILE_MODE})}catch{return()=>{}}let heartbeat=setInterval(()=>{try{let at=new Date(now());utimesSync(file,at,at)}catch{}},options.heartbeatMs??PROCESS_MARKER_HEARTBEAT_MS);heartbeat.unref();let disposed=!1,dispose=()=>{disposed||(disposed=!0,clearInterval(heartbeat),process.off("exit",onProcessExit),removeSignalHook(),rmSync(file,{force:!0}))},onProcessExit=()=>{try{dispose()}catch{}};process.on("exit",onProcessExit);let removeSignalHook=(0,import_signal_exit.default)(onProcessExit);return dispose}function sweepDeadProcessMarkers(agentDir,options={}){let paths=processCrashPaths(agentDir),selfPid=options.pid??process.pid,isAlive=options.isAlive??isProcessAlive,names;try{names=readdirSync(paths.liveDir)}catch{return 0}let recorded=0;for(let name of names){if(!name.endsWith(MARKER_SUFFIX))continue;let pid=Number(name.slice(0,-MARKER_SUFFIX.length));if(!Number.isSafeInteger(pid)||pid<=0||pid===selfPid||isAlive(pid))continue;let claimed=join(paths.liveDir,`${name}.${selfPid}.sweep`);try{renameSync(join(paths.liveDir,name),claimed)}catch{continue}try{let record2=crashRecordFromMarker(readFileSync(claimed,"utf8"),statSync(claimed).mtimeMs);record2!==void 0&&(appendProcessCrashRecord(paths,record2),recorded+=1)}catch{}finally{rmSync(claimed,{force:!0})}}return recorded}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function crashRecordFromMarker(raw,lastHeartbeatMs){let value=JSON.parse(raw);if(typeof value!="object"||value===null)return;let kind=Reflect.get(value,"kind"),startedAt=Reflect.get(value,"startedAt"),senpiVersion=Reflect.get(value,"senpiVersion"),bunVersion=Reflect.get(value,"bunVersion"),productVersion=Reflect.get(value,"productVersion");if(!(typeof kind!="string"||typeof startedAt!="number"||typeof senpiVersion!="string"))return{at:new Date(lastHeartbeatMs).toISOString(),kind,detection:"unclean_exit",uptimeMs:Math.max(0,Math.round(lastHeartbeatMs-startedAt)),...typeof bunVersion=="string"?{bunVersion}:{},senpiVersion,...typeof productVersion=="string"?{productVersion}:{}}}function appendProcessCrashRecord(paths,record2){mkdirSync(paths.dir,{recursive:!0,mode:DIR_MODE}),appendFileSync(paths.recordsFile,`${JSON.stringify(record2)}
4
4
  `,{mode:FILE_MODE});let records=readProcessCrashRecordsFrom(paths.recordsFile);if(records.length<=PROCESS_CRASH_RECORD_LIMIT)return;let kept=records.slice(records.length-PROCESS_CRASH_RECORD_LIMIT);writeFileSync(paths.recordsFile,`${kept.join(`
5
5
  `)}
@@ -10,7 +10,7 @@ import{CHILD_KILL_EXIT_TIMEOUT_MS,CHILD_STALLED_STOP_MAX_MS_ENV,CHILD_STOP_TIMEO
10
10
  `)}
11
11
  `,{mode:CRASH_RECORD_FILE_MODE})}function classifyChildExit(code,signal){return code===0&&signal===null?{reason:"rpc host exited on its own idle policy",exitCode:0}:{reason:`rpc host process exited unexpectedly (${code??signal})`,exitCode:1}}async function noteChildExit(context){let now=context.now??Date.now(),intent=await consumeStopIntent(context.generation,now).catch(()=>{}),outcome=describeExit(context,intent);if(outcome===void 0)return;let stall=await recentStall(context.generation,now,STOP_STALL_EVIDENCE_MAX_AGE_MS).catch(()=>{});await recordTerminalHostRecord(context.daemonDir,{at:new Date(now).toISOString(),...context.signal===null?{code:context.code??void 0}:{signal:context.signal},uptimeMs:Math.max(0,now-context.childStartedAt),kind:"rpc-host",generation:context.instanceId,...outcome,...stall?{stall:{driftMs:stall.driftMs,at:stall.at,attributedSessionId:stall.sessionId}}:{},...crashingRuntimeVersions()}).catch(()=>{})}function describeExit(context,intent){return intent!==void 0?{detection:"engine_stop",sender:intent.sender,...intent.chain?{chain:intent.chain}:{},reason:intent.reason,stopIntent:!0}:context.shutdown!==void 0?{detection:"engine_stop",sender:context.shutdown.supervisor,reason:context.shutdown.reason,stopIntent:!1}:classifyChildExit(context.code,context.signal).exitCode===0?void 0:{detection:context.signal===null||SELF_INFLICTED_SIGNALS.has(context.signal)?"supervisor":"external",stopIntent:!1}}var SELF_INFLICTED_SIGNALS=new Set(["SIGSEGV","SIGBUS","SIGABRT","SIGILL","SIGFPE","SIGTRAP","SIGSYS"]);async function noteEscalatedStop(daemonDir,instanceId,intent,now=Date.now()){await recordTerminalHostRecord(daemonDir,{at:new Date(now).toISOString(),signal:"SIGKILL",kind:"rpc-host",generation:instanceId,detection:"engine_stop",sender:intent.sender,...intent.chain?{chain:intent.chain}:{},reason:`${intent.reason}; supervisor_escalated`,stopIntent:!0}).catch(()=>{})}function hostCrashCleanupPaths(targets){let publicEntry=targets.platform==="win32"?[targets.publicSocket]:[];return targets.successor?publicEntry:[targets.generationPidFile,targets.settingsFile,...publicEntry,targets.pointerFile]}import{existsSync,readFileSync as readFileSync3,realpathSync}from"node:fs";import{access,readFile}from"node:fs/promises";import{dirname,resolve}from"node:path";import{fileURLToPath}from"node:url";function isCliModuleEntry(moduleUrl){let entry=process.argv[1];if(!entry)return!1;try{return fileURLToPath(moduleUrl)===realpathSync(entry)}catch{return!1}}function resolveCliMainPath(modulePath=fileURLToPath(import.meta.url),bundled=isBundledNode){let declared=bundled?resolveDeclaredCliEntry(modulePath):void 0;if(declared!==void 0)return declared;let extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve(dirname(modulePath),"..","..",`cli-main${extension}`);return existsSync(unbundled)?unbundled:resolveDeclaredCliEntry(modulePath)??unbundled}function resolveDeclaredCliEntry(modulePath){let dir=dirname(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve(dir,"package.json");if(existsSync(manifestPath)){try{let declared=JSON.parse(readFileSync3(manifestPath,"utf8")).bin,candidates=typeof declared=="string"?[declared]:Object.values(declared??{});for(let candidate of candidates){let entry=resolve(dir,candidate);if(existsSync(entry))return entry}}catch{}return}let parent=dirname(dir);if(parent===dir)return;dir=parent}}var existsAsync=path=>access(path).then(()=>!0,()=>!1);async function resolveCliMainPathAsync(modulePath=fileURLToPath(import.meta.url),bundled=isBundledNode){let declared=bundled?await resolveDeclaredCliEntryAsync(modulePath):void 0;if(declared!==void 0)return declared;let extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve(dirname(modulePath),"..","..",`cli-main${extension}`);return await existsAsync(unbundled)?unbundled:await resolveDeclaredCliEntryAsync(modulePath)??unbundled}async function resolveDeclaredCliEntryAsync(modulePath){let dir=dirname(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve(dir,"package.json");if(await existsAsync(manifestPath)){try{let declaredBin=JSON.parse(await readFile(manifestPath,"utf8")).bin,candidates=typeof declaredBin=="string"?[declaredBin]:Object.values(declaredBin??{});for(let candidate of candidates){let entry=resolve(dir,candidate);if(await existsAsync(entry))return entry}}catch{}return}let parent=dirname(dir);if(parent===dir)return;dir=parent}}import{watch}from"node:fs";import{createConnection,Socket}from"node:net";var MAX_CLASSIFIED_LINE_BYTES=64*1024,NEWLINE=10,ClientOccupancy=class{constructor(onAttach,ownInstance){this.clients=new Set,this.observers=new Set,this.attached=new Set,this.dependents=new Set,this.closed=!1,this.onAttach=onAttach,this.ownInstance=ownInstance}get attachedCount(){return this.attached.size}get unclassifiedCount(){return this.clients.size-this.observers.size-this.attached.size-this.dependents.size}admit(client){if(this.closed)return client.destroy(),!1;this.clients.add(client);let pending=Buffer.alloc(0),attach=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.attached.add(client),this.onAttach()},depend=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.dependents.add(client)},classify=chunk=>{pending=Buffer.concat([pending,chunk]);for(let newline=pending.indexOf(NEWLINE);newline!==-1;newline=pending.indexOf(NEWLINE)){let line=pending.subarray(0,newline).toString("utf8");if(pending=pending.subarray(newline+1),!isObservingRequest(line)){this.ownInstance!==void 0&&requestOriginHostInstance(line)===this.ownInstance?depend():attach();return}this.observers.add(client)}pending.length>MAX_CLASSIFIED_LINE_BYTES&&attach()};return client.on("data",classify),!0}release(client){let unclassified=this.clients.has(client)&&!this.observers.has(client)&&!this.attached.has(client)&&!this.dependents.has(client);return this.clients.delete(client),this.observers.delete(client),this.attached.delete(client),this.dependents.delete(client),unclassified}destroyAll(){this.closed=!0;for(let client of this.clients)client.destroy()}};var SessionRunActivity=class{#running=new Set;observe(line){let event=parseHostEvent(line);if(event===void 0)return!1;if(event.type==="agent_start")this.#running.add(event.sessionId);else if(event.type==="agent_settled"||event.type==="session_closed")this.#running.delete(event.sessionId);else return!1;return!0}get busySessions(){return this.#running.size}};function parseHostEvent(line){let event;try{event=JSON.parse(line)}catch{return}if(typeof event!="object"||event===null)return;let{type,sessionId}=event;return typeof sessionId=="string"?{type,sessionId}:void 0}import{randomBytes}from"node:crypto";import{hkdfSync}from"node:crypto";import{Duplex}from"node:stream";import{createCipheriv,createDecipheriv}from"node:crypto";var INTERNAL_RECORD_MAX=64*1024,RECORD_LIMIT=1n<<32n,InternalRecordCipher=class{constructor(key,direction,counter=0n){this.key=key,this.direction=direction,this.counter=counter}parameters(){if(this.counter<0n||this.counter>=RECORD_LIMIT)throw new Error("internal_record_counter_exhausted");let count=Buffer.alloc(8);return count.writeBigUInt64BE(this.counter),{nonce:Buffer.concat([Buffer.alloc(4),count]),aad:Buffer.concat([Buffer.from(this.direction),count])}}seal(plaintext){if(plaintext.length<1||plaintext.length>INTERNAL_RECORD_MAX)throw new Error("internal_record_length");let{nonce:nonce2,aad}=this.parameters(),cipher=createCipheriv("aes-256-gcm",this.key,nonce2);cipher.setAAD(aad);let body=Buffer.concat([cipher.update(plaintext),cipher.final(),cipher.getAuthTag()]),length=Buffer.alloc(4);return length.writeUInt32BE(body.length),this.counter++,Buffer.concat([length,body])}open(body){if(body.length<17||body.length>INTERNAL_RECORD_MAX+16)throw new Error("internal_record_length");let{nonce:nonce2,aad}=this.parameters(),decipher=createDecipheriv("aes-256-gcm",this.key,nonce2);decipher.setAAD(aad),decipher.setAuthTag(body.subarray(-16));let plaintext=decipher.update(body.subarray(0,-16)),final=decipher.final();return this.counter++,Buffer.concat([plaintext,final])}};function createInternalRecordStream(wire,key,clientNonce,serverNonce,role){let salt=Buffer.concat([clientNonce,serverNonce]),cipher=direction=>new InternalRecordCipher(Buffer.from(hkdfSync("sha256",key,salt,`senpi-rpc-internal ${direction}`,32)),direction);return new InternalRecordStream(wire,cipher(role==="client"?"c2s":"s2c"),cipher(role==="client"?"s2c":"c2s"))}var InternalRecordStream=class extends Duplex{constructor(wire,sender,receiver){super(),this.header=Buffer.alloc(4),this.headerUsed=0,this.bodyUsed=0,this.offset=0,this.wireDone=!1,this.wireClosed=!1,this.ended=!1,this.wire=wire,this.sender=sender,this.receiver=receiver,this.once("error",error=>{error.message.startsWith("internal_record")&&process.stderr.write(`senpi rpc: internal hop closed: ${error.message}
12
12
  `)}),this.on("error",()=>{}),wire.on("data",chunk=>{wire.pause(),this.pending=chunk,this.offset=0,this.consume()}),wire.once("end",()=>{this.wireDone=!0,this.pending===void 0&&this.finish()}),wire.once("error",error=>this.destroy(error)),wire.once("close",()=>{this.wireDone=!0,this.wireClosed=!0,this.ended&&this.readableEnded?this.destroy():this.pending===void 0&&this.finish()}),this.once("end",()=>{this.wireClosed&&this.destroy()})}finish(){this.ended||(this.ended=!0,this.headerUsed!==0||this.body!==void 0?this.destroy(new Error("internal_record_truncated")):this.push(null))}consume(){try{let chunk=this.pending;if(!chunk)return;for(;this.offset<chunk.length;){if(!this.body){let n2=Math.min(4-this.headerUsed,chunk.length-this.offset);if(chunk.copy(this.header,this.headerUsed,this.offset,this.offset+n2),this.headerUsed+=n2,this.offset+=n2,this.headerUsed!==4)break;let length=this.header.readUInt32BE();if(length<17||length>INTERNAL_RECORD_MAX+16)throw new Error("internal_record_length");this.headerUsed=0,this.body=Buffer.alloc(length)}let n=Math.min(this.body.length-this.bodyUsed,chunk.length-this.offset);if(chunk.copy(this.body,this.bodyUsed,this.offset,this.offset+n),this.bodyUsed+=n,this.offset+=n,this.bodyUsed===this.body.length){let plaintext=this.receiver.open(this.body);if(this.body=void 0,this.bodyUsed=0,!this.push(plaintext)){this.offset===chunk.length&&(this.pending=void 0,this.wireDone&&this.finish());return}}}this.pending=void 0,this.wireDone?this.finish():this.wire.resume()}catch(cause){this.destroy(cause instanceof Error&&cause.message.startsWith("internal_record")?cause:new Error("internal_record_unverified",{cause}))}}_read(){this.pending?this.consume():this.wire.resume()}_write(chunk,_encoding,callback){let offset=0,next=error=>{if(error){callback(error);return}if(this.destroyed){callback(new Error("internal_hop_lost"));return}if(offset===chunk.length){callback();return}try{let end=Math.min(chunk.length,offset+INTERNAL_RECORD_MAX),record2=this.sender.seal(chunk.subarray(offset,end));offset=end,this.wire.write(record2,next)}catch(cause){callback(cause instanceof Error?cause:new Error("internal_record_invalid"))}};next()}_final(callback){this.wire.end(callback)}_destroy(error,callback){this.wire.destroy(),callback(error)}};var INTERNAL_LAUNCH_ID="internal";function proof(key,label,first,second){return rpcAuthProof(key,label,INTERNAL_LAUNCH_ID,first,second)}function matches(actual,expected){return rpcProofMatches(expected,actual)}function object(value){if(!isObject(value))throw new Error("auth_failed");return value}function isObject(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function nonce(value){if(typeof value!="string"||!RPC_AUTH_HEX.test(value))throw new Error("auth_failed");return value}var HOST_PRE_AUTH_BUDGET={maxBytes:8192,timeoutMs:2e3};async function handshake(socket,budget,run){let readBytes=0,ended=!1,rejectPending,fail=error=>{ended=!0,rejectPending?.(error),socket.destroy()},timer=budget.timeoutMs===void 0?void 0:setTimeout(()=>fail(new Error("internal_auth_timeout")),budget.timeoutMs);timer?.unref();let onError=error=>fail(error),onClose=()=>fail(new Error("internal_hop_lost"));socket.on("error",onError),socket.once("close",onClose);let read=()=>new Promise((resolve2,reject)=>{if(ended)return reject(new Error("internal_hop_lost"));let buffer=Buffer.alloc(0);rejectPending=cause=>{socket.off("data",data),reject(cause)};let data=chunk=>{let newline=chunk.indexOf(10),used=newline===-1?chunk.length:newline+1;if(readBytes+=used,readBytes>budget.maxBytes)return fail(new Error("internal_auth_oversized"));if(buffer=Buffer.concat([buffer,chunk.subarray(0,used)]),newline!==-1){socket.pause(),socket.off("data",data),rejectPending=void 0,used<chunk.length&&socket.unshift(chunk.subarray(used));try{resolve2(object(JSON.parse(buffer.toString("utf8"))))}catch{reject(new Error("auth_failed"))}}};socket.on("data",data),socket.resume()});try{return await run(read,frame=>new Promise((resolve2,reject)=>{socket.write(`${JSON.stringify(frame)}
13
- `,error=>error?reject(error):resolve2())}))}catch(cause){throw socket.destroy(),cause}finally{timer&&clearTimeout(timer),socket.off("error",onError),socket.off("close",onClose)}}function connectInternalConnection(socket,key,options={}){return handshake(socket,{maxBytes:MAX_RPC_LINE_CHARACTERS,timeoutMs:options.timeoutMs},async(read,send)=>{let clientNonce=randomBytes(32).toString("hex"),[response]=await Promise.all([read(),send({id:"internal-protocol",type:"get_protocol_info",observe:!0,auth:{client_nonce:clientNonce}})]),data=response.data;if(!isObject(data)||!isObject(data.auth))throw new Error("host_identity_unproven");let auth=data.auth,serverNonce=nonce(auth.server_nonce);if(response.id!=="internal-protocol"||response.success!==!0||auth.launch_id!==INTERNAL_LAUNCH_ID||!matches(auth.server_proof,proof(key,"server",clientNonce,serverNonce)))throw new Error("host_identity_unproven");let[result]=await Promise.all([read(),send({id:"internal-auth",type:"authenticate",client_proof:proof(key,"client",serverNonce,clientNonce)})]);if(result.id!=="internal-auth"||result.command!=="authenticate"||result.success!==!0)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"client")})}function acceptInternalConnection(socket,key,protocol={}){return handshake(socket,HOST_PRE_AUTH_BUDGET,async(read,send)=>{let refuse=async frame2=>{throw await send({id:frame2.id,type:"response",command:frame2.type,success:!1,error:"auth_required",errorCode:"auth_required"}),new Error("auth_required")},first=await read(),offered=isObject(first.auth)?first.auth.client_nonce:void 0;if(first.type!=="get_protocol_info"||typeof offered!="string"||!RPC_AUTH_HEX.test(offered))return refuse(first);let clientNonce=offered,serverNonce=randomBytes(32).toString("hex"),[frame]=await Promise.all([read(),send({id:first.id,type:"response",command:first.type,success:!0,data:{...protocol,capabilities:[...Array.isArray(protocol.capabilities)?protocol.capabilities:[],"socket_auth"],auth:{launch_id:INTERNAL_LAUNCH_ID,server_nonce:serverNonce,server_proof:proof(key,"server",clientNonce,serverNonce)}}})]);if(frame.type!=="authenticate")return refuse(frame);let valid=matches(frame.client_proof,proof(key,"client",serverNonce,clientNonce));if(await send({id:frame.id,type:"response",command:"authenticate",success:valid,...valid?{}:{error:"auth_failed",errorCode:"auth_failed"}}),!valid)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"server")})}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}var INTERNAL_OBSERVER_HANDSHAKE_MS=5e3,SupervisorActivity=class{constructor(options){this.runs=new SessionRunActivity,this.options=options,this.decider=new IdleExitDecider(options.idleExitMs),this.clients=new ClientOccupancy(()=>this.refresh(),options.instanceId),this.observerLink=createObserverLink({open:()=>this.connectObserver(),settled:options.settled,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}})}current(){return{connections:this.clients.attachedCount,activeTurns:activeTurnsForIdleDecision({healthy:this.observerLink.healthy(),unhealthySince:this.observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:this.decider.idleExitMs,observedBusy:this.runs.busySessions})}}refresh(){let current=this.current();return(current.connections>0||current.activeTurns>0||this.clients.unclassifiedCount>0)&&this.options.onActivity?.(),this.decider.update(current)}quiescent(){return this.observerLink.healthy()&&this.runs.busySessions===0&&this.clients.attachedCount===0&&this.clients.unclassifiedCount===0}openObserver(){return this.observerLink.open()}stopObserver(){this.observerLink.stop(),this.observerSocket?.destroy()}async connectObserver(){let secret=this.options.internalSecret,next=createConnection(resolveSocketTransportAddress(this.options.internalSocket,process.platform,secret));secret&&sendSocketHandshake(next,secret);let stream;try{this.options.internalKey?stream=await connectInternalConnection(next,this.options.internalKey,{timeoutMs:INTERNAL_OBSERVER_HANDSHAKE_MS}):(await waitForConnect(next,5e3),stream=next)}catch(cause){throw next.destroy(),cause}return this.observerSocket=stream,attachJsonlLineReader(stream,line=>this.observeHostEvent(line),{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{let lost=()=>{handler(),this.options.onActivity?.()};stream.once("close",lost),stream.once("error",lost)}}}observeHostEvent(line){this.runs.observe(line)&&this.refresh()}},OWNER_EXIT_GRACE_MS=2e3,OWNER_PROBE_MAX_INTERVAL_MS=5e3,SupervisorOwner=class{constructor(generationDir){this.watchFailed=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.gone=!1,this.revision=0,this.stopped=!1,this.idle=new IdleExitDecider(OWNER_EXIT_GRACE_MS,()=>performance.now()),this.generationDir=generationDir}async start(fd){if(await this.reload(),!(fd===void 0||this.owner==null))try{let pipe=new Socket({fd,readable:!0,writable:!1});this.pipe=pipe;let bound=this.owner,failed=!1,eof=()=>{!failed&&!this.stopped&&sameHostOwner(this.owner,bound)&&(this.gone=!0)};pipe.once("end",eof),process.platform==="win32"&&pipe.once("close",eof),pipe.once("error",()=>{failed=!0,this.pipe===pipe&&(this.pipe=void 0),pipe.destroy()}),pipe.resume()}catch{this.pipe=void 0}}async reload(){let revision=++this.revision,next=await readHostOwner(this.generationDir);if(!(this.stopped||revision!==this.revision)){if(sameHostOwner(this.owner,next)||(this.pipe?.destroy(),this.pipe=void 0,this.gone=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.activity()),this.owner=next,next==null)this.watcher?.close(),this.watcher=void 0;else if(!this.watcher&&!this.watchFailed)try{this.watcher=watch(this.generationDir,(_event,filename)=>{filename?.toString()==="owner.json"&&this.reload()}),this.watcher.once("error",()=>{this.watchFailed=!0,this.watcher?.close(),this.watcher=void 0})}catch{this.watchFailed=!0}}}activity(){this.idle.update({connections:1,activeTurns:0})}async shouldExit(activity){this.watcher||await this.reload();let owner=this.owner,revision=this.revision;if(owner!=null&&!this.pipe&&!this.gone&&performance.now()>=this.nextProbeAt){let gone=await hostOwnerGone(owner);if(this.stopped||revision!==this.revision)return!1;this.gone=gone,this.nextProbeAt=performance.now()+this.probeIntervalMs,this.probeIntervalMs=Math.min(OWNER_PROBE_MAX_INTERVAL_MS,this.probeIntervalMs*2)}let quiet=this.gone&&owner!=null&&activity.quiescent();if(this.idle.update({connections:quiet?0:1,activeTurns:0})!=="exit")return!1;let current=await readHostOwner(this.generationDir);return!this.stopped&&revision===this.revision&&sameHostOwner(owner,current)&&activity.quiescent()}stop(){this.stopped=!0,this.watcher?.close(),this.pipe?.destroy()}};function waitForConnect(socket,timeoutMs){return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve2()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}import{readFile as readFile2}from"node:fs/promises";var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3,REPLACED_CONFIRMATIONS=3,IDENTITY_PROBE_TIMEOUT_MS=2e3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0)return endpoint.pointer===void 0?()=>{}:watchPointerSupersession(endpoint,endpoint.pointer,onLost);let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function watchPointerSupersession(endpoint,pointer,onLost){let probe=endpoint.probeInstanceId??probeAnsweringInstance,readPointer=endpoint.readPointerInstanceId??pointerInstanceId,agreeingPolls=0,observing=!1,lost=!1,observe=async()=>{let named=await readPointer(pointer.file);return named===void 0||named===pointer.instanceId?!1:await probe(endpoint.path)===named},timer=setInterval(()=>{lost||observing||endpoint.settled?.()===!0||(observing=!0,observe().then(replaced=>{lost||endpoint.settled?.()===!0||(agreeingPolls=replaced?agreeingPolls+1:0,!(agreeingPolls<REPLACED_CONFIRMATIONS)&&(lost=!0,clearInterval(timer),onLost("replaced")))},()=>{agreeingPolls=0}).finally(()=>{observing=!1}))},SUPERSESSION_POLL_MS);return timer.unref?.(),()=>clearInterval(timer)}async function pointerInstanceId(file){try{let parsed=JSON.parse(await readFile2(file,"utf8")),instanceId=typeof parsed=="object"&&parsed!==null?Reflect.get(parsed,"instance_id"):void 0;return typeof instanceId=="string"&&instanceId!==""?instanceId:void 0}catch{return}}async function probeAnsweringInstance(path){let{isRecord:isRecord2,requestOnSocket}=await import("./host-socket-request-3CWE4265.js"),answer=await requestOnSocket(path,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},IDENTITY_PROBE_TIMEOUT_MS).catch(()=>{});return isRecord2(answer)&&typeof answer.instanceId=="string"?answer.instanceId:void 0}function ignore(){}var SupervisorDrain=class{constructor(child,shuttingDown,beginStopping=()=>{},relay){this.draining=!1,this.child=child,this.shuttingDown=shuttingDown,this.beginStopping=beginStopping,this.relay=relay}get active(){return this.draining}drain(){if(this.draining||this.shuttingDown())return;this.draining=!0,this.beginStopping(),supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??6e5;this.graceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),this.requestChildDrain()},graceMs),this.graceTimer.unref(),this.requestChildDrain()}stop(){this.graceTimer&&clearTimeout(this.graceTimer)}async acceptRequests(generation){let stop=watchDrainRequest(generation.drainRequestFile,request=>{supervisorLog(`drain requested (${request.reason})`),this.drain()});return await writeDrainWatch(generation.drainWatchFile,{pid:process.pid}).catch(cause=>{supervisorLog(`cannot advertise the drain request: ${errorMessage(cause)}`)}),stop}requestChildDrain(){let{child,relay}=this;if(!(child.pid===void 0||child.exitCode!==null||child.signalCode!==null)&&(relay&&writeDrainRequest(relay.file,{sender:relay.sender,reason:"supervisor_drain"}).catch(cause=>{supervisorLog(`could not relay the drain to the host: ${errorMessage(cause)}`)}),process.platform!=="win32"))try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage(cause)}`)}}};function drainOnPublicSocketLoss(path,identity,settled,drain,onReplaced,pointer){return watchForSupersession({path,identity,settled,...pointer&&{pointer}},loss=>{loss==="replaced"&&onReplaced(),supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drain.drain()})}async function watchWin32ChildIdentity(child,shuttingDown,onGone){let pid=child.pid;if(pid===void 0)return()=>{};let childStartTime=await readProcessStartTime(pid,process.platform,1e3).catch(()=>{}),missingIdentityChecks=0,checking=!1,timer=setInterval(()=>{shuttingDown()||checking||child.exitCode!==null||child.signalCode!==null||(checking=!0,readProcessStartTime(pid,process.platform,1e3).then(currentStartTime=>{currentStartTime===void 0&&!processIsLive(pid)?missingIdentityChecks++:currentStartTime!==void 0&&(missingIdentityChecks=0),(childStartTime!==void 0&&currentStartTime!==void 0&&currentStartTime!==childStartTime||missingIdentityChecks>=2)&&onGone()}).catch(()=>{}).finally(()=>{checking=!1}))},500);return timer.unref?.(),()=>clearInterval(timer)}import{randomBytes as randomBytes2}from"node:crypto";import{readFile as readFile4}from"node:fs/promises";import{join as join5}from"node:path";import{readFileSync as readFileSync4}from"node:fs";function readProcessStartTicks(pid,platform=process.platform){if(platform==="linux")try{let stat2=readFileSync4(`/proc/${pid}/stat`,"utf8"),ticks=stat2.slice(stat2.lastIndexOf(")")+2).split(" ")[19];return ticks!==void 0&&/^\d+$/.test(ticks)?ticks:void 0}catch{return}}async function compareRecordedStart(pid,recorded,platform,probe){if(platform==="linux"){if(recorded.ticks===void 0)return"unknown";let observed2=probe.ticks(pid);return observed2===void 0?"unknown":observed2===recorded.ticks?"same":"changed"}if(recorded.time===void 0)return"unknown";let observed=await probe.time(pid),recordedMs=processStartTimeMs(recorded.time),observedMs=observed===void 0?void 0:processStartTimeMs(observed);return recordedMs===void 0||observedMs===void 0?"unknown":sameProcessStartMs(recordedMs,observedMs)?"same":"changed"}import{randomUUID}from"node:crypto";import{realpathSync as realpathSync2}from"node:fs";import{mkdir,readFile as readFile3,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join3}from"node:path";var INTERNAL_HOST_DIR_PREFIX="senpi-rpc-host-internal-",SHORT_TEMP_ROOT="/tmp";function internalHostDirRoots(){let primary=tmpdir();return canonicalPath(primary)!==canonicalPath(SHORT_TEMP_ROOT)?[primary,SHORT_TEMP_ROOT]:[Buffer.byteLength(primary)<Buffer.byteLength(SHORT_TEMP_ROOT)?primary:SHORT_TEMP_ROOT]}function canonicalPath(path){try{return realpathSync2(path)}catch{return path}}function internalHostDirRoot(name){for(let root of internalHostDirRoots())if(Buffer.byteLength(join3(root,name,"host.sock"))<=MAX_SOCKET_PATH_BYTES)return root;let tried=internalHostDirRoots().map(root=>join3(root,name,"host.sock"));throw new Error(`internal_socket_path_too_long: every candidate exceeds ${MAX_SOCKET_PATH_BYTES} bytes (${tried.join(", ")}); set TMPDIR to a shorter directory`)}async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join3(baseDir,`internal-${randomUUID()}`);return await mkdir(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID()}`,dir:dir2,secretPath:join3(dir2,"secret")}}let name=`${INTERNAL_HOST_DIR_PREFIX}${randomUUID().slice(0,8)}`,dir=join3(internalHostDirRoot(name),name);return await mkdir(dir,{recursive:!1,mode:448}),await writeFile(join3(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join3(dir,"host.sock"),dir,secretPath:join3(dir,".secret")}}var CHILD_START_TIME_WAIT_MS=1e4,CHILD_START_TIME_UNHURRIED_MS=15e3;async function readChildStartTime(pid,timeoutMs){let identity=await readProcessIdentity(pid,process.platform,timeoutMs,void 0,"UTC");if(identity.kind==="error")throw identity.error;return identity.kind==="present"?identity.identity:void 0}async function recordChildPid(file,pid,running){try{await writeJsonAtomic(file,{pid,processStartTime:null});let processStartTime=await waitForStartTime(pid,CHILD_START_TIME_WAIT_MS,p=>readChildStartTime(p,1e3)).catch(()=>{})??await readChildStartTime(pid,CHILD_START_TIME_UNHURRIED_MS).catch(()=>{});if(processStartTime===void 0){supervisorLog(`host child pid ${pid} start time unreadable at recording`);return}if(!running())return;await writeJsonAtomic(file,{pid,processStartTime})}catch(cause){supervisorLog(`could not record the host child pid: ${errorMessage(cause)}`)}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile3(settingsFile,"utf8"))}catch{return}}import{execFileSync}from"node:child_process";import{closeSync as closeSync2,constants,fstatSync,openSync,rmSync as rmSync2}from"node:fs";import{join as join4}from"node:path";import{closeSync}from"node:fs";import{Socket as Socket2}from"node:net";function watchHostLifetime(fd,gone,unavailable){let stopped=!1,bun=Reflect.get(globalThis,"Bun");if(typeof bun=="object"&&bun!==null&&typeof Reflect.get(bun,"file")=="function"){let reader=Reflect.get(bun,"file")(fd).stream().getReader();return(async()=>{try{for(;!stopped;){let{done}=await reader.read();if(done){stopped||gone();return}}}catch{stopped||unavailable()}})(),()=>{stopped||(stopped=!0,reader.cancel().catch(()=>{}).finally(()=>closeSync(fd)))}}let socket=new Socket2({fd,readable:!0,writable:!1});return socket.once("end",()=>{stopped||gone()}),socket.once("error",()=>{stopped||unavailable()}),socket.unref(),socket.resume(),()=>{stopped=!0,socket.destroy()}}var HOST_WATCH_LIFETIME_FIFO_ENV="SENPI_RPC_HOST_LIFETIME_FIFO";function prepareLifetimeBinding(hopDir,platform=process.platform){if(platform!=="linux")return{};let path=join4(hopDir,"lifetime.fifo");try{return rmSync2(path,{force:!0}),execFileSync("mkfifo",["-m","600",path],{stdio:"ignore"}),openSync(path,constants.O_RDWR),{lifetimeFifo:path}}catch{return{}}}function armLifetimeBinding(binding,gone,unavailable,platform=process.platform){if(platform==="win32")return;let fifo=platform==="linux"?openFifoReadEnd(binding.lifetimeFifo):void 0;if(fifo!==void 0)return binding.lifetimeFd!==void 0&&closeSync2(binding.lifetimeFd),watchHostLifetime(fifo,()=>gone("supervisor lifetime FIFO closed"),unavailable);if(binding.lifetimeFd!==void 0)return watchHostLifetime(binding.lifetimeFd,()=>gone("supervisor stdin lifetime closed"),unavailable)}function openFifoReadEnd(path){if(path===void 0)return;let fd;try{fd=openSync(path,constants.O_RDONLY|constants.O_NONBLOCK|constants.O_NOFOLLOW)}catch{return}let stat2=fstatSync(fd),owned=typeof process.getuid!="function"||stat2.uid===process.getuid();if(stat2.isFIFO()&&owned&&(stat2.mode&511)===384)return fd;closeSync2(fd)}async function recordedOwnerStartTime(dir){if(dir!==void 0)try{let owner=JSON.parse(await readFile4(join5(dir,".owner"),"utf8")),start=owner!==null&&typeof owner=="object"?Reflect.get(owner,"processStartTime"):void 0;return typeof start=="string"?start:void 0}catch{return}}async function prepareInternalHop(daemonDir){let created=await createInternalSocketPath(daemonDir),internal={...created,secretPath:created.secretPath??socketSecretPath(created.socket)},internalSecret=process.platform==="win32"?await createSocketSecret(internal.secretPath):void 0,internalKey=process.platform==="win32"?void 0:randomBytes2(32);return{internal,internalSocket:internal.socket,internalSecret,internalKey,...internalKey&&internal.dir!==void 0?prepareLifetimeBinding(internal.dir):{},supervisorStart:internalKey?{time:await recordedOwnerStartTime(internal.dir),ticks:readProcessStartTicks(process.pid)}:void 0,transport:{...internalSecret?{internalSecret}:{},...internalKey?{internalKey}:{}}}}import{spawn}from"node:child_process";import{Socket as Socket4}from"node:net";import{extname}from"node:path";function runtimeExecArgv(execArgv=process.execArgv,bun=process.versions.bun!==void 0){let args=[];for(let index=0;index<execArgv.length;index++){let arg=execArgv[index];if(bun){if(arg==="-e"||arg==="--eval"||arg==="-p"||arg==="--print"||arg==="-pe"){index++;continue}if(arg.startsWith("-e")||arg.startsWith("-p"))continue}if(arg==="-e"||arg==="--eval"||arg==="-pe"||arg==="--input-type"||arg==="--input_type"){index++;continue}if(arg==="-p"||arg==="--print"){execArgv[index+1]!==void 0&&!execArgv[index+1].startsWith("-")&&index++;continue}arg==="-i"||arg==="--interactive"||arg.startsWith("--interactive=")||arg.startsWith("--eval=")||arg.startsWith("--print=")||arg.startsWith("--input-type=")||arg.startsWith("--input_type=")||args.push(arg)}return args}import{rmSync as rmSync3}from"node:fs";import{rm}from"node:fs/promises";import{Socket as Socket3}from"node:net";var HOST_WATCH_BACKSTOP_INTERVAL_MS=3e4,HOST_WATCH_PPID_INTERVAL_MS=250,HOST_WATCH_PPID_BACKUP_INTERVAL_MS=5e3,HOST_WATCH_IDENTITY_INTERVAL_MS=5e3,HOST_WATCH_IDENTITY_ONLY_INTERVAL_MS=1e3,HOST_WATCH_SPAWNING_IDENTITY_INTERVAL_MS=6e4;function supervisorPoll(ppid,recorded,fire,stopped){let stopPpid,ppidIntervalMs;return{arm(intervalMs){stopped()||ppid===void 0||ppidIntervalMs===intervalMs||(stopPpid?.(),ppidIntervalMs=intervalMs,stopPpid=watchPpid(ppid,recorded,fire,intervalMs))},soleInterval:recorded.ticks!==void 0||recorded.time!==void 0?HOST_WATCH_IDENTITY_ONLY_INTERVAL_MS:HOST_WATCH_PPID_INTERVAL_MS,stop:()=>stopPpid?.()}}function watchPpid(supervisorPid,recorded,fire,intervalMs){if(supervisorPid===process.pid)return()=>{};let linux=process.platform==="linux",comparable=linux?recorded.ticks!==void 0:recorded.time!==void 0,identityEveryTicks=Math.max(1,Math.round((linux?HOST_WATCH_IDENTITY_INTERVAL_MS:HOST_WATCH_SPAWNING_IDENTITY_INTERVAL_MS)/intervalMs)),probe={ticks:pid=>readProcessStartTicks(pid),time:pid=>readProcessStartTime(pid,process.platform,1e3)},ticks=0,stopped=!1,probing=!1,timer=setInterval(()=>{if(!stopped){if(!processAlive(supervisorPid)){fire(`supervisor pid ${supervisorPid} is gone`);return}ticks+=1,!(!comparable||probing||ticks%identityEveryTicks!==0)&&(probing=!0,compareRecordedStart(supervisorPid,recorded,process.platform,probe).then(result=>{!stopped&&result==="changed"&&fire(`supervisor pid ${supervisorPid} start time changed`)},()=>{}).finally(()=>{probing=!1}))}},intervalMs);return timer.unref?.(),()=>{stopped=!0,clearInterval(timer)}}function processAlive(pid){try{return process.kill(pid,0),!0}catch(cause){return!(cause instanceof Error&&"code"in cause&&cause.code==="ESRCH")}}var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID",HOST_WATCH_PSTART_ENV="SENPI_RPC_HOST_WATCH_PSTART",HOST_WATCH_PSTART_TICKS_ENV="SENPI_RPC_HOST_WATCH_PSTART_TICKS",HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function readHostWatchdogConfig(env=process.env){let ppid=parsePositiveInteger(env[HOST_WATCH_PPID_ENV]),fd=process.platform!=="win32"&&ppid!==void 0?void 0:parsePositiveInteger(env[HOST_WATCH_FD_ENV]);if(fd===void 0&&ppid===void 0)return;let scratchDir=env[HOST_SCRATCH_DIR_ENV],cleanupPaths=env[HOST_CLEANUP_PATHS_ENV]?.split(`
13
+ `,error=>error?reject(error):resolve2())}))}catch(cause){throw socket.destroy(),cause}finally{timer&&clearTimeout(timer),socket.off("error",onError),socket.off("close",onClose)}}function connectInternalConnection(socket,key,options={}){return handshake(socket,{maxBytes:MAX_RPC_LINE_CHARACTERS,timeoutMs:options.timeoutMs},async(read,send)=>{let clientNonce=randomBytes(32).toString("hex"),[response]=await Promise.all([read(),send({id:"internal-protocol",type:"get_protocol_info",observe:!0,auth:{client_nonce:clientNonce}})]),data=response.data;if(!isObject(data)||!isObject(data.auth))throw new Error("host_identity_unproven");let auth=data.auth,serverNonce=nonce(auth.server_nonce);if(response.id!=="internal-protocol"||response.success!==!0||auth.launch_id!==INTERNAL_LAUNCH_ID||!matches(auth.server_proof,proof(key,"server",clientNonce,serverNonce)))throw new Error("host_identity_unproven");let[result]=await Promise.all([read(),send({id:"internal-auth",type:"authenticate",client_proof:proof(key,"client",serverNonce,clientNonce)})]);if(result.id!=="internal-auth"||result.command!=="authenticate"||result.success!==!0)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"client")})}function acceptInternalConnection(socket,key,protocol={}){return handshake(socket,HOST_PRE_AUTH_BUDGET,async(read,send)=>{let refuse=async frame2=>{throw await send({id:frame2.id,type:"response",command:frame2.type,success:!1,error:"auth_required",errorCode:"auth_required"}),new Error("auth_required")},first=await read(),offered=isObject(first.auth)?first.auth.client_nonce:void 0;if(first.type!=="get_protocol_info"||typeof offered!="string"||!RPC_AUTH_HEX.test(offered))return refuse(first);let clientNonce=offered,serverNonce=randomBytes(32).toString("hex"),[frame]=await Promise.all([read(),send({id:first.id,type:"response",command:first.type,success:!0,data:{...protocol,capabilities:[...Array.isArray(protocol.capabilities)?protocol.capabilities:[],"socket_auth"],auth:{launch_id:INTERNAL_LAUNCH_ID,server_nonce:serverNonce,server_proof:proof(key,"server",clientNonce,serverNonce)}}})]);if(frame.type!=="authenticate")return refuse(frame);let valid=matches(frame.client_proof,proof(key,"client",serverNonce,clientNonce));if(await send({id:frame.id,type:"response",command:"authenticate",success:valid,...valid?{}:{error:"auth_failed",errorCode:"auth_failed"}}),!valid)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"server")})}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}var INTERNAL_OBSERVER_HANDSHAKE_MS=5e3,SupervisorActivity=class{constructor(options){this.runs=new SessionRunActivity,this.options=options,this.decider=new IdleExitDecider(options.idleExitMs),this.clients=new ClientOccupancy(()=>this.refresh(),options.instanceId),this.observerLink=createObserverLink({open:()=>this.connectObserver(),settled:options.settled,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}})}current(){return{connections:this.clients.attachedCount,activeTurns:activeTurnsForIdleDecision({healthy:this.observerLink.healthy(),unhealthySince:this.observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:this.decider.idleExitMs,observedBusy:this.runs.busySessions})}}refresh(){let current=this.current();return(current.connections>0||current.activeTurns>0||this.clients.unclassifiedCount>0)&&this.options.onActivity?.(),this.decider.update(current)}quiescent(){return this.observerLink.healthy()&&this.runs.busySessions===0&&this.clients.attachedCount===0&&this.clients.unclassifiedCount===0}openObserver(){return this.observerLink.open()}stopObserver(){this.observerLink.stop(),this.observerSocket?.destroy()}async connectObserver(){let secret=this.options.internalSecret,next=createConnection(resolveSocketTransportAddress(this.options.internalSocket,process.platform,secret));secret&&sendSocketHandshake(next,secret);let stream;try{this.options.internalKey?stream=await connectInternalConnection(next,this.options.internalKey,{timeoutMs:INTERNAL_OBSERVER_HANDSHAKE_MS}):(await waitForConnect(next,5e3),stream=next)}catch(cause){throw next.destroy(),cause}return this.observerSocket=stream,attachJsonlLineReader(stream,line=>this.observeHostEvent(line),{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{let lost=()=>{handler(),this.options.onActivity?.()};stream.once("close",lost),stream.once("error",lost)}}}observeHostEvent(line){this.runs.observe(line)&&this.refresh()}},OWNER_EXIT_GRACE_MS=2e3,OWNER_PROBE_MAX_INTERVAL_MS=5e3,SupervisorOwner=class{constructor(generationDir){this.watchFailed=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.gone=!1,this.revision=0,this.stopped=!1,this.idle=new IdleExitDecider(OWNER_EXIT_GRACE_MS,()=>performance.now()),this.generationDir=generationDir}async start(fd){if(await this.reload(),!(fd===void 0||this.owner==null))try{let pipe=new Socket({fd,readable:!0,writable:!1});this.pipe=pipe;let bound=this.owner,failed=!1,eof=()=>{!failed&&!this.stopped&&sameHostOwner(this.owner,bound)&&(this.gone=!0)};pipe.once("end",eof),process.platform==="win32"&&pipe.once("close",eof),pipe.once("error",()=>{failed=!0,this.pipe===pipe&&(this.pipe=void 0),pipe.destroy()}),pipe.resume()}catch{this.pipe=void 0}}async reload(){let revision=++this.revision,next=await readHostOwner(this.generationDir);if(!(this.stopped||revision!==this.revision)){if(sameHostOwner(this.owner,next)||(this.pipe?.destroy(),this.pipe=void 0,this.gone=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.activity()),this.owner=next,next==null)this.watcher?.close(),this.watcher=void 0;else if(!this.watcher&&!this.watchFailed)try{this.watcher=watch(this.generationDir,(_event,filename)=>{filename?.toString()==="owner.json"&&this.reload()}),this.watcher.once("error",()=>{this.watchFailed=!0,this.watcher?.close(),this.watcher=void 0})}catch{this.watchFailed=!0}}}activity(){this.idle.update({connections:1,activeTurns:0})}async shouldExit(activity){this.watcher||await this.reload();let owner=this.owner,revision=this.revision;if(owner!=null&&!this.pipe&&!this.gone&&performance.now()>=this.nextProbeAt){let gone=await hostOwnerGone(owner);if(this.stopped||revision!==this.revision)return!1;this.gone=gone,this.nextProbeAt=performance.now()+this.probeIntervalMs,this.probeIntervalMs=Math.min(OWNER_PROBE_MAX_INTERVAL_MS,this.probeIntervalMs*2)}let quiet=this.gone&&owner!=null&&activity.quiescent();if(this.idle.update({connections:quiet?0:1,activeTurns:0})!=="exit")return!1;let current=await readHostOwner(this.generationDir);return!this.stopped&&revision===this.revision&&sameHostOwner(owner,current)&&activity.quiescent()}stop(){this.stopped=!0,this.watcher?.close(),this.pipe?.destroy()}};function waitForConnect(socket,timeoutMs){return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve2()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}import{readFile as readFile2}from"node:fs/promises";var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3,REPLACED_CONFIRMATIONS=3,IDENTITY_PROBE_TIMEOUT_MS=2e3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0)return endpoint.pointer===void 0?()=>{}:watchPointerSupersession(endpoint,endpoint.pointer,onLost);let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function watchPointerSupersession(endpoint,pointer,onLost){let probe=endpoint.probeInstanceId??probeAnsweringInstance,readPointer=endpoint.readPointerInstanceId??pointerInstanceId,agreeingPolls=0,observing=!1,lost=!1,observe=async()=>{let named=await readPointer(pointer.file);return named===void 0||named===pointer.instanceId?!1:await probe(endpoint.path)===named},timer=setInterval(()=>{lost||observing||endpoint.settled?.()===!0||(observing=!0,observe().then(replaced=>{lost||endpoint.settled?.()===!0||(agreeingPolls=replaced?agreeingPolls+1:0,!(agreeingPolls<REPLACED_CONFIRMATIONS)&&(lost=!0,clearInterval(timer),onLost("replaced")))},()=>{agreeingPolls=0}).finally(()=>{observing=!1}))},SUPERSESSION_POLL_MS);return timer.unref?.(),()=>clearInterval(timer)}async function pointerInstanceId(file){try{let parsed=JSON.parse(await readFile2(file,"utf8")),instanceId=typeof parsed=="object"&&parsed!==null?Reflect.get(parsed,"instance_id"):void 0;return typeof instanceId=="string"&&instanceId!==""?instanceId:void 0}catch{return}}async function probeAnsweringInstance(path){let{isRecord:isRecord2,requestOnSocket}=await import("./host-socket-request-QL2WEZTN.js"),answer=await requestOnSocket(path,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},IDENTITY_PROBE_TIMEOUT_MS).catch(()=>{});return isRecord2(answer)&&typeof answer.instanceId=="string"?answer.instanceId:void 0}function ignore(){}var SupervisorDrain=class{constructor(child,shuttingDown,beginStopping=()=>{},relay){this.draining=!1,this.child=child,this.shuttingDown=shuttingDown,this.beginStopping=beginStopping,this.relay=relay}get active(){return this.draining}drain(){if(this.draining||this.shuttingDown())return;this.draining=!0,this.beginStopping(),supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??6e5;this.graceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),this.requestChildDrain()},graceMs),this.graceTimer.unref(),this.requestChildDrain()}stop(){this.graceTimer&&clearTimeout(this.graceTimer)}async acceptRequests(generation){let stop=watchDrainRequest(generation.drainRequestFile,request=>{supervisorLog(`drain requested (${request.reason})`),this.drain()});return await writeDrainWatch(generation.drainWatchFile,{pid:process.pid}).catch(cause=>{supervisorLog(`cannot advertise the drain request: ${errorMessage(cause)}`)}),stop}requestChildDrain(){let{child,relay}=this;if(!(child.pid===void 0||child.exitCode!==null||child.signalCode!==null)&&(relay&&writeDrainRequest(relay.file,{sender:relay.sender,reason:"supervisor_drain"}).catch(cause=>{supervisorLog(`could not relay the drain to the host: ${errorMessage(cause)}`)}),process.platform!=="win32"))try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage(cause)}`)}}};function drainOnPublicSocketLoss(path,identity,settled,drain,onReplaced,pointer){return watchForSupersession({path,identity,settled,...pointer&&{pointer}},loss=>{loss==="replaced"&&onReplaced(),supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drain.drain()})}async function watchWin32ChildIdentity(child,shuttingDown,onGone){let pid=child.pid;if(pid===void 0)return()=>{};let childStartTime=await readProcessStartTime(pid,process.platform,1e3).catch(()=>{}),missingIdentityChecks=0,checking=!1,timer=setInterval(()=>{shuttingDown()||checking||child.exitCode!==null||child.signalCode!==null||(checking=!0,readProcessStartTime(pid,process.platform,1e3).then(currentStartTime=>{currentStartTime===void 0&&!processIsLive(pid)?missingIdentityChecks++:currentStartTime!==void 0&&(missingIdentityChecks=0),(childStartTime!==void 0&&currentStartTime!==void 0&&currentStartTime!==childStartTime||missingIdentityChecks>=2)&&onGone()}).catch(()=>{}).finally(()=>{checking=!1}))},500);return timer.unref?.(),()=>clearInterval(timer)}import{randomBytes as randomBytes2}from"node:crypto";import{readFile as readFile4}from"node:fs/promises";import{join as join5}from"node:path";import{readFileSync as readFileSync4}from"node:fs";function readProcessStartTicks(pid,platform=process.platform){if(platform==="linux")try{let stat2=readFileSync4(`/proc/${pid}/stat`,"utf8"),ticks=stat2.slice(stat2.lastIndexOf(")")+2).split(" ")[19];return ticks!==void 0&&/^\d+$/.test(ticks)?ticks:void 0}catch{return}}async function compareRecordedStart(pid,recorded,platform,probe){if(platform==="linux"){if(recorded.ticks===void 0)return"unknown";let observed2=probe.ticks(pid);return observed2===void 0?"unknown":observed2===recorded.ticks?"same":"changed"}if(recorded.time===void 0)return"unknown";let observed=await probe.time(pid),recordedMs=processStartTimeMs(recorded.time),observedMs=observed===void 0?void 0:processStartTimeMs(observed);return recordedMs===void 0||observedMs===void 0?"unknown":sameProcessStartMs(recordedMs,observedMs)?"same":"changed"}import{randomUUID}from"node:crypto";import{realpathSync as realpathSync2}from"node:fs";import{mkdir,readFile as readFile3,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join3}from"node:path";var INTERNAL_HOST_DIR_PREFIX="senpi-rpc-host-internal-",SHORT_TEMP_ROOT="/tmp";function internalHostDirRoots(){let primary=tmpdir();return canonicalPath(primary)!==canonicalPath(SHORT_TEMP_ROOT)?[primary,SHORT_TEMP_ROOT]:[Buffer.byteLength(primary)<Buffer.byteLength(SHORT_TEMP_ROOT)?primary:SHORT_TEMP_ROOT]}function canonicalPath(path){try{return realpathSync2(path)}catch{return path}}function internalHostDirRoot(name){for(let root of internalHostDirRoots())if(Buffer.byteLength(join3(root,name,"host.sock"))<=MAX_SOCKET_PATH_BYTES)return root;let tried=internalHostDirRoots().map(root=>join3(root,name,"host.sock"));throw new Error(`internal_socket_path_too_long: every candidate exceeds ${MAX_SOCKET_PATH_BYTES} bytes (${tried.join(", ")}); set TMPDIR to a shorter directory`)}async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join3(baseDir,`internal-${randomUUID()}`);return await mkdir(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID()}`,dir:dir2,secretPath:join3(dir2,"secret")}}let name=`${INTERNAL_HOST_DIR_PREFIX}${randomUUID().slice(0,8)}`,dir=join3(internalHostDirRoot(name),name);return await mkdir(dir,{recursive:!1,mode:448}),await writeFile(join3(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join3(dir,"host.sock"),dir,secretPath:join3(dir,".secret")}}var CHILD_START_TIME_WAIT_MS=1e4,CHILD_START_TIME_UNHURRIED_MS=15e3;async function readChildStartTime(pid,timeoutMs){let identity=await readProcessIdentity(pid,process.platform,timeoutMs,void 0,"UTC");if(identity.kind==="error")throw identity.error;return identity.kind==="present"?identity.identity:void 0}async function recordChildPid(file,pid,running){try{await writeJsonAtomic(file,{pid,processStartTime:null});let processStartTime=await waitForStartTime(pid,CHILD_START_TIME_WAIT_MS,p=>readChildStartTime(p,1e3)).catch(()=>{})??await readChildStartTime(pid,CHILD_START_TIME_UNHURRIED_MS).catch(()=>{});if(processStartTime===void 0){supervisorLog(`host child pid ${pid} start time unreadable at recording`);return}if(!running())return;await writeJsonAtomic(file,{pid,processStartTime})}catch(cause){supervisorLog(`could not record the host child pid: ${errorMessage(cause)}`)}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile3(settingsFile,"utf8"))}catch{return}}import{execFileSync}from"node:child_process";import{closeSync as closeSync2,constants,fstatSync,openSync,rmSync as rmSync2}from"node:fs";import{join as join4}from"node:path";import{closeSync}from"node:fs";import{Socket as Socket2}from"node:net";function watchHostLifetime(fd,gone,unavailable){let stopped=!1,bun=Reflect.get(globalThis,"Bun");if(typeof bun=="object"&&bun!==null&&typeof Reflect.get(bun,"file")=="function"){let reader=Reflect.get(bun,"file")(fd).stream().getReader();return(async()=>{try{for(;!stopped;){let{done}=await reader.read();if(done){stopped||gone();return}}}catch{stopped||unavailable()}})(),()=>{stopped||(stopped=!0,reader.cancel().catch(()=>{}).finally(()=>closeSync(fd)))}}let socket=new Socket2({fd,readable:!0,writable:!1});return socket.once("end",()=>{stopped||gone()}),socket.once("error",()=>{stopped||unavailable()}),socket.unref(),socket.resume(),()=>{stopped=!0,socket.destroy()}}var HOST_WATCH_LIFETIME_FIFO_ENV="SENPI_RPC_HOST_LIFETIME_FIFO";function prepareLifetimeBinding(hopDir,platform=process.platform){if(platform!=="linux")return{};let path=join4(hopDir,"lifetime.fifo");try{return rmSync2(path,{force:!0}),execFileSync("mkfifo",["-m","600",path],{stdio:"ignore"}),openSync(path,constants.O_RDWR),{lifetimeFifo:path}}catch{return{}}}function armLifetimeBinding(binding,gone,unavailable,platform=process.platform){if(platform==="win32")return;let fifo=platform==="linux"?openFifoReadEnd(binding.lifetimeFifo):void 0;if(fifo!==void 0)return binding.lifetimeFd!==void 0&&closeSync2(binding.lifetimeFd),watchHostLifetime(fifo,()=>gone("supervisor lifetime FIFO closed"),unavailable);if(binding.lifetimeFd!==void 0)return watchHostLifetime(binding.lifetimeFd,()=>gone("supervisor stdin lifetime closed"),unavailable)}function openFifoReadEnd(path){if(path===void 0)return;let fd;try{fd=openSync(path,constants.O_RDONLY|constants.O_NONBLOCK|constants.O_NOFOLLOW)}catch{return}let stat2=fstatSync(fd),owned=typeof process.getuid!="function"||stat2.uid===process.getuid();if(stat2.isFIFO()&&owned&&(stat2.mode&511)===384)return fd;closeSync2(fd)}async function recordedOwnerStartTime(dir){if(dir!==void 0)try{let owner=JSON.parse(await readFile4(join5(dir,".owner"),"utf8")),start=owner!==null&&typeof owner=="object"?Reflect.get(owner,"processStartTime"):void 0;return typeof start=="string"?start:void 0}catch{return}}async function prepareInternalHop(daemonDir){let created=await createInternalSocketPath(daemonDir),internal={...created,secretPath:created.secretPath??socketSecretPath(created.socket)},internalSecret=process.platform==="win32"?await createSocketSecret(internal.secretPath):void 0,internalKey=process.platform==="win32"?void 0:randomBytes2(32);return{internal,internalSocket:internal.socket,internalSecret,internalKey,...internalKey&&internal.dir!==void 0?prepareLifetimeBinding(internal.dir):{},supervisorStart:internalKey?{time:await recordedOwnerStartTime(internal.dir),ticks:readProcessStartTicks(process.pid)}:void 0,transport:{...internalSecret?{internalSecret}:{},...internalKey?{internalKey}:{}}}}import{spawn}from"node:child_process";import{Socket as Socket4}from"node:net";import{extname}from"node:path";function runtimeExecArgv(execArgv=process.execArgv,bun=process.versions.bun!==void 0){let args=[];for(let index=0;index<execArgv.length;index++){let arg=execArgv[index];if(bun){if(arg==="-e"||arg==="--eval"||arg==="-p"||arg==="--print"||arg==="-pe"){index++;continue}if(arg.startsWith("-e")||arg.startsWith("-p"))continue}if(arg==="-e"||arg==="--eval"||arg==="-pe"||arg==="--input-type"||arg==="--input_type"){index++;continue}if(arg==="-p"||arg==="--print"){execArgv[index+1]!==void 0&&!execArgv[index+1].startsWith("-")&&index++;continue}arg==="-i"||arg==="--interactive"||arg.startsWith("--interactive=")||arg.startsWith("--eval=")||arg.startsWith("--print=")||arg.startsWith("--input-type=")||arg.startsWith("--input_type=")||args.push(arg)}return args}import{rmSync as rmSync3}from"node:fs";import{rm}from"node:fs/promises";import{Socket as Socket3}from"node:net";var HOST_WATCH_BACKSTOP_INTERVAL_MS=3e4,HOST_WATCH_PPID_INTERVAL_MS=250,HOST_WATCH_PPID_BACKUP_INTERVAL_MS=5e3,HOST_WATCH_IDENTITY_INTERVAL_MS=5e3,HOST_WATCH_IDENTITY_ONLY_INTERVAL_MS=1e3,HOST_WATCH_SPAWNING_IDENTITY_INTERVAL_MS=6e4;function supervisorPoll(ppid,recorded,fire,stopped){let stopPpid,ppidIntervalMs;return{arm(intervalMs){stopped()||ppid===void 0||ppidIntervalMs===intervalMs||(stopPpid?.(),ppidIntervalMs=intervalMs,stopPpid=watchPpid(ppid,recorded,fire,intervalMs))},soleInterval:recorded.ticks!==void 0||recorded.time!==void 0?HOST_WATCH_IDENTITY_ONLY_INTERVAL_MS:HOST_WATCH_PPID_INTERVAL_MS,stop:()=>stopPpid?.()}}function watchPpid(supervisorPid,recorded,fire,intervalMs){if(supervisorPid===process.pid)return()=>{};let linux=process.platform==="linux",comparable=linux?recorded.ticks!==void 0:recorded.time!==void 0,identityEveryTicks=Math.max(1,Math.round((linux?HOST_WATCH_IDENTITY_INTERVAL_MS:HOST_WATCH_SPAWNING_IDENTITY_INTERVAL_MS)/intervalMs)),probe={ticks:pid=>readProcessStartTicks(pid),time:pid=>readProcessStartTime(pid,process.platform,1e3)},ticks=0,stopped=!1,probing=!1,timer=setInterval(()=>{if(!stopped){if(!processAlive(supervisorPid)){fire(`supervisor pid ${supervisorPid} is gone`);return}ticks+=1,!(!comparable||probing||ticks%identityEveryTicks!==0)&&(probing=!0,compareRecordedStart(supervisorPid,recorded,process.platform,probe).then(result=>{!stopped&&result==="changed"&&fire(`supervisor pid ${supervisorPid} start time changed`)},()=>{}).finally(()=>{probing=!1}))}},intervalMs);return timer.unref?.(),()=>{stopped=!0,clearInterval(timer)}}function processAlive(pid){try{return process.kill(pid,0),!0}catch(cause){return!(cause instanceof Error&&"code"in cause&&cause.code==="ESRCH")}}var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID",HOST_WATCH_PSTART_ENV="SENPI_RPC_HOST_WATCH_PSTART",HOST_WATCH_PSTART_TICKS_ENV="SENPI_RPC_HOST_WATCH_PSTART_TICKS",HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function readHostWatchdogConfig(env=process.env){let ppid=parsePositiveInteger(env[HOST_WATCH_PPID_ENV]),fd=process.platform!=="win32"&&ppid!==void 0?void 0:parsePositiveInteger(env[HOST_WATCH_FD_ENV]);if(fd===void 0&&ppid===void 0)return;let scratchDir=env[HOST_SCRATCH_DIR_ENV],cleanupPaths=env[HOST_CLEANUP_PATHS_ENV]?.split(`
14
14
  `).filter(Boolean),publicSocket=env[HOST_PUBLIC_SOCKET_ENV],daemonDir=env[HOST_DAEMON_DIR_ENV],instanceId=env[HOST_INSTANCE_ID_ENV];return{fd,ppid,...env[HOST_WATCH_PSTART_ENV]?{processStartTime:env[HOST_WATCH_PSTART_ENV]}:{},...env[HOST_WATCH_PSTART_TICKS_ENV]?{processStartTicks:env[HOST_WATCH_PSTART_TICKS_ENV]}:{},...env[HOST_WATCH_LIFETIME_FIFO_ENV]?{lifetimeFifo:env[HOST_WATCH_LIFETIME_FIFO_ENV]}:{},scratchDir:scratchDir===void 0||scratchDir===""?void 0:scratchDir,cleanupPaths,publicSocket:publicSocket===""?void 0:publicSocket,...daemonDir&&instanceId?{daemonDir,instanceId}:{}}}function readHostWatchdogConfigFromBrandEnv(env=process.env){return readHostWatchdogConfig({[HOST_WATCH_FD_ENV]:env[HOST_WATCH_FD_ENV]??envValue("RPC_HOST_WATCH_FD",env),[HOST_WATCH_PPID_ENV]:env[HOST_WATCH_PPID_ENV]??envValue("RPC_HOST_WATCH_PPID",env),[HOST_WATCH_PSTART_ENV]:env[HOST_WATCH_PSTART_ENV]??envValue("RPC_HOST_WATCH_PSTART",env),[HOST_WATCH_PSTART_TICKS_ENV]:env[HOST_WATCH_PSTART_TICKS_ENV]??envValue("RPC_HOST_WATCH_PSTART_TICKS",env),[HOST_WATCH_LIFETIME_FIFO_ENV]:env[HOST_WATCH_LIFETIME_FIFO_ENV]??envValue("RPC_HOST_LIFETIME_FIFO",env),[HOST_SCRATCH_DIR_ENV]:env[HOST_SCRATCH_DIR_ENV]??envValue("RPC_HOST_SCRATCH_DIR",env),[HOST_PUBLIC_SOCKET_ENV]:env[HOST_PUBLIC_SOCKET_ENV]??envValue("RPC_HOST_PUBLIC_SOCKET",env),[HOST_CLEANUP_PATHS_ENV]:env[HOST_CLEANUP_PATHS_ENV]??envValue("RPC_HOST_CLEANUP_PATHS",env),[HOST_DAEMON_DIR_ENV]:env[HOST_DAEMON_DIR_ENV],[HOST_INSTANCE_ID_ENV]:env[HOST_INSTANCE_ID_ENV]})}var WATCH_ENV_SUFFIXES=["RPC_HOST_WATCH_FD","RPC_HOST_WATCH_PPID","RPC_HOST_WATCH_PSTART","RPC_HOST_WATCH_PSTART_TICKS","RPC_HOST_LIFETIME_FIFO","RPC_HOST_SCRATCH_DIR","RPC_HOST_PUBLIC_SOCKET","RPC_HOST_CLEANUP_PATHS"];function consumeHostWatchdogEnv(env=process.env){let config=readHostWatchdogConfigFromBrandEnv(env);return scrubHostWatchdogEnv(env),config}function scrubHostWatchdogEnv(env=process.env){for(let suffix of WATCH_ENV_SUFFIXES)for(let name of[`SENPI_${suffix}`,...brandEnvNames(suffix)])delete env[name]}function armHostWatchdog(config,onSupervisorGone){if(!config)return()=>{};let stopped=!1,fired=!1,fire=reason=>{if(stopped||fired)return;fired=!0,disarm(),config.daemonDir!==void 0&&config.instanceId!==void 0&&recordHostCrash(config.daemonDir,{at:new Date().toISOString(),uptimeMs:Math.round(process.uptime()*1e3),kind:"rpc-host-watchdog",generation:config.instanceId,reason});let captured=captureBeforeCleanup(config);if(process.platform==="win32"){let cleanup=captured.then(()=>cleanupWatchdogPaths(config));onSupervisorGone(reason,cleanup)}else captured.then(()=>cleanupWatchdogPaths(config)).finally(()=>onSupervisorGone(reason))},disarmers=[],disarm=()=>{stopped=!0;for(let stop of disarmers.splice(0))stop()},poll=supervisorPoll(config.ppid,{ticks:config.processStartTicks,time:config.processStartTime},fire,()=>stopped);disarmers.push(()=>poll.stop());let pollWanted=!1,pipeLive=!1;config.fd!==void 0&&(pipeLive=watchFdForEof(config.fd,fire,disarmers,()=>{pipeLive=!1,pollWanted&&poll.arm(poll.soleInterval)}));let fallback=()=>{pollWanted=!0,poll.arm(pipeLive?HOST_WATCH_PPID_BACKUP_INTERVAL_MS:poll.soleInterval)},stopLifetime;try{stopLifetime=armLifetimeBinding(config,fire,fallback)}catch{stopLifetime=void 0}return stopLifetime!==void 0?(disarmers.push(stopLifetime),poll.arm(HOST_WATCH_BACKSTOP_INTERVAL_MS)):fallback(),disarm}function watchFdForEof(fd,fire,disarmers,onUnavailable){let stream,streamFailed=!1,fired=!1,fireOnce=reason=>{fired||(fired=!0,fire(reason))};try{stream=new Socket3({fd,readable:!0,writable:!1})}catch{return!1}stream.resume();let onEnd=()=>fireOnce(`supervisor pipe fd ${fd} closed`),onClose=()=>{streamFailed||onEnd()},onError=()=>{streamFailed=!0,onUnavailable()};return stream.once("end",onEnd),process.platform==="win32"&&stream.once("close",onClose),stream.once("error",onError),disarmers.push(()=>{stream.off("end",onEnd),stream.off("close",onClose),stream.off("error",onError),stream.destroy()}),!0}function captureBeforeCleanup(config){return config.beforeCleanup===void 0?Promise.resolve():Promise.resolve().then(config.beforeCleanup).catch(()=>{})}async function cleanupWatchdogPaths(config){let paths=[...config.cleanupPaths??[],...config.scratchDir?[config.scratchDir]:[]];for(let path of paths)try{process.platform==="win32"?rmSync3(path,{recursive:!0,force:!0,maxRetries:10,retryDelay:100}):await rm(path,{recursive:!0,force:!0})}catch{}}var INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,ownerFd,presenterBootstrapFd,bindSocket,replaceIdentity;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--mcp-presenter-fd"&&argv[index+1]==="4"){presenterBootstrapFd=4,index++;continue}if(arg==="--owner-fd"&&index+1<argv.length){if(ownerFd=Number(argv[++index]),!Number.isSafeInteger(ownerFd)||ownerFd<3)return;continue}if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}hostArgs.push(arg)}return socket===void 0||ownerFd===presenterBootstrapFd&&ownerFd!==void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,ownerFd,bindSocket,replaceIdentity,presenterBootstrapFd}}var OWNER_WATCH_FD=3,ownerPipes=new Set;function keepOwnerPipe(child){let pipe=child.stdio[OWNER_WATCH_FD];if(!(pipe instanceof Socket4))throw new Error("RPC owner pipe was not inherited");ownerPipes.add(pipe),pipe.on("error",()=>{}),pipe.unref(),child.once("exit",()=>{ownerPipes.delete(pipe),pipe.destroy()})}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...runtimeExecArgv(),resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}var HOST_CHILD_WATCH_FD=3;function spawnHostChild(options){let{launch,internalSocket,internal,internalSecret,publicSocket}=options,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),bootstrap=launch.presenterBootstrapFd!==void 0&&!childLaunch.shell;bootstrap&&childLaunch.args.push("--mcp-presenter-fd","4");let child=spawn(childLaunch.command,childLaunch.args,{env:{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:options.daemonDir,[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_WATCH_FD_ENV]:String(HOST_CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),[HOST_WATCH_PSTART_ENV]:options.supervisorStart?.time,[HOST_WATCH_PSTART_TICKS_ENV]:options.supervisorStart?.ticks,[HOST_WATCH_LIFETIME_FIFO_ENV]:options.lifetimeFifo,...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},[SOCKET_SECRET_FILE_ENV]:process.platform==="win32"&&internalSecret?internal.secretPath:void 0,SENPI_RPC_INTERNAL_KEY_STDIN:options.internalKey?"1":void 0,[HOST_CLEANUP_PATHS_ENV]:options.cleanupPaths.join(`
15
15
  `),...process.platform==="win32"?{}:{[HOST_PUBLIC_SOCKET_ENV]:publicSocket}},shell:childLaunch.shell,stdio:[process.platform==="win32"?"ignore":"pipe","ignore","inherit","pipe",...bootstrap?["pipe"]:[]],windowsHide:!0});if(launch.presenterBootstrapFd!==void 0){let fd=launch.presenterBootstrapFd;import("./mcp-presenter-bootstrap-XUSCQVRC.js").then(({presenterBootstrapStream,relayPresenterBootstrap})=>{let upstream=presenterBootstrapStream(fd);if(upstream&&bootstrap)return relayPresenterBootstrap(upstream,child);upstream?.destroy(),child.stdio[4]?.destroy()}).catch(()=>child.stdio[4]?.destroy())}return options.internalKey&&(child.stdin?.on("error",()=>{}),child.stdin?.write(options.internalKey)),child}import{chmod,mkdir as mkdir2,stat,unlink}from"node:fs/promises";import{createConnection as createConnection2,createServer}from"node:net";import{dirname as dirname2}from"node:path";import{StringDecoder}from"node:string_decoder";function proxyWithAdmission(client,internal,admission,auth){let reply=chunk=>write(client,auth?auth.response(chunk.toString()):chunk),pending=[],refused=new Set,protocols=0,refusals=Promise.resolve(),unsubscribe=admission.onStop(()=>(refusals=refusePending(),refusals));async function refusePending(){let ids=pending.splice(0);for(let id of ids)refused.add(id);try{for(let id of ids)await reply(serializeJsonLine(hostStoppingResponse(id,"open_session",admission)))}catch{fail()}}client.once("close",()=>{unsubscribe(),internal?.destroy()});let fail=()=>{internal?.destroy(),client.destroy()};client.once("error",fail),internal?.once("error",()=>{admission.stopping||fail()}),requests().catch(()=>{admission.stopping||fail()}),internal&&responses(internal).catch(()=>{admission.stopping||fail()});async function requests(){for await(let line of lines(auth?.input??client,MAX_RPC_LINE_CHARACTERS)){if(line===void 0){await reply(serializeJsonLine({type:"response",command:"parse",success:!1,error:`RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`}));continue}let request=record(line);admission.stopping&&request?.type==="get_protocol_info"?await reply(serializeJsonLine({id:request.id,type:"response",command:request.type,success:!0,data:admission.protocol()})):admission.stopping&&(request?.type==="open_session"||!internal)?await reply(serializeJsonLine(hostStoppingResponse(request?.id,String(request?.type??"parse"),admission))):internal&&(request?.type==="open_session"&&pending.push(request.id),request?.type==="get_protocol_info"&&protocols++,await write(internal,`${line}
16
16
  `))}internal?.end()}async function responses(source){let fragments=[];for await(let chunk of source){let newline=chunk.lastIndexOf(10);if(newline===-1){fragments.push(chunk);continue}let complete=chunk.subarray(0,newline+1);if(!auth&&pending.length===0&&protocols===0&&refused.size===0){client.cork();let written;try{for(let fragment of fragments)client.write(fragment);written=write(client,complete)}finally{client.uncork()}await written}else{let batch=fragments.length>0?Buffer.concat([...fragments,complete]):complete;await reply(filterReplies(batch))}fragments=newline+1<chunk.length?[chunk.subarray(newline+1)]:[]}fragments.length>0&&await reply(filterReplies(Buffer.concat(fragments))),await refusals,client.end(()=>client.destroy())}function filterReplies(batch){if(pending.length===0&&protocols===0&&refused.size===0)return batch;let output=[],changed=!1;for(let start=0;start<batch.length;){let newline=batch.indexOf(10,start),end=newline===-1?batch.length:newline+1,line=batch.subarray(start,end);start=end;let response=line.includes('"open_session"')||line.includes('"get_protocol_info"')?record(line.toString("utf8")):void 0;if(response?.type==="response"&&response.command==="open_session"){if(refused.has(response.id)){changed=!0;continue}let index=pending.indexOf(response.id);index!==-1&&pending.splice(index,1)}if(response?.type==="response"&&response.command==="get_protocol_info"&&(protocols=Math.max(0,protocols-1),response.success===!0)){isRecord(response.data)&&admission.observe(response.data),output.push(Buffer.from(serializeJsonLine({...response,data:admission.protocol()}))),changed=!0;continue}output.push(line)}return changed?Buffer.concat(output):batch}}async function write(socket,line){await new Promise((resolve2,reject)=>{socket.write(line,error=>error?reject(error):resolve2())})}async function*lines(socket,limit){let decoder=new StringDecoder("utf8"),buffer="",discarding=!1;for await(let chunk of socket){let text=typeof chunk=="string"?chunk:decoder.write(chunk),offset=0;for(;offset<text.length;){let newline=text.indexOf(`