@code-yeongyu/senpi 2026.11.2-3 → 2026.11.3-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/dist/bundle/chunks/{anthropic-messages-WUPLDYD6.js → anthropic-messages-AFWQB3KN.js} +1 -1
- package/dist/bundle/chunks/{args-AOI4NEA6.js → args-O3WS4WCO.js} +1 -1
- package/dist/bundle/chunks/{chunk-O4GRBX4R.js → chunk-3WJ2DE2G.js} +1 -1
- package/dist/bundle/chunks/{chunk-LMIETUPG.js → chunk-4BF4FLT6.js} +1 -1
- package/dist/bundle/chunks/{chunk-T5ZJ2Q4O.js → chunk-4SENPCEA.js} +1 -1
- package/dist/bundle/chunks/chunk-5DZD623T.js +448 -0
- package/dist/bundle/chunks/{chunk-TXOR5BQL.js → chunk-6BSMXZKQ.js} +1 -1
- package/dist/bundle/chunks/{chunk-VRWJJMHO.js → chunk-7565XQAU.js} +1 -1
- package/dist/bundle/chunks/{chunk-IWM5QRAE.js → chunk-7KLEFHSU.js} +1 -1
- package/dist/bundle/chunks/{chunk-FO56LSUK.js → chunk-BNIZP4OS.js} +1 -1
- package/dist/bundle/chunks/{chunk-L3V65XW7.js → chunk-CJWSQ6CK.js} +1 -1
- package/dist/bundle/chunks/{chunk-QLTQ3UUI.js → chunk-DAPBNRN5.js} +1 -1
- package/dist/bundle/chunks/{chunk-GIY7PGOH.js → chunk-DPBPO5OU.js} +1 -1
- package/dist/bundle/chunks/chunk-ESQBKTNG.js +2 -0
- package/dist/bundle/chunks/{chunk-N4TSAHRL.js → chunk-EVTTLPIY.js} +1 -1
- package/dist/bundle/chunks/{chunk-NYXXKS6D.js → chunk-F4OHTL2K.js} +3 -2
- package/dist/bundle/chunks/{chunk-TVMW2SUP.js → chunk-FJ2UCBOA.js} +2 -2
- package/dist/bundle/chunks/{chunk-KVPRQ5KN.js → chunk-FLM6GZPT.js} +1 -1
- package/dist/bundle/chunks/{chunk-P4AT7SBE.js → chunk-HBCNDC53.js} +1 -1
- package/dist/bundle/chunks/chunk-MOH5HOHX.js +2 -0
- package/dist/bundle/chunks/{chunk-7FUO655J.js → chunk-MOOFLKLI.js} +1 -1
- package/dist/bundle/chunks/{chunk-IHOQR7TU.js → chunk-PX7FF5LE.js} +1 -1
- package/dist/bundle/chunks/{chunk-QAM6AXA2.js → chunk-QTQ3ES2S.js} +12 -9
- package/dist/bundle/chunks/{chunk-FJSJUVQQ.js → chunk-TOOB6OLG.js} +3 -3
- package/dist/bundle/chunks/{chunk-662SCMTH.js → chunk-VPDQ6MOL.js} +1 -1
- package/dist/bundle/chunks/{chunk-BW4YXS7X.js → chunk-WCRNJYHO.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZSVWKOAJ.js → chunk-ZNLCKKF6.js} +170 -226
- package/dist/bundle/chunks/{cli-main-534A3WSC.js → cli-main-XM5FWY3Z.js} +1 -1
- package/dist/bundle/chunks/{credential-accounts-OAK2E5O2.js → credential-accounts-YZYSKA7X.js} +1 -1
- package/dist/bundle/chunks/{health-write-EB4CPHXN.js → health-write-45CX64T2.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-U2PSNNWO.js → help-fast-path-3EDGRKQM.js} +1 -1
- package/dist/bundle/chunks/{host-command-WJIMRBGN.js → host-command-PZ4VYQIW.js} +1 -1
- package/dist/bundle/chunks/{host-session-command-PWVPQ2OV.js → host-session-command-OJFARE5Q.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-NPHFDPGH.js → interactive-mode-7JSJVVIS.js} +1 -1
- package/dist/bundle/chunks/{login-health-7G2DZVOV.js → login-health-YOPTYRTU.js} +1 -1
- package/dist/bundle/chunks/{main-I6FJAFUP.js → main-3YGJ2O4I.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-7E26R5JF.js → multi-session-host-N2RQ7JSZ.js} +4 -4
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-VNBMMIL3.js → openai-codex-responses-YTWLG4OL.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-JLR32APM.js → openai-completions-TIFDYHZL.js} +1 -1
- package/dist/bundle/chunks/{openai-images-LEBNERSM.js → openai-images-OAEMY4RG.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-JCDUNMHA.js → openai-responses-L35NIG5Y.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-CBSDV36M.js → package-manager-cli-JPNA27E5.js} +1 -1
- package/dist/bundle/chunks/{role-LP6LVNCY.js → role-45Y7PQFC.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-ZDCNHIBE.js → rotation-stream-WXWJKJZN.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-GBBTN2WP.js → rpc-mode-Z7MN2ZWA.js} +1 -1
- package/dist/bundle/chunks/{run-attached-tui-PVLUHHJX.js → run-attached-tui-TI6MELEI.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-W45NYTTK.js → schedule-command-OZ5ESMIT.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-LFLUNALC.js → session-control-endpoint-5YKBYJOO.js} +1 -1
- package/dist/bundle/chunks/{session-picker-OZUINLD7.js → session-picker-CMRV72VA.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +324 -376
- package/dist/bundle/chunks/{state-store-SZARKD36.js → state-store-Q47AYMRI.js} +1 -1
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/agent-session.d.ts +8 -0
- package/dist/core/agent-session.js +68 -60
- package/dist/core/credential-pool/classify.d.ts +3 -2
- package/dist/core/credential-pool/classify.js +10 -3
- package/dist/core/dynamic-prompt/build.d.ts +2 -1
- package/dist/core/dynamic-prompt/build.js +1 -2
- package/dist/core/dynamic-prompt/handoff.d.ts +1 -1
- package/dist/core/dynamic-prompt/handoff.js +9 -9
- package/dist/core/dynamic-prompt/identity.js +1 -1
- package/dist/core/dynamic-prompt/intent-gate.d.ts +1 -1
- package/dist/core/dynamic-prompt/intent-gate.js +8 -8
- package/dist/core/dynamic-prompt/policies.d.ts +1 -1
- package/dist/core/dynamic-prompt/policies.js +5 -7
- package/dist/core/dynamic-prompt/style.js +5 -5
- package/dist/core/dynamic-prompt/tool-section.d.ts +5 -0
- package/dist/core/dynamic-prompt/tool-section.js +8 -6
- package/dist/core/dynamic-prompt/verification.d.ts +6 -6
- package/dist/core/dynamic-prompt/verification.js +12 -12
- package/dist/core/dynamic-prompt/working-task.d.ts +1 -1
- package/dist/core/dynamic-prompt/working-task.js +3 -3
- package/dist/core/dynamic-prompt/workstation.js +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.d.ts +13 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.js +64 -2
- package/dist/core/extensions/builtin/anthropic-subscription/session-stream.js +5 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-attempt.d.ts +7 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-attempt.js +28 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-types.d.ts +2 -0
- package/dist/core/extensions/builtin/bash-timeout/index.d.ts +1 -1
- package/dist/core/extensions/builtin/bash-timeout/index.js +3 -28
- package/dist/core/extensions/builtin/bash-timeout/timeout.d.ts +0 -11
- package/dist/core/extensions/builtin/bash-timeout/timeout.js +0 -11
- package/dist/core/extensions/builtin/imagegen/index.d.ts +0 -1
- package/dist/core/extensions/builtin/imagegen/index.js +0 -11
- package/dist/core/extensions/builtin/prompt-preset/execution-tooling.d.ts +5 -5
- package/dist/core/extensions/builtin/prompt-preset/execution-tooling.js +5 -5
- package/dist/core/extensions/builtin/prompt-preset/glm-5.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/glm-5.js +1 -1
- package/dist/core/extensions/builtin/terminal/extension.js +8 -1
- package/dist/core/extensions/builtin/terminal/notify.js +9 -3
- package/dist/core/extensions/builtin/terminal/prompt.d.ts +7 -1
- package/dist/core/extensions/builtin/terminal/prompt.js +27 -60
- package/dist/core/extensions/builtin/terminal/tools/bash.js +10 -2
- package/dist/core/extensions/builtin/todotools/normalize.d.ts +20 -3
- package/dist/core/extensions/builtin/todotools/normalize.js +251 -5
- package/dist/core/extensions/builtin/todotools/prompt.d.ts +2 -2
- package/dist/core/extensions/builtin/todotools/prompt.js +5 -5
- package/dist/core/extensions/builtin/todotools/tools/todo.js +9 -8
- package/dist/core/extensions/builtin/webfetch/webfetch/tool.js +0 -5
- package/dist/core/extensions/builtin/websearch/index.js +9 -4
- package/dist/core/extensions/builtin/websearch/websearch/tool.d.ts +2 -0
- package/dist/core/extensions/builtin/websearch/websearch/tool.js +3 -1
- package/dist/core/model-runtime.js +1 -1
- package/dist/core/provider-failure.d.ts +6 -0
- package/dist/core/provider-failure.js +6 -2
- package/dist/core/retry-fallback/exhaustion.d.ts +18 -0
- package/dist/core/retry-fallback/exhaustion.js +20 -0
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/tools/bash.d.ts +3 -1
- package/dist/core/tools/bash.js +14 -4
- package/dist/core/tools/edit.d.ts +1 -1
- package/dist/core/tools/edit.js +1 -6
- package/dist/core/tools/grep/index.js +2 -3
- package/dist/core/tools/powershell.d.ts +1 -1
- package/dist/core/tools/powershell.js +1 -1
- package/dist/core/tools/read.d.ts +1 -1
- package/dist/core/tools/read.js +1 -1
- package/dist/core/tools/write.d.ts +1 -1
- package/dist/core/tools/write.js +1 -1
- package/dist/engine-trust/shell-trust.d.ts +36 -0
- package/dist/engine-trust/shell-trust.js +44 -0
- package/dist/engine-trust/transport-failure.d.ts +12 -0
- package/dist/engine-trust/transport-failure.js +48 -0
- package/dist/modes/interactive/interactive-mode.js +9 -3
- package/dist/modes/print-mode.js +2 -1
- package/dist/modes/rpc/compact-catalog-families.d.ts +5 -2
- package/dist/modes/rpc/compact-catalog-families.js +5 -2
- package/dist/modes/rpc/compact-catalog-registry.d.ts +9 -1
- package/dist/modes/rpc/compact-catalog-registry.js +9 -2
- package/dist/modes/rpc/compact-recovery-manifest-kinds.d.ts +17 -0
- package/dist/modes/rpc/compact-recovery-manifest-kinds.js +21 -0
- package/dist/modes/rpc/compact-recovery-manifest-shape.d.ts +7 -0
- package/dist/modes/rpc/compact-recovery-manifest.js +11 -3
- package/dist/modes/rpc/compact-socket-commands.js +6 -0
- package/dist/modes/rpc/connection-handler.js +21 -5
- package/dist/modes/rpc/connection-question-bridge.d.ts +3 -1
- package/dist/modes/rpc/connection-question-bridge.js +4 -1
- package/dist/modes/rpc/connection-roles.d.ts +8 -0
- package/dist/modes/rpc/connection-roles.js +18 -0
- package/dist/modes/rpc/method-classes-schema-session.d.ts +4 -0
- package/dist/modes/rpc/method-classes-schema-session.js +1 -0
- package/dist/modes/rpc/method-classes-schema.d.ts +4 -0
- package/dist/modes/rpc/protocol-identity.js +2 -0
- package/dist/modes/rpc/remote-origin.d.ts +31 -0
- package/dist/modes/rpc/remote-origin.js +58 -0
- package/dist/modes/rpc/rpc-protocol-info-types.d.ts +8 -0
- package/dist/modes/rpc/rpc-question-types.d.ts +7 -0
- package/dist/modes/rpc/rpc-question-types.js +0 -3
- package/dist/modes/rpc/rpc-session-command-types.d.ts +3 -0
- package/dist/modes/rpc/session-registry.js +12 -3
- package/dist/modes/rpc/session-worker-client.js +2 -0
- package/dist/modes/rpc/session-worker-protocol.d.ts +3 -0
- package/dist/modes/rpc/session-worker.js +2 -0
- package/docs/engine-socket/fixtures/admission-routes/c-baseline.json +3 -3
- package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
- package/docs/engine-socket/fixtures/admission-routes/i-reset-stream.json +3 -3
- package/docs/engine-socket/fixtures/recovery-manifest/index.json +32 -0
- package/docs/engine-socket/fixtures/recovery-manifest/one-partial-family.json +118 -0
- package/docs/rpc.md +93 -3
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-7UC4W2T2.js +0 -2
- package/dist/bundle/chunks/chunk-R23WXN4L.js +0 -448
- package/dist/bundle/chunks/chunk-W5NLCRB3.js +0 -2
package/dist/bundle/chunks/{multi-session-host-7E26R5JF.js → multi-session-host-N2RQ7JSZ.js}
RENAMED
|
@@ -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-6STZ65LL.js";import{AcceptedTranscript,CALL_NAMED_RECORDS,CALL_RECORDS,CALL_UNKNOWN,COMPACT_LEAF_CODE_UNITS,COMPONENT_RECORDS,CompactCommitDependencies,CompactComponentRoots,CompactContentStore,CompactCurrentComponents,CompactIndexTree,CompactReadError,CompactReadLease,CompactStorageReadError,CompactValues,CompactWriteError,FRAGMENT_ENVELOPE_MAX_BYTES,FRAGMENT_MAX_BYTES,GeneratedFramesCursor,RecoveryStorageHealth,SEQUENCED,SessionEventWriter,TERMINAL_PHASE,TRANSFER_STAGING_MAX_BYTES,TransferStaging,TransferStagingError,admitRecord,answerSetSessionContext,answerSubscribeSessions,answerUnsubscribeSessions,applyContextPatch,callIdentity,callLeaves,callOrder,captureAdmissionReply,correlationChange,enqueueLegacyRecord,field,jsonChunks,notAttachedRefusal,parseBoundedId,privateRootStat,protocolId,publishedSessionContext,recordLoopBlockedMs,recoveryAgentDir,registryStatusSource,runtimeItemKey,socketSink,storageUnavailable,terminal,toolcallIndex,withAdmissionReply,withAdmissionRequest}from"./chunk-FJSJUVQQ.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,StructuredLaneUnavailableError,bindToProviderScope,createAgentSessionRuntime,createRpcConnectionHandler,createWebViewBroker,foreignSessionHolders,isMoveId,isPlainId,isSecurityNoticeState,movedStateDir,outgoingStateDir,parseMoveId,parsePermissionPresetName,parsePlainId,pathExists,prepareOutgoingState,readCodemodeKernelRows,readMainThreadHeapBytes,readManifest,readRecordedRepositoryIdentity,readSessionCwd,rebindSessionFile,runWithProviderScope,sealedOutgoingStateDir,sessionWorkerDataRegistry,sha256File,sharedPathIdentityResolver,startHostChildReaper,structuredLaneEnabled,subscriptionLimits,verifyBundle}from"./chunk-ZSVWKOAJ.js";import"./chunk-LMIETUPG.js";import{SessionHeldError,encodedSessionId,liveSessionHolders,readProcessStartMs,serializeByKey,withSessionMoveLock}from"./chunk-TXOR5BQL.js";import"./chunk-FO56LSUK.js";import"./chunk-PIAY636U.js";import{CONNECTION_ROLE_FIXED,ClientAdmissions,ConnectionRoles,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,EMPTY_SESSION_CONTEXT,EffectLedger,advertisedCompactCapabilities,answerEffectFromTranscript,answeredUiRequestId,beginEffect,buildRpcSessionState,carriesExtensionOwner,drainSessionEffects,effectAnswer,installSessionEffectSink,isEffectBegin,isGrantSelectRequest,latestSessionEffect,recoveryCarrier,refusedExtensionUiResponse,roleConnection,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionRetryFallbackError,setSessionRecoveryEpoch}from"./chunk-R23WXN4L.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_ENV,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_UNSUPPORTED_TRANSPORT,RPC_ERROR_WARM_FAILED,STEER_WHEN_IDLE_CAPABILITY,USER_ACTIVITY_CAPABILITY}from"./chunk-VRKA3LIT.js";import"./chunk-ETCYVVVO.js";import{isRecord}from"./chunk-7ICGN62G.js";import"./chunk-3ESZE3DG.js";import"./chunk-R65P6LAT.js";import{liveToolMediaScope,toolMediaPersister}from"./chunk-GIY7PGOH.js";import"./chunk-FEQDJBDL.js";import"./chunk-XLLQJALL.js";import{SESSION_MOVED,SESSION_MOVED_IN,SESSION_RECLAIMED,SESSION_RELEASED,SessionManager,SessionMovedAwayError,assertValidSessionId,compactUpdatesEnabled,compareRepositoryIdentities,getDefaultSessionDir,headerSessionId,loadEntriesFromFileAsync,ownershipStep,readRepositoryIdentity,sessionOwnership}from"./chunk-662SCMTH.js";import{resolveMovedPath}from"./chunk-L5OFGHDA.js";import"./chunk-UURGXV5B.js";import"./chunk-QLTQ3UUI.js";import{OPEN_AFTER_QUEUED_DEADLINE_MS}from"./chunk-J2OBN7TI.js";import"./chunk-Y4MPEIY5.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-7FUO655J.js";import"./chunk-LGO25HPL.js";import"./chunk-BW4YXS7X.js";import"./chunk-57MRFI6E.js";import"./chunk-Y3TMJV3J.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,HostIdleHandover,agentDirMismatch,beginHandoverResponse,handoverRefusal,isHandoffBusy,isHostIdle,isTransientDaemonEnvName,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-P4AT7SBE.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,PROVIDER_ACCOUNT_TEST_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,RESUME_SESSION_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_ENV_CAPABILITY,SESSION_HELD_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_RELOCATION_CAPABILITY,SESSION_STATUS_CAPABILITY,TOOL_BARRIER_CAPABILITY,WARM_CAPABILITY,computeRuntimeBuildId,hostGeneration,hostInstanceId,parseClientCapabilities,pathIdentityResolverStatus,protocolIdentity}from"./chunk-NYXXKS6D.js";import"./chunk-XGBRBCIQ.js";import"./chunk-QMRJYMNH.js";import"./chunk-WEGTCUO3.js";import"./chunk-GDPWQJDQ.js";import{presenterBootstrapStream}from"./chunk-7DWTKE4Z.js";import{ClientOccupancy,PublicRpcConnection,acceptInternalConnection,armHostWatchdog,consumeHostWatchdogEnv,loopLagErrorMs,prepareSocketPath,scrubHostWatchdogEnv}from"./chunk-S2M5D5GS.js";import{CHILD_STOP_TIMEOUT_MS,SESSION_PATH_RETRY_AFTER_MS,createEndpointReservations,holderGenerationEnded,hostChildDrainRequestFile,ownGenerationDir,parseIdleExitMs,watchDrainRequest,writeHeartbeat,writeStallEvidence}from"./chunk-6LDUM5CL.js";import{HOST_DAEMON_DIR_ENV,canonicalSessionPath,createHostDaemonPaths,sessionDirectoryRemoved}from"./chunk-FNBEICAA.js";import{RpcPublicEndpoint}from"./chunk-E6UCZ7E5.js";import"./chunk-UYO5Z35O.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-H52J72VA.js";import"./chunk-SGS76663.js";import"./chunk-H4QOEVS5.js";import"./chunk-O4GRBX4R.js";import"./chunk-KVPRQ5KN.js";import"./chunk-W5NLCRB3.js";import"./chunk-ZNPH5BWS.js";import"./chunk-6VWIMHMH.js";import"./chunk-7ORS33CE.js";import"./chunk-KLAX467B.js";import"./chunk-SAZ6E74O.js";import{lockWithLossHandling}from"./chunk-F7GBSQRV.js";import"./chunk-GZVCRV7I.js";import{external_exports}from"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import{FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,isLockError}from"./chunk-7X72IACK.js";import"./chunk-YWD54RHU.js";import"./chunk-SOMFLLPD.js";import{isHostOwnedToolRuntimeCapability,isSpawnedBy,toolRuntimeCapabilities}from"./chunk-27XEDYQA.js";import"./chunk-26UBFF6N.js";import{readOwnFootprint}from"./chunk-MTQQ2VQH.js";import"./chunk-HB35RBP4.js";import"./chunk-YU2P3CAR.js";import"./chunk-LPHUMR6R.js";import"./chunk-IYL5E4QQ.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-QAM6AXA2.js";import"./chunk-D2ROBVZ4.js";import{killTrackedDetachedChildren}from"./chunk-T5ZJ2Q4O.js";import"./chunk-YU4AYH4C.js";import"./chunk-N4TSAHRL.js";import"./chunk-LNAZ7XEU.js";import"./chunk-DLAY7CIU.js";import"./chunk-IHOQR7TU.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-V36CXIIB.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-TG4E7Z7W.js";import"./chunk-32R442XT.js";import"./chunk-WHPDEDCC.js";import"./chunk-7UC4W2T2.js";import"./chunk-HK46JMSC.js";import"./chunk-ED7VJGL4.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import"./chunk-TBARMJ75.js";import"./chunk-3SASTB6Y.js";import{SeedFrontierError,seedNextOffset}from"./chunk-5CSZPC55.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-6APXZK7W.js";import"./chunk-WOHQJ6JB.js";import"./chunk-PP52OWBB.js";import"./chunk-IWM5QRAE.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-6WISUXVI.js";import"./chunk-XVRRNJQD.js";import"./chunk-42XRJQM6.js";import"./chunk-2SOVDETB.js";import"./chunk-UKSFF47T.js";import{PUBLIC_SOCKET_IDENTITY_FILE,readSocketIdentityFile,shieldSocketDuringClose,socketEntryReplaced,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-OM7LH7AP.js";import{SOCKET_SECRET_FILE_ENV,acquireOwnershipSafeLock,authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-QEESHRTS.js";import{VERSION,envValue,isBunBinary,normalizePath,resolvePath}from"./chunk-ISZ4EWIS.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import{ownProcessStartedAtMs}from"./chunk-QN2BHP3M.js";import"./chunk-AOTHPTMU.js";import{processStartTimeMs}from"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{randomUUID as randomUUID9}from"node:crypto";import{createServer as createServer2}from"node:net";import{mkdtemp as mkdtemp2,rm as rm9}from"node:fs/promises";import{tmpdir as tmpdir3}from"node:os";import{basename as basename2,dirname as dirname3,join as join12}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,identity2,publicSocket,log){return this.record=superseded.then(replaced=>({type:"host_superseded",...identity2,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-6STZ65LL.js";import{AcceptedTranscript,CALL_NAMED_RECORDS,CALL_RECORDS,CALL_UNKNOWN,COMPACT_LEAF_CODE_UNITS,COMPONENT_RECORDS,CompactCommitDependencies,CompactComponentRoots,CompactContentStore,CompactCurrentComponents,CompactIndexTree,CompactReadError,CompactReadLease,CompactStorageReadError,CompactValues,CompactWriteError,FRAGMENT_ENVELOPE_MAX_BYTES,FRAGMENT_MAX_BYTES,GeneratedFramesCursor,RecoveryStorageHealth,SEQUENCED,SessionEventWriter,TERMINAL_PHASE,TRANSFER_STAGING_MAX_BYTES,TransferStaging,TransferStagingError,admitRecord,answerSetSessionContext,answerSubscribeSessions,answerUnsubscribeSessions,applyContextPatch,callIdentity,callLeaves,callOrder,captureAdmissionReply,correlationChange,enqueueLegacyRecord,field,jsonChunks,notAttachedRefusal,parseBoundedId,privateRootStat,protocolId,publishedSessionContext,recordLoopBlockedMs,recoveryAgentDir,registryStatusSource,runtimeItemKey,socketSink,storageUnavailable,terminal,toolcallIndex,withAdmissionReply,withAdmissionRequest}from"./chunk-TOOB6OLG.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,StructuredLaneUnavailableError,bindToProviderScope,createAgentSessionRuntime,createRpcConnectionHandler,createWebViewBroker,foreignSessionHolders,isMoveId,isPlainId,isSecurityNoticeState,movedStateDir,outgoingStateDir,parseMoveId,parsePermissionPresetName,parsePlainId,pathExists,prepareOutgoingState,readCodemodeKernelRows,readMainThreadHeapBytes,readManifest,readRecordedRepositoryIdentity,readSessionCwd,rebindSessionFile,runWithProviderScope,sealedOutgoingStateDir,sessionWorkerDataRegistry,sha256File,sharedPathIdentityResolver,startHostChildReaper,structuredLaneEnabled,subscriptionLimits,verifyBundle}from"./chunk-ZNLCKKF6.js";import"./chunk-4BF4FLT6.js";import{SessionHeldError,encodedSessionId,liveSessionHolders,readProcessStartMs,serializeByKey,withSessionMoveLock}from"./chunk-6BSMXZKQ.js";import"./chunk-BNIZP4OS.js";import"./chunk-PIAY636U.js";import{CONNECTION_ROLE_FIXED,ClientAdmissions,ConnectionRoles,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,EMPTY_SESSION_CONTEXT,EffectLedger,advertisedCompactCapabilities,answerEffectFromTranscript,answeredUiRequestId,beginEffect,buildRpcSessionState,carriesExtensionOwner,drainSessionEffects,effectAnswer,installSessionEffectSink,isEffectBegin,isGrantSelectRequest,latestSessionEffect,originField,recoveryCarrier,refusedExtensionUiResponse,remoteOriginDeclaration,roleConnection,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionRetryFallbackError,setSessionRecoveryEpoch}from"./chunk-5DZD623T.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_ENV,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_UNSUPPORTED_TRANSPORT,RPC_ERROR_WARM_FAILED,STEER_WHEN_IDLE_CAPABILITY,USER_ACTIVITY_CAPABILITY}from"./chunk-VRKA3LIT.js";import"./chunk-ETCYVVVO.js";import{isRecord}from"./chunk-7ICGN62G.js";import"./chunk-3ESZE3DG.js";import"./chunk-R65P6LAT.js";import{liveToolMediaScope,toolMediaPersister}from"./chunk-DPBPO5OU.js";import"./chunk-FEQDJBDL.js";import"./chunk-XLLQJALL.js";import{SESSION_MOVED,SESSION_MOVED_IN,SESSION_RECLAIMED,SESSION_RELEASED,SessionManager,SessionMovedAwayError,assertValidSessionId,compactUpdatesEnabled,compareRepositoryIdentities,getDefaultSessionDir,headerSessionId,loadEntriesFromFileAsync,ownershipStep,readRepositoryIdentity,sessionOwnership}from"./chunk-VPDQ6MOL.js";import{resolveMovedPath}from"./chunk-L5OFGHDA.js";import"./chunk-UURGXV5B.js";import"./chunk-DAPBNRN5.js";import{OPEN_AFTER_QUEUED_DEADLINE_MS}from"./chunk-J2OBN7TI.js";import"./chunk-Y4MPEIY5.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-MOOFLKLI.js";import"./chunk-LGO25HPL.js";import"./chunk-WCRNJYHO.js";import"./chunk-57MRFI6E.js";import"./chunk-Y3TMJV3J.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,HostIdleHandover,agentDirMismatch,beginHandoverResponse,handoverRefusal,isHandoffBusy,isHostIdle,isTransientDaemonEnvName,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-HBCNDC53.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,PROVIDER_ACCOUNT_TEST_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,RESUME_SESSION_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_ENV_CAPABILITY,SESSION_HELD_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_RELOCATION_CAPABILITY,SESSION_STATUS_CAPABILITY,TOOL_BARRIER_CAPABILITY,WARM_CAPABILITY,computeRuntimeBuildId,hostGeneration,hostInstanceId,parseClientCapabilities,pathIdentityResolverStatus,protocolIdentity}from"./chunk-F4OHTL2K.js";import"./chunk-XGBRBCIQ.js";import"./chunk-QMRJYMNH.js";import"./chunk-WEGTCUO3.js";import"./chunk-GDPWQJDQ.js";import{presenterBootstrapStream}from"./chunk-7DWTKE4Z.js";import{ClientOccupancy,PublicRpcConnection,acceptInternalConnection,armHostWatchdog,consumeHostWatchdogEnv,loopLagErrorMs,prepareSocketPath,scrubHostWatchdogEnv}from"./chunk-S2M5D5GS.js";import{CHILD_STOP_TIMEOUT_MS,SESSION_PATH_RETRY_AFTER_MS,createEndpointReservations,holderGenerationEnded,hostChildDrainRequestFile,ownGenerationDir,parseIdleExitMs,watchDrainRequest,writeHeartbeat,writeStallEvidence}from"./chunk-6LDUM5CL.js";import{HOST_DAEMON_DIR_ENV,canonicalSessionPath,createHostDaemonPaths,sessionDirectoryRemoved}from"./chunk-FNBEICAA.js";import{RpcPublicEndpoint}from"./chunk-E6UCZ7E5.js";import"./chunk-UYO5Z35O.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-H52J72VA.js";import"./chunk-SGS76663.js";import"./chunk-H4QOEVS5.js";import"./chunk-3WJ2DE2G.js";import"./chunk-FLM6GZPT.js";import"./chunk-ESQBKTNG.js";import"./chunk-ZNPH5BWS.js";import"./chunk-6VWIMHMH.js";import"./chunk-7ORS33CE.js";import"./chunk-KLAX467B.js";import"./chunk-SAZ6E74O.js";import{lockWithLossHandling}from"./chunk-F7GBSQRV.js";import"./chunk-GZVCRV7I.js";import{external_exports}from"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import{FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,isLockError}from"./chunk-7X72IACK.js";import"./chunk-YWD54RHU.js";import"./chunk-SOMFLLPD.js";import{isHostOwnedToolRuntimeCapability,isSpawnedBy,toolRuntimeCapabilities}from"./chunk-27XEDYQA.js";import"./chunk-26UBFF6N.js";import{readOwnFootprint}from"./chunk-MTQQ2VQH.js";import"./chunk-HB35RBP4.js";import"./chunk-YU2P3CAR.js";import"./chunk-LPHUMR6R.js";import"./chunk-IYL5E4QQ.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-QTQ3ES2S.js";import"./chunk-D2ROBVZ4.js";import{killTrackedDetachedChildren}from"./chunk-4SENPCEA.js";import"./chunk-YU4AYH4C.js";import"./chunk-EVTTLPIY.js";import"./chunk-LNAZ7XEU.js";import"./chunk-DLAY7CIU.js";import"./chunk-PX7FF5LE.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-V36CXIIB.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-TG4E7Z7W.js";import"./chunk-32R442XT.js";import"./chunk-WHPDEDCC.js";import"./chunk-MOH5HOHX.js";import"./chunk-HK46JMSC.js";import"./chunk-ED7VJGL4.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import"./chunk-TBARMJ75.js";import"./chunk-3SASTB6Y.js";import{SeedFrontierError,seedNextOffset}from"./chunk-5CSZPC55.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-6APXZK7W.js";import"./chunk-WOHQJ6JB.js";import"./chunk-PP52OWBB.js";import"./chunk-7KLEFHSU.js";import"./chunk-ZOFZRJSL.js";import"./chunk-ZFIC2DZV.js";import"./chunk-6WISUXVI.js";import"./chunk-XVRRNJQD.js";import"./chunk-42XRJQM6.js";import"./chunk-2SOVDETB.js";import"./chunk-UKSFF47T.js";import{PUBLIC_SOCKET_IDENTITY_FILE,readSocketIdentityFile,shieldSocketDuringClose,socketEntryReplaced,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-OM7LH7AP.js";import{SOCKET_SECRET_FILE_ENV,acquireOwnershipSafeLock,authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-QEESHRTS.js";import{VERSION,envValue,isBunBinary,normalizePath,resolvePath}from"./chunk-ISZ4EWIS.js";import"./chunk-ATQFN5HI.js";import"./chunk-EYSV6A7S.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import{ownProcessStartedAtMs}from"./chunk-QN2BHP3M.js";import"./chunk-AOTHPTMU.js";import{processStartTimeMs}from"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{randomUUID as randomUUID9}from"node:crypto";import{createServer as createServer2}from"node:net";import{mkdtemp as mkdtemp2,rm as rm9}from"node:fs/promises";import{tmpdir as tmpdir3}from"node:os";import{basename as basename2,dirname as dirname3,join as join12}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,identity2,publicSocket,log){return this.record=superseded.then(replaced=>({type:"host_superseded",...identity2,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 CALLER_ENV_NAMES_ENV="SENPI_RPC_CALLER_ENV_NAMES",DEFAULT_CALLER_ENV_NAMES=Object.freeze(["OMOCAT_LANE"]),MAX_SESSION_ENV_ENTRIES=16,MAX_SESSION_ENV_VALUE_LENGTH=4096,ENV_NAME=/^[A-Z_][A-Z0-9_]*$/u,MAX_ECHOED_NAME_LENGTH=64;function callerEnvPassableNames(hostEnv=process.env){let names=new Set(DEFAULT_CALLER_ENV_NAMES);for(let raw of(hostEnv[CALLER_ENV_NAMES_ENV]??"").split(",")){let name=raw.trim();ENV_NAME.test(name)&&!isTransientDaemonEnvName(name)&&names.add(name)}return names}function sessionEnvShapeError(value){if(value===void 0)return;if(!isPlainRecord(value))return"env must be an object of strings.";let entries=Object.entries(value);if(entries.length>MAX_SESSION_ENV_ENTRIES)return`env allows at most ${MAX_SESSION_ENV_ENTRIES} entries.`;for(let[name,entry]of entries){if(!ENV_NAME.test(name))return`env name "${echoedName(name)}" must match ${ENV_NAME.source}.`;if(typeof entry!="string")return`env.${echoedName(name)} must be a string.`;if(entry.includes("\0"))return`env.${echoedName(name)} must not contain NUL.`;if(entry.length>MAX_SESSION_ENV_VALUE_LENGTH)return`env.${echoedName(name)} must be at most ${MAX_SESSION_ENV_VALUE_LENGTH} characters.`}}function sessionEnvError(value,hostEnv=process.env){let shape=sessionEnvShapeError(value);if(shape!==void 0||!isPlainRecord(value))return shape;let passable=callerEnvPassableNames(hostEnv);for(let name of Object.keys(value))if(!passable.has(name))return`env.${echoedName(name)} is not a caller-passable name (passable: ${[...passable].sort().join(", ")}).`}function inheritedSessionEnv(parent,requested){let merged={...parent,...requested};return Object.keys(merged).length===0?void 0:merged}function echoedName(name){return name.length>MAX_ECHOED_NAME_LENGTH?`${name.slice(0,MAX_ECHOED_NAME_LENGTH)}...`:name}function isPlainRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}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&&sessionEnvShapeError(record.sessionEnv)===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_recovery_page","release_recovery","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.sessionEnv?{sessionEnv:Object.freeze({...profile.sessionEnv})}:{},...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}`})}import{randomUUID as randomUUID2}from"node:crypto";import{tmpdir}from"node:os";import{join as join3}from"node:path";var OWNER_UNKNOWN=Object.freeze({ownerUnknown:!0}),MessageIdentities=class{constructor(){this.joins=new Map,this.unvouched=new Set,this.overflowed=!1,this.evictions=0,this.overflows=0}reset(){this.joins.clear(),this.unvouched.clear(),this.overflowed=!1,this.held=void 0}status(){return{ownerJoinsEvicted:this.evictions,ownerJoinsOverflowed:this.overflows}}joined(transition,owner){if(transition.kind!=="append")return;if(owner===void 0){transition.owningMessageId!==void 0&&this.unvouch(transition.id);return}if(this.joins.set(transition.id,owner),this.joins.size<=1024)return;let[oldest]=this.joins.keys();oldest!==void 0&&(this.joins.delete(oldest),this.evictions+=1,this.unvouch(oldest))}unvouch(entryId){if(this.unvouched.add(entryId),this.unvouched.size<=4096)return;let[forgotten]=this.unvouched.keys();forgotten!==void 0&&this.unvouched.delete(forgotten),this.overflows+=1,!this.overflowed&&(this.overflowed=!0,process.stderr.write(`senpi rpc acceptance: unvouched-owner ring overflowed (4096; evicted or never-joined owned entries); unmatched entries carry ownerUnknown until the epoch ends
|
|
@@ -8,7 +8,7 @@ import{getInternalHostBootstrap}from"./chunk-6STZ65LL.js";import{AcceptedTranscr
|
|
|
8
8
|
`)}};var AcceptedRootReads=class{constructor(){this.live=new Set,this.rootOwners=new WeakMap,this.current=new CompactLaneCurrent}get liveRoots(){return this.live.size}holds(root){return this.live.has(root)}readCurrent(root){if(!this.live.has(root))throw new Error("accepted root released");return this.current.read(root.current)}readCurrentComponents(root){if(!this.live.has(root))throw new Error("accepted root released");return this.current.readComponents(root.current)}readCurrentActive(root){if(!this.live.has(root))throw new Error("accepted root released");return this.current.readActive(root.current)}readCurrentCalls(root){if(!this.live.has(root))throw new Error("accepted root released");return this.current.readCalls(root.current)}cutStorage(root,use){return this.current.cutStorage(root.current,use)}readSettled(root){return this.settledOwner(root).read(root.settled)}settledOf(root){return this.settledOwner(root).reader(root.settled)}settledOwner(root){let owner=this.rootOwners.get(root);if(!owner||!this.live.has(root))throw new Error("accepted root released");return owner}};import{createHash as createHash2,randomUUID}from"node:crypto";import{constants}from"node:fs";import{lstat,mkdir as mkdir2,open,rename,rm as rm2}from"node:fs/promises";import{join as join2}from"node:path";var RANGE=1024;async function syncDirectory(path){let directory=await open(path,"r");try{await directory.sync()}finally{await directory.close()}}var SessionGenerations=class{constructor(agentDir){this.issued=0,this.ceiling=Number.MAX_SAFE_INTEGER,this.failed=!1,this.closed=!1,this.binding=0,this.pending=Promise.resolve(),this.agentDir=agentDir,this.dir=join2(agentDir,`.senpi-recovery-generations-${process.getuid?.()??"user"}`)}bind(sessionId){let path=join2(this.dir,createHash2("sha256").update(sessionId).digest("hex"));if(this.closed||path===this.path)return this.pending;let previous=this.path;return this.path=path,this.binding++,this.pending=this.pending.then(async()=>{await this.release?.(),this.release=void 0,this.failed=!1,this.issued=this.ceiling=previous?Math.max(this.issued,this.ceiling):this.issued,await this.initialize(path)}).catch(cause=>this.unavailable(cause)).finally(()=>{this.binding--}),this.pending}async initialize(path){if(await mkdir2(this.dir,{mode:448,recursive:!0}),!privateRootStat(await lstat(this.dir)))throw new CompactReadError("ownership");await syncDirectory(this.agentDir),this.release=await acquireOwnershipSafeLock(`${path}.lock`,{retries:{retries:0,minTimeout:0,maxTimeout:1}});try{let file=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{let stat=await file.stat();if(!stat.isFile()||stat.size>32)throw new CompactReadError("integrity");let text3=await file.readFile("utf8"),floor=Number(text3);if(!/^(0|[1-9]\d*)$/.test(text3)||!Number.isSafeInteger(floor))throw new CompactReadError("integrity");this.issued=this.ceiling=Math.max(this.issued,floor)}finally{await file.close()}}catch(cause){if(!(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"))throw cause}await this.reserve(path)}next(){if(this.closed||this.failed||this.binding>0||this.issued>=this.ceiling)return;let generation=++this.issued;return this.path&&this.ceiling-generation===RANGE/2&&(this.pending=this.reserve(this.path).catch(cause=>this.unavailable(cause))),generation}async reserve(path){let next=Math.min(Number.MAX_SAFE_INTEGER,this.ceiling+RANGE);if(next<=this.ceiling)throw new CompactReadError("unavailable");let temporary=`${path}.${randomUUID()}.tmp`;try{let file=await open(temporary,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL,384);try{await file.writeFile(String(next)),await file.sync()}finally{await file.close()}await rename(temporary,path),await syncDirectory(this.dir),this.ceiling=next}finally{await rm2(temporary,{force:!0})}}unavailable(cause){if(this.failed=!0,!(cause instanceof Error))throw cause}idle(){return this.pending}close(){this.closed||(this.closed=!0,this.pending=this.pending.then(async()=>{await this.release?.(),this.release=void 0}))}};var RETIRED_SETTLED=Object.freeze({base:void 0,overrides:void 0}),SessionAcceptanceLane=class extends AcceptedRootReads{constructor(storage,diagnose=reason=>process.stderr.write(`senpi rpc acceptance: settled transition: ${reason}
|
|
9
9
|
`),agentDir=recoveryAgentDir){super(),this.epoch="",this.sequence=0,this.activeMessageId=null,this.turnId=null,this.correlation=null,this.refusedCorrelations=0,this.identities=new MessageIdentities,this.storageRetired=!1,this.nonce=randomUUID2(),this.cleanup=Promise.resolve(),this.compact=()=>({settled:this.settled,current:this.current}),this.generations=new SessionGenerations(agentDir),this.storage={...storage,dir:storage?.dir??tmpdir(),health:storage?.health??new RecoveryStorageHealth(agentDir)},this.diagnose=diagnose;let dir=join3(storage?.dir??tmpdir(),`senpi-transcript-${randomUUID2()}`);this.staging=new TransferStaging(new CompactContentStore({...this.storage,dir})),this.transcript=new AcceptedTranscript(this.staging)}get recoveryEpoch(){return this.nonce}get acceptedSequence(){return this.sequence}get sessionEpoch(){return this.epoch}get retired(){return this.retiredAs!==void 0}get retirement(){return this.retiredAs}get openBroadcastDialogs(){return this.retired?void 0:this.current.openBroadcastDialogs}bootstrap(input,nonce=randomUUID2()){this.retired||(this.settled&&this.retireSettled(),this.identities.reset(),this.nonce=nonce,input.epochSignal&&Buffer.from(nonce,"ascii").copy(Buffer.from(input.epochSignal)),this.settled=new CompactSettledMessages(nonce,{...this.storage,dir:join3(this.storage?.dir??tmpdir(),`senpi-settled-${randomUUID2()}`)},this.diagnose),this.epoch=randomUUID2(),this.current.bootstrap({...this.storage,dir:join3(this.storage?.dir??tmpdir(),`senpi-current-${randomUUID2()}`),epoch:nonce,sessionEpoch:this.epoch}),this.sequence=0,this.transcript.release(),this.transcript=new AcceptedTranscript(this.staging),this.transcript.bootstrap(input.transcript),this.activeMessageId=null,this.turnId=null,this.correlation=null,this.refusedCorrelations=0)}applyTranscript(transitions){if(!(this.retired||this.epoch===""))for(let transition of transitions){this.sequence+=1,this.transcript.apply(transition);let owner=foldCompactTransition(this.compact(),transition,this.transcript.available,this.nonce);this.identities.joined(transition,owner)}}accept(record,carrier,canonical,canonicalRefused=!1){let type=field(record,"type");if(this.identities.clear(),this.retired||this.epoch===""||typeof type!="string"||!SEQUENCED.has(type))return;this.beforeAccept?.(record);let folds=!canonicalRefused&&this.current.admits(record,type),correlation=folds?correlationChange(this.correlation,this.turnId,record):void 0,at={sequence:this.sequence+(correlation?1:0),turnId:this.turnId},place=admitRecord(this.current,record,type,at,folds);if(!place)return;!folds&&correlationChange(this.correlation,this.turnId,record)&&(this.refusedCorrelations+=1),correlation&&(this.correlation=Object.freeze({sequence:place.sequence-1,...correlation}));let{turnId,call}=place;this.turnId=turnId,this.sequence=place.sequence,(type==="turn_end"||type==="agent_end")&&(this.turnId=null);let messageId=type.startsWith("message_")&&this.settled.valid(carrier)?carrier.messageId:null;type==="message_start"&&(this.activeMessageId=messageId);let unit={record,type,carrier,canonical,sequence:this.sequence,turnId,call};return this.identities.hold(type,this.sequence,record,folds?foldCompactRecord(this.compact(),unit):void 0),type==="message_end"&&this.activeMessageId===messageId&&(this.activeMessageId=null),{sessionEpoch:this.epoch,sequence:this.sequence,historyVersion:this.transcript.historyVersion,messageId,turnId}}acceptControl(unit){if(!(this.retired||this.epoch===""||!unit))return this.beforeAccept?.({type:"materializer_control"}),this.sequence+=1,this.current.fold(unit,this.sequence),this.sequence}compactUnavailable(cause){this.retired||this.current.fail(cause)}freeze(){let root=Object.freeze({sessionEpoch:this.epoch,sequence:this.sequence,activeMessageId:this.activeMessageId,turnId:this.turnId,correlation:this.correlation,refusedCorrelations:this.refusedCorrelations,transcript:this.transcript.freeze(),settled:this.retired?RETIRED_SETTLED:this.settled.freeze(),current:this.retired?void 0:this.current.freeze()});return this.retired||(this.rootOwners.set(root,this.settled),this.live.add(root),root.transcript.tail.retainCut(root.transcript.count)),root}release(root){this.live.delete(root)&&(root.transcript.tail.releaseCut(root.transcript.count),this.rootOwners.get(root)?.release(root.settled),this.current.release(root.current),this.retired&&this.retireStorage())}storageStatus(){return{...this.settled.storageStatus(),refusedRecords:this.current.refusedRecords,...this.identities.status(),transcript:this.staging.status()}}async idle(){await this.generations.idle(),await this.cleanup,await this.settled.idle(),await this.current.idle(),await this.staging.idle()}retireSettled(){for(let root of this.live)this.release(root);this.cleanup=Promise.all([this.cleanup,this.settled.retire()]).then(()=>{}),this.cleanup.catch(()=>this.diagnose("retired_owner"))}retire(reason,keep=new Set){this.retiredAs??=reason,this.identities.reset(),this.generations.close(),this.transcript=new AcceptedTranscript(this.staging);for(let root of this.live)keep.has(root)||this.release(root);this.retireStorage()}retireStorage(){this.storageRetired||this.live.size>0||(this.storageRetired=!0,this.settled&&this.retireSettled(),this.current.retire(),this.cleanup=Promise.all([this.cleanup,this.staging.close()]).then(()=>{}),this.cleanup.catch(()=>this.diagnose("retired_owner")))}};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)}
|
|
10
10
|
`)}function beginSessionClose(host,handle2,onRole,options){let entry=host.get(handle2);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing")return onRole?.(!1),entry;if(entry.state!=="open")throw new RpcSessionRegistryError("unknown_session");return entry.attachments-=1,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry.detachedAt??=host.now(),entry.reservationKey&&!sessionIsWriting(entry)&&host.markDetached(entry.reservationKey),entry):(entry.state="closing",onRole?.(!0),entry.closeCompletion=new Promise(resolve2=>{entry.closeResolve=resolve2}),entry)}async function releaseWithinGrace(host,handle2,key){let timer,late=new Promise(resolve2=>{timer=setTimeout(()=>resolve2("late"),host.closeGraceMs)}),removal=host.releaseReservation(key).then(()=>"removed",cause=>(reportDetachedFailure(handle2,cause),"failed")),outcome=await Promise.race([removal,late]);clearTimeout(timer),outcome==="late"&&reportDetachedFailure(handle2,new Error(`session path reservation was not removed within ${host.closeGraceMs} ms; closing anyway`))}function closeSession(host,handle2){return beginSessionClose(host,handle2).state!=="closing"?Promise.resolve():closeMarkedSession(host,handle2)}function closeMarkedSession(host,handle2){host.sync();let entry=host.get(handle2);if(entry?.state!=="closing")throw new RpcSessionRegistryError("unknown_session");let completion=entry.closeCompletion;if(!completion)return Promise.resolve();if(entry.closeStarted)return completion;entry.closeStarted=!0;let previousLifecycle=entry.lifecycleMutex,releaseTimer,released=!1,disposePromise,scopeClosed=!1,disposeOnce=()=>disposePromise||(disposePromise=Promise.resolve(entry.runtime?.dispose()),disposePromise),closeScopeOnce=async()=>{scopeClosed||(scopeClosed=!0,await disposeOnce().catch(()=>{}),await entry.scope.close?.())},release=async()=>{released||(released=!0,releaseTimer&&clearTimeout(releaseTimer),entry.reservationKey&&await releaseWithinGrace(host,handle2,entry.reservationKey),entry.state="closed",host.delete(handle2))},graceful=(async()=>{await previousLifecycle;try{await entry.runtime?.session.abort()}catch(cause){reportDetachedFailure(handle2,cause)}try{await entry.runtime?.session.waitForIdle()}catch(cause){reportDetachedFailure(handle2,cause)}try{await disposeOnce()}catch(cause){reportDetachedFailure(handle2,cause)}try{await closeScopeOnce()}catch(cause){reportDetachedFailure(handle2,cause)}})(),settled=!1,finish=async()=>{settled||(settled=!0,await release(),entry.closeResolve?.())};return releaseTimer=setTimeout(()=>{disposeOnce().catch(cause=>reportDetachedFailure(handle2,cause)),closeScopeOnce().catch(cause=>reportDetachedFailure(handle2,cause)),graceful.catch(cause=>reportDetachedFailure(handle2,cause)),finish()},host.closeGraceMs),graceful.then(finish,cause=>(reportDetachedFailure(handle2,cause),finish())),completion}async function openRegistrySession(host,requested,options){host.validateProfile(requested);let profile=resolveMovedProfile(requested);host.syncRuntimeMetadata();let sessionPath=profile.sessionPath?canonicalSessionPath(profile.sessionPath):void 0,requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){for(let entry2 of host.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(sessionPath!==void 0&&entry2.reservationKey===sessionPath))throw new RpcSessionRegistryError("session_id_in_use")}if(sessionPath){await settleClosingReservation(host.entries.values(),sessionPath,host.closeGraceMs);let deadline=Date.now()+host.closeGraceMs;for(;host.pendingClaims.has(sessionPath);)await settlePendingClaim(host.pendingClaims,sessionPath,Math.max(0,deadline-Date.now()))}if(sessionPath&&host.reservations.has(sessionPath))return attachToOpenSession(host.entries,sessionPath,profile,options,host.options.pathReservations,host.now());if(options?.attachOnly)throw new RpcSessionRegistryError("session_not_held",void 0,{reason:"session_not_held",action:"rediscover_holder"});let claimSettled;sessionPath&&(host.reservations.add(sessionPath),host.options.pathReservations&&(claimSettled=await takeCrossGenerationClaim(host.reservations,host.pendingClaims,host.options.pathReservations,sessionPath)));let handle2=host.nextHandle(),opening;try{opening=buildOpeningEntry({profile,sessionPath,requestedDurableId,options,now:host.now(),createRuntime:host.options.createRuntime,sync:()=>host.syncRuntimeMetadata()})}catch(cause){try{sessionPath&&(host.reservations.delete(sessionPath),await host.options.pathReservations?.release(sessionPath))}catch(releaseCause){process.stderr.write(`senpi rpc open of ${sessionPath} could not release its claim: ${String(releaseCause)}
|
|
11
|
-
`)}finally{claimSettled?.()}throw cause}let{entry,storedProfile,runtimeProfile,sessionStartEvent,settleOpen}=opening;host.entries.set(handle2,entry),claimSettled?.(),host.options.onSizeChange?.(host.entries.size);try{let newSessionOptions={...requestedDurableId!==void 0?{id:requestedDurableId}:{},...storedProfile.spawnedBy?{spawnedBy:storedProfile.spawnedBy}:{}},manager=sessionPath?host.options.sessionFileLoad==="blocking"?SessionManager.open(sessionPath,void 0,storedProfile.cwd,newSessionOptions):await SessionManager.openAsync(sessionPath,void 0,storedProfile.cwd,newSessionOptions,host.options.createSlicer?.()):SessionManager.create(storedProfile.cwd,void 0,newSessionOptions);return entry.runtime=await runWithProviderScope(entry.scope,()=>createAgentSessionRuntime(host.options.createRuntime,{cwd:manager.getCwd(),agentDir:host.options.agentDir,sessionManager:manager,sessionStartEvent,launchProfile:runtimeProfile})),assertRequestedModelResolved(runtimeProfile,entry.runtime.diagnostics),ClientAdmissions.sealQueuedOnReplace(entry.runtime),EffectLedger.sealOnReplace(entry.runtime),entry.durableSessionId=manager.getSessionId(),entry.sessionPath??=manager.getSessionFile(),host.options.workerIsolate!==!0&&structuredLaneEnabled()&&(entry.acceptance=new SessionAcceptanceLane(void 0,void 0,host.options.agentDir),await entry.acceptance.generations.bind(entry.durableSessionId),entry.acceptance.bootstrap({transcript:manager.beginTranscriptJournal()}),setSessionRecoveryEpoch(entry.runtime.session,entry.acceptance.recoveryEpoch)),entry.state="open",settleOpen.resolve(),{sessionId:handle2,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath}}catch(error2){try{await entry.runtime?.dispose()}catch{}finally{try{await entry.scope.close?.()}finally{host.entries.delete(handle2),host.options.onSizeChange?.(host.entries.size),sessionPath&&await releaseWithinGrace(host.teardownHost,handle2,sessionPath)}}if(error2 instanceof RpcSessionRegistryError)throw settleOpen.reject(error2),error2;let wrapped=new RpcSessionRegistryError("open_failed",error2 instanceof Error?error2.message:void 0);throw settleOpen.reject(wrapped),wrapped}}var RpcSessionRegistry=class{get agentDir(){return this.options.agentDir}constructor(options){this.entries=new Map,this.reservations=new Set,this.pendingClaims=new Map,this.nextHandle=0,options.createRuntime.prepare&&(this.warm=createRegistryWarm(options.createRuntime.prepare,{agentDir:options.agentDir,...options.mcpRegistry!==void 0?{mcpRegistry:options.mcpRegistry}:{}})),this.options=options.mcpRegistry===void 0?options:{...options,createRuntime:runtimeOptions=>options.createRuntime({...runtimeOptions,mcpRegistry:options.mcpRegistry})},this.supportsCompact=options.createRuntime.supportsCompact??(()=>!1),this.now=options.now??Date.now,this.closeGraceMs=options.closeGraceMs??1e4,this.teardownHost={closeGraceMs:this.closeGraceMs,get:handle2=>this.entries.get(handle2),delete:handle2=>{let deleted=this.entries.delete(handle2);return this.options.onSizeChange?.(this.entries.size),deleted},releaseReservation:async key=>{await this.options.pathReservations?.release(key)
|
|
11
|
+
`)}finally{claimSettled?.()}throw cause}let{entry,storedProfile,runtimeProfile,sessionStartEvent,settleOpen}=opening;host.entries.set(handle2,entry),claimSettled?.(),host.options.onSizeChange?.(host.entries.size);try{let newSessionOptions={...requestedDurableId!==void 0?{id:requestedDurableId}:{},...storedProfile.spawnedBy?{spawnedBy:storedProfile.spawnedBy}:{}},manager=sessionPath?host.options.sessionFileLoad==="blocking"?SessionManager.open(sessionPath,void 0,storedProfile.cwd,newSessionOptions):await SessionManager.openAsync(sessionPath,void 0,storedProfile.cwd,newSessionOptions,host.options.createSlicer?.()):SessionManager.create(storedProfile.cwd,void 0,newSessionOptions);return entry.runtime=await runWithProviderScope(entry.scope,()=>createAgentSessionRuntime(host.options.createRuntime,{cwd:manager.getCwd(),agentDir:host.options.agentDir,sessionManager:manager,sessionStartEvent,launchProfile:runtimeProfile})),assertRequestedModelResolved(runtimeProfile,entry.runtime.diagnostics),ClientAdmissions.sealQueuedOnReplace(entry.runtime),EffectLedger.sealOnReplace(entry.runtime),entry.durableSessionId=manager.getSessionId(),entry.sessionPath??=manager.getSessionFile(),host.options.workerIsolate!==!0&&structuredLaneEnabled()&&(entry.acceptance=new SessionAcceptanceLane(void 0,void 0,host.options.agentDir),await entry.acceptance.generations.bind(entry.durableSessionId),entry.acceptance.bootstrap({transcript:manager.beginTranscriptJournal()}),setSessionRecoveryEpoch(entry.runtime.session,entry.acceptance.recoveryEpoch)),entry.state="open",settleOpen.resolve(),{sessionId:handle2,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath}}catch(error2){try{await entry.runtime?.dispose()}catch{}finally{try{await entry.scope.close?.()}finally{host.entries.delete(handle2),host.options.onSizeChange?.(host.entries.size),sessionPath&&await releaseWithinGrace(host.teardownHost,handle2,sessionPath)}}if(error2 instanceof RpcSessionRegistryError)throw settleOpen.reject(error2),error2;let wrapped=new RpcSessionRegistryError("open_failed",error2 instanceof Error?error2.message:void 0);throw settleOpen.reject(wrapped),wrapped}}var RpcSessionRegistry=class{get agentDir(){return this.options.agentDir}constructor(options){this.entries=new Map,this.reservations=new Set,this.pendingClaims=new Map,this.nextHandle=0,options.createRuntime.prepare&&(this.warm=createRegistryWarm(options.createRuntime.prepare,{agentDir:options.agentDir,...options.mcpRegistry!==void 0?{mcpRegistry:options.mcpRegistry}:{}})),this.options=options.mcpRegistry===void 0?options:{...options,createRuntime:runtimeOptions=>options.createRuntime({...runtimeOptions,mcpRegistry:options.mcpRegistry})},this.supportsCompact=options.createRuntime.supportsCompact??(()=>!1),this.now=options.now??Date.now,this.closeGraceMs=options.closeGraceMs??1e4,this.teardownHost={closeGraceMs:this.closeGraceMs,get:handle2=>this.entries.get(handle2),delete:handle2=>{let deleted=this.entries.delete(handle2);return this.options.onSizeChange?.(this.entries.size),deleted},releaseReservation:async key=>{let settle=beginPendingClaim(this.pendingClaims,key);try{await this.options.pathReservations?.release(key)}finally{this.reservations.delete(key),settle()}},markDetached:key=>this.options.pathReservations?.setAttached(key,!1),now:()=>this.now(),sync:()=>this.syncRuntimeMetadata()}}get size(){return this.entries.size}holderPids(observedStarts){return this.options.pathReservations?.holderPids?.(observedStarts)??Promise.resolve([])}openSession(requested,options){return openRegistrySession({entries:this.entries,reservations:this.reservations,pendingClaims:this.pendingClaims,options:this.options,teardownHost:this.teardownHost,closeGraceMs:this.closeGraceMs,now:this.now,nextHandle:()=>`rpc-${++this.nextHandle}`,validateProfile:profile=>this.validateProfile(profile),syncRuntimeMetadata:()=>this.syncRuntimeMetadata()},requested,options)}peek(handle2){return this.entries.get(handle2)}attachSession(handle2){let entry=this.entries.get(handle2);return attachLiveSession(entry,this.now(),()=>markPathAttached(entry,this.options.pathReservations))}getForCommand(handle2,command){let entry=this.entries.get(handle2);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress","host_response"].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){return beginSessionClose(this.teardownHost,handle2,onRole,options)}async close(handle2){return closeSession(this.teardownHost,handle2)}async closeMarked(handle2){return closeMarkedSession(this.teardownHost,handle2)}list(){this.syncRuntimeMetadata();let now=this.now();return[...this.entries].map(([sessionId,entry])=>({sessionId,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,cwd:entry.cwd,name:entry.runtime?.session.sessionManager.getSessionName(),kind:entry.kind,context:publishedSessionContext(entry.context,entry.contextOverlay),attachments:Math.max(0,entry.attachments),retain_on_disconnect:entry.retainOnDisconnect===!0,status:entry.state==="quarantined"?"closing":entry.state,idleMs:Math.max(0,now-entry.lastCommandAt),tool_child:entry.runtime?.session.toolChildRow()??{state:"none"}}))}syncRuntimeMetadata(){syncRuntimeMetadata(this.entries.values(),this.reservations,this.options.pathReservations)}validateProfile(profile){if(!isAbsolute2(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute2(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");if(profile.durableSessionId!==void 0)try{assertValidSessionId(profile.durableSessionId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}}};var HANDOVER_PARKED_REOPEN_BUDGET_MS=12e4,HANDOVER_PARKED_REOPEN_POLL_MS=250,HANDOVER_PARKED_REOPEN_MAX_ATTEMPTS=8,HANDOVER_PARKED_REOPEN_QUIET_STREAK=8;async function reopenHandoverParkedSessions(open3,agentDir,socket,holder){let daemonDir=createHostDaemonPaths({socket,agentDir}).dir,deadline=Date.now()+HANDOVER_PARKED_REOPEN_BUDGET_MS,reopenAttempts=new Map,heldPolls=new Map,emptyStreak=0,sawAnyPark=!1;for(;;){if(holder?.shouldReopen!==void 0&&!holder.shouldReopen())return;let parked=await inheritedParks(daemonDir,holder);for(let entry of parked)sawAnyPark=!0,await reopenOne(daemonDir,open3,entry,reopenAttempts,heldPolls,holder);let remaining=(await inheritedParks(daemonDir,holder)).length;if(holder?.shouldReopen!==void 0&&!holder.shouldReopen()||(emptyStreak=remaining===0?emptyStreak+1:0,sawAnyPark&&emptyStreak>=HANDOVER_PARKED_REOPEN_QUIET_STREAK)||Date.now()>=deadline)return;await new Promise(resolve2=>setTimeout(resolve2,HANDOVER_PARKED_REOPEN_POLL_MS))}}async function inheritedParks(daemonDir,holder){return(await readHandoverParkedSessions(daemonDir)).filter(entry=>entry.parkedBy===void 0||entry.parkedBy!==holder?.hostInstance)}async function reopenOne(daemonDir,open3,entry,attempts,heldPolls,holder){let taskStatus=entry.contextOverlay&&Object.hasOwn(entry.contextOverlay,"task_status")?entry.contextOverlay.task_status:entry.sessionContext?.task_status;if(typeof taskStatus=="string"&&["completed","cancelled","error","failed","lost","interrupted"].includes(taskStatus)){await clearHandoverParkedSession(daemonDir,entry.sessionPath),process.stderr.write(`senpi rpc successor dropped a terminal parked session (${taskStatus}): ${entry.sessionPath}
|
|
12
12
|
`);return}if(await dropHandoverParkedSessionIfFileGone(daemonDir,entry.sessionPath),!existsSync4(entry.sessionPath)){process.stderr.write(`senpi rpc successor dropped a parked session whose file is gone: ${entry.sessionPath}
|
|
13
13
|
`);return}try{if(await open3(entry),holder?.shouldReopen!==void 0&&!holder.shouldReopen())return;await clearHandoverParkedSession(daemonDir,entry.sessionPath)}catch(cause){if(cause instanceof RpcSessionRegistryError&&cause.code==="session_path_in_use"){let polls=(heldPolls?.get(entry.sessionPath)??0)+1;heldPolls?.set(entry.sessionPath,polls),(polls===1||polls%40===0)&&process.stderr.write(`senpi rpc successor reopen parked session ${entry.sessionPath} waiting on the holder: ${String(cause)}
|
|
14
14
|
`);return}let tried=(attempts.get(entry.sessionPath)??0)+1;if(attempts.set(entry.sessionPath,tried),tried>=HANDOVER_PARKED_REOPEN_MAX_ATTEMPTS){process.stderr.write(`senpi rpc successor gave up reopening parked session ${entry.sessionPath} after ${tried} attempts: ${String(cause)}
|
|
@@ -33,13 +33,13 @@ import{getInternalHostBootstrap}from"./chunk-6STZ65LL.js";import{AcceptedTranscr
|
|
|
33
33
|
`),droppedAfterClose=!0},writeRecord=record=>{if(entry.scope.state==="closed")return dropAfterClose();writeInScope(record)},writeStructuredInScope=bindToProviderScope(record=>{writer.structuredLanes.accept(sessionId,record);let control=pairing?.structured(record);control&&lane?lane.acceptControl(unit(control.carrier,control.record)):control&&writer.enqueueCanonical(sessionId,control)}),taggedSink={writeRecord,...structured?{writeStructured:record=>{entry.scope.state!=="closed"&&writeStructuredInScope(record)},structuredFailed:cause=>{lane?lane.compactUnavailable(cause):writer.canonicalUnavailable(sessionId,cause)}}:{},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,rpcOwner:()=>{let owner=writer.connectionContext.owner,connection=writer.currentConnection();return owner&&connection&&rpcOwnersByConnection.set(connection,owner),owner},retireRpcBinding:()=>{rpcBindingGeneration=randomUUID3(),rpcOwnersByConnection.clear()},publishLoadedSurfacesChanged:(previous,digest)=>{entry.scope.state!=="closed"&&writer.publishLoadedSurfacesChanged(sessionId,previous,digest)},...options,workerSecurityBridge:writer.workerSecurityBridge,secretInputRoute:writer.secretInputRoute(sessionId),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=>{if(writer.handleMcpForm(command))return Promise.resolve();let invoke=()=>runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command)));return carriesExtensionOwner(command)?writer.connectionContext.withBinding(rpcBindingGeneration,invoke):invoke()},cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),pendingPrompts:()=>handler.pendingPrompts(),connectionDetached:connectionId=>{rpcOwnersByConnection.get(connectionId)?.retire(),rpcOwnersByConnection.delete(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.admissions=compactUpdatesEnabled()?new CompactAdmissions(ADMISSION_LIMITS,(socketEpoch,admissionId)=>this.writer.routesAdmission(socketEpoch,admissionId)):void 0,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.drainHeldSessions=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,capabilities:connectionOptions.capabilities&&advertisedCompactCapabilities(connectionOptions.capabilities,!1)},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{createHash as createHash4}from"node:crypto";function admissionBaseline(reply,identity2,live,routes){return new GeneratedFramesCursor(!1,async function*(){let answer3=await reply;if(answer3!==void 0&&(yield serializeJsonLine(answer3),live()))for(let admissionId of routes??[identity2.admissionId])yield serializeJsonLine({type:"recovery_manifest",...identity2,admissionId,componentRef:identity2.componentRef??"manifest"})},()=>{})}var RouteAnnouncement=class _RouteAnnouncement{constructor(reason){this.reason=reason}static emit(reason,emit){return emit(),new _RouteAnnouncement(reason)}};var OpenRefused=class extends Error{constructor(response){super("compact open refused"),this.response=response,this.name="OpenRefused"}};async function compactOpen(host,command,physical){let peer=host.writer.currentConnection(),socketEpoch=peer===void 0?void 0:host.writer.socketEpochOf(peer),admissions=host.admissions;if(peer===void 0||socketEpoch===void 0||admissions===void 0)return error(command.id,command.type,"unsupported_transport");let{id:_request,admissionId,...request}=command;if(admissionId===void 0)throw new CompactAdmissionError("malformed_request");let fingerprint=createHash4("sha256").update(JSON.stringify(Object.entries(request).sort(([a],[b])=>a.localeCompare(b)))).digest("hex"),delivery,baseline,completedOpen,accepted,announced,retireAfterReply,answerFinally=emit=>{announced=RouteAnnouncement.emit("open_ended",emit),retireAfterReply?.(announced),retireAfterReply=void 0},cancelledAnswer=async()=>{let result=await admissions.result(socketEpoch,admissionId);if(!(result?.state!=="cancelled"||typeof result.answer.generation!="number"))return{id:command.id,type:"response",command:command.type,success:!1,error:"attempt_cancelled",errorCode:"attempt_cancelled",code:"attempt_cancelled",admissionId,generation:result.answer.generation}};try{let answer3=await admissions.run({socketEpoch,peer,admissionId,fingerprint},async signal=>{let result,physicalSucceeded=!1,response2=await physical(async opened=>{let sessionId=opened.sessionId,lane=host.writer.recoveryLane(sessionId);if(!lane)throw new CompactAdmissionError("storage_unavailable");let caller={socketEpoch,sessionId},checkpoints=host.writer.recoveryCheckpoints,frozen=checkpoints.freeze({...caller,peer,admissionId,routeKind:"ordinary"},lane,!0);if(!frozen.ok)throw new CompactAdmissionError("storage_unavailable");let token=frozen.value.token,identity2={sessionId,admissionId,generation:token.admission.generation,token:token.id},active=!0;delivery=Promise.withResolvers();let reply=delivery.promise;host.writer.registerAdmission(peer,admissionId,sessionId),baseline=()=>host.writer.installAdmissionBaseline(peer,admissionBaseline(reply,identity2,()=>active),()=>host.writer.socketEpochOf(peer)===socketEpoch),accepted={admissionId,generation:token.admission.generation};let retire2=retirement=>{checkpoints.retireRoute(caller,admissionId,retirement),host.writer.unregisterAdmission(peer,admissionId)},release=async superseded=>{active&&(active=!1,superseded?retire2("reopen_superseded"):announced?retire2(announced):retireAfterReply=retire2,physicalSucceeded&&(releaseOwnerAttachment(host,peer,sessionId),await releaseDisconnectAttachment(host,sessionId)))};completedOpen={sessionId,release:()=>release(!0)},result={answer:{type:"response",command:command.type,success:!0,sessionId,admissionId,generation:token.admission.generation,data:{sessionId,...opened.attached?{attached:!0}:{},recovery:{token:token.id,componentRef:"manifest"}}},release:()=>release(!1)}},signal).catch(async cause=>{throw await result?.release(),cause});if(response2!==void 0)throw await result?.release(),new OpenRefused(response2);if(result===void 0)throw new CompactAdmissionError("storage_unavailable");return physicalSucceeded=!0,result}),cancelled=await cancelledAnswer(),response=cancelled??{...answer3,id:command.id};if(delivery){(cancelled===void 0&&answer3.success===!0&&completedOpen?host.writer.supersedeOpen(peer,completedOpen.sessionId,admissionId,completedOpen.release):void 0)?.().catch(cause=>process.stderr.write(`senpi rpc superseded open release failed: ${String(cause)}
|
|
34
34
|
`));let reply=delivery,deliver=()=>{baseline?.(),reply.resolve(response)};cancelled?answerFinally(deliver):deliver()}else await host.writer.enqueueControl(response,peer);return}catch(cause){if(delivery?.resolve(void 0),!(cause instanceof OpenRefused)&&!(cause instanceof CompactAdmissionError)){let unexpected={...error(command.id,command.type,code(cause)),...accepted};throw accepted&&answerFinally(()=>{host.writer.enqueueControl(unexpected,peer).catch(written2=>{process.stderr.write(`senpi rpc failed open's refusal not written: ${String(written2)}
|
|
35
35
|
`)})}),cause}let refusal4=cause instanceof OpenRefused?cause.response:await cancelledAnswer()??error(command.id,command.type,`admission_${cause.reason}`,{kind:"request_refused",reason:cause.reason,hint:"new_request"});if(accepted===void 0)return refusal4;let ended={...refusal4,...accepted},written;answerFinally(()=>{written=host.writer.enqueueControl(ended,peer)}),await written;return}}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(`
|
|
36
|
-
`)){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);if(retryFallbackError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${retryFallbackError}`);let envError=sessionEnvError(command.env);if(envError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_ENV}: ${envError}`);let sessionEnv=inheritedSessionEnv(parentSessionEnv(host,command.spawnedBy?.parentSessionId),command.env);return{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}:{},...sessionEnv!==void 0?{sessionEnv}:{}}}function parentSessionEnv(host,parentSessionId){if(parentSessionId===void 0)return;let parent=host.registry.list().find(row=>row.durableSessionId===parentSessionId||row.sessionId===parentSessionId);if(parent===void 0)return;let entry=host.registry.peek(parent.sessionId);return entry?.state==="open"&&host.bindings.has(parent.sessionId)?entry.profile.sessionEnv:void 0}function openWithBarrier(host,command){return compactUpdatesEnabled()&&command.admissionId!==void 0?compactOpen(host,command,(accept,signal)=>openPhysicalWithBarrier(host,command,accept,signal)):openPhysicalWithBarrier(host,command)}function openPhysicalWithBarrier(host,command,accept,signal){let owner=host.writer.currentConnection();if(owner===void 0)return open2(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 start=()=>open2(host,command,owner,accept===void 0?void 0:{accept,signal}),opened=signal===void 0?start():runAdmissionProducer(signal,start,async()=>{});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 open2(host,{...parkedOpenCommand(entry),attended:!1},void 0,{reply:!1,defaults:!1,contextOverlay:entry.contextOverlay})}async function open2(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),options?.signal?.throwIfAborted(),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}),options?.signal?.throwIfAborted();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;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)));let lane=entry.acceptance??entry.worker?.acceptance;if(lane&&host.writer.registerAcceptance(openedSession.sessionId,lane),options?.accept&&await options.accept(openedSession),owner!==void 0&&(host.writer.hasRegisteredConnectionCapabilities(owner)||host.writer.setConnectionCapabilities(owner,host.pendingCapabilities.get(owner)??host.connectionOptions?.capabilities??[]),host.writer.attachConnectionToSession(owner,openedSession.sessionId,options?.accept!==void 0)),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_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)})}if(options?.signal?.throwIfAborted(),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")),!options?.accept&&!host.draining&&owner!==void 0&&host.releasedConnections.has(owner)&&(releaseOwnerAttachment(host,owner,openedSession.sessionId),await releaseOwnedSession(host,openedSession.sessionId)),options?.accept)return;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&&!options?.signal?.aborted){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{}(!opened.attached||!compactUpdatesEnabled())&&host.writer.forgetSession(opened.sessionId)}if(cause instanceof CompactAdmissionError)throw cause;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]}}}function declareSocketClient(host,command){let peer=host.writer.currentConnection(),selection=peer===void 0?void 0:host.writer.compactSelection(peer),role=caps=>host.connectionRoles.declare(roleConnection(peer),caps),reason=selection?selection.declare(command.capabilities,host.registry.supportsCompact?.()===!0,role):command.capabilities!==void 0&&!role(command.capabilities)?"connection_role_fixed":void 0;if(reason)return error(command.id,command.type,reason==="connection_role_fixed"?CONNECTION_ROLE_FIXED:reason);if(peer!==void 0){let caps=compactUpdatesEnabled()?selection?.capabilities??command.capabilities??host.pendingCapabilities.get(peer)??[]:command.capabilities??[];host.pendingCapabilities.set(peer,[...caps]),host.writer.setConnectionCapabilities(peer,caps)}else command.capabilities!==void 0&&host.writer.setSoleSecretCapabilities(command.capabilities);return{id:command.id,type:"response",command:"set_client_info",success:!0,...selection?.ack()?{data:selection.ack()}:{}}}function compactAdmissionGate(host,command){if(!compactUpdatesEnabled())return;let peer=host.writer.currentConnection(),selection=peer===void 0?void 0:host.writer.compactSelection(peer);if(!(command.type==="open_session"||command.type==="attach_session"||command.type==="reclaim_session"||command.type==="reset_stream"||command.type==="subscribe_sessions"&&(command.admissionId!==void 0||command.mirror!==void 0&&command.mirror!=="none")))return;let refuse=reason=>error(command.id,command.type,reason);if(selection?.refused)return refuse("compact_selection_refused");if(command.admissionId!==void 0&&!selection?.selected)return refuse("compact_not_negotiated");if(selection?.selected){if((command.type==="open_session"||command.type==="attach_session"||command.type==="subscribe_sessions")&&command.admissionId===void 0)return refuse("compact_admission_required");if(command.type==="open_session"&&host.registry.supportsCompact?.({...host.defaults,...command})!==!0||command.type==="attach_session"&&!host.writer.recoveryLane(command.sessionId)||command.type==="subscribe_sessions"&&host.registry.list().some(row=>row.status==="open"&&!host.writer.recoveryLane(row.sessionId)))return refuse("compact_endpoint_unsupported")}selection&&(selection.admitted=!0)}function invalidCompactAdmission(command){if(!compactUpdatesEnabled()||command.type!=="cancel_attempt"&&command.type!=="reset_stream"&&!("admissionId"in command))return;let id="admissionId"in command?command.admissionId:void 0;if(!(typeof id=="string"&&parseBoundedId(id).ok))return error(command.id,command.type,"admission_malformed_request",{kind:"request_refused",reason:"malformed_request",hint:"new_request"})}function unknownCompactAdmission(host,command){if(!host.admissions||command.admissionId===void 0||command.type==="open_session"||command.type==="attach_session"||command.type==="subscribe_sessions"||command.type==="get_recovery_page"||command.type==="release_recovery")return;let admissionId=command.admissionId,peer=host.writer.currentConnection(),epoch=peer===void 0?void 0:host.writer.socketEpochOf(peer);if(peer!==void 0&&host.writer.holdsAdmission(peer,admissionId,"sessionId"in command?command.sessionId:void 0))return;let refusal4={id:command.id,type:"response",command:command.type,success:!1,error:"unknown_admission",errorCode:"unknown_admission",errorData:{code:"unknown_admission",admissionId},code:"unknown_admission",admissionId};return command.type==="cancel_attempt"&&epoch!==void 0?host.admissions.pending(epoch,admissionId).then(pending=>pending?void 0:refusal4,cause=>{if(!(cause instanceof CompactAdmissionError))throw cause;return error(command.id,command.type,`admission_${cause.reason}`,{kind:"request_refused",reason:cause.reason,hint:"new_request"})}):refusal4}import{createHash as createHash5}from"node:crypto";function statusSnapshot(events,socketEpoch,admissionId,sessionId,rows){let chunks=function*(){yield'{"seq":0,"snapshot":[';let comma="";for(let row of rows())yield comma,yield*jsonChunks(row,FRAGMENT_MAX_BYTES/2),comma=",";yield"]}"},minted=events.mint({socketEpoch,sessionId,admissionId},{sessionEpoch:hostInstanceId(),sequence:0},{},{chunks});if(!minted.ok)throw new CompactAdmissionError("storage_unavailable");return minted.value}async function compactSubscribe(host,command){let peer=host.writer.currentConnection(),socketEpoch=peer===void 0?void 0:host.writer.socketEpochOf(peer),events=host.writer.recoveryEvents,{admissionId,id,...request}=command;if(peer===void 0||socketEpoch===void 0||!events||!host.admissions||admissionId===void 0)return error(id,command.type,"unsupported_transport");let fingerprint=createHash5("sha256").update(JSON.stringify(Object.entries(request).sort(([a],[b])=>a.localeCompare(b)))).digest("hex"),delivery,baseline,cancelledAnswer=async()=>(await host.admissions?.result(socketEpoch,admissionId))?.state==="cancelled"?{id,type:"response",command:command.type,success:!1,code:"attempt_cancelled",errorCode:"attempt_cancelled",error:"attempt_cancelled",admissionId,generation:0}:void 0;try{let answer3=await host.admissions.run({peer,socketEpoch,admissionId,fingerprint},async()=>{let lease,subscribed=answerSubscribeSessions(command,peer,host.writer.status,(rows,subscriptionId2)=>{host.writer.registerSubscription(peer,admissionId,subscriptionId2),lease=statusSnapshot(events,socketEpoch,admissionId,subscriptionId2,rows)}),subscriptionId=subscribed.activate;if(!subscribed.answer.success||subscribed.answer.command!=="subscribe_sessions"||subscriptionId===void 0)return{answer:{...subscribed.answer},release:async()=>{}};if(lease===void 0)throw new CompactAdmissionError("storage_unavailable");let pending=host.writer.status.pendingBuffer(subscriptionId);if(!pending)throw new CompactAdmissionError("storage_unavailable");let eventLease=lease,identity2={sessionId:subscriptionId,admissionId,generation:0};delivery=Promise.withResolvers();let reply=delivery.promise,live=!0,installed=!1;baseline=()=>{installed||(installed=!0,host.writer.installAdmissionBaseline(peer,admissionBaseline(reply,{...identity2,eventLease,componentRef:"record"},()=>live),()=>host.writer.socketEpochOf(peer)===socketEpoch))};let{snapshot:_snapshot,...data2}=subscribed.answer.data;return{answer:{...subscribed.answer,...identity2,data:{...data2,recovery:eventLease}},activate:()=>{baseline?.(),host.writer.status.activate(subscriptionId)},refusal:()=>pending.reason===void 0?void 0:{...error(void 0,command.type,pending.reason,{kind:"request_refused",reason:pending.reason,hint:"new_request"}),admissionId,generation:0},release:async()=>{live&&(live=!1,host.writer.unregisterSubscription(peer,subscriptionId),host.writer.status.unsubscribe(peer,subscriptionId),events.abandon(socketEpoch,eventLease.id))}}});if(host.writer.socketEpochOf(peer)!==socketEpoch){delivery?.resolve(void 0);return}let response={...await cancelledAnswer()??answer3,id};delivery?(baseline?.(),delivery.resolve(response)):await host.writer.enqueueControl(response,peer);return}catch(cause){if(!(cause instanceof CompactAdmissionError))throw cause;let refusal4=await cancelledAnswer()??error(id,command.type,`admission_${cause.reason}`,{kind:"request_refused",reason:cause.reason,hint:"new_request"});if(delivery){baseline?.(),delivery.resolve({...refusal4});return}return refusal4}}async function resetStream(host,command){let peer=host.writer.currentConnection(),socketEpoch=peer===void 0?void 0:host.writer.socketEpochOf(peer),{sessionId,admissionId}=command,refused3=()=>error(command.id,command.type,"recovery_unknown_token",{kind:"repair_needed",reason:"unknown_token"});if(!host.admissions||peer===void 0||socketEpoch===void 0||sessionId===void 0)return refused3();let result=await host.admissions.result(socketEpoch,admissionId);if(result?.state!=="complete"||result.answer.sessionId!==sessionId&&!host.writer.isCompactSubscription(peer,admissionId,sessionId))return refused3();let checkpoints=host.writer.recoveryCheckpoints,caller={socketEpoch,sessionId},stream=checkpoints.stream(caller),lane=host.writer.recoveryLane(sessionId);if(!lane||!stream?.routes.includes(admissionId))return refused3();let routeKind=host.writer.isCompactSubscription(peer,admissionId,sessionId)?"mirror":"ordinary",frozen=checkpoints.freeze({...caller,peer,admissionId,routeKind},lane);if(!frozen.ok)return error(command.id,command.type,`recovery_${frozen.failure.kind}`,{...frozen.failure});let token=frozen.value.token,generation=token.admission.generation,answer3={id:command.id,type:"response",command:"reset_stream",success:!0,sessionId,admissionId,generation,data:{recovery:{token:token.id,componentRef:"manifest"}}};host.writer.installAdmissionBaseline(peer,admissionBaseline(Promise.resolve(answer3),{sessionId,admissionId,generation,token:token.id},()=>!0,stream.routes),()=>host.writer.socketEpochOf(peer)===socketEpoch)}import{createHmac,randomBytes,randomInt}from"node:crypto";var repairAdviceKey=randomBytes(32),tokenRetryAfterMs=token=>100+createHmac("sha256",repairAdviceKey).update(token,"utf8").digest().readUInt32BE(0)%1901,codeOf=failure=>failure.kind==="request_refused"?`recovery_${failure.reason}`:`recovery_${failure.kind}`;function callerOf(writer,command){let{id,type,sessionId}=command;if(sessionId===void 0)return error(id,type,RPC_ERROR_MISSING_SESSION_ID);let connection=writer.currentConnection(),socketEpoch=connection===void 0?void 0:writer.socketEpochOf(connection);return socketEpoch===void 0?error(id,type,RPC_ERROR_UNSUPPORTED_TRANSPORT):{socketEpoch,sessionId}}function refused(id,type,reason){let failure={kind:"request_refused",reason,hint:"new_request"};return error(id,type,codeOf(failure),{...failure})}async function answerRecoveryPage(pages,writer,command){let caller=callerOf(writer,command);if("type"in caller)return caller;let{id,type}=command,lane=writer.recoveryLane(caller.sessionId),outcome;try{outcome=await pages.request(caller,command)}catch(cause){if(!(cause instanceof CompactStorageReadError||cause instanceof CompactReadError))throw cause;outcome={ok:!1,failure:storageUnavailable("unavailable")}}let source=!outcome.ok&&(outcome.failure.kind==="request_refused"||outcome.failure.reason==="unknown_token")?void 0:lane,healthRevision=null;try{source&&(healthRevision=await source.staging.store.health.revision())}catch(cause){if(!(cause instanceof Error))throw cause;outcome={ok:!1,failure:storageUnavailable("unavailable")}}let failure=outcome.ok?void 0:outcome.failure;if(failure?.kind==="request_refused")return error(id,type,codeOf(failure),{...failure});let repair={state:failure?.kind??"ok",healthRevision,source:source?{sessionEpoch:source.sessionEpoch,sequence:source.acceptedSequence}:null,hint:"restart_from_catalog",retryAfterMs:outcome.ok?0:failure?.reason==="unknown_token"?tokenRetryAfterMs("lease"in command?command.lease.id:command.token):randomInt(100,2001)},ordinary=writer.ordinaryRoute(writer.currentConnection()??"",caller.sessionId),generation=outcome.ok&&"generation"in outcome.value?outcome.value.generation:ordinary?.routes.includes(command.admissionId)?ordinary.generation:writer.isCompactSubscription(writer.currentConnection()??"",command.admissionId,caller.sessionId)?0:void 0;return outcome.ok?{id,type:"response",command:type,success:!0,...generation!==void 0?{sessionId:caller.sessionId,admissionId:command.admissionId,generation}:{},data:{...outcome.value,repair}}:error(id,type,codeOf(outcome.failure),{...outcome.failure,repair})}function answerReleaseRecovery(events,writer,command){let caller=callerOf(writer,command);if("type"in caller)return caller;let{id,type,lease,admissionId}=command,kind=lease?.kind;if(kind==="checkpoint")return refused(id,type,"lease_kind_unsupported");if(kind!=="event"||typeof lease?.id!="string"||typeof admissionId!="string")return refused(id,type,"malformed_request");let outcome=events.release(caller,lease.id,admissionId);return outcome.ok?(writer.unregisterSubscription(writer.currentConnection()??"",caller.sessionId),{id,type:"response",command:type,success:!0,data:outcome.value}):error(id,type,codeOf(outcome.failure),{...outcome.failure})}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"});if(command.admissionId!==void 0&&host.admissions)return compactOpen(host,command,async(accept,signal)=>{signal.throwIfAborted(),attach(host,owner,command.sessionId);try{await accept({sessionId:command.sessionId,durableSessionId:command.durableSessionId,attached:!0})}catch(cause){throw releaseOwnerAttachment(host,owner,command.sessionId),await releaseDisconnectAttachment(host,command.sessionId),cause}});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)&&!(host.writer.recoveryPages!==void 0&&(command.type==="get_recovery_page"||command.type==="release_recovery"))&&!(host.writer.recoveryPages!==void 0&&command.type==="reset_stream"&&host.writer.isCompactSubscription(owner,command.admissionId,command.sessionId))&&!(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)
|
|
36
|
+
`)){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);if(retryFallbackError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${retryFallbackError}`);let envError=sessionEnvError(command.env);if(envError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_ENV}: ${envError}`);let sessionEnv=inheritedSessionEnv(parentSessionEnv(host,command.spawnedBy?.parentSessionId),command.env);return{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}:{},...sessionEnv!==void 0?{sessionEnv}:{}}}function parentSessionEnv(host,parentSessionId){if(parentSessionId===void 0)return;let parent=host.registry.list().find(row=>row.durableSessionId===parentSessionId||row.sessionId===parentSessionId);if(parent===void 0)return;let entry=host.registry.peek(parent.sessionId);return entry?.state==="open"&&host.bindings.has(parent.sessionId)?entry.profile.sessionEnv:void 0}function openWithBarrier(host,command){return compactUpdatesEnabled()&&command.admissionId!==void 0?compactOpen(host,command,(accept,signal)=>openPhysicalWithBarrier(host,command,accept,signal)):openPhysicalWithBarrier(host,command)}function openPhysicalWithBarrier(host,command,accept,signal){let owner=host.writer.currentConnection();if(owner===void 0)return open2(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 start=()=>open2(host,command,owner,accept===void 0?void 0:{accept,signal}),opened=signal===void 0?start():runAdmissionProducer(signal,start,async()=>{});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 open2(host,{...parkedOpenCommand(entry),attended:!1},void 0,{reply:!1,defaults:!1,contextOverlay:entry.contextOverlay})}async function open2(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),options?.signal?.throwIfAborted(),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}),options?.signal?.throwIfAborted();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;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)));let lane=entry.acceptance??entry.worker?.acceptance;if(lane&&host.writer.registerAcceptance(openedSession.sessionId,lane),options?.accept&&await options.accept(openedSession),owner!==void 0&&(host.writer.hasRegisteredConnectionCapabilities(owner)||host.writer.setConnectionCapabilities(owner,host.pendingCapabilities.get(owner)??host.connectionOptions?.capabilities??[]),host.writer.attachConnectionToSession(owner,openedSession.sessionId,options?.accept!==void 0)),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_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)})}if(options?.signal?.throwIfAborted(),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")),!options?.accept&&!host.draining&&owner!==void 0&&host.releasedConnections.has(owner)&&(releaseOwnerAttachment(host,owner,openedSession.sessionId),await releaseOwnedSession(host,openedSession.sessionId)),options?.accept)return;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&&!options?.signal?.aborted){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{}(!opened.attached||!compactUpdatesEnabled())&&host.writer.forgetSession(opened.sessionId)}if(cause instanceof CompactAdmissionError)throw cause;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]}}}function declareSocketClient(host,command){let peer=host.writer.currentConnection(),selection=peer===void 0?void 0:host.writer.compactSelection(peer),role=caps=>host.connectionRoles.declare(roleConnection(peer),caps),origin=remoteOriginDeclaration(command.remoteOrigin,declared=>host.connectionRoles.acceptsOrigin(roleConnection(peer),declared));if("refusal"in origin)return error(command.id,command.type,origin.refusal);let reason=selection?selection.declare(command.capabilities,host.registry.supportsCompact?.()===!0,role):command.capabilities!==void 0&&!role(command.capabilities)?"connection_role_fixed":void 0;if(reason)return error(command.id,command.type,reason==="connection_role_fixed"?CONNECTION_ROLE_FIXED:reason);if(peer!==void 0){let caps=compactUpdatesEnabled()?selection?.capabilities??command.capabilities??host.pendingCapabilities.get(peer)??[]:command.capabilities??[];host.pendingCapabilities.set(peer,[...caps]),host.writer.setConnectionCapabilities(peer,caps)}else command.capabilities!==void 0&&host.writer.setSoleSecretCapabilities(command.capabilities);return origin.origin!==void 0&&host.connectionRoles.declareOrigin(roleConnection(peer),origin.origin),{id:command.id,type:"response",command:"set_client_info",success:!0,...selection?.ack()?{data:selection.ack()}:{}}}function compactAdmissionGate(host,command){if(!compactUpdatesEnabled())return;let peer=host.writer.currentConnection(),selection=peer===void 0?void 0:host.writer.compactSelection(peer);if(!(command.type==="open_session"||command.type==="attach_session"||command.type==="reclaim_session"||command.type==="reset_stream"||command.type==="subscribe_sessions"&&(command.admissionId!==void 0||command.mirror!==void 0&&command.mirror!=="none")))return;let refuse=reason=>error(command.id,command.type,reason);if(selection?.refused)return refuse("compact_selection_refused");if(command.admissionId!==void 0&&!selection?.selected)return refuse("compact_not_negotiated");if(selection?.selected){if((command.type==="open_session"||command.type==="attach_session"||command.type==="subscribe_sessions")&&command.admissionId===void 0)return refuse("compact_admission_required");if(command.type==="open_session"&&host.registry.supportsCompact?.({...host.defaults,...command})!==!0||command.type==="attach_session"&&!host.writer.recoveryLane(command.sessionId)||command.type==="subscribe_sessions"&&host.registry.list().some(row=>row.status==="open"&&!host.writer.recoveryLane(row.sessionId)))return refuse("compact_endpoint_unsupported")}selection&&(selection.admitted=!0)}function invalidCompactAdmission(command){if(!compactUpdatesEnabled()||command.type!=="cancel_attempt"&&command.type!=="reset_stream"&&!("admissionId"in command))return;let id="admissionId"in command?command.admissionId:void 0;if(!(typeof id=="string"&&parseBoundedId(id).ok))return error(command.id,command.type,"admission_malformed_request",{kind:"request_refused",reason:"malformed_request",hint:"new_request"})}function unknownCompactAdmission(host,command){if(!host.admissions||command.admissionId===void 0||command.type==="open_session"||command.type==="attach_session"||command.type==="subscribe_sessions"||command.type==="get_recovery_page"||command.type==="release_recovery")return;let admissionId=command.admissionId,peer=host.writer.currentConnection(),epoch=peer===void 0?void 0:host.writer.socketEpochOf(peer);if(peer!==void 0&&host.writer.holdsAdmission(peer,admissionId,"sessionId"in command?command.sessionId:void 0))return;let refusal4={id:command.id,type:"response",command:command.type,success:!1,error:"unknown_admission",errorCode:"unknown_admission",errorData:{code:"unknown_admission",admissionId},code:"unknown_admission",admissionId};return command.type==="cancel_attempt"&&epoch!==void 0?host.admissions.pending(epoch,admissionId).then(pending=>pending?void 0:refusal4,cause=>{if(!(cause instanceof CompactAdmissionError))throw cause;return error(command.id,command.type,`admission_${cause.reason}`,{kind:"request_refused",reason:cause.reason,hint:"new_request"})}):refusal4}import{createHash as createHash5}from"node:crypto";function statusSnapshot(events,socketEpoch,admissionId,sessionId,rows){let chunks=function*(){yield'{"seq":0,"snapshot":[';let comma="";for(let row of rows())yield comma,yield*jsonChunks(row,FRAGMENT_MAX_BYTES/2),comma=",";yield"]}"},minted=events.mint({socketEpoch,sessionId,admissionId},{sessionEpoch:hostInstanceId(),sequence:0},{},{chunks});if(!minted.ok)throw new CompactAdmissionError("storage_unavailable");return minted.value}async function compactSubscribe(host,command){let peer=host.writer.currentConnection(),socketEpoch=peer===void 0?void 0:host.writer.socketEpochOf(peer),events=host.writer.recoveryEvents,{admissionId,id,...request}=command;if(peer===void 0||socketEpoch===void 0||!events||!host.admissions||admissionId===void 0)return error(id,command.type,"unsupported_transport");let fingerprint=createHash5("sha256").update(JSON.stringify(Object.entries(request).sort(([a],[b])=>a.localeCompare(b)))).digest("hex"),delivery,baseline,cancelledAnswer=async()=>(await host.admissions?.result(socketEpoch,admissionId))?.state==="cancelled"?{id,type:"response",command:command.type,success:!1,code:"attempt_cancelled",errorCode:"attempt_cancelled",error:"attempt_cancelled",admissionId,generation:0}:void 0;try{let answer3=await host.admissions.run({peer,socketEpoch,admissionId,fingerprint},async()=>{let lease,subscribed=answerSubscribeSessions(command,peer,host.writer.status,(rows,subscriptionId2)=>{host.writer.registerSubscription(peer,admissionId,subscriptionId2),lease=statusSnapshot(events,socketEpoch,admissionId,subscriptionId2,rows)}),subscriptionId=subscribed.activate;if(!subscribed.answer.success||subscribed.answer.command!=="subscribe_sessions"||subscriptionId===void 0)return{answer:{...subscribed.answer},release:async()=>{}};if(lease===void 0)throw new CompactAdmissionError("storage_unavailable");let pending=host.writer.status.pendingBuffer(subscriptionId);if(!pending)throw new CompactAdmissionError("storage_unavailable");let eventLease=lease,identity2={sessionId:subscriptionId,admissionId,generation:0};delivery=Promise.withResolvers();let reply=delivery.promise,live=!0,installed=!1;baseline=()=>{installed||(installed=!0,host.writer.installAdmissionBaseline(peer,admissionBaseline(reply,{...identity2,eventLease,componentRef:"record"},()=>live),()=>host.writer.socketEpochOf(peer)===socketEpoch))};let{snapshot:_snapshot,...data2}=subscribed.answer.data;return{answer:{...subscribed.answer,...identity2,data:{...data2,recovery:eventLease}},activate:()=>{baseline?.(),host.writer.status.activate(subscriptionId)},refusal:()=>pending.reason===void 0?void 0:{...error(void 0,command.type,pending.reason,{kind:"request_refused",reason:pending.reason,hint:"new_request"}),admissionId,generation:0},release:async()=>{live&&(live=!1,host.writer.unregisterSubscription(peer,subscriptionId),host.writer.status.unsubscribe(peer,subscriptionId),events.abandon(socketEpoch,eventLease.id))}}});if(host.writer.socketEpochOf(peer)!==socketEpoch){delivery?.resolve(void 0);return}let response={...await cancelledAnswer()??answer3,id};delivery?(baseline?.(),delivery.resolve(response)):await host.writer.enqueueControl(response,peer);return}catch(cause){if(!(cause instanceof CompactAdmissionError))throw cause;let refusal4=await cancelledAnswer()??error(id,command.type,`admission_${cause.reason}`,{kind:"request_refused",reason:cause.reason,hint:"new_request"});if(delivery){baseline?.(),delivery.resolve({...refusal4});return}return refusal4}}async function resetStream(host,command){let peer=host.writer.currentConnection(),socketEpoch=peer===void 0?void 0:host.writer.socketEpochOf(peer),{sessionId,admissionId}=command,refused3=()=>error(command.id,command.type,"recovery_unknown_token",{kind:"repair_needed",reason:"unknown_token"});if(!host.admissions||peer===void 0||socketEpoch===void 0||sessionId===void 0)return refused3();let result=await host.admissions.result(socketEpoch,admissionId);if(result?.state!=="complete"||result.answer.sessionId!==sessionId&&!host.writer.isCompactSubscription(peer,admissionId,sessionId))return refused3();let checkpoints=host.writer.recoveryCheckpoints,caller={socketEpoch,sessionId},stream=checkpoints.stream(caller),lane=host.writer.recoveryLane(sessionId);if(!lane||!stream?.routes.includes(admissionId))return refused3();let routeKind=host.writer.isCompactSubscription(peer,admissionId,sessionId)?"mirror":"ordinary",frozen=checkpoints.freeze({...caller,peer,admissionId,routeKind},lane);if(!frozen.ok)return error(command.id,command.type,`recovery_${frozen.failure.kind}`,{...frozen.failure});let token=frozen.value.token,generation=token.admission.generation,answer3={id:command.id,type:"response",command:"reset_stream",success:!0,sessionId,admissionId,generation,data:{recovery:{token:token.id,componentRef:"manifest"}}};host.writer.installAdmissionBaseline(peer,admissionBaseline(Promise.resolve(answer3),{sessionId,admissionId,generation,token:token.id},()=>!0,stream.routes),()=>host.writer.socketEpochOf(peer)===socketEpoch)}import{createHmac,randomBytes,randomInt}from"node:crypto";var repairAdviceKey=randomBytes(32),tokenRetryAfterMs=token=>100+createHmac("sha256",repairAdviceKey).update(token,"utf8").digest().readUInt32BE(0)%1901,codeOf=failure=>failure.kind==="request_refused"?`recovery_${failure.reason}`:`recovery_${failure.kind}`;function callerOf(writer,command){let{id,type,sessionId}=command;if(sessionId===void 0)return error(id,type,RPC_ERROR_MISSING_SESSION_ID);let connection=writer.currentConnection(),socketEpoch=connection===void 0?void 0:writer.socketEpochOf(connection);return socketEpoch===void 0?error(id,type,RPC_ERROR_UNSUPPORTED_TRANSPORT):{socketEpoch,sessionId}}function refused(id,type,reason){let failure={kind:"request_refused",reason,hint:"new_request"};return error(id,type,codeOf(failure),{...failure})}async function answerRecoveryPage(pages,writer,command){let caller=callerOf(writer,command);if("type"in caller)return caller;let{id,type}=command,lane=writer.recoveryLane(caller.sessionId),outcome;try{outcome=await pages.request(caller,command)}catch(cause){if(!(cause instanceof CompactStorageReadError||cause instanceof CompactReadError))throw cause;outcome={ok:!1,failure:storageUnavailable("unavailable")}}let source=!outcome.ok&&(outcome.failure.kind==="request_refused"||outcome.failure.reason==="unknown_token")?void 0:lane,healthRevision=null;try{source&&(healthRevision=await source.staging.store.health.revision())}catch(cause){if(!(cause instanceof Error))throw cause;outcome={ok:!1,failure:storageUnavailable("unavailable")}}let failure=outcome.ok?void 0:outcome.failure;if(failure?.kind==="request_refused")return error(id,type,codeOf(failure),{...failure});let repair={state:failure?.kind??"ok",healthRevision,source:source?{sessionEpoch:source.sessionEpoch,sequence:source.acceptedSequence}:null,hint:"restart_from_catalog",retryAfterMs:outcome.ok?0:failure?.reason==="unknown_token"?tokenRetryAfterMs("lease"in command?command.lease.id:command.token):randomInt(100,2001)},ordinary=writer.ordinaryRoute(writer.currentConnection()??"",caller.sessionId),generation=outcome.ok&&"generation"in outcome.value?outcome.value.generation:ordinary?.routes.includes(command.admissionId)?ordinary.generation:writer.isCompactSubscription(writer.currentConnection()??"",command.admissionId,caller.sessionId)?0:void 0;return outcome.ok?{id,type:"response",command:type,success:!0,...generation!==void 0?{sessionId:caller.sessionId,admissionId:command.admissionId,generation}:{},data:{...outcome.value,repair}}:error(id,type,codeOf(outcome.failure),{...outcome.failure,repair})}function answerReleaseRecovery(events,writer,command){let caller=callerOf(writer,command);if("type"in caller)return caller;let{id,type,lease,admissionId}=command,kind=lease?.kind;if(kind==="checkpoint")return refused(id,type,"lease_kind_unsupported");if(kind!=="event"||typeof lease?.id!="string"||typeof admissionId!="string")return refused(id,type,"malformed_request");let outcome=events.release(caller,lease.id,admissionId);return outcome.ok?(writer.unregisterSubscription(writer.currentConnection()??"",caller.sessionId),{id,type:"response",command:type,success:!0,data:outcome.value}):error(id,type,codeOf(outcome.failure),{...outcome.failure})}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"});if(command.admissionId!==void 0&&host.admissions)return compactOpen(host,command,async(accept,signal)=>{signal.throwIfAborted(),attach(host,owner,command.sessionId);try{await accept({sessionId:command.sessionId,durableSessionId:command.durableSessionId,attached:!0})}catch(cause){throw releaseOwnerAttachment(host,owner,command.sessionId),await releaseDisconnectAttachment(host,command.sessionId),cause}});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)&&!(host.writer.recoveryPages!==void 0&&(command.type==="get_recovery_page"||command.type==="release_recovery"))&&!(host.writer.recoveryPages!==void 0&&command.type==="reset_stream"&&host.writer.isCompactSubscription(owner,command.admissionId,command.sessionId))&&!(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)
|
|
37
37
|
`)}}import{isAbsolute as isAbsolute3,join as join10}from"node:path";import{copyFile,mkdir as mkdir3,readdir as readdir2,rename as rename2,rm as rm5,writeFile as writeFile3}from"node:fs/promises";import{basename,dirname,join as join7,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 rm5(staging,{recursive:!0,force:!0}),await mkdir3(join7(staging,dirname(SESSION_BUNDLE_PATH)),{recursive:!0}),await copyFile(sessionFile,join7(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(join7(staging,SESSION_BUNDLE_PATH))},sidecars,droppedUserMessages:[...options.droppedUserMessages],payloads:stateFiles.length>0?[{kind:EXTENSION_STATE_PAYLOAD,files:stateFiles}]:[]};return await writeFile3(join7(staging,MANIFEST_FILE),`${JSON.stringify(manifest,null,1)}
|
|
38
38
|
`),await rm5(options.bundleDir,{recursive:!0,force:!0}),await rename2(staging,options.bundleDir),manifest}async function copySidecars(sessionDir,sessionId,staging){let sources=[],extensions=join7(sessionDir,"extensions"),sidecarName=`${encodedSessionId(sessionId)}.json`;if(await pathExists(extensions))for(let extension of await readdir2(extensions,{withFileTypes:!0})){let file=join7(extensions,extension.name,sidecarName);extension.isDirectory()&&await pathExists(file)&&sources.push(file)}sources.push(...await filesUnder(join7(sessionDir,"resident-blobs",sessionId)));let files=[];for(let source of sources){let path=bundlePath("files",sessionDir,source);await mkdir3(dirname(join7(staging,path)),{recursive:!0}),await copyFile(source,join7(staging,path)),files.push({path,sha256:await sha256File(join7(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 mkdir3(dirname(join7(staging,path)),{recursive:!0}),await copyFile(source,join7(staging,path)),files.push({path,sha256:await sha256File(join7(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=join7(dir,entry.name);files.push(...entry.isDirectory()?await filesUnder(path):[path])}return files}import{rm as rm6}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,text3]of texts.entries())await inputs.admit({clientMessageId:`move:${moveId}:${index}`,text:text3,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 rm6(bundleDir,{recursive:!0,force:!0}),await rm6(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 mkdir5,readdir as readdir3,rm as rm7}from"node:fs/promises";import{dirname as dirname2,join as join9}from"node:path";import{mkdir as mkdir4,readFile as readFile3,rename as renameFile,writeFile as writeFile4}from"node:fs/promises";import{join as join8}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,rename3,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 rename3();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 join8(this.dir,`${parseMoveId(moveId)}.json`)}async raw(moveId){try{return JSON.parse(await readFile3(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 writeFile4(temp,`${JSON.stringify({...record,...landing,at:new Date().toISOString()})}
|
|
39
39
|
`),this.#locks.assertHeld(file),await renameFile(temp,file)}locked(moveId,fn){let file=this.path(moveId);return serializeByKey(file,async()=>(await mkdir4(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=join9(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=join9(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 rm7(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=join9(sessionDir,"extensions");if(await pathExists(extensions))for(let extension of await readdir3(extensions,{withFileTypes:!0}))extension.isDirectory()&&await rm7(join9(extensions,extension.name,`${encodedSessionId(sessionId)}.json`),{force:!0});await rm7(join9(sessionDir,"resident-blobs",sessionId),{recursive:!0,force:!0}),await rm7(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=join9(staging,STAGED_PAYLOADS,file.path);if(await mkdir5(dirname2(to),{recursive:!0}),await copyFile2(join9(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 rm7(dir,{recursive:!0,force:!0});for(let file of files){let to=join9(dir,file.path.slice(EXTENSION_STATE_PREFIX.length));await mkdir5(dirname2(to),{recursive:!0}),await copyFile2(join9(staging,STAGED_PAYLOADS,file.path),to)}}}async function stage(bundleDir,manifest,staging,from){let file=join9(staging,manifest.sessionFileName);if(!(await pathExists(file)&&await movedInFor(file,manifest.moveId))){await rm7(staging,{recursive:!0,force:!0});for(let item of[manifest.session,...manifest.sidecars]){let to=item===manifest.session?file:join9(staging,item.path.replace(/^files\//,""));await mkdir5(dirname2(to),{recursive:!0}),await copyFile2(join9(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 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 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 text2=value=>typeof value=="string"&&value.trim()!=="";function parse(raw){let{op}=raw;if(op==="import"){if(!text2(raw.bundleDir)||!text2(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=text2(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!text2(raw.sessionPath)||!text2(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!text2(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 text2(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=join10(port.agentDir,"session-moves"),ledger=new MoveLedger(join10(root,"ledger")),outgoing=moveId=>join10(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 rm8}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 rm8(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}}}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","secret_input_v1","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,PROVIDER_ACCOUNT_TEST_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,SESSION_ENV_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"&&(!compactUpdatesEnabled()||capability!=="compact_message_updates_v1"&&capability!=="compact_events")&&!isHostOwnedToolRuntimeCapability(capability))])]}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()})}function answerProtocolInfo(host,command){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:advertisedCompactCapabilities(capabilities,host.writer.currentConnection()!==void 0&&host.registry.supportsCompact?.()===!0),mode:"multi",...protocolIdentity(host.defaults.agentDir),memory_pressure:host.memoryPressure,path_identity_resolver:pathIdentityResolverStatus(sharedPathIdentityResolver())}}}function answerSubscriptionLimits(command){return{id:command.id,type:"response",command:"get_subscription_limits",success:!0,data:{accounts:subscriptionLimits.snapshot()}}}function answerListSessions(host,command){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}}}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,refused2({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,refused2(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,refused2(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,refused2(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,{...refused2(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 refused2(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 malformed=invalidCompactAdmission(command);if(malformed)return Promise.resolve(malformed);let ownership=unknownCompactAdmission(host,command);return ownership instanceof Promise?ownership.then(refusal4=>refusal4??admitted(host,command)):ownership?Promise.resolve(ownership):admitted(host,command)}function admitted(host,command){let refusal4=attachmentGate(host,command)??compactAdmissionGate(host,command);if(refusal4)return Promise.resolve(refusal4);if(command.type==="set_client_info"&&compactUpdatesEnabled()){let reply=declareSocketClient(host,command);if(!reply.success)return Promise.resolve(reply);let peer=host.writer.currentConnection();if(command.capabilities!==void 0&&peer!==void 0&&(command={...command,capabilities:[...host.pendingCapabilities.get(peer)??[]]}),command.id===void 0&&command.capabilities===void 0)return Promise.resolve(void 0)}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),withAdmissionRequest(command,host.writer.currentConnection(),()=>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==="reset_stream"&&host.admissions)return resetStream(host,command);if(command.type==="cancel_attempt"&&host.admissions!==void 0){let peer=host.writer.currentConnection(),epoch=peer===void 0?void 0:host.writer.socketEpochOf(peer);if(epoch===void 0)return error(command.id,command.type,"unsupported_transport");let outcome=await host.admissions.cancel(epoch,command.admissionId);return{id:command.id,type:"response",command:"cancel_attempt",success:!0,data:{outcome}}}if(command.type==="get_protocol_info")return answerProtocolInfo(host,command);if(command.type==="get_subscription_limits")return answerSubscriptionLimits(command);if(command.type==="list_sessions")return answerListSessions(host,command);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)return command.id===void 0&&compactUpdatesEnabled()?void 0:declareSocketClient(host,command);if(command.type==="subscribe_sessions"){if(host.admissions&&command.admissionId!==void 0)return compactSubscribe(host,command);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)}
|
|
40
40
|
`)}})().catch(cause=>{host.writer.status.unsubscribe(connection,activate),process.stderr.write(`senpi rpc subscribe answer could not be delivered: ${String(cause)}
|
|
41
41
|
`)});return}return answer3}if(command.type==="unsubscribe_sessions"){let peer=host.writer.currentConnection(),answer3=answerUnsubscribeSessions(command,peer,host.writer.status);return answer3.success&&peer!==void 0&&host.writer.unregisterSubscription(peer,command.subscriptionId),answer3}if(command.type==="get_effect_status"&&!command.sessionId&&command.sessionPath!==void 0)return answerEffectFromTranscript(command.id,command.sessionPath,command.effectId);if(command.type==="get_recovery_page"&&host.writer.recoveryPages!==void 0)return answerRecoveryPage(host.writer.recoveryPages,host.writer,command);if(command.type==="release_recovery"&&host.writer.recoveryEvents!==void 0)return answerReleaseRecovery(host.writer.recoveryEvents,host.writer,command);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 join11}from"node:path";function resolveSocketPath(value,agentDir){if(value==="unix://")return join11(agentDir,"rpc","rpc.sock");if(value.startsWith("unix://")){let path=value.slice(7);return path.length===0?join11(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,secretFrameBytes:64*1024,secretInputs:64,secretIds:1088};var 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)}};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")}function workerCapabilities(options,message,writer){let current=message.connection===void 0||!compactUpdatesEnabled()?void 0:writer?.compactSelection(message.connection);return current&&(current.refused||message.capabilities.length!==current.capabilities.length||!message.capabilities.every(cap=>current.capabilities.includes(cap)))?(acknowledge(message.signal,!1),options):options.connectionRoles?.declare(roleConnection(message.connection),message.capabilities)===!1?(acknowledge(message.signal,!1),options):(message.connection===void 0&&(options={...options,capabilities:message.capabilities}),options.clientInfo?.setCapabilities(message.connection,message.capabilities),acknowledge(message.signal,!0),options)}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()}};var WORKER_PERMIT_BYTES=FRAGMENT_ENVELOPE_MAX_BYTES,WORKER_CONTROL_SLOTS=1,PERMIT_WORD={credit:0,host:1,worker:2},PERMIT_TAG={idle:0,granted:1,denied:2,closed:3,waiting:4},WorkerPermitLedger=class{constructor(capacity=TRANSFER_STAGING_MAX_BYTES){this.granted=0,this.waiting=new Set,this.ceiling=Math.floor(capacity/WORKER_PERMIT_BYTES)-WORKER_CONTROL_SLOTS}request(grant){return this.granted>=this.ceiling?(this.waiting.add(grant),!1):(this.granted+=1,grant(),!0)}release(){this.granted-=1;let[next]=this.waiting;next&&(this.waiting.delete(next),this.granted+=1,next())}withdraw(grant){this.waiting.delete(grant)}status(){return{granted:this.granted,waiting:this.waiting.size,ceiling:this.ceiling}}},hostWorkerPermits=new WorkerPermitLedger,HostPermits=class{constructor(ledger){this.block=new SharedArrayBuffer(3*Int32Array.BYTES_PER_ELEMENT),this.state=new Int32Array(this.block),this.holding=!1,this.closed=!1,this.grant=()=>{this.holding=!0,Atomics.add(this.state,PERMIT_WORD.credit,WORKER_PERMIT_BYTES),this.signal(PERMIT_TAG.granted)},this.ledger=ledger,this.request()}returned(){this.closed||!this.holding||Atomics.load(this.state,PERMIT_WORD.credit)>=WORKER_PERMIT_BYTES||(this.holding=!1,this.ledger.release(),this.request())}close(){this.closed||(this.closed=!0,this.signal(PERMIT_TAG.closed),this.holding?this.ledger.release():this.ledger.withdraw(this.grant),this.holding=!1)}request(){this.ledger.request(this.grant)||this.signal(PERMIT_TAG.denied)}signal(tag){Atomics.store(this.state,PERMIT_WORD.host,tag),Atomics.notify(this.state,PERMIT_WORD.credit)}};var PAID=new Set(["ready","snapshot","output","canonical","canonical_unavailable","fragment"]),FRAGMENT_KIND=protocolId("worker_frame"),WorkerIntake=class{constructor(staging,fail2,ledger=hostWorkerPermits){this.expected=0,this.serial=0,this.assembled=new WeakSet,this.staging=staging,this.fail=fail2,this.permits=new HostPermits(ledger)}get nextOrdinal(){return this.expected}get refusal(){return this.refused}received(message){PAID.has(message.type)&&!this.assembled.delete(message)&&this.permits.returned()}inOrder(message){if(message.ordinal===this.expected)return this.expected+=1,!0;message.signal&&acknowledge(message.signal,!1);let kind=(message.ordinal??Number.POSITIVE_INFINITY)<this.expected?"duplicate":"gap";return this.fail(`session_worker_frame_${kind}`),!1}fragment(frame2){let end=frame2.offset+frame2.text.length*2,final=end===frame2.length;if(frame2.ordinal!==void 0&&!final&&!this.inOrder(frame2))return this.refuse(frame2);let fed=this.open?.fed??0;if(frame2.offset!==fed)return this.refuse(frame2,`session_worker_frame_${frame2.offset<fed?"duplicate":"gap"}`);try{this.open??={transfer:this.staging.begin(FRAGMENT_KIND,protocolId(`t${++this.serial}`),frame2.length),fed},this.open.transfer.append(frame2.text),this.open.fed=end}catch(error2){let cause=error2 instanceof TransferStagingError?error2.reason:"failed",ordinal=frame2.ordinal===void 0?void 0:frame2.ordinal+Math.ceil((frame2.length-frame2.offset)/FRAGMENT_MAX_BYTES)-1;this.refused={cause,event:{type:frame2.of,...ordinal===void 0?{}:{ordinal},length:frame2.length}};let at=ordinal===void 0?"":` ordinal ${ordinal}`;return this.refuse(frame2,`session_worker_transfer_${cause}: ${frame2.of}${at} (${frame2.length} stored bytes)`)}if(!final)return;let content=this.open.transfer.commit();return this.open=void 0,this.whole(content,frame2)}refuse(frame2,error2){this.open?.transfer.abort(),this.open=void 0,error2!==void 0&&(frame2.signal&&acknowledge(frame2.signal,!1),this.fail(error2))}async whole(content,frame2){try{let text3="";for await(let chunk of this.staging.chunks(content))text3+=chunk;let message=JSON.parse(text3);return this.assembled.add(message),Object.assign(message,frame2.ordinal===void 0?{}:{ordinal:frame2.ordinal},frame2.firstOrdinal===void 0?{}:{firstOrdinal:frame2.firstOrdinal},frame2.signal?{signal:frame2.signal}:{},frame2.epochSignal&&"bootstrap"in message?{bootstrap:{...message.bootstrap,epochSignal:frame2.epochSignal}}:{})}finally{this.staging.abandon(content)}}};import{randomUUID as randomUUID4}from"node:crypto";var WorkerOwnerGates=class{constructor(){this.generation=randomUUID4(),this.issued=new Map}capture(context,connection,command){let transport=context.transport;if(connection===void 0||transport===void 0||!carriesExtensionOwner(command))return;let owner=transport.capture(this.generation);owner.retired&&(this.generation=randomUUID4(),owner=transport.capture(this.generation));let owners=this.issued.get(connection)??new Set;return owners.add(owner),this.issued.set(connection,owners),owner.wire}detach(context,connection){let owners=this.issued.get(connection);if(!owners)return[];this.issued.delete(connection);let current=context.transportOf(connection),kept=new Set,retired=[];for(let owner of owners)current!==void 0&¤t.ownerId!==owner.wire.ownerId&&!owner.retired?kept.add(owner):(owner.retire(),retired.push({ownerId:owner.wire.ownerId,bindingGeneration:owner.wire.bindingGeneration}));return kept.size>0&&this.issued.set(connection,kept),retired}retireAll(){let retired=[];for(let owners of this.issued.values())for(let owner of owners)owner.retire(),retired.push({ownerId:owner.wire.ownerId,bindingGeneration:owner.wire.bindingGeneration});return this.issued.clear(),this.generation=randomUUID4(),retired}};var SECRET_FRAME_TYPES=["extension_ui_request","secret_input_settled"];function secretFrameType(record){let type="type"in record?record.type:void 0;return SECRET_FRAME_TYPES.find(known=>known===type)}var WorkerSecretIds=class{constructor(){this.sent=new Map}has(id){return this.sent.has(id)}ids(){return this.sent.keys()}admitsNew(){if(this.sent.size>=SESSION_WORKER_LIMITS.secretIds)return!1;let open3=0;for(let sent of this.sent.values())sent.has("secret_input_settled")||open3++;return open3<SESSION_WORKER_LIMITS.secretInputs}add(id){this.sent.has(id)||this.sent.set(id,new Set)}admitFrame(id,record){let sent=this.sent.get(id),type=secretFrameType(record);return!sent||type===void 0||sent.has(type)||Buffer.byteLength(JSON.stringify(record))>SESSION_WORKER_LIMITS.secretFrameBytes?!1:(sent.add(type),!0)}forget(id){this.sent.delete(id)}clear(){this.sent.clear()}};import{randomUUID as randomUUID5}from"node:crypto";import{fileURLToPath}from"node:url";import{Worker}from"node:worker_threads";var compiledWorkerEntry=typeof SENPI_RPC_SESSION_WORKER_ENTRY=="string"?SENPI_RPC_SESSION_WORKER_ENTRY:"./src/modes/rpc/session-worker.ts";function startSessionWorker(webviewBroker){return sessionWorkerDataRegistry.spawn(issued=>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(),extensionData:issued.extensionData,...webviewBroker?{webviewBroker:webviewBroker.port}:{}},transferList:[...webviewBroker?[webviewBroker.port]:[],...issued.transfer]}))}async function reconcileWorkerReplacement(message,lane,callbacks){message.snapshot&&(message.bootstrap&&compactUpdatesEnabled()&&await lane?.generations.bind(message.snapshot.state.sessionId),await callbacks.reconcile(message.snapshot.liveSessionPaths))}var SessionWorkerClient=class{constructor(callbacks,agentDir=recoveryAgentDir){this.secretIds=new WorkerSecretIds,this.privateOperations=new Map,this.webviewBroker=createWebViewBroker(),this.bindingReady=!1,this.request=message=>this.requests.request(message),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.owners=new WorkerOwnerGates,this.callbacks=callbacks,this.agentDir=agentDir,this.spawned=startSessionWorker(this.webviewBroker),this.worker=this.spawned.result,this.exited=new Promise((resolve2,reject)=>{this.worker.once("exit",()=>{this.intake?.permits.close();for(let id of this.secretIds.ids())this.secretRoute?.forget(id);this.secretIds.clear(),this.stopPrivateBinding?.(),this.privateBinding?.dispose(),this.owners.retireAll(),this.spawned.issued.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(){if(!compactUpdatesEnabled()){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}let nonce=randomUUID5(),acceptance=new SessionAcceptanceLane(void 0,void 0,this.agentDir),intake=new WorkerIntake(acceptance.staging,error2=>this.fail(error2));this.acceptance=acceptance,this.intake=intake;let negotiated=!1;try{let result=await this.request({type:"commit",acceptance:!0,recoveryEpoch:nonce,permits:intake.permits.block});if(result.type!=="ready")throw new Error("Invalid worker commit response");if(!result.bootstrap)throw new StructuredLaneUnavailableError;return acceptance.bootstrap(result.bootstrap,nonce),negotiated=!0,this.snapshot=result.snapshot,result.snapshot}finally{negotiated||(intake.permits.close(),acceptance.retire("close"),this.acceptance=this.intake=void 0)}}async bind(sessionId,writer,requestClose,options){return this.sessionId=sessionId,this.writer=writer,this.secretRoute=writer.secretInputRoute(sessionId),this.acceptance&&writer.registerAcceptance(sessionId,this.acceptance),compactUpdatesEnabled()&&process.stderr.write(`senpi rpc worker ${sessionId}: bound mode=${this.acceptance?"acceptance":"legacy"}
|
|
42
|
-
`),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(),owner=this.owners.capture(writer.connectionContext,connection,command),answered="type"in command&&command.type==="extension_ui_response"?answeredUiRequestId(command):void 0;if(!(answered!==void 0&&writer.acceptWorkerGrantResponse(sessionId,answered,connection)===!1)){if(answered!==void 0&&this.secretIds.has(answered)&&!this.secretRoute?.accepts(answered)){let response=command;writer.enqueue(sessionId,refusedExtensionUiResponse(response.id,"secret_answer_refused"));return}await this.request({type:"command",admissionReply:captureAdmissionReply(),command,connection,roles:options.connectionRoles?.rolesOf(roleConnection(connection)),...owner===void 0?{}:{owner}})}},cancelPendingExtensionUiRequests:()=>this.post({type:"cancel_ui"}),connectionDetached:connection=>this.postRetired(this.owners.detach(writer.connectionContext,connection)),dispose:async()=>{this.postRetired(this.owners.retireAll()),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.intake?.permits.close(),this.stopped=!0,this.requests.close(new Error("session_closing")),this.worker.terminate()}postRetired(owners){owners.length>0&&this.post({type:"owners_retired",owners})}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&&message.signal&&acknowledge(message.signal,!1);return}switch(this.intake?.received(message),message.type){case"secret_select":{if(!this.secretIds.has(message.id)&&!this.secretIds.admitsNew()){acknowledge(message.signal,!1);return}let select=()=>{let reason=this.secretRoute?.select(message.id,()=>this.post({type:"cancel_secret",id:message.id}))??(this.secretRoute?void 0:"no_presenter");reason===void 0&&this.secretIds.add(message.id);let result=reason===void 0?{accepted:!0,connection:this.secretRoute?.presenter(message.id)}:{accepted:!1,reason},encoded=new TextEncoder().encode(JSON.stringify(result));new Uint8Array(message.decision,4).set(encoded),Atomics.store(new Int32Array(message.decision,0,1),0,encoded.length),acknowledge(message.signal,!0)};message.connection!==void 0&&this.writer?this.writer.withConnection(message.connection,select):select();return}case"secret_frame":if(!this.secretIds.admitFrame(message.id,message.record)){acknowledge(message.signal,!1);return}this.secretRoute?.send(message.id,message.record),acknowledge(message.signal,!0);return;case"secret_settled":this.secretRoute?.settled(message.id),acknowledge(message.signal,!0);return;case"secret_forget":this.secretIds.forget(message.id),this.secretRoute?.forget(message.id),acknowledge(message.signal,!0);return;case"secret_handshake":this.writer?.setSoleSecretCapabilities(message.capabilities),acknowledge(message.signal,!0);return;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:randomUUID5(),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}let lane=this.acceptance;if(this.intake?.inOrder(message)===!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.recordText===void 0?message.record:JSON.parse(message.recordText);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(isGrantSelectRequest(record)){let target=writer.routeWorkerGrant(sessionId,record.id,message.connection,this.options.capabilities??[],()=>this.post({type:"cancel_grant",id:record.id}));if(!target.accepted){acknowledge(message.signal,!0);return}outputConnection=target.connection}let enqueue=()=>withAdmissionReply(message.admissionReply,()=>(message.bootstrap?lane?.bootstrap(message.bootstrap):(lane?.applyTranscript(message.transitions??[]),lane?.accept(record,message.recovery,frameUnit(message),message.canonicalRefused===!0)),enqueueLegacyRecord(writer,sessionId,record)?writer.waitForSessionBackpressure(sessionId):(acknowledge(message.signal,!1),this.fail("session_output_overflow_or_closed"),Promise.reject(new Error("session_output_overflow_or_closed")))));reconcileWorkerReplacement(message,lane,this.callbacks).then(()=>outputConnection===void 0?enqueue():message.owner===void 0||outputConnection!==message.connection?writer.withConnection(outputConnection,enqueue):writer.connectionContext.runCaptured(outputConnection,message.owner,enqueue)).then(()=>acknowledge(message.signal,!0),cause=>{acknowledge(message.signal,!1),this.fail(cause instanceof Error?cause.message:String(cause))});return}case"canonical":case"canonical_unavailable":if(!this.writer||!this.sessionId||this.stopped){acknowledge(message.signal,!1);return}if(this.intake?.inOrder(message)===!1)return;message.type==="canonical"?this.acceptance?.acceptControl(frameUnit({...message,canonical:message.record})):this.acceptance?.compactUnavailable(canonicalLoss(message)),acknowledge(message.signal,!0);return;case"capabilities":this.options=workerCapabilities(this.options,message,this.writer);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"fragment":this.intake?.fragment(message)?.then(whole=>this.receive(whole),()=>this.fail("session_worker_transfer_unreadable"));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.acceptance?.retire("worker_failed"),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}
|
|
42
|
+
`),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(),owner=this.owners.capture(writer.connectionContext,connection,command),answered="type"in command&&command.type==="extension_ui_response"?answeredUiRequestId(command):void 0;if(!(answered!==void 0&&writer.acceptWorkerGrantResponse(sessionId,answered,connection)===!1)){if(answered!==void 0&&this.secretIds.has(answered)&&!this.secretRoute?.accepts(answered)){let response=command;writer.enqueue(sessionId,refusedExtensionUiResponse(response.id,"secret_answer_refused"));return}await this.request({type:"command",admissionReply:captureAdmissionReply(),command,connection,roles:options.connectionRoles?.rolesOf(roleConnection(connection)),...originField(options.connectionRoles?.originOf(connection)),...owner===void 0?{}:{owner}})}},cancelPendingExtensionUiRequests:()=>this.post({type:"cancel_ui"}),connectionDetached:connection=>this.postRetired(this.owners.detach(writer.connectionContext,connection)),dispose:async()=>{this.postRetired(this.owners.retireAll()),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.intake?.permits.close(),this.stopped=!0,this.requests.close(new Error("session_closing")),this.worker.terminate()}postRetired(owners){owners.length>0&&this.post({type:"owners_retired",owners})}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&&message.signal&&acknowledge(message.signal,!1);return}switch(this.intake?.received(message),message.type){case"secret_select":{if(!this.secretIds.has(message.id)&&!this.secretIds.admitsNew()){acknowledge(message.signal,!1);return}let select=()=>{let reason=this.secretRoute?.select(message.id,()=>this.post({type:"cancel_secret",id:message.id}))??(this.secretRoute?void 0:"no_presenter");reason===void 0&&this.secretIds.add(message.id);let result=reason===void 0?{accepted:!0,connection:this.secretRoute?.presenter(message.id)}:{accepted:!1,reason},encoded=new TextEncoder().encode(JSON.stringify(result));new Uint8Array(message.decision,4).set(encoded),Atomics.store(new Int32Array(message.decision,0,1),0,encoded.length),acknowledge(message.signal,!0)};message.connection!==void 0&&this.writer?this.writer.withConnection(message.connection,select):select();return}case"secret_frame":if(!this.secretIds.admitFrame(message.id,message.record)){acknowledge(message.signal,!1);return}this.secretRoute?.send(message.id,message.record),acknowledge(message.signal,!0);return;case"secret_settled":this.secretRoute?.settled(message.id),acknowledge(message.signal,!0);return;case"secret_forget":this.secretIds.forget(message.id),this.secretRoute?.forget(message.id),acknowledge(message.signal,!0);return;case"secret_handshake":this.writer?.setSoleSecretCapabilities(message.capabilities),acknowledge(message.signal,!0);return;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:randomUUID5(),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}let lane=this.acceptance;if(this.intake?.inOrder(message)===!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.recordText===void 0?message.record:JSON.parse(message.recordText);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(isGrantSelectRequest(record)){let target=writer.routeWorkerGrant(sessionId,record.id,message.connection,this.options.capabilities??[],()=>this.post({type:"cancel_grant",id:record.id}));if(!target.accepted){acknowledge(message.signal,!0);return}outputConnection=target.connection}let enqueue=()=>withAdmissionReply(message.admissionReply,()=>(message.bootstrap?lane?.bootstrap(message.bootstrap):(lane?.applyTranscript(message.transitions??[]),lane?.accept(record,message.recovery,frameUnit(message),message.canonicalRefused===!0)),enqueueLegacyRecord(writer,sessionId,record)?writer.waitForSessionBackpressure(sessionId):(acknowledge(message.signal,!1),this.fail("session_output_overflow_or_closed"),Promise.reject(new Error("session_output_overflow_or_closed")))));reconcileWorkerReplacement(message,lane,this.callbacks).then(()=>outputConnection===void 0?enqueue():message.owner===void 0||outputConnection!==message.connection?writer.withConnection(outputConnection,enqueue):writer.connectionContext.runCaptured(outputConnection,message.owner,enqueue)).then(()=>acknowledge(message.signal,!0),cause=>{acknowledge(message.signal,!1),this.fail(cause instanceof Error?cause.message:String(cause))});return}case"canonical":case"canonical_unavailable":if(!this.writer||!this.sessionId||this.stopped){acknowledge(message.signal,!1);return}if(this.intake?.inOrder(message)===!1)return;message.type==="canonical"?this.acceptance?.acceptControl(frameUnit({...message,canonical:message.record})):this.acceptance?.compactUnavailable(canonicalLoss(message)),acknowledge(message.signal,!0);return;case"capabilities":this.options=workerCapabilities(this.options,message,this.writer);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"fragment":this.intake?.fragment(message)?.then(whole=>this.receive(whole),()=>this.fail("session_worker_transfer_unreadable"));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.acceptance?.retire("worker_failed"),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}
|
|
43
43
|
`)}});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(compactUpdatesEnabled()&&await worker.acceptance?.generations.bind(snapshot.state.sessionId),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.supportsCompact=()=>!0,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,options.configuration.agentDir))}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),retain_on_disconnect:entry.retainOnDisconnect===!0,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{randomBytes as randomBytes3,randomUUID as randomUUID8}from"node:crypto";import{createServer}from"node:net";import{createHash as createHash6,createPublicKey,randomBytes as randomBytes2,randomUUID as randomUUID6}from"node:crypto";import{verify}from"node:crypto";function signed(value,transcript,key){return!isRecord(value)||Object.keys(value).length!==2||value.type!=="proof"||typeof value.signature!="string"||!/^[a-f0-9]{128}$/.test(value.signature)?!1:verify(null,Buffer.from(transcript),key,Buffer.from(value.signature,"hex"))}function send(stream,value){stream.write(`${JSON.stringify(value)}
|
|
44
44
|
`)||stream.destroy()}function privateFrames(stream,receive,deadline=!0){let timer=deadline?setTimeout(()=>stream.destroy(),3e4):void 0,detach=attachJsonlLineReader(stream,line=>{try{receive(JSON.parse(line))}catch{stream.destroy()}},{maxLineLength:16*1024,onOversizedLine:()=>stream.destroy()});return stream.on("error",()=>stream.destroy()),stream.once("close",()=>{clearTimeout(timer),detach()}),()=>{clearTimeout(timer),detach()}}function identity(value){return typeof value=="string"&&value.length>0&&value.length<=256}function parsePresenterEnrollment(value){if(!isRecord(value)||Object.keys(value).length!==11||value.type!=="enroll"||value.version!==2||value.purpose!=="mcp_form"||typeof value.publicKey!="string"||value.publicKey.length>1024||typeof value.installationKeyId!="string"||!/^[a-f0-9]{64}$/.test(value.installationKeyId)||!identity(value.backendGeneration)||typeof value.launchRequestNonce!="string"||!/^[a-f0-9]{64}$/.test(value.launchRequestNonce)||value.launchKind!=="initial"&&value.launchKind!=="replacement"||!identity(value.environmentId))return;let predecessor=value.predecessorHostInstance;if((value.launchKind==="initial"?predecessor!==null:!identity(predecessor))||predecessor!==null&&typeof predecessor!="string")return;let realm=value.executionRealm;if(!Array.isArray(realm))return;let executionRealm;if(realm.length===1&&realm[0]==="native")executionRealm=["native"];else if(realm.length===3&&realm[0]==="wsl"&&identity(realm[1])&&identity(realm[2]))executionRealm=["wsl",realm[1],realm[2]];else return;try{let key=createPublicKey(value.publicKey);if(key.asymmetricKeyType!=="ed25519"||createHash6("sha256").update(key.export({type:"spki",format:"der"})).digest("hex")!==value.installationKeyId)return}catch{return}return{type:"enroll",version:2,purpose:"mcp_form",publicKey:value.publicKey,installationKeyId:value.installationKeyId,backendGeneration:value.backendGeneration,launchRequestNonce:value.launchRequestNonce,launchKind:value.launchKind,predecessorHostInstance:predecessor,executionRealm,environmentId:value.environmentId}}function presenterEnrollmentTranscript(request,hostInstance,nonce){return JSON.stringify(["mcp-presenter-enroll-v2",request.purpose,request.installationKeyId,request.backendGeneration,request.launchRequestNonce,request.launchKind,request.predecessorHostInstance,request.executionRealm,request.environmentId,hostInstance,nonce,3e4])}var McpPresenterEnrollment=class{constructor(hostInstance,endpoint){this.started=!1,this.nonces=new Set,this.hostInstance=hostInstance,this.endpoint=endpoint}bootstrap(stream,enrolled){if(this.started){stream.destroy();return}this.started=!0,this.stream=stream;let pending,consumed=!1,stop=privateFrames(stream,value=>{if(consumed)return;if(!pending){if(isRecord(value)&&value.type==="enroll"&&value.version!==2){consumed=!0,stop(),stream.end(`${JSON.stringify({type:"unavailable",versions:[2]})}
|
|
45
45
|
`);return}let request=parsePresenterEnrollment(value);if(!request||request.predecessorHostInstance===this.hostInstance){stream.destroy();return}this.nonces.add(request.launchRequestNonce),pending={request,key:createPublicKey(request.publicKey),transcript:presenterEnrollmentTranscript(request,this.hostInstance,randomBytes2(32).toString("hex")),deadline:performance.now()+3e4},send(stream,{type:"challenge",version:2,transcript:pending.transcript,hostInstance:this.hostInstance});return}let attempt=pending;if(consumed=!0,pending=void 0,stop(),performance.now()>=attempt.deadline||!signed(value,attempt.transcript,attempt.key)){stream.destroy();return}let principal={id:randomUUID6(),key:attempt.key,enrollment:attempt.request};enrolled(principal),stream.end(`${JSON.stringify({type:"enrolled",version:2,principalId:principal.id,hostInstance:this.hostInstance,backendGeneration:attempt.request.backendGeneration,launchRequestNonce:attempt.request.launchRequestNonce,endpoint:this.endpoint})}
|