@code-yeongyu/senpi 2026.10.26-1 → 2026.10.26-2

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 (148) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/bundle/chunks/{anthropic-messages-M235FJQV.js → anthropic-messages-ODSFJCXR.js} +1 -1
  3. package/dist/bundle/chunks/{args-FBNJOJSR.js → args-SWKJAYQD.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-YQRTQ7H6.js → azure-openai-responses-REGXS4XO.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  6. package/dist/bundle/chunks/chunk-2XF6W6F6.js +410 -0
  7. package/dist/bundle/chunks/{chunk-DMFAVE5N.js → chunk-4QVORFQ2.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-ZXHLH4MW.js → chunk-5W3DTM2J.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-QREKAXKX.js → chunk-6GAMRAVM.js} +5 -5
  10. package/dist/bundle/chunks/{chunk-MSHRIZGT.js → chunk-7IZH2KQX.js} +3 -3
  11. package/dist/bundle/chunks/{chunk-PH3JDRB2.js → chunk-ARSENVDY.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-5KZH6EYQ.js → chunk-CNDPCYNT.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-DYWIFF2Q.js → chunk-CYOHFREV.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-3LPWILUZ.js → chunk-DNDZPKIQ.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-ZLIVZQDY.js → chunk-EQNUL2WB.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-5FQMNHXV.js → chunk-ESNSRUW4.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-LO5MYLGF.js → chunk-FQDARFHT.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-7KOUQSBX.js → chunk-GPPOPK76.js} +3 -3
  19. package/dist/bundle/chunks/chunk-I2WFLKZ2.js +5 -0
  20. package/dist/bundle/chunks/{chunk-I7QWTWVZ.js → chunk-IHKHCWWG.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-MY4ZD3EW.js → chunk-IY4G44MN.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-OQ3WDMB3.js → chunk-JH7MVRNJ.js} +1 -1
  23. package/dist/bundle/chunks/chunk-KBSFTXAT.js +2 -0
  24. package/dist/bundle/chunks/{chunk-UW6M3EXY.js → chunk-KRO63T4Q.js} +1 -1
  25. package/dist/bundle/chunks/{chunk-J5FCH7TI.js → chunk-KTDIIF2F.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-3WP5RFQR.js → chunk-NDNIMC5W.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-CDQPA4FP.js → chunk-ODRGPC5S.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-3A3XCLNH.js → chunk-PDG4XWO2.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-QYFOHFPS.js → chunk-PPECSSWX.js} +1 -1
  30. package/dist/bundle/chunks/{chunk-5LWUUXMH.js → chunk-PY4ZQHTN.js} +1 -1
  31. package/dist/bundle/chunks/{chunk-EZP6AYW2.js → chunk-RPW3XQW3.js} +22 -22
  32. package/dist/bundle/chunks/{chunk-SOXQ42VS.js → chunk-RQ5JTXUC.js} +1 -1
  33. package/dist/bundle/chunks/{chunk-JFQUWEN7.js → chunk-TQ67PB7U.js} +2 -2
  34. package/dist/bundle/chunks/{chunk-6U3TBFBA.js → chunk-UJPG4ROT.js} +1 -1
  35. package/dist/bundle/chunks/{chunk-UDM7VO6O.js → chunk-XM36IFP3.js} +1 -1
  36. package/dist/bundle/chunks/{chunk-XQ45JMGN.js → chunk-Z6BREXV3.js} +1 -1
  37. package/dist/bundle/chunks/{chunk-ADQAPDPV.js → chunk-ZP6JJDYV.js} +1 -1
  38. package/dist/bundle/chunks/{cli-main-55EQA5PS.js → cli-main-Q2GA53XM.js} +1 -1
  39. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-ZJQGIIRC.js → cloudflare-workers-ai-system-one-WDHT7BBV.js} +1 -1
  40. package/dist/bundle/chunks/cursor-agent.js +1 -1
  41. package/dist/bundle/chunks/devin-agent.js +1 -1
  42. package/dist/bundle/chunks/{dispatch-C2IBP5VV.js → dispatch-5R3TYAYB.js} +3 -3
  43. package/dist/bundle/chunks/{google-generative-ai-5G4RIQA6.js → google-generative-ai-FHYFXKLA.js} +1 -1
  44. package/dist/bundle/chunks/{google-vertex-ALD4P27O.js → google-vertex-5DWE5U5K.js} +1 -1
  45. package/dist/bundle/chunks/{help-fast-path-PEIKGCKZ.js → help-fast-path-FETLIF3W.js} +1 -1
  46. package/dist/bundle/chunks/{host-command-657VCQ34.js → host-command-XEB7SHT3.js} +1 -1
  47. package/dist/bundle/chunks/{host-session-command-OV5XDOJK.js → host-session-command-FFN52LXJ.js} +1 -1
  48. package/dist/bundle/chunks/{interactive-mode-MLXSYK2H.js → interactive-mode-5DEKY3YW.js} +1 -1
  49. package/dist/bundle/chunks/{mistral-conversations-RAE4K2XY.js → mistral-conversations-I2PI7DDF.js} +1 -1
  50. package/dist/bundle/chunks/{multi-session-host-774MACJU.js → multi-session-host-OPR5VBFO.js} +3 -3
  51. package/dist/bundle/chunks/{openai-codex-responses-3CW4R7TG.js → openai-codex-responses-WSEX6SH7.js} +1 -1
  52. package/dist/bundle/chunks/{openai-completions-5UIJXQUF.js → openai-completions-YCBHTBSS.js} +1 -1
  53. package/dist/bundle/chunks/{openai-responses-2BO44MRW.js → openai-responses-GXNSQF4A.js} +1 -1
  54. package/dist/bundle/chunks/{package-manager-cli-MZHVCX2S.js → package-manager-cli-W55E3LHP.js} +1 -1
  55. package/dist/bundle/chunks/{pi-messages-RF6GER4R.js → pi-messages-O6GISIRW.js} +1 -1
  56. package/dist/bundle/chunks/{role-ETSFSDTS.js → role-SHIZQKK4.js} +1 -1
  57. package/dist/bundle/chunks/{rotation-stream-ZMQB4GPO.js → rotation-stream-2PCZWNKF.js} +1 -1
  58. package/dist/bundle/chunks/{rpc-mode-UJXOIZCW.js → rpc-mode-IDUJTSYS.js} +1 -1
  59. package/dist/bundle/chunks/{schedule-command-KA7LFFNK.js → schedule-command-B7RRSANU.js} +1 -1
  60. package/dist/bundle/chunks/{session-control-endpoint-MFWXUR7Z.js → session-control-endpoint-LMZH5JLH.js} +1 -1
  61. package/dist/bundle/chunks/{session-picker-BP33NRSL.js → session-picker-DTGBOXDR.js} +1 -1
  62. package/dist/bundle/chunks/session-worker.js +41 -41
  63. package/dist/bundle/chunks/{typesafe-system-one-GNNZ5O5U.js → typesafe-system-one-XGYJJVSE.js} +1 -1
  64. package/dist/bundle/cli.js +2 -2
  65. package/dist/bundle/index.js +1 -1
  66. package/dist/bundle/rpc-entry.js +1 -1
  67. package/dist/bundle/runtime-manifest.json +1 -1
  68. package/dist/core/agent-session.d.ts +11 -1
  69. package/dist/core/agent-session.js +19 -2
  70. package/dist/core/extensions/builtin/compaction/index.js +7 -1
  71. package/dist/core/extensions/builtin/herdr/index.js +9 -5
  72. package/dist/core/extensions/builtin/mcp/auth/oauth-issuer.d.ts +6 -0
  73. package/dist/core/extensions/builtin/mcp/auth/oauth-issuer.js +25 -0
  74. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.d.ts +3 -3
  75. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.js +50 -19
  76. package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.js +4 -3
  77. package/dist/core/extensions/builtin/mcp/auth/oauth.js +19 -12
  78. package/dist/core/extensions/builtin/mcp/modern/dispatch.js +1 -0
  79. package/dist/core/extensions/builtin/mcp/modern/parameter-headers.d.ts +4 -1
  80. package/dist/core/extensions/builtin/mcp/modern/parameter-headers.js +33 -35
  81. package/dist/core/extensions/builtin/mcp/modern/request.js +3 -0
  82. package/dist/core/extensions/builtin/mcp/modern/transport.d.ts +2 -0
  83. package/dist/core/extensions/builtin/mcp/modern/transport.js +4 -2
  84. package/dist/core/extensions/builtin/terminal/extension-state.js +2 -1
  85. package/dist/core/extensions/builtin/vertex-model-garden/auth.d.ts +9 -0
  86. package/dist/core/extensions/builtin/vertex-model-garden/auth.js +17 -1
  87. package/dist/core/extensions/builtin/websearch/websearch/providers/google.d.ts +6 -0
  88. package/dist/core/extensions/builtin/websearch/websearch/providers/google.js +6 -1
  89. package/dist/core/extensions/types.d.ts +2 -0
  90. package/dist/core/lifecycle-children.d.ts +3 -1
  91. package/dist/core/lifecycle-children.js +79 -15
  92. package/dist/core/lifecycle-record.js +1 -24
  93. package/dist/core/lifecycle-session-binding.js +2 -1
  94. package/dist/core/lifecycle-wait-items.d.ts +17 -0
  95. package/dist/core/lifecycle-wait-items.js +72 -0
  96. package/dist/core/model-runtime.js +6 -1
  97. package/dist/core/provider-api-key-auth.d.ts +6 -1
  98. package/dist/core/provider-api-key-auth.js +11 -4
  99. package/dist/core/provider-composer.d.ts +8 -1
  100. package/dist/core/provider-composer.js +7 -3
  101. package/dist/core/sdk.js +4 -1
  102. package/dist/core/session-activity.js +2 -0
  103. package/dist/core/session-lifecycle-types.d.ts +20 -4
  104. package/dist/core/session-lifecycle.js +35 -4
  105. package/dist/core/structured-session-lane.d.ts +33 -0
  106. package/dist/core/structured-session-lane.js +62 -0
  107. package/dist/core/work-custody-record.d.ts +2 -1
  108. package/dist/core/work-custody-record.js +2 -0
  109. package/dist/core/work-obligations.d.ts +1 -1
  110. package/dist/core/work-obligations.js +8 -2
  111. package/dist/modes/json-event.d.ts +79 -1
  112. package/dist/modes/json-event.js +79 -1
  113. package/dist/modes/rpc/compact-content-index.d.ts +85 -0
  114. package/dist/modes/rpc/compact-content-index.js +254 -0
  115. package/dist/modes/rpc/compact-content-store.d.ts +6 -43
  116. package/dist/modes/rpc/compact-content-store.js +22 -157
  117. package/dist/modes/rpc/compact-index-pages.d.ts +12 -0
  118. package/dist/modes/rpc/compact-index-pages.js +31 -0
  119. package/dist/modes/rpc/compact-session-state.d.ts +11 -39
  120. package/dist/modes/rpc/compact-session-state.js +17 -26
  121. package/dist/modes/rpc/compact-spool-dir.d.ts +4 -1
  122. package/dist/modes/rpc/compact-spool-dir.js +41 -8
  123. package/dist/modes/rpc/compact-spool-storage.d.ts +53 -0
  124. package/dist/modes/rpc/compact-spool-storage.js +162 -0
  125. package/dist/modes/rpc/compact-storage-io.d.ts +2 -1
  126. package/dist/modes/rpc/compact-storage-io.js +7 -1
  127. package/dist/modes/rpc/compact-transition.d.ts +41 -0
  128. package/dist/modes/rpc/compact-transition.js +12 -0
  129. package/dist/modes/rpc/connection-handler.d.ts +2 -0
  130. package/dist/modes/rpc/connection-handler.js +12 -6
  131. package/dist/modes/rpc/host-ensure-start.js +5 -3
  132. package/dist/modes/rpc/security-presentations.js +2 -1
  133. package/dist/modes/rpc/session-binding.js +10 -0
  134. package/dist/modes/rpc/session-event-writer.d.ts +2 -0
  135. package/dist/modes/rpc/session-event-writer.js +2 -0
  136. package/dist/modes/rpc/session-record-stream.d.ts +3 -3
  137. package/dist/modes/rpc/session-record-stream.js +3 -3
  138. package/dist/modes/rpc/session-structured-lanes.d.ts +12 -0
  139. package/dist/modes/rpc/session-structured-lanes.js +24 -0
  140. package/dist/modes/rpc/session-worker-client.js +6 -5
  141. package/dist/modes/rpc/structured-session-records.d.ts +12 -0
  142. package/dist/modes/rpc/structured-session-records.js +88 -0
  143. package/docs/extensions.md +7 -1
  144. package/docs/rpc.md +17 -2
  145. package/package.json +6 -6
  146. package/dist/bundle/chunks/chunk-GQJYNFMO.js +0 -2
  147. package/dist/bundle/chunks/chunk-VICDRG3J.js +0 -410
  148. package/dist/bundle/chunks/chunk-VL7O5PO4.js +0 -5
@@ -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{getInternalHostBootstrap}from"./chunk-MYAENL22.js";import{SessionEventWriter,answerSetSessionContext,answerSubscribeSessions,answerUnsubscribeSessions,applyContextPatch,notAttachedRefusal,publishedSessionContext,recordLoopBlockedMs,registryStatusSource,socketSink}from"./chunk-VL7O5PO4.js";import{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,EXTENSION_STATE_PAYLOAD,EXTENSION_STATE_PREFIX,HostMcpRegistry,MANIFEST_FILE,MOVE_BUNDLE_FORMAT,MoveBundleInvalidError,ProviderScope,SESSION_BUNDLE_PATH,STATE_ATTEMPT_FIELD,SessionPendingInputs,bindToProviderScope,createAgentSessionRuntime,createRpcConnectionHandler,createWebViewBroker,foreignSessionHolders,isMoveId,isPlainId,isSecurityNoticeState,movedStateDir,outgoingStateDir,parseMoveId,parsePermissionPresetName,parsePlainId,pathExists,prepareOutgoingState,readCodemodeKernelRows,readMainThreadHeapBytes,readManifest,readRecordedRepositoryIdentity,readSessionCwd,rebindSessionFile,runWithProviderScope,sealedOutgoingStateDir,sha256File,startHostChildReaper,subscriptionLimits,verifyBundle}from"./chunk-EZP6AYW2.js";import"./chunk-6U3TBFBA.js";import{SessionHeldError,encodedSessionId,liveSessionHolders,readProcessStartMs,serializeByKey,withSessionMoveLock}from"./chunk-UDM7VO6O.js";import"./chunk-ADQAPDPV.js";import{flushRawStdout,liveToolMediaScope,takeOverStdout,toolMediaPersister,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-3A3XCLNH.js";import"./chunk-DXJJP6RP.js";import"./chunk-GXY5JEI5.js";import{CONNECTION_ROLE_FIXED,ClientAdmissions,ConnectionRoles,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,EMPTY_SESSION_CONTEXT,EffectLedger,answerEffectFromTranscript,beginEffect,buildRpcSessionState,drainSessionEffects,effectAnswer,installSessionEffectSink,isEffectBegin,latestSessionEffect,roleConnection,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionRetryFallbackError}from"./chunk-VICDRG3J.js";import{RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_OWNER_CHANGED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_SESSION_HELD,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_WARM_FAILED,STEER_WHEN_IDLE_CAPABILITY,USER_ACTIVITY_CAPABILITY}from"./chunk-GY5MR5KR.js";import"./chunk-3LPWILUZ.js";import{SESSION_MOVED,SESSION_MOVED_IN,SESSION_RECLAIMED,SESSION_RELEASED,SessionManager,SessionMovedAwayError,assertValidSessionId,compareRepositoryIdentities,getDefaultSessionDir,headerSessionId,loadEntriesFromFileAsync,ownershipStep,readRepositoryIdentity,sessionOwnership}from"./chunk-DYWIFF2Q.js";import{resolveMovedPath}from"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-Y3TMJV3J.js";import"./chunk-JFQUWEN7.js";import{isRecord}from"./chunk-JPGT64RV.js";import"./chunk-HWTD4QF3.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,HostIdleHandover,agentDirMismatch,beginHandoverResponse,handoverRefusal,isHandoffBusy,isHostIdle,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-MSHRIZGT.js";import{ATTENDED_CAPABILITY,AUTH_KEY_VERIFY_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,BROWSER_ENGINE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DETACH_CONNECTION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,ENTRIES_TAIL_CAPABILITY,EVAL_CELLS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,OBSERVE_READS_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,RESUME_SESSION_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_HELD_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_RELOCATION_CAPABILITY,SESSION_STATUS_CAPABILITY,TOOL_BARRIER_CAPABILITY,WARM_CAPABILITY,computeRuntimeBuildId,hostGeneration,hostInstanceId,parseClientCapabilities,protocolIdentity}from"./chunk-5KZH6EYQ.js";import"./chunk-QMRJYMNH.js";import"./chunk-XMNPK472.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-SOXQ42VS.js";import"./chunk-XMJKZK5H.js";import"./chunk-6VWIMHMH.js";import"./chunk-LO5MYLGF.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import{lockWithLossHandling}from"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import{isHostOwnedToolRuntimeCapability,isSpawnedBy,toolRuntimeCapabilities}from"./chunk-I7QWTWVZ.js";import"./chunk-26UBFF6N.js";import{readOwnFootprint}from"./chunk-MTQQ2VQH.js";import"./chunk-L2O6K3SJ.js";import"./chunk-H4WJ4LY3.js";import{presenterBootstrapStream}from"./chunk-Z6SAQ5O3.js";import{ClientOccupancy,PublicRpcConnection,acceptInternalConnection,armHostWatchdog,consumeHostWatchdogEnv,loopLagErrorMs,prepareSocketPath,scrubHostWatchdogEnv}from"./chunk-ZAUVY6ZC.js";import{SESSION_PATH_RETRY_AFTER_MS,createEndpointReservations,holderGenerationEnded,hostChildDrainRequestFile,ownGenerationDir,parseIdleExitMs,watchDrainRequest,writeHeartbeat,writeStallEvidence}from"./chunk-J2YAYTB2.js";import{HOST_DAEMON_DIR_ENV,canonicalSessionPath,createHostDaemonPaths,sessionDirectoryRemoved}from"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import{RpcPublicEndpoint}from"./chunk-GWGNVYPB.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import{FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,isLockError}from"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3WP5RFQR.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-J5FCH7TI.js";import"./chunk-FDL4CF6F.js";import{killTrackedDetachedChildren}from"./chunk-7KOUQSBX.js";import"./chunk-YU4AYH4C.js";import"./chunk-QREKAXKX.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ZLIVZQDY.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-MY4ZD3EW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-5LWUUXMH.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-ZXHLH4MW.js";import"./chunk-45SZOLCU.js";import"./chunk-GQJYNFMO.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-5FQMNHXV.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import{PUBLIC_SOCKET_IDENTITY_FILE,readSocketIdentityFile,shieldSocketDuringClose,socketEntryReplaced,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-VRDU425E.js";import{SOCKET_SECRET_FILE_ENV,authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{VERSION,envValue,isBunBinary,normalizePath,resolvePath}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import{ownProcessStartedAtMs}from"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import{processStartTimeMs}from"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{createServer as createServer2}from"node:net";import{mkdtemp,rm as rm6}from"node:fs/promises";import{tmpdir}from"node:os";import{basename as basename2,dirname as dirname3,join as join7}from"node:path";var HostCoreGate=class{constructor(registry,route,hooks){this.inFlight=new Map,this.answering=new Set,this.route=route,this.runtimeBuildId=hooks.runtimeBuildId,this.endpoint=hooks.endpoint,this.handover=hooks.handover===void 0?void 0:new HostIdleHandover({...hooks.handover,isIdle:()=>isHostIdle(registry,this.inFlight)})}async intercept(parsed,deliver){if(!isRecord2(parsed)||parsed.type!==BEGIN_HANDOVER_COMMAND)return!1;let answering=this.answerBegin(parsed).then(deliver);this.answering.add(answering);try{await answering}finally{this.answering.delete(answering)}return!0}async answerBegin(parsed){if(this.handover===void 0)return beginHandoverResponse(parsed.id,{kind:"refused",reason:"handover_unsupported"});let request=parseBeginHandover(parsed);if(typeof request=="string")return beginHandoverResponse(parsed.id,request);let detail2=request.agentDir===void 0||this.endpoint===void 0?void 0:await agentDirMismatch(this.endpoint.socket,request.agentDir,this.endpoint.agentDir);return beginHandoverResponse(parsed.id,detail2===void 0?await this.handover.begin(request):{kind:"refused",reason:"foreign_agent_dir",detail:detail2})}async answered(){for(;this.answering.size>0;)await Promise.allSettled([...this.answering])}async dispatch(command){let pending=this.handover?.view();if(pending!==void 0&&this.handover?.admits(command.type)===!1)return handoverRefusal(command,pending);let key="sessionId"in command?command.sessionId:void 0;this.inFlight.set(key,(this.inFlight.get(key)??0)+1);let response;try{response=await this.route(command)}finally{let remaining=(this.inFlight.get(key)??1)-1;remaining>0?this.inFlight.set(key,remaining):this.inFlight.delete(key),this.handover?.observe()}return response===void 0?void 0:withHostIdentity(response,this.runtimeBuildId,this.handover?.view())}};function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var HandoffAnnouncement=class{begin(superseded,identity,publicSocket,log){return this.record=superseded.then(replaced=>({type:"host_superseded",...identity,successor:replaced?{socket:publicSocket}:null}),cause=>{log(`handoff announcement failed: ${String(cause)}`)}),this.record}deliverLate(stream,arrivedBeforeDrain){let record=this.record;return!arrivedBeforeDrain||record===void 0?!1:(record.then(announced=>announced===void 0?stream.destroy():stream.end(`${JSON.stringify(announced)}
2
+ import{getInternalHostBootstrap}from"./chunk-MYAENL22.js";import{SessionEventWriter,answerSetSessionContext,answerSubscribeSessions,answerUnsubscribeSessions,applyContextPatch,notAttachedRefusal,publishedSessionContext,recordLoopBlockedMs,registryStatusSource,socketSink}from"./chunk-I2WFLKZ2.js";import{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,EXTENSION_STATE_PAYLOAD,EXTENSION_STATE_PREFIX,HostMcpRegistry,MANIFEST_FILE,MOVE_BUNDLE_FORMAT,MoveBundleInvalidError,ProviderScope,SESSION_BUNDLE_PATH,STATE_ATTEMPT_FIELD,SessionPendingInputs,bindToProviderScope,createAgentSessionRuntime,createRpcConnectionHandler,createWebViewBroker,foreignSessionHolders,isMoveId,isPlainId,isSecurityNoticeState,movedStateDir,outgoingStateDir,parseMoveId,parsePermissionPresetName,parsePlainId,pathExists,prepareOutgoingState,readCodemodeKernelRows,readMainThreadHeapBytes,readManifest,readRecordedRepositoryIdentity,readSessionCwd,rebindSessionFile,runWithProviderScope,sealedOutgoingStateDir,sha256File,startHostChildReaper,structuredLaneEnabled,subscriptionLimits,verifyBundle}from"./chunk-RPW3XQW3.js";import"./chunk-UJPG4ROT.js";import{SessionHeldError,encodedSessionId,liveSessionHolders,readProcessStartMs,serializeByKey,withSessionMoveLock}from"./chunk-XM36IFP3.js";import"./chunk-ZP6JJDYV.js";import{flushRawStdout,liveToolMediaScope,takeOverStdout,toolMediaPersister,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-PDG4XWO2.js";import"./chunk-DXJJP6RP.js";import"./chunk-GXY5JEI5.js";import{CONNECTION_ROLE_FIXED,ClientAdmissions,ConnectionRoles,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,EMPTY_SESSION_CONTEXT,EffectLedger,answerEffectFromTranscript,answeredUiRequestId,beginEffect,buildRpcSessionState,drainSessionEffects,effectAnswer,installSessionEffectSink,isEffectBegin,latestSessionEffect,roleConnection,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionRetryFallbackError}from"./chunk-2XF6W6F6.js";import{RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_OWNER_CHANGED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_SESSION_HELD,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_WARM_FAILED,STEER_WHEN_IDLE_CAPABILITY,USER_ACTIVITY_CAPABILITY}from"./chunk-GY5MR5KR.js";import"./chunk-DNDZPKIQ.js";import{SESSION_MOVED,SESSION_MOVED_IN,SESSION_RECLAIMED,SESSION_RELEASED,SessionManager,SessionMovedAwayError,assertValidSessionId,compareRepositoryIdentities,getDefaultSessionDir,headerSessionId,loadEntriesFromFileAsync,ownershipStep,readRepositoryIdentity,sessionOwnership}from"./chunk-CYOHFREV.js";import{resolveMovedPath}from"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-Y3TMJV3J.js";import"./chunk-TQ67PB7U.js";import{isRecord}from"./chunk-JPGT64RV.js";import"./chunk-HWTD4QF3.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,HostIdleHandover,agentDirMismatch,beginHandoverResponse,handoverRefusal,isHandoffBusy,isHostIdle,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-7IZH2KQX.js";import{ATTENDED_CAPABILITY,AUTH_KEY_VERIFY_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,BROWSER_ENGINE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DETACH_CONNECTION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,ENTRIES_TAIL_CAPABILITY,EVAL_CELLS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,OBSERVE_READS_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,RESUME_SESSION_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_HELD_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_RELOCATION_CAPABILITY,SESSION_STATUS_CAPABILITY,TOOL_BARRIER_CAPABILITY,WARM_CAPABILITY,computeRuntimeBuildId,hostGeneration,hostInstanceId,parseClientCapabilities,protocolIdentity}from"./chunk-CNDPCYNT.js";import"./chunk-QMRJYMNH.js";import"./chunk-XMNPK472.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-RQ5JTXUC.js";import"./chunk-XMJKZK5H.js";import"./chunk-6VWIMHMH.js";import"./chunk-FQDARFHT.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import{lockWithLossHandling}from"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import{isHostOwnedToolRuntimeCapability,isSpawnedBy,toolRuntimeCapabilities}from"./chunk-IHKHCWWG.js";import"./chunk-26UBFF6N.js";import{readOwnFootprint}from"./chunk-MTQQ2VQH.js";import"./chunk-L2O6K3SJ.js";import"./chunk-H4WJ4LY3.js";import{presenterBootstrapStream}from"./chunk-Z6SAQ5O3.js";import{ClientOccupancy,PublicRpcConnection,acceptInternalConnection,armHostWatchdog,consumeHostWatchdogEnv,loopLagErrorMs,prepareSocketPath,scrubHostWatchdogEnv}from"./chunk-ZAUVY6ZC.js";import{SESSION_PATH_RETRY_AFTER_MS,createEndpointReservations,holderGenerationEnded,hostChildDrainRequestFile,ownGenerationDir,parseIdleExitMs,watchDrainRequest,writeHeartbeat,writeStallEvidence}from"./chunk-J2YAYTB2.js";import{HOST_DAEMON_DIR_ENV,canonicalSessionPath,createHostDaemonPaths,sessionDirectoryRemoved}from"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import{RpcPublicEndpoint}from"./chunk-GWGNVYPB.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import{FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,isLockError}from"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-NDNIMC5W.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-KTDIIF2F.js";import"./chunk-FDL4CF6F.js";import{killTrackedDetachedChildren}from"./chunk-GPPOPK76.js";import"./chunk-YU4AYH4C.js";import"./chunk-6GAMRAVM.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-EQNUL2WB.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-IY4G44MN.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-PY4ZQHTN.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-5W3DTM2J.js";import"./chunk-45SZOLCU.js";import"./chunk-KBSFTXAT.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-ESNSRUW4.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import{PUBLIC_SOCKET_IDENTITY_FILE,readSocketIdentityFile,shieldSocketDuringClose,socketEntryReplaced,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-VRDU425E.js";import{SOCKET_SECRET_FILE_ENV,authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{VERSION,envValue,isBunBinary,normalizePath,resolvePath}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import{ownProcessStartedAtMs}from"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import{processStartTimeMs}from"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{createServer as createServer2}from"node:net";import{mkdtemp,rm as rm6}from"node:fs/promises";import{tmpdir}from"node:os";import{basename as basename2,dirname as dirname3,join as join7}from"node:path";var HostCoreGate=class{constructor(registry,route,hooks){this.inFlight=new Map,this.answering=new Set,this.route=route,this.runtimeBuildId=hooks.runtimeBuildId,this.endpoint=hooks.endpoint,this.handover=hooks.handover===void 0?void 0:new HostIdleHandover({...hooks.handover,isIdle:()=>isHostIdle(registry,this.inFlight)})}async intercept(parsed,deliver){if(!isRecord2(parsed)||parsed.type!==BEGIN_HANDOVER_COMMAND)return!1;let answering=this.answerBegin(parsed).then(deliver);this.answering.add(answering);try{await answering}finally{this.answering.delete(answering)}return!0}async answerBegin(parsed){if(this.handover===void 0)return beginHandoverResponse(parsed.id,{kind:"refused",reason:"handover_unsupported"});let request=parseBeginHandover(parsed);if(typeof request=="string")return beginHandoverResponse(parsed.id,request);let detail2=request.agentDir===void 0||this.endpoint===void 0?void 0:await agentDirMismatch(this.endpoint.socket,request.agentDir,this.endpoint.agentDir);return beginHandoverResponse(parsed.id,detail2===void 0?await this.handover.begin(request):{kind:"refused",reason:"foreign_agent_dir",detail:detail2})}async answered(){for(;this.answering.size>0;)await Promise.allSettled([...this.answering])}async dispatch(command){let pending=this.handover?.view();if(pending!==void 0&&this.handover?.admits(command.type)===!1)return handoverRefusal(command,pending);let key="sessionId"in command?command.sessionId:void 0;this.inFlight.set(key,(this.inFlight.get(key)??0)+1);let response;try{response=await this.route(command)}finally{let remaining=(this.inFlight.get(key)??1)-1;remaining>0?this.inFlight.set(key,remaining):this.inFlight.delete(key),this.handover?.observe()}return response===void 0?void 0:withHostIdentity(response,this.runtimeBuildId,this.handover?.view())}};function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var HandoffAnnouncement=class{begin(superseded,identity,publicSocket,log){return this.record=superseded.then(replaced=>({type:"host_superseded",...identity,successor:replaced?{socket:publicSocket}:null}),cause=>{log(`handoff announcement failed: ${String(cause)}`)}),this.record}deliverLate(stream,arrivedBeforeDrain){let record=this.record;return!arrivedBeforeDrain||record===void 0?!1:(record.then(announced=>announced===void 0?stream.destroy():stream.end(`${JSON.stringify(announced)}
3
3
  `)),!0)}};import{existsSync as existsSync4}from"node:fs";import{createHash}from"node:crypto";import{existsSync,renameSync}from"node:fs";import{mkdir,readdir,readFile,rm,writeFile}from"node:fs/promises";import{join}from"node:path";var recordDir=daemonDir=>join(daemonDir,"handover-parked"),entryFile=(daemonDir,sessionPath)=>join(recordDir(daemonDir),`${createHash("sha256").update(sessionPath,"utf8").digest("hex").slice(0,16)}.json`),mutationChain=Promise.resolve();function enqueueMutation(mutation){let next=mutationChain.then(mutation,mutation);return mutationChain=next.catch(()=>{}),next}function isEntry(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;let record=value;return typeof record.sessionPath=="string"&&typeof record.retainOnDisconnect=="boolean"&&(record.durableSessionId===void 0||typeof record.durableSessionId=="string")&&(record.cwd===void 0||typeof record.cwd=="string")&&(record.parkedBy===void 0||typeof record.parkedBy=="string")&&(record.thinkingLevel===void 0||typeof record.thinkingLevel=="string")&&(record.permissionPreset===void 0||typeof record.permissionPreset=="string"&&parsePermissionPresetName(record.permissionPreset)!==void 0)&&sessionPromptSurfaceError(record.promptSurface)===void 0&&sessionBrowserEngineError(record.browserEngine)===void 0&&sessionKindError(record.sessionKind)===void 0&&sessionContextError(record.sessionContext)===void 0&&(record.contextOverlay===void 0||!("refusal"in applyContextPatch(void 0,record.contextOverlay)))&&sessionAutoTitleError(record.autoTitle)===void 0&&sessionRetryFallbackError(record.retryFallback)===void 0&&(record.model===void 0||typeof record.model=="object"&&record.model!==null&&typeof record.model.provider=="string"&&typeof record.model.modelId=="string")}async function writeEntryFile(daemonDir,entry){await mkdir(recordDir(daemonDir),{recursive:!0,mode:448});let file=entryFile(daemonDir,entry.sessionPath),tmp=`${file}.${process.pid}.${Math.random().toString(16).slice(2,10)}.tmp`;await writeFile(tmp,`${JSON.stringify(entry,null,2)}
4
4
  `,{mode:384}),renameSync(tmp,file)}function recordHandoverParkedSession(daemonDir,entry){return enqueueMutation(()=>writeEntryFile(daemonDir,entry))}async function readHandoverParkedSessions(daemonDir){let names;try{names=(await readdir(recordDir(daemonDir))).filter(name=>name.endsWith(".json"))}catch{return[]}let entries=[];for(let name of names){let file=join(recordDir(daemonDir),name);try{let parsed=JSON.parse(await readFile(file,"utf8"));isEntry(parsed)&&entries.push(parsed)}catch(cause){cause instanceof SyntaxError&&(process.stderr.write(`senpi rpc handover-parked entry ${name} is corrupt; dropping it
5
5
  `),await rm(file,{force:!0}))}}return entries}function clearHandoverParkedSession(daemonDir,sessionPath){return enqueueMutation(()=>rm(entryFile(daemonDir,sessionPath),{force:!0}))}function dropHandoverParkedSessionIfFileGone(daemonDir,sessionPath){return existsSync(sessionPath)?Promise.resolve():clearHandoverParkedSession(daemonDir,sessionPath)}import{isAbsolute as isAbsolute2}from"node:path";import{access}from"node:fs/promises";import{isAbsolute}from"node:path";var MAX_WARM_PROFILES=64;function profileKey(profile){let context=Object.entries(profile.sessionContext??{}).sort(([a],[b])=>a<b?-1:a>b?1:0);return JSON.stringify([profile.cwd,profile.sessionKind??"interactive",context])}var HostWarmer=class{constructor(load){this.warm=new Set,this.loading=new Map,this.load=load}async run(profile){let key=profileKey(profile);if(this.warm.has(key))return"already_warm";let pending=this.loading.get(key);return pending===void 0&&(pending=this.loadOnce(key,profile),this.loading.set(key,pending)),await pending,"warmed"}async loadOnce(key,profile){try{if(await this.load(profile),this.warm.add(key),this.warm.size>MAX_WARM_PROFILES){let oldest=this.warm.values().next().value;oldest!==void 0&&this.warm.delete(oldest)}}finally{this.loading.delete(key)}}};function createRegistryWarm(prepare,host){let warmer=new HostWarmer(async profile=>{await access(profile.cwd);let launchProfile={cwd:profile.cwd,...profile.sessionKind!==void 0?{sessionKind:profile.sessionKind}:{},...profile.sessionContext!==void 0?{sessionContext:Object.freeze({...profile.sessionContext})}:{}},scope=new ProviderScope;try{await runWithProviderScope(scope,()=>prepare({cwd:profile.cwd,agentDir:host.agentDir,launchProfile:Object.freeze(launchProfile),...host.mcpRegistry!==void 0?{mcpRegistry:host.mcpRegistry}:{}}))}finally{scope.close()}});return profile=>warmer.run(profile)}function refusal(command,code2){return{id:command.id,type:"response",command:"warm",success:!1,error:code2}}async function answerWarm(command,host){if(host.draining)return refusal(command,"host_draining");let kindError=sessionKindError(command.kind);if(kindError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);if(host.warm===void 0)return{id:command.id,type:"response",command:"warm",success:!0,data:{state:"unsupported"}};let sessionContext=host.hostContext?{...command.context,...host.hostContext}:command.context,cwd=command.cwd??host.cwd;if(!isAbsolute(cwd))return refusal(command,RPC_ERROR_INVALID_PATH);try{let state=await host.warm({cwd,...command.kind!==void 0?{sessionKind:command.kind}:{},...sessionContext!==void 0?{sessionContext}:{}});return{id:command.id,type:"response",command:"warm",success:!0,data:{state}}}catch(cause){return refusal(command,`${RPC_ERROR_WARM_FAILED}: ${cause instanceof Error?cause.message:String(cause)}`)}}var observations=new Set(["get_state","get_snapshot","get_effect_status","get_pending_inputs","get_messages","get_entries","get_tree","get_fork_messages","get_last_assistant_text","get_session_stats","resolve_path","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_model_thinking_level","get_fast_mode","get_commands","get_loaded_surfaces","get_media","get_auth_providers","get_provider_accounts","memory_report","eval_cells.list","eval_cells.peek"]);function refreshesSessionActivity(command){return!observations.has(command)}var RpcSessionRegistryError=class extends Error{constructor(code2,reason,detail2){super(code2==="open_failed"&&reason?`${code2}: ${reason}`:code2),this.code=code2,this.name="RpcSessionRegistryError",detail2&&(this.detail=detail2)}};function frozenProfile(profile){return Object.freeze({...profile,...profile.holderEndpoint?{holderEndpoint:Object.freeze({...profile.holderEndpoint})}:{},...profile.creationModel?{creationModel:Object.freeze({...profile.creationModel})}:{},...profile.sessionContext?{sessionContext:Object.freeze({...profile.sessionContext})}:{},...profile.retryFallback?{retryFallback:Object.freeze({modelFallback:profile.retryFallback.modelFallback,fallbackChains:Object.freeze(Object.fromEntries(Object.entries(profile.retryFallback.fallbackChains).map(([key,entries])=>[key,Object.freeze([...entries])])))})}:{}})}function sessionIdentity(profile){return{kind:profile.sessionKind??"interactive",context:profile.sessionContext??EMPTY_SESSION_CONTEXT}}function attachLiveSession(entry,now,markAttached){if(entry?.state!=="open")throw new RpcSessionRegistryError("unknown_session");let wasParked=entry.retainOnDisconnect===!0&&entry.attachments===0;return entry.attachments++,entry.detachedAt=void 0,entry.lastCommandAt=now,markAttached(),wasParked&&entry.runtime&&(entry.lifecycleMutex=entry.lifecycleMutex.then(()=>entry.runtime?.emitAttachmentEvent("session_resumed"))),entry}function markPathAttached(entry,claims){entry?.reservationKey&&claims?.setAttached(entry.reservationKey,!0)}function beginPendingClaim(pending,sessionPath){let settled=Promise.withResolvers();return pending.set(sessionPath,settled.promise),()=>{pending.get(sessionPath)===settled.promise&&pending.delete(sessionPath),settled.resolve()}}async function takeCrossGenerationClaim(reservations,pending,pathReservations,sessionPath){let settle=beginPendingClaim(pending,sessionPath),holder;try{holder=await pathReservations.claim(sessionPath)}catch(cause){throw reservations.delete(sessionPath),settle(),cause}if(holder===void 0)return settle;throw reservations.delete(sessionPath),settle(),new RpcSessionRegistryError("session_path_in_use",void 0,{owner:holder,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}async function settlePendingClaim(pending,sessionPath,graceMs){let timer,late=new Promise(resolve2=>{timer=setTimeout(()=>resolve2("late"),graceMs)});try{for(let claim=pending.get(sessionPath);claim!==void 0;claim=pending.get(sessionPath))if(await Promise.race([claim.then(()=>"settled"),late])==="late")throw new RpcSessionRegistryError("session_path_in_use","another open of this path is still taking its claim",{reason:"claim_in_progress",retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}finally{clearTimeout(timer)}}function syncRuntimeMetadata(entries,reservations,pathReservations){for(let entry of entries){let manager=entry.runtime?.session.sessionManager;if(!manager)continue;let currentPath=manager.getSessionFile(),currentKey=currentPath?canonicalSessionPath(currentPath):void 0;(currentPath!==entry.sessionPath||currentKey!==entry.reservationKey)&&(entry.reservationKey&&(reservations.delete(entry.reservationKey),pathReservations?.release(entry.reservationKey)),currentKey&&(reservations.add(currentKey),pathReservations?.claim(currentKey,entry.attachments>0)),entry.reservationKey=currentKey,entry.sessionPath=currentPath),entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}async function settleClosingReservation(entries,sessionPath,closeGraceMs){let closing=[...entries].find(entry=>entry.reservationKey===sessionPath&&entry.state==="closing");if(!closing?.closeCompletion)return;let deadline;try{await Promise.race([closing.closeCompletion,new Promise(resolve2=>{deadline=setTimeout(resolve2,closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}function assertRequestedModelResolved(profile,diagnostics){let requested=profile.creationModel;if(requested===void 0)return;let unresolved=diagnostics.find(diagnostic=>diagnostic.code==="model_unresolved");if(unresolved!==void 0)throw new RpcSessionRegistryError("open_failed",`model_unavailable: ${unresolved.message}`,{reason:"model_unavailable",requestedModel:`${requested.provider}/${requested.modelId}`})}var DEFAULT_OPEN_IN_PROGRESS_WAIT_MS=45e3,OPEN_IN_PROGRESS_WAIT_RETRY_MS=2e3;function openInProgressWaitMs(){let override=Number(process.env.SENPI_OPEN_IN_PROGRESS_WAIT_MS);return Number.isFinite(override)&&override>0?override:DEFAULT_OPEN_IN_PROGRESS_WAIT_MS}var OpenInProgressWaitError=class extends Error{};function openingOwner(sessionPath){return{instanceId:hostInstanceId(),pid:process.pid,processStartTime:null,sessionPath,attached:!0,current:!0}}function waitWithDeadline(openCompletion,waitMs){let timer;return Promise.race([openCompletion,new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new OpenInProgressWaitError),waitMs)})]).finally(()=>{timer!==void 0&&clearTimeout(timer)})}async function attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now){let existing=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="open");if(!existing){let inFlight=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="opening");if(inFlight?.[1].openCompletion!==void 0){try{await waitWithDeadline(inFlight[1].openCompletion,openInProgressWaitMs())}catch(cause){throw cause instanceof OpenInProgressWaitError?new RpcSessionRegistryError("session_path_in_use","the session is still opening",{reason:"open_in_progress",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS,owner:openingOwner(sessionPath)}):new RpcSessionRegistryError("session_path_in_use","the in-flight open failed",{reason:"open_failed",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS})}return attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now)}throw new RpcSessionRegistryError("session_path_in_use","the session is still being released",{reason:"path_still_held",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS})}let[handle2,entry]=existing,wasParked=entry.retainOnDisconnect===!0&&entry.attachments===0;if(entry.attachments+=1,entry.detachedAt=void 0,pathReservations?.setAttached(sessionPath,!0),options?.retainOnDisconnect&&(entry.retainOnDisconnect=!0),!entry.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return profile.promptSurface!==void 0&&profile.promptSurface!==entry.profile.promptSurface&&(entry.profile=frozenProfile({...entry.profile,promptSurface:profile.promptSurface}),entry.runtime?.setPromptSurface(profile.promptSurface)),profile.browserEngine!==void 0&&profile.browserEngine!==entry.profile.browserEngine&&(entry.profile=frozenProfile({...entry.profile,browserEngine:profile.browserEngine}),entry.runtime?.setBrowserEngine(profile.browserEngine)),profile.permissionPreset!==void 0&&(entry.profile=frozenProfile({...entry.profile,permissionPreset:profile.permissionPreset}),entry.runtime?.setPermissionPreset(profile.permissionPreset)),entry.lastCommandAt=now,wasParked&&(entry.lifecycleMutex=entry.lifecycleMutex.then(()=>entry.runtime?.emitAttachmentEvent("session_resumed")),await entry.lifecycleMutex),{sessionId:handle2,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,attached:!0}}import{existsSync as existsSync2}from"node:fs";function resolveMovedProfile(requested){let profile={...requested,cwd:resolveMovedPath(requested.cwd),...requested.sessionPath?{sessionPath:resolveMovedPath(requested.sessionPath)}:{}};if(profile.sessionPath!==requested.sessionPath&&profile.sessionPath&&!existsSync2(profile.sessionPath))throw new RpcSessionRegistryError("open_failed",`moved session file does not exist: ${profile.sessionPath}`);return profile}import{existsSync as existsSync3}from"node:fs";function createEntrySwitchSession(entry,createRuntime,syncRuntimeMetadata2){return(sessionPath,options)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath,options);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),ClientAdmissions.sealQueuedOnReplace(replacement),EffectLedger.sealOnReplace(replacement),runtime.releaseSessionHold(),entry.runtime=replacement,syncRuntimeMetadata2(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation}}function buildOpeningEntry(input){let{profile,sessionPath,requestedDurableId,options}=input,isResume=sessionPath!==void 0&&existsSync3(sessionPath),sessionStartEvent=isResume||profile.attended===!1?{type:"session_start",reason:isResume?"resume":"startup",...profile.attended===!1?{attended:!1}:{}}:void 0,storedProfile=frozenProfile({...profile,...sessionPath?{sessionPath}:{}}),runtimeProfile=isResume?frozenProfile({...storedProfile,creationModel:void 0,initialThinkingLevel:void 0}):storedProfile,settleOpen,openCompletion=new Promise((resolve2,reject)=>{settleOpen={resolve:resolve2,reject}});openCompletion.catch(()=>{});let entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),sessionPath,reservationKey:sessionPath,cwd:storedProfile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:input.now,lifecycleMutex:Promise.resolve(),openCompletion};return entry.switchSession=createEntrySwitchSession(entry,input.createRuntime,input.sync),requestedDurableId!==void 0&&(entry.durableSessionId=requestedDurableId),{entry,storedProfile,runtimeProfile,sessionStartEvent,settleOpen}}function sessionIsWriting(entry){return entry.worker?.busy===!0||entry.runtime?.session.isSessionBusy===!0}function reportDetachedFailure(handle2,cause){process.stderr.write(`senpi rpc session ${handle2} teardown failed: ${String(cause)}
@@ -21,13 +21,13 @@ import{getInternalHostBootstrap}from"./chunk-MYAENL22.js";import{SessionEventWri
21
21
  `)}await host.registry.peek(sessionId)?.closeCompletion,terminal?.()}finally{finalization.resolve(),host.finalizations.delete(sessionId)}}function createFinalization(){let resolveFinalization;return{promise:new Promise(resolve2=>{resolveFinalization=resolve2}),resolve:()=>resolveFinalization?.()}}async function tearDownReleased(host,sessionId,sessionPath){let claim=tryClaimClose(host,sessionId,{drainAttachments:!0});if(!claim)return!1;let binding2=host.bindings.get(sessionId);return binding2?.cancelPendingExtensionUiRequests?.(),forgetSessionOwnership(host,sessionId),claim.finalizer?await finalizeClose(host,sessionId,binding2,()=>host.writer.releaseSession(sessionId,sessionPath)):await host.finalizations.get(sessionId)?.promise,host.writer.forgetSession(sessionId),!0}async function tearDownUnloaded(host,sessionId,sessionPath){let claim=tryClaimClose(host,sessionId,{drainAttachments:!0});if(!claim)return!1;let binding2=host.bindings.get(sessionId);return binding2?.cancelPendingExtensionUiRequests?.(),forgetSessionOwnership(host,sessionId),claim.finalizer?await finalizeClose(host,sessionId,binding2,()=>host.writer.parkSession(sessionId,sessionPath,"unloaded")):await host.finalizations.get(sessionId)?.promise,host.writer.forgetSession(sessionId),!0}async function dispose(host){host.stopLimitBroadcast(),host.drainExitRequested=!0,stopSweep(host),host.drainTimer!==void 0&&clearInterval(host.drainTimer),await Promise.all([...host.bindings.entries()].map(async([sessionId,binding2])=>{let claim=tryClaimClose(host,sessionId,{drainAttachments:!0});claim&&(claim.finalizer?await finalizeClose(host,sessionId,binding2,()=>host.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},"host_shutdown")):await host.finalizations.get(sessionId)?.promise,host.writer.forgetSession(sessionId))})),host.bindings.clear(),host.uninstallEffectSink?.(),host.uninstallEffectSink=void 0}function relocationConnection(host,sessionId){return host.attachOrder.connections(sessionId).find(connection=>host.sessionsByConnection.get(connection)?.has(sessionId)===!0&&host.writer.getConnectionCapabilities(connection)?.includes(SESSION_RELOCATION_CAPABILITY)===!0)}function connectionLeft(host,sessionId,connection){host.attachOrder.detached(sessionId,connection),host.bindings.get(sessionId)?.connectionDetached?.(connection)}async function releaseDisconnectAttachment(host,sessionId){let live=host.registry.peek(sessionId),endsSession=live?.retainOnDisconnect!==!0&&(live?.attachments??0)<=1,session=live?.state==="open"?live.runtime?.session:void 0;if(endsSession&&live?.state==="open"&&live.worker?.snapshot?.streaming){let unsubscribe=live.worker.subscribeSettled(()=>{unsubscribe(),releaseOwnedSession(host,sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred worker release ${sessionId} failed: ${String(cause)}
22
22
  `)})});return!0}if(endsSession&&session?.isStreaming){let released=!1,unsubscribe=session.subscribe(event=>{event.type!=="agent_settled"&&event.type!=="agent_idle"||released||(released=!0,unsubscribe(),releaseOwnedSession(host,sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred release for session ${sessionId} failed: ${String(cause)}
23
23
  `)}))});return!0}return await releaseOwnedSession(host,sessionId),!1}function recordAttachment(host,owner,sessionId){host.writer.attachConnectionToSession(owner,sessionId);let owned=host.sessionsByConnection.get(owner)??new Map;owned.set(sessionId,(owned.get(sessionId)??0)+1),host.sessionsByConnection.set(owner,owned),host.attachOrder.attached(sessionId,owner)}async function releaseConnection(host,connectionId){host.releasedConnections.add(connectionId),host.writer.clearConnectionCapabilities(connectionId),host.connectionRoles.release(connectionId);for(let sessionId of host.sessionsByConnection.get(connectionId)?.keys()??[])host.writer.detachConnectionFromSession(connectionId,sessionId),connectionLeft(host,sessionId,connectionId);host.writer.hasConnection(connectionId)||host.pendingCapabilities.delete(connectionId);let opens=host.opensByConnection.get(connectionId),owned=host.sessionsByConnection.get(connectionId);if(host.sessionsByConnection.delete(connectionId),host.draining)return opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[...owned?.keys()??[]];if(owned===void 0)return opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[];let deferred=new Set;return await Promise.all([...owned].map(async([sessionId,count])=>{for(let attachment=0;attachment<count;attachment++)await releaseDisconnectAttachment(host,sessionId)&&deferred.add(sessionId)})),opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[...deferred]}async function releaseOwnedSession(host,sessionId){let live=host.registry.peek(sessionId),parks=live?.state==="open"&&live.retainOnDisconnect===!0&&live.attachments===1,claim=tryClaimClose(host,sessionId,{drainAttachments:!1,detach:!0});if(!claim)return;if(!claim.finalizer){host.writer.status.publish(sessionId,"detach","client"),parks&&live.runtime&&(live.lifecycleMutex=live.lifecycleMutex.then(()=>live.runtime?.emitAttachmentEvent("session_parked")),await live.lifecycleMutex),await host.finalizations.get(sessionId)?.promise;return}let binding2=host.bindings.get(sessionId);binding2?.cancelPendingExtensionUiRequests?.(),await finalizeClose(host,sessionId,binding2)}function releaseOwnerAttachment(host,owner,sessionId){let owned=host.sessionsByConnection.get(owner),count=owned?.get(sessionId);!owned||count===void 0||(count===1?(host.writer.detachConnectionFromSession(owner,sessionId),owned.delete(sessionId),connectionLeft(host,sessionId,owner)):owned.set(sessionId,count-1),owned.size===0&&host.sessionsByConnection.delete(owner))}function forgetSessionOwnership(host,sessionId){host.attachOrder.forgetSession(sessionId);for(let[connection,owned]of host.sessionsByConnection)owned.delete(sessionId),owned.size===0&&host.sessionsByConnection.delete(connection)}async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecord=record=>{toolSpans.observe(record),writer.enqueue(sessionId,record)},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry.switchSession)return entry.switchSession;if(property==="setRebindSession")return callback=>{entry.rebindSession=callback,entry.runtime?.setRebindSession(callback)};let runtime=entry.runtime;if(!runtime)throw new Error("Session runtime was not created");let value=Reflect.get(runtime,property,runtime);return typeof value=="function"?value.bind(runtime):value}}),droppedAfterClose=!1,handler=await runWithProviderScope(entry.scope,async()=>{let writeInScope=bindToProviderScope(enqueueRecord),dropAfterClose=()=>{droppedAfterClose||process.stderr.write(`senpi rpc host: dropped a record for closed session ${sessionId} at ${new Date().toISOString()}
24
- `),droppedAfterClose=!0},taggedSink={writeRecord:record=>{if(entry.scope.state==="closed")return dropAfterClose();writeInScope(record)},writeRaw:()=>{if(entry.scope.state==="closed")return dropAfterClose();throw new Error("Shared session bindings deliver records through writeRecord, never writeRaw")},waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,publishLoadedSurfacesChanged:(previous,digest)=>{entry.scope.state!=="closed"&&writer.publishLoadedSurfacesChanged(sessionId,previous,digest)},...options,workerSecurityBridge:writer.workerSecurityBridge,grantDialogSettled:id=>writer.settleGrantDialog(sessionId,id),bindSecurityPresentation:(session,ui)=>writer.bindSecurityPresentations(sessionId,session.sessionId,session.securityNotices,ui),bindMcpForms:(session,ui)=>writer.bindMcpForms(sessionId,session.sessionId,ui,()=>session.admitHumanAnswer()),clientInfo:options.clientInfo===void 0?void 0:{...options.clientInfo,hasCapability:(connection,capability)=>writer.getConnectionCapabilities(connection)?.includes(capability)===!0}})});return await handler.ready,{handle:command=>writer.handleMcpForm(command)?Promise.resolve():runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),pendingPrompts:()=>handler.pendingPrompts(),connectionDetached:connectionId=>runWithProviderScope(entry.scope,()=>handler.connectionDetached(connectionId)),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}var SessionAttachOrder=class{constructor(){this.next=0,this.order=new Map}attached(sessionId,connection){let connections=this.order.get(sessionId)??new Map;connections.has(connection)||connections.set(connection,this.next++),this.order.set(sessionId,connections)}detached(sessionId,connection){let connections=this.order.get(sessionId);connections?.delete(connection),connections?.size===0&&this.order.delete(sessionId)}forgetSession(sessionId){this.order.delete(sessionId)}connections(sessionId){return[...(this.order.get(sessionId)??new Map).entries()].sort((left,right)=>left[1]-right[1]).map(([connection])=>connection)}};var RouterContext=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.attachOrder=new SessionAttachOrder,this.opensByConnection=new Map,this.releasedConnections=new Set,this.pendingCapabilities=new Map,this.connectionRoles=new ConnectionRoles,this.finalizations=new Map,this.draining=!1,this.handoffParks=0,this.drainExitRequested=!1,this.handoffClosed=new Set,this.activeRequests=new Map,this.requestSettledListeners=new Map,this.memoryPressure=!1,this.releaseTeardown=(sessionId,sessionPath)=>tearDownReleased(this,sessionId,sessionPath),this.stopLimitBroadcast=subscriptionLimits.subscribe(limits=>writer.broadcastHostRecord({type:"subscription_limits",...limits})),this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.onHandoffParked=idle?.onHandoffParked,this.handoverParkedDir=idle?.handoverParkedDir,this.canExitWhenEmpty=idle?.canExitWhenEmpty,writer.status.setSource(registryStatusSource(registry)),writer.status.setLastEffectProvider(sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session===void 0)return;let latest=latestSessionEffect(session);return latest===void 0?void 0:{effectId:latest.effectId,kind:latest.kind,state:latest.state}}),writer.afterRecord=sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session!==void 0)for(let status of drainSessionEffects(session))this.writer.status.publishEffect(sessionId,status)},this.uninstallEffectSink=installSessionEffectSink({owns:session=>routingIdOf(this,session)!==void 0,flush:(session,statuses)=>{let sessionId=routingIdOf(this,session);if(sessionId!==void 0)for(let status of statuses)this.writer.status.publishEffect(sessionId,status)}}),Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>sweepIdleSessions(this),tickMs),this.sweepTimer.unref?.()}}};import{execFile}from"node:child_process";var READ_ONLY_OR_CONTROL=new Set(["get_state","get_snapshot","get_effect_status","get_pending_inputs","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_model_thinking_level","get_fast_mode","get_session_stats","resolve_path","get_fork_messages","get_entries","get_tree","get_last_assistant_text","get_messages","get_media","get_commands","get_loaded_surfaces","get_auth_providers","get_provider_accounts","memory_report","eval_cells.list","eval_cells.peek","eval_cells.stop","export_html","export_jsonl","abort","interrupt","abort_compaction","abort_branch_summary","abort_retry","abort_bash","clear_queue","check_reload_veto","cleanup_bash_output","set_client_info","extension_ui_response","extension_ui_progress","host_response"]);function readProcessStarts(){let windows=process.platform==="win32",command=windows?"powershell.exe":"ps",args=windows?["-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { if ($null -ne $_.CreationDate) { "{0} {1}" -f $_.ProcessId, $_.CreationDate.ToUniversalTime().ToString("o") } }']:["-axo","pid=,lstart="];return new Promise(resolve2=>{execFile(command,args,{timeout:windows?5e3:1e3,maxBuffer:4*1024*1024,windowsHide:!0,...windows?{}:{env:{...process.env,LC_ALL:"C",LANG:"C"}}},(error2,stdout)=>{if(error2)return resolve2(void 0);let starts=new Map;for(let line of stdout.split(`
24
+ `),droppedAfterClose=!0},writeRecord=record=>{if(entry.scope.state==="closed")return dropAfterClose();writeInScope(record)},writeStructuredInScope=bindToProviderScope(record=>writer.structuredLanes.accept(sessionId,record)),taggedSink={writeRecord,...structuredLaneEnabled()?{writeStructured:record=>{entry.scope.state!=="closed"&&writeStructuredInScope(record)}}:{},writeRaw:()=>{if(entry.scope.state==="closed")return dropAfterClose();throw new Error("Shared session bindings deliver records through writeRecord, never writeRaw")},waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,publishLoadedSurfacesChanged:(previous,digest)=>{entry.scope.state!=="closed"&&writer.publishLoadedSurfacesChanged(sessionId,previous,digest)},...options,workerSecurityBridge:writer.workerSecurityBridge,grantDialogSettled:id=>writer.settleGrantDialog(sessionId,id),bindSecurityPresentation:(session,ui)=>writer.bindSecurityPresentations(sessionId,session.sessionId,session.securityNotices,ui),bindMcpForms:(session,ui)=>writer.bindMcpForms(sessionId,session.sessionId,ui,()=>session.admitHumanAnswer()),clientInfo:options.clientInfo===void 0?void 0:{...options.clientInfo,hasCapability:(connection,capability)=>writer.getConnectionCapabilities(connection)?.includes(capability)===!0}})});return await handler.ready,{handle:command=>writer.handleMcpForm(command)?Promise.resolve():runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),pendingPrompts:()=>handler.pendingPrompts(),connectionDetached:connectionId=>runWithProviderScope(entry.scope,()=>handler.connectionDetached(connectionId)),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}var SessionAttachOrder=class{constructor(){this.next=0,this.order=new Map}attached(sessionId,connection){let connections=this.order.get(sessionId)??new Map;connections.has(connection)||connections.set(connection,this.next++),this.order.set(sessionId,connections)}detached(sessionId,connection){let connections=this.order.get(sessionId);connections?.delete(connection),connections?.size===0&&this.order.delete(sessionId)}forgetSession(sessionId){this.order.delete(sessionId)}connections(sessionId){return[...(this.order.get(sessionId)??new Map).entries()].sort((left,right)=>left[1]-right[1]).map(([connection])=>connection)}};var RouterContext=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.attachOrder=new SessionAttachOrder,this.opensByConnection=new Map,this.releasedConnections=new Set,this.pendingCapabilities=new Map,this.connectionRoles=new ConnectionRoles,this.finalizations=new Map,this.draining=!1,this.handoffParks=0,this.drainExitRequested=!1,this.handoffClosed=new Set,this.activeRequests=new Map,this.requestSettledListeners=new Map,this.memoryPressure=!1,this.releaseTeardown=(sessionId,sessionPath)=>tearDownReleased(this,sessionId,sessionPath),this.stopLimitBroadcast=subscriptionLimits.subscribe(limits=>writer.broadcastHostRecord({type:"subscription_limits",...limits})),this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.onHandoffParked=idle?.onHandoffParked,this.handoverParkedDir=idle?.handoverParkedDir,this.canExitWhenEmpty=idle?.canExitWhenEmpty,writer.status.setSource(registryStatusSource(registry)),writer.status.setLastEffectProvider(sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session===void 0)return;let latest=latestSessionEffect(session);return latest===void 0?void 0:{effectId:latest.effectId,kind:latest.kind,state:latest.state}}),writer.afterRecord=sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session!==void 0)for(let status of drainSessionEffects(session))this.writer.status.publishEffect(sessionId,status)},this.uninstallEffectSink=installSessionEffectSink({owns:session=>routingIdOf(this,session)!==void 0,flush:(session,statuses)=>{let sessionId=routingIdOf(this,session);if(sessionId!==void 0)for(let status of statuses)this.writer.status.publishEffect(sessionId,status)}}),Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>sweepIdleSessions(this),tickMs),this.sweepTimer.unref?.()}}};import{execFile}from"node:child_process";var READ_ONLY_OR_CONTROL=new Set(["get_state","get_snapshot","get_effect_status","get_pending_inputs","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_model_thinking_level","get_fast_mode","get_session_stats","resolve_path","get_fork_messages","get_entries","get_tree","get_last_assistant_text","get_messages","get_media","get_commands","get_loaded_surfaces","get_auth_providers","get_provider_accounts","memory_report","eval_cells.list","eval_cells.peek","eval_cells.stop","export_html","export_jsonl","abort","interrupt","abort_compaction","abort_branch_summary","abort_retry","abort_bash","clear_queue","check_reload_veto","cleanup_bash_output","set_client_info","extension_ui_response","extension_ui_progress","host_response"]);function readProcessStarts(){let windows=process.platform==="win32",command=windows?"powershell.exe":"ps",args=windows?["-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { if ($null -ne $_.CreationDate) { "{0} {1}" -f $_.ProcessId, $_.CreationDate.ToUniversalTime().ToString("o") } }']:["-axo","pid=,lstart="];return new Promise(resolve2=>{execFile(command,args,{timeout:windows?5e3:1e3,maxBuffer:4*1024*1024,windowsHide:!0,...windows?{}:{env:{...process.env,LC_ALL:"C",LANG:"C"}}},(error2,stdout)=>{if(error2)return resolve2(void 0);let starts=new Map;for(let line of stdout.split(`
25
25
  `)){let row=/^\s*(\d+)\s+(.+)$/.exec(line);if(!row)continue;let start=processStartTimeMs(row[2]);start!==void 0&&starts.set(Number(row[1]),start)}resolve2(starts)})})}function sessionHeldCheck(resolveDaemonPids){let daemonPids,processStarts,pidStarts=new Map,observedStarts=new Map;return async(sessionFile,sessionId)=>{let holders=await foreignSessionHolders(sessionFile,sessionId,{holderEnded:generation=>holderGenerationEnded(generation),readProcessStartMs:pid=>{let probe=pidStarts.get(pid);return probe||(probe=(async()=>{process.platform!=="linux"&&(processStarts??=readProcessStarts());let start=(await processStarts)?.get(pid)??await readProcessStartMs(pid);return observedStarts.set(pid,start),start})(),pidStarts.set(pid,probe)),probe}});if(holders.length===0)return;daemonPids??=resolveDaemonPids?.(observedStarts)??Promise.resolve([]);let family=await daemonPids,foreign=holders.filter(holder=>!family.includes(holder.pid));if(foreign.length>0)throw new RpcSessionRegistryError(RPC_ERROR_SESSION_HELD,void 0,{holders:foreign.map(({pid,cwd,host_socket,host_instance})=>({pid,...cwd===void 0?{}:{cwd},...host_socket===void 0?{}:{host_socket},...host_instance===void 0?{}:{host_instance}}))})}}async function dispatchSessionBinding(command,entry,binding2,acknowledgePrompt2,daemonPids){if(!binding2)throw new RpcSessionRegistryError("unknown_session");if(!READ_ONLY_OR_CONTROL.has(command.type)){let assertSessionNotHeld=sessionHeldCheck(daemonPids),state=entry.worker?.snapshot?.state;await assertSessionNotHeld(entry.runtime?.session.sessionFile??state?.sessionFile??entry.sessionPath,entry.runtime?.session.sessionId??state?.sessionId??entry.durableSessionId),"sessionPath"in command&&await assertSessionNotHeld(command.sessionPath)}command.type==="prompt"&&acknowledgePrompt2(),await binding2.handle(command)}function invalidSpawnedBy(command){let ancestry=command.spawnedBy;return ancestry!==void 0&&!isSpawnedBy(ancestry)}function validatedOpenProfile(host,command,options){let defaults=options?.defaults===!1?void 0:host.defaults,instanceId=host.defaults.hostContext?.host_instance??hostInstanceId();if(command.expectedHostInstance!==void 0){if(typeof command.expectedHostInstance!="string"||command.expectedHostInstance.trim()==="")return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: expectedHostInstance must be a non-empty string`,{reason:"invalid_expected_host_instance",action:"supply_host_instance"});if(command.expectedHostInstance!==instanceId)return error(command.id,"open_session",RPC_ERROR_OWNER_CHANGED,{reason:"host_instance_mismatch",action:"rediscover_holder",expectedHostInstance:command.expectedHostInstance,hostInstance:instanceId})}let kindError=sessionKindError(command.kind);if(command.attended!==void 0&&command.attended!==!1)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: attended must be false or omitted`);if(kindError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);let autoTitleError=sessionAutoTitleError(command.auto_title);if(autoTitleError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${autoTitleError}`);let promptSurfaceError=sessionPromptSurfaceError(command.promptSurface);if(promptSurfaceError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${promptSurfaceError}`);let browserEngineError=sessionBrowserEngineError(command.browserEngine);if(browserEngineError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${browserEngineError}`);if(!command.provider!=!command.modelId)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: provider and modelId must be given together`);let retryFallbackError=sessionRetryFallbackError(command.retryFallback);return retryFallbackError?error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${retryFallbackError}`):{cwd:command.cwd??host.defaults.cwd,...command.attended===!1?{attended:!1}:{},sessionPath:command.sessionPath,holderEndpoint:{host_instance:instanceId,...process.env[HOST_DAEMON_DIR_ENV]?{host_daemon_dir:process.env[HOST_DAEMON_DIR_ENV]}:{},...host.defaults.hostContext?.host_socket===void 0?{}:{host_socket:host.defaults.hostContext.host_socket}},permissionPreset:command.permissionPreset??defaults?.permissionPreset,creationModel:command.provider&&command.modelId?{provider:command.provider,modelId:command.modelId}:defaults?.creationModel,initialThinkingLevel:command.thinkingLevel??defaults?.initialThinkingLevel,sessionKind:command.kind,sessionContext:host.defaults.hostContext?{...command.context,...host.defaults.hostContext}:command.context,...command.durableSessionId!==void 0?{durableSessionId:command.durableSessionId}:{},...typeof command.auto_title=="boolean"?{autoTitle:command.auto_title}:{},...command.promptSurface!==void 0?{promptSurface:command.promptSurface}:{},...command.browserEngine!==void 0?{browserEngine:command.browserEngine}:{},...command.retryFallback!==void 0?{retryFallback:command.retryFallback}:{}}}function openWithBarrier(host,command){let owner=host.writer.currentConnection();if(owner===void 0)return open(host,command);let resolveBarrier,barrier=new Promise(resolve2=>{resolveBarrier=resolve2}),opens=host.opensByConnection.get(owner)??new Set,inFlight=0;for(let pending of host.opensByConnection.values())inFlight+=pending.size;opens.add(barrier),host.opensByConnection.set(owner,opens),command.id!==void 0&&host.writer.sendOpenQueued(owner,{type:"queued",for_request:command.id,position:inFlight+1,in_flight:inFlight});let opened=open(host,command,owner);if(command.sessionPath!==void 0&&host.handoverParkedDir!==void 0){let dir=host.handoverParkedDir,sessionPath=command.sessionPath;opened.then(response=>{response===void 0&&clearHandoverParkedSession(dir,sessionPath).catch(()=>{})},()=>{})}return opened.finally(()=>{resolveBarrier(),opens.delete(barrier),opens.size===0&&host.opensByConnection.delete(owner)})}function reopenParked(host,entry){return open(host,{...parkedOpenCommand(entry),attended:!1},void 0,{reply:!1,defaults:!1,contextOverlay:entry.contextOverlay})}async function open(host,command,owner,options){let profile=validatedOpenProfile(host,command,options);if("type"in profile)return profile;let opened,assertSessionNotHeld=sessionHeldCheck(observedStarts=>host.registry.holderPids?.(observedStarts)??Promise.resolve([]));try{if(await assertSessionNotHeld(command.sessionPath),invalidSpawnedBy(command))return error(command.id,"open_session","invalid_spawned_by");let ancestry=command.spawnedBy;opened=await host.registry.openSession(ancestry?{...profile,spawnedBy:ancestry}:profile,{retainOnDisconnect:command.retain_on_disconnect===!0,attachOnly:command.expectedHostInstance!==void 0});let openedSession=opened;if(host.writer.isSessionSealed(openedSession.sessionId))return await releaseOwnedSession(host,openedSession.sessionId),opened=void 0,error(command.id,"open_session","session_output_overflow",{sessionId:openedSession.sessionId,sessionPath:openedSession.sessionPath,action:"unload_and_reopen"});let entry=host.registry.getForCommand(openedSession.sessionId,"open_session");!opened.attached&&options?.contextOverlay!==void 0&&(entry.contextOverlay=options.contextOverlay);let state=entry.worker?.snapshot?.state;if(await assertSessionNotHeld(entry.runtime?.session.sessionFile??state?.sessionFile??entry.sessionPath,entry.runtime?.session.sessionId??state?.sessionId??entry.durableSessionId),host.writer.setSessionKind(openedSession.sessionId,entry.kind),host.writer.setSessionMedia(openedSession.sessionId,toolMediaPersister(()=>liveToolMediaScope(entry))),owner!==void 0&&(host.writer.hasRegisteredConnectionCapabilities(owner)||host.writer.setConnectionCapabilities(owner,host.pendingCapabilities.get(owner)??host.connectionOptions?.capabilities??[]),host.writer.attachConnectionToSession(owner,openedSession.sessionId)),owner!==void 0){let owned=host.sessionsByConnection.get(owner)??new Map;owned.set(openedSession.sessionId,(owned.get(openedSession.sessionId)??0)+1),host.sessionsByConnection.set(owner,owned),host.attachOrder.attached(openedSession.sessionId,owner)}if(!host.bindings.has(openedSession.sessionId)){host.bindings.set(openedSession.sessionId,await host.createBinding(openedSession.sessionId,entry,host.writer,()=>{close(host,{type:"close_session",sessionId:openedSession.sessionId})},{...host.connectionOptions,capabilities:owner!==void 0?host.pendingCapabilities.get(owner)??host.connectionOptions?.capabilities??[]:host.connectionOptions?.capabilities,connectionRoles:host.connectionRoles,clientInfo:{setCapabilities:(connectionId,capabilities)=>{connectionId!==void 0&&(host.writer.setConnectionCapabilities(connectionId,capabilities),host.pendingCapabilities.set(connectionId,[...capabilities]))},connectionId:()=>host.writer.currentConnection(),relocationConnection:()=>relocationConnection(host,openedSession.sessionId),deliverTo:(connection,deliver)=>host.writer.withConnection(connection,deliver)}})),entry.worker&&(entry.worker.bindingReady=!0);let settled=()=>{host.draining&&queueMicrotask(()=>sweepDrain(host))};typeof entry.worker?.subscribeSettled=="function"?entry.worker.subscribeSettled(settled):typeof entry.runtime?.session.subscribe=="function"&&entry.runtime.session.subscribe(event=>{(event.type==="agent_settled"||event.type==="agent_idle")&&settled()}),entry.worker&&entry.worker.exited.then(async()=>{await host.finalizations.get(openedSession.sessionId)?.promise,host.bindings.delete(openedSession.sessionId),forgetSessionOwnership(host,openedSession.sessionId),host.writer.forgetSession(openedSession.sessionId)})}opened.attached?host.writer.status.publish(openedSession.sessionId,"attach","client"):(host.writer.publishSessionOpened({type:"session_opened",sessionId:openedSession.sessionId,durableSessionId:openedSession.durableSessionId,...openedSession.sessionPath!==void 0?{sessionPath:openedSession.sessionPath}:{},kind:entry.kind,cwd:entry.cwd,context:entry.context}),host.writer.status.publish(openedSession.sessionId,"open","client")),!host.draining&&owner!==void 0&&host.releasedConnections.has(owner)&&(releaseOwnerAttachment(host,owner,openedSession.sessionId),await releaseOwnedSession(host,openedSession.sessionId));let replyState=entry.worker?.snapshot?.state??(entry.runtime?buildRpcSessionState(entry.runtime.session):void 0);if(!replyState)throw new Error("Session state was not created");options?.reply!==!1&&host.writer.enqueue(opened.sessionId,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:opened.sessionId,state:replyState,...opened.attached?{attached:!0}:{}}});return}catch(cause){if(opened){if(!opened.attached){let entry=host.registry.peek(opened.sessionId);(entry?.runtime!==void 0||entry?.worker!==void 0)&&host.writer.sealRolledBackOpen(opened.sessionId,entry.sessionPath)}try{opened.attached?await releaseOwnedSession(host,opened.sessionId):await host.registry.close(opened.sessionId)}catch{}host.writer.forgetSession(opened.sessionId)}return error(command.id,"open_session",code(cause),detail(cause))}}async function detachConnection(command,connectionId,release){if(connectionId===void 0)return{id:command.id,type:"response",command:"detach_connection",success:!1,error:"detach_connection needs a socket connection"};let deferred=await release(connectionId);return{id:command.id,type:"response",command:"detach_connection",success:!0,data:{deferred:[...deferred]}}}var MOVE_SESSION_CAPABILITY="move_session",MOVE_SESSION_REVOKE_CAPABILITY="move_session_revoke",RPC_ERROR_INVALID_MOVE_REQUEST="invalid_move_request",RPC_ERROR_SESSION_OPEN_HERE="session_open_here",RPC_ERROR_MOVE_NOT_RELEASED="move_not_released",RPC_ERROR_MOVE_FAILED="move_failed";var UNLOAD_SESSION_CAPABILITY="unload_session",SUBSCRIPTION_LIMITS_CAPABILITY="subscription_limits",RESOLVE_PATH_CAPABILITY="resolve_path";function multiSessionHostCapabilities(options){return[...new Set(["multi_session","snapshot_cursor","ui_answer_ledger","dialog_observer",...options.mcpPresenters?["mcp_form_presenter_v1"]:[],"session_lifecycle","expected_host_instance","attach_session","release_attachment","release_caller_aware","reclaim_session",AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,SUBSCRIPTION_LIMITS_CAPABILITY,RESOLVE_PATH_CAPABILITY,STEER_WHEN_IDLE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,EVAL_CELLS_CAPABILITY,AUTH_KEY_VERIFY_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,TOOL_BARRIER_CAPABILITY,USER_ACTIVITY_CAPABILITY,SESSION_HELD_CAPABILITY,RESUME_SESSION_CAPABILITY,ATTENDED_CAPABILITY,OBSERVE_READS_CAPABILITY,ENTRIES_TAIL_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,DETACH_CONNECTION_CAPABILITY,UNLOAD_SESSION_CAPABILITY,MOVE_SESSION_CAPABILITY,MOVE_SESSION_REVOKE_CAPABILITY,SESSION_RELOCATION_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_STATUS_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,BROWSER_ENGINE_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,...options.warm?[WARM_CAPABILITY]:[],...toolRuntimeCapabilities(options.toolRuntime),...options.negotiated.filter(capability=>capability!=="mcp_form_presenter_v1"&&!isHostOwnedToolRuntimeCapability(capability))])]}function identityMatches(host,entry,durableSessionId,expectedHostInstance){let durable=entry.runtime?.session.sessionId??entry.worker?.snapshot?.state.sessionId??entry.durableSessionId;return typeof durableSessionId=="string"&&durableSessionId.length>0&&durableSessionId===durable&&(expectedHostInstance===void 0||expectedHostInstance===(host.defaults.hostContext?.host_instance??hostInstanceId()))}function hostStopping(host){return host.draining||host.drainExitRequested}function drainingRefusal(host,command){if(hostStopping(host))return error(command.id,command.type,"session_busy_lifecycle",{reason:"host_draining"})}function attach(host,owner,sessionId){if(!host.registry.attachSession)throw new Error("live attachment is unavailable");host.registry.attachSession(sessionId),recordAttachment(host,owner,sessionId),host.writer.status.publish(sessionId,"attach","client")}function attachSession(host,command){let draining=drainingRefusal(host,command);if(draining)return draining;let entry=host.registry.peek(command.sessionId);if(entry?.state!=="open"||!host.bindings.has(command.sessionId))return error(command.id,command.type,"unknown_session",{});if(!identityMatches(host,entry,command.durableSessionId,command.expectedHostInstance))return error(command.id,command.type,"session_identity_mismatch",{});let owner=host.writer.currentConnection();if(owner===void 0)return error(command.id,command.type,"session_not_attached",{reason:"no_connection"});try{return attach(host,owner,command.sessionId),{id:command.id,type:"response",command:command.type,success:!0,data:{sessionId:command.sessionId,attached:!0}}}catch(cause){return error(command.id,command.type,code(cause),detail(cause)??{})}}async function releaseAttachment(host,command){let owner=host.writer.currentConnection();if(owner===void 0||!host.sessionsByConnection.get(owner)?.has(command.sessionId))return error(command.id,command.type,"session_not_attached",{reason:"not_attached"});releaseOwnerAttachment(host,owner,command.sessionId);let deferred=!hostStopping(host)&&await releaseDisconnectAttachment(host,command.sessionId);return{id:command.id,type:"response",command:command.type,success:!0,data:{deferred}}}async function reclaimSession(host,command){let draining=drainingRefusal(host,command);if(draining)return draining;if(typeof command.sessionPath!="string"||command.sessionPath.length===0)return error(command.id,command.type,"unknown_session",{});let key=canonicalSessionPath(command.sessionPath),row=host.registry.list().find(candidate=>candidate.sessionPath!==void 0&&canonicalSessionPath(candidate.sessionPath)===key),entry=row&&host.registry.peek(row.sessionId);if(!row||!entry)return error(command.id,command.type,"unknown_session",{});if(entry.state!=="open"||!host.bindings.has(row.sessionId))return error(command.id,command.type,"session_busy_lifecycle",{});if(typeof command.expectedHostInstance!="string"||!identityMatches(host,entry,command.durableSessionId,command.expectedHostInstance))return error(command.id,command.type,"session_identity_mismatch",{});let owner=host.writer.currentConnection();if(owner===void 0)return error(command.id,command.type,"session_not_attached",{reason:"no_connection"});let own=host.sessionsByConnection.get(owner)?.get(row.sessionId)??0,elsewhere=Math.max(0,entry.attachments-own);if(elsewhere>0)return error(command.id,command.type,"attached_elsewhere",{attachments:elsewhere});attach(host,owner,row.sessionId);let claim=claimClose(host,row.sessionId,{drainAttachments:!0});if(host.sessionsByConnection.get(owner)?.delete(row.sessionId),host.sessionsByConnection.get(owner)?.size===0&&host.sessionsByConnection.delete(owner),connectionLeft(host,row.sessionId,owner),host.handoverParkedDir!==void 0&&entry.sessionPath!==void 0&&await clearHandoverParkedSession(host.handoverParkedDir,entry.sessionPath).catch(()=>{}),claim.finalizer){let binding2=host.bindings.get(row.sessionId);binding2?.cancelPendingExtensionUiRequests?.(),await finalizeClose(host,row.sessionId,binding2,()=>host.writer.sealLifecycle(row.sessionId,{type:"session_closed",sessionId:row.sessionId,reason:"client_close"},!0))}return host.writer.detachConnectionFromSession(owner,row.sessionId),host.writer.forgetSession(row.sessionId),{id:command.id,type:"response",command:command.type,success:!0,data:{reclaimed:!0,sessionId:row.sessionId}}}var ATTACH_GATE_EXEMPT=new Set(["get_protocol_info","list_sessions","subscribe_sessions","unsubscribe_sessions","get_subscription_limits","warm","detach_connection","open_session","attach_session","reclaim_session","get_effect_status","get_state","get_snapshot","get_messages","get_entries","get_tree","get_fork_messages","get_last_assistant_text","get_media","get_commands","get_loaded_surfaces","get_available_models","get_available_thinking_levels","get_fast_mode","get_session_stats","get_pending_inputs","get_steering_messages","get_follow_up_messages","get_auth_providers","get_provider_accounts","resolve_path","memory_report","eval_cells.list","eval_cells.peek","check_reload_veto"]);function logSafe(value){return JSON.stringify(value).slice(1,-1)}function attachmentGate(host,command){let owner=host.writer.currentConnection();if(!(owner===void 0||ATTACH_GATE_EXEMPT.has(command.type))&&!(!("sessionId"in command)||command.sessionId===void 0)&&!(command.type==="close_session"||command.type==="set_session_context"||command.type==="release_attachment")&&!host.sessionsByConnection.get(owner)?.has(command.sessionId)){if(process.env.SENPI_RPC_REQUIRE_ATTACH==="1")return error(command.id,command.type,"session_not_attached",{reason:"this connection is not attached to that session",action:"attach first with attach_session { sessionId, durableSessionId } or open_session { sessionPath }"});process.stderr.write(`senpi rpc host: ${command.type} on ${logSafe(command.sessionId)} from a connection not attached to it (refused from the next release)
26
26
  `)}}import{isAbsolute as isAbsolute3,join as join5}from"node:path";import{copyFile,mkdir as mkdir2,readdir as readdir2,rename,rm as rm2,writeFile as writeFile2}from"node:fs/promises";import{basename,dirname,join as join2,posix,relative,sep}from"node:path";import{realpath}from"node:fs/promises";import{resolve}from"node:path";async function realSessionPath(path){let absolute=resolve(path);try{return await realpath(absolute)}catch{return absolute}}var lockKey=resolvedPath=>`session-move:${resolvedPath}`,pathChains=new Map;function orderedRealPath(path){let key=resolve(path),next=(pathChains.get(key)??Promise.resolve("")).then(()=>realSessionPath(path));return pathChains.set(key,next),next.then(()=>{pathChains.get(key)===next&&pathChains.delete(key)}),next}var moveLockKey=async sessionFile=>lockKey(await orderedRealPath(sessionFile));async function withSessionMoveLock2(sessionFile,step,guard){let path=await orderedRealPath(sessionFile);return serializeByKey(lockKey(path),async()=>{await guard?.();let sessionId=headerSessionId(await loadEntriesFromFileAsync(path));return sessionId===void 0?step():withSessionMoveLock(path,sessionId,step)})}function exportSessionForMove(options){return withSessionMoveLock2(options.sessionFile,async()=>(await options.lockedGuard?.(),writeMoveBundle(options)),options.guard)}var MovedStateMissingError=class extends Error{constructor(dir){super(`The extension state the move release staged is missing (${dir}); the session was not exported without it. Finish the move as declined to take the session back, then release it again.`),this.name="MovedStateMissingError"}};async function writeMoveBundle(options){let{sessionFile}=options,moveId=parseMoveId(options.moveId),entries=await loadEntriesFromFileAsync(sessionFile),sessionId=parsePlainId(headerSessionId(entries),"session id"),holders=await liveSessionHolders(sessionFile,sessionId);if(holders.length>0)throw new SessionHeldError(sessionFile,holders);let ownership=sessionOwnership(entries);if(!ownership.writable&&!(ownership.state==="moving"&&ownership.moveId===moveId))throw new SessionMovedAwayError(sessionFile,ownership);ownership.writable&&(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_RELEASED,{reason:"move",move_id:moveId,session_id:sessionId,target:options.target,released_at:new Date().toISOString()});let stateDir=typeof options.extensionStateDir=="function"?await options.extensionStateDir():options.extensionStateDir;if(stateDir!==void 0&&!await pathExists(stateDir))throw new MovedStateMissingError(stateDir);let staging=`${options.bundleDir}.partial-${process.pid}`;await rm2(staging,{recursive:!0,force:!0}),await mkdir2(join2(staging,dirname(SESSION_BUNDLE_PATH)),{recursive:!0}),await copyFile(sessionFile,join2(staging,SESSION_BUNDLE_PATH));let sidecars=await copySidecars(dirname(sessionFile),sessionId,staging),stateFiles=await copyExtensionState(stateDir,staging),manifest={format:MOVE_BUNDLE_FORMAT,moveId,sessionId,sessionFileName:basename(sessionFile),sourceCwd:await readSessionCwd(sessionFile)??"",repository:await readRecordedRepositoryIdentity(sessionFile),session:{path:SESSION_BUNDLE_PATH,sha256:await sha256File(join2(staging,SESSION_BUNDLE_PATH))},sidecars,droppedUserMessages:[...options.droppedUserMessages],payloads:stateFiles.length>0?[{kind:EXTENSION_STATE_PAYLOAD,files:stateFiles}]:[]};return await writeFile2(join2(staging,MANIFEST_FILE),`${JSON.stringify(manifest,null,1)}
27
27
  `),await rm2(options.bundleDir,{recursive:!0,force:!0}),await rename(staging,options.bundleDir),manifest}async function copySidecars(sessionDir,sessionId,staging){let sources=[],extensions=join2(sessionDir,"extensions"),sidecarName=`${encodedSessionId(sessionId)}.json`;if(await pathExists(extensions))for(let extension of await readdir2(extensions,{withFileTypes:!0})){let file=join2(extensions,extension.name,sidecarName);extension.isDirectory()&&await pathExists(file)&&sources.push(file)}sources.push(...await filesUnder(join2(sessionDir,"resident-blobs",sessionId)));let files=[];for(let source of sources){let path=bundlePath("files",sessionDir,source);await mkdir2(dirname(join2(staging,path)),{recursive:!0}),await copyFile(source,join2(staging,path)),files.push({path,sha256:await sha256File(join2(staging,path))})}return files}async function copyExtensionState(dir,staging){if(dir===void 0)return[];let files=[];for(let source of await filesUnder(dir)){let path=bundlePath("state",dir,source);await mkdir2(dirname(join2(staging,path)),{recursive:!0}),await copyFile(source,join2(staging,path)),files.push({path,sha256:await sha256File(join2(staging,path))})}return files}function bundlePath(prefix,from,source){return posix.join(prefix,...relative(from,source).split(sep))}async function filesUnder(dir){if(!await pathExists(dir))return[];let files=[];for(let entry of await readdir2(dir,{withFileTypes:!0})){let path=join2(dir,entry.name);files.push(...entry.isDirectory()?await filesUnder(path):[path])}return files}import{rm as rm3}from"node:fs/promises";var hook;function moveStep(step){hook?.(step)}async function requeueInput(sessionFile,moveId,texts){if(texts.length===0)return;let sessionManager=await SessionManager.openAsync(sessionFile),next=0,inputs=new SessionPendingInputs({sessionManager,nextQueuedId:()=>`move-${moveId}-${next++}`});for(let[index,text2]of texts.entries())await inputs.admit({clientMessageId:`move:${moveId}:${index}`,text:text2,mode:"followUp"},()=>{})}var MoveMismatchError=class extends Error{constructor(expected,found,what){super(`The answer is about move ${expected}, but ${what} belongs to move ${found}; nothing was changed. Finish each move with its own answer and bundle.`),this.code="move_mismatch",this.name="MoveMismatchError"}},MoveAlreadyMovedError=class extends Error{constructor(moveId){super(`The receiver revoked its copy for move ${moveId}, but this session file was already marked moved by an earlier accepted answer; nothing was changed and no copy is writable. Copy the session to a new thread to keep working from it.`),this.code="move_already_moved",this.name="MoveAlreadyMovedError"}};function finishMove(options){return withSessionMoveLock2(options.sessionFile,()=>settleMove(options),options.guard)}async function settleMove(options){let{sessionFile,bundleDir,moveId,answer:answer3}=options;if(await pathExists(bundleDir)){let bundled=(await readManifest(bundleDir)).moveId;if(bundled!==moveId)throw new MoveMismatchError(moveId,bundled,"the kept bundle")}let entries=await loadEntriesFromFileAsync(sessionFile),ownership=sessionOwnership(entries);if(ownership.writable){reclaimed(entries,moveId)&&await requeueDroppedInput(sessionFile,bundleDir),await discardMoveFiles(sessionFile,bundleDir,moveId);return}if(ownership.moveId!==moveId)throw new MoveMismatchError(moveId,ownership.moveId,"the session file");if(ownership.state==="moved"){if("revoked"in answer3)throw new MoveAlreadyMovedError(moveId);await discardMoveFiles(sessionFile,bundleDir,moveId);return}let sessionId=headerSessionId(entries)??"";switch(answer3.state){case"receiving":return;case"accepted":if("revoked"in answer3){await takeBack(sessionFile,bundleDir,{move_id:moveId,session_id:sessionId,reason:"revoked"});break}(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_MOVED,{move_id:moveId,session_id:sessionId,target:ownership.target,moved_at:new Date().toISOString()}),moveStep("finish:recorded");break;case"declined":case"failed":await takeBack(sessionFile,bundleDir,{move_id:moveId,session_id:sessionId,reason:answer3.state,detail:answer3.reason});break;default:{let unreachable=answer3;throw new Error(`Unknown move answer ${JSON.stringify(unreachable)}`)}}moveStep("finish:requeued"),await discardMoveFiles(sessionFile,bundleDir,moveId)}async function takeBack(sessionFile,bundleDir,data2){(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_RECLAIMED,{...data2,reclaimed_at:new Date().toISOString()}),moveStep("finish:recorded"),await requeueDroppedInput(sessionFile,bundleDir)}async function discardMoveFiles(sessionFile,bundleDir,moveId){await rm3(bundleDir,{recursive:!0,force:!0}),await rm3(outgoingStateDir(sessionFile,moveId),{recursive:!0,force:!0})}function reclaimed(entries,moveId){return entries.some(entry=>entry.type==="custom"&&entry.customType===SESSION_RECLAIMED&&entry.data?.move_id===moveId)}async function requeueDroppedInput(sessionFile,bundleDir){if(!await pathExists(bundleDir))return;let manifest=await readManifest(bundleDir);await requeueInput(sessionFile,manifest.moveId,manifest.droppedUserMessages)}import{copyFile as copyFile2,mkdir as mkdir4,readdir as readdir3,rm as rm4}from"node:fs/promises";import{dirname as dirname2,join as join4}from"node:path";import{mkdir as mkdir3,readFile as readFile2,rename as renameFile,writeFile as writeFile3}from"node:fs/promises";import{join as join3}from"node:path";function parseLanding(value){if(typeof value!="object"||value===null)return{};let{target,committing}=value;return{...typeof target=="string"?{target}:{},...committing===!0?{committing:!0}:{}}}function settledLanding(record,committing,outcome){if(record?.state==="receiving"&&committing)return outcome==="absent"?{state:"failed",reason:"import_failed"}:outcome==="revoked"?{state:"accepted",revoked:!0}:{state:"accepted"};if(record?.state==="accepted"&&!("revoked"in record)&&outcome==="revoked")return{state:"accepted",revoked:!0}}function landsAt(record,landing,target){return record?.state==="receiving"&&landing.committing!==!0&&landing.target===target}function landedElsewhere(record,landing){let stored=landing.target;return record?.state==="accepted"&&"revoked"in record?"it was revoked here and never lands again":record?.state==="receiving"&&landing.committing===!0?"an import of it stopped mid-commit, and a move lands once; only the file it landed is accepted":record?.state==="accepted"?"it already landed here once, and a move lands once (a deleted copy is gone; copy the session to a new thread instead)":record?.state==="receiving"&&stored===void 0?"an older version started receiving it and where it landed is unknown; only its already landed file is accepted":stored===void 0?void 0:`it lands only as ${stored}`}var LOCK_OPTIONS={realpath:!1,stale:1e4,update:2e3,retries:0},LOCK_WAIT_MS=15e3,MoveRecordUnlockedError=class extends Error{constructor(file){super(`Move record ${file} was written outside its lock; the write was refused.`),this.code="move_record_unlocked",this.name="MoveRecordUnlockedError"}},MoveRecordLocks=class{#held=new Map;async hold(file,fn){let held=await acquireMoveRecordLock(file);this.#held.set(file,held);try{return await fn()}finally{this.#held.delete(file),await held.release().catch(()=>{})}}assertHeld(file){let held=this.#held.get(file);if(held===void 0)throw new MoveRecordUnlockedError(file);held.assertHeld()}};async function acquireMoveRecordLock(file){let startedAt=Date.now();for(let attempt=0;;attempt+=1)try{return await lockWithLossHandling(file,{...LOCK_OPTIONS,lockfilePath:`${file}.lock`})}catch(error2){if(!isLockError(error2))throw error2;let waited=Date.now()-startedAt;if(waited>=LOCK_WAIT_MS)throw new Error(`Move record ${file} stayed locked for ${waited}ms`,{cause:error2});let delay2=Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS*2**attempt,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS);await new Promise(resolve2=>setTimeout(resolve2,delay2))}}var READY_TTL_MS=10*6e4,FINAL_STATES=["accepted","declined","failed"],MoveFencedError=class extends Error{constructor(moveId,record,detail2){super(`Move ${moveId} can no longer be imported here: ${detail2??`it was already answered (${record?.state??"no record"})`}.`),this.code="move_fenced",this.name="MoveFencedError",this.record=record}},DECLINE_REASONS=["no_record","expired","cancelled","chunk_without_ready","repository"],FAIL_REASONS=["bundle_invalid","import_failed"];function parseMoveStatus(value){let record=parseRecord(value);return record?.state==="ready"?void 0:record}function parseRecord(value){if(typeof value!="object"||value===null)return;let{state,reason}=value;if(state==="accepted"&&value.revoked===!0)return{state,revoked:!0};if(state==="receiving")return{state};if(state==="accepted")return{state};let{expiresAt}=value;if(state==="ready"&&typeof expiresAt=="string"&&!Number.isNaN(Date.parse(expiresAt)))return{state,expiresAt};let decline=DECLINE_REASONS.find(known=>known===reason);if(state==="declined"&&decline!==void 0)return{state,reason:decline};let fail2=FAIL_REASONS.find(known=>known===reason);if(state==="failed"&&fail2!==void 0)return{state,reason:fail2}}var MoveLedger=class{#locks=new MoveRecordLocks;constructor(dir,options={}){this.dir=dir,this.now=options.now??Date.now}prepare(moveId){return this.locked(moveId,async()=>{let record=await this.current(moveId);if(record===void 0){let ready={state:"ready",expiresAt:new Date(this.now()+READY_TTL_MS).toISOString()};return await this.write(moveId,ready),ready}if(record.state==="ready"||record.state==="receiving"||record.state==="accepted")return record;throw new MoveFencedError(moveId,record)})}beginReceive(moveId,target){return this.locked(moveId,async()=>{let record=await this.current(moveId),landing=await this.landing(moveId);if(record?.state==="ready"){await this.write(moveId,{state:"receiving"},{target});return}if(landsAt(record,landing,target))return;if(record?.state==="receiving"||record?.state==="accepted")throw new MoveFencedError(moveId,record,landedElsewhere(record,landing));if(record!==void 0)throw new MoveFencedError(moveId,record);let declined={state:"declined",reason:"chunk_without_ready"};throw await this.write(moveId,declined),new MoveFencedError(moveId,declined)})}expire(moveId){return this.locked(moveId,()=>this.current(moveId))}answerStatus(moveId,here){return this.locked(moveId,async()=>{let record=await this.reconcile(moveId,await this.current(moveId),here.landed);if(here.revoked===!0)return{state:"accepted",revoked:!0};if(record?.state==="accepted")return record;if(here.movedIn)return{state:"accepted"};if(record?.state==="ready")return{state:"receiving"};if(record!==void 0)return record;let declined={state:"declined",reason:"no_record"};return await this.write(moveId,declined),declined})}decline(moveId,reason){return this.settle(moveId,{state:"declined",reason},["receiving"])}fail(moveId,reason,options={}){return this.locked(moveId,async()=>await options.unlessLanded?.()?this.current(moveId):this.settleLocked(moveId,{state:"failed",reason},[]))}commit(moveId,target,rename2,prepare){return this.locked(moveId,async()=>{let record=await this.read(moveId),landing=await this.landing(moveId);if(!landsAt(record,landing,target))throw new MoveFencedError(moveId,record,landedElsewhere(record,landing));await prepare?.(),await this.write(moveId,{state:"receiving"},{target,committing:!0}),moveStep("import:stamped");let result=await rename2();return moveStep("import:renamed"),await this.write(moveId,{state:"accepted"},{target}),result})}confirmLanded(moveId,target,revoked){return this.locked(moveId,async()=>{let record=await this.read(moveId),landing=await this.landing(moveId);if(!(record===void 0||record.state==="receiving"||record.state==="accepted")||landing.target!==void 0&&landing.target!==target)throw new MoveFencedError(moveId,record,landedElsewhere(record,landing));let marked=record?.state==="accepted"&&"revoked"in record;record?.state==="accepted"&&(marked||!revoked)||await this.write(moveId,revoked?{state:"accepted",revoked:!0}:{state:"accepted"},{target})})}async reconcile(moveId,record,landed){let{target,committing}=await this.landing(moveId);if(landed===void 0||target===void 0)return record;let next=settledLanding(record,committing===!0,await landed(target));return next===void 0?record:(await this.write(moveId,next,{target}),next)}markRevoked(moveId){return this.locked(moveId,async()=>{let record=await this.read(moveId);if(record!==void 0&&record.state!=="receiving"&&record.state!=="accepted"||record?.state==="accepted"&&"revoked"in record)return;let{target}=await this.landing(moveId);await this.write(moveId,{state:"accepted",revoked:!0},target===void 0?{}:{target})})}settle(moveId,next,keeps){return this.locked(moveId,()=>this.settleLocked(moveId,next,keeps))}async settleLocked(moveId,next,keeps){let record=await this.current(moveId);return record!==void 0&&(FINAL_STATES.includes(record.state)||keeps.includes(record.state))||record!==void 0&&(await this.landing(moveId)).committing===!0?record:(await this.write(moveId,next),next)}async current(moveId){let record=await this.read(moveId);if(record?.state!=="ready"||this.now()<Date.parse(record.expiresAt))return record;let expired={state:"declined",reason:"expired"};return await this.write(moveId,expired),expired}path(moveId){return join3(this.dir,`${parseMoveId(moveId)}.json`)}async raw(moveId){try{return JSON.parse(await readFile2(this.path(moveId),"utf8"))}catch(error2){if(error2.code==="ENOENT")return;throw error2}}async read(moveId){let value=await this.raw(moveId);if(value===void 0)return;let record=parseRecord(value);if(record===void 0)throw new Error(`Move record ${this.path(moveId)} is not a move record`);return record}async landing(moveId){return parseLanding(await this.raw(moveId))}async write(moveId,record,landing={}){let file=this.path(moveId),temp=`${file}.${process.pid}.tmp`;this.#locks.assertHeld(file),await writeFile3(temp,`${JSON.stringify({...record,...landing,at:new Date().toISOString()})}
28
28
  `),this.#locks.assertHeld(file),await renameFile(temp,file)}locked(moveId,fn){let file=this.path(moveId);return serializeByKey(file,async()=>(await mkdir3(this.dir,{recursive:!0}),this.#locks.hold(file,fn)))}};var RevokeMismatchError=class extends Error{constructor(moveId){super(`This session file is not the copy this device imported for move ${moveId}; nothing was changed. Revoke only the copy that move brought in, with that move's id.`),this.code="move_mismatch",this.name="RevokeMismatchError"}},REVOKED="revoked";function revokeImportedMove(options){return withSessionMoveLock2(options.sessionFile,async()=>{await seal(options.sessionFile,options.moveId),moveStep("revoke:sealed"),await options.ledger.markRevoked(options.moveId),moveStep("revoke:marked")},options.guard)}async function seal(sessionFile,moveId){let entries=await loadEntriesFromFileAsync(sessionFile),sessionId=headerSessionId(entries),ownership={writable:!0},latest;for(let entry of entries){let step=ownershipStep(ownership,entry,sessionId);step.kind==="apply"&&(ownership=step.next,latest=entry)}let ofThisMove=latest!==void 0&&data(latest,"move_id")===moveId;if(!(ofThisMove&&latest?.customType===SESSION_MOVED&&data(latest,"reason")===REVOKED)){if(!(ownership.writable&&ofThisMove&&latest?.customType===SESSION_MOVED_IN))throw new RevokeMismatchError(moveId);(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_MOVED,{move_id:moveId,session_id:sessionId??"",target:data(latest,"from")??"",reason:REVOKED,moved_at:new Date().toISOString()})}}function data(entry,key){if(typeof entry.data!="object"||entry.data===null)return;let value=entry.data[key];return typeof value=="string"?value:void 0}var MoveRefusedError=class extends Error{constructor(targetCwd,sourceCwd){super(`${targetCwd} is not the same repository the session was recorded in (${sourceCwd}). Pick a checkout of the same repository, or copy the session into this folder instead.`),this.name="MoveRefusedError",this.code="move_repository_mismatch"}},MoveTargetOccupiedError=class extends Error{constructor(target){super(`A session that can still be written already sits at ${target}; the moved session was not imported over it. Close or move that session first, then send it again.`),this.code="move_target_occupied",this.name="MoveTargetOccupiedError"}},movedInFor=async(file,moveId)=>(await loadEntriesFromFileAsync(file)).some(entry=>entry.type==="custom"&&entry.customType===SESSION_MOVED_IN&&entry.data?.move_id===moveId);async function importOutcome(file,moveId){let outcome="absent";for(let entry of await loadEntriesFromFileAsync(file)){if(entry.type!=="custom")continue;let data2=entry.data;data2?.move_id===moveId&&(entry.customType===SESSION_MOVED_IN?outcome="moved_in":outcome==="moved_in"&&entry.customType===SESSION_MOVED&&data2.reason===REVOKED&&(outcome="revoked"))}return outcome}var StatusPathMismatchError=class extends Error{constructor(moveId,sessionFile){super(`${sessionFile} is not the copy this device imported for move ${moveId}; nothing was answered. Pass the session_path import returned for this move, or leave sessionPath out to answer from this device's record.`),this.code="move_mismatch",this.name="StatusPathMismatchError"}};async function answerMoveStatus(ledger,moveId,sessionFile){let landed=async target=>await pathExists(target)?importOutcome(target,moveId):"absent";return sessionFile===void 0||!await pathExists(sessionFile)?ledger.answerStatus(moveId,{movedIn:!1,landed}):serializeByKey(await moveLockKey(sessionFile),async()=>{let outcome=await importOutcome(sessionFile,moveId);if(outcome==="absent")throw new StatusPathMismatchError(moveId,sessionFile);return ledger.answerStatus(moveId,{movedIn:!0,revoked:outcome==="revoked",landed})})}async function importMovedSession(options){let manifest=await readManifest(options.bundleDir),targetCwd=resolvePath(options.targetCwd),sessionDir=options.sessionDir?normalizePath(options.sessionDir):getDefaultSessionDir(targetCwd),target=join4(sessionDir,manifest.sessionFileName),landed=async()=>await pathExists(target)&&await movedInFor(target,manifest.moveId);if(await landed())return await options.ledger.confirmLanded(manifest.moveId,target,await importOutcome(target,manifest.moveId)==="revoked"),{sessionFile:target};try{await verifyBundle(options.bundleDir,manifest)}catch(error2){throw error2 instanceof MoveBundleInvalidError&&await options.ledger.fail(manifest.moveId,"bundle_invalid",{unlessLanded:landed}),error2}let read=options.readIdentity??readRepositoryIdentity;if(compareRepositoryIdentities(manifest.repository,await read(targetCwd))!=="same")throw await landed()||await options.ledger.decline(manifest.moveId,"repository"),new MoveRefusedError(targetCwd,manifest.sourceCwd);await options.ledger.beginReceive(manifest.moveId,target),moveStep("import:received");let staging=join4(sessionDir,".move-staging",encodeURIComponent(manifest.moveId));try{let staged=await stage(options.bundleDir,manifest,staging,options.from??""),sessionFile=await options.ledger.commit(manifest.moveId,target,()=>rebindSessionFile(staged,targetCwd,sessionDir),async()=>{await replacePredecessor(target,manifest.sessionId,sessionDir),await placeExtensionState(staging,manifest,movedStateDir(target,manifest.moveId))});return moveStep("import:accepted"),await rm4(staging,{recursive:!0,force:!0}),{sessionFile}}catch(error2){throw error2 instanceof MoveFencedError||await options.ledger.fail(manifest.moveId,error2 instanceof MoveBundleInvalidError?"bundle_invalid":"import_failed",{unlessLanded:landed}),error2}}async function replacePredecessor(target,sessionId,sessionDir){if(!await pathExists(target))return;let entries=await loadEntriesFromFileAsync(target);if(headerSessionId(entries)!==sessionId||sessionOwnership(entries).writable)throw new MoveTargetOccupiedError(target);let extensions=join4(sessionDir,"extensions");if(await pathExists(extensions))for(let extension of await readdir3(extensions,{withFileTypes:!0}))extension.isDirectory()&&await rm4(join4(extensions,extension.name,`${encodedSessionId(sessionId)}.json`),{force:!0});await rm4(join4(sessionDir,"resident-blobs",sessionId),{recursive:!0,force:!0}),await rm4(target,{force:!0})}var STAGED_PAYLOADS=".payloads",extensionStateFiles=manifest=>manifest.payloads.filter(payload=>payload.kind===EXTENSION_STATE_PAYLOAD).flatMap(p=>p.files);async function stagePayloads(bundleDir,manifest,staging){for(let file of manifest.payloads.flatMap(payload=>payload.files)){let to=join4(staging,STAGED_PAYLOADS,file.path);if(await mkdir4(dirname2(to),{recursive:!0}),await copyFile2(join4(bundleDir,file.path),to),await sha256File(to)!==file.sha256)throw new MoveBundleInvalidError(`${file.path} changed in transit`)}}async function placeExtensionState(staging,manifest,dir){let files=extensionStateFiles(manifest);if(files.length!==0){await rm4(dir,{recursive:!0,force:!0});for(let file of files){let to=join4(dir,file.path.slice(EXTENSION_STATE_PREFIX.length));await mkdir4(dirname2(to),{recursive:!0}),await copyFile2(join4(staging,STAGED_PAYLOADS,file.path),to)}}}async function stage(bundleDir,manifest,staging,from){let file=join4(staging,manifest.sessionFileName);if(!(await pathExists(file)&&await movedInFor(file,manifest.moveId))){await rm4(staging,{recursive:!0,force:!0});for(let item of[manifest.session,...manifest.sidecars]){let to=item===manifest.session?file:join4(staging,item.path.replace(/^files\//,""));await mkdir4(dirname2(to),{recursive:!0}),await copyFile2(join4(bundleDir,item.path),to)}await stagePayloads(bundleDir,manifest,staging),(await SessionManager.openAsync(file,staging)).appendCustomEntry(SESSION_MOVED_IN,{move_id:manifest.moveId,session_id:manifest.sessionId,from,bundle_sha256:manifest.session.sha256,moved_in_at:new Date().toISOString()})}return await requeueInput(file,manifest.moveId,manifest.droppedUserMessages),file}var CORE_CODES=new Set(["move_fenced","move_bundle_invalid","move_repository_mismatch","move_target_occupied","move_mismatch","move_already_moved","session_moved_away"]),RENAMED_CODES={ESESSIONHELD:"session_held"};function plainMoveId(value){try{return parseMoveId(value)}catch{return}}var text=value=>typeof value=="string"&&value.trim()!=="";function parse(raw){let{op}=raw;if(op==="import"){if(!text(raw.bundleDir)||!text(raw.cwd)||!isAbsolute3(raw.bundleDir)||!isAbsolute3(raw.cwd))return"import needs bundleDir and cwd as absolute paths.";let from=typeof raw.from=="string"?raw.from:void 0;return raw.from!==void 0&&from===void 0?"from must be a string.":{op,bundleDir:raw.bundleDir,cwd:raw.cwd,from:from??""}}let id=plainMoveId(raw.moveId);if(id===void 0)return"moveId must be a plain id: a letter or digit, then letters, digits, '.', '_' or '-', at most 128 characters.";switch(op){case"prepare":case"cancel":return{op,moveId:id};case"status":{let sessionPath=text(raw.sessionPath)?raw.sessionPath:void 0;return raw.sessionPath!==void 0&&sessionPath===void 0?"sessionPath must be a non-empty string.":{op,moveId:id,sessionPath}}case"export":{let dropped=raw.droppedUserMessages??[];return!text(raw.sessionPath)||!text(raw.target)?"export needs sessionPath and target.":!Array.isArray(dropped)||!dropped.every(item=>typeof item=="string")?"droppedUserMessages must be the dropped.user_messages strings release_session returned.":{op,sessionPath:raw.sessionPath,moveId:id,target:raw.target,dropped}}case"finish":{let answer3=parseMoveStatus(raw.answer);return!text(raw.sessionPath)||answer3===void 0?"finish needs sessionPath and the receiver's answer from status (receiving, accepted, declined or failed).":{op,sessionPath:raw.sessionPath,moveId:id,answer:answer3}}case"revoke":return text(raw.sessionPath)?{op,sessionPath:raw.sessionPath,moveId:id}:"revoke needs sessionPath, the copy this host imported for the move.";default:return'op must be one of "prepare", "cancel", "status", "export", "import", "finish" or "revoke".'}}var wireRecord=record=>record.state==="ready"?{state:"ready",expires_at:record.expiresAt}:record;async function moveSession(port,command){let raw={...command},parsed=parse(raw);if(typeof parsed=="string")return refusal2(command.id,RPC_ERROR_INVALID_MOVE_REQUEST,parsed);let root=join5(port.agentDir,"session-moves"),ledger=new MoveLedger(join5(root,"ledger")),outgoing=moveId=>join5(root,"outgoing",moveId);try{return answer(command.id,await run(parsed,port,ledger,outgoing))}catch(cause){if(cause instanceof MoveRefusal)return refusal2(command.id,cause.code,cause.message);let code2=typeof cause=="object"&&cause!==null&&"code"in cause?cause.code:void 0,detail2=cause instanceof Error?cause.message:String(cause);return refusal2(command.id,typeof code2=="string"?RENAMED_CODES[code2]??(CORE_CODES.has(code2)?code2:RPC_ERROR_MOVE_FAILED):RPC_ERROR_MOVE_FAILED,detail2)}}async function run(parsed,port,ledger,outgoing){switch(parsed.op){case"prepare":return wireRecord(await ledger.prepare(parsed.moveId));case"cancel":return wireRecord(await ledger.decline(parsed.moveId,"cancelled"));case"status":return answerMoveStatus(ledger,parsed.moveId,parsed.sessionPath);case"export":{let sessionFile=await orderedRealPath(parsed.sessionPath),bundleDir=outgoing(parsed.moveId),manifest=await exportSessionForMove({sessionFile,moveId:parsed.moveId,target:parsed.target,droppedUserMessages:parsed.dropped,bundleDir,extensionStateDir:()=>sealedOutgoingStateDir(sessionFile,parsed.moveId),guard:async()=>{await refuseOpenHere(port,sessionFile,"This session is open on this host. Release it with release_session reason move and this moveId first."),await refuseUnlessSealedFor(sessionFile,parsed.moveId)},lockedGuard:()=>refuseUnlessSealedFor(sessionFile,parsed.moveId)});return{move_id:manifest.moveId,session_id:manifest.sessionId,bundle_dir:bundleDir,files:1+manifest.sidecars.length}}case"import":{let cwd=resolvePath(parsed.cwd),sessionDir=getDefaultSessionDir(cwd,port.agentDir),{sessionFile}=await importMovedSession({bundleDir:normalizePath(parsed.bundleDir),targetCwd:cwd,ledger,sessionDir,from:parsed.from}),sessionId=headerSessionId(await loadEntriesFromFileAsync(sessionFile));if(sessionId===void 0)throw new Error(`The imported session at ${sessionFile} has no id in its header.`);return{session_id:sessionId,session_path:sessionFile}}case"finish":{let sessionFile=await orderedRealPath(parsed.sessionPath);return await finishMove({sessionFile,bundleDir:outgoing(parsed.moveId),moveId:parsed.moveId,answer:parsed.answer,guard:()=>refuseOpenHere(port,sessionFile,"This session is open on this host, so its runtime would not see the move end. Close it here, then finish the move.")}),ownershipOf(sessionFile)}case"revoke":{let sessionFile=await orderedRealPath(parsed.sessionPath);return await revokeImportedMove({sessionFile,moveId:parsed.moveId,ledger,guard:()=>refuseOpenHere(port,sessionFile,"This session is open on this host, so its runtime would not see the revoke. Close it here, then revoke the move.")}),ownershipOf(sessionFile)}}}async function ownershipOf(sessionFile){let ownership=sessionOwnership(await loadEntriesFromFileAsync(sessionFile));return{ownership:ownership.writable?"writable":ownership.state}}var MoveRefusal=class extends Error{constructor(code2,detail2){super(detail2),this.name="MoveRefusal",this.code=code2}};async function refuseUnlessSealedFor(sessionFile,moveId){let ownership=sessionOwnership(await loadEntriesFromFileAsync(sessionFile));if(ownership.writable||ownership.state!=="moving"||ownership.moveId!==moveId)throw new MoveRefusal(RPC_ERROR_MOVE_NOT_RELEASED,"This session file is not sealed for this move. Release it with release_session reason move and this moveId first; that also hands back its queued input.")}async function refuseOpenHere(port,sessionFile,detail2){if((await Promise.all(port.hostedPaths().map(path=>realSessionPath(path)))).includes(sessionFile))throw new MoveRefusal(RPC_ERROR_SESSION_OPEN_HERE,detail2)}function answer(id,data2){return"refuse"in data2?refusal2(id,data2.refuse,data2.detail):{id,type:"response",command:"move_session",success:!0,data:data2}}function refusal2(id,code2,detail2){return{id,type:"response",command:"move_session",success:!1,error:code2,errorCode:code2,errorData:{detail:detail2}}}import{rm as rm5}from"node:fs/promises";var NOTHING_DROPPED={deliveries:[],user_messages:[]};function takeQueuedInput(session){let admittedBefore=session.externalAdmission.list().pending,cleared=session.clearQueue({abortWillFollow:!0}),stillAdmitted=new Set(session.externalAdmission.list().pending);return{deliveries:admittedBefore.filter(deliveryId=>!stillAdmitted.has(deliveryId)),user_messages:cleared.ordered.map(queued=>queued.text)}}async function abortAndSettle(port,sessionId,session){session.abortBash();let stopStarts=session.subscribe(event=>{event.type==="agent_start"&&session.abort()}),deadline,expired=new Promise(resolve2=>{deadline=setTimeout(resolve2,1e4)});try{await Promise.race([Promise.allSettled([session.abort().then(()=>session.waitForIdle()),port.otherRequestsSettled(sessionId),...port.pendingPrompts(sessionId)]),expired])}finally{clearTimeout(deadline),stopStarts()}}var SESSION_RELEASED_ENTRY_TYPE="session_released",RELEASED_ADMISSION_CLOSED="release_session handed this session to another runtime; deliver there instead (admission is closed here)",RELEASE_QUEUED_HINT="queued user input is still owed a turn; release with interrupt: true to take it out and receive it in dropped.user_messages";async function releaseSession(port,command){let validMove=command.reason==="move"&&isMoveId(command.moveId);if(command.reason!=="takeover"&&!validMove)return refusal3(command.id,RPC_ERROR_INVALID_RELEASE_REASON);if(port.draining())return refusal3(command.id,RPC_ERROR_HOST_DRAINING);let first=releasable(port,command,void 0);if(!("session"in first))return first;if(command.reason==="move"&&!isPlainId(first.session.sessionManager.getSessionId()))return refusal3(command.id,RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"session_id_not_plain"});let busy=busySignals(port,command.sessionId,first.session),interrupted=busy.length>0;if(interrupted&&command.interrupt!==!0)return refusal3(command.id,busyCode(busy),{attachments:first.attachments,...busyData(busy)});let admission=first.session.externalAdmission,dropped=NOTHING_DROPPED,answer3,stagedState,sealed=!1;try{interrupted&&(admission.close(RELEASED_ADMISSION_CLOSED),dropped=takeQueuedInput(first.session),await abortAndSettle(port,command.sessionId,first.session),await first.session.whenQueueClearRecorded());let manager=first.session.sessionManager;if(manager.isTranscriptFlushed()||await manager.persistHeaderNow(),command.reason==="move"){let moveId=parseMoveId(command.moveId);stagedState=await prepareOutgoingState(first.sessionPath,moveId);let[failed]=await first.session.extensionRunner.emitSessionMove({type:"session_move_export",moveId,dir:stagedState.dir});if(failed!==void 0)throw new Error(`${failed.extensionPath} could not write its state for the move: ${failed.error}`)}return answer3=await claimAndRelease(port,command,interrupted,dropped,stagedState?.attempt,()=>{sealed=!0}),answer3}catch(cause){return cause instanceof SessionMovedAwayError?(answer3=refusal3(command.id,cause.code,{detail:cause.message,...interrupted?{interrupted:!0,dropped}:{}}),answer3):(answer3=refusal3(command.id,RPC_ERROR_RELEASE_FAILED,{detail:cause instanceof Error?cause.message:String(cause),...interrupted?{interrupted:!0,dropped}:{}}),answer3)}finally{answer3?.success!==!0&&(admission.reopen(),stagedState!==void 0&&!sealed&&await rm5(stagedState.dir,{recursive:!0,force:!0}))}}async function claimAndRelease(port,command,interrupted,dropped,stateAttempt,onSealed){let taken=interrupted?{interrupted:!0,dropped}:void 0,ready=releasable(port,command,taken);if(!("session"in ready))return ready;let stillBusy=busySignals(port,command.sessionId,ready.session);if(stillBusy.length>0)return refusal3(command.id,busyCode(stillBusy),{attachments:ready.attachments,...busyData(stillBusy),interrupted,...taken});let admission=ready.session.externalAdmission;admission.close(RELEASED_ADMISSION_CLOSED);try{ready.session.sessionManager.appendCustomEntry(SESSION_RELEASED_ENTRY_TYPE,{reason:command.reason,...command.reason==="move"?{move_id:command.moveId,...stateAttempt===void 0?{}:{[STATE_ATTEMPT_FIELD]:stateAttempt},target:command.target??"",session_id:ready.session.sessionManager.getSessionId()}:{},interrupted,attachments:ready.attachments,host_instance:port.hostInstance??null,released_at:new Date().toISOString()})}catch(cause){throw admission.reopen(),cause}return onSealed(),await port.tearDown(command.sessionId,ready.sessionPath)?{id:command.id,type:"response",command:"release_session",success:!0,data:{released:!0,session_path:ready.sessionPath,attachments:ready.attachments,dropped}}:refusal3(command.id,RPC_ERROR_SESSION_CLOSING,taken)}function busySignals(port,sessionId,session){let activity=session.activitySnapshot,signals=[];return activity.isStreaming&&signals.push("turn"),port.pendingPrompts(sessionId).length>0&&signals.push("prompt"),session.pendingMessageCount>0&&signals.push("queued"),session.externalAdmission.list().pending.length>0&&signals.push("delivery"),activity.isBashRunning&&signals.push("bash"),activity.isCompacting&&signals.push("compaction"),activity.hasSessionWork&&signals.push("session_work"),signals.length===0&&isHandoffBusy(activity)&&signals.push("activity"),port.otherRequests(sessionId)>0&&signals.push("request"),signals}function busyData(signals){return signals.includes("queued")?{busy:signals,retry_with:{interrupt:!0},hint:RELEASE_QUEUED_HINT}:{busy:signals}}function busyCode(signals){return signals.some(signal=>signal==="turn"||signal==="prompt"||signal==="queued"||signal==="delivery")?RPC_ERROR_TURN_ACTIVE:RPC_ERROR_SESSION_BUSY}function releasable(port,command,taken){let refuse=(code2,data2)=>refusal3(command.id,code2,data2||taken?{...data2,...taken}:void 0),entry;try{entry=port.lookup(command.sessionId)}catch(cause){return refuse(port.code(cause))}if(entry.state!=="open")return refuse(RPC_ERROR_SESSION_CLOSING);let session=entry.runtime?.session;if(session===void 0)return refuse(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"worker_runtime"});let sessionPath=entry.sessionPath??session.sessionFile;if(sessionPath===void 0)return refuse(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"no_session_file"});let elsewhere=port.otherAttachments(command.sessionId);return elsewhere>0&&command.force!==!0?refuse(RPC_ERROR_ATTACHED,{attachments:elsewhere}):{session,sessionPath,attachments:entry.attachments}}function refusal3(id,code2,data2){return{id,type:"response",command:"release_session",success:!1,error:code2,...data2&&{errorCode:code2,errorData:data2}}}function sessionMemory(host,sessionId){let view=host.hostMemoryView;if(view===void 0)return{main_heap_bytes:0,kernel_heap_bytes:0,kernel_count:0};let kernels=view.kernels().filter(kernel=>kernel.sessionId===sessionId),kernelHeapBytes=0;for(let kernel of kernels)kernelHeapBytes+=kernel.liveBytes;return{main_heap_bytes:view.mainHeapBytes(),kernel_heap_bytes:kernelHeapBytes,kernel_count:kernels.length}}function acknowledgePrompt(host,id,sessionId){let connection=host.writer.currentConnection();if(id===void 0||connection===void 0)return;let inFlight=Math.max(0,(host.activeRequests.get(sessionId)??1)-1);host.writer.sendOpenQueued(connection,{type:"queued",for_request:id,position:inFlight+1,in_flight:inFlight})}function otherRequestsSettled(host,sessionId){return new Promise(resolve2=>{let listeners=host.requestSettledListeners.get(sessionId)??new Set,check=()=>{(host.activeRequests.get(sessionId)??0)>1||(listeners.delete(check),listeners.size===0&&host.requestSettledListeners.delete(sessionId),resolve2())};listeners.add(check),host.requestSettledListeners.set(sessionId,listeners),check()})}var CHILD_TASK_SOURCE=/^senpi-task/,ACTIONS={extension_work:"let the named work finish, or unload with force: true (it is stopped, not resumed on reopen)",turn_active:"wait for the turn to end, or unload with interrupt: true to stop it first",work_pending:"wait for the work to finish, or unload with interrupt: true",children_live:'wait for the child tasks, or unload with children: "detach" to leave them running',attached:"ask the other clients to detach, or unload with force: true (they receive session_parked)"};async function unloadSession(port,command){if(port.draining())return answer2(command,refused({reason:"host_draining",detail:"this host is draining and parks every session itself"}));let first=loaded(port,command.sessionId);if("reason"in first)return answer2(command,refused(first));let{effectId}=command;if(effectId!==void 0){let begun=await beginEffect({session:first.session,by:port.by,sessionId:command.sessionId},"unload",{...command,effectId});if(!isEffectBegin(begun))return begun;if("replay"in begun)return answer2(command,{outcome:begun.replay.state==="failed"?"refused":"unloaded",...refusalFields(begun.replay.outcome),...effectAnswer(begun.replay,command.sessionId,!0)})}let blocked=blockers(port,command,first.session,first.durableSessionId),standing=blocked.find(refusal4=>!interruptible(refusal4)||command.interrupt!==!0);return standing!==void 0?fail(command,first.session,standing):(blocked.length>0&&await abortAndSettle(port,command.sessionId,first.session),claimAndUnload(port,command))}async function claimAndUnload(port,command){let ready=loaded(port,command.sessionId);if("reason"in ready)return answer2(command,refused(ready));let stillBlocked=blockers(port,command,ready.session,ready.durableSessionId);if(stillBlocked.length>0)return fail(command,ready.session,stillBlocked[0]);command.clearQueue===!0&&(ClientAdmissions.clearQueuedFor(ready.session),ready.session.clearQueue());let effect=command.effectId===void 0?void 0:EffectLedger.forSession(ready.session).transition(command.effectId,"done",{disposition:"unloaded"});return await port.tearDown(command.sessionId,ready.sessionPath)?answer2(command,{outcome:"unloaded",sessionPath:ready.sessionPath,...effect===void 0?{}:effectAnswer(effect,command.sessionId)}):answer2(command,{outcome:"refused",reason:"session_closing",detail:"another close of this session finished first"})}function interruptible(refusal4){return refusal4.reason==="turn_active"||refusal4.reason==="work_pending"}function blockers(port,command,session,durableSessionId){let found=[],activity=session.activitySnapshot,running=[activity.isStreaming&&"an agent run",port.pendingPrompts(command.sessionId).length>0&&"a prompt about to start",activity.isCompacting&&"compaction",activity.hasSessionWork&&"session work"].filter(label=>typeof label=="string");running.length>0&&found.push({reason:"turn_active",detail:running.join(", "),action:ACTIONS.turn_active});let pending=[activity.isBashRunning&&"a bash command",session.externalAdmission.list().pending.length>0&&"an admitted delivery not yet written",port.otherRequests(command.sessionId)>0&&"another request for this session"].filter(label=>typeof label=="string");pending.length>0&&found.push({reason:"work_pending",detail:pending.join(", "),action:ACTIONS.work_pending});let sources=session.activeWakeSources,childSources=sources.filter(source=>CHILD_TASK_SOURCE.test(source)),otherSources=sources.filter(source=>!CHILD_TASK_SOURCE.test(source));otherSources.length>0&&command.force!==!0&&found.push({reason:"extension_work",detail:`work published by ${otherSources.join(", ")}`,action:ACTIONS.extension_work});let childSessions=port.openChildSessions(durableSessionId);if(command.children!=="detach"&&(childSources.length>0||childSessions>0)){let what=childSessions>0?`${childSessions} child session(s) open on this host`:"child tasks still working";found.push({reason:"children_live",detail:what,action:ACTIONS.children_live})}let others=port.otherAttachments(command.sessionId);return others>0&&command.force!==!0&&found.push({reason:"attached",detail:`${others} other client(s) attached`,action:ACTIONS.attached}),found}function loaded(port,sessionId){let entry;try{entry=port.lookup(sessionId)}catch(cause){return{reason:"unsupported",detail:port.code(cause)}}if(entry.state!=="open")return{reason:"session_closing",detail:"the session is already closing"};let session=entry.runtime?.session;if(session===void 0)return{reason:"unsupported",detail:"a worker isolate owns this session's runtime"};let sessionPath=entry.sessionPath??session.sessionFile;return sessionPath===void 0?{reason:"unsupported",detail:"the session has no file to reopen it by",action:"send a prompt first so the session is written, or close it instead"}:{session,sessionPath,durableSessionId:session.sessionManager.getSessionId()}}function fail(command,session,refusal4){if(command.effectId===void 0)return answer2(command,refused(refusal4));let status=EffectLedger.forSession(session).transition(command.effectId,"failed",{outcome:{kind:"refused",reason:refusal4.reason,detail:refusal4.detail,...refusal4.action===void 0?{}:{action:refusal4.action}}});return answer2(command,{...refused(refusal4),...effectAnswer(status,command.sessionId)})}function refusalFields(outcome){return outcome?.reason===void 0?{}:{reason:outcome.reason,...outcome.detail===void 0?{}:{detail:outcome.detail},...outcome.action===void 0?{}:{action:outcome.action}}}function refused(refusal4){return{outcome:"refused",reason:refusal4.reason,detail:refusal4.detail,...refusal4.action===void 0?{}:{action:refusal4.action}}}function answer2(command,data2){return{id:command.id,type:"response",command:"unload_session",success:!0,data:data2}}function handle(host,command){let refusal4=attachmentGate(host,command);if(refusal4)return Promise.resolve(refusal4);let sessionId="sessionId"in command?command.sessionId:void 0;return host.draining&&sessionId!==void 0&&host.handoffClosed.has(sessionId)?Promise.resolve(void 0):host.draining&&command.type==="open_session"?Promise.resolve(error(command.id,command.type,"host_draining")):command.type==="warm"?answerWarm(command,{draining:host.draining,warm:host.registry.warm,cwd:host.defaults.cwd,hostContext:host.defaults.hostContext}):(host.activeRequests.set(sessionId,(host.activeRequests.get(sessionId)??0)+1),runWithSessionAttribution({sessionId},()=>dispatch(host,command)).finally(()=>{let remaining=(host.activeRequests.get(sessionId)??1)-1;if(remaining>0?host.activeRequests.set(sessionId,remaining):host.activeRequests.delete(sessionId),sessionId!==void 0)for(let listener of host.requestSettledListeners.get(sessionId)??[])listener();host.draining&&sweepDrain(host)}))}function otherAttachments(host,caller,sessionId){let own=caller===void 0?0:host.sessionsByConnection.get(caller)?.get(sessionId)??0;return Math.max(0,(host.registry.peek(sessionId)?.attachments??0)-own)}async function dispatch(host,command){if(command.type==="get_protocol_info"){let capabilities=multiSessionHostCapabilities({warm:host.registry.warm!==void 0,toolRuntime:host.defaults.toolRuntime??"in-process",negotiated:host.connectionOptions?.capabilities??[],mcpPresenters:host.writer.mcpPresenters!==void 0});return{id:command.id,type:"response",command:"get_protocol_info",success:!0,data:{protocolVersion:1,serverVersion:VERSION,capabilities,mode:"multi",...protocolIdentity(host.defaults.agentDir),memory_pressure:host.memoryPressure}}}if(command.type==="get_subscription_limits")return{id:command.id,type:"response",command:"get_subscription_limits",success:!0,data:{accounts:subscriptionLimits.snapshot()}};if(command.type==="list_sessions"){let withMemory=host.registry.list().map(row=>({...row,memory:sessionMemory(host,row.sessionId)})),sessions=command.include_workers===!0?withMemory:withMemory.filter(row=>row.kind!=="worker").map(({context:_context,...row})=>row);return{id:command.id,type:"response",command:"list_sessions",success:!0,data:{sessions}}}if(command.type==="detach_connection")return detachConnection(command,host.writer.currentConnection(),id=>releaseConnection(host,id));if(command.type==="open_session")return openWithBarrier(host,command);if(command.type==="attach_session")return attachSession(host,command);if(command.type==="release_attachment")return releaseAttachment(host,command);if(command.type==="reclaim_session")return reclaimSession(host,command);if(command.type==="close_session")return close(host,command);if(command.type==="release_session")return releaseSession({draining:()=>host.draining,hostInstance:host.defaults.hostContext?.host_instance,otherAttachments:sessionId2=>otherAttachments(host,host.writer.currentConnection(),sessionId2),lookup:sessionId2=>host.registry.getForCommand(sessionId2,"release_session"),code:cause=>code(cause),otherRequests:sessionId2=>Math.max(0,(host.activeRequests.get(sessionId2)??1)-1),otherRequestsSettled:sessionId2=>otherRequestsSettled(host,sessionId2),pendingPrompts:sessionId2=>host.bindings.get(sessionId2)?.pendingPrompts?.()??[],tearDown:(sessionId2,sessionPath)=>host.releaseTeardown(sessionId2,sessionPath)},command);if(command.type==="move_session"){let agentDir=host.registry.agentDir;return agentDir===void 0?error(command.id,command.type,"move_unsupported: this host keeps no agent directory to move sessions in"):moveSession({agentDir,hostedPaths:()=>host.registry.list().flatMap(row=>row.sessionPath===void 0?[]:[row.sessionPath])},command)}if(command.type==="unload_session"){let caller=host.writer.currentConnection();return unloadSession({draining:()=>host.draining,by:{connectionId:caller??"host"},lookup:sessionId2=>host.registry.getForCommand(sessionId2,"unload_session"),code:cause=>code(cause),otherRequests:sessionId2=>Math.max(0,(host.activeRequests.get(sessionId2)??1)-1),otherRequestsSettled:sessionId2=>otherRequestsSettled(host,sessionId2),pendingPrompts:sessionId2=>host.bindings.get(sessionId2)?.pendingPrompts?.()??[],otherAttachments:sessionId2=>otherAttachments(host,caller,sessionId2),openChildSessions:durableSessionId=>host.registry.list().filter(row=>row.durableSessionId!==durableSessionId&&(row.context?.parent_session_id===durableSessionId||row.context?.root_session_id===durableSessionId)).length,tearDown:(sessionId2,sessionPath)=>tearDownUnloaded(host,sessionId2,sessionPath)},command)}if(command.type==="set_client_info"&&!command.sessionId){let connection=host.writer.currentConnection();return command.capabilities!==void 0&&!host.connectionRoles.declare(roleConnection(connection),command.capabilities)?{id:command.id,type:"response",command:"set_client_info",success:!1,error:CONNECTION_ROLE_FIXED}:(connection!==void 0&&(host.pendingCapabilities.set(connection,command.capabilities??[]),host.writer.setConnectionCapabilities(connection,command.capabilities??[])),{id:command.id,type:"response",command:"set_client_info",success:!0})}if(command.type==="subscribe_sessions"){let connection=host.writer.currentConnection(),{answer:answer3,activate}=answerSubscribeSessions(command,connection,host.writer.status);if(activate!==void 0&&connection!==void 0){(async()=>{await host.writer.enqueueControl(answer3,connection),await new Promise(resolve2=>queueMicrotask(resolve2));try{host.writer.hasConnection(connection)?host.writer.status.activate(activate):host.writer.status.unsubscribe(connection,activate)}catch(cause){process.stderr.write(`senpi rpc subscription activation failed: ${String(cause)}
29
29
  `)}})().catch(cause=>{host.writer.status.unsubscribe(connection,activate),process.stderr.write(`senpi rpc subscribe answer could not be delivered: ${String(cause)}
30
- `)});return}return answer3}if(command.type==="unsubscribe_sessions")return answerUnsubscribeSessions(command,host.writer.currentConnection(),host.writer.status);if(command.type==="get_effect_status"&&!command.sessionId&&command.sessionPath!==void 0)return answerEffectFromTranscript(command.id,command.sessionPath,command.effectId);if(!command.sessionId)return error(command.id,command.type,RPC_ERROR_MISSING_SESSION_ID);let sessionId=command.sessionId;if(host.writer.isSessionSealed(sessionId)&&host.registry.peek(sessionId)?.state==="open")return error(command.id,command.type,"session_output_overflow",{sessionId,action:"unload_and_reopen"});if(command.type==="set_session_context")return setSessionContext(host,command);try{let entry=host.registry.getForCommand(sessionId,command.type);await dispatchSessionBinding(command,entry,host.bindings.get(sessionId),()=>acknowledgePrompt(host,command.id,sessionId),observedStarts=>host.registry.holderPids?.(observedStarts)??Promise.resolve([]));return}catch(cause){return error(command.id,command.type,code(cause),detail(cause))}}function setSessionContext(host,command){let owner=host.writer.currentConnection();if(owner!==void 0&&host.sessionsByConnection.get(owner)?.has(command.sessionId)!==!0)return notAttachedRefusal(command);try{let entry=host.registry.getForCommand(command.sessionId,command.type);return answerSetSessionContext(command,entry,host.writer.status)}catch(cause){return error(command.id,command.type,code(cause),detail(cause))}}var SessionCommandRouter=class{constructor(...args){this.context=new RouterContext(...args),this.context.releaseTeardown=(sessionId,sessionPath)=>this.tearDownReleased(sessionId,sessionPath)}tearDownReleased(sessionId,sessionPath){return tearDownReleased(this.context,sessionId,sessionPath)}get sessionCount(){return this.context.registry.size}handle(command){return handle(this.context,command)}beginDrain(){beginDrain(this.context)}setMemoryPressure(pressure){this.context.memoryPressure=pressure}sweepIdleSessions(){sweepIdleSessions(this.context)}dispose(){return dispose(this.context)}reopenParked(entry){return reopenParked(this.context,entry)}releaseConnection(connectionId){return releaseConnection(this.context,connectionId)}setHostMemoryView(view){this.context.hostMemoryView=view}};import{chmod}from"node:fs/promises";import{join as join6}from"node:path";function resolveSocketPath(value,agentDir){if(value==="unix://")return join6(agentDir,"rpc","rpc.sock");if(value.startsWith("unix://")){let path=value.slice(7);return path.length===0?join6(agentDir,"rpc","rpc.sock"):path.startsWith("@")&&process.platform==="linux"?`\0${path.slice(1)}`:path}return value}function formatSocketAddress(socketPath){return socketPath.startsWith("\0")?`unix://@${socketPath.slice(1)}`:`unix://${socketPath}`}function listen(server,socketPath,secret){return new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(resolveSocketTransportAddress(socketPath,process.platform,secret),async()=>{server.off("error",reject);try{if(process.platform!=="win32"&&!socketPath.startsWith("\0"))return await chmod(socketPath,384),resolve2(await statSocketIdentity(socketPath));resolve2(void 0)}catch(cause){reject(cause)}})})}var SESSION_WORKER_LIMITS={workers:20,requests:64,controlRequests:4,controlBytes:1024*1024,requestBytes:16*1024*1024,outputBytes:16*1024*1024,reservations:64,openMs:3e4,controlMs:5e3},WORKER_CREDIT_CODES={granted:1,conflict:2,limit:3};function typedWorkerRefusal(cause){let message=cause instanceof Error?cause.message:String(cause);throw message.startsWith("open_failed: ")?new RpcSessionRegistryError("open_failed",message.slice(13)):cause}function closedByWorkerDeath(cause){return cause instanceof RpcSessionRegistryError?cause.code==="session_closing":cause instanceof Error&&(cause.message==="session_closing"||cause.message==="session_worker_exited")}var RESERVATION_DENIAL_CODES={conflict:"session_path_in_use",limit:"session_reservation_limit"},SessionPathReservations=class{constructor(){this.owners=new Map}owner(path){return this.owners.get(path)}count(handle2){let count=0;for(let owner of this.owners.values())owner===handle2&&count++;return count}reserve(handle2,path,live){let owner=this.owners.get(path);return owner?owner===handle2?"granted":"conflict":this.count(handle2)>=SESSION_WORKER_LIMITS.reservations&&(!live||(this.reconcile(handle2,live),this.count(handle2)>=SESSION_WORKER_LIMITS.reservations))?"limit":(this.owners.set(path,handle2),"granted")}reconcile(handle2,live){for(let[path,owner]of this.owners)owner!==handle2||path===live.sessionPath||live.livePaths.includes(path)||this.owners.delete(path)}releaseAll(handle2){for(let[path,owner]of this.owners)owner===handle2&&this.owners.delete(path)}};import{fileURLToPath}from"node:url";import{Worker}from"node:worker_threads";var SessionWorkerRequests=class{constructor(send2,timeout){this.pending=new Map,this.serial=0,this.closed=!1,this.send=send2,this.timeout=timeout}remainingOpenMs(){let now=Date.now();return this.openingDeadline===void 0&&(this.openingDeadline=now+SESSION_WORKER_LIMITS.openMs),Math.max(0,this.openingDeadline-now)}get activeCount(){return this.pending.size}request(message){if(this.closed)return Promise.reject(new Error("session_closing"));let control=message.type==="command"&&"type"in message.command&&typeof message.command.type=="string"&&["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(message.command.type),bytes=Buffer.byteLength(JSON.stringify(message)),count=0,pendingBytes=0;for(let pending of this.pending.values())pending.control===control&&(count++,pendingBytes+=pending.bytes);let maxCount=control?SESSION_WORKER_LIMITS.controlRequests:SESSION_WORKER_LIMITS.requests,maxBytes=control?SESSION_WORKER_LIMITS.controlBytes:SESSION_WORKER_LIMITS.requestBytes;if(count>=maxCount||pendingBytes+bytes>maxBytes)return Promise.reject(new Error("session_worker_request_limit"));let request=++this.serial;return new Promise((resolve2,reject)=>{let timer=message.type==="command"&&!control?void 0:setTimeout(this.timeout,control?SESSION_WORKER_LIMITS.controlMs:this.remainingOpenMs());this.pending.set(request,{resolve:resolve2,reject,bytes,control,timer});try{this.send({...message,request})}catch(cause){this.pending.delete(request),clearTimeout(timer),reject(cause instanceof Error?cause:new Error(String(cause)))}})}receive(message){let pending=this.pending.get(message.request);pending&&(clearTimeout(pending.timer),this.pending.delete(message.request),message.type==="result"&&message.error?pending.reject(new Error(message.error)):pending.resolve(message))}close(error2){this.closed=!0;for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(error2);this.pending.clear()}};function acknowledgeGrant(signal,grant){let state=new Int32Array(signal);Atomics.store(state,0,WORKER_CREDIT_CODES[grant]),Atomics.notify(state,0)}function acknowledge(signal,granted){acknowledgeGrant(signal,granted?"granted":"conflict")}import{randomUUID}from"node:crypto";var compiledWorkerEntry=typeof SENPI_RPC_SESSION_WORKER_ENTRY=="string"?SENPI_RPC_SESSION_WORKER_ENTRY:"./src/modes/rpc/session-worker.ts",SessionWorkerClient=class{constructor(callbacks){this.privateOperations=new Map,this.webviewBroker=createWebViewBroker(),this.worker=new Worker(isBunBinary?fileURLToPath(new URL(compiledWorkerEntry,import.meta.url)).replaceAll("\\","/"):new URL(import.meta.url.endsWith(".ts")?"./session-worker.ts":"./session-worker.js",import.meta.url),{workerData:{hostProcessStartedAtMs:ownProcessStartedAtMs(),...this.webviewBroker?{webviewBroker:this.webviewBroker.port}:{}},...this.webviewBroker?{transferList:[this.webviewBroker.port]}:{}}),this.bindingReady=!1,this.requests=new SessionWorkerRequests(message=>this.worker.postMessage(message),()=>this.fail("session_worker_request_timeout")),this.stopped=!1,this.options={},this.listeners=new Set,this.cancelUiPending=!1,this.stopLimitMirror=()=>{},this.callbacks=callbacks,this.exited=new Promise((resolve2,reject)=>{this.worker.once("exit",()=>{this.stopPrivateBinding?.(),this.privateBinding?.dispose();for(let operation of this.privateOperations.values())operation.operation.abort();this.privateOperations.clear(),!this.stopped&&!this.closeTimer&&this.fail("session_worker_exited"),this.stopped=!0,this.closeTimer&&clearTimeout(this.closeTimer),this.requests.close(new Error("session_worker_exited")),this.webviewBroker?.dispose(),this.stopLimitMirror(),this.listeners.clear();let released=callbacks.exit();released?released.then(()=>{this.publishTerminalFailure(),resolve2()},reject):(this.publishTerminalFailure(),resolve2())})}),this.worker.on("message",message=>this.receive(message)),this.worker.on("error",error2=>this.fail(error2 instanceof Error?error2.message:String(error2)))}async prepare(configuration,profile){this.stopLimitMirror(),this.stopLimitMirror=subscriptionLimits.subscribeMirror(limits=>this.post({type:"subscription_limits",accounts:[limits]}));let result=await this.request({type:"prepare",configuration,profile,subscriptionLimits:subscriptionLimits.mirrorSnapshot()});if(result.type!=="prepared")throw new Error("Invalid worker prepare response");return result.sessionPath}async setPromptSurface(surface){if((await this.request({type:"prompt_surface",surface})).type!=="result")throw new Error("Invalid worker prompt_surface response")}async setBrowserEngine(engine){if((await this.request({type:"browser_engine",engine})).type!=="result")throw new Error("Invalid worker browser_engine response")}async setPermissionPreset(preset){if((await this.request({type:"permission_preset",preset})).type!=="result")throw new Error("Invalid worker permission_preset response")}async commit(){let result=await this.request({type:"commit"});if(result.type!=="ready")throw new Error("Invalid worker commit response");return this.snapshot=result.snapshot,result.snapshot}async bind(sessionId,writer,requestClose,options){return this.sessionId=sessionId,this.writer=writer,this.requestClose=requestClose,this.options=options,await this.request({type:"bind",sessionId,capabilities:options.capabilities??[],connection:writer.currentConnection(),roles:options.connectionRoles?.rolesOf(roleConnection(writer.currentConnection())),mcpFormsEnforced:writer.mcpPresenters!==void 0}),{handle:async command=>{if(writer.handleMcpForm(command))return;let connection=writer.currentConnection();"type"in command&&command.type==="extension_ui_response"&&"id"in command&&typeof command.id=="string"&&writer.acceptWorkerGrantResponse(sessionId,command.id,connection)===!1||await this.request({type:"command",command,connection,roles:options.connectionRoles?.rolesOf(roleConnection(connection))})},cancelPendingExtensionUiRequests:()=>this.post({type:"cancel_ui"}),dispose:async()=>{this.post({type:"cancel_ui"})}}}get busy(){return this.requests.activeCount>0||this.snapshot?.busy===!0}get handoffBusy(){return this.requests.activeCount>0||(this.snapshot?.handoffBusy??this.snapshot?.busy)===!0}subscribeSettled(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}close(graceMs){return this.stopped||this.closeTimer?this.exited:(this.post({type:"close"}),this.closeTimer=setTimeout(()=>this.quarantine(),graceMs),this.exited)}quarantine(){this.stopped=!0,this.requests.close(new Error("session_closing")),this.worker.terminate()}request(message){return this.requests.request(message)}post(message){if(!this.stopped){if(message.type==="cancel_ui"){if(this.cancelUiPending)return;this.cancelUiPending=!0}this.worker.postMessage(message)}}receive(message){if(this.stopped){"signal"in message&&acknowledge(message.signal,!1);return}switch(message.type){case"mcp_form_bind":{this.stopPrivateBinding?.(),this.privateBinding?.dispose();let writer=this.writer,sessionId=this.sessionId;if(!writer?.mcpPresenters||!sessionId){this.fail("private_form_unavailable");return}let bound=writer.bindMcpForms(sessionId,message.durableId,{},()=>{});if(bound instanceof Promise){this.fail("private_form_unavailable");return}this.privateBinding=writer.getMcpFormBinding(sessionId);let binding2=this.privateBinding;if(!binding2){this.fail("private_form_unavailable");return}let unsubscribe=binding2.subscribe?.(()=>this.post({type:"mcp_form_availability",epoch:binding2.epoch,version:binding2.version?.()}));this.stopPrivateBinding=()=>{unsubscribe?.(),bound?.()},this.post({type:"mcp_form_bound",id:message.id,epoch:binding2.epoch,version:binding2.version?.()});return}case"mcp_form_ready":{let binding2=this.privateBinding;this.post({type:"mcp_form_availability",id:message.id,epoch:message.epoch,version:binding2?.epoch===message.epoch?binding2.version?.():void 0});return}case"mcp_form_release":this.privateBinding?.epoch===message.epoch&&this.stopPrivateBinding?.();return;case"mcp_form_cancel":{let operation=this.privateOperations.get(message.id);operation?.epoch===message.epoch&&operation[message.lifetime].abort();return}case"mcp_form_create":{let binding2=this.privateBinding,presenter=binding2?.epoch===message.epoch&&binding2.version?.()===message.version?binding2.capture():void 0,operation=new AbortController,presentation=new AbortController;this.privateOperations.set(message.id,{operation,presentation,epoch:message.epoch});let fence=new Int32Array(message.operationFence),result=presenter?.present({...message.input,operationSignal:operation.signal,presentationSignal:presentation.signal,operationCurrent:()=>Atomics.load(fence,0)===0});Promise.resolve(result).then(outcome=>{this.privateOperations.delete(message.id),this.post({type:"mcp_form_settlement",id:message.id,epoch:message.epoch,settlementId:randomUUID(),outcome:outcome??{kind:"processing_failure",source:"host_termination",humanAdmission:!1}})});return}case"prepared":case"ready":case"result":{this.requests.receive(message),this.snapshot&&Promise.resolve(this.callbacks.reconcile(this.snapshot.liveSessionPaths)).catch(()=>this.fail("session_claim_reconcile_failed"));return}case"reserve":Promise.resolve(this.callbacks.reserve(message.path)).then(grant=>acknowledgeGrant(message.signal,this.stopped?"conflict":grant),()=>acknowledgeGrant(message.signal,"conflict"));return;case"snapshot":this.snapshot=message.snapshot,Promise.resolve(this.callbacks.reconcile(message.snapshot.liveSessionPaths)).then(()=>{if(acknowledge(message.signal,!this.stopped),message.settled)for(let listener of[...this.listeners])listener()},()=>{acknowledge(message.signal,!1),this.fail("session_claim_reconcile_failed")});return;case"control_done":this.cancelUiPending=!1;return;case"output":{let writer=this.writer,sessionId=this.sessionId;if(!writer||!sessionId||this.stopped){acknowledge(message.signal,!1);return}message.snapshot?this.snapshot=message.snapshot:this.snapshot&&(this.snapshot={...this.snapshot,...message.activity,state:{...this.snapshot.state,isStreaming:message.activity.streaming}});let record=message.record;if("type"in record&&record.type==="security_grant_settled"&&"id"in record&&typeof record.id=="string"){writer.settleGrantDialog(sessionId,record.id),acknowledge(message.signal,!0);return}if("type"in record&&record.type==="security_notice_snapshot"){if(!("snapshot"in record)||!isSecurityNoticeState(record.snapshot)){acknowledge(message.signal,!1),this.fail("invalid_security_notice_snapshot");return}writer.acceptWorkerSecuritySnapshot(sessionId,record.snapshot),acknowledge(message.signal,!0);return}let outputConnection=message.connection;if("type"in record&&record.type==="extension_ui_request"&&"method"in record&&record.method==="select"&&"grantSelect"in record&&record.grantSelect===!0&&"id"in record&&typeof record.id=="string"){let id=record.id,target=writer.routeWorkerGrant(sessionId,id,message.connection,this.options.capabilities??[],()=>this.post({type:"cancel_grant",id}));if(!target.accepted){acknowledge(message.signal,!0);return}outputConnection=target.connection}let enqueue=()=>writer.enqueue(sessionId,message.record)?writer.waitForSessionBackpressure(sessionId):(acknowledge(message.signal,!1),this.fail("session_output_overflow_or_closed"),Promise.reject(new Error("session_output_overflow_or_closed")));Promise.resolve(message.snapshot?this.callbacks.reconcile(message.snapshot.liveSessionPaths):void 0).then(()=>outputConnection===void 0?enqueue():writer.withConnection(outputConnection,enqueue)).then(()=>acknowledge(message.signal,!0),cause=>{acknowledge(message.signal,!1),this.fail(cause instanceof Error?cause.message:String(cause))});return}case"capabilities":message.connection===void 0&&(this.options={...this.options,capabilities:message.capabilities}),this.options.connectionRoles?.declare(roleConnection(message.connection),message.capabilities)===!1&&process.stderr.write(`senpi rpc worker role drift: connection ${roleConnection(message.connection)} declared a changed role
30
+ `)});return}return answer3}if(command.type==="unsubscribe_sessions")return answerUnsubscribeSessions(command,host.writer.currentConnection(),host.writer.status);if(command.type==="get_effect_status"&&!command.sessionId&&command.sessionPath!==void 0)return answerEffectFromTranscript(command.id,command.sessionPath,command.effectId);if(!command.sessionId)return error(command.id,command.type,RPC_ERROR_MISSING_SESSION_ID);let sessionId=command.sessionId;if(host.writer.isSessionSealed(sessionId)&&host.registry.peek(sessionId)?.state==="open")return error(command.id,command.type,"session_output_overflow",{sessionId,action:"unload_and_reopen"});if(command.type==="set_session_context")return setSessionContext(host,command);try{let entry=host.registry.getForCommand(sessionId,command.type);await dispatchSessionBinding(command,entry,host.bindings.get(sessionId),()=>acknowledgePrompt(host,command.id,sessionId),observedStarts=>host.registry.holderPids?.(observedStarts)??Promise.resolve([]));return}catch(cause){return error(command.id,command.type,code(cause),detail(cause))}}function setSessionContext(host,command){let owner=host.writer.currentConnection();if(owner!==void 0&&host.sessionsByConnection.get(owner)?.has(command.sessionId)!==!0)return notAttachedRefusal(command);try{let entry=host.registry.getForCommand(command.sessionId,command.type);return answerSetSessionContext(command,entry,host.writer.status)}catch(cause){return error(command.id,command.type,code(cause),detail(cause))}}var SessionCommandRouter=class{constructor(...args){this.context=new RouterContext(...args),this.context.releaseTeardown=(sessionId,sessionPath)=>this.tearDownReleased(sessionId,sessionPath)}tearDownReleased(sessionId,sessionPath){return tearDownReleased(this.context,sessionId,sessionPath)}get sessionCount(){return this.context.registry.size}handle(command){return handle(this.context,command)}beginDrain(){beginDrain(this.context)}setMemoryPressure(pressure){this.context.memoryPressure=pressure}sweepIdleSessions(){sweepIdleSessions(this.context)}dispose(){return dispose(this.context)}reopenParked(entry){return reopenParked(this.context,entry)}releaseConnection(connectionId){return releaseConnection(this.context,connectionId)}setHostMemoryView(view){this.context.hostMemoryView=view}};import{chmod}from"node:fs/promises";import{join as join6}from"node:path";function resolveSocketPath(value,agentDir){if(value==="unix://")return join6(agentDir,"rpc","rpc.sock");if(value.startsWith("unix://")){let path=value.slice(7);return path.length===0?join6(agentDir,"rpc","rpc.sock"):path.startsWith("@")&&process.platform==="linux"?`\0${path.slice(1)}`:path}return value}function formatSocketAddress(socketPath){return socketPath.startsWith("\0")?`unix://@${socketPath.slice(1)}`:`unix://${socketPath}`}function listen(server,socketPath,secret){return new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(resolveSocketTransportAddress(socketPath,process.platform,secret),async()=>{server.off("error",reject);try{if(process.platform!=="win32"&&!socketPath.startsWith("\0"))return await chmod(socketPath,384),resolve2(await statSocketIdentity(socketPath));resolve2(void 0)}catch(cause){reject(cause)}})})}var SESSION_WORKER_LIMITS={workers:20,requests:64,controlRequests:4,controlBytes:1024*1024,requestBytes:16*1024*1024,outputBytes:16*1024*1024,reservations:64,openMs:3e4,controlMs:5e3},WORKER_CREDIT_CODES={granted:1,conflict:2,limit:3};function typedWorkerRefusal(cause){let message=cause instanceof Error?cause.message:String(cause);throw message.startsWith("open_failed: ")?new RpcSessionRegistryError("open_failed",message.slice(13)):cause}function closedByWorkerDeath(cause){return cause instanceof RpcSessionRegistryError?cause.code==="session_closing":cause instanceof Error&&(cause.message==="session_closing"||cause.message==="session_worker_exited")}var RESERVATION_DENIAL_CODES={conflict:"session_path_in_use",limit:"session_reservation_limit"},SessionPathReservations=class{constructor(){this.owners=new Map}owner(path){return this.owners.get(path)}count(handle2){let count=0;for(let owner of this.owners.values())owner===handle2&&count++;return count}reserve(handle2,path,live){let owner=this.owners.get(path);return owner?owner===handle2?"granted":"conflict":this.count(handle2)>=SESSION_WORKER_LIMITS.reservations&&(!live||(this.reconcile(handle2,live),this.count(handle2)>=SESSION_WORKER_LIMITS.reservations))?"limit":(this.owners.set(path,handle2),"granted")}reconcile(handle2,live){for(let[path,owner]of this.owners)owner!==handle2||path===live.sessionPath||live.livePaths.includes(path)||this.owners.delete(path)}releaseAll(handle2){for(let[path,owner]of this.owners)owner===handle2&&this.owners.delete(path)}};import{fileURLToPath}from"node:url";import{Worker}from"node:worker_threads";var SessionWorkerRequests=class{constructor(send2,timeout){this.pending=new Map,this.serial=0,this.closed=!1,this.send=send2,this.timeout=timeout}remainingOpenMs(){let now=Date.now();return this.openingDeadline===void 0&&(this.openingDeadline=now+SESSION_WORKER_LIMITS.openMs),Math.max(0,this.openingDeadline-now)}get activeCount(){return this.pending.size}request(message){if(this.closed)return Promise.reject(new Error("session_closing"));let control=message.type==="command"&&"type"in message.command&&typeof message.command.type=="string"&&["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(message.command.type),bytes=Buffer.byteLength(JSON.stringify(message)),count=0,pendingBytes=0;for(let pending of this.pending.values())pending.control===control&&(count++,pendingBytes+=pending.bytes);let maxCount=control?SESSION_WORKER_LIMITS.controlRequests:SESSION_WORKER_LIMITS.requests,maxBytes=control?SESSION_WORKER_LIMITS.controlBytes:SESSION_WORKER_LIMITS.requestBytes;if(count>=maxCount||pendingBytes+bytes>maxBytes)return Promise.reject(new Error("session_worker_request_limit"));let request=++this.serial;return new Promise((resolve2,reject)=>{let timer=message.type==="command"&&!control?void 0:setTimeout(this.timeout,control?SESSION_WORKER_LIMITS.controlMs:this.remainingOpenMs());this.pending.set(request,{resolve:resolve2,reject,bytes,control,timer});try{this.send({...message,request})}catch(cause){this.pending.delete(request),clearTimeout(timer),reject(cause instanceof Error?cause:new Error(String(cause)))}})}receive(message){let pending=this.pending.get(message.request);pending&&(clearTimeout(pending.timer),this.pending.delete(message.request),message.type==="result"&&message.error?pending.reject(new Error(message.error)):pending.resolve(message))}close(error2){this.closed=!0;for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(error2);this.pending.clear()}};function acknowledgeGrant(signal,grant){let state=new Int32Array(signal);Atomics.store(state,0,WORKER_CREDIT_CODES[grant]),Atomics.notify(state,0)}function acknowledge(signal,granted){acknowledgeGrant(signal,granted?"granted":"conflict")}import{randomUUID}from"node:crypto";var compiledWorkerEntry=typeof SENPI_RPC_SESSION_WORKER_ENTRY=="string"?SENPI_RPC_SESSION_WORKER_ENTRY:"./src/modes/rpc/session-worker.ts",SessionWorkerClient=class{constructor(callbacks){this.privateOperations=new Map,this.webviewBroker=createWebViewBroker(),this.worker=new Worker(isBunBinary?fileURLToPath(new URL(compiledWorkerEntry,import.meta.url)).replaceAll("\\","/"):new URL(import.meta.url.endsWith(".ts")?"./session-worker.ts":"./session-worker.js",import.meta.url),{workerData:{hostProcessStartedAtMs:ownProcessStartedAtMs(),...this.webviewBroker?{webviewBroker:this.webviewBroker.port}:{}},...this.webviewBroker?{transferList:[this.webviewBroker.port]}:{}}),this.bindingReady=!1,this.requests=new SessionWorkerRequests(message=>this.worker.postMessage(message),()=>this.fail("session_worker_request_timeout")),this.stopped=!1,this.options={},this.listeners=new Set,this.cancelUiPending=!1,this.stopLimitMirror=()=>{},this.callbacks=callbacks,this.exited=new Promise((resolve2,reject)=>{this.worker.once("exit",()=>{this.stopPrivateBinding?.(),this.privateBinding?.dispose();for(let operation of this.privateOperations.values())operation.operation.abort();this.privateOperations.clear(),!this.stopped&&!this.closeTimer&&this.fail("session_worker_exited"),this.stopped=!0,this.closeTimer&&clearTimeout(this.closeTimer),this.requests.close(new Error("session_worker_exited")),this.webviewBroker?.dispose(),this.stopLimitMirror(),this.listeners.clear();let released=callbacks.exit();released?released.then(()=>{this.publishTerminalFailure(),resolve2()},reject):(this.publishTerminalFailure(),resolve2())})}),this.worker.on("message",message=>this.receive(message)),this.worker.on("error",error2=>this.fail(error2 instanceof Error?error2.message:String(error2)))}async prepare(configuration,profile){this.stopLimitMirror(),this.stopLimitMirror=subscriptionLimits.subscribeMirror(limits=>this.post({type:"subscription_limits",accounts:[limits]}));let result=await this.request({type:"prepare",configuration,profile,subscriptionLimits:subscriptionLimits.mirrorSnapshot()});if(result.type!=="prepared")throw new Error("Invalid worker prepare response");return result.sessionPath}async setPromptSurface(surface){if((await this.request({type:"prompt_surface",surface})).type!=="result")throw new Error("Invalid worker prompt_surface response")}async setBrowserEngine(engine){if((await this.request({type:"browser_engine",engine})).type!=="result")throw new Error("Invalid worker browser_engine response")}async setPermissionPreset(preset){if((await this.request({type:"permission_preset",preset})).type!=="result")throw new Error("Invalid worker permission_preset response")}async commit(){let result=await this.request({type:"commit"});if(result.type!=="ready")throw new Error("Invalid worker commit response");return this.snapshot=result.snapshot,result.snapshot}async bind(sessionId,writer,requestClose,options){return this.sessionId=sessionId,this.writer=writer,this.requestClose=requestClose,this.options=options,await this.request({type:"bind",sessionId,capabilities:options.capabilities??[],connection:writer.currentConnection(),roles:options.connectionRoles?.rolesOf(roleConnection(writer.currentConnection())),mcpFormsEnforced:writer.mcpPresenters!==void 0}),{handle:async command=>{if(writer.handleMcpForm(command))return;let connection=writer.currentConnection(),grantAnswer="type"in command&&command.type==="extension_ui_response"?answeredUiRequestId(command):void 0;grantAnswer!==void 0&&writer.acceptWorkerGrantResponse(sessionId,grantAnswer,connection)===!1||await this.request({type:"command",command,connection,roles:options.connectionRoles?.rolesOf(roleConnection(connection))})},cancelPendingExtensionUiRequests:()=>this.post({type:"cancel_ui"}),dispose:async()=>{this.post({type:"cancel_ui"})}}}get busy(){return this.requests.activeCount>0||this.snapshot?.busy===!0}get handoffBusy(){return this.requests.activeCount>0||(this.snapshot?.handoffBusy??this.snapshot?.busy)===!0}subscribeSettled(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}close(graceMs){return this.stopped||this.closeTimer?this.exited:(this.post({type:"close"}),this.closeTimer=setTimeout(()=>this.quarantine(),graceMs),this.exited)}quarantine(){this.stopped=!0,this.requests.close(new Error("session_closing")),this.worker.terminate()}request(message){return this.requests.request(message)}post(message){if(!this.stopped){if(message.type==="cancel_ui"){if(this.cancelUiPending)return;this.cancelUiPending=!0}this.worker.postMessage(message)}}receive(message){if(this.stopped){"signal"in message&&acknowledge(message.signal,!1);return}switch(message.type){case"mcp_form_bind":{this.stopPrivateBinding?.(),this.privateBinding?.dispose();let writer=this.writer,sessionId=this.sessionId;if(!writer?.mcpPresenters||!sessionId){this.fail("private_form_unavailable");return}let bound=writer.bindMcpForms(sessionId,message.durableId,{},()=>{});if(bound instanceof Promise){this.fail("private_form_unavailable");return}this.privateBinding=writer.getMcpFormBinding(sessionId);let binding2=this.privateBinding;if(!binding2){this.fail("private_form_unavailable");return}let unsubscribe=binding2.subscribe?.(()=>this.post({type:"mcp_form_availability",epoch:binding2.epoch,version:binding2.version?.()}));this.stopPrivateBinding=()=>{unsubscribe?.(),bound?.()},this.post({type:"mcp_form_bound",id:message.id,epoch:binding2.epoch,version:binding2.version?.()});return}case"mcp_form_ready":{let binding2=this.privateBinding;this.post({type:"mcp_form_availability",id:message.id,epoch:message.epoch,version:binding2?.epoch===message.epoch?binding2.version?.():void 0});return}case"mcp_form_release":this.privateBinding?.epoch===message.epoch&&this.stopPrivateBinding?.();return;case"mcp_form_cancel":{let operation=this.privateOperations.get(message.id);operation?.epoch===message.epoch&&operation[message.lifetime].abort();return}case"mcp_form_create":{let binding2=this.privateBinding,presenter=binding2?.epoch===message.epoch&&binding2.version?.()===message.version?binding2.capture():void 0,operation=new AbortController,presentation=new AbortController;this.privateOperations.set(message.id,{operation,presentation,epoch:message.epoch});let fence=new Int32Array(message.operationFence),result=presenter?.present({...message.input,operationSignal:operation.signal,presentationSignal:presentation.signal,operationCurrent:()=>Atomics.load(fence,0)===0});Promise.resolve(result).then(outcome=>{this.privateOperations.delete(message.id),this.post({type:"mcp_form_settlement",id:message.id,epoch:message.epoch,settlementId:randomUUID(),outcome:outcome??{kind:"processing_failure",source:"host_termination",humanAdmission:!1}})});return}case"prepared":case"ready":case"result":{this.requests.receive(message),this.snapshot&&Promise.resolve(this.callbacks.reconcile(this.snapshot.liveSessionPaths)).catch(()=>this.fail("session_claim_reconcile_failed"));return}case"reserve":Promise.resolve(this.callbacks.reserve(message.path)).then(grant=>acknowledgeGrant(message.signal,this.stopped?"conflict":grant),()=>acknowledgeGrant(message.signal,"conflict"));return;case"snapshot":this.snapshot=message.snapshot,Promise.resolve(this.callbacks.reconcile(message.snapshot.liveSessionPaths)).then(()=>{if(acknowledge(message.signal,!this.stopped),message.settled)for(let listener of[...this.listeners])listener()},()=>{acknowledge(message.signal,!1),this.fail("session_claim_reconcile_failed")});return;case"control_done":this.cancelUiPending=!1;return;case"output":{let writer=this.writer,sessionId=this.sessionId;if(!writer||!sessionId||this.stopped){acknowledge(message.signal,!1);return}message.snapshot?this.snapshot=message.snapshot:this.snapshot&&(this.snapshot={...this.snapshot,...message.activity,state:{...this.snapshot.state,isStreaming:message.activity.streaming}});let record=message.record;if("type"in record&&record.type==="security_grant_settled"&&"id"in record&&typeof record.id=="string"){writer.settleGrantDialog(sessionId,record.id),acknowledge(message.signal,!0);return}if("type"in record&&record.type==="security_notice_snapshot"){if(!("snapshot"in record)||!isSecurityNoticeState(record.snapshot)){acknowledge(message.signal,!1),this.fail("invalid_security_notice_snapshot");return}writer.acceptWorkerSecuritySnapshot(sessionId,record.snapshot),acknowledge(message.signal,!0);return}let outputConnection=message.connection;if("type"in record&&record.type==="extension_ui_request"&&"method"in record&&record.method==="select"&&"grantSelect"in record&&record.grantSelect===!0&&"id"in record&&typeof record.id=="string"){let id=record.id,target=writer.routeWorkerGrant(sessionId,id,message.connection,this.options.capabilities??[],()=>this.post({type:"cancel_grant",id}));if(!target.accepted){acknowledge(message.signal,!0);return}outputConnection=target.connection}let enqueue=()=>writer.enqueue(sessionId,message.record)?writer.waitForSessionBackpressure(sessionId):(acknowledge(message.signal,!1),this.fail("session_output_overflow_or_closed"),Promise.reject(new Error("session_output_overflow_or_closed")));Promise.resolve(message.snapshot?this.callbacks.reconcile(message.snapshot.liveSessionPaths):void 0).then(()=>outputConnection===void 0?enqueue():writer.withConnection(outputConnection,enqueue)).then(()=>acknowledge(message.signal,!0),cause=>{acknowledge(message.signal,!1),this.fail(cause instanceof Error?cause.message:String(cause))});return}case"capabilities":message.connection===void 0&&(this.options={...this.options,capabilities:message.capabilities}),this.options.connectionRoles?.declare(roleConnection(message.connection),message.capabilities)===!1&&process.stderr.write(`senpi rpc worker role drift: connection ${roleConnection(message.connection)} declared a changed role
31
31
  `),this.options.clientInfo?.setCapabilities(message.connection,message.capabilities),acknowledge(message.signal,!0);return;case"loaded_surfaces":{let writer=this.writer,sessionId=this.sessionId;if(!writer||!sessionId||this.stopped){acknowledge(message.signal,!1);return}writer.publishLoadedSurfacesChanged(sessionId,message.previous,message.digest),acknowledge(message.signal,!0);return}case"request_close":this.requestClose?.();return;case"subscription_limits":subscriptionLimits.adopt(message.limits);return;case"failure":this.fail(message.error);return}}fail(error2){this.stopped||(this.callbacks.failure(error2),this.terminalFailure=error2,this.writer&&this.sessionId&&this.writer.enqueue(this.sessionId,{type:"session_error",error:error2}),this.quarantine())}publishTerminalFailure(){let error2=this.terminalFailure,writer=this.writer,sessionId=this.sessionId;error2===void 0||!writer||!sessionId||(this.terminalFailure=void 0,writer.closeSession(sessionId,{type:"response",command:"close_session",success:!1,error:error2},"error"))}};import{isAbsolute as isAbsolute4}from"node:path";var WorkerSessionClaims=class{constructor(reservations){this.paths=new Map,this.releases=new Set,this.closed=!1,this.reservations=reservations}async claim(path,attached=!0){if(this.closed)throw new RpcSessionRegistryError("session_closing");if(!this.reservations)return;let previous=this.paths.get(path);if(previous)return previous.ownership;let record={ownership:this.reservations.claim(path,attached),attached};this.paths.set(path,record);let owner=await record.ownership;return owner&&this.paths.get(path)===record&&this.paths.delete(path),owner}setAttached(attached){for(let[path,record]of this.paths)record.attached!==attached&&(record.attached=attached,record.ownership.then(owner=>{!owner&&this.paths.get(path)===record&&this.reservations?.setAttached(path,record.attached)}))}reconcile(livePaths,attached){let live=new Set(livePaths);for(let path of this.paths.keys())live.has(path)||this.release(path);this.setAttached(attached)}release(path){let record=this.paths.get(path);if(!record)return Promise.resolve();this.paths.delete(path);let removal=record.ownership.then(async owner=>{owner||await this.reservations?.release(path)});return this.releases.add(removal),removal.then(()=>this.releases.delete(removal),()=>this.releases.delete(removal)),removal}async close(){this.closed=!0,await Promise.all([...this.paths.keys()].map(path=>this.release(path)).concat([...this.releases]))}};async function openWorkerSession(host,profile,options){if(!isAbsolute4(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute4(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");let requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){try{assertValidSessionId(requestedDurableId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}let requestedKey=profile.sessionPath?host.knownReservationKey(profile.sessionPath):void 0;for(let entry2 of host.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(requestedKey!==void 0&&entry2.reservationKey===requestedKey))throw new RpcSessionRegistryError("session_id_in_use")}if(profile.sessionPath){let key=host.knownReservationKey(profile.sessionPath),owner=key?host.reservations.owner(key):void 0;if(key&&owner)return host.attach(owner,key,options,profile)}if(options?.attachOnly)throw new RpcSessionRegistryError("session_not_held",void 0,{reason:"session_not_held",action:"rediscover_holder"});if(host.size>=SESSION_WORKER_LIMITS.workers)throw new Error("too_many_sessions");let handle2=host.nextHandle(),claims=new WorkerSessionClaims(host.options.pathReservations);host.claims.set(handle2,claims);let storedProfile=frozenProfile(profile),entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),cwd:profile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:host.now(),lifecycleMutex:Promise.resolve(),...requestedDurableId!==void 0?{durableSessionId:requestedDurableId}:{}},workerFailure,worker=host.createWorker({reserve:path=>host.reserve(handle2,path),reconcile:livePaths=>host.reconcile(handle2,livePaths),exit:()=>{if(host.entries.get(handle2)!==entry)return;let finish=()=>{host.entries.get(handle2)===entry&&(entry.state="closed",host.entries.delete(handle2),host.claims.delete(handle2),host.reservations.releaseAll(handle2),entry.closeResolve?.())};return releaseWithinGrace({closeGraceMs:host.closeGraceMs,releaseReservation:()=>claims.close()},handle2,entry.reservationKey??handle2).then(finish)},failure:error2=>{workerFailure=error2,entry.state="quarantined",process.stderr.write(`senpi rpc session ${handle2} quarantined: ${error2}
32
32
  `)}});entry.worker=worker,host.entries.set(handle2,entry);try{let path=await worker.prepare(host.options.configuration,profile).catch(typedWorkerRefusal),owner=host.reservations.owner(path);if(owner){let attached=await host.attach(owner,path,options,profile);return entry.state="quarantined",worker.quarantine(),attached}let predecessor=await claims.claim(path);if(predecessor)throw new RpcSessionRegistryError("session_path_in_use",void 0,{owner:predecessor,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS});let grant=await host.reserve(handle2,path);if(grant!=="granted")throw new RpcSessionRegistryError(RESERVATION_DENIAL_CODES[grant]);entry.reservationKey=path,entry.requestedPathKey=profile.sessionPath?path:void 0,entry.sessionPath=path;let snapshot=await worker.commit();if(entry.state!=="opening")throw workerFailure===void 0?new RpcSessionRegistryError("session_closing"):new RpcSessionRegistryError("open_failed",workerFailure.replace(/^open_failed: /,""));return entry.durableSessionId=snapshot.state.sessionId,entry.cwd=snapshot.state.cwd,entry.state="open",host.openResult(handle2,entry)}catch(cause){throw entry.state="quarantined",worker.quarantine(),workerFailure!==void 0&&closedByWorkerDeath(cause)?new RpcSessionRegistryError("open_failed",workerFailure.replace(/^open_failed: /,"")):cause}}var WorkerSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new SessionPathReservations,this.claims=new Map,this.serial=0,this.options=options,this.closeGraceMs=options.closeGraceMs,this.now=options.now,this.createWorker=options.createWorker??(callbacks=>new SessionWorkerClient(callbacks))}get size(){return this.entries.size}holderPids(observedStarts){return this.options.pathReservations?.holderPids?.(observedStarts)??Promise.resolve([])}openSession(profile,options){return openWorkerSession({entries:this.entries,reservations:this.reservations,claims:this.claims,options:this.options,closeGraceMs:this.closeGraceMs,size:this.size,now:this.now,nextHandle:()=>`rpc-${++this.serial}`,knownReservationKey:path=>this.knownReservationKey(path),attach:(owner,path,options2,requested)=>this.attach(owner,path,options2,requested),reserve:(handle2,path)=>this.reserve(handle2,path),reconcile:(handle2,paths)=>this.reconcile(handle2,paths),openResult:(handle2,entry)=>this.openResult(handle2,entry),createWorker:this.createWorker},profile,options)}peek(handle2){return this.entries.get(handle2)}attachSession(handle2){return attachLiveSession(this.entries.get(handle2),this.now(),()=>this.claims.get(handle2)?.setAttached(!0))}getForCommand(handle2,command){let entry=this.entries.get(handle2);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="quarantined"||entry.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(command))throw new RpcSessionRegistryError("session_closing");if(entry.state!=="open"&&entry.state!=="closing")throw new RpcSessionRegistryError("unknown_session");return(entry.attachments>0||refreshesSessionActivity(command))&&(entry.lastCommandAt=this.now()),entry}beginClose(handle2,onRole,options){let entry=this.entries.get(handle2);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing"||entry.state==="quarantined")return onRole?.(!1),entry;if(entry.state!=="open"&&entry.state!=="opening")throw new RpcSessionRegistryError("unknown_session");return entry.attachments--,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry.detachedAt??=this.now(),entry.worker?.busy||this.claims.get(handle2)?.setAttached(!1),entry):(entry.state="closing",entry.closeCompletion=new Promise(resolve2=>{entry.closeResolve=resolve2}),onRole?.(!0),entry)}close(handle2){return this.beginClose(handle2).state==="closing"?this.closeMarked(handle2):Promise.resolve()}async closeMarked(handle2){let entry=this.entries.get(handle2);if(entry?.state!=="closing"||!entry.worker)throw new RpcSessionRegistryError("unknown_session");if(entry.closeStarted)return entry.closeCompletion;entry.closeStarted=!0;let timer;await Promise.race([entry.worker.close(this.closeGraceMs),new Promise(resolve2=>{timer=setTimeout(()=>{entry.state!=="closed"&&(entry.state="quarantined"),resolve2()},this.closeGraceMs)})]),timer&&clearTimeout(timer)}list(){let now=this.now();return[...this.entries].map(([sessionId,entry])=>{let state=entry.worker?.snapshot?.state;return{sessionId,durableSessionId:state?.sessionId??entry.durableSessionId,sessionPath:state?.sessionFile??entry.sessionPath,cwd:state?.cwd??entry.cwd,name:state?.sessionName,kind:entry.kind,context:publishedSessionContext(entry.context,entry.contextOverlay),attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state,idleMs:Math.max(0,now-entry.lastCommandAt),tool_child:{state:"none"}}})}knownReservationKey(path){if(this.reservations.owner(path))return path;for(let entry of this.entries.values()){if(entry.profile.sessionPath===path&&entry.requestedPathKey&&this.reservations.owner(entry.requestedPathKey))return entry.requestedPathKey;let snapshot=entry.worker?.snapshot;if(snapshot?.state.sessionFile===path)return snapshot.sessionPath}}async attach(owner,path,options,requested={cwd:""}){let{promptSurface,browserEngine,permissionPreset}=requested,entry=this.entries.get(owner);if(entry?.state!=="open"||!entry.worker?.bindingReady||entry.worker.snapshot?.sessionPath!==path)throw new RpcSessionRegistryError("session_path_in_use");promptSurface!==void 0&&promptSurface!==entry.profile.promptSurface&&(entry.profile=frozenProfile({...entry.profile,promptSurface}),await entry.worker.setPromptSurface(promptSurface)),browserEngine!==void 0&&browserEngine!==entry.profile.browserEngine&&(entry.profile=frozenProfile({...entry.profile,browserEngine}),await entry.worker.setBrowserEngine(browserEngine)),permissionPreset!==void 0&&(entry.profile=frozenProfile({...entry.profile,permissionPreset}),await entry.worker.setPermissionPreset(permissionPreset));let result=this.openResult(owner,entry);return entry.attachments++,this.claims.get(owner)?.setAttached(!0),options?.retainOnDisconnect&&(entry.retainOnDisconnect=!0),entry.lastCommandAt=this.now(),{...result,attached:!0}}reservationCount(handle2){return this.reservations.count(handle2)}async reserve(handle2,path){let entry=this.entries.get(handle2);if(!entry)return"conflict";if(this.reservations.owner(path)===handle2)return"granted";if(entry.state!=="opening"&&entry.state!=="open")return"conflict";let grant=this.reservations.reserve(handle2,path,this.liveWorkerPaths(entry));if(grant!=="granted")return grant;if(await this.claims.get(handle2)?.claim(path,entry.attachments>0||entry.worker?.busy===!0)||this.entries.get(handle2)!==entry||entry.state!=="opening"&&entry.state!=="open"){let live=this.liveWorkerPaths(entry);return this.reservations.reconcile(handle2,live??{livePaths:[],sessionPath:entry.reservationKey}),"conflict"}return"granted"}async reconcile(handle2,livePaths){let entry=this.entries.get(handle2);if(entry?.state!=="open")return;let sessionPath=entry.worker?.snapshot?.sessionPath,attached=entry.attachments>0||entry.worker?.busy===!0;if(sessionPath){if(await this.claims.get(handle2)?.claim(sessionPath,attached))throw new RpcSessionRegistryError("session_path_in_use");if(this.entries.get(handle2)!==entry||entry.state!=="open")return}this.reservations.reconcile(handle2,{livePaths,sessionPath}),this.claims.get(handle2)?.reconcile(sessionPath?[...livePaths,sessionPath]:livePaths,attached),sessionPath&&(entry.reservationKey=sessionPath,entry.sessionPath=sessionPath)}liveWorkerPaths(entry){let snapshot=entry.state==="open"?entry.worker?.snapshot:void 0;if(snapshot)return{livePaths:snapshot.liveSessionPaths,sessionPath:snapshot.sessionPath}}openResult(handle2,entry){let state=entry.worker?.snapshot?.state;if(!state)throw new RpcSessionRegistryError("open_failed");return{sessionId:handle2,durableSessionId:state.sessionId,sessionPath:state.sessionFile}}};import{createPublicKey,randomBytes,randomUUID as randomUUID2,verify}from"node:crypto";import{createServer}from"node:net";import{Duplex,PassThrough,Readable,Writable}from"node:stream";var McpPresenterControl=class{constructor(writer,path){this.principals=new Map,this.controls=new Set,this.revokeControls=new Map,this.backendGenerations=new Map,this.successors=new Map,this.writer=writer,this.authority=writer.enableMcpPresenters(),this.path=path,this.server=createServer(stream=>this.manage(stream))}listen(){return new Promise((resolve2,reject)=>{this.server.once("error",reject),this.server.listen(this.path,()=>{this.server.off("error",reject),resolve2()})})}successorBootstrap(){let owner=this.launchOwner;if(!owner||owner.stream.destroyed)return;let id=randomUUID2(),toChild=new PassThrough,fromChild=new PassThrough,endpoint=Duplex.from({readable:Readable.toWeb(toChild),writable:Writable.toWeb(fromChild)});this.successors.set(id,{stream:owner.stream,write:toChild});let stop=privateFrames(fromChild,value=>{if(!isRecord(value)){endpoint.destroy();return}value.type==="challenge"?send(owner.stream,{type:"mcp_presenter_successor_challenge",id,challenge:value}):value.type==="enrolled"?(send(owner.stream,{type:"mcp_presenter_successor_enrolled",id,enrollment:value}),stop(),this.successors.delete(id)):endpoint.destroy()});return endpoint.once("close",()=>{stop(),this.successors.delete(id),toChild.destroy(),fromChild.destroy()}),toChild.write(`${JSON.stringify({type:"enroll",publicKey:owner.principal.key.export({type:"spki",format:"pem"}),backendGeneration:owner.backendGeneration})}
33
33
  `),endpoint}bootstrap(stream){let key,backend,transcript,id=randomUUID2(),stop=privateFrames(stream,value=>{if(!key){if(!isRecord(value)||value.type!=="enroll"||typeof value.publicKey!="string"||typeof value.backendGeneration!="string"){stream.destroy();return}try{key=createPublicKey(value.publicKey)}catch{stream.destroy();return}if(key.asymmetricKeyType!=="ed25519"){stream.destroy();return}backend=value.backendGeneration,transcript=JSON.stringify(["mcp-presenter-enroll-v1",this.authority.instance,backend,randomBytes(32).toString("hex")]),send(stream,{type:"challenge",transcript,hostInstance:this.authority.instance});return}if(!transcript||!signed(value,transcript,key)){stream.destroy();return}this.principals.set(id,{id,key,sessions:new WeakSet}),send(stream,{type:"enrolled",principalId:id,hostInstance:this.authority.instance,backendGeneration:backend,endpoint:this.path}),stop(),stream.end()})}dispose(){this.authority.dispose();for(let stream of this.controls)stream.destroy();this.controls.clear();for(let successor of this.successors.values())successor.write.destroy();this.successors.clear(),this.principals.clear(),this.server.close()}manage(stream){if(this.controls.size>=64){stream.destroy();return}this.controls.add(stream);let principal,owner,transcript,pending,backendGeneration,deadline=performance.now()+3e4,challengeTimer=setTimeout(()=>stream.destroy(),3e4),registrations=new Map,revoke=()=>{clearTimeout(challengeTimer);for(let registration of registrations.values())owner?.revoke(registration);registrations.clear(),this.controls.delete(stream),this.revokeControls.delete(stream),this.backendGenerations.delete(stream),this.launchOwner?.stream===stream&&(this.launchOwner=void 0);for(let[id,successor]of this.successors)successor.stream===stream&&(successor.write.destroy(),this.successors.delete(id))};this.revokeControls.set(stream,revoke),stream.once("close",revoke);let stop=privateFrames(stream,value=>{if(!isRecord(value)){stream.destroy();return}if(value.type==="mcp_presenter_successor_proof"&&typeof value.id=="string"){let successor=this.successors.get(value.id);if(successor?.stream!==stream||typeof value.signature!="string"){stream.destroy();return}successor.write.write(`${JSON.stringify({type:"proof",signature:value.signature})}