UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

6,669 lines • 238 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { y as isFutureDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { t as stableStringify } from "./stable-stringify-vqde_3tT.mjs";
import { b as uniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { i as createAbortError } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { l as trackAsyncWork } from "./async-work-scope-BXagjUap.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { C as isSubagentSessionKey, x as isCronSessionKey, y as isAcpSessionKey } from "./session-key-CqAyZeVk.mjs";
import { a as isSameOpenClawAgentDatabasePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { a as resolveAgentDir, f as resolveAgentWorkspaceDir, o as resolveAgentEntry } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as classifyGatewayStorageFailure } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { r as hasSqliteWorkerOutcomeUnknown } from "./sqlite-worker-error-DEIJgRIz.mjs";
import { p as isDiagnosticsEnabled } from "./diagnostic-events-BjAH1Kbx.mjs";
import { m as withDiagnosticsTimelineObserver, n as emitDiagnosticsTimelineEvent, s as measureDiagnosticsTimelineSpan, u as observeDiagnosticsTimelinePhases } from "./diagnostics-timeline-CSwiG24r.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import { h as SessionGoalOperationError } from "./openclaw-state-worker-error-C8y1JGQN.mjs";
import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs";
import "./sqlite-worker-contract--dxXkOty.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { n as GATEWAY_CLIENT_IDS } from "./client-info-Cm1BcrMm.mjs";
import { fh as isReactionEmoji, uv as readAgentRuntimeRestrictionErrorDetails } from "./src-BX8OAe1J.mjs";
import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs";
import { n as hasSessionAutoModelFallbackProvenance, t as hasSessionActiveAutoModelFallback } from "./model-override-provenance-DeIPDBg8.mjs";
import { r as hasLegacyAutoFallbackWithoutOrigin } from "./agent-scope-BwB8YH6y.mjs";
import { i as classifyAgentRunTerminalOutcome } from "./agent-run-terminal-outcome-CurjWZiA.mjs";
import { i as claimAgentRunContext, l as getAgentRunContext, o as clearAgentRunContext, w as resolveProjectedAgentRunProgressState } from "./agent-run-registry-D7vkrqFT.mjs";
import { d as getAgentEventLifecycleGeneration } from "./agent-events-BdfWYmot.mjs";
import { c as prepareSessionSourceAuthority, o as composeSessionSourceAssertion, s as createDynamicSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { d as hasGatewayAdminScope } from "./operator-scopes-CULmYfyY.mjs";
import { n as OPENCLAW_AGENT_RUNTIME_ID } from "./agent-runtime-id-D8s1CaYB.mjs";
import { m as resolveConfiguredModelPolicyAllow } from "./model-selection-shared-9Kz63Hhm.mjs";
import { n as parseModelRef, t as findNormalizedProviderValue } from "./model-selection-normalize-DIZCRGVF.mjs";
import { i as resolveModelFallbackAvailability, t as modelFallbackOverrideFromAvailability } from "./model-selection-config-Bvf5WqHo.mjs";
import { t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-constants-CkbqRgGl.mjs";
import { _ as retainGatewayRootWorkAdmissionContinuation, u as isGatewayRestartDrainError } from "./gateway-work-admission-79pid1hQ.mjs";
import { c as createAgentDatabaseAdmissionErrorShape, t as AgentDatabaseAdmissionError } from "./agent-database-admission-CL6wHJ_N.mjs";
import { s as readSessionTranscriptRunId } from "./transcript-events-BHwlF03q.mjs";
import { n as extractTextFromChatContent } from "./chat-content-Dkam4EQe.mjs";
import { n as getUserTurnTranscriptAdmissionOwner, t as bindUserTurnPromptReactionSource } from "./user-turn-transcript-admission-BdVewOwR.mjs";
import { t as captureRequesterOrigin } from "./requester-origin-DG-fk-U0.mjs";
import { t as sameSessionTranscriptStorePath } from "./transcript-store-identity-jolHcJiu.mjs";
import { t as captureSessionTranscriptStorageEnvironment } from "./transcript-target-binding-BvjuRqS9.mjs";
import { n as extractAssistantTextForPhase, t as extractAssistantPhaseText } from "./chat-message-content-DNUdbbJ8.mjs";
import { a as isInternalMessageChannel, l as isWebchatClient, n as isBrowserOperatorUiClient, s as isOperatorUiClient } from "./message-channel-DTYVLJT1.mjs";
import "./agent-run-terminal-outcome-wduf2occ.mjs";
import { l as isAgentRunDirectAbortReason, m as resolveAgentRunErrorLifecycleFields, o as createAgentRunRestartAbortError, p as resolveAgentRunAbortLifecycleFields, u as isAgentRunRestartAbortReason } from "./run-termination-0Ig0-bk6.mjs";
import { i as resolveSessionWorkStartError, p as retireProviderReviewAcknowledgment } from "./session-work-start-CFJs8WNp.mjs";
import { f as withExecRequestTurn, n as adoptExecRequestSession } from "./exec-request-context-C8VKkMcB.mjs";
import { V as bindSessionEffectTransition, X as captureSessionTarget, r as bindSessionControllerEntryTarget } from "./session-controller.state-BApgK0mV.mjs";
import { M as stripReplyMediaFailureFallback, _ as isReplyPayloadStatusNotice, a as buildTtsSupplementMediaPayload, b as isReplyPayloadTtsSupplement, c as getReplyPayloadMetadata, g as isReplyPayloadSessionWriterDeliveryAuthorized, l as getReplyPayloadTtsSupplement, o as copyReplyPayloadMetadata, p as isHostNoticePayload } from "./reply-payload-k5WsQWxi.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { d as resolveCreatorSandbox, r as authorizeGatewaySessionCreation } from "./operator-role-policy-DhcqVpmG.mjs";
import { i as buildSessionCreationStamp } from "./session-entry-provenance-01l9mXT0.mjs";
import { t as SessionMutationAuthorizationChangedError } from "./session-mutation-authorization-error-0K0ZVV7q.mjs";
import { h as isProgressCardRefreshInputProvenance, v as progressCardRefreshRunProjection } from "./input-provenance-DupvvURj.mjs";
import { i as sessionToolOverridesEqual, r as normalizeSessionToolOverrides } from "./session-tool-overrides-CLYOZ-eE.mjs";
import { m as withoutGatewayToolCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs";
import { o as resolveSessionRoutingContract, t as SESSION_ROUTING_CHANGED_ERROR_REASON } from "./main-session-BNL3-mRV.mjs";
import { n as sessionDeliveryChannel } from "./delivery-context.read-BrYAJ7RK.mjs";
import { i as toDatabaseOptions } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs";
import { n as getSessionActorStorageBinding, o as runWithSessionActorStorage, t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs";
import { t as prepareSqliteScope } from "./session-accessor.sqlite-read-scope-7Z2ARJnl.mjs";
import "./session-accessor.sqlite-scope-Cbj2BdoG.mjs";
import { _ as retainPreparedSessionEntryPredicate } from "./session-accessor.sqlite-entry-cache-publication-state-B4mkg2yK.mjs";
import { n as appendChatCanvasBlocksToMessage, o as isToolHistoryBlockType } from "./chat-display-projection.canvas-XAAIxHM8.mjs";
import { r as readAssistantDisplayContent } from "./assistant-display-content-CBuMU4m5.mjs";
import { s as resolveStateContentionPresentation } from "./chat-display-projection.sanitize-DYNE5Y5I.mjs";
import { o as hasStagedMediaFacts, p as readPersistedMediaFacts } from "./media-facts-B-0Dpo5L.mjs";
import { t as combineNonStreamingReplyParts } from "./trim-code-text-Dr7f3RLr.mjs";
import { r as isSessionTranscriptProjectionUnavailableError, t as SessionTranscriptProjectionUnavailableError } from "./session-transcript-projection-error-D8lfGKCW.mjs";
import { o as withSessionHistoryWorkerDatabase, r as retainSessionHistoryWorkerDatabase } from "./session-transcript-worker-runtime-DMpH3wlh.mjs";
import { u as sanitizeAssistantVisibleTextWithProfile } from "./assistant-visible-text-fPqh5m9O.mjs";
import { t as renderAgentHarnessPreflightUserMessage } from "./user-facing-text-Dqp3fcZx.mjs";
import { v as renderFailoverCodeUserCopy } from "./user-copy-DFvWpx47.mjs";
import { u as renderStorageFailureSummary } from "./assistant-request-failure-copy-CDAkRIru.mjs";
import { M as readSessionSubmittedInput, W as normalizeMessageClientSources, d as rewritePreparedTranscriptMessageAtAnchor } from "./session-accessor-CizTbDQj.mjs";
import { i as assertSessionGoalOperationTime } from "./goals-operation-policy-D3lqf5_y.mjs";
import { i as buildRunUserTurnIdempotencyKey } from "./user-turn-transcript.metadata-GFtsH_a_.mjs";
import { n as withSessionActorStorage, t as acquireSessionActorStorage } from "./session-actor-storage-acquisition-bj-qIczw.mjs";
import { a as startSessionTranscriptIndexReconcile, l as waitForSessionTranscriptProjection } from "./session-transcript-reconcile-CtdkqWN1.mjs";
import { B as isCompetingSessionControllerWorkActive, C as trackSessionControllerSourceWork, E as captureRpcSourceScopeMatcher, r as readSessionControllerAdmissionError, t as beginSessionEffect, x as retireSessionControllerSourceCancellation } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { a as prepareSessionCapabilityRead, s as withPreparedSessionCapabilityRead } from "./subagent-session-store--G7wm9iV.mjs";
import { t as readSessionTranscriptWatermark } from "./session-accessor.sqlite-transcript-watermark-D0VDXIZd.mjs";
import { a as acquireSessionInputActor, o as bindUserTurnInputActor } from "./session-accessor.sqlite-transcript-turn-VItOcLIr.mjs";
import { n as withSessionPendingInputAuthorityGuard } from "./session-pending-input-authority-DyqYXnbO.mjs";
import { t as GATEWAY_RESTART_UNAVAILABLE_REASON } from "./restart-unavailable-CqvsgSBG.mjs";
import { r as resolveRequestedSessionAgentId, s as tryResolveSessionCompatibilityOwnerAgentId, t as resolveChatSendSessionKey } from "./session-request-agent-tfwWH53J.mjs";
import { r as prepareQualifiedSessionEntryTarget } from "./session-accessor.entry-f0bkn7cv.mjs";
import { a as isAgentHarnessSessionKey, m as resolveMissingAgentHarnessSessionError } from "./agent-harness-session-key-BRYGtzM6.mjs";
import { g as withOwnedSessionTranscriptWrites, l as getOwnedSessionTranscriptReader, v as withSessionTranscriptSourcePublication } from "./transcript-write-context-_7rz2F7z.mjs";
import { c as updateSessionEntry } from "./session-accessor.entry-mutation-IJ4DYZ4a.mjs";
import { r as resolveSessionTranscriptDatabasePath } from "./session-accessor.transcript-target-njOktg4F.mjs";
import { n as readSessionTranscriptAnchorsAsync, t as readActiveTranscriptEntryAnchorAsync } from "./session-transcript-anchor-read-BUt-Wh3r.mjs";
import { t as applyAssistantDeliveryDirectives } from "./transcript-assistant-delivery-Ddb-cbeg.mjs";
import "./sessions-D5Vvu3AE.mjs";
import { n as resolveSessionResetType, t as resolveChannelResetConfig } from "./reset-mDbPCz5g.mjs";
import { r as isSyntheticGatewayCaller } from "./gateway-personal-caller-_qqOw6oy.mjs";
import { i as gatewayClientSessionCreator, o as resolveChatSendCallerContext, r as gatewayClientSenderFields } from "./gateway-client-identity-BkzV3v8p.mjs";
import { s as withQualifiedGatewaySessionStoreTarget } from "./session-utils-store-lookup-BrmEKLOy.mjs";
import { n as omitInternalSessionEffectsEntries, t as findCanonicalStoreMatch } from "./session-utils-store-selection-B-u2328z.mjs";
import { n as captureSessionMutationRouting } from "./session-sharing-preparation-vuYznHON.mjs";
import { D as updateRpcSourceSessionId, a as getRpcSourceIdentity, c as getRpcSourceStartedAt, g as isRpcSourceRegistered, k as resolveChatRunExpiresAtMs, o as getRpcSourceLifecycleGeneration, p as isRpcSourceActive, r as getRpcSourceForGateway, u as hasRpcSourceForController, v as listRpcSourceEntries } from "./session-controller.rpc-sources-CTFbRW2t.mjs";
import { n as chatRunBelongsToSelectedAgent } from "./chat-run-owner-2pVCqGmw.mjs";
import { s as transferGatewayLocalUserIngress } from "./local-user-ingress-CLpC74uh.mjs";
import { n as isVisibleSpawnedSession } from "./subagent-capabilities-D82nSYzB.mjs";
import { n as runOutsideOperatorToolGatewayAuthority } from "./operator-tool-gateway-authority-BJCYeVPR.mjs";
import { i as bindWorkerToolPreparation } from "./host-private-capabilities-DDumj0c_.mjs";
import { n as resolveAgentTimeoutMs } from "./timeout-BEnEcjB4.mjs";
import { t as loadGatewaySessionEntryReadOnlyInWorker } from "./session-utils-store-worker-BU_tdh8T.mjs";
import { l as captureReplySessionExecutionSelection } from "./reply-tool-authority-CcXbHQOX.mjs";
import { a as MessageInjectionTargetUnavailableError, l as createMessageInjectionAuthority } from "./message-injection-authority-B9SdalrV.mjs";
import { a as prepareSessionParticipantInput, t as bindRequesterProfile } from "./requester-profile-DgtOmQ0f.mjs";
import { r as resolveInboundReplyToolAuthorityOverlay } from "./reply-tool-authority-inbound-BQ8cxNJQ.mjs";
import "./session-controller.mailbox-BcK8UF_b.mjs";
import { i as hasGlobalHooks, n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { r as logVerbose } from "./globals-CgepmiqE.mjs";
import { n as runAgentHarnessBeforeMessageWriteHook } from "./hook-helpers-DKwpcDXZ.mjs";
import { r as retainsUserTurnTranscriptMedia, t as createUserTurnTranscriptRecorder } from "./user-turn-transcript-CQTz-i5Y.mjs";
import { r as stopSession } from "./session-controller.stop-BqKrTY7V.mjs";
import { l as ExpectedProfileMismatchError } from "./session-sharing-read-BqjuH16A.mjs";
import "./session-sharing-BIP3raq1.mjs";
import { n as getRegisteredAgentHarness } from "./registry-ubpieJjd.mjs";
import { i as resolveSessionSubmittedModelRef, r as resolveSessionModelRef } from "./session-model-ref-Cha0Enxi.mjs";
import { o as resolveEffectiveAgentRuntime } from "./thinking-runtime-BKWl4CUs.mjs";
import { r as resolveGatewayModelSupportsImages } from "./session-utils-model-BFA7PxHy.mjs";
import "./channel-outbound-DQFse8vD.mjs";
import { a as resolveCommandAuthorizationAsync } from "./command-auth-CC1Z19Eh.mjs";
import { n as deriveGatewaySessionLifecycleSnapshot } from "./session-lifecycle-projection-CAIipPlB.mjs";
import { p as refuseCollaborativeSteering, s as hasPendingFollowupQueueWork } from "./state-DGvM9kEH.mjs";
import { n as resolveAgentIdentity } from "./identity-Cd2mxvzm.mjs";
import { t as readAcpSessionMetaForEntries } from "./session-meta-readonly-B5S0IsZ_.mjs";
import { d as withQualifiedGatewaySessionEntry, o as prepareDeletedAgentSessionCheck, u as withGatewaySessionEntry } from "./session-utils-store-CiI_s_OK.mjs";
import { l as resolveAssistantIdentityName } from "./assistant-avatar-DjDH3za_.mjs";
import { n as resolveSendPolicy } from "./send-policy-Be9xpkMD.mjs";
import { r as emitSessionsChanged } from "./session-change-event-DFgDuXAu.mjs";
import { n as resolvePreparedSessionEntryResetFreshness, r as resolveSessionEntryResetFreshness } from "./entry-freshness-QZXboFNc.mjs";
import { i as describeFailoverError } from "./failover-error-CbIiC30n.mjs";
import { a as logMessageReceived, r as logMessageProcessed } from "./diagnostic-C-GjPJGO.mjs";
import { r as resolveOperatorSessionCreation } from "./session-creation-provenance-DCFhTDpD.mjs";
import "./reply-payload-CwASJYas.mjs";
import { t as formatForLog } from "./ws-log-CbOV6uhk.mjs";
import { t as chatAbortMarkerTimestampMs } from "./server-chat-state-hXRKEuCM.mjs";
import { t as errorShapeFromError } from "./error-shape-BcwiXcnc.mjs";
import { t as respondError } from "./response-C7fEiIN1.mjs";
import { n as runWithAgentWorkspaceReadiness } from "./workspace-readiness-ClUjI0tp.mjs";
import { i as captureQueuedOperatorRecoverySource } from "./operator-run-recovery-DNcb8p2u.mjs";
import { n as captureAcpSessionEntryBinding } from "./session-meta-entry.kernel-DN2jvKpc.mjs";
import { a as resolveActiveReplyRunOwnerForSignal } from "./session-controller.barriers-DbvoxYCP.mjs";
import { t as finalizeInboundContext } from "./inbound-context-0zDtB0Zn.mjs";
import { r as warnLegacyAgentRunStart } from "./agent-run-start-Cf0O0aGQ.mjs";
import "./commands-registry-CwAxsNJ9.mjs";
import { r as resolveTextCommand } from "./commands-registry-normalize-dI3NYF5y.mjs";
import { n as readAgentRunTerminalOutcome } from "./agent-run-terminal-outcome-BQoZ_25h.mjs";
import { i as dispatchInboundMessageWithProjectedDispatcher } from "./dispatch-vEUtrodM.mjs";
import { a as emitInboundMessageAuditTerminal, r as emitMessageReceivedHooks, s as DispatchSessionRefreshRequiredError } from "./dispatch-from-config-CIEmLnTP.mjs";
import { t as REPLY_OPERATION_RUN_STATE } from "./reply-operation-run-state--V_f6Ot2.mjs";
import { o as bindReplySourceInput, s as bindReplySourcePreparationRetry } from "./get-reply.types-Cne2gAVx.mjs";
import { t as COLLABORATIVE_STEERING_DISABLED_TEXT } from "./dispatch-from-config.payloads-BWvEWyjL.mjs";
import { i as prepareSessionWriterDeliveryAuthority } from "./session-writer-delivery-authority-DNB-b5xs.mjs";
import { r as bindPreparedToolAuthority } from "./tool-authority-preparation-BOURfTvP.mjs";
import { t as hasInboundAudio } from "./inbound-media-BJ8l1Cri.mjs";
import { a as captureCurrentReplyMessageInjectionTarget, s as finalizeReplyMessageInjectionAttempt, t as beginSessionControllerSteer } from "./session-controller.steer-BWjVys2Y.mjs";
import { i as captureSessionControllerInterruptBefore } from "./session-controller-Bu0l-8-p.mjs";
import { t as isInternalSourceReplyChannel } from "./source-reply-delivery-mode-mRdJZOCZ.mjs";
import { o as projectChatDisplayMessage } from "./chat-display-projection.core-ApUvO4fQ.mjs";
import { o as readSessionMessageByIdAsync } from "./session-transcript-readers-D1WqgwbF.mjs";
import { n as formatAudioTranscriptForAgent, t as DEFAULT_ECHO_TRANSCRIPT_FORMAT } from "./echo-transcript-C-BDqHL2.mjs";
import { a as resolveEnvelopeFormatOptions } from "./envelope-C1e0Wmhj.mjs";
import { s as withCurrentUserTurnInput } from "./user-turn-transcript-runtime-context-BZjNfwCQ.mjs";
import { t as assertPreparedSkillLibrarySelection } from "./selection-Bz10gm8A.mjs";
import { t as DEVICE_FOLDER_ATTACHMENTS_UNSUPPORTED } from "./node-workspace-protocol-CnO26WQI.mjs";
import { t as recordSessionCreated } from "./session-created-Cgp2r4Ic.mjs";
import { s as resolveQueueSettings } from "./queue-B_hYGqNE.mjs";
import { t as buildInboundMediaNoteProjection } from "./media-note-C9JRPyCM.mjs";
import { n as buildInboundUserContextPrefix } from "./inbound-meta-CVLLcIT8.mjs";
import { t as recordGatewaySessionRunFailure } from "./session-run-error-BKTAlaL5.mjs";
import { n as resolveChatAttachmentMaxBytes } from "./chat-attachment-policy-7g-oMINW.mjs";
import { n as attachManagedOutgoingMediaToMessage } from "./managed-image-attachments-DSFNBym_.mjs";
import { a as hasManagedOutgoingAssistantContent, c as prepareAssistantDisplayText, i as hasAssistantDisplayMediaContent, l as sanitizeAssistantDisplayText, o as hasVisibleAssistantFinalMessage, r as extractAssistantDisplayText, s as isMediaBearingPayload, u as stripManagedOutgoingAssistantContentBlocks } from "./chat-assistant-content-CmiwVcNn.mjs";
import "./session-utils-CavYkLyd.mjs";
import { a as prepareWebchatReplyMediaForDisplay, c as readChatSendReplyPayload, l as replaceChatSendReplyPayload, n as captureWebchatReplyMediaScope, o as withPreparedWebchatReplyMedia, s as buildTranscriptReplyTextFromInputs, u as selectChatSendFinalReplyInputs } from "./chat-reply-media-Cjx1PVof.mjs";
import { t as persistGatewaySessionLifecycleEvent } from "./session-lifecycle-state-YOgSt9Rr.mjs";
import { t as recordAcceptedSessionParticipantInput } from "./session-participant-input-recording-_5WgfQwo.mjs";
import { t as createChannelReplyPipeline } from "./reply-pipeline-BLDOfhMa.mjs";
import "./chat-display-projection-lHBiRfmJ.mjs";
import { i as markChatAbortTerminalOutcome, l as waitForChatAbortTerminalPersistence, n as captureChatAbortRegistrationGuard } from "./chat-abort-lifecycle-internal-ChM03p20.mjs";
import { a as broadcastChatTerminal, c as isSourceReplyTranscriptMirrorPayload, i as broadcastChatQueueNotice, n as broadcastChatError, o as broadcastSideResult, r as broadcastChatFinal, s as isBtwReplyPayload, t as broadcastChatDelta } from "./chat-broadcast-til2j59n.mjs";
import { t as appendInjectedAssistantMessageToTranscript } from "./chat-transcript-inject-BGdtJFJV.mjs";
import { i as setGatewayDedupeEntry, t as captureAgentJobSession } from "./agent-job-mP_hfXWa.mjs";
import { n as readQueuedChatInputAdmission } from "./queued-chat-input-admission-B0IYOgxt.mjs";
import { _ as resolveExplicitOriginBindingTargets, g as resolveChatSendOriginatingRoute, h as isAcpBridgeClient, m as normalizeChatSendRequest } from "./session-create-root-DP_F1Kuw.mjs";
import { i as roundedChatSendTimingMs, n as prepareChatSendAckTiming, t as createOperatorChatSendServerTiming } from "./chat-server-timing-Cp4A59kY.mjs";
import { r as prepareReplyMessageContinuation, t as prepareSteeringDelivery } from "./steering-delivery-preparation-BASNdY_q.mjs";
import { n as resolveSessionMutationAuthorizationAsync, s as recordSessionOperatorSource } from "./session-sharing-authorization-async-eavQ3y-d.mjs";
import { t as captureWorkerTurnInputSource } from "./worker-turn-transcript-target-gs6cRY6a.mjs";
import { c as rewriteAssistantTranscriptMessageByTurnIndexAndMedia, l as rewriteSourceReplyTranscriptMirrors, n as buildAssistantDisplayRewrite, o as publishAssistantTranscriptRewrite, s as rewriteAssistantTranscriptMessageByIdempotencyKey, t as assistantTranscriptScope } from "./chat-transcript-persistence-CsYeaysF.mjs";
import { c as withAbortedPartialPersistenceWarning, n as abortedPartialPersistenceError } from "./chat-aborted-partial-DMRg9ZMt.mjs";
import { t as readCommittedSourceReplyContent } from "./chat-transcript-source-reply-owner-CAnoESBh.mjs";
import { i as registerChatAbortController, o as updateChatRunProvider, s as resolveChatAbortDiagnosticReason } from "./chat-abort-DHc0iNFP.mjs";
import { t as prepareSkillLibrarySessionCreation } from "./skill-library-session-CBGwzYPf.mjs";
import { a as parseMessageWithAttachments, i as logAttachmentFailure, n as MediaOffloadError, o as persistInboundImagesForTranscript, r as discardPreparedInboundMedia, s as stripImageMediaMarkers, t as INLINE_IMAGE_DURABLE_OMISSION_MARKER } from "./chat-attachments-CZUu2WVn.mjs";
import { n as createChatAbortOps } from "./chat-abort-ops-BGjSJRNq.mjs";
import { i as resolveGatewayInputParticipant, l as retainGatewayOperatorRun, o as isDirectGatewayUserClient, r as prepareGatewaySkillLibraryTurn, t as invalidateSkillAuthoringForOtherRequester } from "./skill-library-authoring-CwgXRvu2.mjs";
import { r as prepareSessionWorkspace } from "./session-create-project-BLnUiBsn.mjs";
import { a as captureGatewayClientUploadCommitGuard } from "./upload-policy-Dp8z9OKP.mjs";
import { t as captureGatewayUiCommandTarget } from "./ui-command-target-O1ior1sD.mjs";
import { n as readChatSendDiagnostics, r as startChatSendDiagnostics } from "./chat-send-diagnostics-CD0USSMK.mjs";
import { n as resolveAgentTurnRunObserver } from "./principal-sFUJS96k.mjs";
import { n as pendingChatSendDedupeKey } from "./server-shared-BUcqD38M.mjs";
import { i as buildAbortedChatSendPayload, l as readPreRegisteredRun, p as writePreRegisteredChatAbort, t as abortChatRunsForSessionKeyWithPartials, u as resolveChatAbortRequester } from "./chat-abort-runtime-Dwe_1h4x.mjs";
import { n as descendantAbortError } from "./chat-abort-descendants-2IwJM3Ms.mjs";
import { o as resolveSessionNativeRuntimeRestriction } from "./sessions-patch-model-selection-BNlUFUUI.mjs";
import { t as scheduleChatDashboardSessionTitle } from "./chat-send-background-9_or3I0e.mjs";
import { t as publishCommittedSessionGoalChange } from "./session-goal-change-DXdlavSm.mjs";
import { t as createAssistantCommentaryMediaCustody } from "./chat-send-commentary-media-Dvgp-c_W.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { performance } from "node:perf_hooks";
import { isDeepStrictEqual } from "node:util";
//#region src/config/sessions/goals-operations-read.ts
/** Durable ingress receipts precede transient dedupe and busy-session refusals. */
async function lookupSessionGoalOperation(e) {
	assertSessionGoalOperationTime(e.operation, Date.now());
	const t = captureSessionActorStorageOwner(e, {
		assertCurrent() {},
		authorize() {}
	});
	if (t) return withSessionActorStorage(e, {
		lifetime: {
			assertCurrent() {},
			assertReadable() {}
		},
		authority: t.authority
	}, (t) => t.actor.storage.read({
		type: "session.goal.receipt",
		input: {
			sessionKey: t.actor.target.sessionKey,
			expectedSessionId: e.expectedSessionId,
			operation: e.operation
		}
	}, t.authority));
	const n = {
		...e,
		...e.storePath ? { storePath: path.resolve(e.storePath) } : {},
		operation: { ...e.operation },
		env: captureSessionTranscriptStorageEnvironment(e.env ?? process.env)
	};
	const r = captureOpenClawStateWorkerContext({ env: n.env });
	const assertCurrent = () => {
		r.maintenanceScope?.assertAdmission();
		r.admission.assertCurrent();
	};
	const i = await prepareSqliteScope(n);
	assertCurrent();
	return withSessionHistoryWorkerDatabase(toDatabaseOptions(i), async (e) => {
		const t = await e.readGoalOperationReceipt({
			sessionKey: i.sessionKey,
			expectedSessionId: n.expectedSessionId,
			operation: n.operation,
			env: n.env
		});
		assertCurrent();
		e.assertCurrent();
		if ("error" in t) throw new SessionGoalOperationError(t.error.code, t.error.message);
		return t.receipt;
	});
}
//#endregion
//#region src/gateway/server-methods/chat-send-active-leaf.ts
const ACTIVE_LEAF_CHANGED_ERROR_REASON = "active-leaf-changed";
function assertExpectedLeafActive(e, t, n, r) {
	const i = e.transcript?.activePathRelation ?? (e.entry?.sessionId ? void 0 : t === null ? "exact" : "off-path");
	if (i === void 0) throw new Error("Chat admission omitted its worker-prepared active path");
	const a = n === void 0 || n === e.entry?.sessionId;
	const o = i === "exact" || (n !== void 0 || r?.allowEmptyAncestor === true) && (i === "ancestor" || r?.allowEmptyAncestor === true && t === null);
	if (!a || !o) throw new Error(ACTIVE_LEAF_CHANGED_ERROR_REASON);
}
//#endregion
//#region src/gateway/server-methods/chat-send-session-settings.ts
const SESSION_SETTINGS_CHANGED_ERROR_REASON = "session-settings-changed";
function captureAdmittedChatSendSessionSettings(e) {
	const { entry: t, expectedPermissionMode: n, expectedToolOverrides: r } = e;
	if (n !== void 0 && (t?.permissionMode ?? null) !== n || r !== void 0 && !sessionToolOverridesEqual(t?.toolOverrides, r)) throw new Error(SESSION_SETTINGS_CHANGED_ERROR_REASON);
	if (!e.commit) return;
	return Object.freeze({
		permissionMode: t?.permissionMode,
		toolOverrides: normalizeSessionToolOverrides(t?.toolOverrides)
	});
}
//#endregion
//#region src/gateway/server-methods/chat-send-admission-errors.ts
function resolveChatSendStorageErrorMessage(e) {
	return renderStorageFailureSummary(classifyGatewayStorageFailure(e));
}
function respondChatSessionRoutingChanged(e) {
	respondError(e, ErrorCodes.INVALID_REQUEST, "session routing changed; review and retry", { details: { reason: SESSION_ROUTING_CHANGED_ERROR_REASON } });
}
function respondChatSendAdmissionError(e, t, n) {
	if (isAgentRunRestartAbortReason(e) || isGatewayRestartDrainError(e)) return respondError(t, ErrorCodes.UNAVAILABLE, "Gateway is restarting; retry after reconnecting", {
		retryable: true,
		details: { reason: GATEWAY_RESTART_UNAVAILABLE_REASON }
	});
	if (e instanceof SessionGoalOperationError) return respondError(t, ErrorCodes.INVALID_REQUEST, e.message, { details: { reason: `goal-${e.code}` } });
	const r = e instanceof Error ? e.message : void 0;
	if (r === "goal-session-busy") return respondError(t, ErrorCodes.UNAVAILABLE, "This session still has active or queued work. Wait for it to finish, then retry the Goal.", {
		retryable: true,
		details: { reason: "goal-session-busy" }
	});
	if (r === "session-routing-changed") return respondChatSessionRoutingChanged(t);
	if (r === "active-leaf-changed" || r === "session-settings-changed") return respondError(t, ErrorCodes.INVALID_REQUEST, r === "active-leaf-changed" ? "active branch changed; review and retry" : "Session settings changed before send. Retry.", { details: { reason: r } });
	if (isSessionTranscriptProjectionUnavailableError(e)) return respondError(t, ErrorCodes.UNAVAILABLE, "session transcript is rebuilding; retry shortly", {
		details: { method: "chat.send" },
		retryable: true,
		retryAfterMs: 250
	});
	const i = resolveChatSendStorageErrorMessage(e);
	const a = errorShapeFromError(i ? ErrorCodes.UNAVAILABLE : ErrorCodes.INVALID_REQUEST, e, { message: i ?? formatForLog(e) });
	t(false, void 0, a);
	if (i !== void 0 || hasSqliteWorkerOutcomeUnknown(e)) n?.(a.message);
}
//#endregion
//#region src/gateway/server-methods/chat-send-retry.ts
/** Classify an accepted-send failure without relying on unstable error text. */
function classifyAcceptedChatSendFailure(e) {
	if (e.executionStarted || e.sideEffectsObserved) return "reconcile";
	if (e.phase === "pre-ack" && e.error instanceof AgentDatabaseAdmissionError && createAgentDatabaseAdmissionErrorShape(e.error.refusal).retryable) return "client-retry";
	if (!isSessionTranscriptProjectionUnavailableError(e.error)) return "terminal";
	return e.phase === "post-ack" ? "retry" : "client-retry";
}
/** Wait for the exact failed projection before another accepted-send dispatch attempt. */
async function waitForAcceptedChatSendRetry(e, t, n) {
	if (!isSessionTranscriptProjectionUnavailableError(t)) throw t;
	await waitForSessionTranscriptProjection({
		...e,
		sessionId: t.sessionId
	}, n);
}
/** One Gateway budget covers setup and retries inside the already-admitted resolver. */
function createAcceptedChatSendRetry(e) {
	let t = 2;
	return async (n) => {
		while (true) try {
			return await n();
		} catch (n) {
			if (t === 0 || e.classify(n) !== "retry") throw n;
			t -= 1;
			await e.waitForRetry(n);
		}
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-dispatch-errors.ts
function formatReturnedAgentErrors(e) {
	if (e.collaborativeSteeringRefused) return COLLABORATIVE_STEERING_DISABLED_TEXT;
	if (e.runtimeError !== void 0) return e.runtimeError;
	const t = e.payloads.map((e) => e.text?.trim()).filter((e) => Boolean(e));
	const [n, ...r] = [...new Set(t)];
	if (!n || r.length === 0) return n || (e.runtimeFailed ? "agent run failed" : void 0);
	if (r.length === 1) return `${n}\n\nAdditional error: ${r[0]}`;
	return `${n}\n\nAdditional errors:\n${r.map((e) => `- ${e}`).join("\n")}`;
}
function resolveChatSendReturnedOutcome(e) {
	const { runtimeOutcome: t, deliveredReplies: n, agentRunStarted: r, isInternalTextSlashCommandTurn: i } = e;
	const a = readAgentRunTerminalOutcome(e.dispatchResult);
	const o = t ? classifyAgentRunTerminalOutcome(t) : a && (a === "failed" ? "failure" : "success");
	const s = o === "cancellation";
	const c = o === "failure" || o === "timeout";
	const l = n.map((e) => readChatSendReplyPayload(e.input)).filter((e) => e.isError);
	return {
		runtimeClassification: o,
		runtimeCancelled: s,
		runtimeFailed: c,
		returnedAgentErrorPayloads: l,
		hasOnlyFinalWarnings: l.length > 0 && n.every(({ kind: e, input: t }) => {
			const n = readChatSendReplyPayload(t);
			return e === "final" && n.isError === true || isReplyPayloadStatusNotice(n);
		}),
		hasReturnedAgentError: o ? c : l.length > 0 && (r || !i),
		returnedAgentErrorMessage: formatReturnedAgentErrors({
			payloads: l,
			runtimeError: t?.error,
			runtimeFailed: c,
			collaborativeSteeringRefused: e.collaborativeSteeringRefused
		})
	};
}
function formatChatSendError(e) {
	if (e instanceof DispatchSessionRefreshRequiredError) return `Your message didn't run because the conversation changed. Refresh the conversation, then send it again.\n\n${String(e)}`;
	return resolveStateContentionPresentation(e)?.errorMessage ?? resolveChatSendStorageErrorMessage(e) ?? renderAgentHarnessPreflightUserMessage(e) ?? renderFailoverCodeUserCopy(describeFailoverError(e).code) ?? String(e);
}
async function handleChatSendSetupError(e) {
	const { cleanupAdmittedRun: t, lifecycleGeneration: n } = e.admission;
	const { agentId: r, clientRunId: i, sessionKey: a } = e.session;
	const o = getAgentRunContext(i)?.projectSessionMessages === false;
	if (e.error instanceof ExpectedProfileMismatchError) {
		t();
		clearAgentRunContext(i, n);
		e.context.removeChatRun(i, i, a);
		e.respond(false, void 0, e.error.error);
		return;
	}
	const s = formatChatSendError(e.error);
	const c = resolveStateContentionPresentation(e.error)?.errorKind;
	const l = resolveAgentRunErrorLifecycleFields(e.error, void 0).stopReason === "restart" ? "client-retry" : classifyAcceptedChatSendFailure({
		error: e.error,
		phase: "pre-ack"
	});
	if (e.committedInput && l !== "client-retry" && getAgentRunContext(i)?.projectSessionLifecycle !== false) {
		const t = Date.now();
		try {
			await persistGatewaySessionLifecycleEvent({
				sessionKey: a,
				agentId: r,
				expectedWriter: {
					runId: i,
					...e.committedInput
				},
				event: {
					runId: i,
					sessionId: e.committedInput.sessionId,
					lifecycleGeneration: n,
					ts: t,
					data: {
						phase: "error",
						startedAt: getRpcSourceStartedAt(e.admission.activeRunAbort.entry),
						endedAt: t,
						error: s,
						errorKind: c
					}
				}
			});
			emitSessionsChanged(e.context, {
				sessionKey: a,
				agentId: r,
				reason: "chat.setup-error"
			});
		} catch (t) {
			e.context.logGateway.warn(`webchat session lifecycle persist failed after setup error: ${formatForLog(t)}`);
		}
	}
	t();
	clearAgentRunContext(i, n);
	e.context.removeChatRun(i, i, a);
	const u = e.error instanceof SessionMutationAuthorizationChangedError ? e.error.error : e.error instanceof SessionGoalOperationError ? errorShape(ErrorCodes.INVALID_REQUEST, e.error.message, { details: {
		code: "GOAL_OPERATION_REJECTED",
		reason: e.error.code
	} }) : errorShapeFromError(ErrorCodes.UNAVAILABLE, e.error, {
		message: s,
		...l === "client-retry" ? {
			retryable: true,
			retryAfterMs: 250
		} : {}
	});
	const d = {
		runId: i,
		status: "error",
		summary: s
	};
	if (e.cacheResult !== false && l !== "client-retry") setGatewayDedupeEntry({
		dedupe: e.context.dedupe,
		key: `chat:${i}`,
		session: captureAgentJobSession({
			...getRpcSourceIdentity(e.admission.activeRunAbort.entry),
			lifecycleGeneration: getRpcSourceLifecycleGeneration(e.admission.activeRunAbort.entry)
		}),
		entry: {
			ts: Date.now(),
			ok: false,
			payload: d,
			error: u
		}
	});
	e.respond(false, d, u, {
		runId: i,
		error: formatForLog(e.error)
	});
	if (!o && l !== "client-retry") broadcastChatError({
		terminalEntry: e.admission.activeRunAbort.entry,
		context: e.context,
		runId: i,
		sessionKey: a,
		agentId: r,
		errorMessage: s,
		errorKind: c
	});
}
/** Own dispatch settlement and post-cleanup lifecycle persistence. */
function createChatSendDispatchErrorLifecycle(e) {
	const { admission: t, context: n, isQueuedFollowupEnqueued: r, persistUserTurnTranscript: i, session: a, userTurnRecorder: o } = e;
	const { activeRunAbort: s, cleanupAdmittedRun: c, lifecycleGeneration: l } = t;
	const { agentId: u, clientRunId: d, now: f, sessionKey: p } = a;
	const m = captureChatAbortRegistrationGuard([{
		runId: d,
		entry: s.entry
	}]);
	const captureJobSession = () => captureAgentJobSession({
		...getRpcSourceIdentity(s.entry),
		lifecycleGeneration: getRpcSourceLifecycleGeneration(s.entry)
	});
	const h = getAgentRunContext(d);
	const g = h?.projectSessionMessages === false;
	const _ = h?.projectSessionLifecycle === false;
	let v;
	let y;
	let b;
	let x;
	const classifyFailure = (t) => e.injectionDisposition?.isRefused() ? "reconcile" : classifyAcceptedChatSendFailure({
		error: t,
		phase: "post-ack",
		executionStarted: e.isAgentRunStarted(),
		sideEffectsObserved: e.hasObservedSideEffects?.()
	});
	const broadcastError = (t) => {
		if (!g && (e.isReplyDispatchRun?.() || s.entry.adapter.chatErrorDispatchOwned === true || s.entry.adapter.terminalOutcomeObserved !== true)) {
			if (t.stopReason === "restart") broadcastChatTerminal({
				terminalEntry: s.entry,
				context: n,
				runId: d,
				sessionKey: p,
				agentId: u,
				state: "aborted",
				stopReason: "restart"
			});
			else broadcastChatError({
				terminalEntry: s.entry,
				context: n,
				runId: d,
				sessionKey: p,
				agentId: u,
				...t
			});
		}
	};
	const handleError = async (c) => {
		let l = c;
		try {
			await e.injectionDisposition?.settleRefusal();
		} catch (e) {
			l = new AggregateError([l, e], "Refused input custody could not settle");
		}
		const u = formatChatSendError(l);
		const p = resolveStateContentionPresentation(l)?.errorKind;
		if (r()) {
			n.logGateway.warn(`webchat dispatch failed after followup queue admission: ${formatForLog(l)}`);
			return;
		}
		if (s.entry.adapter.terminalOutcomeObserved === true) await waitForChatAbortTerminalPersistence(s.entry).catch((e) => {
			n.logGateway.warn(`webchat terminal lifecycle settlement failed: ${formatForLog(e)}`);
		});
		const h = resolveAgentRunErrorLifecycleFields(s.controller.signal.reason, void 0);
		const g = h.stopReason ? h : resolveAgentRunErrorLifecycleFields(l, void 0);
		const S = s.controller.signal.aborted;
		const C = n.chatRunState.runs.get(d)?.abortMarker;
		const w = s.entry.adapter.terminalOutcomeObserved === true;
		if (S && C !== void 0) {
			v = C;
			n.logGateway.warn(`chat.send post-dispatch threw after abort for runId=${d}: ${formatForLog(l)}`);
			if (!o.hasPersisted() && !o.isBlocked()) try {
				await i();
			} catch (e) {
				n.logGateway.warn(`webchat user transcript update failed after abort: ${formatForLog(e)}`);
			}
			return;
		}
		n.chatRunState.deleteAbortMarker(d);
		s.cleanup();
		b = o.hasPersisted() || o.isBlocked() ? void 0 : async () => {
			await i();
		};
		if (!_ && C === void 0 && !w) y = {
			allowUnstartedFailure: !e.isAgentRunStarted() ? true : void 0,
			terminationFields: g,
			endedAt: Date.now(),
			error: u,
			errorKind: p,
			sessionId: getRpcSourceIdentity(s.entry).sessionId,
			lifecycleRevision: a.entry?.lifecycleRevision ?? t.initialSessionEntry?.lifecycleRevision,
			startedAt: getRpcSourceStartedAt(s.entry) ?? f
		};
		if (!w || e.isReplyDispatchRun?.() || s.entry.adapter.chatErrorDispatchOwned === true) {
			const publish = () => {
				if (!m()) return;
				const e = g.stopReason === "restart";
				const t = errorShapeFromError(ErrorCodes.UNAVAILABLE, l, { message: u });
				setGatewayDedupeEntry({
					dedupe: n.dedupe,
					key: `chat:${d}`,
					session: captureJobSession(),
					entry: {
						ts: Date.now(),
						ok: e,
						payload: e ? buildAbortedChatSendPayload({
							runId: d,
							stopReason: "restart",
							endedAt: y?.endedAt ?? Date.now()
						}) : {
							runId: d,
							status: "error",
							summary: u,
							...g
						},
						...e ? {} : { error: t }
					}
				});
				broadcastError({
					errorMessage: u,
					errorKind: p,
					stopReason: g.stopReason
				});
			};
			if (y || e.isReplyDispatchRun?.()) x = publish;
			else publish();
		}
	};
	const settleTerminalPersistence = async () => {
		if (e.isReplyDispatchRun?.() && s.entry) await waitForChatAbortTerminalPersistence(s.entry).catch((e) => {
			n.logGateway.warn(`webchat terminal lifecycle settlement failed: ${formatForLog(e)}`);
		});
	};
	const finalize = async () => {
		await settleTerminalPersistence();
		const i = y;
		const clearRun = () => {
			if (!r() && (!e.isAgentRunStarted() || e.isReplyDispatchRun?.())) {
				n.chatRunState.clearRun(d);
				n.agentRunSeq.delete(d);
			}
		};
		try {
			if (!i) {
				const e = v ?? (s.controller.signal.aborted ? n.chatRunState.runs.get(d)?.abortMarker : void 0);
				if (e) {
					const t = chatAbortMarkerTimestampMs(e);
					setGatewayDedupeEntry({
						dedupe: n.dedupe,
						key: `chat:${d}`,
						session: captureJobSession(),
						entry: {
							ts: t,
							ok: true,
							payload: buildAbortedChatSendPayload({
								runId: d,
								stopReason: s.entry.adapter.abortStopReason ?? "rpc",
								endedAt: t
							})
						}
					});
				}
				clearAgentRunContext(d, l);
				n.removeChatRun(d, d, p);
				return;
			}
			await b?.().catch((e) => {
				n.logGateway.warn(`webchat user transcript update failed after error: ${formatForLog(e)}`);
			});
			clearAgentRunContext(d, l);
			n.removeChatRun(d, d, p);
			try {
				await persistGatewaySessionLifecycleEvent({
					sessionKey: p,
					...u ? { agentId: u } : {},
					expectedWriter: {
						...i.allowUnstartedFailure ? { allowUnstartedFailure: true } : {},
						runId: d,
						sessionId: i.sessionId,
						lifecycleRevision: i.lifecycleRevision
					},
					assertCommitAllowed: () => {
						if (!m()) throw new Error("Chat input was replaced before its failure could be persisted");
					},
					event: {
						runId: d,
						sessionId: i.sessionId,
						lifecycleGeneration: l,
						ts: i.endedAt,
						data: {
							phase: "error",
							startedAt: i.startedAt,
							endedAt: i.endedAt,
							error: i.error,
							errorKind: i.errorKind,
							...i.terminationFields
						}
					}
				});
				if (!g && !i.terminationFields.aborted) await t.recordFailureNotice?.({
					runId: d,
					error: i.error,
					errorKind: i.errorKind
				});
				emitSessionsChanged(n, {
					sessionKey: p,
					...u ? { agentId: u } : {},
					reason: "chat.dispatch-error"
				});
			} catch (e) {
				n.logGateway.warn(`webchat session lifecycle persist failed after error: ${formatForLog(e)}`);
			}
		} finally {
			try {
				x?.();
			} finally {
				clearRun();
				c();
			}
		}
	};
	return {
		broadcastError,
		classifyFailure,
		finalize,
		handleError,
		settleTerminalPersistence
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-reply-context.ts
const REPLY_CONTEXT_BODY_MAX_CHARS = 2e3;
/** Adds hydrated reply metadata to the direct-injection user prompt. */
function buildChatSendReplyInjectionText(e) {
	const t = buildInboundUserContextPrefix(e.ctx, resolveEnvelopeFormatOptions(e.cfg), e.sessionEntry);
	return t ? `${t}\n\n${e.body}` : e.body;
}
function extractReplyTargetText(e) {
	if (typeof e.text === "string" && e.text.trim()) return e.text;
	if (typeof e.content === "string" && e.content.trim()) return e.content;
	if (!Array.isArray(e.content)) return;
	const t = e.content.map((e) => {
		const t = asOptionalRecord(e);
		return t && typeof t.text === "string" ? t.text : "";
	}).filter((e) => e.trim());
	return t.length > 0 ? t.join("\n") : void 0;
}
/** Copies hydrated reply fields onto the inbound context without clobbering unset keys. */
function applyChatSendReplyContextFields(e, t) {
	for (const n of [
		"ReplyToId",
		"ReplyToBody",
		"ReplyToSender"
	]) if (t[n] !== void 0) e[n] = t[n];
}
/**
* Resolves a webchat reply target from session history. Always preserves the
* reply_to_id linkage; body/sender hydrate only when the transcript message
* still resolves, mirroring Discord's missing-referenced-message tolerance.
*/
async function resolveChatSendReplyContext(e) {
	const t = e.replyToId?.trim();
	if (!t) return {};
	const n = { ReplyToId: t };
	const r = e.sessionEntry?.sessionId;
	if (!r) return n;
	try {
		const i = await readSessionMessageByIdAsync({
			agentId: e.agentId,
			sessionEntry: e.sessionEntry,
			sessionId: r,
			sessionKey: e.sessionKey,
			storePath: e.storePath
		}, t, { allowResetArchiveFallback: true });
		if (!i.found) return n;
		const a = projectChatDisplayMessage(i.message, { resolveCronJobName: () => void 0 });
		if (!a) return n;
		const o = extractReplyTargetText(a)?.trim();
		const s = o && a.role === "assistant" ? sanitizeAssistantVisibleTextWithProfile(o, "history").trim() : o;
		if (!s) return n;
		n.ReplyToBody = truncateUtf16Safe(s, REPLY_CONTEXT_BODY_MAX_CHARS);
		n.ReplyToSender = a.role === "assistant" ? (await resolveAssistantIdentityName({
			cfg: e.cfg,
			agentId: e.agentId
		})).name : e.userSenderLabel?.trim() || "User";
		return n;
	} catch (r) {
		e.warn?.(`chat.send reply context hydration failed for ${t}: ${String(r)}`);
		return n;
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-message-injection.ts
/** Captures admitted request data for the detached injection attempt. */
function createChatSendMessageInjectionStarter(e) {
	const { p: t, rawMessage: n, supportsTaskSuggestions: r } = e.request;
	const { agentId: i, cfg: a, entry: o, sessionKey: s, storePath: c, clientRunId: l, resolvedSessionModel: u } = e.session;
	const { ctx: d, isInternalTextSlashCommandTurn: f, replyOptionImages: p, replyOptionMedia: m } = e.turn;
	const assertCurrent = () => {
		e.abortSignal.throwIfAborted();
		e.assertCurrent?.();
		e.operatorAuthority?.assertCurrent();
	};
	return async () => {
		try {
			var h = _usingCtx();
			const g = e.target;
			if (!g || f) return;
			const _ = h.u(e.diagnostics?.scope("detail.run_admission.steer_authority"));
			assertCurrent();
			const v = prepareSteeringDelivery({
				agentId: i,
				sessionKey: s,
				storePath: c,
				entry: o,
				assertCurrent
			});
			let y = false;
			let b;
			const release = () => {
				if (b?.kind === "prepared") b.release();
				v.release();
			};
			try {
				const canAdmit = () => {
					try {
						v.assertCurrent();
						return true;
					} catch (t) {
						if (!(t instanceof MessageInjectionTargetUnavailableError)) throw t;
						e.logGateway.warn("chat steering rejected; falling back to follow-up dispatch", {
							reason: "terminal-delivery-unavailable",
							runId: l,
							activeRunId: g.runId,
							sessionKey: s,
							error: t.message
						});
						return false;
					}
				};
				const { debounceMs: c } = resolveQueueSettings({
					cfg: a,
					channel: d.Provider,
					sessionEntry: o,
					inlineMode: t.queueMode
				});
				const f = e.documentContext?.status === "rendered" ? e.documentContext : void 0;
				const h = f?.images ?? [];
				const x = h.length > 0 ? [...p ?? [], ...h.map((e) => ({
					type: "image",
					data: e.data,
					mimeType: e.mimeType
				}))] : p;
				const S = await resolveCommandAuthorizationAsync({
					ctx: d,
					cfg: a,
					commandAuthorized: d.CommandAuthorized === true
				});
				const C = resolveInboundReplyToolAuthorityOverlay({
					ctx: d,
					sessionEntry: {
						spawnedBy: o?.spawnedBy,
						permissionMode: e.admittedSessionSettings?.permissionMode,
						toolOverrides: e.admittedSessionSettings?.toolOverrides
					},
					senderIsOwner: S.senderIsOwner,
					operatorAuthority: e.operatorAuthority,
					disableTools: false
				});
				const { traceAuthorized: w, allowCollaborativeSteering: T, ...E } = C;
				_?.mark("detail.run_admission.steer_continuation");
				b = await prepareReplyMessageContinuation({
					target: g,
					assertCurrent,
					delivery: v,
					input: {
						kind: "continuation",
						caller: E,
						config: a,
						executionSelection: captureReplySessionExecutionSelection({
							config: a,
							agentId: i,
							sessionEntry: o
						}),
						selectedRoute: u,
						fallbackAvailability: resolveModelFallbackAvailability({
							cfg: a,
							agentId: i,
							sessionKey: s,
							selectedModel: u,
							hasSessionModelOverride: o?.modelOverrideSource !== "default" && Boolean(o?.modelOverride || o?.providerOverride) && !hasLegacyAutoFallbackWithoutOrigin(o),
							modelOverrideSource: o?.modelOverrideSource === "default" ? void 0 : o?.modelOverrideSource,
							hasAutoFallbackProvenance: hasSessionAutoModelFallbackProvenance(o),
							modelSelectionLocked: o?.modelSelectionLocked
						})
					}
				});
				if (b.kind === "deferred") {
					e.logGateway.warn("chat steering rejected; falling back to follow-up dispatch", {
						reason: b.reason,
						error: b.errorMessage,
						runId: l,
						activeRunId: g.runId,
						sessionKey: s
					});
					return;
				}
				const D = b.kind === "prepared" ? b : void 0;
				_?.mark("detail.run_admission.steer_delivery");
				try {
					await v.prepareCurrent();
				} catch (t) {
					assertCurrent();
					e.logGateway.warn("chat steering rejected; falling back to follow-up dispatch", {
						reason: "terminal-delivery-unavailable",
						runId: l,
						activeRunId: g.runId,
						sessionKey: s,
						error: String(t)
					});
					return;
				}
				if (d.media?.some((e) => e.path) && !hasStagedMediaFacts(d.media)) {
					_?.mark("detail.run_admission.steer_attachments");
					const { stageReplyMedia: t } = await import("./stage-reply-media-BQJMsS2L.mjs");
					await t({
						ctx: d,
						sessionCtx: d,
						cfg: a,
						agentId: i,
						sessionKey: s,
						workspaceDir: resolveAgentWorkspaceDir(a, i),
						sessionEntry: o,
						skillOverrides: e.admittedSessionSettings?.toolOverrides?.skills,
						abortSignal: e.abortSignal,
						assertCurrent: () => {
							assertCurrent();
							v.assertCurrent();
						}
					});
				}
				const O = d.BodyForAgent ?? d.Body ?? n;
				const k = f?.text.trim();
				const A = d.media?.length || k || e.documentContext?.status === "failed" ? [
					buildInboundMediaNoteProjection(d).text,
					O.trim(),
					k
				].filter(Boolean).join("\n\n") : O;
				let j = false;
				_?.mark("detail.run_admission.steer_admit");
				const M = await beginSessionControllerSteer({
					input: e.sourceRef.input,
					target: g,
					text: t.replyToId ? buildChatSendReplyInjectionText({
						body: A,
						cfg: a,
						ctx: d,
						sessionEntry: o
					}) : A,
					options: {
						currentInboundContext: t.replyToId ? void 0 : { text: buildInboundUserContextPrefix(d, resolveEnvelopeFormatOptions(a), o) },
						canAdmit: () => {
							j = !canAdmit();
							return !j;
						},
						assertCurrent: e.assertCurrent || e.operatorAuthority ? assertCurrent : void 0,
						toolAuthorityPreparation: bindPreparedToolAuthority(bindWorkerToolPreparation({
							authorityKind: e.assertCurrent || e.operatorAuthority ? "source-bound" : "run",
							assertCurrent,
							compatAssertCurrent: () => {
								assertCurrent();
								D?.read();
							},
							prepareCurrent: async () => {
								await D?.prepareCurrent();
								await v.prepareCurrent();
							}
						})),
						inboundAudio: hasInboundAudio(d),
						steeringMode: "all",
						isInboundUserMessage: true,
						allowCollaborativeSteering: a.messages?.queue?.allowCollaborativeSteering === true && (!d.InputProvenance || d.InputProvenance.kind === "external_user"),
						...isProgressCardRefreshInputProvenance(d.InputProvenance) ? {
							allowPendingUserInputAnswer: false,
							debounceMs: 0
						} : {},
						...D ? { toolAuthorityFingerprint: D.fingerprint } : { toolAuthorityOverlay: C },
						...x?.length ? { images: x } : {},
						...e.imageOrder?.length ? { imageOrder: e.imageOrder } : {},
						...m?.length ? { media: m } : {},
						waitForTranscriptCommit: true,
						abortSignal: e.abortSignal,
						...!isProgressCardRefreshInputProvenance(d.InputProvenance) && c !== void 0 ? { debounceMs: c } : {},
						...D ? {} : { taskSuggestionDeliveryMode: r ? "gateway" : void 0 },
						userTurnTranscriptRecorder: e.userTurnTranscriptRecorder
					}
				});
				if (!M) return;
				M.outcome.then(release, release);
				y = true;
				return j ? void 0 : M;
			} finally {
				if (!y) release();
			}
		} catch (e) {
			h.e = e;
		} finally {
			h.d();
		}
	};
}
/** Keep a terminal injection decision through detached preparation and reply dispatch. */
function createChatSendInjectionDisposition(e, t) {
	let n = false;
	const r = {};
	const isRefused = () => n && t?.collaborativeSteeringFallback === "reject" || r.admission?.status === "skipped" && r.admission.reason === "collaborative-steering-disabled";
	return {
		runState: r,
		isRefused,
		isCollaborationBlocked: () => n,
		async observe(e) {
			const i = await e?.outcome;
			if (i?.status === "rejected" && i.reason === "collaborative_steering_disabled") {
				n = true;
				if (t?.collaborativeSteeringFallback === "reject") r.admission = {
					status: "skipped",
					reason: "collaborative-steering-disabled"
				};
				return;
			}
			return e;
		},
		async settleRefusal() {
			if (isRefused()) await refuseCollaborativeSteering(e, r);
		}
	};
}
/** Join steering before fallible source preparation can trigger a separate reply. */
async function settleChatSendMessageInjection(e) {
	if (!e) return false;
	const t = await e.outcome;
	if (t.status === "failed") throw t.error;
	return t.status !== "rejected";
}
/** Finish an accepted steer without entering reply dispatch, or return false for fallback. */
async function finalizeAcceptedChatSendMessageInjection(e) {
	const { context: t, ctx: n, session: r } = e;
	const { agentId: i, cfg: a, clientRunId: o, entry: s, sessionKey: c, storePath: l } = r;
	const u = finalizeInboundContext(n);
	const d = isProgressCardRefreshInputProvenance(n.InputProvenance);
	const f = await finalizeReplyMessageInjectionAttempt({
		attempt: e.attempt,
		target: e.target,
		inboundAudio: hasInboundAudio(u)
	});
	if (f.status === "rejected") return false;
	recordAcceptedSessionParticipantInput(n, {
		agentId: i,
		sessionKey: c,
		storePath: l
	});
	const p = normalizeLowercaseStringOrEmpty(u.Surface ?? u.Provider ?? "unknown");
	const m = u.To ?? u.From;
	const h = u.MessageSidFull ?? u.MessageSid ?? u.MessageSidFirst ?? u.MessageSidLast;
	const g = f.status === "indeterminate" ? f.outcome.errorMessage : void 0;
	const _ = g ? d ? "progress_refresh_receipt_unconfirmed" : "question_response_indeterminate" : "active_run_injected";
	await e.persistUserTurnTranscriptBestEffort();
	if (isDiagnosticsEnabled(a)) {
		logMessageReceived({
			sessionKey: c,
			channel: p,
			chatId: m,
			messageId: h,
			source: "dispatchInboundMessage"
		});
		logMessageProcessed({
			channel: p,
			chatId: m,
			messageId: h,
			sessionKey: c,
			durationMs: Math.max(0, Date.now() - e.startedAt),
			outcome: g ? "error" : "completed",
			reason: _
		});
	}
	emitMessageReceivedHooks({
		ctx: u,
		hookRunner: getGlobalHookRunner(),
		sessionKey: c,
		timestamp: typeof u.Timestamp === "number" && Number.isFinite(u.Timestamp) ? u.Timestamp : void 0
	});
	emitInboundMessageAuditTerminal({
		cfg: a,
		counts: {
			tool: 0,
			block: 0,
			final: 0
		},
		ctx: u,
		observedRunId: o,
		startedAt: e.startedAt,
		terminal: g ? {
			outcome: "error",
			options: {
				reason: _,
				error: g
			}
		} : {
			outcome: "completed",
			options: { reason: _ }
		}
	});
	const v = Date.now();
	if (s) r.entry = {
		...s,
		updatedAt: v
	};
	await updateSessionEntry({
		storePath: l,
		sessionKey: c
	}, () => ({ updatedAt: v }), {
		skipMaintenance: true,
		takeCacheOwnership: true
	}).catch((e) => {
		t.logGateway.warn(`failed to touch session after accepted steering: ${String(e)}`);
	});
	if (!t.chatRunState.hasAbortMarker(o)) {
		setGatewayDedupeEntry({
			dedupe: t.dedupe,
			key: `chat:${o}`,
			session: captureAgentJobSession(e.sourceRef ? {
				...getRpcSourceIdentity(e.sourceRef),
				lifecycleGeneration: getRpcSourceLifecycleGeneration(e.sourceRef)
			} : void 0),
			entry: {
				ts: Date.now(),
				ok: d || !g,
				payload: {
					runId: o,
					status: d ? "accepted" : g ? "error" : "ok",
					...g ? { summary: g } : {}
				},
				...!d && g ? { error: errorShape(ErrorCodes.UNAVAILABLE, g) } : {}
			}
		});
		if (g) broadcastChatError({
			terminalEntry: e.sourceRef,
			context: t,
			runId: o,
			sessionKey: c,
			agentId: i,
			errorMessage: g
		});
		else broadcastChatFinal({
			context: t,
			runId: o,
			sessionKey: c,
			agentId: i,
			terminalEntry: e.sourceRef
		});
	}
	return true;
}
//#endregion
//#region src/gateway/server-methods/chat-send-reply-delivery.ts
/** Match prepared evidence to the current session without querying its transcript. */
function resolveChatReplyTranscriptStart(e, t, n) {
	const r = {
		agentId: e.agentId,
		sessionKey: e.sessionKey,
		sessionId: t.entry?.sessionId ?? e.backingSessionId,
		storePath: t.storePath
	};
	if (n && (n.agentId !== r.agentId || n.sessionId !== r.sessionId || n.sessionKey !== r.sessionKey || !isSameOpenClawAgentDatabasePath(n.storePath, r.storePath))) return;
	const i = n ?? {
		generation: null,
		maxSeq: null
	};
	return {
		sessionId: r.sessionId,
		generation: i.generation,
		afterSeq: i.maxSeq ?? 0
	};
}
/** Released SDK producers may still omit transcript facts until the next SDK major. */
function resolveLegacyChatReplyTranscriptStart(e, t) {
	warnLegacyAgentRunStart();
	const n = t.entry?.sessionId ?? e.backingSessionId;
	return resolveChatReplyTranscriptStart(e, t, n ? {
		agentId: e.agentId,
		sessionId: n,
		sessionKey: e.sessionKey,
		storePath: t.storePath,
		...readSessionTranscriptWatermark({
			agentId: e.agentId,
			sessionId: n,
			sessionKey: e.sessionKey,
			storePath: t.storePath
		})
	} : null);
}
/** Decide receipt coverage from one current anchor snapshot and the observed transcript bounds. */
function resolveChatReplyDeliveryFromAnchors(e) {
	const { facts: t, afterSeq: n, watermark: r, currentWatermark: i } = e;
	const a = t.anchors.find((t) => t.entryId === e.admissionId);
	const o = t.anchors.find((t) => t.entryId === e.inputId);
	const s = t.anchors.find((t) => t.entryId === e.messageId);
	if (!a || !o) return "missing";
	if (!s || s.rawSeq <= n || s.activeMessagePosition <= o.activeMessagePosition) return;
	if (t.tail?.entries.some((e) => e.role === "user" && e.anchor && e.anchor.activeMessagePosition > s.activeMessagePosition)) return "missing";
	if (i.generation !== r.generation || i.maxSeq !== r.maxSeq || s.generation !== i.generation || t.tail?.lastSeq !== i.maxSeq) return "pending";
	return "delivered";
}
//#endregion
//#region src/gateway/server-methods/chat-send-delivery-authority.ts
async function createChatSendReplyFinalizationAuthority(e, t, n) {
	const { cfg: r, sessionKey: i, agentId: a, sessionLoadOptions: o } = e.session;
	const s = e.terminalEntry ? captureChatAbortRegistrationGuard([{
		runId: e.session.clientRunId,
		entry: e.terminalEntry
	}]) : () => true;
	const c = /* @__PURE__ */ new Map();
	try {
		for (const n of t) {
			const t = getReplyPayloadMetadata(n)?.sessionWriterDeliveryAuthority;
			if (t && !c.has(t)) {
				const n = t.agentId ?? a;
				c.set(t, await prepareSessionWriterDeliveryAuthority({
					...t,
					agentId: n
				}, n === a ? e.session.storePath : void 0));
			}
		}
	} catch (e) {
		for (const e of c.values()) e.release();
		throw e;
	}
	const l = [];
	const deliveryAuthorized = () => s() && (!e.isCurrent || e.isCurrent()) && t.every((e) => {
		const t = getReplyPayloadMetadata(e)?.sessionWriterDeliveryAuthority;
		return isReplyPayloadSessionWriterDeliveryAuthorized(e, t ? c.get(t)?.authority?.readCurrentSession?.() : void 0);
	});
	const authorizeDelivery = (t) => {
		if (deliveryAuthorized()) return true;
		e.context.logGateway.warn(`webchat settled final reply skipped: session writer changed before ${t}`);
		n?.();
		return false;
	};
	return {
		deliveryAuthorized,
		authorizeDelivery,
		release: () => {
			for (const e of l) e.release();
			for (const e of c.values()) e.release();
		},
		captureMediaScope: async () => {
			try {
				const t = await captureWebchatReplyMediaScope({
					cfg: r,
					sessionKey: i,
					agentId: a,
					sessionLoadOptions: o,
					requesterContext: e.requesterContext,
					accountId: e.accountId,
					assertCurrent: () => {
						if (!deliveryAuthorized()) throw new Error("Chat media delivery is no longer authorized.");
					}
				});
				l.push(t);
				return t;
			} catch (e) {
				if (!authorizeDelivery("media preparation")) return;
				throw e;
			}
		}
	};
}
//#endregion
//#region src/gateway/server-methods/chat-tts-markers.ts
function stripVisibleTextFromTtsSupplement(e) {
	return isReplyPayloadTtsSupplement(e) ? buildTtsSupplementMediaPayload(e) : e;
}
function resolveTtsSupplementMarkerText(e) {
	const t = e.trim();
	const n = projectChatDisplayMessage({
		role: "assistant",
		content: [{
			type: "text",
			text: t
		}]
	}, { maxChars: Number.MAX_SAFE_INTEGER });
	const r = Array.isArray(n?.content) ? n.content : void 0;
	return extractAssistantDisplayText(r) ?? (typeof n?.text === "string" ? n.text.trim() : void 0) ?? t;
}
function buildTtsSupplementTranscriptMarker(e) {
	const t = getReplyPayloadTtsSupplement(e);
	if (!t) return;
	const n = resolveTtsSupplementMarkerText(e.text?.trim() || t.spokenText.trim());
	return { textSha256: sha256Hex(n) };
}
function buildMediaOnlyTtsSupplementTranscriptMarker(e) {
	if (e.text?.trim()) return;
	return buildTtsSupplementTranscriptMarker(e);
}
//#endregion
//#region src/gateway/server-methods/chat-send-reply-finalization.ts
const retainCommittedChatReplyMedia = (e, t) => {
	const n = readAssistantDisplayContent(e.message);
	if (hasManagedOutgoingAssistantContent(n)) t(async () => {
		await attachManagedOutgoingMediaToMessage({
			messageId: e.messageId,
			blocks: n
		});
	});
};
function resolveTranscriptMirrorOwner(e) {
	const t = e.map((e) => getReplyPayloadMetadata(e)?.sourceReplyTranscriptMirror);
	if (t.every((e) => e?.expectedSessionId === void 0 && !e?.transcriptWriteBlocked)) return { kind: "none" };
	const n = t[0];
	if (!n) return { kind: "invalid" };
	const r = n.sessionKey.trim();
	const i = n.expectedSessionId?.trim();
	if (!r || !n.transcriptWriteBlocked && !i || t.some((e) => n.transcriptWriteBlocked && !e?.transcriptWriteBlocked || e?.sessionKey.trim() !== r || e.expectedSessionId?.trim() !== i || e.agentId !== n.agentId || !n.transcriptWriteBlocked && e.transcriptWriteBlocked === true)) return { kind: "invalid" };
	return {
		kind: n.transcriptWriteBlocked ? "blocked" : "owner",
		owner: {
			sessionKey: r,
			...i ? { expectedSessionId: i } : {},
			...n.agentId ? { agentId: n.agentId } : {}
		}
	};
}
function buildChatSendBtwSideResult(e) {
	const t = e.map((e) => readChatSendReplyPayload(e.input)).filter(isBtwReplyPayload);
	const n = combineNonStreamingReplyParts(t.map((e) => e.text));
	if (t.length === 0 || !n) return;
	return {
		question: expectDefined(t[0], "btw replies entry at 0").btw.question.trim(),
		text: n,
		isError: t.some((e) => e.isError)
	};
}
/** Finalize settled reply payloads, retaining the runtime's transcript ownership and outcome. */
async function finalizeChatSendDispatchedReplies(e) {
	const { context: t, deliveredReplies: n, emitFirstAssistantServerTiming: r, foldCommandBlocks: i, persistUserTurnTranscript: a, session: o, suppressReplies: s } = e;
	const { agentId: c, backingSessionId: l, cfg: u, clientRunId: d, sessionKey: f, sessionLoadOptions: p } = o;
	const m = e.state === "aborted" ? "aborted" : "stop";
	const h = buildChatSendBtwSideResult(n);
	if (h) {
		broadcastSideResult({
			context: t,
			payload: {
				kind: "btw",
				runId: d,
				sessionKey: f,
				...c ? { agentId: c } : {},
				...h,
				ts: Date.now()
			}
		});
		broadcastChatFinal({
			terminalEntry: e.terminalEntry,
			context: t,
			runId: d,
			sessionKey: f,
			agentId: c
		});
		return;
	}
	const g = !e.runtimeOwnsTranscript && n.length > 0 && n.every(({ input: e }) => {
		const t = readChatSendReplyPayload(e);
		const n = getReplyPayloadMetadata(t);
		return n?.commandReply === true && n.contextFreeCommand === true && n.assistantTranscriptOwned !== true;
	});
	const _ = selectChatSendFinalReplyInputs({
		deliveredReplies: n,
		foldCommandBlocks: i,
		suppressReplies: s
	});
	const v = _.map(readChatSendReplyPayload);
	const { authorizeDelivery: y, captureMediaScope: b, release: x } = await createChatSendReplyFinalizationAuthority(e, v, () => broadcastChatFinal({
		context: t,
		runId: d,
		sessionKey: f,
		agentId: c,
		terminalEntry: e.terminalEntry
	}));
	try {
		const n = resolveTranscriptMirrorOwner(v);
		const i = n.kind === "owner" || n.kind === "blocked" ? n.owner : void 0;
		const o = await b();
		if (!o) return;
		const h = await loadGatewaySessionEntryReadOnlyInWorker({
			cfg: t.getRuntimeConfig(),
			key: f,
			...p,
			projection: []
		});
		const x = i ? await loadGatewaySessionEntryReadOnlyInWorker({
			cfg: t.getRuntimeConfig(),
			key: i.sessionKey,
			...p,
			...i.agentId ? { agentId: i.agentId } : {},
			projection: []
		}) : void 0;
		const S = Boolean(n.kind === "owner" && i && x?.entry?.sessionId === i.expectedSessionId);
		if (n.kind === "owner" && !S) t.logGateway.warn(`webchat transcript append skipped: binding-owned session changed before finalization`);
		if (n.kind === "invalid") t.logGateway.warn(`webchat transcript append skipped: inconsistent binding-owned transcript metadata`);
		if (n.kind === "blocked") t.logGateway.warn(`webchat transcript append skipped: binding-owned user turn was not persisted`);
		const C = n.kind === "none" || S;
		const w = S && i ? i.sessionKey : f;
		const T = S && i ? i.agentId ?? c : c;
		const { storePath: E, entry: D } = S && x ? x : h;
		const O = D?.sessionId ?? l ?? d;
		const { payloads: k, inputs: A, mediaMessage: j, assistantContent: M, persistedAssistantContent: N, broadcastContent: P, managedMediaPrepareFailed: F } = await prepareWebchatReplyMediaForDisplay({
			scope: o,
			storePath: h.storePath,
			transcriptTarget: {
				sessionKey: w,
				agentId: T
			},
			inputs: _,
			abortSignal: e.abortSignal,
			includeSensitiveMedia: false,
			includeSensitiveDisplay: true,
			logGateway: t.logGateway
		});
		const I = k.map((e) => buildMediaOnlyTtsSupplementTranscriptMarker(e)).find((e) => Boolean(e));
		const L = hasAssistantDisplayMediaContent(N) ? N : void 0;
		const ee = extractAssistantDisplayText(M) ?? buildTranscriptReplyTextFromInputs(A);
		const R = ee?.trim() ?? "";
		const z = j?.transcriptText || (F ? R : buildTranscriptReplyTextFromInputs(A)) || R;
		let B;
		const V = v.some((e) => getReplyPayloadMetadata(e)?.assistantTranscriptOwned === true);
		const te = Boolean((!e.runtimeOwnsTranscript && !V || S) && C && (z || L?.length));
		if (g) await a({ contextFreeCommand: true });
		else await a();
		if (!y("transcript append")) return;
		if (te) {
			const e = await appendInjectedAssistantMessageToTranscript({
				sessionKey: w,
				message: z,
				...L?.length ? { content: L } : {},
				sessionId: O,
				storePath: E,
				agentId: T,
				idempotencyKey: d,
				stopReason: m,
				ttsSupplement: I,
				...g ? { contextFreeCommand: true } : {},
				config: u,
				onMessageCommitted: retainCommittedChatReplyMedia
			});
			if (e.ok) B = P?.length ? applyAssistantDeliveryDirectives({
				...e.message,
				content: P.map((e) => ({ ...e }))
			}) : e.message;
			else {
				t.logGateway.warn(`webchat transcript append failed: ${e.error ?? "unknown error"}`);
				const n = stripManagedOutgoingAssistantContentBlocks(N) ?? stripManagedOutgoingAssistantContentBlocks(M);
				const r = extractAssistantDisplayText(n) ?? ee;
				B = {
					role: "assistant",
					...n?.length ? { content: n } : r ? { content: [{
						type: "text",
						text: r
					}] } : {},
					...r ? { text: r } : {},
					timestamp: Date.now(),
					...I ? { openclawTtsSupplement: I } : {},
					stopReason: m,
					usage: {
						input: 0,
						output: 0,
						totalTokens: 0
					}
				};
			}
		} else if (P?.length) B = {
			role: "assistant",
			content: P,
			text: extractAssistantDisplayText(P) ?? "",
			timestamp: Date.now(),
			stopReason: m,
			usage: {
				input: 0,
				output: 0,
				totalTokens: 0
			}
		};
		if (!y("broadcast")) return;
		const ne = t.chatRunState.runs.get(d);
		if (!s && ne?.bufferIsCurrent?.() !== false) B = appendChatCanvasBlocksToMessage(B, ne?.canvasBlocks ?? []);
		if (hasVisibleAssistantFinalMessage(B)) {
			r();
			t.chatRunState.flushPendingText(d);
		}
		broadcastChatTerminal({
			terminalEntry: e.terminalEntry,
			context: t,
			runId: d,
			sessionKey: f,
			agentId: c,
			message: B,
			state: e.state,
			stopReason: e.stopReason
		});
	} finally {
		x();
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-reply-session.ts
/** Initialization owns the start binding; later delivery decisions read fresh stored rows. */
function createChatReplySessionReader(e, t, n) {
	const r = e.storePath ?? resolveSessionStorePathCore(e.cfg.session?.store, { agentId: e.agentId });
	let i = {
		sessionKey: e.sessionKey,
		sessionId: e.entry?.sessionId ?? e.backingSessionId,
		lifecycleRevision: e.entry?.lifecycleRevision,
		storePath: r
	};
	const a = e.sessionTarget;
	const o = a?.readSource;
	const s = a && o && typeof o.databaseIdentity === "string" && n && a.storeKeys.length === 1 && a.storeKeys[0] === a.storeKey && e.capturedReadSources?.length === 1 && isDeepStrictEqual(e.capturedReadSources[0], o) ? {
		target: a,
		source: {
			...o,
			databaseIdentity: o.databaseIdentity
		},
		assertWorkCurrent: n
	} : void 0;
	const c = captureSessionMutationRouting(e.cfg, void 0, [e]);
	const l = s ? () => {
		s.assertWorkCurrent();
		c(t());
	} : void 0;
	return {
		assertRetainedSourceCurrent: l,
		notePreparedSession(t) {
			if (t.sessionKey === e.sessionKey) i = { ...t };
		},
		captureTranscriptStart(t) {
			const n = {
				entry: i,
				storePath: i.storePath ?? r
			};
			const a = t === void 0 ? resolveLegacyChatReplyTranscriptStart(e, n) : resolveChatReplyTranscriptStart(e, n, t);
			return a ? {
				...a,
				lifecycleRevision: i.lifecycleRevision
			} : void 0;
		},
		async readCurrentSession(n = e.sessionKey, i = e.agentId) {
			const a = t();
			if (s && l && n === e.sessionKey && i === e.agentId) {
				const e = l;
				e();
				return withQualifiedGatewaySessionStoreTarget({
					target: s.target,
					logicalStorePath: r,
					preparedSource: {
						...s.source,
						assertCurrent: e
					},
					includeMembership: false,
					readOptions: { projection: "exact" },
					consume: (t, n, r) => {
						r();
						e();
						omitInternalSessionEffectsEntries(t.store, t.storeKeys);
						const i = findCanonicalStoreMatch(t.store, t.storeKeys);
						return {
							...t,
							cfg: a,
							entry: i?.entry,
							legacyKey: i?.key !== t.canonicalKey ? i?.key : void 0
						};
					}
				});
			}
			const o = captureSessionMutationRouting(a, void 0, [{
				sessionKey: n,
				agentId: i
			}]);
			return await loadGatewaySessionEntryReadOnlyInWorker({
				...e.sessionLoadOptions,
				cfg: a,
				key: n,
				excludeInternalEffects: true,
				agentId: i,
				assertActive: () => o(t())
			});
		}
	};
}
//#endregion
//#region src/gateway/server-methods/chat-transcript-media-enrichment.ts
/** Enrich the committed occurrence even when input preparation changed the turn watermark. */
async function rewriteAssistantTranscriptMessageById(e) {
	await waitForSessionTranscriptProjection(e.scope, e.abortSignal);
	e.assertCurrent();
	const t = await readActiveTranscriptEntryAnchorAsync({
		...e.scope,
		entryId: e.messageId
	});
	e.assertCurrent();
	if (!t) return null;
	const n = await rewritePreparedTranscriptMessageAtAnchor(t, (t) => {
		const n = asOptionalRecord(t);
		if (n?.role !== "assistant" || readSessionTranscriptRunId(n) !== e.runId) return;
		return buildAssistantDisplayRewrite({
			message: n,
			displayContent: e.content,
			mediaBySource: e.mediaBySource,
			managedMediaUrls: e.mediaUrls,
			retainOriginalText: true
		});
	}, {
		active: "sequence",
		expectedEntry: { lifecycleRevision: e.expectedLifecycleRevision },
		assertCurrent: e.assertCurrent,
		assertNativeCurrent: e.assertCurrent
	});
	return n ? {
		generation: n.generation,
		messageId: e.messageId
	} : null;
}
//#endregion
//#region src/gateway/server-methods/chat-send-reply-dispatch.ts
/** Build delivery options and capture state for the core-owned webchat dispatcher. */
function createChatSendReplyDispatch(e) {
	const { accountId: t, getRuntimeConfig: n, isAgentRunStarted: r, logGateway: i, session: a, userTurnRecorder: o } = e;
	const { backingSessionId: s, cfg: c, clientRunId: l } = a;
	const u = {
		...a.sessionLoadOptions,
		clone: false
	};
	const { notePreparedSession: d, readCurrentSession: f, captureTranscriptStart: p, assertRetainedSourceCurrent: m } = createChatReplySessionReader(a, n, e.assertWorkCurrent);
	let h;
	let g = l;
	const captureAgentTranscriptStart = (e = l, t) => {
		g = e;
		const n = p(t);
		h = n;
		return n !== void 0;
	};
	const { onModelSelected: _, ...v } = createChannelReplyPipeline({
		cfg: c,
		agentId: a.agentId,
		channel: INTERNAL_MESSAGE_CHANNEL
	});
	const y = [];
	const b = /* @__PURE__ */ new Set();
	const x = createAssistantCommentaryMediaCustody({
		requesterContext: e.requesterContext,
		session: {
			...a,
			storePath: a.storePath ?? resolveSessionStorePathCore(c.session?.store, { agentId: a.agentId })
		},
		accountId: t,
		getRunId: () => g,
		isCurrent: () => r() && e.isRunCurrent?.() === true,
		abortSignal: e.abortSignal,
		logGateway: i,
		prepareAssistantTranscriptMessage: e.prepareAssistantTranscriptMessage
	});
	const resolveReplyDeliveryFacts = async (t = 0) => {
		const i = a.sessionTarget?.readSource;
		const s = m && i ? retainSessionHistoryWorkerDatabase({
			agentId: i.agentId,
			path: i.path
		}) : void 0;
		try {
			const i = o.getAdmissionReceipt();
			const c = h;
			const l = g;
			const u = c?.lifecycleRevision;
			const d = i && getOwnedSessionTranscriptReader(i);
			const isRunCurrent = () => {
				const t = o.getAdmissionReceipt();
				return Boolean(i && i.agentId === a.agentId && i.sessionKey === a.sessionKey && r() && e.isRunCurrent?.() === true && !e.abortSignal?.aborted && g === l && h === c && t?.logicalTurnId === i.logicalTurnId && t?.entryId === i.entryId);
			};
			const isInspectionCurrent = () => {
				if (!isRunCurrent()) return false;
				m?.();
				s?.owner.assertCurrent();
				d?.assertCurrent();
				return true;
			};
			const isCurrent = async () => {
				if (!i || !isRunCurrent()) return false;
				const e = await f();
				return isRunCurrent() && e.entry?.sessionId === i.sessionId && e.entry.lifecycleRevision === u && resolveSessionTranscriptDatabasePath({
					agentId: a.agentId,
					sessionId: i.sessionId,
					sessionKey: a.sessionKey,
					storePath: e.storePath
				}) === i.storePath;
			};
			if (!i || !c || c.sessionId !== i.sessionId || !(d ? isInspectionCurrent() : await isCurrent())) return {
				source: "missing",
				terminal: "missing"
			};
			const p = i;
			await waitForSessionTranscriptProjection(p, e.abortSignal);
			if (!(d || m ? isInspectionCurrent() : await isCurrent())) return {
				source: "missing",
				terminal: "missing"
			};
			const _ = captureSessionMutationRouting(n(), void 0, [p]);
			let v = "pending";
			let y = "missing";
			await readSessionTranscriptAnchorsAsync(p, {
				entryIds: [i.entryId],
				afterSeq: c.afterSeq,
				includeSession: true,
				includeWatermark: true,
				includeMessagesForRunId: l
			}, e.abortSignal, (e) => {
				_(n());
				if (!isInspectionCurrent() || e.session?.sessionId !== i.sessionId || e.session.lifecycleRevision !== u || !e.watermark) {
					v = "missing";
					return;
				}
				const r = e.anchors.find((e) => e.entryId === i.entryId);
				if (!r || r.rawSeq !== i.rawSeq) {
					v = "missing";
					return;
				}
				let a = r;
				for (const t of e.tail?.entries ?? []) if (t.role === "user" && t.anchor && t.anchor.activeMessagePosition > a.activeMessagePosition) a = t.anchor;
				if (t > 0 && a.entryId === r.entryId) {
					v = "missing";
					return;
				}
				v = "missing";
				for (const t of e.tail?.entries ?? []) {
					const n = asOptionalRecord(t.message);
					if (n?.role !== "assistant" || readSessionTranscriptRunId(n) !== l) continue;
					if (!(n.stopReason === "toolUse" || Array.isArray(n.content) && n.content.some((e) => isToolHistoryBlockType(asOptionalRecord(e)?.type)) ? extractAssistantTextForPhase(n, { phase: "final_answer" }) : extractAssistantPhaseText(n)) || !extractAssistantPhaseText(projectChatDisplayMessage(n))) continue;
					const r = resolveChatReplyDeliveryFromAnchors({
						facts: e,
						admissionId: i.entryId,
						inputId: a.entryId,
						messageId: t.entryId,
						afterSeq: c.afterSeq,
						watermark: e.watermark,
						currentWatermark: e.watermark
					});
					if (r !== void 0) {
						v = r;
						const e = asOptionalRecord(n.openclawDeliveryMirror);
						if (e?.kind === "message-tool-source-reply" && e.final === true) {
							y = r;
							return;
						}
					}
				}
			});
			_(n());
			return isInspectionCurrent() ? {
				source: y,
				terminal: v
			} : {
				source: "missing",
				terminal: "missing"
			};
		} finally {
			s?.release();
		}
	};
	const needsAgentMediaTranscriptFinalization = (e) => isMediaBearingPayload(e) || Boolean(getReplyPayloadMetadata(e)?.assistantMediaFailures?.length);
	const agentMediaTranscriptKey = (e) => {
		const t = getReplyPayloadMetadata(e);
		const n = t?.assistantTranscriptOwned === true ? t.assistantTranscriptIdempotencyKey?.trim() : void 0;
		if (n) return `owned:${n}`;
		if (t?.assistantMessageIndex !== void 0) return `index:${t.assistantMessageIndex}`;
		const r = t?.assistantTranscriptSource?.committedMessageId;
		if (r) return `message:${r}`;
		return "unkeyed";
	};
	const appendWebchatAgentMediaTranscriptIfNeeded = async (n) => {
		const o = readChatSendReplyPayload(n);
		if (!r() || !needsAgentMediaTranscriptFinalization(o)) return;
		const d = agentMediaTranscriptKey(o);
		if (b.has(d)) return;
		if (isSourceReplyTranscriptMirrorPayload(o)) return;
		const p = e.getReplyDispatchRun?.();
		const m = p?.getResult().assistantTranscript;
		if (p && !m) {
			i.warn("webchat runtime-owned media skipped: assistant transcript was not persisted");
			return;
		}
		const _ = m?.sessionKey ?? a.sessionKey;
		const v = m?.agentId ?? a.agentId;
		const y = buildTtsSupplementTranscriptMarker(o);
		const x = await captureWebchatReplyMediaScope({
			requesterContext: e.requesterContext,
			cfg: c,
			sessionKey: _,
			agentId: v,
			sessionLoadOptions: {
				...u,
				agentId: v
			},
			accountId: t,
			assertCurrent: () => {
				e.abortSignal?.throwIfAborted();
				if (e.isRunCurrent && !e.isRunCurrent()) throw new Error("Chat media run is no longer current.");
			}
		});
		try {
			const { storePath: t, entry: r } = await f(_, v);
			const a = r?.sessionId ?? s ?? l;
			const { payloads: [u], inputs: p, mediaMessage: S, assistantContent: C, persistedAssistantContent: w, mediaBySource: T } = await prepareWebchatReplyMediaForDisplay({
				scope: x,
				storePath: t,
				inputs: replaceChatSendReplyPayload(n, stripVisibleTextFromTtsSupplement(o)),
				abortSignal: e.abortSignal,
				includeSensitiveMedia: o.sensitiveMedia !== true,
				logGateway: i
			});
			if (!u) return;
			const E = getReplyPayloadMetadata(u)?.assistantMediaFailures ?? [];
			const D = E.length > 0;
			const O = hasAssistantDisplayMediaContent(w) || D ? w : void 0;
			if (!O?.length) return;
			const k = S?.transcriptText ?? extractAssistantDisplayText(C) ?? buildTranscriptReplyTextFromInputs(p);
			const A = getReplyPayloadMetadata(o);
			const j = uniqueStrings(A?.assistantTranscriptMediaUrls?.length ? A.assistantTranscriptMediaUrls : [...Array.isArray(o.mediaUrls) ? o.mediaUrls : [], ...typeof o.mediaUrl === "string" ? [o.mediaUrl] : []]);
			const M = m?.idempotencyKey ?? (A?.assistantTranscriptOwned === true ? A.assistantTranscriptIdempotencyKey?.trim() : void 0);
			const N = assistantTranscriptScope({
				sessionKey: _,
				sessionId: a,
				storePath: t,
				agentId: v
			});
			const P = A?.assistantMessageIndex;
			const F = A?.assistantTranscriptSource?.committedMessageId;
			let I = null;
			if (M && N) {
				if (m && (await f(_, v)).entry?.sessionId !== m.sessionId) {
					i.warn("webchat runtime-owned media skipped: transcript session changed");
					return;
				}
				I = await rewriteAssistantTranscriptMessageByIdempotencyKey({
					content: O,
					mediaBySource: T,
					idempotencyKey: M,
					managedMediaUrls: j,
					scope: N
				});
				if (!I) {
					i.warn("webchat runtime-owned assistant media rewrite skipped: transcript identity not found");
					return;
				}
			} else if (F && N && !y) {
				const t = await rewriteAssistantTranscriptMessageById({
					messageId: F,
					runId: g,
					content: O,
					mediaBySource: T,
					mediaUrls: j,
					expectedLifecycleRevision: h?.lifecycleRevision ?? null,
					scope: N,
					assertCurrent: x.assertCurrent,
					abortSignal: e.abortSignal
				});
				if (!t) {
					i.warn("webchat assistant media rewrite skipped: committed occurrence unavailable");
					return;
				}
				if (h) h.generation = t.generation;
				I = t;
			} else if (P !== void 0 && N) {
				if (h?.sessionId !== a) return;
				const e = await rewriteAssistantTranscriptMessageByTurnIndexAndMedia({
					afterSeq: h.afterSeq,
					assistantMessageIndex: P,
					content: O,
					mediaBySource: T,
					expectedGeneration: h.generation,
					mediaUrls: j,
					rejectedMediaCount: E.filter((e) => e.code === "invalid-reference").length,
					scope: N
				});
				if (e) {
					h.generation = e.generation;
					I = e;
				}
			}
			if (I && N) {
				b.add(d);
				if (C?.length) await attachManagedOutgoingMediaToMessage({
					messageId: I.messageId,
					blocks: C
				});
				await publishAssistantTranscriptRewrite({
					scope: N,
					rewritten: [I]
				});
				return;
			}
			const L = O.some((e) => e.type === "attachment_error") && O.every((e) => e.type === "text" || e.type === "attachment_error");
			const ee = stripReplyMediaFailureFallback(u.text, E)?.trim();
			if (P === void 0 && D && L && ee) return;
			const R = P !== void 0 && P >= 1 && !D && !y && !o.isError && !isReplyPayloadStatusNotice(o) && !A?.toolErrorWarning && !A?.nonTerminalToolErrorWarning && !A?.terminalProviderError;
			const z = R ? O.filter((e) => e.type !== "text") : O;
			const B = await appendInjectedAssistantMessageToTranscript({
				sessionKey: _,
				message: R ? "" : k,
				content: z,
				sessionId: a,
				storePath: t,
				agentId: v,
				idempotencyKey: P !== void 0 && P >= 1 ? `${l}:assistant-media:${P}` : `${l}:assistant-media`,
				ttsSupplement: y,
				config: c,
				onMessageCommitted: retainCommittedChatReplyMedia
			});
			if (B.ok) {
				b.add(d);
				return;
			}
			i.warn(`webchat transcript append failed for media reply: ${B.error ?? "unknown error"}`);
		} finally {
			x.release();
		}
	};
	const deliverInput = async (t, n) => {
		const i = readChatSendReplyPayload(t);
		const a = getReplyPayloadMetadata(i);
		if (a?.beforeAgentRunBlocked === true || a?.sourceReplyTranscriptMirror?.transcriptWriteBlocked === true) o.markBlocked();
		switch (n.kind) {
			case "block":
			case "final":
				y.push({
					input: t,
					kind: n.kind
				});
				if (n.kind === "block" && e.onCommandBlock && !r() && e.isRunCurrent?.()) {
					const t = y.map(({ input: e, kind: t }) => {
						const n = readChatSendReplyPayload(e);
						if (t !== "block" || n.isReasoning === true || isBtwReplyPayload(n)) return "";
						return (e.kind === "prepared" ? prepareAssistantDisplayText : sanitizeAssistantDisplayText)(n.text, { preserveBoundaries: true }) ?? "";
					});
					if (t.at(-1)) e.onCommandBlock(combineNonStreamingReplyParts(t));
				}
				break;
			case "tool": if (isMediaBearingPayload(i)) {
				const e = copyReplyPayloadMetadata(i, {
					...i,
					text: void 0
				});
				y.push(...replaceChatSendReplyPayload(t, e).map((e) => ({
					input: e,
					kind: "final"
				})));
			}
		}
	};
	const S = {
		...v,
		onError: (e) => {
			i.warn(`webchat dispatch failed: ${formatForLog(e)}`);
		},
		deliver: (e, t) => deliverInput({
			kind: "raw",
			payload: e
		}, t),
		deliverPrepared: (e, t) => deliverInput({
			kind: "prepared",
			plan: e
		}, t)
	};
	const finalizeAgentMediaTranscript = async () => {
		const e = /* @__PURE__ */ new Map();
		for (const { input: t } of y) {
			const n = readChatSendReplyPayload(t);
			if (!needsAgentMediaTranscriptFinalization(n)) continue;
			e.set(agentMediaTranscriptKey(n), t);
		}
		for (const t of e.values()) try {
			await appendWebchatAgentMediaTranscriptIfNeeded(t);
		} catch (e) {
			i.warn(`webchat media finalization failed: ${formatForLog(e)}`);
		}
	};
	const runAgentMediaTranscript = async (e, t) => {
		return await e.run(async () => {
			try {
				return await x.run(t);
			} finally {
				const e = x.lastRewrite;
				if (e && h && e.sessionId === h.sessionId) h.generation = e.generation;
				await finalizeAgentMediaTranscript();
			}
		});
	};
	return {
		captureAgentTranscriptStart,
		notePreparedSession: d,
		deliveredReplies: y,
		dispatcherOptions: S,
		hasAppendedWebchatAgentMedia: () => b.size > 0,
		onModelSelected: _,
		prepareAssistantTranscriptMessage: x.prepareAssistantTranscriptMessage,
		resolveReplyDelivery: async (e) => (await resolveReplyDeliveryFacts(e)).terminal,
		resolveReplyDeliveryFacts,
		runAgentMediaTranscript
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-source-finalization.ts
function selectChatSendAgentReplyInputs(e) {
	return e.deliveredReplies.filter((t) => {
		const n = readChatSendReplyPayload(t.input);
		return getReplyPayloadMetadata(n)?.sessionWriterDeliveryAuthority || isSourceReplyTranscriptMirrorPayload(n) ? t.kind === "final" && n.isError !== true : !e.hasReturnedAgentErrorPayloads && isReplyPayloadStatusNotice(n);
	}).map((e) => e.input);
}
function createChatSendLateReplyFinalizer(e) {
	const t = e.terminalEntry ? captureChatAbortRegistrationGuard([{
		runId: e.session.clientRunId,
		entry: e.terminalEntry
	}]) : () => true;
	return async ({ runId: n, clientRunId: r, payloads: i, completion: a, isCurrent: o }) => {
		let s = i;
		const { context: c, session: l } = e;
		const isCurrent = () => o() && (r !== l.clientRunId || t());
		const u = {
			terminalEntry: r === l.clientRunId ? e.terminalEntry : void 0,
			context: c,
			runId: r,
			sessionKey: l.sessionKey,
			agentId: l.agentId
		};
		const d = a.kind !== "progress";
		let f = false;
		try {
			if (!d) {
				const t = s.filter((e) => getReplyPayloadMetadata(e)?.queueAdmissionNotice === "queued");
				if (t.length > 0) {
					const n = await finalizeChatSendAgentReplyPayloads({
						...e,
						terminalEntry: u.terminalEntry,
						emitFirstAssistantServerTiming: () => {},
						inputs: t.map((e) => ({
							kind: "raw",
							payload: e
						})),
						isCurrent,
						session: {
							...l,
							clientRunId: r
						},
						publishMessage: (e) => {
							f = true;
							const t = typeof e?.text === "string" ? e.text : void 0;
							if (t) broadcastChatQueueNotice({
								...u,
								text: t
							});
							return false;
						}
					});
					s = s.filter((e) => getReplyPayloadMetadata(e)?.queueAdmissionNotice !== "queued");
					if (s.length === 0) return n;
				}
			}
			const t = await finalizeChatSendAgentReplyPayloads({
				...e,
				terminalEntry: u.terminalEntry,
				emitFirstAssistantServerTiming: () => {},
				inputs: s.map((e) => ({
					kind: "raw",
					payload: e
				})),
				isCurrent,
				session: {
					...l,
					clientRunId: r
				},
				suppressFinal: a.kind === "failed" || a.kind === "aborted",
				publishMessage: (e, t, n) => {
					f = true;
					if (a.kind === "progress") {
						const i = typeof e?.text === "string" ? e.text : void 0;
						if (i) {
							const e = c.chatRunState.getOrCreate(r);
							e.releaseBufferAuthority?.();
							e.releaseBufferAuthority = n;
							broadcastChatDelta({
								...u,
								text: i,
								isCurrent: () => c.chatRunState.runs.get(r) === e && t()
							});
							return true;
						}
					} else {
						const t = c.chatRunState.runs.get(r);
						const n = t?.bufferIsCurrent?.() === false ? [] : t?.canvasBlocks ?? [];
						broadcastChatTerminal({
							...u,
							state: "final",
							message: appendChatCanvasBlocksToMessage(e ?? (n.length ? {
								role: "assistant",
								content: [],
								timestamp: Date.now()
							} : void 0), n),
							stopReason: a.stopReason
						});
					}
					return false;
				}
			});
			if (!isCurrent()) return {
				kind: "dropped",
				reason: "no-visible-content"
			};
			if (a.kind === "failed" || a.kind === "aborted" || d && t.kind === "dropped") {
				const e = c.chatRunState.resolveBuffer(r, { final: true });
				const t = c.chatRunState.runs.get(r);
				const n = t?.bufferIsCurrent?.() === false ? [] : t?.canvasBlocks ?? [];
				const i = a.kind === "completed" && a.allowCanvasOnly === true && s.length === 0 && n.length > 0 && !(t?.rawBuffer ?? t?.buffer ?? "").trim();
				if (a.kind === "failed" || a.kind === "aborted") c.chatRunState.flushPendingText(r);
				f = true;
				broadcastChatTerminal({
					...u,
					stopReason: a.stopReason,
					...a.kind === "failed" ? {
						state: "error",
						errorMessage: a.error,
						errorKind: a.errorKind
					} : {
						state: a.kind === "aborted" ? "aborted" : "final",
						...a.kind === "aborted" && e.text && !e.suppress || i ? { message: appendChatCanvasBlocksToMessage({
							role: "assistant",
							content: i ? [] : [{
								type: "text",
								text: e.text
							}],
							timestamp: Date.now()
						}, n) } : {}
					}
				});
			}
			return d ? {
				kind: "delivered",
				hasSourceReplyTranscriptMirror: t.kind === "delivered" && t.hasSourceReplyTranscriptMirror
			} : t;
		} catch (e) {
			if (d && !f && isCurrent()) {
				c.chatRunState.flushPendingText(r);
				broadcastChatTerminal({
					...u,
					state: "error",
					errorMessage: formatErrorMessage(e)
				});
			}
			throw e;
		} finally {
			if (d) {
				c.removeChatRun(n, r, l.sessionKey);
				if (isCurrent()) {
					c.chatRunState.clearRun(r);
					c.agentRunSeq.delete(r);
				}
				c.agentRunSeq.delete(n);
			}
		}
	};
}
async function finalizeChatSendAgentReplyPayloads(e) {
	const { context: t, emitFirstAssistantServerTiming: n, session: r } = e;
	const { agentId: i, backingSessionId: a, clientRunId: o, sessionKey: s, sessionLoadOptions: c } = r;
	let l = false;
	const u = e.inputs.flatMap((e) => {
		const t = readChatSendReplyPayload(e);
		const n = getReplyPayloadMetadata(t);
		if (n?.assistantMessageIndex === void 0 && !n?.assistantTranscriptOwned || n?.sessionWriterDeliveryAuthority || isSourceReplyTranscriptMirrorPayload(t) || isHostNoticePayload(t)) return [e];
		l = true;
		return replaceChatSendReplyPayload(e, copyReplyPayloadMetadata(t, {
			...t,
			text: n?.responseUsageLine
		}));
	});
	const d = u.map(readChatSendReplyPayload);
	if (d.length === 0) return {
		kind: "dropped",
		reason: "no-visible-content"
	};
	const { deliveryAuthorized: f, authorizeDelivery: p, captureMediaScope: m, release: h } = await createChatSendReplyFinalizationAuthority(e, d);
	let g = false;
	try {
		const r = d.some(isSourceReplyTranscriptMirrorPayload);
		const _ = await m();
		if (!_) return {
			kind: "dropped",
			reason: "no-visible-content"
		};
		const { storePath: v, entry: y } = await loadGatewaySessionEntryReadOnlyInWorker({
			cfg: t.getRuntimeConfig(),
			key: s,
			...c,
			projection: []
		});
		const b = y?.sessionId ?? a ?? o;
		const x = assistantTranscriptScope({
			sessionId: b,
			sessionKey: s,
			storePath: v,
			agentId: i
		});
		const S = await Promise.all(d.map(async (t) => x ? readCommittedSourceReplyContent({
			scope: x,
			payload: t,
			abortSignal: e.abortSignal,
			assertCurrent: _.assertCurrent
		}) : void 0));
		_.assertCurrent();
		const C = S.some(Boolean);
		const { finalInputsByIndex: w, sourceReplyContentStates: T, sourceReplyBroadcastContent: E } = await withPreparedWebchatReplyMedia({
			scope: _,
			storePath: v,
			inputs: u.filter((e, t) => !S[t]),
			abortSignal: e.abortSignal,
			includeSensitiveMedia: false,
			logGateway: t.logGateway
		}, async ({ payloads: e, inputsByIndex: t, buildContent: n }) => {
			const r = [];
			const i = [];
			let a = 0;
			for (const [o] of d.entries()) {
				const s = S[o];
				if (s) {
					r[o] = {
						broadcastContent: [],
						persistedContent: s,
						hasManagedOutgoingContent: hasManagedOutgoingAssistantContent(s),
						backedManagedOutgoingContent: true
					};
					continue;
				}
				const c = a++;
				if (!e[c]) continue;
				const { persistedAssistantContent: l, broadcastContent: u } = await n(t[c] ?? []);
				const d = {
					broadcastContent: u ?? [],
					persistedContent: l ?? [],
					hasManagedOutgoingContent: hasManagedOutgoingAssistantContent(l),
					backedManagedOutgoingContent: false
				};
				r[o] = d;
				i.push(...d.broadcastContent);
			}
			return {
				finalInputsByIndex: t,
				sourceReplyContentStates: r,
				sourceReplyBroadcastContent: i
			};
		});
		const D = extractAssistantDisplayText(E) ?? buildTranscriptReplyTextFromInputs(w.flat());
		if (!E.length && !D && !C && !l) return {
			kind: "dropped",
			reason: "no-visible-content"
		};
		const O = [];
		const k = [];
		for (const [e, t] of d.entries()) {
			const n = T[e];
			if (!n) continue;
			const r = getReplyPayloadMetadata(t)?.sourceReplyTranscriptMirror;
			const i = r?.idempotencyKey;
			if (typeof i !== "string" || i.trim().length === 0 || !r) continue;
			const a = {
				idempotencyKey: i,
				metadata: r
			};
			k.push(a);
			if (!n.backedManagedOutgoingContent && hasAssistantDisplayMediaContent(n.persistedContent)) {
				if (!n.hasManagedOutgoingContent) n.backedManagedOutgoingContent = true;
				O.push({
					...a,
					state: n
				});
			}
		}
		if (!p("transcript finalization")) return {
			kind: "dropped",
			reason: "no-visible-content"
		};
		if (x && O.length > 0) {
			const e = await rewriteSourceReplyTranscriptMirrors({
				candidates: k,
				requests: O,
				scope: x
			});
			if (e.length > 0) {
				for (const t of e) {
					const e = t.request.state;
					if (e.hasManagedOutgoingContent) await attachManagedOutgoingMediaToMessage({
						messageId: t.messageId,
						blocks: e.persistedContent
					});
					e.backedManagedOutgoingContent = true;
				}
				await publishAssistantTranscriptRewrite({
					scope: x,
					rewritten: e
				});
			}
		}
		const A = T.flatMap((e) => {
			if (e.hasManagedOutgoingContent && !e.backedManagedOutgoingContent) return stripManagedOutgoingAssistantContentBlocks(e.broadcastContent) ?? [{
				type: "text",
				text: "Media reply could not be displayed."
			}];
			return e.broadcastContent;
		});
		const j = extractAssistantDisplayText(A) ?? (A.length === 0 ? D : void 0);
		const M = A.length || j ? {
			role: "assistant",
			content: A.length ? A : [{
				type: "text",
				text: j
			}],
			...j ? { text: j } : {},
			timestamp: Date.now(),
			stopReason: "stop",
			usage: {
				input: 0,
				output: 0,
				totalTokens: 0
			}
		} : void 0;
		if (!e.suppressFinal) {
			if (!p("broadcast")) return {
				kind: "dropped",
				reason: "no-visible-content"
			};
			if (hasVisibleAssistantFinalMessage(M)) n();
			if (e.publishMessage) g = e.publishMessage(M, f, h);
			else if (M) broadcastChatFinal({
				terminalEntry: e.terminalEntry,
				context: t,
				runId: o,
				sessionKey: s,
				agentId: i,
				message: M
			});
		}
		return {
			kind: "delivered",
			hasSourceReplyTranscriptMirror: r
		};
	} catch (e) {
		if (!p("reply finalization")) return {
			kind: "dropped",
			reason: "no-visible-content"
		};
		throw e;
	} finally {
		if (!g) h();
	}
}
/** Persist and broadcast agent-run source/status replies that bypass the normal model turn. */
async function finalizeChatSendSourceReplies(e) {
	const t = await finalizeChatSendAgentReplyPayloads({
		...e,
		inputs: selectChatSendAgentReplyInputs(e)
	});
	return t.kind === "delivered" && t.hasSourceReplyTranscriptMirror;
}
//#endregion
//#region src/gateway/server-methods/chat-send-tool-event-recipients.ts
function registerChatSendToolEventRecipients(e, t) {
	const { client: n, context: r, cfg: i, sessionKey: a, selectedAgent: o, storePath: s } = e;
	const c = resolveAgentTurnRunObserver({
		principal: n,
		registerToolEventRecipient: r.registerToolEventRecipient
	});
	if (c) {
		c(t);
		const e = tryResolveSessionCompatibilityOwnerAgentId(i, a);
		const n = captureRpcSourceScopeMatcher({
			storePath: s,
			resolveGatewayContext: r.resolveGatewayContext
		});
		for (const [r, i] of listRpcSourceEntries()) {
			const s = getRpcSourceIdentity(i);
			const l = o.agentId !== void 0 && chatRunBelongsToSelectedAgent({
				agentId: s.agentId,
				sessionKey: s.sessionKey,
				defaultAgentId: e,
				selectedAgentId: o.agentId
			});
			const u = s.sessionKey === a && l;
			if (r !== t && u && n(i) && isRpcSourceActive(i)) c(r);
		}
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-late-followup.ts
/** One Gateway admission owns the outcome of its queued reply, including concurrent duplicates. */
function createChatSendLateFollowupDisposition(e) {
	let t = "pending";
	const n = [];
	const recordDrop = (n, r, i = true) => {
		if (i && n.completion.kind !== "progress") {
			t = "settled";
			if (r === "non-webchat-origin" || r === "origin-mismatch") e.onTerminalDrop?.(n.completion);
		}
		e.logGateway.info("webchat late reply disposition", {
			runId: e.runId,
			followupRunId: n.runId,
			outcome: "late-and-dropped",
			reason: r
		});
	};
	return {
		recordQueued: () => {
			if (t === "pending") t = isInternalMessageChannel(e.originatingChannel) ? "deliver" : "drop";
		},
		deliver: Object.assign(async (r) => {
			if (t === "delivering") return recordDrop(r, "delivery-in-flight", false);
			if (t !== "deliver") return recordDrop(r, t === "pending" ? "terminal-not-recorded" : t === "drop" ? "non-webchat-origin" : "already-settled");
			if (!isInternalMessageChannel(r.originatingChannel)) return recordDrop(r, "origin-mismatch");
			if (r.completion.kind === "progress") {
				n.push(...r.payloads.filter((e) => getReplyPayloadMetadata(e)?.queueAdmissionNotice !== "queued"));
				await e.deliver({
					...r,
					clientRunId: e.retainSourceIdentity === false ? r.runId : e.runId,
					isCurrent: () => t === "deliver"
				});
				return;
			}
			t = "delivering";
			try {
				const i = await e.deliver({
					...r,
					clientRunId: e.retainSourceIdentity === false ? r.runId : e.runId,
					payloads: [...n, ...r.payloads],
					isCurrent: () => t === "delivering"
				});
				if (i.kind === "dropped") return recordDrop(r, i.reason);
				t = "settled";
			} catch (e) {
				recordDrop(r, "delivery-failed");
				throw e;
			} finally {
				n.length = 0;
			}
		}, {
			ownsCompletion: (e) => t === "deliver" && isInternalMessageChannel(e),
			createSourceRetry: () => {
				if (t === "delivering" || t === "settled") throw new Error("Queued source reply no longer owns recovery delivery");
				if (t === "pending") t = "settled";
				const n = createChatSendLateFollowupDisposition({
					...e,
					retainSourceIdentity: false,
					onTerminalDrop: void 0
				});
				n.recordQueued();
				return n.deliver;
			}
		})
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-turn-adoption.ts
function createChatSendTurnAdoptionLifecycle(e) {
	let t = false;
	let n = false;
	const r = captureChatAbortRegistrationGuard([{
		runId: e.runId,
		entry: e.sourceRef
	}]);
	let i = false;
	let a;
	const recordQueuedTerminal = (n, i = false) => {
		if (t || !r()) return;
		const a = e.context.chatRunState.runs.get(e.runId);
		t = true;
		markChatAbortTerminalOutcome(e.sourceRef);
		const o = Date.now();
		const s = n.kind === "failed";
		try {
			setGatewayDedupeEntry({
				dedupe: e.context.dedupe,
				key: `chat:${e.runId}`,
				session: captureAgentJobSession({
					...getRpcSourceIdentity(e.sourceRef),
					lifecycleGeneration: getRpcSourceLifecycleGeneration(e.sourceRef)
				}),
				entry: {
					ts: o,
					ok: !s,
					payload: n.kind === "aborted" ? buildAbortedChatSendPayload({
						runId: e.runId,
						endedAt: o,
						stopReason: n.stopReason
					}) : {
						runId: e.runId,
						status: s ? n.errorKind ?? "error" : "completed",
						endedAt: o,
						stopReason: n.stopReason,
						...s ? { summary: n.error } : {}
					}
				}
			});
			if (i && !e.suppressReplies) broadcastChatTerminal({
				terminalEntry: e.sourceRef,
				context: e.context,
				runId: e.runId,
				sessionKey: e.sessionKey,
				agentId: e.agentId,
				stopReason: n.stopReason,
				...s ? {
					state: "error",
					errorMessage: n.error,
					errorKind: n.errorKind
				} : { state: n.kind === "aborted" ? "aborted" : "final" }
			});
		} finally {
			if (r() && e.context.chatRunState.runs.get(e.runId) === a) e.context.chatRunState.clearRun(e.runId);
		}
	};
	const recordQueuedAbort = (t) => recordQueuedTerminal({
		kind: "aborted",
		stopReason: e.sourceRef.adapter.abortStopReason ?? resolveAgentRunAbortLifecycleFields(e.controller.signal).stopReason
	}, t);
	const o = e.suppressReplies ? void 0 : createChatSendLateReplyFinalizer({
		terminalEntry: e.sourceRef,
		requesterContext: e.requesterContext,
		abortSignal: e.controller.signal,
		accountId: e.accountId,
		context: e.context,
		session: e.session
	});
	const s = createChatSendLateFollowupDisposition({
		runId: e.runId,
		originatingChannel: e.originatingChannel,
		logGateway: e.context.logGateway,
		onTerminalDrop: (e) => recordQueuedTerminal(e, true),
		deliver: async (n) => {
			if (n.clientRunId === e.runId && n.completion.kind !== "progress" && n.isCurrent() && r()) markChatAbortTerminalOutcome(e.sourceRef);
			try {
				const i = o ? await o({
					...n,
					isCurrent: () => n.isCurrent() && r() && (n.clientRunId !== e.runId || !t)
				}) : {
					kind: "dropped",
					reason: "no-visible-content"
				};
				if (n.clientRunId === e.runId && n.completion.kind !== "progress") recordQueuedTerminal(n.completion);
				return i;
			} catch (t) {
				if (n.clientRunId === e.runId && n.completion.kind !== "progress") recordQueuedTerminal({
					kind: "failed",
					error: String(t)
				});
				throw t;
			}
		}
	});
	const c = e.sourceRef.adapter.cancel?.bind(e.sourceRef.adapter);
	e.sourceRef.adapter.cancel = (t) => {
		c?.(t);
		if (e.sourceRef.input.custody.enqueued && !e.sourceRef.input.custody.adopted) recordQueuedAbort(e.sourceRef.adapter.projectSessionTerminalPending !== true);
	};
	const l = {
		admission: "cancel-only",
		abortSignal: e.sourceRef.input.abortSignal,
		...e.originatingLeafEntryId !== void 0 ? { originatingLeafEntryId: e.originatingLeafEntryId } : {},
		ownerKey: e.ownerKey,
		onAdopted: () => {
			e.sourceRef.input.abortSignal.throwIfAborted();
		},
		onDeferred: () => {
			if (e.hasCronCreatorAuthority) l.cronCreatorAuthorityUnavailable = "queued-local-operator";
			const t = e.sourceRef.input;
			if (!isRpcSourceRegistered(e.sourceRef) || t.abortSignal.aborted || t.phase === "consumed") return false;
			a ??= e.retainWorkAdmission();
			setGatewayDedupeEntry({
				dedupe: e.context.dedupe,
				key: `chat:${e.runId}`,
				session: captureAgentJobSession({
					...getRpcSourceIdentity(e.sourceRef),
					lifecycleGeneration: getRpcSourceLifecycleGeneration(e.sourceRef)
				}),
				entry: {
					ts: Date.now(),
					ok: true,
					payload: {
						runId: e.runId,
						status: "accepted"
					}
				}
			});
			s.recordQueued();
			e.armOperatorRunCancellation?.();
			return true;
		},
		onCancellationRetired: () => {
			retireSessionControllerSourceCancellation(e.sourceRef.input);
			e.retireOperatorRunCancellation?.();
		},
		onAbandoned: () => {
			if (!e.sourceRef.input.custody.enqueued) return;
			recordQueuedTerminal({
				kind: "aborted",
				stopReason: "aborted"
			}, e.sourceRef.adapter.projectSessionTerminalPending !== true);
		},
		onSettled: () => {
			if (i) return;
			i = true;
			try {
				if (!e.sourceRef.input.custody.enqueued || !r()) return;
				e.retireOperatorRunCancellation?.();
				if (!t && e.controller.signal.aborted) recordQueuedAbort(e.sourceRef.adapter.projectSessionTerminalPending !== true);
				if (!t) n = true;
			} finally {
				a?.();
				a = void 0;
			}
		}
	};
	bindReplySourceInput(l, e.sourceRef.input);
	const u = e.sourceRef.adapter.onSettled?.bind(e.sourceRef.adapter);
	e.sourceRef.adapter.onSettled = async () => {
		try {
			await l.onSettled?.();
		} finally {
			await u?.();
		}
	};
	return {
		lifecycle: l,
		isEnqueued: () => !n && e.sourceRef.input.custody.enqueued === true,
		isTerminal: () => t,
		isSteered: () => n,
		onRunStarted: (n) => {
			if (e.sourceRef.input.custody.enqueued && !t && r() && s.deliver.ownsCompletion(e.originatingChannel)) e.context.addChatRun(n, {
				sessionKey: e.sessionKey,
				agentId: e.agentId,
				clientRunId: e.runId
			});
		},
		onQueueDisposition: (t) => {
			recordQueuedTerminal({
				kind: "failed",
				error: `Queued input was dropped (${t}).`
			}, true);
			e.context.logGateway.info("chat queue turn intentionally skipped", {
				runId: e.runId,
				sessionKey: e.sessionKey,
				outcome: "skipped",
				reason: t
			});
		},
		onQueuedFollowupReplyBatch: Object.assign(async (e) => {
			if (!t && r()) await s.deliver(e);
		}, s.deliver)
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-user-turn.ts
const audioPreflightLoader = createLazyImportLoader(() => import("./audio-preflight-B2vRcXb3.mjs"));
async function resolveChatUiTranscriptEcho(e) {
	const t = e.cfg?.tools?.media?.audio;
	const n = isWebchatClient(e.clientInfo) || isOperatorUiClient(e.clientInfo) || e.clientInfo?.id === GATEWAY_CLIENT_IDS.MACOS_APP || e.clientInfo?.id === GATEWAY_CLIENT_IDS.IOS_APP || e.clientInfo?.id === GATEWAY_CLIENT_IDS.ANDROID_APP;
	const r = t?.echoFormat ?? "📝 \"{transcript}\"";
	if (!n || !t?.echoTranscript || !r.includes("{transcript}") || !e.ctx.media?.length) return;
	e.assertCurrent();
	const i = await audioPreflightLoader.load().then(({ transcribeAudioAttachments: n }) => n({
		ctx: e.ctx,
		...e.cfg ? {
			agentDir: resolveAgentDir(e.cfg, e.agentId),
			workspaceDir: resolveAgentWorkspaceDir(e.cfg, e.agentId)
		} : {},
		cfg: {
			...e.cfg,
			tools: {
				...e.cfg?.tools,
				media: {
					...e.cfg?.tools?.media,
					audio: {
						...t,
						echoTranscript: false
					}
				}
			}
		},
		assertCurrent: e.assertCurrent
	})).catch(() => void 0);
	e.assertCurrent();
	if (!i) return;
	e.ctx.Transcript = i;
	return r.replace("{transcript}", () => i);
}
function applyChatSendManagedMedia(e, t, n = "replace-empty") {
	if (t.length === 0) return;
	if (n === "replace-empty") {
		if (!e.media || e.media.length === 0) e.media = t;
		return;
	}
	const r = e.media ?? [];
	const i = new Set(r.flatMap((e) => e.path ? [e.path] : []));
	const a = t.filter((e) => !e.path || !i.has(e.path));
	if (a.length > 0) e.media = [...r, ...a];
}
function buildChatSendPromptMedia(e) {
	if (!e.imageOrder.includes("offloaded")) return;
	const t = e.offloadedRefs.filter((e) => e.mimeType.startsWith("image/")).map((e) => ({
		path: e.path,
		url: e.mediaRef,
		contentType: e.mimeType
	}));
	return t.length > 0 ? t : void 0;
}
/** Assemble transcript media and the portable inbound context after attachment preparation. */
function prepareChatSendUserTurn(e) {
	const { request: t, session: n, admission: r, attachments: i, client: a, logGateway: o, userTurn: s } = e;
	const c = (async () => {
		if (i.parsedImages.length === 0 && i.offloadedRefs.length === 0) return {
			entries: [],
			omission: "none"
		};
		return await persistInboundImagesForTranscript({
			images: i.parsedImages,
			offloadedRefs: i.offloadedRefs,
			log: o,
			logContext: "chat.send",
			assertCurrent: () => {
				r.assertWorkAdmissionCurrent?.();
				r.assertClientUploadAllowed?.();
			}
		});
	})();
	const l = c.then((e) => {
		const t = e.entries.filter((e) => i.explicitOriginTargetsPlugin || e.imageKind === "inline" || e.imageKind === "offloaded" && !i.mediaPathOffloads.some((e) => e.contentType?.startsWith("image/")));
		const n = !i.explicitOriginTargetsPlugin;
		return t.map((e) => Object.assign({
			path: e.path,
			contentType: e.fact.contentType ?? "application/octet-stream"
		}, e.fact.fileName ? { fileName: e.fact.fileName } : {}, n && (e.imageKind === "inline" || e.imageKind === "offloaded") ? { hydrationSuppressed: true } : {}));
	});
	l.catch(() => void 0);
	const u = t.inboundMessage;
	const d = !t.suppressCommandInterpretation && u.trim().startsWith("/") ? "text" : void 0;
	const buildTextContext = (e) => {
		const n = e === t.inboundMessage ? i.parsedMessage : `${e}${i.parsedMessage.slice(t.inboundMessage.length)}`;
		const r = t.systemProvenanceReceipt ? [t.systemProvenanceReceipt, n].filter(Boolean).join("\n\n") : n;
		return {
			Body: r,
			BodyForAgent: r,
			BodyForCommands: e,
			RawBody: n,
			CommandBody: e
		};
	};
	const f = normalizeOptionalString(a?.connect?.device?.id);
	const p = normalizeOptionalString(a?.connId);
	const m = captureGatewayUiCommandTarget(a);
	const h = f ? `device:${f}` : p ? `connection:${p}` : void 0;
	const { originatingChannel: g, originatingTo: _, accountId: v, messageThreadId: y, explicitDeliverRoute: b } = r.originatingRoute;
	const x = resolveOperatorSessionCreation(a);
	r.assertWorkAdmissionCurrent?.();
	const S = n.cfg ? resolveCreatorSandbox(n.cfg, x) : void 0;
	const C = {
		...buildTextContext(u),
		InputProvenance: t.systemInputProvenance,
		...isProgressCardRefreshInputProvenance(t.systemInputProvenance) ? { InternalTurnSource: "progress-card-refresh" } : {},
		SessionKey: n.sessionKey,
		AgentId: n.agentId,
		OriginatingTo: _,
		ExplicitDeliverRoute: b,
		AccountId: v,
		MessageThreadId: y,
		...d ? { CommandSource: d } : {},
		CommandAuthorized: !t.suppressCommandInterpretation,
		CommandTurn: d ? {
			kind: "text-slash",
			source: d,
			authorized: true,
			body: u
		} : {
			kind: "normal",
			source: "message",
			authorized: false,
			body: u
		},
		...t.suppressCommandInterpretation ? { CommandInterpretationSuppressed: true } : {},
		MessageSid: n.clientRunId,
		SessionCreation: {
			...x,
			...S ? { sandbox: S } : {}
		},
		...resolveChatSendCallerContext(a, t.clientInfo, g),
		GatewayRunToolBindings: t.toolBindings,
		GatewayUiCommandTarget: m
	};
	const w = readQueuedChatInputAdmission(n.clientRunId)?.requesterProfile;
	const T = a?.authenticatedUserProfile;
	const E = !t.systemInputProvenance || t.systemInputProvenance.kind === "external_user";
	if (w && E) bindRequesterProfile(C, {
		...w,
		isCurrent: () => {
			try {
				r.assertWorkAdmissionCurrent?.();
				return w.isCurrent();
			} catch {
				return false;
			}
		}
	});
	else if (a && T && (a.authenticatedUserId || a.internal?.authenticatedOperator) && isBrowserOperatorUiClient(t.clientInfo) && !isSyntheticGatewayCaller(a) && E) {
		const e = a.authenticatedUserId;
		const { profileId: t, displayName: n } = T;
		bindRequesterProfile(C, {
			id: t,
			displayName: n,
			isCurrent: () => {
				try {
					r.assertWorkAdmissionCurrent?.();
				} catch {
					return false;
				}
				return !a.invalidated && !a.connectionSignal?.aborted && !isSyntheticGatewayCaller(a) && Boolean(a.authenticatedUserId || a.internal?.authenticatedOperator) && a.authenticatedUserId === e && a.authenticatedUserProfile?.profileId === t;
			}
		});
	}
	if (a) transferGatewayLocalUserIngress(a, C);
	if (i.mediaPathOffloads.length > 0) C.media = i.mediaPathOffloads;
	const D = i.mediaPathOffloads.some((e) => e.contentType?.startsWith("image/"));
	let O;
	let k;
	let A = false;
	s.setInputPromise(c.then(async (i) => {
		A = i.omission === "inline-image-save-failed";
		const a = i.entries.map((e) => e.fact);
		const o = i.entries.flatMap((e, t) => e.imageKind ? [{
			kind: e.imageKind,
			factIndex: t
		}] : []);
		const c = e.assertInputCurrent ?? (() => {
			r.assertWorkAdmissionCurrent?.();
			r.assertClientUploadAllowed?.();
		});
		const l = await resolveChatUiTranscriptEcho({
			clientInfo: t.clientInfo,
			agentId: n.agentId,
			cfg: n.cfg,
			ctx: C,
			assertCurrent: c
		});
		if (l !== void 0 && C.Transcript) {
			O = l;
			k = formatAudioTranscriptForAgent(C.Transcript);
		}
		return {
			...s.baseInput,
			...l ? { text: [s.baseInput.text, l].filter(Boolean).join("\n") } : {},
			...i.omission === "inline-image-save-failed" ? { text: [
				s.baseInput.text,
				l,
				INLINE_IMAGE_DURABLE_OMISSION_MARKER
			].filter(Boolean).join("\n") } : {},
			...a.length > 0 ? { media: a } : {},
			...o.length > 0 ? { mediaImageLayout: { slots: o } } : {}
		};
	}));
	const j = w && E && w.isCurrent() ? {
		type: "profile",
		id: w.id
	} : resolveGatewayInputParticipant(a, t.systemInputProvenance);
	if (j) prepareSessionParticipantInput(C, j, s.baseInput.timestamp);
	return {
		prepareSessionCreation: async (i) => {
			if (!t.systemInputProvenance) {
				const t = await prepareSkillLibrarySessionCreation(a, e.getConfig ?? n.cfg ?? {}, x, i);
				r.assertWorkAdmissionCurrent?.();
				C.SessionCreation = {
					...t,
					...S ? { sandbox: S } : {}
				};
			}
		},
		applyApprovedText: (e) => {
			if (e === t.inboundMessage.trim() && !k) return;
			Object.assign(C, buildTextContext(e));
			let n = e;
			if (k) {
				const t = A && e.endsWith("\n" + "[image attachment omitted: durable managed media claim unavailable]") ? INLINE_IMAGE_DURABLE_OMISSION_MARKER : void 0;
				const r = t ? e.slice(0, -(t.length + 1)) : e;
				const i = O !== void 0 && (r === O || r.endsWith("\n" + O));
				n = i && O !== void 0 ? r === O ? "" : r.slice(0, -(O.length + 1)) : r;
				const a = buildTextContext(n);
				C.agentText = [
					a.BodyForAgent,
					i ? k : void 0,
					t
				].filter(Boolean).join("\n");
				C.BodyForAgent = C.agentText;
				if (!i) C.Transcript = void 0;
				C.BodyForCommands = a.BodyForCommands;
				C.CommandBody = a.CommandBody;
				C.RawBody = a.RawBody;
			}
			if (C.CommandTurn) C.CommandTurn = {
				...C.CommandTurn,
				body: n
			};
		},
		discardUnreferencedMedia: async (e) => {
			if (!e) return;
			const t = new Set((readPersistedMediaFacts(e) ?? []).flatMap((e) => [e.url, e.path]));
			const n = await c;
			await discardPreparedInboundMedia(n.entries.filter((e) => !t.has(e.fact.url) && !t.has(e.path)), o);
		},
		accountId: v,
		ctx: C,
		isInternalTextSlashCommandTurn: d === "text",
		queuedFollowupOwnerKey: h,
		pluginBoundMediaPromise: l,
		managedMediaApplyMode: i.explicitOriginTargetsPlugin ? "replace-empty" : "append-missing",
		replyOptionImages: D ? void 0 : i.parsedImages.length > 0 ? i.parsedImages : void 0,
		replyOptionMedia: buildChatSendPromptMedia(i)
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-agent-dispatch.ts
function startChatDispatch(e) {
	const { diagnostics: t, admissionStartedAt: n, admission: r, attachments: i, client: a, context: o, toolsAllow: s, skillLibrary: c, cronCreatorAuthority: l, assertDashboardReadCurrent: u, externalAuthorityAdmission: d, injection: f, request: p, session: m, turn: h, userTurn: g } = e;
	const { imageOrder: _ } = i;
	const v = isProgressCardRefreshInputProvenance(p.systemInputProvenance);
	const { activeRunAbort: y, admittedSessionId: b, chatSendTraceAttributes: x, gatewayWorkAdmission: S, messageInjectionTarget: C, retainGatewayWorkAdmission: w } = r;
	const { agentId: T, cfg: E, clientRunId: D, expectedLeafEntryId: O, storePath: k, selectedAgent: A, sessionKey: j } = m;
	let { entry: M } = m;
	const { p: N, supportsTaskSuggestions: P } = p;
	const { accountId: F, ctx: I, isInternalTextSlashCommandTurn: L, managedMediaApplyMode: ee, pluginBoundMediaPromise: R, queuedFollowupOwnerKey: z, replyOptionImages: B, replyOptionMedia: V } = h;
	const { persist: te, persistBestEffort: ne, recorder: H } = g;
	const { beginCapturedMessageInjection: U, replyContextFieldsPromise: re } = f;
	let W;
	const ie = createDeferredCore();
	let G = false;
	let K;
	const isRunCurrent = () => !y.controller.signal.aborted && isRpcSourceRegistered(y.entry);
	const q = createChatSendReplyDispatch({
		getRuntimeConfig: o.getRuntimeConfig,
		assertWorkCurrent: r.assertWorkAdmissionCurrent,
		requesterContext: I,
		accountId: F,
		prepareAssistantTranscriptMessage: e.prepareAssistantTranscriptMessage,
		isAgentRunStarted: () => G,
		isRunCurrent,
		abortSignal: y.controller.signal,
		onCommandBlock: L ? (e) => broadcastChatDelta({
			context: o,
			runId: D,
			sessionKey: j,
			agentId: T,
			text: e,
			isCurrent: isRunCurrent
		}) : void 0,
		getReplyDispatchRun: () => K,
		logGateway: o.logGateway,
		session: m,
		userTurnRecorder: H
	});
	const J = createChatSendTurnAdoptionLifecycle({
		requesterContext: I,
		accountId: F,
		sourceRef: r.sourceRef,
		context: o,
		runId: D,
		controller: y.controller,
		sessionKey: j,
		agentId: A.agentId,
		ownerKey: z,
		...O !== void 0 ? { originatingLeafEntryId: O } : {},
		originatingChannel: r.originatingRoute.originatingChannel,
		session: m,
		hasCronCreatorAuthority: l !== void 0,
		suppressReplies: v,
		releaseSourceWorkAdmission: r.releaseSourceWorkAdmission,
		retainWorkAdmission: w,
		armOperatorRunCancellation: r.armOperatorRunCancellation,
		retireOperatorRunCancellation: r.retireOperatorRunCancellation
	});
	const Y = createChatSendInjectionDisposition({
		controllerInput: r.sourceRef.input,
		operatorAuthority: r.operatorAuthority,
		turnAdoptionLifecycle: J.lifecycle,
		userTurnTranscriptRecorder: H
	}, E.messages?.queue);
	let X = false;
	const ae = {
		isSteered: () => X || J.isSteered(),
		isEnqueued: J.isEnqueued,
		isTerminal: J.isTerminal
	};
	const Z = createChatSendDispatchErrorLifecycle({
		admission: r,
		hasObservedSideEffects: () => X || W !== void 0 || q.deliveredReplies.length > 0,
		injectionDisposition: Y,
		context: o,
		isAgentRunStarted: () => G,
		isQueuedFollowupEnqueued: () => J.isEnqueued() || J.isTerminal(),
		persistUserTurnTranscript: te,
		session: m,
		userTurnRecorder: H,
		isReplyDispatchRun: () => K !== void 0
	});
	const oe = createAcceptedChatSendRetry({
		classify: Z.classifyFailure,
		waitForRetry: (e) => waitForAcceptedChatSendRetry({
			agentId: T,
			sessionKey: j,
			storePath: k
		}, e, y.controller.signal)
	});
	bindReplySourcePreparationRetry(r.sourceRef.input, oe);
	const { emit: Q, emitFirstAssistant: se, dispatchStartedAtMs: ce } = createOperatorChatSendServerTiming(e);
	Q("dispatch-started");
	const le = { run: (e) => S.run(async () => {
		try {
			var n = _usingCtx();
			$?.mark("replyContext");
			if (re) applyChatSendReplyContextFields(I, await re);
			$?.mark("runAdmission");
			const r = n.u(t.scope("detail.run_admission.steer_prepare"));
			W = await withCurrentUserTurnInput(H, U);
			r?.mark("detail.run_admission.steer_settlement");
			X = await settleChatSendMessageInjection(W);
			W = await Y.observe(W);
			r?.finish();
			return await (X ? e() : withCurrentUserTurnInput(H, e));
		} catch (e) {
			n.e = e;
		} finally {
			n.d();
		}
	}) };
	const ue = u ? {
		agentId: T,
		runId: D,
		sessionKey: j,
		get sessionId() {
			return getRpcSourceIdentity(r.sourceRef).sessionId;
		},
		assertCurrent: u
	} : void 0;
	const $ = t.scope("dispatch");
	scheduleChatDashboardSessionTitle({
		admittedSessionId: b,
		agentId: T,
		cfg: E,
		context: o,
		request: p,
		sessionKey: j,
		storePath: k
	}, ie.promise);
	const de = q.runAgentMediaTranscript(le, () => measureDiagnosticsTimelineSpan("gateway.chat_send.dispatch_inbound", async () => {
		if (!X) r.assertWorkAdmissionCurrent();
		let i;
		if (!X && M && (Object.hasOwn(M, "pendingProjectGitUrl") || M.pendingWorktree)) {
			$?.mark("worktree");
			m.entry = M = { ...M };
			i = prepareSessionWorkspace({
				admission: r,
				client: a,
				context: o,
				session: m
			});
			await i.promptReady;
			i.assertCurrent();
		}
		const u = i?.assertCurrent;
		if (W) try {
			var f = _usingCtx();
			f.u(t.scope("detail.run_admission.steer_finalize"));
			const e = await finalizeAcceptedChatSendMessageInjection({
				attempt: W,
				sourceRef: r.sourceRef,
				context: o,
				ctx: I,
				persistUserTurnTranscriptBestEffort: ne,
				session: m,
				startedAt: n,
				target: C
			});
			u?.();
			if (e) {
				X = true;
				return {
					queuedFinal: false,
					counts: {
						tool: 0,
						block: 0,
						final: 0
					}
				};
			}
		} catch (e) {
			f.e = e;
		} finally {
			f.d();
		}
		$?.mark("preparation");
		const g = await prepareGatewaySkillLibraryTurn(c, h.prepareSessionCreation, () => $?.mark("authoring"));
		r.assertWorkAdmissionCurrent();
		$?.mark("preparation");
		const v = await R;
		u?.();
		applyChatSendManagedMedia(I, v, ee);
		$?.mark("replyInitialization");
		const onAgentRunStart = (e, n, i, s) => {
			J.onRunStarted(e);
			t.finish();
			K = i;
			if (y.markExecutionStarted()) r.armOperatorRunCancellation();
			G = true;
			q.captureAgentTranscriptStart(e, s);
			Q("agent-run-started", e !== D ? { agentRunId: e } : void 0, ce);
			registerChatSendToolEventRecipients({
				client: a,
				context: o,
				cfg: E,
				sessionKey: j,
				selectedAgent: A,
				storePath: k
			}, e);
			return i?.completionSource;
		};
		const dispatchInbound = () => {
			u?.();
			return dispatchInboundMessageWithProjectedDispatcher({
				ctx: I,
				cfg: E,
				toolsAllow: s,
				dispatcherOptions: q.dispatcherOptions,
				onSessionMetadataChanges: (e) => e.forEach((e) => emitSessionsChanged(o, e)),
				replyOptions: bindReplySourceInput({
					[REPLY_OPERATION_RUN_STATE]: Y.runState,
					prepareAssistantTranscriptMessage: q.prepareAssistantTranscriptMessage,
					...isInternalSourceReplyChannel(I) ? {
						resolveReplyDelivery: q.resolveReplyDelivery,
						resolveReplyDeliveryFacts: q.resolveReplyDeliveryFacts
					} : {},
					...r.admittedSessionSettings ? { admittedSessionSettings: r.admittedSessionSettings } : {},
					runId: D,
					operatorAuthority: r.operatorAuthority,
					providerReviewAcknowledgment: p.providerReviewAcknowledgment,
					dashboardReadAdmission: ue,
					skillLibraryAuthoring: g,
					...l ? { cronCreatorAuthorityCapability: l } : {},
					...P ? { taskSuggestionDeliveryMode: "gateway" } : {},
					expectedActiveReplyOperation: r.expectedActiveReplyOperation,
					...e.getSessionInitializationOptions(),
					onSessionPrepared: (e) => {
						$?.mark("preparation");
						r.onSessionPrepared(e);
						q.notePreparedSession(e);
						trackSessionControllerSourceWork(r.sourceRef.input, recordSessionOperatorSource({
							agentId: T,
							sessionKey: j,
							storePath: e.storePath ?? k,
							authority: r.operatorAuthority,
							assertCurrent: r.assertWorkAdmissionCurrent,
							log: o.logGateway
						}));
					},
					onTranscriptStartPreparation: () => t.scope("snapshot")?.finish,
					abortSignal: y.controller.signal,
					getProviderLoginConfig: o.getRuntimeConfig,
					assertProviderLoginAuthority: () => {
						a?.connectionSignal?.throwIfAborted();
						if (a?.invalidated || !a?.connect.scopes?.includes("operator.admin")) throw new Error("Provider login authority is no longer active.");
					},
					onFollowupQueueDisposition: J.onQueueDisposition,
					onQueuedFollowupReplyBatch: J.onQueuedFollowupReplyBatch,
					turnAdoptionLifecycle: J.lifecycle,
					images: B,
					imageOrder: _.length > 0 ? _ : void 0,
					media: V,
					...N.timeoutMs !== void 0 ? { timeoutOverrideMs: N.timeoutMs } : {},
					thinkingLevelOverride: N.thinking,
					normalizeThinkingLevelOverride: p.normalizeThinkingLevelOverride,
					fastModeOverride: N.fastMode,
					queueModeOverride: N.queueMode,
					userTurnTranscriptRecorder: H,
					...Y.isCollaborationBlocked() ? { messageInjectionDisposition: "collaborative-steering-disabled" } : N.queueMode === "steer" && C ? { messageInjectionDisposition: "rejected" } : {},
					fastModeAutoOnSecondsOverride: N.fastAutoOnSeconds,
					onAgentRunStart,
					onPreparedAgentRunStart: ({ runId: e, executionIdentityToken: t, options: n, transcriptStart: r }) => onAgentRunStart(e, t, n, r),
					onModelSelected: (e) => {
						updateChatRunProvider({
							runId: D,
							resolveGatewayContext: o.resolveGatewayContext,
							providerId: e.provider,
							authProviderId: resolveProviderIdForAuth(e.provider, { config: E })
						});
						q.onModelSelected(e);
						Q("model-selected", {
							provider: e.provider,
							model: e.model
						}, ce);
					}
				}, r.sourceRef.input)
			});
		};
		const dispatchWithRetry = () => withExecRequestTurn({
			identity: {
				runId: D,
				...getRpcSourceIdentity(r.sourceRef),
				ownerConnId: r.sourceRef.adapter.requester?.connectionId,
				ownerDeviceId: r.sourceRef.adapter.requester?.deviceId,
				initiatingPersonalOperator: r.sourceRef.adapter.initiatingPersonalOperator,
				controlUiVisible: r.sourceRef.adapter.controlUiVisible,
				turnKind: r.sourceRef.adapter.turnKind
			},
			abortSignal: y.controller.signal
		}, () => oe(() => withDiagnosticsTimelineObserver(t.observeSpan, () => withCurrentUserTurnInput(H, dispatchInbound))));
		const runDispatch = () => l && d ? d.run(l, dispatchWithRetry, y.controller.signal) : dispatchWithRetry();
		const b = await runWithAgentWorkspaceReadiness(i, async () => {
			try {
				return await runDispatch();
			} finally {
				await i?.waitUntilReady();
			}
		});
		if (b.beforeAgentRunBlocked === true) H.markBlocked();
		return b;
	}, {
		phase: "agent-turn",
		config: E,
		attributes: x
	})).then(async (e) => {
		t.finish(ae);
		if (e.deferredToActiveRun === "followup" && J.isEnqueued()) {
			const e = q.deliveredReplies.map(({ input: e }) => readChatSendReplyPayload(e)).filter(isReplyPayloadStatusNotice);
			if (e.length > 0) await J.onQueuedFollowupReplyBatch({
				kind: "queued-followup",
				runId: D,
				originatingChannel: r.originatingRoute.originatingChannel,
				payloads: e,
				completion: { kind: "progress" }
			});
		}
		if (X || J.isEnqueued() || J.isTerminal()) return;
		Q("dispatch-completed", void 0, ce);
		const n = performance.now();
		await measureDiagnosticsTimelineSpan("gateway.chat_send.post_dispatch", async () => {
			const t = K?.getResult();
			const n = t?.terminalOutcome;
			const { runtimeClassification: i, runtimeCancelled: a, runtimeFailed: s, returnedAgentErrorPayloads: c, hasOnlyFinalWarnings: l, hasReturnedAgentError: u, returnedAgentErrorMessage: d } = resolveChatSendReturnedOutcome({
				dispatchResult: e,
				runtimeOutcome: n,
				deliveredReplies: q.deliveredReplies,
				agentRunStarted: G,
				isInternalTextSlashCommandTurn: L,
				collaborativeSteeringRefused: e.collaborativeSteeringRefused
			});
			if (!H.hasPersisted() && !H.isBlocked() && (u || G && c.length === 0 && H.hasRuntimePersistencePending())) await ne();
			const f = {
				terminalEntry: r.sourceRef,
				requesterContext: I,
				abortSignal: y.controller.signal,
				accountId: F,
				context: o,
				deliveredReplies: q.deliveredReplies,
				emitFirstAssistantServerTiming: se,
				session: m
			};
			let p = false;
			if (!v && (!G || K || l) && !u && !o.chatRunState.hasAbortMarker(D)) await finalizeChatSendDispatchedReplies({
				...f,
				foldCommandBlocks: L || K !== void 0,
				persistUserTurnTranscript: ne,
				suppressReplies: !K && q.hasAppendedWebchatAgentMedia(),
				runtimeOwnsTranscript: t?.assistantTranscript?.agentId === T && t.assistantTranscript.sessionKey === j && t.assistantTranscript.sessionId === getRpcSourceIdentity(y.entry).sessionId,
				state: a ? "aborted" : "final",
				stopReason: n?.stopReason
			});
			else if (!v && !o.chatRunState.hasAbortMarker(D)) p = await finalizeChatSendSourceReplies({
				...f,
				hasReturnedAgentErrorPayloads: u,
				suppressFinal: s
			});
			const h = e.collaborativeSteeringRefused || u && (s || !p);
			await Z.settleTerminalPersistence();
			if (!o.chatRunState.hasAbortMarker(D)) {
				if (h && !e.collaborativeSteeringRefused) Z.broadcastError({
					errorMessage: d,
					errorKind: i === "timeout" ? "timeout" : void 0,
					stopReason: n?.stopReason
				});
				const s = h ? errorShape(ErrorCodes.UNAVAILABLE, d ?? "agent returned an error payload") : void 0;
				setGatewayDedupeEntry({
					dedupe: o.dedupe,
					key: `chat:${D}`,
					session: captureAgentJobSession({
						...getRpcSourceIdentity(r.sourceRef),
						lifecycleGeneration: r.lifecycleGeneration
					}),
					entry: {
						ts: Date.now(),
						ok: !h,
						payload: h ? {
							runId: D,
							status: i === "timeout" ? "timeout" : "error",
							summary: d ?? "agent returned an error payload",
							...n ? { endedAt: n.endedAt } : {},
							...n?.stopReason ? { stopReason: n.stopReason } : {}
						} : a ? buildAbortedChatSendPayload({
							runId: D,
							endedAt: n?.endedAt ?? Date.now(),
							stopReason: n?.stopReason
						}) : {
							runId: D,
							status: v && !J.isSteered() ? "completed" : "ok",
							...t?.terminalOutcome?.stopReason ? { stopReason: t.terminalOutcome.stopReason } : {}
						},
						...s ? { error: s } : {}
					}
				});
			}
		}, {
			phase: "agent-turn",
			config: E,
			attributes: x
		});
		Q("post-dispatch-completed", { postDispatchMs: roundedChatSendTimingMs(performance.now() - n) }, ce);
	}).catch((e) => {
		t.finish(ae);
		return Z.handleError(e);
	});
	trackSessionControllerSourceWork(r.sourceRef.input, de);
	const fe = (async () => {
		try {
			await de;
		} finally {
			ie.resolve();
			await Z.finalize();
			emitSessionsChanged(o, {
				sessionKey: j,
				agentId: T,
				reason: "agent.input.settled"
			}, {
				accessChanged: false,
				rowScope: "runtime"
			});
			if (H.isBlocked() && i.offloadedRefs.length > 0) discardPreparedInboundMedia(i.offloadedRefs);
		}
	})();
	fe.catch((e) => {
		o.logGateway.warn(`webchat dispatch settlement failed: ${formatForLog(e)}`);
	});
	return fe;
}
//#endregion
//#region src/gateway/server-methods/chat-send-attachments.ts
/** Validate and durably offload attachments before input custody and ACK. */
async function prepareChatSendAttachments(e) {
	const { request: t, session: n, admission: r, respond: i, context: a } = e;
	const { inboundMessage: o, normalizedAttachments: s, explicitOrigin: c } = t;
	const { cfg: l, agentId: u, resolvedSessionModel: d, clientRunId: f } = n;
	const { activeRunAbort: p, chatSendTraceAttributes: m, cleanupAdmittedRun: h, finishAbortedChatSend: g, lifecycleGeneration: _ } = r;
	const assertInputCurrent = () => {
		p.controller.signal.throwIfAborted();
		r.assertWorkAdmissionCurrent();
		r.assertClientUploadAllowed?.();
	};
	let v = o;
	let y = [];
	let b = [];
	let x = [];
	let S = [];
	let C = false;
	let w;
	try {
		const e = await resolveExplicitOriginBindingTargets(c);
		assertInputCurrent();
		C = e.plugin;
		const t = readQueuedChatInputAdmission(f);
		if (t) S = readPersistedMediaFacts(t.target.message) ?? [];
		if (s.length > 0) {
			if ((r.initialSessionEntry ?? r.admittedSessionEntry ?? n.entry)?.deviceFolder) throw new Error(DEVICE_FOLDER_ATTACHMENTS_UNSUPPORTED);
			const t = performance.now();
			await measureDiagnosticsTimelineSpan("gateway.chat_send.prepare_attachments", async () => {
				const t = { value: e.acp || C ? true : void 0 };
				const resolveSupportsImages = async () => {
					t.value ??= await resolveGatewayModelSupportsImages({
						loadGatewayModelCatalog: a.loadGatewayModelCatalog,
						loadGatewayModelCatalogSnapshot: a.loadGatewayModelCatalogSnapshot,
						agentId: u,
						provider: d.provider,
						model: d.model
					});
					return t.value;
				};
				const n = await parseMessageWithAttachments(o, s, {
					maxBytes: resolveChatAttachmentMaxBytes(l),
					log: a.logGateway,
					supportsImages: t.value ?? resolveSupportsImages,
					acceptNonImage: true,
					signal: p.controller.signal,
					assertCurrent: assertInputCurrent
				});
				const r = t.value !== false;
				v = r ? n.message : stripImageMediaMarkers(n.message, n.offloadedRefs);
				y = n.images;
				b = n.imageOrder;
				x = n.offloadedRefs;
				S = x.filter((e) => !r || !e.mimeType.startsWith("image/")).map((e) => ({
					path: e.path,
					url: e.mediaRef,
					contentType: e.mimeType,
					fileName: e.label
				}));
			}, {
				phase: "agent-turn",
				config: l,
				attributes: {
					...m,
					attachmentCount: s.length
				}
			});
			assertInputCurrent();
			p.controller.signal.throwIfAborted();
			w = roundedChatSendTimingMs(performance.now() - t);
		}
	} catch (e) {
		const t = p.controller.signal.aborted && (a.chatRunState.hasAbortMarker(f) || Object.is(e, p.controller.signal.reason));
		if (!t) p.cleanup();
		await discardPreparedInboundMedia(x);
		if (t) {
			g();
			return { ok: false };
		}
		h();
		clearAgentRunContext(f, _);
		logAttachmentFailure(a.logGateway, "chat.send attachment offload failed", e);
		i(false, void 0, e instanceof SessionMutationAuthorizationChangedError ? e.error : errorShape(e instanceof MediaOffloadError ? ErrorCodes.UNAVAILABLE : ErrorCodes.INVALID_REQUEST, String(e)));
		return { ok: false };
	}
	return {
		ok: true,
		value: {
			explicitOriginTargetsPlugin: C,
			imageOrder: b,
			mediaPathOffloads: S,
			offloadedRefs: x,
			parsedImages: y,
			parsedMessage: v,
			prepareAttachmentsMs: w
		}
	};
}
/** Preparation owns cleanup until a transcript or pending input takes custody of its media. */
function bindChatSendPreparedMediaCustody(e) {
	let t;
	e.admission.setDiscardAbandonedPreparedMedia(() => {
		if (!t || !retainsUserTurnTranscriptMedia(t)) discardPreparedInboundMedia(e.attachments.offloadedRefs);
	});
	return (e) => {
		t = e;
	};
}
//#endregion
//#region src/gateway/current-prompt-reaction.ts
/** Captured only by authenticated chat admission, never by channel-route inference. */
function createCurrentPromptReaction(e) {
	return async (t) => {
		t.assertCurrent();
		const n = getUserTurnTranscriptAdmissionOwner(e.recorder);
		const r = n?.receipt();
		if (!n || e.recorder.isBlocked() || !r || r.agentId !== e.agentId || r.sessionKey !== e.sessionKey) throw new Error("Current WebChat prompt has not been committed.");
		const assertCurrent = () => {
			t.assertCurrent();
			if (e.recorder.isBlocked() || n.receipt() !== r) throw new Error("Current WebChat prompt admission changed.");
		};
		if (!isReactionEmoji(t.emoji)) throw new Error("one emoji grapheme is required");
		if (t.dryRun) return {
			messageId: r.entryId,
			changed: false,
			reactions: []
		};
		const { commitSessionReaction: i } = await import("./session-reaction-mutation-C-HwKU10.mjs");
		assertCurrent();
		const a = await i({
			scope: {
				agentId: r.agentId,
				sessionKey: r.sessionKey,
				storePath: r.storePath
			},
			sessionKey: e.sessionKey,
			sessionId: r.sessionId,
			agentId: e.agentId,
			messageId: r.entryId,
			emoji: t.emoji,
			remove: t.remove,
			actor: {
				type: "agent",
				id: e.agentId,
				label: resolveAgentIdentity(e.context.getRuntimeConfig(), e.agentId)?.name ?? e.agentId
			},
			identityId: "agent:" + e.agentId,
			context: e.context,
			assertCurrent
		});
		return {
			messageId: r.entryId,
			changed: a.changed,
			reactions: a.reactions
		};
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-dashboard-authority.ts
/** One source authorization survives queue adoption; read grants retain the original work lease. */
async function createChatSendDashboardAuthority(e) {
	const { admission: t, session: n, client: r, context: i, externalAuthorityAdmission: a, externalAdmissionParams: o } = e;
	const { sessionKey: s } = o;
	const c = a?.allowsDashboardReads(o);
	const l = c && !e.sessionMutationAuthorization ? await resolveSessionMutationAuthorizationAsync({
		client: r,
		context: i,
		method: "chat.send",
		requestParams: {
			agentId: n.agentId,
			sessionKey: s
		},
		expectedTarget: {
			agentId: n.agentId,
			sessionKey: s,
			storePath: n.storePath,
			sessionId: getRpcSourceIdentity(t.sourceRef).sessionId
		}
	}) : void 0;
	if (l?.error) throw new SessionMutationAuthorizationChangedError(l.error);
	const u = e.sessionMutationAuthorization ?? l?.authorization;
	if (c && !u) throw new Error("Dashboard session authorization is unavailable.");
	const d = c && a ? () => {
		e.sessionMutationCommitGuard?.();
		if (t.lifecycleGeneration !== getAgentEventLifecycleGeneration()) throw new Error("Dashboard prompt source lifecycle is no longer active.");
		if (t.activeRunAbort.controller.signal.aborted && !(isRpcSourceRegistered(t.sourceRef) && t.sourceRef.input.custody.cancellationRetired)) t.activeRunAbort.controller.signal.throwIfAborted();
		if (r?.invalidated || e.hasCurrentClientAuthority?.() === false || !a.allowsDashboardReads(o)) throw new Error("Dashboard message read admission is no longer active.");
		(u?.assertAdmittedInputCurrent ?? u?.assertCurrent)?.();
	} : void 0;
	return {
		release: () => l?.authorization?.release?.(),
		assertReadCurrent: d ? () => {
			t.assertWorkAdmissionCurrent();
			d();
		} : void 0,
		bindPromptRecorder(e) {
			if (!d) return;
			bindUserTurnPromptReactionSource(e, {
				agentId: n.agentId,
				sessionKey: s,
				assertCurrent: d,
				createReaction: (e) => createCurrentPromptReaction({
					agentId: n.agentId,
					sessionKey: s,
					recorder: e,
					context: i
				})
			});
		}
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-goal-ack.ts
/** Dispatch owns cleanup; a lost ACK reconciles through the durable Goal receipt. */
async function acknowledgeCodexGoal(e) {
	const { context: t, session: n, request: r, client: i, userTurn: a } = e.dispatch;
	try {
		await Promise.race([e.committed, e.dispatched]);
		const o = a.recorder.hasPersisted() ? await a.persist() : void 0;
		const s = o?.sessionTurnMutationResult?.result;
		if (!s || !o?.sessionEntry || !r.goalOperation) throw new Error("Codex Goal input was not committed; inspect the run before retrying.");
		await publishCommittedSessionGoalChange(t, {
			sessionKey: n.sessionKey,
			agentId: n.agentId,
			entry: o.sessionEntry,
			actor: gatewayClientSessionCreator(i),
			summary: `goal ${r.goalOperation.action}`
		});
		e.respond(true, {
			...e.ackPayload,
			...s
		}, void 0, { runId: n.clientRunId });
	} catch (i) {
		if (!a.recorder.hasPersisted() && r.goalOperation) t.dedupe.set(`chat:${n.clientRunId}`, {
			ts: Date.now(),
			ok: true,
			requestIdentity: r.goalOperation.requestFingerprint
		});
		e.respond(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, String(i), { retryable: true }));
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-goal-admission.ts
function requiresRuntimeApprovedChatInput(e) {
	return hasGlobalHooks("before_agent_run") || isAcpBridgeClient(e);
}
/** Codex Goal input stays pending until its native writer admits it. */
function resolveCodexGoalAdmission(e, t, n, r) {
	const { session: i, request: a, context: o, client: s } = e;
	const c = o.getRuntimeConfig();
	const l = getRegisteredAgentHarness("codex")?.harness;
	const u = !n || n.state === "local";
	return Boolean(a.goalOperation && t.entry && isDirectGatewayUserClient(s) && l && (u ? !c.cloudWorkers?.requiredProfile : n.executionMode === "remote-exec" && l.cloudPlacement?.mode === "remote-exec") && isDirectChatGoalSession({
		entry: t.entry,
		allowAborted: a.goalOperation.action === "resume",
		allowVisibleSpawn: true,
		acpMeta: r,
		requestedSessionId: i.requestedSessionId,
		sessionKey: t.canonicalKey
	}) && resolveEffectiveAgentRuntime({
		cfg: c,
		agentId: i.agentId,
		sessionKey: t.canonicalKey,
		sessionEntry: t.entry,
		provider: i.resolvedSessionModel.provider,
		modelId: i.resolvedSessionModel.model
	}) === "codex") ? u ? "local" : "worker" : void 0;
}
function isDirectChatGoalSession(e) {
	const t = e.entry;
	return Boolean(t?.sessionId && e.sessionKey !== "global" && (t.abortedLastRun !== true || e.allowAborted === true) && t.archivedAt === void 0 && t.initializationPending !== true && t.pendingFinalDelivery === void 0 && t.pluginOwnerId === void 0 && (t.spawnedBy === void 0 && (t.spawnDepth ?? 0) === 0 || e.allowVisibleSpawn === true && isVisibleSpawnedSession(e.sessionKey, { entry: t })) && t.subagentRole === void 0 && e.acpMeta == null && t.cronRunContinuation === void 0 && !isSubagentSessionKey(e.sessionKey) && !isCronSessionKey(e.sessionKey) && !isAcpSessionKey(e.sessionKey) && !isAgentHarnessSessionKey(e.sessionKey) && (e.requestedSessionId === void 0 || e.requestedSessionId === t.sessionId));
}
/** Fresh local input commits before execution; other runtimes retain pending custody. */
function isLocalChatInputAdmission(e, t, n, r, i) {
	const { session: a, request: o, context: s } = e;
	const c = s.getRuntimeConfig();
	const l = t.entry ?? n;
	if (c.cloudWorkers?.requiredProfile || requiresRuntimeApprovedChatInput(e.client) || o.goalOperation && hasGlobalHooks("reply_dispatch", { dispatchKind: "agent" }) || r && r.state !== "local" || !l || !isDirectChatGoalSession({
		entry: l,
		acpMeta: i,
		sessionKey: t.canonicalKey,
		requestedSessionId: a.requestedSessionId,
		allowAborted: o.goalOperation?.action === "resume",
		allowVisibleSpawn: Boolean(o.goalOperation)
	}) || l.agentHarnessId !== void 0 && l.agentHarnessId !== "openclaw") return false;
	if (n) return true;
	const u = {
		agentId: a.agentId,
		now: Date.now(),
		resetOverride: resolveChannelResetConfig({
			sessionCfg: c.session,
			channel: sessionDeliveryChannel(t.entry)
		}),
		resetType: resolveSessionResetType({ sessionKey: t.canonicalKey }),
		sessionCfg: c.session,
		sessionKey: t.canonicalKey,
		storePath: t.storePath
	};
	if (isIncognitoSessionKey(t.canonicalKey)) return resolveSessionEntryResetFreshness(u).state === "fresh";
	if (!t.lifecycleTimestamps) throw new Error("Chat session freshness was not prepared; retry.");
	return resolvePreparedSessionEntryResetFreshness(u, l, t.lifecycleTimestamps).state === "fresh";
}
/** Keep native placement facts borrowed until Goal admission consumes the current row. */
async function withGoalChatPlacement(e, t, n) {
	if (!e.prepareSessionPlacement) throw new Error("Worker placement admission reader is unavailable; retry.");
	const r = await e.prepareSessionPlacement(t);
	try {
		await n({
			sessionId: t,
			facts: r
		});
	} finally {
		r.release();
	}
}
/** Goal and initial-session policy are revalidated in the same input writer barrier. */
function createChatSendGoalCommitGuard(e) {
	const { admission: t, session: n, client: r, context: i, sessionMutationAuthorization: a, sessionMutationCommitGuard: o } = e;
	const s = t.initialSessionEntry ? {
		config: structuredClone(i.getRuntimeConfig()),
		key: n.sessionLoadKey,
		agentId: n.sessionLoadOptions.agentId,
		storePath: n.storePath,
		canonicalKey: n.sessionKey
	} : void 0;
	const check = (e) => {
		e();
		const a = i.getRuntimeConfig();
		const o = t.initialSessionEntry;
		if (o) {
			t.assertInitialSkillSelection?.();
			if (!isDeepStrictEqual(a, s?.config)) throw new Error("Session routing changed before Goal admission; refresh and retry.");
			const e = authorizeGatewaySessionCreation({
				cfg: a,
				client: r,
				agentId: n.agentId
			});
			if (e) throw new SessionMutationAuthorizationChangedError(e);
			const i = resolveOperatorSessionCreation(r);
			if (i.actor?.id !== o.createdActor?.id || resolveCreatorSandbox(a, i) !== o.sandbox) throw new Error("Session creation policy changed before Goal admission; retry.");
		}
		if (t.activeRunAbort.controller.signal.aborted || t.lifecycleGeneration !== getAgentEventLifecycleGeneration() || n.sessionRoutingChanged(a)) throw new Error("Goal admission changed before commit; refresh and retry.");
	};
	const c = [o, a?.assertCurrent];
	return {
		assertCurrent: t.codexGoalAdmission ? composeSessionSourceAssertion(c, check) : () => check(() => c.forEach((e) => e?.())),
		routingPredicate: s
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-retry-comparison.ts
function chatSendRequestConflictError(e = false) {
	return errorShape(ErrorCodes.INVALID_REQUEST, e ? "The previous mention selections cannot be verified. Check the conversation history and use a new message ID to send again." : "This message ID was already used for different input. Check the conversation history and use a new message ID to send again.", { details: { reason: "chat-request-conflict" } });
}
/** Submitted bytes compare input; the caller's current owner still decides replay. */
function readChatSendRetryComparison(e) {
	if (!e.entry?.sessionId) return;
	const { agentId: t, storePath: n, sessionKey: r, clientRunId: i } = e;
	const { sessionId: a, lifecycleRevision: o } = e.entry;
	return readSessionSubmittedInput({
		agentId: t,
		storePath: n,
		sessionKey: r,
		sessionId: a
	}, `${i}:user`, { includeSource: true }).then((e) => {
		return {
			agentId: t,
			storePath: n,
			sessionKey: r,
			sessionId: a,
			lifecycleRevision: o,
			clientRunId: i,
			submitted: e?.message,
			source: e?.source,
			messageSeq: e?.messageSeq
		};
	});
}
function compareChatSendSubmittedInput(e, t, n) {
	if (!n && t.entry?.sessionId || n && (n.agentId !== t.agentId || n.storePath !== t.storePath || n.sessionKey !== t.sessionKey || n.sessionId !== t.entry?.sessionId || n.lifecycleRevision !== t.entry?.lifecycleRevision || n.clientRunId !== t.clientRunId)) throw new SessionTranscriptProjectionUnavailableError(t.entry?.sessionId ?? n?.sessionId ?? t.clientRunId, "window-changed");
	const r = n?.submitted;
	if (!r) return e.mentions?.length || e.workContext ? "unverifiable" : false;
	const i = r["__openclaw"]?.chatRequestIdentity;
	if (typeof i === "string") return i !== e.requestIdentity;
	const a = r["__openclaw"]?.humanMentions;
	const o = r["__openclaw"]?.workContext;
	const s = extractTextFromChatContent(r.content, {
		joinWith: "\n",
		normalizeText: (e) => e
	}) ?? "";
	if (n?.source === "pending" && s !== e.rawMessage) return "unverifiable";
	if (!e.mentions?.length && !a?.length && !e.workContext && !o) return false;
	return s !== e.rawMessage || !isDeepStrictEqual(a ?? [], e.mentions ?? []) || !isDeepStrictEqual(o, e.workContext);
}
//#endregion
//#region src/gateway/server-methods/chat-send-session-binding.ts
function bindChatSendPreparedSession(e) {
	const { sourceRef: t } = e;
	let n = getRpcSourceIdentity(t).sessionId;
	return (r) => {
		const i = t.input;
		const a = i.claim?.operation;
		if (r.sessionKey !== e.sessionKey) return;
		if (!isRpcSourceRegistered(t) || e.lifecycleGeneration !== getAgentEventLifecycleGeneration() || !e.admission.isActive() || i.abortSignal.aborted || i.phase === "consumed" || i.retirementRequested || i.custody.cancellationRetired || i.withdrawalHolds > 0 || a?.abortFrozen || a?.result || t.adapter.projectSessionTerminalPending || t.adapter.projectSessionTerminalPersisted) throw createAbortError("chat session preparation no longer owns its admission");
		adoptExecRequestSession({
			runId: e.runId,
			previousSessionId: n,
			sessionId: r.sessionId
		});
		const o = i.mailbox.owner;
		const s = o.target;
		if (!s) throw new Error("Prepared RPC source lost its physical target");
		bindSessionControllerEntryTarget(o, captureSessionTarget({
			storeScope: s.storeScope,
			sessionKey: s.sessionKey,
			aliases: s.aliases,
			agentId: s.agentId,
			incarnation: r.sessionId
		}));
		updateRpcSourceSessionId(t, r.sessionId);
		n = r.sessionId;
	};
}
function createChatSendSessionInitialization(e) {
	const { authorization: t } = e;
	const n = {
		sessionKey: e.sessionKey,
		agentId: e.agentId
	};
	return () => ({
		...e.getSessionInitializationOptions(),
		onDatabaseRegistration: t?.followRegistration ? (e) => t.followRegistration?.(n, e) : void 0,
		...e.needsCreationBinding && t?.bindCreation ? {
			bindSessionCreation: (e) => {
				t.bindCreation?.(n, e);
				return t.assertCurrent;
			},
			onSessionCreated: t.recordCreatedSession
		} : {}
	});
}
//#endregion
//#region src/gateway/server-methods/chat-send-admission-context.ts
function prepareChatSendAdmissionContext(e) {
	const { request: t, session: n, client: r } = e;
	const { p: i, explicitOrigin: a, normalizedAttachments: o } = t;
	const { cfg: s, entry: c, sessionKey: l, selectedAgent: u, agentId: d, clientRunId: f, resolvedSessionModel: p } = n;
	return {
		chatSendTraceAttributes: {
			runId: f,
			sessionKey: l,
			agentId: u.agentId ?? d,
			provider: p.provider,
			model: p.model,
			hasAttachments: o.length > 0,
			hasExplicitOrigin: a !== void 0,
			hasConnectedClient: r?.connect !== void 0
		},
		originatingRoute: resolveChatSendOriginatingRoute({
			client: t.clientInfo,
			deliver: i.deliver,
			entry: c,
			explicitOrigin: a,
			hasConnectedClient: r?.connect !== void 0,
			mainKey: s.session?.mainKey,
			sessionKey: l
		})
	};
}
/** Reuse request preparation; final ordered admission checks this lifecycle binding. */
async function prepareChatSendAcpMetadata({ session: e, diagnostics: t }, n) {
	try {
		var r = _usingCtx();
		const i = n ?? {
			canonicalKey: e.sessionTarget.canonicalKey,
			binding: e.entry ? captureAcpSessionEntryBinding(e.entry) : null
		};
		r.u(t?.scope("detail.admission.acp_metadata"));
		const [a] = await readAcpSessionMetaForEntries({
			cfg: e.cfg,
			entries: [{
				agentId: e.agentId,
				sessionKey: i.canonicalKey,
				entry: i.binding ?? void 0
			}]
		});
		return {
			binding: i.binding,
			meta: a ?? null
		};
	} catch (e) {
		r.e = e;
	} finally {
		r.d();
	}
}
function prepareChatSendAcpRefresh(e, t, n) {
	if (!t) return;
	const r = n.entry ? captureAcpSessionEntryBinding(n.entry) : null;
	return isDeepStrictEqual(t.binding, r) ? void 0 : () => prepareChatSendAcpMetadata(e, {
		binding: r,
		canonicalKey: n.canonicalKey
	});
}
/** Check the captured target assertion and settle admission failure before responding. */
function assertChatSendSessionTargetOrRespond(e) {
	try {
		e.assertSessionTargetCurrent();
		return true;
	} catch (t) {
		e.cleanup();
		respondChatSendAdmissionError(t, e.respond);
		return false;
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-goal-retry.ts
async function prepareGoalChatSendRetry({ request: e, session: t, context: n }) {
	if (!e.goalOperation) return;
	const r = n.dedupe.get(`chat:${t.clientRunId}`);
	try {
		const n = {
			sessionKey: t.sessionKey,
			storePath: t.storePath,
			agentId: t.agentId,
			expectedSessionId: t.entry?.sessionId ?? t.backingSessionId ?? t.clientRunId,
			operation: e.goalOperation
		};
		let i = await lookupSessionGoalOperation(n);
		const a = i ? void 0 : await readChatSendRetryComparison(t);
		if (a?.submitted) i = await lookupSessionGoalOperation(n);
		return {
			receipt: i,
			dedupe: r,
			comparison: a
		};
	} catch (e) {
		if (!(e instanceof SessionGoalOperationError)) throw e;
		return {
			receipt: e,
			dedupe: r
		};
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-reservation.ts
/** Bind pending reservation and acceptance updates to one captured chat-send attempt. */
function createPendingChatSendReservationAccess(e) {
	const { pendingChatSendKey: t, clientRunId: n } = e.session;
	const { now: r, sessionKey: i, backingSessionId: a, rawSessionKey: o, selectedAgent: s, timeoutMs: c } = e.session;
	const { turnKind: l } = e.request;
	const read = () => readPreRegisteredRun({
		key: t,
		entry: e.context.dedupe.get(t)
	});
	return {
		read,
		abort: (t) => writePreRegisteredChatAbort({
			context: e.context,
			runId: n,
			stopReason: t,
			attemptId: e.attemptId,
			requestIdentity: e.requestIdentity
		}),
		reserve: () => {
			const { context: u, request: d, attemptId: f } = e;
			u.dedupe.set(t, {
				ts: r,
				ok: true,
				requestIdentity: e.requestIdentity,
				payload: {
					runId: n,
					attemptId: f,
					status: "accepted",
					sessionKey: i,
					...a ? { sessionId: a } : {},
					...o === i ? {} : { sessionKeyAliases: [o] },
					...s.agentId ? { agentId: s.agentId } : {},
					ownerConnId: normalizeOptionalString(e.client?.connId),
					ownerDeviceId: normalizeOptionalString(e.client?.connect?.device?.id),
					expiresAtMs: resolveChatRunExpiresAtMs({
						now: r,
						timeoutMs: c
					}),
					turnKind: l,
					...d.goalOperation ? { goalFingerprint: d.goalOperation.requestFingerprint } : {}
				}
			});
		},
		clear: () => {
			const r = read();
			if (r?.runId === n && normalizeOptionalString(r.payload.attemptId) === e.attemptId) e.context.dedupe.delete(t);
		},
		markInputAccepted: () => {
			const t = e.context.dedupe.get("chat:" + n);
			if (t?.ok !== true || t.requestIdentity !== e.requestIdentity || t.payload !== void 0 || t.error !== void 0) throw new Error("Chat input acceptance marker changed before acknowledgment");
			t.effectAccepted = true;
		}
	};
}
/** A retained request identity is not an ACK; only response-bearing rows may replay. */
function readChatSendDedupeResponse(e, t) {
	const n = e.get(`chat:${t}`);
	return n?.ok && n.payload === void 0 && n.error === void 0 ? void 0 : n;
}
/** Consume prepared receipts and current RAM ownership without yielding before reservation. */
function inspectGoalChatSendRetry({ request: e, session: t, respond: n, context: r, assertCurrent: i, prepared: a }) {
	i?.();
	const { clientRunId: o, pendingChatSendKey: s } = t;
	if (!e.goalOperation) return { kind: "new" };
	try {
		const t = a?.receipt;
		if (t instanceof SessionGoalOperationError) throw t;
		if (t) return {
			kind: "replay",
			receipt: t
		};
		const i = readPreRegisteredRun({
			key: s,
			entry: r.dedupe.get(s)
		});
		const c = r.dedupe.get(`chat:${o}`)?.requestIdentity;
		const l = a?.comparison?.submitted;
		const u = l?.["__openclaw"]?.chatRequestIdentity;
		const d = c !== void 0 && typeof u === "string" && c !== u;
		if (l && !i?.payload.goalFingerprint && !d) {
			n(false, void 0, chatSendRequestConflictError());
			return { kind: "settled" };
		}
		const f = c !== void 0 && c !== e.goalOperation.requestFingerprint;
		const p = readChatSendDedupeResponse(r.dedupe, o);
		const m = c === e.goalOperation.requestFingerprint && p !== void 0 && p !== a?.dedupe;
		if (!f && (i?.payload.goalFingerprint === e.goalOperation.requestFingerprint || m || !i && getRpcSourceForGateway(o, r.resolveGatewayContext))) {
			n(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, "Goal is being admitted; retry the same request.", { retryable: true }));
			return { kind: "settled" };
		}
		if (f || i || p || r.chatRunState.hasAbortMarker(o) || getRpcSourceForGateway(o, r.resolveGatewayContext)) throw new SessionGoalOperationError("operation-conflict", "Goal operation ID is already used by another request.");
		return { kind: "new" };
	} catch (e) {
		if (!(e instanceof SessionGoalOperationError)) throw e;
		n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, e.message, { details: { reason: `goal-${e.code}` } }));
		return { kind: "settled" };
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-pre-admission.ts
function resolveChatSendRequestConflict({ request: e, session: t, context: n }, r, i) {
	if (e.goalOperation) return;
	const a = [n.dedupe.get(`chat:${t.clientRunId}`), n.dedupe.get(t.pendingChatSendKey)];
	if (a.some((t) => t?.requestIdentity !== void 0 && t.requestIdentity !== e.requestIdentity)) return chatSendRequestConflictError();
	const o = i !== void 0 && readPreRegisteredRun({
		key: t.pendingChatSendKey,
		entry: a[1]
	})?.payload.attemptId === i;
	const s = o ? a.slice(0, 1) : a;
	if (!r && e.requestIdentity !== void 0 && s.some((t) => t?.requestIdentity === e.requestIdentity)) return;
	if (!(r?.submitted !== void 0 || s.some(Boolean) || n.chatRunState.hasAbortMarker(t.clientRunId) || !o && getRpcSourceForGateway(t.clientRunId, n.resolveGatewayContext))) return;
	const c = compareChatSendSubmittedInput(e, t, r);
	return c ? chatSendRequestConflictError(c === "unverifiable") : void 0;
}
function prepareChatSendRetryComparison(e, t) {
	try {
		resolveChatSendRequestConflict(e, void 0, t);
		return;
	} catch (t) {
		if (!isSessionTranscriptProjectionUnavailableError(t)) throw t;
		return readChatSendRetryComparison(e.session);
	}
}
/** Consume current authority in one synchronous frame after any required worker preparation. */
async function consumeChatSendCurrent(e, t) {
	const invoke = () => {
		e.assertCurrent?.();
		return t();
	};
	if (e.withCurrent) return e.withCurrent(invoke);
	if (e.assertCurrentAsync) await e.assertCurrentAsync();
	return invoke();
}
async function respondPreparedChatSendRetry(e, t = false) {
	try {
		const n = prepareChatSendRetryComparison(e) ?? (t ? readChatSendRetryComparison(e.session) : void 0);
		const r = n ? await n : void 0;
		return await consumeChatSendCurrent(e, () => respondChatSendRetry(e, r));
	} catch (t) {
		if (!isSessionTranscriptProjectionUnavailableError(t)) throw t;
		respondChatSendAdmissionError(t, e.respond);
		return true;
	}
}
/** Consume prepared comparison and current RAM ownership without yielding before reservation. */
function respondChatSendRetry(e, t) {
	e.assertCurrent?.();
	const { session: n, context: r, respond: i } = e;
	const { clientRunId: a, pendingChatSendKey: o } = n;
	const s = resolveChatSendRequestConflict(e, t);
	if (s) {
		i(false, void 0, s);
		return true;
	}
	const c = readChatSendDedupeResponse(r.dedupe, a);
	if (c) {
		i(c.ok, c.payload, c.error, { cached: true });
		return true;
	}
	const l = r.chatRunState.runs.get(a)?.abortMarker;
	if (l !== void 0) {
		const e = chatAbortMarkerTimestampMs(l);
		const t = buildAbortedChatSendPayload({
			runId: a,
			endedAt: e
		});
		setGatewayDedupeEntry({
			dedupe: r.dedupe,
			key: `chat:${a}`,
			entry: {
				ts: e,
				ok: true,
				payload: t
			}
		});
		i(true, t, void 0, {
			cached: true,
			runId: a
		});
		return true;
	}
	const u = r.dedupe.get(`chat:${a}`)?.effectAccepted === true;
	const d = readPreRegisteredRun({
		key: o,
		entry: r.dedupe.get(o)
	}) || getRpcSourceForGateway(a, r.resolveGatewayContext);
	if (u || d && t?.submitted) {
		i(true, {
			runId: a,
			status: "in_flight"
		}, void 0, {
			cached: true,
			runId: a
		});
		return true;
	}
	if (d) {
		i(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, "Chat input is being admitted; retry the same request.", { retryable: true }));
		return true;
	}
	if (t?.submitted) {
		const e = readQueuedChatInputAdmission(a)?.target;
		if (t.source === "pending" && e?.agentId === n.agentId && (e.storePath === n.storePath || sameSessionTranscriptStorePath(e.storePath, n.readSource?.path)) && e.sessionKey === n.sessionKey && e.sessionId === n.entry?.sessionId) return false;
		i(true, {
			runId: a,
			status: "ok",
			...t.messageSeq !== void 0 ? { messageSeq: t.messageSeq } : {}
		}, void 0, {
			cached: true,
			runId: a
		});
		return true;
	}
	return false;
}
/** Settle stop/retry/dedupe cases before reserving lifecycle admission. */
async function runChatSendPreAdmission(e) {
	const { request: t, session: n, respond: r, context: i, client: a } = e;
	const { stopCommand: o } = t;
	const { cfg: s, entry: c, sessionKey: l, rawSessionKey: u, selectedAgent: d, clientRunId: f, storePath: p, sessionRoutingChanged: m } = n;
	const consumeNewDispatchDecision = () => {
		if (m(s)) {
			respondChatSessionRoutingChanged(r);
			return false;
		}
		const e = resolveSessionWorkStartError(l, c, {
			allowPendingWorkspace: true,
			providerReviewAcknowledgment: t.providerReviewAcknowledgment,
			runId: f
		});
		if (e) {
			r(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, e));
			return false;
		}
		return true;
	};
	const consumeInitialDecision = () => {
		if (resolveSendPolicy({
			cfg: s,
			entry: c,
			sessionKey: l,
			channel: sessionDeliveryChannel(c),
			chatType: c?.chatType
		}) === "deny") {
			r(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "send blocked by session policy"));
			return false;
		}
		if (!t.goalOperation) try {
			if (respondChatSendRetry(e)) return false;
		} catch (e) {
			if (!isSessionTranscriptProjectionUnavailableError(e)) throw e;
		}
		return true;
	};
	if (!(o ? consumeInitialDecision() : await consumeChatSendCurrent(e, consumeInitialDecision))) return false;
	if (t.goalOperation) {
		const t = await prepareGoalChatSendRetry(e);
		const n = await consumeChatSendCurrent(e, () => inspectGoalChatSendRetry({
			...e,
			prepared: t
		}));
		if (n.kind === "settled") return false;
		if (n.kind === "replay") {
			r(true, {
				...n.receipt,
				replayed: true
			}, void 0, {
				cached: true,
				runId: f
			});
			return false;
		}
	}
	if (o) {
		const t = resolveChatAbortRequester(a);
		const o = n.readSource?.path ?? p;
		const f = {};
		const assertCurrent = () => {
			if (f.failure) throw f.failure.error;
			try {
				e.assertCurrent?.();
			} catch (e) {
				f.failure = { error: e };
				throw e;
			}
		};
		let h;
		try {
			if (await respondPreparedChatSendRetry(e, true)) return false;
			if (m(s)) {
				respondChatSessionRoutingChanged(r);
				return false;
			}
			assertCurrent();
			h = await abortChatRunsForSessionKeyWithPartials({
				context: i,
				ops: createChatAbortOps(i),
				sessionKey: l,
				sessionKeyAliases: l === u ? void 0 : [u],
				agentId: d.agentId,
				sessionId: c?.sessionId,
				session: {
					ok: true,
					value: {
						cfg: s,
						storePath: o,
						entry: c,
						canonicalKey: l,
						agentId: n.agentId
					}
				},
				defaultAgentId: tryResolveSessionCompatibilityOwnerAgentId(s, l),
				abortOrigin: "stop-command",
				stopReason: "stop",
				requester: t,
				stopSource: "channel-user",
				controllerTargets: [captureSessionTarget({
					storeScope: p,
					sessionKey: l,
					aliases: [u],
					agentId: d.agentId,
					incarnation: c?.sessionId
				})],
				hookContext: {
					sessionKey: l,
					sessionEntry: c,
					sessionId: c?.sessionId,
					commandSource: "gateway:chat.send",
					senderId: t.deviceId ?? t.connId
				},
				assertCurrent,
				cascadeDescendants: true
			});
			try {
				assertCurrent();
			} catch (e) {
				throw abortedPartialPersistenceError(e, h.warning);
			}
		} catch (e) {
			const t = f.failure ? f.failure.error : e;
			const n = f.failure && e instanceof AggregateError && e.cause instanceof Error ? e.cause : e;
			if (t instanceof SessionMutationAuthorizationChangedError) throw n instanceof SessionMutationAuthorizationChangedError ? n : new SessionMutationAuthorizationChangedError({
				...t.error,
				message: n instanceof Error ? n.message : t.message
			});
			respondChatSendAdmissionError(t, (e, i, a) => {
				r(e, i, a && n instanceof Error && n.cause === t ? {
					...a,
					message: n.message
				} : a);
			});
			return false;
		}
		const g = h.unauthorized ? errorShape(ErrorCodes.INVALID_REQUEST, "unauthorized") : h.error ?? descendantAbortError(h.descendants, "Session");
		if (g) {
			r(false, void 0, withAbortedPartialPersistenceWarning(g, h.warning));
			return false;
		}
		r(true, {
			ok: true,
			aborted: h.aborted,
			runIds: h.runIds,
			...h.warning ? { warning: h.warning } : {}
		});
		return false;
	}
	if (!t.goalOperation && await respondPreparedChatSendRetry(e, true)) return false;
	return consumeChatSendCurrent(e, consumeNewDispatchDecision);
}
//#endregion
//#region src/gateway/server-methods/chat-send-session.ts
function chatSendPreparationConfig(e, t, n, r, i) {
	const a = e.agents?.defaults;
	const o = resolveAgentEntry(e, t);
	const s = resolveSessionModelRef(e, n, t);
	const c = resolveConfiguredModelPolicyAllow({
		cfg: e,
		agentId: t
	});
	const l = [s, ...(modelFallbackOverrideFromAvailability(resolveModelFallbackAvailability({
		cfg: e,
		agentId: t,
		sessionKey: i,
		selectedModel: s,
		hasSessionModelOverride: Boolean(n?.modelOverride),
		modelOverrideSource: n?.modelOverrideSource === "default" ? void 0 : n?.modelOverrideSource,
		modelSelectionLocked: n?.modelSelectionLocked
	})) ?? []).flatMap((e) => {
		const t = parseModelRef(e, s.provider);
		return t ? [t] : [];
	})];
	const u = Object.fromEntries([...new Set(l.map(({ provider: e }) => e))].map((t) => {
		const n = findNormalizedProviderValue(e.models?.providers, t);
		return [t, n ? {
			...n,
			models: n.models?.filter(({ id: e }) => l.some((n) => n.provider === t && n.model === e))
		} : void 0];
	}));
	const d = [...new Set([
		"webchat",
		r?.explicitOrigin?.originatingChannel,
		sessionDeliveryChannel(n)
	].filter((e) => Boolean(e)))];
	return {
		defaultModel: a?.model,
		agentModel: o?.model,
		defaultModels: a?.models,
		agentModels: o?.models,
		modelPolicy: {
			refs: c.refs,
			owner: c.refs.length > 0 ? c.repairConfigPath : null
		},
		runtime: o?.runtime,
		models: {
			mode: e.models?.mode,
			providers: u
		},
		auth: e.auth,
		workspace: o?.workspace ?? a?.workspace,
		agentDir: o?.agentDir,
		timeoutSeconds: a?.timeoutSeconds,
		defaultSandbox: a?.sandbox,
		agentSandbox: o?.sandbox,
		tools: e.tools,
		agentTools: o?.tools,
		plugins: {
			enabled: e.plugins?.enabled,
			allow: e.plugins?.allow,
			deny: e.plugins?.deny,
			load: e.plugins?.load,
			slots: e.plugins?.slots,
			entries: Object.fromEntries(Object.entries(e.plugins?.entries ?? {}).map(([e, { enabled: t, hooks: n, subagent: r, llm: i }]) => [e, {
				enabled: t,
				hooks: n,
				subagent: r,
				llm: i
			}]))
		},
		channels: {
			defaults: e.channels?.defaults,
			selected: Object.fromEntries(d.map((t) => [t, e.channels?.[t]]))
		},
		roles: e.gateway?.roles,
		nodeCommands: e.gateway?.nodes?.commands,
		commands: e.commands,
		sendPolicy: e.session?.sendPolicy,
		reset: e.session?.reset,
		resetByType: e.session?.resetByType,
		resetByChannel: e.session?.resetByChannel
	};
}
async function prepareChatSendSessionEntry(e) {
	const { cfg: t, client: n, agentId: r, getRuntimeConfig: i } = e;
	const a = authorizeGatewaySessionCreation({
		cfg: t,
		client: n,
		agentId: r
	});
	if (a) throw new Error(a.message);
	const o = await prepareSkillLibrarySessionCreation(n, i, resolveOperatorSessionCreation(n));
	const assertSkillSelection = () => assertPreparedSkillLibrarySelection(o.skillLibrarySelections);
	const s = Date.now();
	const c = randomUUID();
	return {
		entry: {
			...buildSessionCreationStamp({
				...o,
				sandbox: resolveCreatorSandbox(t, o),
				now: s
			}),
			sessionId: c,
			lifecycleRevision: randomUUID(),
			updatedAt: s,
			sessionStartedAt: s,
			lastInteractionAt: s,
			chatType: "direct"
		},
		assertSkillSelection
	};
}
async function loadChatSendSessionContext(e) {
	const { request: t, context: n } = e;
	const { p: r, explicitOrigin: i, normalizedAttachments: a } = t;
	const o = r.sessionKey;
	if (!o.trim()) return {
		ok: false,
		error: "sessionKey must not be blank"
	};
	const s = normalizeOptionalString(r.agentId);
	const c = r.idempotencyKey;
	const l = pendingChatSendDedupeKey(c);
	const u = n.getRuntimeConfig();
	const d = resolveRequestedSessionAgentId(u, o, s);
	if (!d.ok) return {
		ok: false,
		error: d.error
	};
	const f = d.agentId;
	const p = resolveChatSendSessionKey(u, o, f);
	const m = { agentId: f };
	const h = captureSessionMutationRouting(u, void 0, [{
		sessionKey: o,
		agentId: f
	}]);
	const assertConfigCurrent = () => h(n.getRuntimeConfig());
	const g = performance.now();
	const _ = await measureDiagnosticsTimelineSpan("gateway.chat_send.load_session", () => t.stopCommand ? loadGatewaySessionEntryReadOnlyInWorker({
		excludeInternalEffects: true,
		cfg: u,
		key: p,
		...m
	}) : withGatewaySessionEntry(p, m, (e) => e, u, assertConfigCurrent), {
		phase: "agent-turn",
		attributes: {
			runId: c,
			hasAttachments: a.length > 0,
			hasExplicitOrigin: i !== void 0
		}
	});
	assertConfigCurrent();
	const preparationFor = (e) => chatSendPreparationConfig(e, f, _.entry, t, p);
	if (!isDeepStrictEqual(preparationFor(u), preparationFor(n.getRuntimeConfig()))) throw new Error("Session preparation changed; retry.");
	const v = roundedChatSendTimingMs(performance.now() - g);
	const { cfg: y, agentId: b, storePath: x, entry: S, canonicalKey: C, legacyKey: w } = _;
	const T = normalizeOptionalString(r.expectedSessionRoutingContract);
	const E = r.expectedLeafEntryId === null ? null : normalizeOptionalString(r.expectedLeafEntryId);
	const sessionRoutingChanged = (e) => T !== void 0 && T.toLowerCase() !== resolveSessionRoutingContract(e);
	return {
		ok: true,
		value: {
			rawSessionKey: o,
			sessionLoadKey: p,
			clientRunId: c,
			pendingChatSendKey: l,
			sessionLoadOptions: m,
			sessionLoadMs: v,
			cfg: y,
			agentId: b,
			selectedAgent: d,
			...t.explicitOrigin ? { preparationOrigin: t.explicitOrigin } : {},
			storePath: x,
			..._.readSource ? { readSource: _.readSource } : {},
			..._.capturedReadSource ? { capturedReadSource: _.capturedReadSource } : {},
			..._.capturedReadSources ? { capturedReadSources: _.capturedReadSources } : {},
			entry: S,
			sessionKey: C,
			legacyKey: w,
			sessionRoutingChanged,
			expectedLeafEntryId: E,
			agentIdOverride: s,
			requestedAgentId: f
		}
	};
}
/** Load and validate the session/model facts shared by later admission and dispatch phases. */
async function prepareChatSendSession(e) {
	const t = await loadChatSendSessionContext(e);
	if (!t.ok) return t;
	const n = t.value;
	const { request: r, client: i } = e;
	const { p: a } = r;
	const { cfg: o, agentId: s, sessionKey: c, entry: l, legacyKey: u } = n;
	if (isIncognitoSessionKey(c) && !l) return {
		ok: false,
		error: `Incognito session "${c}" was not found.`
	};
	const d = resolveMissingAgentHarnessSessionError(c, l);
	if (d) return {
		ok: false,
		error: d
	};
	const f = prepareDeletedAgentSessionCheck({
		cfg: o,
		sessionKey: c,
		entry: l,
		acpMetadataSessionKey: u,
		assertCurrent: e.assertCurrent
	});
	const p = f instanceof Promise ? await f : f;
	if (f instanceof Promise) e.assertCurrent?.();
	if (p !== null) return {
		ok: false,
		error: `Agent "${p}" no longer exists in configuration`
	};
	const m = normalizeOptionalString(a.sessionId);
	const h = l?.sessionId ?? m;
	if (!l) {
		const e = authorizeGatewaySessionCreation({
			cfg: o,
			client: i,
			agentId: s
		});
		if (e) return {
			ok: false,
			error: e
		};
	}
	const g = resolveSessionModelRef(o, l, s);
	const _ = resolveProviderIdForAuth(g.provider, { config: o });
	const v = resolveAgentTimeoutMs({
		cfg: o,
		overrideMs: a.timeoutMs
	});
	const y = Date.now();
	return {
		ok: true,
		value: {
			...n,
			requestedSessionId: m,
			backingSessionId: h,
			resolvedSessionModel: g,
			resolvedSessionAuthProvider: _,
			timeoutMs: v,
			now: y
		}
	};
}
async function qualifyChatSendSession(e, t) {
	const n = await prepareQualifiedSessionEntryTarget({
		...e,
		canonicalKey: e.sessionKey,
		requestedKey: e.sessionLoadKey,
		storeKey: e.legacyKey ?? e.sessionKey,
		readSource: e.capturedReadSource
	}, e.capturedReadSources);
	return {
		...e,
		sessionTarget: n,
		releaseSessionStorage: t,
		activeRunScopeKey: n.canonicalKey,
		readSource: n.readSource
	};
}
/** Validate a worker-prepared admission row against the qualified session source. */
function assertCurrentChatSendSession(e, t) {
	if (e.sessionRoutingChanged(t.cfg)) throw new Error(SESSION_ROUTING_CHANGED_ERROR_REASON);
	const { agentId: n, storeKey: r, readSource: i } = e.sessionTarget;
	const a = t.agentId !== n && "agent" || (t.legacyKey ?? t.canonicalKey) !== r && "store key" || i && !isDeepStrictEqual(t.capturedReadSource, i) && "store source";
	if (a) throw new Error(`Session storage changed while starting work (${a}). Retry.`);
}
function withCurrentChatSendSession(e) {
	const { session: t } = e;
	const n = captureSessionMutationRouting(t.cfg, void 0, [t]);
	const r = { explicitOrigin: t.preparationOrigin };
	const i = chatSendPreparationConfig(t.cfg, t.agentId, t.entry, r, t.sessionKey);
	const assertConfigCurrent = () => {
		const a = e.getRuntimeConfig();
		n(a);
		if (t.sessionRoutingChanged(a)) throw new Error(SESSION_ROUTING_CHANGED_ERROR_REASON);
		if (!isDeepStrictEqual(i, chatSendPreparationConfig(a, t.agentId, t.entry, r, t.sessionKey))) throw new Error("Session preparation changed; retry.");
	};
	const consume = (n, r, i) => {
		assertCurrentChatSendSession(t, n);
		return e.consume(n, r, i);
	};
	if (isIncognitoSessionKey(t.sessionKey)) return withGatewaySessionEntry(t.sessionLoadKey, {
		...t.sessionLoadOptions,
		includeMembership: e.includeMembership
	}, consume, t.cfg, assertConfigCurrent);
	return withQualifiedGatewaySessionEntry({
		cfg: t.cfg,
		target: t.sessionTarget,
		logicalStorePath: t.storePath,
		includeMembership: e.includeMembership,
		includeLifecycle: true,
		transcript: e.includeActivePath && t.expectedLeafEntryId !== void 0 ? {
			sessionKey: t.sessionTarget.storeKey,
			agentId: t.agentId,
			entryIds: [],
			activePathEntryId: t.expectedLeafEntryId,
			includeSession: true
		} : void 0,
		consume,
		assertConfigCurrent
	}).catch((e) => {
		if (isSessionTranscriptProjectionUnavailableError(e)) startSessionTranscriptIndexReconcile({
			agentId: t.agentId,
			path: t.sessionTarget.storePath,
			preferredSessionId: e.sessionId
		});
		throw e;
	});
}
/** Refuse before send admission so confirmation can retain the unsent composer. */
async function prepareChatSendNativeRuntimeRestriction(e) {
	const { request: t, session: n, client: r, context: i } = e;
	const { entry: a, cfg: o, agentId: s, sessionKey: c, resolvedSessionModel: l } = n;
	if (t.turnKind !== "main" || t.stopCommand || !a && n.requestedSessionId || !t.suppressCommandInterpretation && resolveTextCommand(t.inboundMessage, o)) return;
	const u = resolveEffectiveAgentRuntime({
		cfg: o,
		agentId: s,
		sessionKey: c,
		sessionEntry: a,
		provider: l.provider,
		modelId: l.model
	});
	if (u === "openclaw") return;
	const d = getRegisteredAgentHarness(u)?.harness;
	if (!d || d.executionEnvironment !== "host-only") return;
	const restrictionFor = (e, t, n, i) => resolveSessionNativeRuntimeRestriction({
		operation: "send",
		cfg: e,
		agentId: s,
		sessionKey: c,
		entry: t,
		persistedEntry: i,
		preparedSessionCapabilityEntry: {
			sessionKey: c,
			entry: t
		},
		harness: d,
		provider: n.provider,
		modelId: n.model,
		callerCanConsent: hasGatewayAdminScope(r)
	});
	const f = resolveOperatorSessionCreation(r);
	const p = a ?? buildSessionCreationStamp({
		...f,
		sandbox: resolveCreatorSandbox(o, f),
		now: n.now
	});
	const m = await withPreparedSessionCapabilityRead(() => restrictionFor(o, p, l, a));
	const h = readAgentRuntimeRestrictionErrorDetails(m?.details);
	if (a || !m || !hasGatewayAdminScope(r) || !h || h.reason === "sandbox-required" || h.reason === "remote-execution") return m;
	const [{ loadReplySessionInitializationSnapshot: g, commitReplySessionInitialization: _ }, { recordSessionCreated: v }] = await Promise.all([import("./session-accessor.reset-D3NzIoho.mjs"), import("./session-created-DtqA-8Lk.mjs")]);
	await (e.assertCurrentAsync ? e.assertCurrentAsync() : e.assertCurrent?.());
	const y = {
		agentId: s,
		sessionKey: c,
		storePath: n.storePath
	};
	const b = await g(y);
	await (e.assertCurrentAsync ? e.assertCurrentAsync() : e.assertCurrent?.());
	const sessionChanged = () => errorShape(ErrorCodes.INVALID_REQUEST, "Session changed before native confirmation. Retry.");
	if (b.currentEntry) return sessionChanged();
	const x = await prepareChatSendSessionEntry({
		cfg: o,
		client: r,
		agentId: s,
		getRuntimeConfig: i.getRuntimeConfig
	});
	const S = await prepareSessionCapabilityRead(() => {
		const e = i.getRuntimeConfig();
		const t = resolveSessionModelRef(e, void 0, s);
		return readAgentRuntimeRestrictionErrorDetails(restrictionFor(e, x.entry, t)?.details);
	});
	let C;
	try {
		C = await _({
			...y,
			activeSessionKey: c,
			expectedRevision: b.revision,
			databaseSource: b.databaseSource,
			sessionEntry: x.entry,
			commitGuard: () => {
				e.assertCurrent?.();
				x.assertSkillSelection();
				const t = i.getRuntimeConfig();
				const a = resolveOperatorSessionCreation(r);
				const o = resolveSessionModelRef(t, void 0, s);
				const d = authorizeGatewaySessionCreation({
					cfg: t,
					client: r,
					agentId: s
				});
				const f = S.read();
				if (d || !hasGatewayAdminScope(r) || n.sessionRoutingChanged(t) || a.actor?.id !== x.entry.createdActor?.id || resolveCreatorSandbox(t, a) !== x.entry.sandbox || o.provider !== l.provider || o.model !== l.model || f?.reason !== h.reason || resolveEffectiveAgentRuntime({
					cfg: t,
					agentId: s,
					sessionKey: c,
					provider: o.provider,
					modelId: o.model
				}) !== u) throw new Error(d?.message ?? "Native session creation changed before commit.");
			}
		});
	} finally {
		S.release();
	}
	if (!C.ok) return sessionChanged();
	await v(o, {
		agentId: s,
		sessionKey: c,
		entry: C.sessionEntry
	});
	emitSessionsChanged(i, {
		agentId: s,
		sessionKey: c,
		reason: "create"
	});
	return withPreparedSessionCapabilityRead(() => restrictionFor(i.getRuntimeConfig(), C.sessionEntry, l, C.sessionEntry));
}
//#endregion
//#region src/gateway/server-methods/chat-send-work-admission.ts
function assertChatSendWorkAdmissionCurrent(e) {
	if (!e.retainedWork.isActive() || !e.admission.isActive() || e.lifecycleGeneration !== getAgentEventLifecycleGeneration() || e.controller.signal.aborted && !(isRpcSourceRegistered(e.sourceRef) && e.sourceRef.input.custody.cancellationRetired)) throw new Error("Chat admission ended or was cancelled; submit a new turn.");
}
/** Preparation returns facts; the caller consumes current retry ownership before reserving. */
function prepareChatSendAdmissionRetry(e) {
	try {
		return prepareChatSendRetryComparison(e)?.catch((e) => ({ error: e }));
	} catch (e) {
		return { error: e };
	}
}
function consumeChatSendAdmissionRetry(e, t) {
	try {
		if (t && "error" in t) throw t.error;
		if (readPreRegisteredRun({
			key: e.session.pendingChatSendKey,
			entry: e.context.dedupe.get(e.session.pendingChatSendKey)
		})?.payload.goalFingerprint) {
			respondError(e.respond, ErrorCodes.INVALID_REQUEST, "Run ID is reserved by a Goal request; use a new ID.");
			return false;
		}
		return !e.request.goalOperation && respondChatSendRetry(e, t) ? false : t;
	} catch (t) {
		if (t instanceof SessionMutationAuthorizationChangedError) throw t;
		respondChatSendAdmissionError(t, e.respond);
		return false;
	}
}
/** An awaited retry comparison must return to current rows before admission can consume it. */
async function withCurrentChatSendRetry(e, t, n) {
	const withCurrent = (t) => withCurrentChatSendSession({
		session: e.session,
		getRuntimeConfig: e.context.getRuntimeConfig,
		includeMembership: Boolean(e.withPreparedCurrent),
		includeActivePath: e.request.p.queueMode !== "steer",
		consume: (n, r, i) => {
			const consumeCurrent = () => t(n);
			if (e.withPreparedCurrent) return e.withPreparedCurrent({
				agentId: n.agentId,
				storePath: n.storePath,
				sessionKey: n.canonicalKey,
				entry: n.entry,
				readSource: n.capturedReadSource,
				members: r.get(n.legacyKey ?? n.canonicalKey) ?? []
			}, consumeCurrent, i);
			i();
			return consumeCurrent();
		}
	});
	const r = await withCurrent((r) => {
		const i = prepareChatSendRetryComparison({
			...e,
			session: {
				...e.session,
				entry: r.entry
			}
		}, t);
		if (i) return observeChatSendWork(i);
		n(r, void 0);
	});
	if (r) {
		const e = await r();
		await withCurrent((t) => n(t, e));
	}
}
/** Settle an invalid exact attempt before selecting its admission failure response. */
function respondChatSendWorkAdmissionFailure(e, t, n, r) {
	if (t instanceof ExpectedProfileMismatchError) throw t;
	const { context: i, respond: a, session: o } = e;
	const { clientRunId: s } = o;
	const c = n.pendingReservation;
	const l = normalizeOptionalString(c?.payload.attemptId);
	if (!readChatSendDedupeResponse(i.dedupe, s) && (!l || l === n.attemptId)) {
		const e = n.runAbort.controller.signal.aborted ? n.runAbort.entry?.adapter.abortStopReason ?? "rpc" : n.lifecycleGeneration !== getAgentEventLifecycleGeneration() ? "restart" : !c || !isFutureDateTimestampMs(c.payload.expiresAtMs, { nowMs: Date.now() }) ? "timeout" : void 0;
		if (e && e !== "restart") writePreRegisteredChatAbort({
			context: i,
			runId: s,
			stopReason: e,
			attemptId: n.attemptId,
			requestIdentity: n.requestIdentity
		});
	}
	try {
		const t = resolveChatSendRequestConflict(e, r);
		if (t) {
			a(false, void 0, t);
			return;
		}
	} catch {}
	const u = i.chatRunState.hasAbortMarker(s) && readChatSendDedupeResponse(i.dedupe, s);
	if (u) {
		a(u.ok, u.payload, u.error, {
			cached: true,
			runId: s
		});
		return;
	}
	respondChatSendAdmissionError(t, a, (t) => {
		if (isProgressCardRefreshInputProvenance(e.request.systemInputProvenance)) return;
		broadcastChatError({
			context: i,
			terminalEntry: n.runAbort.entry,
			runId: s,
			sessionKey: o.sessionKey,
			agentId: o.agentId,
			errorMessage: t
		});
	});
}
/** New input is checked only after the chat owner has reconciled prior receipts. */
function admitChatSendUploads({ params: e, client: t, context: n, respond: r }) {
	try {
		const r = captureGatewayClientUploadCommitGuard({
			method: "chat.send",
			requestParams: e,
			client: t,
			context: n
		});
		r?.();
		return {
			ok: true,
			assertClientUploadAllowed: r
		};
	} catch (e) {
		if (!(e instanceof SessionMutationAuthorizationChangedError)) throw e;
		r(false, void 0, e.error);
		return { ok: false };
	}
}
/** Observe started work before the retained read releases; consuming still rethrows its error. */
function observeChatSendWork(e) {
	e.catch(() => {});
	return () => e;
}
/** Queued and collected turns share the original session and caller admission until settlement. */
function createChatSendWorkAdmission(e) {
	const t = e.terminal;
	const n = t && getSessionActorStorageBinding({
		agentId: t.target.agentId,
		sessionKey: t.target.canonicalKey,
		storePath: t.storePath
	});
	const inStorage = (e) => n ? runWithSessionActorStorage(n, e) : e();
	let r = 1;
	const i = [];
	let a = t?.target.readSource;
	let o = t?.lifecycleRevision;
	let isCommittedDestinationCurrent;
	let s;
	let c;
	let l;
	let u;
	let d = true;
	const releaseAdmission = () => {
		for (const e of i.splice(0)) try {
			e();
		} catch (e) {
			warnCleanupFailure(e);
		}
		try {
			e.admission.release();
		} finally {
			try {
				e.releaseCallerAuthority?.();
			} finally {
				e.releaseGatewayRootContinuation?.();
			}
		}
	};
	const warnCleanupFailure = (t) => {
		e.logGateway.warn(`Failed to finish pending chat input: ${formatForLog(t)}`);
	};
	const finishRelease = () => {
		if (!u) {
			d = false;
			releaseAdmission();
			return;
		}
		const close = async () => {
			try {
				await (await u)?.actor.release();
			} finally {
				d = false;
				releaseAdmission();
			}
		};
		close().catch(warnCleanupFailure);
	};
	const release = () => {
		if (r === 0) return;
		r -= 1;
		if (r !== 0) return;
		let e = void 0;
		try {
			e = inStorage(() => l?.());
		} catch (e) {
			warnCleanupFailure(e);
		}
		if (e) e.then(finishRelease, (e) => {
			warnCleanupFailure(e);
			finishRelease();
		});
		else finishRelease();
	};
	const hold = () => {
		let e = false;
		return () => {
			if (e) return;
			e = true;
			release();
		};
	};
	const retain = () => {
		if (r === 0) throw new Error("cannot retain a released chat work admission");
		r += 1;
		return hold();
	};
	return {
		acquireInputActor() {
			if (!u) {
				if (!t || r === 0) throw new Error("Chat input actor has no live admission");
				const assertCurrent = () => {
					if (!d || !t.isActive()) throw new Error("Chat input actor admission ended");
				};
				const n = e.followRegistration;
				u = inStorage(() => acquireSessionInputActor({
					agentId: t.target.agentId,
					storePath: t.storePath,
					readSource: t.target.readSource,
					target: {
						canonicalKey: t.target.canonicalKey,
						storeKeys: [...t.target.storeKeys]
					}
				}, {
					assertCurrent,
					assertReadable: assertCurrent
				}, n && ((e) => n({
					sessionKey: t.target.canonicalKey,
					agentId: t.target.agentId
				}, e))));
			}
			return u;
		},
		addCleanup: (e) => i.push(e),
		isActive: () => r > 0,
		assertCommittedDestinationCurrent() {
			if (isCommittedDestinationCurrent && (r === 0 || !t?.isActive() || !isCommittedDestinationCurrent())) throw new Error("Committed chat input session changed");
		},
		recordFailureNotice(e) {
			if (!t) throw new Error("Failed input notice requires its original admission target");
			const n = o;
			const i = {
				agentId: t.target.agentId,
				storePath: t.target.storePath,
				sessionKey: t.target.storeKey,
				sessionId: getRpcSourceIdentity(t.sourceRef).sessionId,
				expectedOwner: { lifecycleRevision: n }
			};
			const assertCommitAllowed = () => {
				if (r === 0 || !t.isActive()) throw new Error("Failed input notice admission ended");
			};
			return inStorage(() => withOwnedSessionTranscriptWrites({
				sessionTarget: i,
				assertCommitAllowed,
				withTranscriptWrite: trackAsyncWork
			}, () => recordGatewaySessionRunFailure({
				...e,
				target: i,
				assertCommitAllowed,
				sessionEntryCurrent: a ? {
					source: {
						...a,
						sessionKey: i.sessionKey
					},
					assertCurrent(e) {
						assertCommitAllowed();
						if (e?.sessionId !== i.sessionId || e.lifecycleRevision !== n) throw new Error("Failed input notice session changed");
					}
				} : void 0
			})));
		},
		release: hold(),
		retain,
		withInputCommitPublication(e, r) {
			if (!t) throw new Error("Chat input publication requires its original admission target");
			return inStorage(() => withSessionTranscriptSourcePublication({
				agentId: t.target.agentId,
				sessionId: getRpcSourceIdentity(t.sourceRef).sessionId,
				sessionKey: t.target.storeKey,
				storePath: t.target.storePath
			}, (e, l) => {
				if (a && (a.agentId !== e.agentId || a.path !== e.path || a.databaseIdentity !== e.databaseIdentity || a.databaseBirthtime !== e.databaseBirthtime)) throw new Error("Committed chat input changed its admitted physical source");
				a ??= e;
				if (!isCommittedDestinationCurrent) {
					const bindDestination = (r) => {
						c?.();
						s = r;
						const { sessionId: i, lifecycleRevision: a } = r;
						const matches = (e) => e !== void 0 && e.archivedAt === void 0 && e.lifecycleRevision === a && (a !== void 0 || e.sessionId === i);
						if (n) isCommittedDestinationCurrent = () => matches(n.actor.storage.readCurrent({
							type: "session.entry.read",
							input: { sessionKey: t.target.storeKey }
						}, n.authority));
						else {
							const n = retainPreparedSessionEntryPredicate({
								databaseIdentity: `file:${e.databaseIdentity}`,
								sessionKey: t.target.storeKey,
								entry: r,
								matches: (e, t) => matches(t)
							});
							c = n.release;
							isCommittedDestinationCurrent = n.isCurrent;
						}
					};
					bindDestination(l);
					i.push(() => c?.());
					bindSessionEffectTransition(captureSessionTarget({
						storeScope: t.storePath,
						sessionKey: t.target.canonicalKey,
						agentId: t.target.agentId
					}), t, ({ previous: e, current: t }) => {
						if (e?.sessionId === s?.sessionId && e?.lifecycleRevision === s?.lifecycleRevision) {
							bindDestination({
								...l,
								...t
							});
							o = t.lifecycleRevision;
						}
					});
				}
				o = l.lifecycleRevision;
				r?.(e, l);
			}, e));
		},
		setPendingInputCleanup: (e) => {
			l = e;
		}
	};
}
/** Rechecked inside the session writer barrier before exclusive input is admitted. */
function assertChatSendExclusiveAdmission(e, t) {
	if (!e.goalOperation && !e.providerReviewAcknowledgment) return;
	const { storePath: n, sessionKey: r, backingSessionId: i, activeRunScopeKey: a } = t;
	if (isCompetingSessionControllerWorkActive(n, [r, i], t.agentId) || hasPendingFollowupQueueWork([
		r,
		i,
		a
	], {
		storeScope: n,
		agentId: t.agentId
	})) throw new Error(e.providerReviewAcknowledgment ? "The session still has active work. Review its status before continuing." : "goal-session-busy");
}
function createChatSendPendingInputAdmission({ runId: e, expectedProfileId: t, sessionMutationAuthorization: n, sessionMutationCommitGuard: r, assertCustodyLifetimeCurrent: i, assertClientUploadAllowed: a }) {
	const assertCustodyCurrent = () => {
		i();
		if (n?.assertAdmittedInputCurrent) n.assertAdmittedInputCurrent();
		else {
			r?.();
			n?.assertCurrent();
		}
	};
	let o;
	const s = t === void 0 ? assertCustodyCurrent : createMessageInjectionAuthority(() => {
		if (o) throw o.cause;
		assertCustodyCurrent();
		return true;
	});
	return {
		runId: e,
		authority: n?.admittedInputAuthority ? withSessionPendingInputAuthorityGuard(n.admittedInputAuthority, i, t === void 0 ? void 0 : (e) => {
			o ??= { cause: e };
			s();
			throw e;
		}) : void 0,
		assertCurrent: () => {
			a?.();
			r?.();
			assertCustodyCurrent();
		},
		assertAdmittedCurrent: s
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-admission-cleanup.ts
/** Join started preparation before releasing its existing controller and caller custody. */
async function prepareAdmittedChatSendDispatch({ params: e, runAbort: t, admission: n, releaseCaller: r, assertSessionTargetCurrent: i }) {
	const { respond: a } = e;
	let releaseGatewayRootContinuation = () => {};
	let o = r;
	const cleanup = () => {
		try {
			t.cleanup();
			n.release();
			releaseGatewayRootContinuation();
		} finally {
			o?.();
			o = void 0;
		}
	};
	let s;
	try {
		if (!assertChatSendSessionTargetOrRespond({
			assertSessionTargetCurrent: i,
			cleanup,
			respond: a
		})) return;
		const r = await consumeChatSendCurrent(e, () => {
			t.controller.signal.throwIfAborted();
			releaseGatewayRootContinuation = retainGatewayRootWorkAdmissionContinuation() ?? (() => {});
			const r = e.onAdmissionOwned ? observeChatSendWork(n.run(e.onAdmissionOwned)) : void 0;
			s = r;
			return { admission: r };
		});
		if (r.admission) {
			if (!await r.admission()) {
				cleanup();
				return;
			}
			await consumeChatSendCurrent(e, () => true);
		}
		if (!assertChatSendSessionTargetOrRespond({
			assertSessionTargetCurrent: i,
			cleanup,
			respond: a
		})) return;
	} catch (e) {
		if (s) await Promise.allSettled([s()]);
		cleanup();
		throw e;
	}
	return {
		releaseCallerAuthority: o,
		releaseGatewayRootContinuation
	};
}
/** Own cleanup after chat admission transfers work beyond the request frame. */
function createAdmittedChatSendCleanup(e) {
	let t;
	return {
		cleanup: () => {
			e.cleanupAbort();
			e.releaseRetainedWork();
			t?.();
			t = void 0;
		},
		setDiscardPreparedMedia: (e) => {
			t = e;
		}
	};
}
/** Publish Stop from the captured source identity before releasing its admitted custody. */
function finishAbortedChatSend(e) {
	const t = Date.now();
	const n = buildAbortedChatSendPayload({
		runId: e.runId,
		stopReason: e.stopReason ?? "rpc",
		endedAt: t
	});
	setGatewayDedupeEntry({
		dedupe: e.context.dedupe,
		key: `chat:${e.runId}`,
		session: captureAgentJobSession({
			...getRpcSourceIdentity(e.sourceRef),
			lifecycleGeneration: e.lifecycleGeneration
		}),
		entry: {
			ts: t,
			ok: true,
			payload: n
		}
	});
	e.cleanup();
	clearAgentRunContext(e.runId, e.lifecycleGeneration);
	e.respond(true, n, void 0, { runId: e.runId });
}
/** Release caller authority when admitted work settles. */
function releaseChatSendCallerAuthority(e) {
	try {
		e.operator.release?.();
	} finally {
		if (e.request.providerReviewAcknowledgment) retireProviderReviewAcknowledgment(e.request.providerReviewAcknowledgment);
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-interrupt-admission.ts
/** Retain the caller before an interrupt can change session state. */
async function prepareChatSendInterruptAdmission(e) {
	const t = await retainGatewayOperatorRun({
		...e.operator,
		entry: e.entry
	});
	const assertCurrent = () => {
		e.assertCurrent?.();
		e.abortSignal.throwIfAborted();
		t.authority?.assertCurrent();
		if (e.interruptCapture) e.assertSessionTargetCurrent();
	};
	try {
		assertCurrent();
		return {
			operator: t,
			interrupt: () => {
				assertCurrent();
				if (!e.interruptCapture) return false;
				const t = stopSession({
					source: "interrupt",
					capture: e.interruptCapture,
					assertCurrent,
					onError: () => "continue"
				});
				assertCurrent();
				return t.aborted || t.queuedCancelled > 0;
			}
		};
	} catch (e) {
		t.release();
		throw e;
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-admission.ts
/** Reserve the session lifecycle and register the abortable run before attachment work. */
async function admitChatSend(e) {
	const { request: t, session: n, respond: r, context: i, client: a, diagnostics: o } = e;
	const { p: s, turnKind: c } = t;
	const l = t.goalOperation?.requestFingerprint ?? t.requestIdentity;
	const u = isProgressCardRefreshInputProvenance(t.systemInputProvenance);
	const { rawSessionKey: d, clientRunId: f, cfg: p, storePath: m, entry: h, sessionKey: g, selectedAgent: _, requestedSessionId: v, backingSessionId: y, agentId: b, resolvedSessionModel: x, resolvedSessionAuthProvider: S, activeRunScopeKey: C, timeoutMs: w, expectedLeafEntryId: T } = n;
	const assertSessionTargetCurrent = () => {
		if (n.sessionRoutingChanged(i.getRuntimeConfig())) throw new Error(SESSION_ROUTING_CHANGED_ERROR_REASON);
	};
	const E = {
		cached: true,
		runId: f
	};
	const { chatSendTraceAttributes: D, originatingRoute: O } = prepareChatSendAdmissionContext(e);
	const k = getAgentEventLifecycleGeneration();
	const A = randomUUID();
	const j = createPendingChatSendReservationAccess({
		context: i,
		client: a,
		attemptId: A,
		requestIdentity: l,
		request: t,
		session: n
	});
	const M = t.goalOperation ? await prepareGoalChatSendRetry(e) : void 0;
	const N = prepareChatSendAdmissionRetry(e);
	const P = N instanceof Promise ? await N : N;
	const clearReservationAndThrow = (e) => {
		j.clear();
		throw e;
	};
	const F = await consumeChatSendCurrent(e, () => {
		e.assertCurrent?.();
		const t = inspectGoalChatSendRetry({
			...e,
			prepared: M
		});
		if (t.kind !== "new") {
			if (t.kind === "replay") r(true, {
				...t.receipt,
				replayed: true
			}, void 0, E);
			return;
		}
		const n = consumeChatSendAdmissionRetry(e, P);
		if (n === false) return;
		const o = readSessionControllerAdmissionError({
			scope: m,
			identities: [
				g,
				d,
				y
			],
			agentId: b
		});
		if (o) {
			if (isAgentRunDirectAbortReason(o)) {
				j.abort("rpc");
				const e = readChatSendDedupeResponse(i.dedupe, f);
				r(e.ok, e.payload, e.error, E);
			} else respondChatSendAdmissionError(o, r);
			return;
		}
		const c = admitChatSendUploads({
			params: s,
			client: a,
			context: i,
			respond: r
		});
		if (!c.ok) return;
		j.reserve();
		return {
			retryComparison: n,
			uploadAdmission: c
		};
	}).catch(clearReservationAndThrow);
	if (!F) return { ok: false };
	let I = F.retryComparison;
	const L = F.uploadAdmission;
	const ee = t.goalOperation?.action === "start" && !h && !v ? await prepareChatSendSessionEntry({
		cfg: n.cfg,
		client: a,
		agentId: b,
		getRuntimeConfig: i.getRuntimeConfig
	}).catch(clearReservationAndThrow) : void 0;
	let R = ee?.entry.sessionId ?? y ?? f;
	let z;
	let B = false;
	let V;
	let te = false;
	let ne = false;
	let H;
	let U;
	let re;
	let W;
	let ie;
	let G;
	let K = false;
	let q;
	let assertSourceAuthority = e.assertCurrent;
	let assertAcceptedInputAuthority;
	const J = captureSessionTarget({
		storeScope: m,
		sessionKey: g,
		aliases: [d, n.sessionTarget.storeKey],
		agentId: b,
		incarnation: R
	});
	const Y = registerChatAbortController({
		target: J,
		policy: resolveQueueSettings({
			cfg: p,
			channel: O.originatingChannel,
			sessionEntry: h,
			inlineMode: s.queueMode
		}),
		authority: { assertCurrent: () => assertSourceAuthority?.() },
		runId: f,
		sessionId: R,
		sessionKey: g,
		agentId: _.agentId,
		timeoutMs: w,
		ownerConnId: normalizeOptionalString(a?.connId),
		ownerDeviceId: normalizeOptionalString(a?.connect?.device?.id),
		providerId: x.provider,
		authProviderId: S,
		resolveTerminalProducer: (e) => resolveActiveReplyRunOwnerForSignal(e.input.abortSignal),
		kind: "chat-send",
		turnKind: c,
		...u ? {
			controlUiVisible: false,
			projectSessionActive: false
		} : {},
		lifecycleGeneration: k
	});
	const X = Y.entry?.input.policy.mode === "interrupt" ? captureSessionControllerInterruptBefore(Y.entry.input) : void 0;
	const ae = i.workerSessionPlacementService;
	const isPendingReservationCurrent = () => {
		if (i.chatRunState.hasAbortMarker(f)) return false;
		const e = j.read();
		if (e && normalizeOptionalString(e.payload.attemptId) !== A) {
			K = true;
			return false;
		}
		if (!e) {
			const e = readChatSendDedupeResponse(i.dedupe, f);
			if (e || Y.entry && !isRpcSourceRegistered(Y.entry) && hasRpcSourceForController(f, Y.entry)) {
				K = true;
				q = e;
				return false;
			}
		}
		if (k !== getAgentEventLifecycleGeneration()) {
			Y.controller.abort(createAgentRunRestartAbortError());
			j.abort("restart");
			return false;
		}
		if (!isFutureDateTimestampMs(e?.payload.expiresAtMs, { nowMs: Date.now() })) {
			Y.controller.abort("timeout");
			j.abort("timeout");
			return false;
		}
		return true;
	};
	const commitChatWorkAdmission = async (r, a) => {
		let c = r;
		if (i.workerSessionPlacementService !== ae) throw new Error("Worker placement owner changed during chat admission; retry.");
		if (ae && a?.sessionId !== R) try {
			var l = _usingCtx();
			const e = l.u(o?.scope("detail.admission.placement_prepare"));
			return await withGoalChatPlacement(ae, R, (t) => {
				e?.finish();
				return commitChatWorkAdmission(c, t);
			});
		} catch (e) {
			l.e = e;
		} finally {
			l.d();
		}
		let u = false;
		for (;;) try {
			var d = _usingCtx();
			let r;
			let l;
			const p = d.u(o?.scope("detail.admission.current_session"));
			await withCurrentChatSendRetry(e, A, (o, d) => {
				I = d;
				e.assertCurrent?.();
				const p = resolveChatSendRequestConflict(e, I, A);
				if (p) throw new Error(p.message);
				if (!isPendingReservationCurrent()) return;
				const m = o.entry;
				const _ = m?.sessionId;
				re = m;
				const x = resolveChatSendRequestConflict({
					...e,
					session: {
						...n,
						entry: m
					}
				}, I, A);
				if (x) throw new Error(x.message);
				W = captureAdmittedChatSendSessionSettings({
					commit: true,
					entry: m,
					expectedPermissionMode: s.expectedPermissionMode,
					expectedToolOverrides: s.expectedToolOverrides
				});
				assertChatSendExclusiveAdmission(t, n);
				if (h && !m) throw new Error(`Session "${g}" was deleted while starting work. Retry.`);
				if (s.queueMode !== "steer" && T !== void 0) assertExpectedLeafActive(o, T, v, { allowEmptyAncestor: true });
				const S = v ?? y;
				if (S && _ !== S) throw new Error(`Session "${g}" changed while starting work. Retry.`);
				l = prepareChatSendAcpRefresh(e, c, o);
				if (l) return;
				const w = resolveSessionWorkStartError(g, m, {
					allowPendingWorkspace: true,
					providerReviewAcknowledgment: t.providerReviewAcknowledgment,
					runId: f
				});
				if (w) throw new Error(w);
				R = _ ?? y ?? f;
				if (!B) {
					G = s.queueMode === "steer" ? captureCurrentReplyMessageInjectionTarget(Y.entry?.input.mailbox.owner.id ?? C) : void 0;
					z = Y.entry?.input.mailbox.owner.active;
					B = true;
				}
				if (t.goalOperation?.action === "start" && !m && !v) {
					const e = ee;
					U = e.entry;
					ie = e.assertSkillSelection;
					R = U.sessionId;
				}
				if (i.workerSessionPlacementService !== ae) throw new Error("Worker placement owner changed during chat admission; retry.");
				const E = a?.sessionId !== R;
				if (ae && E) {
					u = true;
					return;
				}
				const D = a?.facts.prepareRead();
				if (D) {
					r = observeChatSendWork(D);
					return;
				}
				const O = a?.facts.current();
				const k = c?.meta ?? null;
				H = resolveCodexGoalAdmission(e, o, O, k);
				ne = !H && isLocalChatInputAdmission(e, o, U, O, k) && z === void 0 && resolveProjectedAgentRunProgressState({
					agentId: b,
					sessionId: R,
					sessionKeys: [g]
				}) === void 0;
				te = Boolean(t.goalOperation && ne);
				if (t.goalOperation && !te && !H) throw new SessionGoalOperationError("invalid", "Goal start or resume requires an idle built-in local session with recoverable history or a supported local or cloud-worker Codex session.");
			}).catch((e) => {
				if (isSessionTranscriptProjectionUnavailableError(e)) isPendingReservationCurrent();
				throw e;
			});
			if (l) {
				p?.finish();
				c = await l();
				continue;
			}
			if (!r) break;
			p?.mark("detail.admission.placement_refresh");
			await r();
		} catch (e) {
			d.e = e;
		} finally {
			d.d();
		}
		return u ? commitChatWorkAdmission(c) : void 0;
	};
	let Z;
	let releaseCapturedOperator = () => {};
	let oe = false;
	let Q;
	try {
		try {
			var se = _usingCtx();
			const r = se.u(o?.scope("detail.admission.work"));
			const a = se.u(o?.scope("detail.admission.operator"));
			const s = await prepareChatSendInterruptAdmission({
				operator: {
					...e,
					runId: f
				},
				interruptCapture: X,
				entry: Y.entry,
				assertCurrent: e.assertCurrent,
				assertSessionTargetCurrent,
				abortSignal: Y.controller.signal
			});
			Z = s.operator;
			releaseCapturedOperator = Z.release;
			const c = await prepareChatSendAcpMetadata(e);
			a?.mark("detail.admission.lifecycle_prepare");
			V = await beginSessionEffect({
				agentId: b,
				sourceInput: Y.entry?.input,
				isSettling: () => Y.entry?.adapter.terminalOutcomeObserved === true,
				target: J,
				storeWriterIdentities: [g, n.sessionTarget.storeKey],
				assertAllowed: () => {
					e.assertCurrent?.();
					assertSessionTargetCurrent();
					assertChatSendExclusiveAdmission(t, n);
				},
				revalidateAllowed: async () => {
					try {
						var e = _usingCtx();
						a?.finish();
						e.u(o?.scope("detail.admission.revalidate"));
						return await commitChatWorkAdmission(c);
					} catch (t) {
						e.e = t;
					} finally {
						e.d();
					}
				},
				onInterrupt: (e) => {
					Y.controller.abort(e);
				}
			});
			if (H && !Z.authority) throw new Error("Codex Goals require a current authenticated operator request.");
			Y.initializeTiming({
				now: Date.now(),
				timeoutMs: w
			});
			r?.finish();
			if (Y.controller.signal.aborted && !readChatSendDedupeResponse(i.dedupe, f)) j.abort(Y.entry?.adapter.abortStopReason ?? "rpc");
			Y.controller.signal.throwIfAborted();
			e.assertCurrent?.();
			Q = await consumeChatSendCurrent(e, () => resolveChatSendRequestConflict(e, I, A));
			if (X && !Q && !K && isPendingReservationCurrent() && Y.registered) oe = s.interrupt();
		} catch (e) {
			se.e = e;
		} finally {
			se.d();
		}
	} catch (t) {
		const n = j.read();
		j.clear();
		Y.cleanup();
		V?.release();
		releaseCapturedOperator();
		respondChatSendWorkAdmissionFailure(e, t, {
			attemptId: A,
			lifecycleGeneration: k,
			pendingReservation: n,
			requestIdentity: l,
			runAbort: Y
		}, I);
		return { ok: false };
	}
	if (Q) {
		j.clear();
		Y.cleanup();
		V.release();
		Z.release();
		r(false, void 0, Q);
		return { ok: false };
	}
	if (Y?.registered && !K && !readChatSendDedupeResponse(i.dedupe, f)) i.dedupe.set(`chat:${f}`, {
		ts: Date.now(),
		ok: true,
		requestIdentity: l
	});
	j.clear();
	const releaseAdmissionOwners = () => {
		V.release();
		Z.release();
	};
	if (K) {
		Y.cleanup();
		releaseAdmissionOwners();
		const e = q ?? readChatSendDedupeResponse(i.dedupe, f);
		if (e) {
			r(e.ok, e.payload, e.error, E);
			return { ok: false };
		}
		r(true, {
			runId: f,
			status: "in_flight"
		}, void 0, E);
		return { ok: false };
	}
	if (k !== getAgentEventLifecycleGeneration()) {
		if (Y.entry) Y.entry.adapter.abortStopReason = "restart";
		Y.controller.abort();
		Y.cleanup();
		releaseAdmissionOwners();
		if (!readChatSendDedupeResponse(i.dedupe, f)) j.abort(Y.entry?.adapter.abortStopReason ?? "restart");
		const e = readChatSendDedupeResponse(i.dedupe, f);
		r(e?.ok ?? true, e?.payload, e?.error, E);
		return { ok: false };
	}
	if (!Y.registered) {
		releaseAdmissionOwners();
		r(true, {
			runId: f,
			status: "in_flight"
		}, void 0, E);
		return { ok: false };
	}
	assertSourceAuthority = () => {
		Z.authority?.assertCurrent();
		assertAcceptedInputAuthority?.();
		assertSessionTargetCurrent();
		if (!V?.isActive()) throw new Error("Chat source preparation custody ended");
	};
	const ce = await prepareAdmittedChatSendDispatch({
		params: e,
		assertSessionTargetCurrent,
		runAbort: Y,
		admission: V,
		releaseCaller: () => {
			try {
				releaseChatSendCallerAuthority({
					operator: Z,
					request: t
				});
			} finally {
				n.releaseSessionStorage?.();
			}
		}
	});
	if (!ce) return { ok: false };
	const { releaseCallerAuthority: le, releaseGatewayRootContinuation: ue } = ce;
	const $ = V;
	const de = Y.entry;
	let fe = true;
	const pe = bindChatSendPreparedSession({
		runId: f,
		sessionKey: g,
		sourceRef: de,
		lifecycleGeneration: k,
		admission: { isActive: () => fe && $.isActive() }
	});
	const me = createChatSendWorkAdmission({
		admission: $,
		followRegistration: e.followRegistration,
		releaseCallerAuthority: le,
		releaseGatewayRootContinuation: ue,
		logGateway: i.logGateway,
		terminal: {
			target: n.sessionTarget,
			storePath: m,
			sourceRef: de,
			lifecycleRevision: re?.lifecycleRevision ?? U?.lifecycleRevision,
			isActive: () => $.isActive()
		}
	});
	const { cleanup: he, setDiscardPreparedMedia: ge } = createAdmittedChatSendCleanup({
		cleanupAbort: () => {
			fe = false;
			Y.cleanup();
		},
		releaseRetainedWork: me.release
	});
	const rejectSessionRoutingChanged = () => {
		he();
		clearAgentRunContext(f, k);
		respondChatSessionRoutingChanged(r);
	};
	claimAgentRunContext(f, {
		agentId: _.agentId ?? b,
		sessionKey: g,
		sessionId: R,
		lifecycleGeneration: k,
		...progressCardRefreshRunProjection(t.systemInputProvenance)
	});
	return {
		ok: true,
		value: {
			activeRunAbort: Y,
			operatorAuthority: Z.authority,
			armOperatorRunCancellation: Z.armCancellation,
			retireOperatorRunCancellation: Z.retireCancellation,
			admittedSessionSettings: W,
			admittedSessionId: R,
			...z ? { expectedActiveReplyOperation: z } : {},
			sourceRef: de,
			bindAcceptedInputAuthority: (e) => {
				assertAcceptedInputAuthority = () => {
					me.assertCommittedDestinationCurrent();
					e();
				};
			},
			onSessionPrepared: pe,
			initialSessionEntry: U,
			admittedSessionEntry: re,
			chatSendTraceAttributes: D,
			assertInitialSkillSelection: ie,
			cleanupAdmittedRun: he,
			finishAbortedChatSend: () => finishAbortedChatSend({
				context: i,
				respond: r,
				runId: f,
				lifecycleGeneration: k,
				stopReason: Y.entry?.adapter.abortStopReason,
				sourceRef: de,
				cleanup: he
			}),
			gatewayWorkAdmission: V,
			lifecycleGeneration: k,
			markInputAccepted: j.markInputAccepted,
			interruptedActiveRun: oe,
			messageInjectionTarget: G,
			originatingRoute: O,
			rejectSessionRoutingChanged,
			releaseSourceWorkAdmission: me.release,
			retainGatewayWorkAdmission: me.retain,
			recordFailureNotice: me.recordFailureNotice,
			withInputCommitPublication: me.withInputCommitPublication,
			acquireInputActor: () => me.acquireInputActor(),
			setPendingInputCleanup: me.setPendingInputCleanup,
			assertClientUploadAllowed: L.assertClientUploadAllowed,
			assertWorkAdmissionCurrent: () => assertChatSendWorkAdmissionCurrent({
				retainedWork: me,
				admission: $,
				lifecycleGeneration: k,
				controller: Y.controller,
				sourceRef: de
			}),
			localGoalAdmission: te,
			localInputAdmission: ne,
			codexGoalAdmission: H,
			setDiscardAbandonedPreparedMedia: ge
		}
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-setup.ts
/** Normalize, prepare, and exclusively admit one new chat.send request. */
async function prepareAndAdmitChatSend({ params: e, respond: t, context: n, client: r, hasCurrentClientAuthority: i, sessionMutationAuthorization: a }, o, s, c, l) {
	const u = c?.scope("admission");
	const d = a || i ? () => {
		a?.assertCurrent();
		if (i?.() === false) throw new Error("Gateway caller authority is no longer active.");
	} : void 0;
	const f = a?.withCurrent;
	const assertCurrentAsync = async () => f ? f(() => d?.()) : d?.();
	const p = normalizeChatSendRequest({
		params: e,
		client: r,
		...s?.trustedSystemInput ? { trustedSystemInput: true } : {},
		...s?.goalResume ? { goalResume: s.goalResume } : {},
		...s?.providerReviewAcknowledgment ? { providerReviewAcknowledgment: s.providerReviewAcknowledgment } : {}
	});
	const m = p instanceof Promise ? await p : p;
	if (!m.ok) {
		t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, m.error, m.reason ? { details: { reason: m.reason } } : void 0));
		return;
	}
	if (p instanceof Promise || m.value.goalOperation) try {
		d?.();
	} catch (e) {
		respondChatSendAdmissionError(e, t);
		return;
	}
	const h = await prepareChatSendSession({
		request: m.value,
		context: n,
		client: r,
		assertCurrent: d
	});
	if (!h.ok) {
		t(false, void 0, typeof h.error === "string" ? errorShape(ErrorCodes.INVALID_REQUEST, h.error) : h.error);
		return;
	}
	if (m.value.mentions) {
		const e = await n.mentionInbox?.validateRecipientsAsync(r, h.value.entry ? {
			sessionKey: h.value.sessionKey,
			agentId: h.value.agentId
		} : { agentId: h.value.agentId }, m.value.mentions.map((e) => e.profileId));
		if (!e?.ok) {
			t(false, void 0, e?.error ?? errorShape(ErrorCodes.UNAVAILABLE, "Human mentions are unavailable; reconnect and retry."));
			return;
		}
	}
	u?.mark("authority");
	const g = {
		request: m.value,
		session: h.value,
		respond: t,
		context: n,
		client: r,
		assertCurrent: d,
		assertCurrentAsync,
		withCurrent: f
	};
	if (!await runChatSendPreAdmission(g)) return;
	let _;
	try {
		_ = await qualifyChatSendSession(h.value, l);
	} catch (e) {
		respondChatSendAdmissionError(e, t);
		return;
	}
	const v = await prepareChatSendNativeRuntimeRestriction({
		...g,
		session: _
	});
	if (v) {
		t(false, void 0, v);
		return;
	}
	u?.mark("runAdmission");
	const y = await admitChatSend({
		...g,
		session: _,
		onAdmissionOwned: o,
		hasCurrentClientAuthority: i,
		withPreparedCurrent: a?.withPreparedCurrent,
		followRegistration: a?.followRegistration,
		diagnostics: c
	});
	if (!y.ok) return;
	u?.finish();
	return {
		request: m.value,
		session: _,
		admission: y.value
	};
}
//#endregion
//#region src/gateway/server-methods/chat-user-turn-recorder.ts
function createGatewayChatUserTurnController(e) {
	const { admission: t, request: n, session: r } = e;
	const i = readQueuedChatInputAdmission(r.clientRunId);
	const a = r.entry;
	const o = a?.modelOverrideFallbackOriginProvider;
	const s = a?.modelOverrideFallbackOriginModel;
	const c = (o && s && hasSessionActiveAutoModelFallback(a) ? {
		provider: o,
		model: s
	} : void 0) ?? r.resolvedSessionModel;
	const l = resolveSessionSubmittedModelRef(a);
	const u = {
		...c,
		...l ? { previous: l } : {}
	};
	const d = isProgressCardRefreshInputProvenance(n.systemInputProvenance);
	const f = n.goalOperation?.action === "resume" ? void 0 : gatewayClientSenderFields(e.client).sender;
	const p = i ? i.requesterProfile?.id : e.client?.authenticatedUserProfile?.profileId;
	const m = e.client?.internal?.agentToolCaller;
	const h = captureRequesterOrigin({
		requesterOrigin: m?.requesterOrigin,
		sessionKey: r.sessionKey,
		operatorProfileId: m ? void 0 : t.operatorAuthority?.profileId,
		messageProvider: INTERNAL_MESSAGE_CHANNEL,
		agentAccountId: t.originatingRoute.accountId,
		chatType: "direct",
		messageThreadId: t.originatingRoute.messageThreadId,
		senderId: m ? void 0 : f?.id,
		senderName: m ? void 0 : f?.name
	});
	const g = e.mentionInbox;
	const _ = buildRunUserTurnIdempotencyKey(r.clientRunId);
	const v = i?.target.message["__openclaw"]?.humanMentions ?? n.mentions;
	const y = !e.client?.internal?.syntheticClient && (!n.systemInputProvenance || n.systemInputProvenance.kind === "external_user") ? normalizeMessageClientSources([n.clientInfo]) : [];
	const b = {
		...e.transcript,
		...n.goalOperation?.action === "resume" ? { display: false } : {},
		text: n.rawMessage,
		requesterOrigin: h,
		...n.workContext ? { workContext: n.workContext } : {},
		...n.mentions ? { mentions: n.mentions } : {},
		timestamp: r.now,
		idempotencyKey: _,
		...n.p.replyToId ? { replyToId: n.p.replyToId } : {},
		...f ? { sender: f } : {},
		...y.length ? { transport: { clients: y } } : {},
		...hasGatewayAdminScope(e.client) ? { senderIsOwner: true } : {},
		provenance: n.systemInputProvenance ?? (e.client?.internal?.syntheticClient ? void 0 : { kind: "external_user" })
	};
	const x = n.p.replyToId ? resolveChatSendReplyContext({
		replyToId: n.p.replyToId,
		cfg: r.cfg,
		agentId: r.agentId,
		sessionKey: r.sessionKey,
		sessionEntry: r.entry,
		storePath: r.storePath,
		userSenderLabel: n.clientInfo?.displayName,
		warn: e.warn
	}) : void 0;
	let S = x ? x.then((e) => ({
		...b,
		...e.ReplyToBody ? { replyToPreview: {
			text: e.ReplyToBody,
			...e.ReplyToSender ? { senderLabel: e.ReplyToSender } : {}
		} } : {}
	})) : Promise.resolve(b);
	let C = false;
	let w;
	const onPersistenceError = (t) => e.warn(`gateway user transcript persistence failed: ${formatForLog(t)}`);
	const captureWorkerGoalSource = () => captureWorkerTurnInputSource({
		agentId: r.agentId,
		sessionId: getRpcSourceIdentity(t.sourceRef).sessionId,
		sessionKey: r.sessionKey
	});
	const prepareWorkerGoalSource = async () => prepareSessionSourceAuthority(captureWorkerGoalSource());
	const T = t.codexGoalAdmission === "worker" ? Object.assign(() => captureWorkerGoalSource()(), {
		prepareSessionSource: prepareWorkerGoalSource,
		prepareSessionSourceScope: prepareWorkerGoalSource
	}) : void 0;
	const E = createUserTurnTranscriptRecorder({
		onMessagePersisted: e.onMessagePersisted,
		...i ? { message: i.target.message } : {},
		pendingInputRequestFingerprint: i?.requestFingerprint ?? n.goalOperation?.requestFingerprint ?? (f?.id ? sha256Hex(stableStringify([
			{
				...n.p,
				sessionId: getRpcSourceIdentity(t.sourceRef).sessionId,
				expectedLeafEntryId: void 0
			},
			f.identity ?? f.id,
			hasGatewayAdminScope(e.client)
		])) : void 0),
		...n.goalOperation ? { sessionTurnMutation: {
			kind: "goal",
			operation: n.goalOperation,
			runId: r.clientRunId,
			...e.goalCommitGuard,
			assertCurrent: t.codexGoalAdmission === "worker" ? composeSessionSourceAssertion([e.goalCommitGuard?.assertCurrent, T]) : e.goalCommitGuard?.assertCurrent
		} } : {},
		input: b,
		resolveInput: async () => {
			try {
				var e = _usingCtx();
				e.u(observeDiagnosticsTimelinePhases("persist.resolveInput"));
				return await S;
			} catch (t) {
				e.e = t;
			} finally {
				e.d();
			}
		},
		target: () => {
			const e = r.sessionTarget;
			const n = getRpcSourceIdentity(t.sourceRef).sessionId;
			return {
				sessionId: n,
				expectedSessionId: n,
				initialSessionEntry: t.initialSessionEntry,
				sessionKey: e.storeKey,
				sessionEntry: void 0,
				storePath: e.storePath,
				agentId: r.agentId,
				config: r.cfg
			};
		},
		...(t.localInputAdmission || e.commitInitialInput) && !d ? { sessionLifecyclePatch: { lastInteractionAt: e.startedAt } } : {},
		errorContext: "gateway chat user turn transcript",
		assertOriginalInputCommit: composeSessionSourceAssertion([e.assertOriginalInputCommit, t.operatorAuthority?.assertCurrent]),
		beforeMessageWrite: (t) => {
			if (i) return t.message;
			const r = t.message.idempotencyKey === _;
			const a = runAgentHarnessBeforeMessageWriteHook(t);
			if (r && a?.role === "user") {
				const t = a;
				const r = { ...asOptionalRecord(Reflect.get(a, "__openclaw")) };
				delete r.chatRequestIdentity;
				delete r.suppressCommandInterpretation;
				delete r.chatSendDelivery;
				delete r.chatSendRuntime;
				delete r.modelSelection;
				const i = !e.client?.internal?.syntheticClient && !C && t.display !== false && t.excludeFromContext !== true && (!t.provenance || t.provenance.kind === "external_user");
				return {
					...a,
					...C ? { excludeFromContext: true } : {},
					__openclaw: {
						...r,
						...n.requestIdentity ? { chatRequestIdentity: n.requestIdentity } : {},
						...n.suppressCommandInterpretation ? { suppressCommandInterpretation: true } : {},
						...n.p.deliver !== void 0 || n.explicitOrigin ? { chatSendDelivery: {
							deliver: n.p.deliver,
							originatingChannel: n.p.originatingChannel,
							originatingTo: n.p.originatingTo,
							originatingAccountId: n.p.originatingAccountId,
							originatingThreadId: n.p.originatingThreadId
						} } : {},
						...n.p.thinking !== void 0 || n.p.fastMode !== void 0 || n.p.fastAutoOnSeconds !== void 0 || n.p.timeoutMs !== void 0 ? { chatSendRuntime: {
							thinking: n.p.thinking,
							fastMode: n.p.fastMode,
							fastAutoOnSeconds: n.p.fastAutoOnSeconds,
							timeoutMs: n.p.timeoutMs
						} } : {},
						...i ? { modelSelection: u } : {},
						...C ? { contextFreeCommand: true } : {}
					}
				};
			}
			return a;
		},
		onPersistenceError,
		...v && p && g ? { onOriginalInputCommitted: ({ message: t, anchor: a }) => {
			const o = t["__openclaw"]?.humanMentions;
			const s = extractTextFromChatContent(t.content, {
				joinWith: "\n",
				normalizeText: (e) => e
			}) ?? "";
			const c = i ? v : v.filter((e) => Array.isArray(o) && o.some((t) => {
				const r = asOptionalRecord(t);
				return r?.profileId === e.profileId && r.start === e.start && r.end === e.end && s.slice(e.start, e.end) === n.rawMessage.slice(e.start, e.end);
			}));
			if (!c.length) {
				e.warn("Human mentions skipped because the committed text no longer contains the selected tokens.");
				return;
			}
			w = g.recordCommittedInputAsync({
				sourceId: _,
				committedSource: {
					generation: a.generation,
					sequence: a.rawSeq,
					timestamp: t.timestamp
				},
				agentId: a.agentId,
				sessionKey: r.sessionKey,
				sessionId: a.sessionId,
				messageId: a.entryId,
				senderProfileId: p,
				recipientProfileIds: c.map((e) => e.profileId),
				excerpt: s
			});
			w.catch(onPersistenceError);
		} } : {}
	});
	bindUserTurnInputActor(E, {
		phase: "acceptInput",
		acquire: t.acquireInputActor
	});
	const persist = async (e) => {
		try {
			var n = _usingCtx();
			if (e?.contextFreeCommand === true && !E.hasPersisted()) C = true;
			if (t.codexGoalAdmission && !E.hasPersisted()) return;
			const i = await measureDiagnosticsTimelineSpan("gateway.chat_send.persist_user_transcript", () => E.persistFallback({ sessionLifecyclePatch: e?.sessionLifecyclePatch }), {
				phase: "agent-turn",
				config: r.cfg,
				attributes: t.chatSendTraceAttributes
			});
			n.u(observeDiagnosticsTimelinePhases("persist.mentionPublication"));
			await w;
			return i;
		} catch (e) {
			n.e = e;
		} finally {
			n.d();
		}
	};
	return {
		baseInput: b,
		persist,
		persistBestEffort: async (e) => {
			return await persist(e).catch(() => void 0);
		},
		recorder: E,
		replyContextFieldsPromise: x,
		getSessionInitializationOptions: () => ({
			requestedSessionId: r.requestedSessionId,
			resumeRequestedSession: n.reconnectResumeRequested,
			...t.localInputAdmission || t.codexGoalAdmission ? {
				expectedExistingSessionId: t.admittedSessionId,
				pinExpectedExistingSession: true,
				newlyCreatedSessionId: t.initialSessionEntry?.sessionId,
				...E.hasPersisted() && !d ? { recordedSessionActivity: {
					sessionId: t.admittedSessionId,
					sessionKey: r.sessionKey,
					at: e.startedAt
				} } : {}
			} : r.entry?.sessionId ? { expectedExistingSessionId: r.entry.sessionId } : {}
		}),
		setInputPromise: (e) => {
			const t = S;
			S = Promise.all([t, e]).then(([e, t]) => ({
				...e,
				...t,
				requesterOrigin: e.requesterOrigin
			}));
		}
	};
}
//#endregion
//#region src/gateway/server-methods/chat-send-input-dispatch.ts
const mediaDocumentContextLoader = createLazyImportLoader(() => import("./file-context-e88njo_1.mjs"));
/** Owns input custody and ACK timing through the detached dispatch handoff. */
async function handleChatSendWithStorage(e, t, n, r, i) {
	try {
		var a = _usingCtx();
		const { req: l, respond: u, context: d, client: f, hasCurrentClientAuthority: p, sessionMutationAuthorization: m, sessionMutationCommitGuard: h } = e;
		const g = m?.takeRelease?.() ?? m?.release;
		const _ = a.u(readChatSendDiagnostics(e) ?? startChatSendDiagnostics(d.logGateway));
		const v = await prepareAndAdmitChatSend(e, t, r, _, i ? () => i.release() : void 0).catch((e) => {
			g?.();
			throw e;
		});
		if (!v) {
			g?.();
			return;
		}
		i?.retain();
		const { request: y, session: b, admission: x } = v;
		x.setPendingInputCleanup(() => g?.());
		const S = a.u({
			dispatched: false,
			[Symbol.dispose]() {
				if (!this.dispatched) x.cleanupAdmittedRun();
			}
		});
		const { systemInputProvenance: C, reconnectResumeRequested: w } = y;
		const { clientRunId: T, cfg: E, storePath: D, entry: O, sessionKey: k, sessionRoutingChanged: A, selectedAgent: j } = b;
		const { activeRunAbort: M, admittedSessionId: N, chatSendTraceAttributes: P, finishAbortedChatSend: F, interruptedActiveRun: I, lifecycleGeneration: L, messageInjectionTarget: ee } = x;
		_.setRunIdentity(N, T);
		const R = _.scope("attachments");
		const z = await prepareChatSendAttachments({
			...v,
			respond: u,
			context: d
		});
		if (!z.ok) return;
		const B = bindChatSendPreparedMediaCustody({
			admission: x,
			attachments: z.value
		});
		const settleInterruptedPreparation = () => {
			if (M.controller.signal.aborted) F();
			else if (A(d.getRuntimeConfig())) x.rejectSessionRoutingChanged();
			else return false;
			return true;
		};
		if (settleInterruptedPreparation()) return;
		const { imageOrder: V, prepareAttachmentsMs: te } = z.value;
		R?.mark("authority");
		const ne = {
			runId: T,
			sessionKey: k,
			spawnedBy: O?.spawnedBy,
			client: f,
			isCurrent: p,
			inputProvenance: C,
			hasExplicitOrigin: y.explicitOrigin !== void 0,
			hasRestoredCronContinuation: O?.cronRunContinuation !== void 0,
			isIncognitoEntry: O?.incognito === true,
			isReconnectResume: w,
			isSystemGenerated: y.suppressCommandInterpretation || y.systemProvenanceReceipt !== void 0,
			turnKind: y.turnKind
		};
		const H = n?.resolve(ne);
		const U = Date.now();
		const re = l.method === "sessions.create";
		let W = x.localInputAdmission || re;
		let ie = false;
		let G;
		let K = void 0;
		let q;
		try {
			try {
				var o = _usingCtx();
				const assertCustodyLifetimeCurrent = () => {
					x.assertWorkAdmissionCurrent();
					if (A(d.getRuntimeConfig())) throw new Error("Session routing changed before input admission; refresh and retry.");
				};
				let e;
				const t = createChatSendPendingInputAdmission({
					runId: T,
					expectedProfileId: l.expectedProfileId,
					sessionMutationAuthorization: m,
					sessionMutationCommitGuard: h,
					assertCustodyLifetimeCurrent,
					assertClientUploadAllowed: x.assertClientUploadAllowed
				});
				const i = composeSessionSourceAssertion([h], (e) => {
					x.assertClientUploadAllowed?.();
					assertCustodyLifetimeCurrent();
					if (W) m?.assertCurrent();
					e();
				});
				const a = r?.stageCreatedInput ? createDynamicSessionSourceAssertion(() => e ?? i, () => {
					throw new Error("Chat input custody changed before admission");
				}) : i;
				a();
				const J = y.goalOperation ? createChatSendGoalCommitGuard({
					admission: x,
					session: b,
					client: f,
					context: d,
					sessionMutationAuthorization: m,
					sessionMutationCommitGuard: h
				}) : void 0;
				const Y = x.codexGoalAdmission ? createDeferredCore() : void 0;
				const X = createGatewayChatUserTurnController({
					onMessagePersisted: Y?.resolve,
					...v,
					client: f,
					commitInitialInput: re,
					transcript: r?.transcript,
					startedAt: U,
					warn: (e) => d.logGateway.warn(e),
					mentionInbox: d.mentionInbox,
					assertOriginalInputCommit: composeSessionSourceAssertion([a, re ? m?.assertCurrent : void 0]),
					goalCommitGuard: J
				});
				const { persist: ae, recorder: Z, replyContextFieldsPromise: oe } = X;
				let Q = !O;
				const withUserTurnInputPublication = (n) => x.withInputCommitPublication(n, (n, i) => {
					G = {
						sessionId: i.sessionId,
						lifecycleRevision: i.lifecycleRevision
					};
					if (!O) {
						m?.recordCreatedSession?.({
							agentId: b.agentId,
							sessionKey: k,
							storePath: D,
							sessionId: N,
							lifecycleRevision: i.lifecycleRevision,
							readSource: n,
							entry: i
						});
						Q = false;
					}
					if (r?.stageCreatedInput) e = t.assertAdmittedCurrent;
					x.bindAcceptedInputAuthority(t.assertAdmittedCurrent);
				});
				const persistGatewayUserTurnTranscript = (...e) => withDiagnosticsTimelineObserver(_.observeSpan, () => withUserTurnInputPublication(() => ae(...e)));
				const persistGatewayUserTurnTranscriptBestEffort = (...e) => withUserTurnInputPublication(() => X.persistBestEffort(...e));
				B(Z);
				R?.mark("preparation");
				const se = prepareChatSendUserTurn({
					...v,
					attachments: z.value,
					client: f,
					logGateway: d.logGateway,
					getConfig: d.getRuntimeConfig,
					assertInputCurrent: a,
					userTurn: X
				});
				const { ctx: ce, isInternalTextSlashCommandTurn: le } = se;
				W = !readQueuedChatInputAdmission(T) && (re && !requiresRuntimeApprovedChatInput(f) || x.localInputAdmission && y.p.queueMode !== "steer" && !ee && !le && (x.localGoalAdmission || X.baseInput.display !== false && (!C || C.kind === "external_user")));
				x.setPendingInputCleanup(async () => {
					try {
						const e = Z.getPendingInputMessage?.() && !Z.isPendingInputConsumed?.();
						const t = "cancelled";
						Z.finishPendingInput?.(t);
						if (e && M.controller.signal.aborted) {
							const e = resolveChatAbortDiagnosticReason(M.controller.signal, M.entry?.adapter);
							d.logGateway.info(`chat pending input aborted: ${e} (${t})`, {
								runId: T,
								sessionKey: k,
								sessionId: N,
								agentId: j.agentId,
								disposition: t,
								reason: e
							});
						}
						await Z.waitForPendingInputSettlement?.();
					} finally {
						q?.release();
						g?.();
						se.discardUnreferencedMedia(Z.getPendingInputMessage?.()).catch((e) => d.logGateway.warn(`Failed to discard unused chat media: ${String(e)}`));
					}
				});
				R?.mark("persist");
				let ue;
				if (x.codexGoalAdmission || Boolean(O?.sessionId && X.baseInput.display !== false && (!C || C.kind === "external_user" || r?.stageCreatedInput === true) && !le && !y.goalOperation && !W)) try {
					var s = _usingCtx();
					ie = true;
					const n = s.u(_.scope("detail.persist.stage"));
					const i = await withDiagnosticsTimelineObserver(_.observeSpan, () => Z.stageApproved?.({
						...t,
						recoverySource: captureQueuedOperatorRecoverySource(x.operatorAuthority)
					}));
					n?.finish();
					if (Z.isPendingInputConsumed?.()) {
						const e = await readChatSendRetryComparison(b);
						a();
						x.cleanupAdmittedRun();
						clearAgentRunContext(T, L);
						u(true, {
							runId: T,
							status: "ok",
							...e?.messageSeq !== void 0 ? { messageSeq: e.messageSeq } : {}
						}, void 0, {
							cached: true,
							runId: T
						});
						return;
					}
					if (!i) throw new Error("Chat input was not durably admitted; refresh and retry.");
					if (r?.stageCreatedInput) e = t.assertAdmittedCurrent;
					x.bindAcceptedInputAuthority(t.assertAdmittedCurrent);
					ue = Z.getPendingInputMessage?.();
					emitSessionsChanged(d, {
						sessionKey: k,
						agentId: j.agentId,
						reason: "send"
					}, { accessChanged: false });
				} catch (e) {
					s.e = e;
				} finally {
					s.d();
				}
				let $;
				if (W) try {
					var c = _usingCtx();
					ie = true;
					const e = c.u(_.scope("detail.persist.transcript"));
					const t = await persistGatewayUserTurnTranscript({ sessionLifecyclePatch: le ? void 0 : {
						...deriveGatewaySessionLifecycleSnapshot({ event: {
							runId: T,
							ts: U,
							data: { phase: "start" }
						} }),
						activeWriterRunId: T,
						lifecycleRunId: T,
						lastRunId: void 0,
						lastInteractionAt: U
					} });
					e?.finish();
					ue = t?.message;
					const n = y.goalOperation;
					if (n) {
						const e = t?.sessionTurnMutationResult;
						$ = e?.result;
						if (!$) {
							$ = await lookupSessionGoalOperation({
								sessionKey: k,
								storePath: D,
								agentId: b.agentId,
								expectedSessionId: N,
								operation: n
							});
							a();
							J?.assertCurrent();
						}
						if ($ && (!t || e?.replayed)) {
							x.cleanupAdmittedRun();
							clearAgentRunContext(T, L);
							u(true, {
								...$,
								replayed: true
							}, void 0, {
								cached: true,
								runId: T
							});
							return;
						}
						if (!$ || !t?.sessionEntry) throw new Error("Goal and its input were not durably admitted.");
						if (x.initialSessionEntry) await recordSessionCreated(b.cfg, {
							sessionKey: k,
							agentId: b.agentId,
							entry: t.sessionEntry
						});
						await publishCommittedSessionGoalChange(d, {
							sessionKey: k,
							agentId: b.agentId,
							entry: t.sessionEntry,
							actor: gatewayClientSessionCreator(f),
							summary: `goal ${n.action}`
						});
					}
					if (!t) throw new Error("Chat input was not durably admitted; refresh and retry.");
					if (L !== getAgentEventLifecycleGeneration()) {
						if (M.entry) M.entry.adapter.abortStopReason = "restart";
						M.controller.abort(createAgentRunRestartAbortError());
					}
					if (M.controller.signal.aborted) {
						F();
						return;
					}
					if (A(d.getRuntimeConfig())) {
						x.rejectSessionRoutingChanged();
						return;
					}
				} catch (e) {
					c.e = e;
				} finally {
					c.d();
				}
				await recordSessionOperatorSource({
					agentId: b.agentId,
					sessionKey: k,
					storePath: D,
					authority: x.operatorAuthority,
					assertCurrent: x.assertWorkAdmissionCurrent,
					log: d.logGateway
				});
				if (ue) se.applyApprovedText(extractTextFromChatContent(ue.content, {
					joinWith: "\n",
					normalizeText: (e) => e
				}) ?? "");
				const de = o.u(_.scope("detail.persist.authority"));
				q = await createChatSendDashboardAuthority({
					admission: x,
					session: b,
					client: f,
					context: d,
					hasCurrentClientAuthority: p,
					sessionMutationCommitGuard: h,
					sessionMutationAuthorization: m,
					externalAuthorityAdmission: n,
					externalAdmissionParams: ne
				});
				de?.finish();
				const fe = q.assertReadCurrent;
				q.bindPromptRecorder(Z);
				R?.mark("preparation");
				if (ee) invalidateSkillAuthoringForOtherRequester(k, f?.internal?.syntheticClient ? void 0 : f?.authenticatedUserProfile?.profileId);
				const pe = ee && !le && ce.media?.length ? await mediaDocumentContextLoader.load().then(async (e) => ({
					status: "rendered",
					...await e.renderInboundDocumentContext({
						ctx: ce,
						cfg: b.cfg
					})
				})).catch((e) => {
					mediaDocumentContextLoader.clear();
					logVerbose(`steer document render failed, injecting raw content: ${formatErrorMessage(e)}`);
					return { status: "failed" };
				}) : void 0;
				if (settleInterruptedPreparation()) return;
				const me = createChatSendMessageInjectionStarter({
					diagnostics: _,
					operatorAuthority: x.operatorAuthority,
					target: ee,
					sourceRef: x.sourceRef,
					abortSignal: M.controller.signal,
					request: y,
					session: b,
					admittedSessionSettings: x.admittedSessionSettings,
					turn: se,
					imageOrder: V,
					documentContext: pe,
					userTurnTranscriptRecorder: Z,
					logGateway: d.logGateway,
					assertCurrent: l.expectedProfileId === void 0 && !x.assertClientUploadAllowed && !isProgressCardRefreshInputProvenance(C) ? void 0 : a
				});
				R?.mark("effects");
				const { serverTiming: he, chatSendTiming: ge, ackReadyEvent: _e } = prepareChatSendAckTiming({
					client: f,
					request: y,
					session: b,
					prepareAttachmentsMs: te,
					chatSendTraceAttributes: P
				});
				if (r?.beforeDispatch) {
					a();
					K = await r.beforeDispatch({
						runId: T,
						assertCurrent: a,
						assertWorkAdmissionCurrent: () => {
							x.assertClientUploadAllowed?.();
							x.assertWorkAdmissionCurrent();
						}
					});
					a();
				}
				d.addChatRun(T, {
					sessionKey: k,
					agentId: j.agentId,
					clientRunId: T,
					...ge ? { chatSendTiming: ge } : {}
				});
				const ve = Z.getAdmissionReceipt?.();
				const ye = {
					...$,
					runId: T,
					status: "started",
					...ve ? { messageSeq: ve.activeMessagePosition + 1 } : {},
					...I ? { interruptedActiveRun: true } : {},
					...he ? { serverTiming: he } : {}
				};
				emitDiagnosticsTimelineEvent(_e(ye.status), { config: E });
				a();
				x.setDiscardAbandonedPreparedMedia(void 0);
				R?.mark("response");
				x.markInputAccepted();
				if (!x.codexGoalAdmission) u(true, ye, void 0, { runId: T });
				R?.finish();
				_.acknowledge();
				d.recordClientActivity?.(f);
				const be = ge?.ackedAtMs ?? performance.now();
				K = void 0;
				const xe = {
					...v,
					diagnostics: _,
					admissionStartedAt: U,
					attachments: z.value,
					client: f,
					context: d,
					toolsAllow: r?.toolsAllow,
					prepareAssistantTranscriptMessage: r?.prepareAssistantTranscriptMessage,
					skillLibrary: {
						sessionKey: k,
						owner: {
							client: f,
							context: d,
							sessionMutationCommitGuard: () => {
								h?.();
								x.assertWorkAdmissionCurrent();
							}
						},
						isHumanTurn: !r && !C && !w && y.turnKind === "main"
					},
					cronCreatorAuthority: H,
					assertDashboardReadCurrent: fe,
					getSessionInitializationOptions: createChatSendSessionInitialization({
						sessionKey: k,
						agentId: b.agentId,
						authorization: m,
						needsCreationBinding: Q,
						getSessionInitializationOptions: X.getSessionInitializationOptions
					}),
					externalAuthorityAdmission: n,
					injection: {
						beginCapturedMessageInjection: me,
						replyContextFieldsPromise: oe
					},
					timing: {
						chatSendAckedAtMs: be,
						chatSendTiming: ge
					},
					turn: se,
					userTurn: {
						...X,
						persist: persistGatewayUserTurnTranscript,
						persistBestEffort: persistGatewayUserTurnTranscriptBestEffort
					}
				};
				const Se = withoutGatewayToolCallerIdentity(() => runOutsideOperatorToolGatewayAuthority(() => startChatDispatch(xe)));
				S.dispatched = true;
				if (Y) await acknowledgeCodexGoal({
					dispatch: xe,
					committed: Y.promise,
					dispatched: Se,
					ackPayload: ye,
					respond: u
				});
			} catch (e) {
				o.e = e;
			} finally {
				o.d();
			}
		} catch (e) {
			q?.release();
			K?.();
			await handleChatSendSetupError({
				cacheResult: y.goalOperation === void 0 && !ie,
				committedInput: G,
				admission: x,
				context: d,
				error: e,
				respond: u,
				session: b
			});
		}
	} catch (e) {
		a.e = e;
	} finally {
		a.d();
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-storage.ts
async function runChatSendWithStorage(e, t) {
	const n = e.params.sessionKey;
	if (typeof n !== "string" || !isIncognitoSessionKey(n)) return t();
	const r = e.context.getRuntimeConfig();
	const i = resolveRequestedSessionAgentId(r, n, typeof e.params.agentId === "string" ? e.params.agentId : void 0);
	if (!i.ok) {
		e.respond(false, void 0, i.error);
		return;
	}
	let a = true;
	let o = false;
	const assertCurrent = () => {
		if (!a) throw new Error("Chat session storage admission ended");
	};
	const s = await acquireSessionActorStorage({
		sessionKey: resolveChatSendSessionKey(r, n, i.agentId),
		agentId: i.agentId
	}, {
		lifetime: {
			assertCurrent,
			assertReadable: assertCurrent
		},
		authority: {
			assertCurrent,
			authorize: assertCurrent
		}
	});
	if (!s) {
		respondError(e.respond, ErrorCodes.INVALID_REQUEST, `Incognito session "${resolveChatSendSessionKey(r, n, i.agentId)}" was not found.`);
		return;
	}
	const release = () => {
		if (!a) return;
		a = false;
		s.actor.release().catch((t) => {
			e.context.logGateway.warn(`Chat session storage cleanup failed: ${String(t)}`);
		});
	};
	try {
		await runWithSessionActorStorage(s, () => t({
			release,
			retain() {
				o = true;
			}
		}));
	} finally {
		if (!o) release();
	}
}
//#endregion
//#region src/gateway/server-methods/chat-send-handler.ts
async function handleChatSendWithOptions(e, t, n, r) {
	await runChatSendWithStorage(e, (i) => handleChatSendWithStorage(e, t, n, r, i));
}
async function handleChatSend(e, t, n) {
	await handleChatSendWithOptions(e, t, n);
}
/** The ordinary chat owner retains the exact human-reviewed continuation through settlement. */
async function handleProviderReviewContinuationChat(e, t) {
	let n = false;
	try {
		await handleChatSendWithOptions(e, async () => {
			n = true;
			return true;
		}, void 0, { providerReviewAcknowledgment: t });
	} finally {
		if (!n) retireProviderReviewAcknowledgment(t);
	}
}
/** Operator Resume admits one hidden internal continuation with the Goal transition. */
async function handleSessionGoalResumeChat(e, t) {
	await handleChatSendWithOptions(e, void 0, void 0, { goalResume: t });
}
/** Dispatches Gateway-authored system input without widening the public chat-send contract. */
async function handleTrustedInternalChatSend(e, t, n) {
	await handleChatSendWithOptions(e, t, void 0, {
		...n,
		trustedSystemInput: true
	});
}
//#endregion
export { isDirectChatGoalSession as a, handleTrustedInternalChatSend as i, handleProviderReviewContinuationChat as n, lookupSessionGoalOperation as o, handleSessionGoalResumeChat as r, handleChatSend as t };