UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9,553 lines • 365 kB
import { g as readStringValue, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty, t as hasNonEmptyString } from "./string-coerce-CCIiB4H7.mjs";
import { T as parseStrictInteger, d as asPositiveFiniteNumber, l as asNonNegativeFiniteNumber, m as asSafeIntegerInRange, s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { t as expandHomePrefix } from "./home-dir-EKmgmdPG.mjs";
import { a as asOptionalRecord, i as asOptionalObjectRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { a as extractErrorCode, p as toErrorObject, s as formatErrorMessage } from "./error-coercion-hDrHOSGy.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { m as normalizeTrimmedStringList, r as filterStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { i as truncateWithMarker } from "./utf16-slice-CuDyEXgS.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { b as formatRawAssistantErrorForUi } from "./redact-Mj7pppxC.mjs";
import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs";
import { t as formatErrorMessage$1 } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { c as withPluginRuntimeGatewayContextResolver, o as getPluginRuntimeGatewayRequestScope, r as getInProcessGatewayRequestContext } from "./gateway-request-scope-BvvDhs5D.mjs";
import { o as getGatewayContextResolver, t as bindGatewayContextResolver } from "./gateway-context-binding-BdXZoMU9.mjs";
import { n as buildModelCatalogRef } from "./model-catalog-refs-Bk2MNoCv.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { _ as resolveDefaultAgentId, x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { o as wrapSqliteWorkerError } from "./sqlite-worker-error-DEIJgRIz.mjs";
import { p as isDiagnosticsEnabled, s as emitTrustedDiagnosticEvent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { h as createChildDiagnosticTraceContext, s as measureDiagnosticsTimelineSpan, y as freezeDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs";
import { a as hasBillableUsage, f as toDiagnosticUsage, n as deriveContextPromptTokens, o as hasNonzeroUsage } from "./usage-CHLnzpJG.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.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 { t as createDedupeCache } from "./dedupe-DxT0h2gR.mjs";
import { w as hasPendingAutomationContinuation } from "./run-history-detail-rOrjKG4Z.mjs";
import { T as selectLiveRuntimeConfig, h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { t as DEFAULT_CONTEXT_TOKENS } from "./defaults-BWyoTPqn.mjs";
import { i as resolveSessionAuthProfileOverrideSource, r as resolveCollapsedSessionAuthPinSource } from "./auth-profile-override-provenance-B7WULxR7.mjs";
import { a as resolveSessionModelOverrideRouteResolution, n as hasSessionAutoModelFallbackProvenance } from "./model-override-provenance-DeIPDBg8.mjs";
import { i as markAutoFallbackPrimaryProbe, n as entryMatchesAutoFallbackPrimaryProbe, t as clearAutoFallbackPrimaryProbeSelection, u as resolveAutoFallbackPrimaryProbe } from "./agent-scope-BwB8YH6y.mjs";
import { i as classifyAgentRunTerminalOutcome } from "./agent-run-terminal-outcome-CurjWZiA.mjs";
import { _ as registerAgentRunContext, b as releaseAgentRunContext, i as claimAgentRunContext, l as getAgentRunContext, o as clearAgentRunContext } from "./agent-run-registry-D7vkrqFT.mjs";
import { C as withAgentRunLifecycleGeneration, a as emitAgentEvent, d as getAgentEventLifecycleGeneration, h as onAgentEventForRun, r as captureAgentRunLifecycleGeneration, t as assertAgentRunLifecycleGenerationCurrent } from "./agent-events-BdfWYmot.mjs";
import { o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { a as drainAgentRunTerminalWrites, i as clearAgentRunTerminalWriteContext, n as bindAgentRunTerminalWriteSettlement } from "./agent-run-terminal-writes-eqeCFAOx.mjs";
import { a as formatThinkingLevelClampNotice, f as normalizeVerboseLevel, p as resolveEffectiveResponseUsage } from "./thinking.shared-jmDGV33r.mjs";
import { o as resolveCliBackendConfig } from "./cli-backends-B8PrIwPC.mjs";
import { n as OPENCLAW_AGENT_RUNTIME_ID } from "./agent-runtime-id-D8s1CaYB.mjs";
import { t as captureRuntimeConfig } from "./runtime-source-projection-DTwMWCo9.mjs";
import { C as findModelInCatalog } from "./model-selection-shared-9Kz63Hhm.mjs";
import { t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-constants-CkbqRgGl.mjs";
import { t as GatewayDrainingError } from "./gateway-work-admission-79pid1hQ.mjs";
import { t as normalizeChatType } from "./chat-type-CL5nBDaO.mjs";
import { a as readUserTurnPromptReactionSource, i as readPendingUserTurnTranscriptAdmission } from "./user-turn-transcript-admission-BdVewOwR.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import { a as resolveMessageChannel } from "./message-channel-normalize-CFHSufeo.mjs";
import { l as revokeMessageActionTurnCapability } from "./message-action-turn-capability-CQk0hiot.mjs";
import { n as SILENT_REPLY_TOKEN } from "./tokens-CcE6ESvH.mjs";
import { t as assertAdmittedRunOperatorAuthority } from "./admitted-run-context-D3Jvk_f_.mjs";
import { a as isInternalMessageChannel, o as isMarkdownCapableMessageChannel } from "./message-channel-DTYVLJT1.mjs";
import { t as resolveGroupSessionKey } from "./group-UpjSVFeV.mjs";
import { l as withSystemEventOwner } from "./system-event-ownership-zDxyv2EM.mjs";
import { i as buildAgentRunTerminalOutcomeFromLifecycleEvent } from "./agent-run-terminal-outcome-wduf2occ.mjs";
import { l as isCliPartialOutputRejected, u as isFailoverError } from "./error-BCRqSFIY.mjs";
import { d as isAgentRunSupersededAbortReason, f as isSessionPlacementSettlementClosedError, l as isAgentRunDirectAbortReason, m as resolveAgentRunErrorLifecycleFields, p as resolveAgentRunAbortLifecycleFields, u as isAgentRunRestartAbortReason } from "./run-termination-0Ig0-bk6.mjs";
import { r as resolveCronRunToolsAllow } from "./tools-allow-CYmLDCc7.mjs";
import { f as withExecRequestTurn } from "./exec-request-context-C8VKkMcB.mjs";
import { c as normalizeDeliveryContext } from "./delivery-context.shared-CRlipPTj.mjs";
import { l as enqueueSystemEvent } from "./system-events-BFJiZPP0.mjs";
import { t as diagnosticLogger } from "./diagnostic-runtime-BxwnWXDu.mjs";
import { B as getReplyOperationSessionTarget, Dt as lifecycleAdmissionByOperation, F as waitForReplyOperationBackend, L as acquireReplyOperationSessionActor, P as runAfterReplyOperationClear, R as captureReplyOperationSessionReader, X as captureSessionTarget, _t as getSessionControllerEntryForOperation, b as markReplyOperationExecutionStarted, bt as isCurrentSessionControllerOperation, f as hasCommittedReplyOperationOutcome, gt as assertSessionControllerOperation, m as hasReplyOperationExecutionStarted, z as getReplyOperationSessionReader } from "./session-controller.state-BApgK0mV.mjs";
import { a as isRuntimeToolAllowed } from "./tool-policy-match-DzwVnbV4.mjs";
import { A as shouldKeepPayloadDuringSilentTurn, C as markReplyPayloadForSourceSuppressionDelivery, O as selectAutomationReplyPayloads, _ as isReplyPayloadStatusNotice, c as getReplyPayloadMetadata, f as isFastModeAutoProgressPayload, k as setReplyPayloadMetadata, m as isRenderablePayload, n as addReplyPayloadMediaFailures, o as copyReplyPayloadMetadata, p as isHostNoticePayload, t as FAST_MODE_AUTO_PROGRESS_KIND, y as isReplyPayloadTerminalContent } from "./reply-payload-k5WsQWxi.mjs";
import { a as readChannelSourceTurnId, c as setChannelSourceTurnId, r as buildChannelSourceTurnId, s as resolveReplySourceTurnId } from "./session-event-handoff-CC7Ui3SA.mjs";
import { p as sessionPersonalProfileId } from "./session-entry-provenance-01l9mXT0.mjs";
import { b as shouldPreserveUserFacingSessionStateForInputProvenance, d as isCronExecutionInputProvenance, v as progressCardRefreshRunProjection } from "./input-provenance-DupvvURj.mjs";
import { a as transferCommandOwnerAuthorityToSuccessor, i as getCommandOwnerAuthority, n as bindCommandOwnerAuthority, r as captureCommandOwnerAssertion } from "./command-owner-authority-BIUd20IP.mjs";
import { o as isAudioFileName } from "./mime-D2wVBzpa.mjs";
import { n as sessionDeliveryChannel } from "./delivery-context.read-BrYAJ7RK.mjs";
import { _ as resolveEffectiveReplyRoute } from "./session-event-target-BPiQeS30.mjs";
import { d as readSessionEntryInWorker, i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { a as readCapturedSessionActorEntry, o as runWithSessionActorStorage, t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs";
import { s as withoutSessionTranscriptReadFence } from "./session-transcript-read-fence-Bl-ZY3_t.mjs";
import { s as stripHeartbeatToken } from "./heartbeat-DHK32_6H.mjs";
import { n as trimTextPreservingCode } from "./trim-code-text-Dr7f3RLr.mjs";
import { n as parseInlineDirectives } from "./directive-tags-batch-D0CxS-zY.mjs";
import { t as INBOUND_CONTEXT_MARKER } from "./inbound-context-marker-CxvFQl8I.mjs";
import "./text-projection-DwmQz6_O.mjs";
import { t as formatTokenCount } from "./token-format-BaacASOf.mjs";
import { c as resolveSessionPluginTraceLines, s as resolveSessionPluginStatusLines } from "./types-BUko5WqP.mjs";
import { n as accountSessionGoalUsage } from "./goals-transitions-D4AKKFj3.mjs";
import { i as sanitizeUserFacingText, n as renderUserFacingText, t as renderAgentHarnessPreflightUserMessage } from "./user-facing-text-Dqp3fcZx.mjs";
import { _ as renderControlUiAgentFailureCopy, b as renderRateLimitOrOverloadedCopy, i as PROVIDER_CONVERSATION_STATE_ERROR_USER_MESSAGE, n as GENERIC_EXTERNAL_RUN_FAILURE_TEXT, v as renderFailoverCodeUserCopy } from "./user-copy-DFvWpx47.mjs";
import { c as classifyOAuthRefreshFailureError, s as classifyOAuthRefreshFailure } from "./oauth-refresh-failure-DxrQiYzV.mjs";
import { o as isAgentHarnessPreflightError } from "./errors-0Ou7CzqA.mjs";
import { d as MODEL_FALLBACK_NOTICE_KIND } from "./transcript-only-openclaw-assistant-BeEOZfu4.mjs";
import "./session-accessor-CizTbDQj.mjs";
import { n as buildSessionTranscriptTurnExpectedState } from "./session-transcript-turn-state-CviQGehX.mjs";
import { o as reduceSessionActorEntry } from "./session-actor-receipt-7upGHtzt.mjs";
import { n as withSessionActorStorage, t as acquireSessionActorStorage } from "./session-actor-storage-acquisition-bj-qIczw.mjs";
import { i as rethrowIncognitoSessionError, n as IncognitoSessionMissingError } from "./incognito-session-error-BxQdjUZa.mjs";
import { b as retireSessionControllerInput, m as bindSessionControllerSource, p as beginSessionControllerSourceInjection } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { i as withSessionActor, o as bindUserTurnInputActor, r as runSessionActorCommand } from "./session-accessor.sqlite-transcript-turn-VItOcLIr.mjs";
import { t as readSessionActorStorageResult } from "./session-actor-storage-result-BkDuCjds.mjs";
import { t as AgentActivityItemSchema } from "./logs-chat-C8_2M86E.mjs";
import { a as patchSessionEntryTarget, i as patchSessionEntryCore } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs";
import { h as resolveSessionPinnedHarnessId } from "./agent-harness-session-key-BRYGtzM6.mjs";
import { i as captureOwnedTranscriptWriteAssertion } from "./transcript-write-context-_7rz2F7z.mjs";
import "./config-CMA-J084.mjs";
import { c as updateSessionEntry } from "./session-accessor.entry-mutation-IJ4DYZ4a.mjs";
import { n as appendTranscriptMessage } from "./session-accessor.sqlite-transcript-write-C8dqprw-.mjs";
import "./directive-tags-C1p_t1Fd.mjs";
import "./sessions-D5Vvu3AE.mjs";
import { l as readChannelContextGatewayContextResolver } from "./admission-evidence-q4_t-NFq.mjs";
import { i as bindWorkerToolPreparation } from "./host-private-capabilities-DDumj0c_.mjs";
import { f as bindReplyOperationQueueDisposition, h as resolveFollowupAbortSignal, m as isFollowupRunAborted, n as bindGoalContinuationExecution, p as isFollowupOperatorAuthorityCurrent, r as createGoalContinuationReturnScope } from "./goal-continuation-return-DCxKXc44.mjs";
import { c as captureReplyExecutionSelection, n as prepareReplyRunToolAuthority } from "./reply-tool-authority-CcXbHQOX.mjs";
import { i as resolveOriginMessageProvider, r as resolveInboundReplyToolAuthorityOverlay } from "./reply-tool-authority-inbound-BQ8cxNJQ.mjs";
import { _ as releaseSessionControllerClaim, g as deferSessionControllerClaimBeforeExecution, h as bindSessionControllerInputOperation, m as attachSessionControllerInputOperation, n as claimSessionControllerInput, s as reserveSessionControllerSource, u as submitSessionControllerInput } from "./session-controller.mailbox-BcK8UF_b.mjs";
import { r as logVerbose } from "./globals-CgepmiqE.mjs";
import { l as withClaimingHookAdmission } from "./hooks-BiZpB_10.mjs";
import { t as resolveAgentHarnessPolicy } from "./policy-DzaOuofI.mjs";
import { n as getRegisteredAgentHarness } from "./registry-ubpieJjd.mjs";
import { s as resolvePersistedOverrideModelRef } from "./model-selection-C2A4Wyix.mjs";
import "./thinking-Da4gHblr.mjs";
import { t as areRuntimeModelRefsEquivalent } from "./model-runtime-aliases-DZy9Ea2c.mjs";
import { i as resolveSessionRuntimeOverrideForProvider } from "./session-runtime-compat-C_CO9LR_.mjs";
import { a as resolveContextTokensForModel } from "./context-C1qC4w3b.mjs";
import { r as resolveSessionModelRef } from "./session-model-ref-Cha0Enxi.mjs";
import { i as resolveCandidateAgentRuntime } from "./thinking-runtime-BKWl4CUs.mjs";
import { a as formatUsd, n as estimateAggregateUsageCost } from "./usage-format-BisQoUIV.mjs";
import { s as shouldAttemptTtsPayload } from "./tts-config-CNw5woLC.mjs";
import { s as isIngressAdoptionLostError } from "./ingress-drain-CMuOTwGV.mjs";
import { s as isChannelRunAuthorizationError } from "./host-context-builder-BXWPIn7b.mjs";
import { r as prepareCommandOwnerAuthority } from "./command-auth-CC1Z19Eh.mjs";
import { l as resolveFastModeForElapsed, n as formatFastModeAutoProgressText } from "./fast-mode-Dk3A3IUk.mjs";
import { t as resolveFastModeState } from "./fast-mode-BcwTQ_IZ.mjs";
import { c as refreshQueuedFollowupSession, d as completeFollowupRunLifecycle, p as refuseCollaborativeSteering, u as admitFollowupRunLifecycle } from "./state-DGvM9kEH.mjs";
import { m as resolveRunEntryCliRuntime } from "./session-utils-store-CiI_s_OK.mjs";
import { i as buildGenericCliContextEngineHostSupport } from "./host-compat-D2mUtPDd.mjs";
import { o as resolveManifestModelCatalogProviderAliasMetadata } from "./model.static-catalog-BYAE0w4W.mjs";
import { n as isLikelyContextOverflowError, t as isContextOverflowError } from "./context-overflow-C7ex88b9.mjs";
import { a as isCompactionFailureError } from "./model-fallback-candidates-CFJLuJlL.mjs";
import { n as resolveSendPolicy } from "./send-policy-Be9xpkMD.mjs";
import { t as classifyFailoverReason } from "./classify-o7Whl-By.mjs";
import { f as resolveFailoverReasonFromError, o as findCliTimeoutError } from "./failover-error-CbIiC30n.mjs";
import { l as shouldClearFailedCliSessionBinding } from "./cli-session-BsEOjZRc.mjs";
import { c as hasNewGeneratedMediaTaskForSessionKey, s as getGeneratedMediaTaskIdsForSessionKey, t as adoptMediaGenerationProgressDraft } from "./media-generation-activity-C0NELI_p.mjs";
import "./command-queue-BenRlAaO.mjs";
import { g as RUN_STALE_TAKEOVER_MS } from "./diagnostic-run-activity-BzWz2WN_.mjs";
import { o as logSessionTurnCreated } from "./diagnostic-C-GjPJGO.mjs";
import { a as hasOutboundReplyContent } from "./reply-payload-CwASJYas.mjs";
import { a as resolveSendableOutboundReplyParts } from "./reply-payload-parts-0Tn7wkpR.mjs";
import { n as isAgentPlanProgressToolName } from "./progress-card-input-WVh4etRi.mjs";
import { t as getTailscalePublishedOrigin } from "./tailscale-published-origin-Bvc-skoM.mjs";
import { n as runWithAgentWorkspaceReadiness, t as captureAgentWorkspaceReadiness } from "./workspace-readiness-ClUjI0tp.mjs";
import { i as resolveCronAuthenticatedChannelRequester } from "./tools-allow-provenance-Bf4KsdEb.mjs";
import { i as isMessagingToolSendAction } from "./embedded-agent-messaging-CBeq8Mz9.mjs";
import { r as resolveCronJobConfigRevision } from "./config-revision-ChGg5L01.mjs";
import { f as isFreshChannelCronAuthorityTurn, p as runWithCronCreatorAuthorityCapability } from "./cron-creator-authority-context-D4fHKVAj.mjs";
import { n as cliBackendAcceptsAuthProfileForwarding, r as resolveCliExecutionAuthProfileId } from "./cli-execution-auth-iYQVEZdU.mjs";
import { a as isExplicitFollowupCommandTurn, i as isExplicitCommandTurn, l as resolveCommandTurnContext } from "./command-turn-context-BaN4kAo-.mjs";
import { t as parseReplyDirectives } from "./reply-directives-BMfUGuku.mjs";
import { r as createStructuredOutboundPayloadPlan } from "./payloads-CQvywZOF.mjs";
import { n as normalizeReplyPayload } from "./normalize-reply-C8AkGgUH.mjs";
import { l as shouldRetryReplyDispatch, n as ReplyDispatchDeliveryError, s as resolveReplyDispatchErrorOutcome } from "./reply-dispatch-outcome-C1yqMjJt.mjs";
import { o as buildReplyUsageState, s as recordReplyUsageState } from "./deliver-hooks-B6z0_4Yo.mjs";
import { t as notifyPreparedAgentRunStart } from "./agent-run-start-Cf0O0aGQ.mjs";
import { n as resolveRoutedDeliveryThreadId } from "./routed-delivery-thread-C0qY6Hpm.mjs";
import { a as resolveReplyOperationRunState, n as recordReplyFollowupAdmission, o as resolveReplySessionEventDelivery, r as recordReplyOperationAgentTurn, s as resolveAgentTurnExecutionStatus } from "./reply-operation-run-state--V_f6Ot2.mjs";
import { a as isReplyProfilerEnabled, c as bindReplySourceToFollowup, i as createReplyTimingTracker, m as retireUnadoptedReplySource, n as shouldBridgeCliPreambleEvents } from "./get-reply.types-Cne2gAVx.mjs";
import { t as resolveReplyFailoverFacts } from "./request-error-facts-Cc7KLiOY.mjs";
import { a as isRequiredReplyExpectation, c as resolveClaimedReplyExpectation, d as resolveReplyCompletion, f as resolveReplyExpectation, i as isHostMissingReplyNoticeText, o as isSyntheticSourceReplyTurn, p as shouldDeliverMissingReplyNotice, r as createMissingReplyNotice, s as observeReplyDelivery, t as MISSING_REPLY_NOTICE_TEXT } from "./reply-completion-CrT6uEHT.mjs";
import { a as buildTerminalAgentRunFailureReplyPayload, c as markAgentRunFailureReplyPayload, d as resolveAgentRunFailureText, f as resolveReplyFailureSummary, i as buildPreflightCompactionFailureText, l as markPostCompactionModelFailurePayload, n as buildExternalRunFailureReply, o as isNonDirectConversationContext, p as resolveTerminalAgentRunFailurePayload, r as buildKnownAgentRunFailureReplyPayload, s as isVerboseFailureDetailEnabled, t as buildAuthProfileFailoverFailureText, u as renderPostCompactionModelFailurePayload } from "./agent-runner-failure-reply-NPeAVva_.mjs";
import { d as createBlockReplyContentKey, f as createBlockReplyPipeline, h as hasBlockReplyDeliveryCustody, l as requiresDurableToolResultDelivery, m as deliverBlockReply, s as maybeApplyTtsToReplyPayload } from "./dispatch-from-config.payloads-BWvEWyjL.mjs";
import { n as resolveReplyTurnKind, t as resolveReplyRunTrigger } from "./reply-turn-kind-BDXTUey9.mjs";
import { t as prepareChannelRunAdmission } from "./channel-run-admission-V419E9U5.mjs";
import { i as QuestionDispatchUnsupportedError, n as QuestionAnswerUnconfirmedError, r as QuestionDispatchRefusedError } from "./gateway-question-dispatch-BdJ_mO-C.mjs";
import { g as readQuestionRejection, r as claimPendingAgentQuestionAnswerFromCaller } from "./gateway-question-u5Q7erev.mjs";
import { t as settleProgressVisibilityCallbackResult } from "./progress-visibility-BGbXGOwY.mjs";
import { a as isShellToolDisplayName, i as isCommandBearingToolCall, r as inferToolMetaFromArgsCore } from "./tool-display-BQXZgFy6.mjs";
import { t as formatToolAggregate } from "./tool-meta-BPR-w7I7.mjs";
import { p as normalizeAgentPlanSteps } from "./streaming-DsQF8isK.mjs";
import { r as bindPreparedToolAuthority } from "./tool-authority-preparation-BOURfTvP.mjs";
import { t as hasInboundAudio } from "./inbound-media-BJ8l1Cri.mjs";
import { c as canInjectReplyMessageTarget, i as beginReplyMessageInjectionTarget, o as captureReplyMessageInjectionTarget, s as finalizeReplyMessageInjectionAttempt } from "./session-controller.steer-BWjVys2Y.mjs";
import { n as bindSessionControllerSourceTurnId, t as markReplyOperationGlobalLaneWaitProgress } from "./session-controller-Bu0l-8-p.mjs";
import { n as prepareTtsPreferences } from "./tts-preferences-CIrFrUQO.mjs";
import { a as resolveSourceReplyExpectation, o as resolveSourceReplyVisibilityPolicy, r as resolveFollowupReplyExpectation, t as isInternalSourceReplyChannel } from "./source-reply-delivery-mode-mRdJZOCZ.mjs";
import { a as isReplyOperationStalledBeforeOutput, c as expireSkillLibraryAuthoring, d as runWithReplyOperationLifecycleAdmission, i as buildStalledTurnRecoveryRun, l as admitReplyTurn, n as beginReplyOperationFinalizationWork, o as resolveStalledTurnNoticeText, r as STALLED_TURN_GUIDANCE, s as buildTranscriptFollowupRun, t as resolveTurnCommentaryProgressOwner, u as createReplyTurnRotationEvidence } from "./commentary-progress-owner-Cm2I90nD.mjs";
import { t as formatSystemTurnPrompt } from "./system-turn-prompt-rhkEP4nq.mjs";
import { i as resolveImplicitCurrentMessageReplyAllowance, n as createReplyToModeFilterForChannel, o as resolveReplyToMode, t as createReplyDeliveryContext } from "./reply-threading-__RxrMKC.mjs";
import { t as createReplySessionEntryHandle } from "./session-entry-handle-CuPvxZpL.mjs";
import { o as peekSessionMcpRuntime } from "./agent-bundle-mcp-manager-api-Um6GkoIv.mjs";
import { i as getMcpAppViewLease, o as leaseMcpAppModelContextForSessionTurn } from "./mcp-ui-resource-3UHFH-eE.mjs";
import { n as hasCompletionMessageSessionSpawn } from "./accepted-session-spawn-DXCz6IHR.mjs";
import { o as resolveModelAuthModeAsync } from "./model-auth-CEsyk_Yg.mjs";
import { t as appendCurrentInboundContext } from "./runtime-context-prompt-CRmsG0oC.mjs";
import { s as withCurrentUserTurnInput } from "./user-turn-transcript-runtime-context-BZjNfwCQ.mjs";
import { r as loadCronJobsStore } from "./store-DaG-8LOU.mjs";
import { n as resolveEffectiveBlockStreamingConfig } from "./block-streaming-BjSQtS33.mjs";
import { i as REPLY_RUN_STILL_SHUTTING_DOWN_TEXT, r as resolveActiveRunQueueAction, t as createTypingSignaler } from "./typing-mode-C5texNIA.mjs";
import { a as handoffCompletedSourceReply, i as reserveSteerCandidate, n as enqueueFollowupRun, o as scheduleFollowupDrain, r as getFollowupQueueDepth, s as resolveQueueSettings, t as claimNextQueuedFollowupRequestFrom } from "./queue-B_hYGqNE.mjs";
import { i as refreshActiveGoalContext } from "./inbound-meta-CVLLcIT8.mjs";
import { i as resolveDelegationCapability, n as isFallbackAttempt } from "./delegation-capability-BKV6nmg1.mjs";
import { a as assertSubagentRegistryWriteSourceCurrent, r as SubagentRegistryWriteError } from "./subagent-registry-persistence-B4kYlt3u.mjs";
import { c as normalizePendingFinalRecoveryPayloads, o as buildRecoverablePendingFinalDeliveryText, s as normalizePendingFinalDeliveryPayloads, u as sanitizePendingFinalDeliveryText } from "./send-C6MWAmk5.mjs";
import { t as resolveSessionWorkerPlacementContext } from "./session-worker-placement-context-CQyX2P4h.mjs";
import { s as resolveBootstrapWarningSignaturesSeen } from "./bootstrap-budget-BcnE4Zqz.mjs";
import { i as LiveSessionModelSwitchError } from "./failover-policy-BJz7cR8u.mjs";
import { a as resolveReplyScheduledToolPolicy, i as resolveModelFallbackOptions, n as buildReplyRunStateParams, o as resolveRunModelHasVision, r as buildRunEntrySelection, t as buildFallbackCandidateTurnParams } from "./agent-runner-run-params-CiEn1JED.mjs";
import { t as resolveCurrentTurnImages } from "./current-turn-images-B85zHU7Q.mjs";
import { n as createSourceReplyDeliveryRuntime, r as readSourceReplyDeliveryRuntime, t as bindSourceReplyDeliveryRuntime } from "./source-reply-delivery-runtime-B-sqDs1R.mjs";
import { n as invalidateTurnCompactionContext, r as recordTurnCompaction } from "./agent-runner-compaction-accounting-BjujZflt.mjs";
import { n as incrementCompactionCount } from "./session-updates-CAMM-3y9.mjs";
import { n as scheduleSessionMaintenance, t as createSessionMaintenanceFollowup } from "./run-pgKf8cOO.mjs";
import { c as hasCompletedSourceReplyDeliveryEvidence, f as hasVisibleCommittedMessagingToolDeliveryEvidence, h as resolveSourceReplyDelivery, m as resolveExplicitFinalSourceReplyDeliveryEvidence, o as hasCommittedSourceReplyDeliveryEvidence, p as hasVisibleOutboundDeliveryEvidence } from "./delivery-evidence-CqR4m_Hg.mjs";
import { t as runEmbeddedAgentEntry } from "./run-entry-BgJbXde3.mjs";
import { u as resolveRunStartupPhase } from "./execution-errors-aeOsnaMY.mjs";
import { r as isFallbackSummaryError } from "./model-fallback-attempt-DPZU4qST.mjs";
import { n as MODEL_FALLBACK_SKIPPED_CODE } from "./model-fallback-runner-DRFeYUEn.mjs";
import { u as withoutRequiredSessionPlacement } from "./session-placement-admission-CBCEtade.mjs";
import { t as createDeferredEmbeddedRunLifecycleManager } from "./deferred-lifecycle-owner-C5yWTb_n.mjs";
import { n as prepareLiveModelSwitchAfterRun } from "./live-model-switch-667ZwKej.mjs";
import { n as resolveCyberAccessProgramForProvider } from "./model-catalog-access-programs-D76ru0cU.mjs";
import { t as buildAgentRuntimeDeliveryPlan } from "./build-1KVS3lgO.mjs";
import { a as extractToolResultText } from "./embedded-agent-tool-results-DbtxSr9V.mjs";
import { t as createAgentLifecycleTerminalBackstop } from "./agent-lifecycle-terminal-DsT43SVO.mjs";
import { r as withBeforeAgentReplyObserver } from "./before-agent-reply-B7qHTCot.mjs";
import { r as stripOpenClawMcpToolPrefix } from "./tool-policy-bZXUEBo2.mjs";
import { n as runEmbeddedAgent } from "./embedded-agent-DHYfZZ9G.mjs";
import { n as filterMessagingToolReplyPayload } from "./reply-payloads-dedupe-xQRy9T4a.mjs";
import { t as createUnrecordedScheduledAccountRefusal } from "./scheduled-unrecorded-account-DtjpvOWO.mjs";
import { n as createReplyMediaContext } from "./reply-media-paths-B3zuAx71.mjs";
import { r as isCronOneShotContinuationJob } from "./one-shot-schedule-Ff0uCKas.mjs";
import { n as registerCronRunExecSource } from "./cron-run-exec-source-BiohUkNP.mjs";
import { g as cliAssistantItemId } from "./trajectory-D7Mvun0h.mjs";
import { t as buildCliMcpDelegationCapabilityBinding } from "./mcp-grant-context-BYEiDRzc.mjs";
import { n as runCliAgent } from "./cli-runner-QfivXQBs.mjs";
import { t as resolveDiagnosticModelResponse } from "./diagnostic-model-response-CbgexSbW.mjs";
import { n as clearCliSessionInStore, o as settleCliSessionResult, t as buildCliSessionForkRunParams } from "./cli-session-store-Dkejl-uo.mjs";
import { t as withAdmittedCliCandidate } from "./run-entry-cli-BeiHZwbO.mjs";
import { r as readPostCompactionContext } from "./post-compaction-context-BSROIzvn.mjs";
import { t as emitAgentRunStatusEvent } from "./agent-run-status-events-BK0y8NgA.mjs";
import { n as runSessionCompactionIfNeeded, t as runMemoryFlushIfNeeded } from "./agent-runner-memory-B5q0ihKJ.mjs";
import { a as mintReplyMessageActionTurnCapability, c as resolveRunFastModeForFallbackCandidate, d as resolveRunAuthProfile, l as resolveRunThinkingLevelForFallbackCandidate, n as buildModelResolveContext, o as resolveFollowupCurrentMessageId, r as buildReplyRouteThreadingToolContext, s as resolveQueuedReplyExecutionConfig, t as buildEmbeddedRunExecutionParams, u as resolveFallbackCandidateRun } from "./agent-runner-utils-D8POqd9a.mjs";
import { n as createCompactionNoticePayload, o as shouldNotifyUserAboutCompaction, r as formatCompactionModelRef, t as createCompactionHookNoticePayload } from "./compaction-notice-DIvJfdHs.mjs";
import { i as prepareReplyMessageJoin, n as hasReplySteeringRequesterMismatch, t as prepareSteeringDelivery } from "./steering-delivery-preparation-BASNdY_q.mjs";
import { t as createAgentPatchedSessionModelFallback } from "./session-model-fallback-C4P5tfpl.mjs";
import { i as prepareCronRunInference, n as assertCronRuntimeAuthorityCandidate, r as resolveCronSandboxPlacement, t as assertCronCandidateSandboxPlacement } from "./run-admission-BMLeRlnV.mjs";
import { t as prepareCronRunAdmission } from "./run-admission-xiqkIo7D.mjs";
import { t as WorkerNodeLostError } from "./worker-node-loss-C_5DPByT.mjs";
import { n as withVisibleWorkSessionReporter } from "./visible-work-sessions-B5x1KERB.mjs";
import { t as readLatestSessionUsageFromTranscriptAsync } from "./session-transcript-usage-BJb0Vv_M.mjs";
import { t as createMcpAppStandaloneTicket } from "./mcp-app-standalone-CtVsHHh4.mjs";
import { r as routeReply, t as isRoutableChannel } from "./route-reply-C7tyScNr.mjs";
import { t as prepareSessionSystemTurnAuthority } from "./session-system-turn-authority-_YKq9CC2.mjs";
import { readFileSync } from "node:fs";
import path, { basename, dirname, resolve } from "node:path";
import crypto, { createHash, randomUUID } from "node:crypto";
import { realpath } from "node:fs/promises";
import { homedir } from "node:os";
import { root } from "@openclaw/fs-safe/root";
import { Value } from "typebox/value";
import { watch as watch$1 } from "@openclaw/fs-safe/watch";
//#region src/auto-reply/fallback-state.ts
/** Formats model-fallback notice state for UI/status messages and persisted transition tracking. */
const FALLBACK_REASON_PART_MAX = 80;
const TRANSIENT_FALLBACK_REASONS = /* @__PURE__ */ new Set([
	"rate_limit",
	"overloaded",
	"timeout",
	"empty_response",
	"no_error_details",
	"unclassified"
]);
const TRANSIENT_ERROR_DETAIL_HINT_RE = /\b(?:429|5\d\d|too many requests|usage limit|quota|try again in|retry[- ]after|seconds?|minutes?|hours?|temporarily unavailable|overloaded|service unavailable|throttl\w*)\b/i;
function truncateFallbackReasonPart(e) {
	return truncateWithMarker(e.replace(/\s+/g, " ").trim(), FALLBACK_REASON_PART_MAX, {
		marker: "…",
		reserve: 1,
		trimEnd: true
	});
}
function formatFallbackAttemptErrorPreview(e) {
	const t = e.error?.trim();
	if (!t || !e.reason || !TRANSIENT_FALLBACK_REASONS.has(e.reason)) return;
	if (!TRANSIENT_ERROR_DETAIL_HINT_RE.test(t)) return;
	const n = formatRawAssistantErrorForUi(t).replace(/^⚠️\s*/, "").replace(/\s+/g, " ").trim();
	if (!n || /unknown error/i.test(n)) return;
	return n;
}
function formatFallbackAttemptReason(e) {
	const t = formatFallbackAttemptErrorPreview(e);
	if (t) return t;
	const n = e.reason?.trim();
	if (n) return n.replace(/_/g, " ");
	return e.code?.trim() || (e.status !== void 0 ? `HTTP ${e.status}` : truncateFallbackReasonPart(e.error || "error"));
}
function buildFallbackReasonSummary(e) {
	const t = e[0];
	const n = t ? formatFallbackAttemptReason(t) : "selected model unavailable";
	const r = e.length > 1 ? ` (+${e.length - 1} more attempts)` : "";
	return `${truncateFallbackReasonPart(n)}${r}`;
}
/** Builds the visible notice shown when runtime falls back from the selected model. */
function buildFallbackNotice(e) {
	const t = buildModelCatalogRef(e.selectedProvider, e.selectedModel);
	const n = buildModelCatalogRef(e.activeProvider, e.activeModel);
	if (areRuntimeModelRefsEquivalent(t, n, { config: e.cfg })) return null;
	return `↪️ Model Fallback: ${n} (selected ${t}; ${buildFallbackReasonSummary(e.attempts)})`;
}
/** Builds the visible notice shown after a successful embedded provider-policy retry. */
function buildProviderPolicyRetryNotice(e) {
	const t = buildModelCatalogRef(e.provider, e.model);
	return `↪️ Retried on ${areRuntimeModelRefsEquivalent(t, "openai/gpt-daybreak-blue-latest", { config: e.cfg }) ? "Daybreak" : t}`;
}
/** Builds the visible notice shown when runtime returns to the selected model. */
function buildFallbackClearedNotice(e) {
	const t = buildModelCatalogRef(e.selectedProvider, e.selectedModel);
	const n = normalizeOptionalString(e.previousActiveModel);
	return `↪️ Model Fallback cleared: ${t}${n && n !== t ? ` (was ${n})` : ""}`;
}
/** Resolves fallback state transitions and the next persisted notice-state fields. */
function resolveFallbackTransition(e) {
	const t = buildModelCatalogRef(e.selectedProvider, e.selectedModel);
	const n = buildModelCatalogRef(e.activeProvider, e.activeModel);
	const r = {
		selectedModel: normalizeOptionalString(e.state?.fallbackNotice?.selectedModel),
		activeModel: normalizeOptionalString(e.state?.fallbackNotice?.activeModel),
		reason: normalizeOptionalString(e.state?.fallbackNotice?.reason)
	};
	const i = { config: e.cfg };
	const a = !areRuntimeModelRefsEquivalent(t, n, i);
	const o = r.selectedModel === t && r.activeModel === n;
	const s = a && !o;
	const c = o ? a : Boolean(r.selectedModel && r.activeModel && !areRuntimeModelRefsEquivalent(r.selectedModel, r.activeModel, i));
	const l = !a && c;
	const u = buildFallbackReasonSummary(e.attempts);
	const d = e.attempts.map((e) => truncateFallbackReasonPart(`${buildModelCatalogRef(e.provider, e.model)} ${formatFallbackAttemptReason(e)}`));
	const f = a ? {
		selectedModel: t,
		activeModel: n,
		reason: u
	} : {
		selectedModel: void 0,
		activeModel: void 0,
		reason: void 0
	};
	return {
		selectedModelRef: t,
		activeModelRef: n,
		fallbackActive: a,
		fallbackTransitioned: s,
		fallbackCleared: l,
		reasonSummary: u,
		attemptSummaries: d,
		previousState: r,
		nextState: f,
		stateChanged: r.selectedModel !== f.selectedModel || r.activeModel !== f.activeModel || r.reason !== f.reason
	};
}
//#endregion
//#region src/auto-reply/reply/reply-delivery.ts
/** Visible progress needs a failure outcome, but retained or suppressed sends are not visibility. */
async function resolveReplyFailureVisibility(e, t) {
	return await e?.() === true || t.some((e) => e.outcome === "delivered" && hasOutboundReplyContent(e.payload, { trimText: true }));
}
function normalizeReplyPayloadDirectives(e) {
	const t = e.parseMode ?? "always";
	const n = e.payload.text ?? "";
	const r = t === "always" || t === "auto" && (n.includes("[[") || /media:/i.test(n) || e.extractMarkdownImages === true && /!\[[^\]]*]\(/.test(n)) ? parseReplyDirectives(n, {
		currentMessageId: e.currentMessageId,
		extractMarkdownImages: e.extractMarkdownImages
	}) : void 0;
	let i = r ? r.text || void 0 : e.payload.text || void 0;
	if (e.trimLeadingWhitespace && i) i = trimTextPreservingCode(i, "start") || void 0;
	const a = e.payload.mediaUrls ?? r?.mediaUrls;
	const o = e.payload.mediaUrl ?? r?.mediaUrls?.[0] ?? a?.[0];
	return { payload: addReplyPayloadMediaFailures(copyReplyPayloadMetadata(e.payload, {
		...e.payload,
		text: i,
		mediaUrls: a,
		mediaUrl: o,
		replyToId: e.payload.replyToId ?? r?.replyToId,
		replyToTag: e.payload.replyToTag || r?.replyToTag,
		replyToCurrent: e.payload.replyToCurrent || r?.replyToCurrent,
		audioAsVoice: Boolean(e.payload.audioAsVoice || r?.audioAsVoice)
	}), r?.mediaFailures) };
}
function createBlockReplyDeliveryHandler(e) {
	const sendDirectBlockReply = async (t, n) => {
		const r = {
			payload: t,
			outcome: "failed-deliver",
			pending: true
		};
		e.directBlockDeliveries.push(r);
		const i = await deliverBlockReply(() => n ? e.onBlockReply(t, n) : e.onBlockReply(t)).catch((e) => {
			r.outcome = resolveReplyDispatchErrorOutcome(e);
			r.pending = false;
			throw e;
		});
		Object.assign(r, i, { pending: i.pending === true });
		if (n?.deliveryIntentId !== void 0 && !i.pending && shouldRetryReplyDispatch(i.outcome)) throw new ReplyDispatchDeliveryError(i.outcome);
		if (i.outcome === "delivered" && !i.pending && i.source?.complete !== false && isReplyPayloadTerminalContent(t)) r.terminalDeliveryConfirmed = true;
	};
	let t;
	let n = Promise.resolve();
	const deliver = async (n, r) => {
		if (e.silentExpected && !shouldKeepPayloadDuringSilentTurn(n) || n.isReasoning === true && e.reasoningPayloadsEnabled !== true || n.isCommentary === true && e.commentaryPayloadsEnabled !== true) return;
		const i = getReplyPayloadMetadata(n);
		const a = i?.assistantMessageIndex;
		const o = i?.blockSourceRange;
		const s = e.blockStreamingEnabled && !r?.completed && isReplyPayloadTerminalContent(n) && !n.isError && a !== void 0 && o !== void 0;
		const c = s && t === a && o[0] > 0;
		setReplyPayloadMetadata(n, { streamedSourceBoundary: c && n.text?.startsWith("\n") ? true : void 0 });
		const { text: l, skip: u } = e.normalizeStreamingText(n);
		const d = getReplyPayloadMetadata(n)?.silentReply === true;
		if (u && !hasOutboundReplyContent({
			...n,
			text: void 0
		}) && !n.audioAsVoice) return;
		const f = n.replyToCurrent ?? e.replyThreading?.implicitCurrentMessage !== "deny";
		const p = l && c && l.startsWith("\n") ? l : l ? trimTextPreservingCode(l, "start") : void 0;
		const m = copyReplyPayloadMetadata(n, {
			...n,
			text: d ? void 0 : p || void 0,
			audioAsVoice: Boolean(n.audioAsVoice),
			mediaUrl: n.mediaUrl ?? n.mediaUrls?.[0],
			replyToId: n.replyToId ?? (f ? e.currentMessageId : void 0)
		});
		if (!isRenderablePayload(m) && !n.audioAsVoice) return;
		const h = e.normalizeMediaPaths ? await e.normalizeMediaPaths(m) : m;
		if (d) h.text = void 0;
		const g = copyReplyPayloadMetadata(n, e.applyReplyToMode(h));
		if (g.text?.trim() !== n.text?.trim()) setReplyPayloadMetadata(g, {
			blockSourceText: void 0,
			blockSourceRange: void 0
		});
		const _ = hasOutboundReplyContent({
			...g,
			text: void 0
		});
		if (!g.text && !_ && !g.audioAsVoice) return;
		if (g.text) {
			if (s && !d) t = a;
			e.typingSignals.signalTextDelta(g.text).catch((e) => {
				logVerbose(`block reply typing signal failed: ${String(e)}`);
			});
		}
		if (r?.deliveryIntentId !== void 0) setReplyPayloadMetadata(g, { independentDeliveryIntentId: r.deliveryIntentId });
		else if (e.blockStreamingEnabled && e.blockReplyPipeline) {
			if (r?.completed) await e.blockReplyPipeline.flush({ force: true });
			e.blockReplyPipeline.enqueue(g);
			if (r?.completed) await e.blockReplyPipeline.flush({ force: true });
			return;
		} else if (!e.blockStreamingEnabled && r?.completed !== true && !_ && g.isReasoning !== true && g.isCommentary !== true) return;
		return { delivery: sendDirectBlockReply(g, r?.deliveryIntentId !== void 0 ? r : void 0) };
	};
	return (t, r) => {
		const i = e.normalizeMediaPaths ? n.then(() => deliver(t, r)) : deliver(t, r);
		n = i.then(() => void 0, () => void 0);
		return i.then((e) => e?.delivery);
	};
}
//#endregion
//#region src/auto-reply/reply/reply-operation-abort.ts
function buildRestartLifecycleReplyText() {
	return "⚠️ Gateway is restarting. Please wait a few seconds and try again.";
}
function resolveSignalAbortReason(e) {
	const t = resolveAgentRunAbortLifecycleFields(e).stopReason;
	if (t === "restart" || t === "superseded") return t;
	return t && !isSessionPlacementSettlementClosedError(e?.reason) ? "user" : void 0;
}
function isReplyOperationUserAbort(e) {
	return e?.result?.kind === "aborted" && e.result.code === "aborted_by_user" || resolveSignalAbortReason(e?.abortSignal) === "user";
}
function hasReplyOperationAbort(e, t, n) {
	return e?.result?.kind === "aborted" && e.result.code === t || e?.abortSignal?.aborted === true && n(e.abortSignal.reason);
}
function resolveReplyOperationTerminationFields(e, t, n) {
	const r = resolveReplyOperationAbortReason(n);
	return {
		...resolveAgentRunErrorLifecycleFields(e, t),
		...r === "restart" || r === "superseded" ? {
			aborted: true,
			stopReason: r
		} : {}
	};
}
function isReplyOperationSuperseded(e) {
	return hasReplyOperationAbort(e, "aborted_for_supersession", isAgentRunSupersededAbortReason);
}
function resolveReplyOperationAbortReason(e, t, n = e?.abortSignal) {
	const r = resolveAgentRunErrorLifecycleFields(t, void 0).stopReason;
	return hasReplyOperationAbort(e, "aborted_for_restart", isAgentRunRestartAbortReason) ? "restart" : isReplyOperationSuperseded(e) ? "superseded" : resolveSignalAbortReason(n) ?? (r === "restart" ? "restart" : r === "superseded" ? "superseded" : isAgentRunDirectAbortReason(t) || isReplyOperationUserAbort(e) ? "user" : void 0);
}
function resolveRestartLifecycleError(e) {
	const t = [e];
	const n = /* @__PURE__ */ new Set();
	for (const e of t) {
		if (!e || n.has(e)) continue;
		n.add(e);
		if (e instanceof GatewayDrainingError) return e;
		if (isFallbackSummaryError(e)) t.push(...e.attempts.map((e) => e.error));
		if (e instanceof Error && "cause" in e) t.push(e.cause);
	}
}
//#endregion
//#region src/auto-reply/reply/agent-runner-core.ts
const BLOCK_REPLY_SEND_TIMEOUT_MS = 15e3;
function scheduleFollowupDrainAfterReplyOperationClear(e) {
	runAfterReplyOperationClear(e.operation, (t) => {
		const n = e.operation.sessionId;
		scheduleFollowupDrain(e.queueKey, e.runFollowup, getSessionControllerEntryForOperation(e.operation), t === n ? void 0 : {
			from: n,
			to: t
		});
	});
}
function markBeforeAgentRunBlockedPayloads(e) {
	return e.map((e) => setReplyPayloadMetadata(e, { beforeAgentRunBlocked: true }));
}
function buildSilentFallbackFailurePayload(e) {
	if (e.completion.outcome !== "missing" || !e.fallbackTransition.fallbackActive || !e.fallbackFailureKnown) return;
	const t = e.fallbackTransition.selectedModelRef;
	const n = e.fallbackTransition.activeModelRef;
	const r = e.fallbackAttempts;
	const i = r.filter((n) => areRuntimeModelRefsEquivalent(`${n.provider}/${n.model}`, t, { config: e.cfg }));
	let a = `⚠️ The configured model backend ${t} produced no usable reply. `;
	if (i.length > 0 && i.every((e) => e.code !== "MODEL_FALLBACK_SKIPPED") && r.every((e) => e.provider.trim() && e.model.trim())) {
		if (i.every(({ reason: e }) => [
			"timeout",
			"server_error",
			"overloaded",
			"tls_certificate"
		].includes(e))) a = `⚠️ I couldn't reach the configured model backend ${t}. `;
		else if (i.every(({ reason: e }) => e === "format" || e === "empty_response")) a = `⚠️ The configured model backend ${t} responded but produced no usable reply. `;
	}
	return markReplyPayloadForSourceSuppressionDelivery({
		text: `${a}Fallback used ${n}, but it produced no visible reply.`,
		isError: true
	});
}
function resolveSourceReplyPolicy(e) {
	const t = resolveSendPolicy({
		cfg: e.cfg,
		entry: e.sessionEntry,
		sessionKey: e.runtimePolicySessionKey ?? e.sessionKey,
		channel: e.sessionCtx.OriginatingChannel ?? e.sessionCtx.Surface ?? e.sessionCtx.Provider ?? sessionDeliveryChannel(e.sessionEntry),
		chatType: e.sessionEntry?.chatType
	});
	return resolveSourceReplyVisibilityPolicy({
		cfg: e.cfg,
		ctx: e.sessionCtx,
		scheduledAutomation: e.opts?.scheduledAutomation !== void 0,
		requested: e.opts?.sourceReplyDeliveryMode,
		sendPolicy: t
	});
}
function resolveReplyRunDeliveryContext(e) {
	const t = resolveSourceReplyPolicy(e);
	if (e.sessionCtx.InboundEventKind === "room_event" || t.sendPolicyDenied || t.suppressDelivery && t.sourceReplyDeliveryMode !== "message_tool_only") return;
	return normalizeDeliveryContext({
		...resolveEffectiveReplyRoute({
			ctx: e.sessionCtx,
			entry: e.sessionEntry
		}),
		threadId: resolveRoutedDeliveryThreadId({
			ctx: e.sessionCtx,
			sessionKey: e.sessionCtx.SessionKey ?? e.sessionKey
		})
	});
}
function hasSuccessfulSourceReplyDelivery(e) {
	return e.blockReplyPipeline?.didStream() || e.hasDirectlySentBlockReply === true || hasVisibleCommittedMessagingToolDeliveryEvidence(e);
}
async function resolveTerminalReplyDelivery(e) {
	if (e.sourceReplyDeliveryState === "delivered" || e.sourceReplyDeliveryState === "pending") return e.sourceReplyDeliveryState;
	const { blockReplyPipeline: t, minimumAssistantMessageIndex: n = 0 } = e;
	if (e.sourceReplyDeliveryState === void 0) await t?.flush({ force: true });
	const r = await observeReplyDelivery(e.resolveReplyDelivery, n, (e) => logVerbose(`reply delivery observation failed; retaining custody: ${String(e)}`));
	if (r === "delivered") return r;
	let i = r === "pending" || t?.hasRetryBlockedTerminalDelivery?.(n) === true;
	for (const t of e.directBlockDeliveries ?? []) {
		if ((getReplyPayloadMetadata(t.payload)?.assistantMessageIndex ?? 0) < n || !isReplyPayloadTerminalContent(t.payload)) continue;
		if (t.terminalDeliveryConfirmed) return "delivered";
		i ||= hasBlockReplyDeliveryCustody(t);
	}
	return t?.didStreamTerminalReply?.(n) ? "delivered" : i ? "pending" : "missing";
}
function resolveFallbackOriginModel(e) {
	if (e.runtimeModelSelection) return {
		...e.runtimeModelSelection,
		persistedAutoFallback: false
	};
	const t = e.fallbackStateEntry;
	if ((t?.modelOverrideSource === "auto" || t !== void 0 && t.modelOverrideSource === void 0 && hasSessionAutoModelFallbackProvenance(t)) && t !== void 0) {
		const e = normalizeOptionalString(t.modelOverrideFallbackOriginProvider);
		const n = normalizeOptionalString(t.modelOverrideFallbackOriginModel);
		if (e && n) return {
			provider: e,
			model: n,
			persistedAutoFallback: true
		};
	}
	return {
		provider: e.run.provider,
		model: e.run.model,
		persistedAutoFallback: false
	};
}
function normalizeAssistantFinalDeliveryText(e) {
	const t = normalizeReplyPayloadDirectives({
		payload: { text: e },
		trimLeadingWhitespace: true,
		parseMode: "auto"
	});
	return sanitizePendingFinalDeliveryText(t.payload.text ?? "");
}
async function refreshSessionEntryFromStore(e) {
	const { storePath: t, sessionKey: n, fallbackEntry: r, activeSessionStore: i } = e;
	if (!t || !n) return r;
	try {
		const a = await readSessionEntryReadOnlyInWorker({
			storePath: t,
			sessionKey: n
		}, void 0, e.reader);
		if (!a || e.expectedGeneration && (a.sessionId !== e.expectedGeneration.sessionId || a.lifecycleRevision !== e.expectedGeneration.lifecycleRevision)) return r;
		if (i) i[n] = a;
		return a;
	} catch (t) {
		if (e.reader) throw t;
		return r;
	}
}
async function handleReplyAgentRunError(e, t) {
	const { resolveVisibleReplyDelivery: n, replyExpectation: r, replyOperation: i, resolvedVerboseLevel: a, returnWithQueuedFollowupDrain: o, sessionCtx: s } = t;
	if (isReplyOperationSuperseded(i)) return {};
	if (i.result?.kind === "aborted" && i.result.code === "aborted_by_user") return o({});
	if (resolveReplyOperationAbortReason(i, e) === "restart") {
		i.abortForRestart();
		return o({});
	}
	if (e instanceof GatewayDrainingError) {
		i.fail("run_failed", e);
		return o({
			text: buildRestartLifecycleReplyText(),
			isError: true
		});
	}
	const c = buildKnownAgentRunFailureReplyPayload({
		err: e,
		sessionCtx: s,
		resolvedVerboseLevel: a
	});
	if (c) {
		i.fail("run_failed", e);
		return o(c);
	}
	const l = await n();
	if ((l || t.userTurnAccepted) && !i.abortSignal.aborted) {
		i.fail("run_failed", e);
		return o(buildTerminalAgentRunFailureReplyPayload({
			replyExpectation: r,
			visibleReplyDelivered: l
		}));
	}
	i.fail("run_failed", e);
	o(void 0);
	throw e;
}
async function cleanupReplyAgentRun(e) {
	const { blockReplyPipeline: t, releaseSourceAdmission: n, providedReplyOperation: r, queueKey: i, replyOperation: a, runFollowupTurn: o, sessionKey: s, shouldDrainQueuedFollowupsAfterClear: c, typing: l } = e;
	try {
		await n?.();
	} catch (e) {
		logVerbose(`failed to release reply admission for ${s ?? "unknown"}: ${String(e)}`);
	}
	if (c) scheduleFollowupDrainAfterReplyOperationClear({
		operation: a,
		queueKey: i,
		runFollowup: o
	});
	if (!r) a.complete();
	t?.stop();
	l.markRunComplete();
	l.markDispatchIdle();
}
//#endregion
//#region src/agents/session-model-auto-revert.ts
/** One-run rollback for agent-selected session models. */
const log = createSubsystemLogger("agents/model-patch");
const REVERT_REASONS = /* @__PURE__ */ new Set([
	"auth",
	"auth_permanent",
	"billing",
	"model_not_found"
]);
async function createAgentPatchedSessionModelRunGuard(e) {
	const t = e.sessionKey ? captureSessionActorStorageOwner(e, {
		assertCurrent() {
			e.assertReadCurrent?.();
		},
		authorize() {}
	}) : void 0;
	const n = {
		agentId: t?.agentId ?? e.agentId,
		sessionKey: e.sessionKey,
		storePath: t?.path ?? e.storePath
	};
	let r;
	let i;
	let a;
	if (e.sessionKey) {
		e.assertReadCurrent?.();
		try {
			const n = t ? readCapturedSessionActorEntry(t, e.sessionKey) : await readSessionEntryInWorker({
				agentId: e.agentId,
				sessionKey: e.sessionKey,
				storePath: e.storePath
			});
			e.assertReadCurrent?.();
			const o = n?.modelFallback;
			r = o?.source === "agent-patch" ? o.ts : void 0;
			if (n && r !== void 0) {
				i = {
					sessionId: n.sessionId,
					lifecycleRevision: n.lifecycleRevision
				};
				const t = resolveSessionModelRef(e.cfg, n, e.agentId);
				a = createAgentPatchedSessionModelFallback({
					model: t.model,
					provider: t.provider,
					entry: n,
					ts: r
				});
			}
		} catch (t) {
			rethrowIncognitoSessionError(t);
			e.assertReadCurrent?.();
			log.warn(`model rollback preparation unavailable; check session storage and model settings: ${formatErrorMessage(t)}`);
			r = void 0;
		}
	}
	let o = {};
	let s = false;
	const captureFailure = (e, t) => {
		if (r === void 0) return false;
		const n = t ? t : resolveFailoverReasonFromError(e);
		const i = n && REVERT_REASONS.has(n) ? n : void 0;
		o = {
			error: e,
			...i ? { reason: i } : {}
		};
		return i !== void 0;
	};
	const captureFallbackFailure = (e) => {
		const t = e[0];
		return t ? captureFailure(new Error(t.error), t.reason) : void 0;
	};
	const reconcile = async (c) => {
		if (s || !n.sessionKey || r === void 0) return;
		s = true;
		try {
			const s = n.sessionKey;
			const reconcileModel = async () => {
				const { cfg: t } = e;
				const { agentId: l, storePath: u } = n;
				const d = r;
				const f = c ? { success: true } : {
					success: false,
					...o
				};
				const p = f.success ? void 0 : f.reason ?? resolveFailoverReasonFromError(f.error);
				if (!f.success && (!p || !REVERT_REASONS.has(p))) return;
				let m;
				let h;
				const g = await patchSessionEntryCore({
					agentId: l,
					sessionKey: s,
					storePath: u
				}, (e) => {
					if (i && (e.sessionId !== i.sessionId || e.lifecycleRevision !== i.lifecycleRevision)) return null;
					const n = e.modelFallback;
					if (n?.source !== "agent-patch") return null;
					if (d !== void 0 && n.ts !== d) {
						if (f.success && a && n.ts > d && d > (n.lastValidatedPatchTs ?? -1)) return { modelFallback: {
							...a,
							ts: n.ts,
							lastValidatedPatchTs: d
						} };
						return null;
					}
					h = e.sessionId;
					if (f.success) return { modelFallback: void 0 };
					const r = resolveSessionModelRef(t, e, l);
					m = `System note: model ${r.provider}/${r.model} failed; reverted to ${n.prevProvider}/${n.prevModel}.`;
					return {
						model: n.prevModel,
						modelProvider: n.prevProvider,
						modelOverride: n.prevModelOverride,
						providerOverride: n.prevProviderOverride,
						modelOverrideSource: n.prevModelOverrideSource,
						modelOverrideRouteResolution: n.prevModelOverrideRouteResolution,
						modelOverrideFallbackOriginProvider: n.prevModelOverrideFallbackOriginProvider,
						modelOverrideFallbackOriginModel: n.prevModelOverrideFallbackOriginModel,
						authProfileOverride: n.prevAuthProfileOverride,
						authProfileOverrideSource: n.prevAuthProfileOverrideSource,
						authProfileOverrideCompactionCount: n.prevAuthProfileOverrideCompactionCount,
						contextWindow: n.prevContextWindow,
						thinkingLevel: n.prevThinkingLevel,
						modelFallback: void 0,
						liveModelSwitchPending: void 0
					};
				});
				if (m && h) try {
					const e = Date.now();
					await appendTranscriptMessage({
						agentId: l,
						sessionId: h,
						sessionKey: s,
						storePath: u,
						expectedLifecycleRevision: g?.lifecycleRevision,
						expectedWriterRunId: g?.activeWriterRunId
					}, {
						config: t,
						message: {
							role: "custom",
							customType: "openclaw.system-note",
							content: m,
							display: true,
							timestamp: e
						}
					});
				} catch {}
			};
			if (t) {
				const e = {
					assertCurrent() {},
					assertReadable() {}
				};
				const r = t.owner ? await t.owner.acquireExisting(s, e) : t.binding ? (await acquireSessionActorStorage({
					...n,
					sessionActor: t.binding
				}, {
					lifetime: e,
					authority: t.authority
				}))?.actor : void 0;
				if (!r) return;
				try {
					await runWithSessionActorStorage({
						...t,
						actor: r
					}, reconcileModel);
				} finally {
					await r.release();
				}
			} else await reconcileModel();
		} catch (t) {
			e.onError?.(t);
		}
	};
	return {
		captureFailure,
		captureFallbackFailure,
		async fail(e, t) {
			captureFailure(e, t);
			await reconcile(false);
		},
		finish: reconcile
	};
}
//#endregion
//#region src/auto-reply/reply/agent-runner-admission.ts
/** Owns reply admission and closes its delivery grant after deferred and terminal writes settle. */
function prepareReplyTurnExecution(e, t) {
	const n = {};
	const r = readChannelContextGatewayContextResolver(e.sessionCtx) ?? getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext;
	const i = e.followupRun.run.scheduledAutomation;
	const a = e.sessionKey ?? e.followupRun.run.sessionKey;
	const o = composeSessionSourceAssertion([
		captureOwnedTranscriptWriteAssertion({
			agentId: e.followupRun.run.agentId,
			sessionId: e.followupRun.run.sessionId,
			sessionKey: a,
			storePath: e.storePath
		}),
		e.followupRun.run.senderIsOwner === true ? captureCommandOwnerAssertion(e.followupRun.run) : void 0,
		e.followupRun.run.internalEventExecution?.assertCurrent,
		i?.assertCurrent
	]);
	if (i && !a) throw new Error("A scheduled session turn requires its admitted session key");
	const onAdmitted = (t) => {
		bindGatewayContextResolver(t, r);
		n.current = t;
		e.followupRun.run.skillLibraryAuthoring?.bind(t);
	};
	const s = i && a ? prepareCronRunAdmission({
		scheduledExecution: i.occurrence.mint({
			cfg: selectLiveRuntimeConfig(e.followupRun.run.config),
			agentId: e.followupRun.run.agentId,
			runId: t,
			runSessionKey: a,
			toolsAllow: resolveCronRunToolsAllow(i.job),
			operatorAuthority: e.followupRun.operatorAuthority
		}),
		admissionSource: i.admissionSource,
		assertSourceCurrent: o,
		cfg: selectLiveRuntimeConfig(e.followupRun.run.config),
		agentId: e.followupRun.run.agentId,
		runId: t,
		sessionId: e.followupRun.run.sessionId,
		sessionKey: e.runtimePolicySessionKey ?? a,
		sourceReplySessionKey: a,
		jobId: i.job.id,
		deliveryAttemptFence: i.deliveryAttemptFence ?? null,
		operatorAuthority: e.followupRun.operatorAuthority,
		channelRequester: resolveCronAuthenticatedChannelRequester(i.job),
		toolsAllow: resolveCronRunToolsAllow(i.job),
		scheduledToolPolicy: resolveReplyScheduledToolPolicy(e.followupRun.run),
		executionIdentity: i.executionIdentity,
		ingressBoundary: "cron.session-agent",
		resolveGatewayContext: r,
		onAdmitted
	}) : void 0;
	const c = s?.preparedRunAdmission ?? prepareChannelRunAdmission({
		sourceContext: e.followupRun.run,
		cfg: selectLiveRuntimeConfig(e.followupRun.run.config),
		runId: t,
		agentId: e.followupRun.run.agentId,
		ingressKind: "channel",
		boundary: "auto-reply.agent-runner",
		operatorAuthority: e.followupRun.operatorAuthority,
		evidence: e.followupRun.channelAdmissionEvidence,
		gatewayLocalUserIngress: e.followupRun.gatewayLocalUserIngress,
		assertSourceCurrent: o,
		onAdmitted
	});
	let l;
	const closeAdmission = () => {
		try {
			(s?.close ?? c.close)();
		} finally {
			l?.();
		}
	};
	try {
		if (s && i) l = registerCronRunExecSource(t, {
			agentId: e.followupRun.run.agentId,
			jobId: i.job.id,
			jobName: i.job.name,
			jobConfigRevision: resolveCronJobConfigRevision(i.job),
			standingGrantAuthority: s.standingGrantAuthority
		});
		const r = e.replyOperation?.abortSignal;
		const a = e.opts?.abortSignal;
		const o = createDeferredEmbeddedRunLifecycleManager({
			replyOperation: e.replyOperation,
			runId: t,
			agentId: e.followupRun.run.agentId,
			sessionId: e.followupRun.run.sessionId,
			sessionKey: e.sessionKey,
			sessionFile: e.followupRun.run.sessionFile,
			abortSignal: resolveFollowupAbortSignal({
				abortSignal: r && a ? AbortSignal.any([r, a]) : r ?? a,
				operatorAuthority: e.followupRun.operatorAuthority
			})
		});
		return {
			preparedRunAdmission: c,
			admittedRunContext: n,
			deferredLifecycle: o,
			scheduledMessageActionTurnCapability: s?.messageActionTurnCapability,
			async close() {
				try {
					await o.complete();
				} finally {
					await drainAgentRunTerminalWrites(c.operationalRunInstance).finally(closeAdmission);
				}
			}
		};
	} catch (e) {
		closeAdmission();
		throw e;
	}
}
/** Retains the scheduled run's registry claim through terminal settlement. */
function prepareReplyTurnRunSource(e, t) {
	const n = e.followupRun.run.scheduledAutomation;
	let r;
	return {
		claim() {
			n?.assertCurrent();
			if (n) {
				r = claimAgentRunContext(t, {
					sessionKey: e.sessionKey ?? e.followupRun.run.sessionKey,
					sessionId: e.followupRun.run.sessionId,
					agentId: e.followupRun.run.agentId,
					lifecycleGeneration: captureAgentRunLifecycleGeneration(t),
					cronRunsByJobId: /* @__PURE__ */ new Map([[n.job.id, {
						nextCheckEnabled: n.job.pacing !== void 0 || isCronOneShotContinuationJob(n.job),
						assertCurrent: () => {
							n.assertCurrent();
							if (!e.replyOperation || e.replyOperation.result || e.replyOperation.abortSignal.aborted) throw new Error("Automation reply owner has closed");
						}
					}]])
				}, {
					trackOwner: true,
					ownsContext: true
				});
				if (!r) throw new Error("The scheduled run context already has an exclusive owner");
			}
		},
		close() {
			releaseAgentRunContext(t, r);
		}
	};
}
//#endregion
//#region src/auto-reply/reply/agent-runner-auto-fallback.ts
/** Decides whether to retry after rechecking auto-fallback primary probe state. */
function resolveRunAfterAutoFallbackPrimaryProbeRecheck(e) {
	const t = e.run.autoFallbackPrimaryProbe;
	if (!t || !e.sessionKey || !e.entry) return e.run;
	const n = resolveAutoFallbackPrimaryProbe({
		entry: e.entry,
		sessionKey: e.sessionKey,
		primaryProvider: t.provider,
		primaryModel: t.model
	});
	if (n) return {
		...e.run,
		provider: n.provider,
		model: n.model,
		requestedRouteResolution: "resolved",
		autoFallbackPrimaryProbe: n
	};
	const r = resolvePersistedOverrideModelRef({
		defaultProvider: e.run.provider,
		overrideProvider: e.entry.providerOverride,
		overrideModel: e.entry.modelOverride
	});
	const i = normalizeOptionalString(e.entry.authProfileOverride);
	const a = {
		...e.run,
		provider: r?.provider ?? e.run.provider,
		model: r?.model ?? e.run.model,
		requestedRouteResolution: r ? resolveSessionModelOverrideRouteResolution(e.entry) : e.run.requestedRouteResolution,
		autoFallbackPrimaryProbe: void 0
	};
	if (r) {
		a.hasSessionModelOverride = true;
		a.hasAutoFallbackProvenance = hasSessionAutoModelFallbackProvenance(e.entry) || void 0;
	} else {
		delete a.hasSessionModelOverride;
		delete a.hasAutoFallbackProvenance;
	}
	const o = e.entry.modelOverrideSource;
	if (r && o && o !== "default") a.modelOverrideSource = o;
	else delete a.modelOverrideSource;
	if (r && i) {
		a.authProfileId = i;
		const t = resolveCollapsedSessionAuthPinSource(e.entry);
		if (t) a.authProfileIdSource = t;
		else delete a.authProfileIdSource;
	} else if (r) {
		delete a.authProfileId;
		delete a.authProfileIdSource;
	}
	return a;
}
/** Clears a recovered primary probe without overwriting a newer session selection. */
async function clearRecoveredAutoFallbackPrimaryProbeSelection(e) {
	if (shouldPreserveUserFacingSessionStateForInputProvenance(e.run.inputProvenance)) return;
	const t = e.run.autoFallbackPrimaryProbe;
	if (!t || e.provider !== t.provider || e.model !== t.model) return;
	if (!e.sessionKey || !e.activeSessionStore) return;
	if (!e.storePath) {
		const n = e.activeSessionStore[e.sessionKey] ?? e.getActiveSessionEntry();
		if (n && entryMatchesAutoFallbackPrimaryProbe(n, t)) {
			clearAutoFallbackPrimaryProbeSelection(n);
			e.activeSessionStore[e.sessionKey] = n;
		}
		return;
	}
	let n;
	const r = await updateSessionEntry({
		storePath: e.storePath,
		sessionKey: e.sessionKey
	}, (e) => {
		n = e;
		if (!entryMatchesAutoFallbackPrimaryProbe(e, t)) return null;
		const r = resolveSessionAuthProfileOverrideSource(e) === "auto";
		clearAutoFallbackPrimaryProbeSelection(e);
		return {
			providerOverride: void 0,
			modelOverride: void 0,
			modelOverrideSource: void 0,
			modelOverrideRouteResolution: void 0,
			modelOverrideFallbackOriginProvider: void 0,
			modelOverrideFallbackOriginModel: void 0,
			...r ? {
				authProfileOverride: void 0,
				authProfileOverrideSource: void 0,
				authProfileOverrideCompactionCount: void 0
			} : {},
			fallbackNotice: void 0,
			updatedAt: e.updatedAt
		};
	}) ?? n;
	if (r) e.activeSessionStore[e.sessionKey] = r;
	else delete e.activeSessionStore[e.sessionKey];
}
//#endregion
//#region src/auto-reply/reply/agent-runner-context-recovery.ts
/** Builds recovery instructions while preserving the existing session mapping. */
function buildContextOverflowRecoveryText() {
	return "⚠️ Auto-compaction could not recover this turn. I kept this conversation mapped to the current session. Please try again, use /compact, or use /new to start a fresh session.\n\nTry starting a fresh session or using a model with a larger context window.";
}
//#endregion
//#region src/auto-reply/reply/agent-runner-error-handler.ts
const MAX_LIVE_SWITCH_RETRIES = 2;
async function handleAgentExecutionError(e) {
	const t = e.turn;
	const n = e.error;
	const r = e.state.postCompactionModelAttempted && e.state.pendingLifecycleTerminal ? true : void 0;
	const takePendingLifecycleTerminal = () => {
		const n = e.state.pendingLifecycleTerminal?.backstop ?? createAgentLifecycleTerminalBackstop({
			runId: e.runId,
			sessionKey: t.sessionKey,
			onTerminalEvent: t.followupRun.run.internalEventExecution?.onTerminalEvent,
			startedAt: e.state.turnStartedAtMs,
			getLifecycleGeneration: () => e.state.lifecycleGeneration,
			resolveTerminationFields: (e) => resolveReplyOperationTerminationFields(e, t.replyOperation?.abortSignal ?? t.opts?.abortSignal, t.replyOperation)
		});
		e.state.pendingLifecycleTerminal = void 0;
		return n;
	};
	const settleFailure = async (i, a = false) => {
		takePendingLifecycleTerminal().emit("error", n);
		t.replyOperation?.fail("run_failed", n);
		await e.modelPatch.fail(n);
		const o = resolveReplyExpectation({
			...t.followupRun.run,
			scheduledAutomation: t.followupRun.run.scheduledAutomation !== void 0
		});
		i.text = resolveAgentRunFailureText({
			text: i.text,
			replyExpectation: o,
			isGenericRunnerFailure: a,
			visibleReplyDelivered: o === "optional" && a ? await e.resolveVisibleReplyDelivery() : false
		});
		return {
			kind: "final",
			payload: markAgentRunFailureReplyPayload(i),
			postCompactionModelFailure: r
		};
	};
	const resolveReplyOperationAbortAction = (e) => {
		const n = resolveReplyOperationAbortReason(t.replyOperation, e, t.replyOperation?.abortSignal ?? t.opts?.abortSignal);
		if (!n) return;
		if (n === "restart") t.replyOperation?.abortForRestart();
		if (isCliPartialOutputRejected(e)) t.replyOperation?.fail("run_failed", e);
		const r = {
			...n === "user" ? {} : {
				aborted: true,
				stopReason: n
			},
			...t.replyOperation && !hasReplyOperationExecutionStarted(t.replyOperation) ? {
				executionStarted: false,
				providerStarted: false
			} : {}
		};
		takePendingLifecycleTerminal().emit(n === "restart" ? "end" : "error", e, r);
		return {
			kind: "aborted",
			reason: n
		};
	};
	const finalFailure = (e) => ({
		kind: "final",
		payload: markAgentRunFailureReplyPayload({ text: e })
	});
	const i = resolveReplyOperationAbortAction(n);
	if (i) return i;
	if (n instanceof WorkerNodeLostError) {
		const e = resolveReplyOperationRunState(t.opts);
		if (n.canContinue && t.replyOperation && e?.continueStalledTurn?.(`${n.message} Continue the interrupted request from the transcript.`, t.replyOperation)) {
			e.replyCompletion = resolveReplyCompletion(resolveReplyExpectation({
				...t.followupRun.run,
				scheduledAutomation: t.followupRun.run.scheduledAutomation !== void 0
			}), "pending");
			takePendingLifecycleTerminal().emit("end", void 0, {
				yielded: true,
				terminalReply: { disposition: "empty" }
			});
			return {
				kind: "final",
				payload: { text: "" }
			};
		}
		delete e?.replyCompletion;
		return settleFailure({ text: `${n.message} This turn will not be continued automatically.` });
	}
	if (isChannelRunAuthorizationError(n)) {
		if (isChannelRunAuthorizationError(n, "unavailable")) return settleFailure({ text: "⚠️ OpenClaw could not verify current channel access. Please try your request again." });
		takePendingLifecycleTerminal().emit("error", n);
		t.replyOperation?.fail("run_failed", n);
		await e.modelPatch.fail(n);
		defaultRuntime.log("Channel request dropped: source authorization is no longer current.");
		return {
			kind: "final",
			payload: { text: SILENT_REPLY_TOKEN }
		};
	}
	if (n instanceof LiveSessionModelSwitchError) {
		if (e.liveModelSwitchRetries <= MAX_LIVE_SWITCH_RETRIES) {
			e.state.pendingLifecycleTerminal = void 0;
			return {
				kind: "retry",
				liveModelSwitchError: n
			};
		}
		defaultRuntime.error(`Live model switch failed after ${MAX_LIVE_SWITCH_RETRIES} retries (${sanitizeForLog(n.provider)}/${sanitizeForLog(n.model)}). The requested model may be unavailable.`);
		takePendingLifecycleTerminal().emit("error", n);
		const r = e.shouldSurfaceToControlUi ? "⚠️ Couldn't switch models. Choose another model in the Control UI, then try again." : isVerboseFailureDetailEnabled(t.resolvedVerboseLevel) ? "⚠️ Agent failed before reply: model switch could not be completed. The requested model may be temporarily unavailable. Please try again shortly." : "⚠️ Model switch could not be completed. The requested model may be temporarily unavailable. Please try again shortly.";
		t.replyOperation?.fail("run_failed", n);
		await e.modelPatch.fail(n);
		return finalFailure(r);
	}
	const a = formatErrorMessage$1(n);
	e.timing.logIfSlow({
		runId: e.runId,
		sessionId: t.followupRun.run.sessionId,
		sessionKey: t.sessionKey,
		outcome: "error",
		error: a
	});
	if (isAgentHarnessPreflightError(n)) {
		const r = buildExternalRunFailureReply({
			message: a,
			error: n
		}, { includeDetails: isVerboseFailureDetailEnabled(t.resolvedVerboseLevel) });
		return await settleFailure({ text: e.shouldSurfaceToControlUi && n.userMessage === void 0 ? renderControlUiAgentFailureCopy() : r.text }, r.isGenericRunnerFailure);
	}
	const o = resolveReplyFailoverFacts(n, a);
	const s = resolveReplyFailureSummary({
		error: n,
		message: a,
		reason: o.reason,
		attempts: isFailoverError(n) ? n.attempts : void 0
	});
	const c = o.reason;
	const l = s?.kind === "billing";
	const u = !l && (c === "context_overflow" || isLikelyContextOverflowError(a));
	const d = !l && isCompactionFailureError(a);
	const f = classifyOAuthRefreshFailureError(n) ?? classifyOAuthRefreshFailure(a);
	const p = buildAuthProfileFailoverFailureText(n) !== null;
	const m = !l && !f && !p && !e.shouldSurfaceToControlUi ? o.providerRequestError : void 0;
	if (resolveRestartLifecycleError(n) instanceof GatewayDrainingError) {
		t.replyOperation?.abortForRestart();
		takePendingLifecycleTerminal().emit("end", void 0, {
			aborted: true,
			stopReason: "restart"
		});
		return {
			kind: "aborted",
			reason: "restart"
		};
	}
	if (d) {
		takePendingLifecycleTerminal().emit("error", n);
		defaultRuntime.error(`Auto-compaction failed (${a}). Preserving existing session mapping for ${t.sessionKey ?? t.followupRun.run.sessionId}.`);
		t.replyOperation?.fail("run_failed", n);
		return finalFailure(buildContextOverflowRecoveryText());
	}
	const h = findCliTimeoutError(n)?.cliTimeout.observedActivity === true;
	if (m) return await settleFailure({ text: s?.kind === "rate_limit" && isFailoverError(n) && n.rateLimitRetriesExhausted !== void 0 ? s.text : m.userMessage });
	defaultRuntime.error(`Embedded agent failed before reply: ${a}`);
	const g = !s && !u ? buildExternalRunFailureReply({
		message: a,
		error: n
	}, {
		includeAuthProfileId: !isNonDirectConversationContext(t.sessionCtx),
		includeDetails: isVerboseFailureDetailEnabled(t.resolvedVerboseLevel),
		replayPrevented: h,
		failoverFacts: o
	}) : void 0;
	const _ = !e.shouldSurfaceToControlUi || g?.isGenericRunnerFailure === false || g?.presentation || renderFailoverCodeUserCopy(o.code) ? g : void 0;
	return await settleFailure({
		text: s?.text ?? (u ? "⚠️ Context overflow — prompt too large for this model. Try a shorter message or a larger-context model." : _?.text ?? (e.shouldSurfaceToControlUi ? renderControlUiAgentFailureCopy() : "⚠️ OpenClaw couldn't finish this request. Check the conversation before trying again. For details, open Settings → Logs in the Control UI or run `openclaw logs --follow`.")),
		..._?.presentation ? { presentation: _.presentation } : {}
	}, !s && !u && (g?.isGenericRunnerFailure ?? true));
}
//#endregion
//#region src/auto-reply/reply/agent-runner-execution-mcp-context.ts
function applyMcpAppModelContext(e, t) {
	const n = e.mcpAppContextLease;
	if (!n) return {
		params: e,
		currentTurnImages: t
	};
	n.assertCurrent();
	const r = t.images ?? [];
	const i = n.project(r.length);
	const a = {
		...e,
		followupRun: {
			...e.followupRun,
			currentInboundContext: appendCurrentInboundContext(e.followupRun.currentInboundContext, [i.context], i.legacyText)
		}
	};
	let o = t;
	const s = i.images;
	if (s.length) o = {
		...t,
		images: [...r, ...s],
		imageOrder: [...t.imageOrder ?? r.map(() => "inline"), ...s.map(() => "inline")],
		...t.mediaImageLayout ? { mediaImageLayout: {
			...t.mediaImageLayout,
			slots: [...t.mediaImageLayout.slots, ...s.map(() => ({ kind: "inline" }))]
		} } : {}
	};
	return {
		params: a,
		currentTurnImages: o
	};
}
//#endregion
//#region src/infra/message-tool-run-outcome-store.ts
/** Keeps incognito side data; durable diagnostic outcomes have no reader. */
async function recordMessageToolRunOutcome(e) {
	const t = {
		assertCurrent() {},
		authorize() {}
	};
	if (!captureSessionActorStorageOwner(e, t)) return false;
	const n = {
		run_id: e.runId,
		session_key: e.sessionKey,
		agent_id: e.agentId,
		provider: e.provider,
		model: e.model,
		outcome: e.outcome,
		run_status: e.runStatus,
		occurred_at: e.occurredAt
	};
	if (!await withSessionActorStorage(e, {
		authority: t,
		lifetime: {
			assertCurrent: () => t.assertCurrent(),
			assertReadable: () => t.assertCurrent()
		}
	}, async ({ actor: e, authority: t }) => {
		const r = await e.storage.mutate({
			type: "session.messageToolOutcome.record",
			input: n
		}, t);
		readSessionActorStorageResult(r);
		return true;
	})) throw new IncognitoSessionMissingError();
	return true;
}
//#endregion
//#region src/auto-reply/reply/agent-runner-execution-outcome.ts
const messageToolOutcomeLog = createSubsystemLogger("auto-reply/message-tool-outcome");
async function recordAgentTurnExecutionOutcome(e, t) {
	if (t?.outcome.kind === "settled" && e.opts?.onVisibleWorkSessions) {
		const n = /* @__PURE__ */ new Map();
		for (const e of t.outcome.result.acceptedSessionSpawns ?? []) if (e.sessionUrl && !n.has(e.childSessionKey)) n.set(e.childSessionKey, {
			sessionKey: e.childSessionKey,
			url: e.sessionUrl,
			...e.publicRead === true ? { publicRead: true } : {},
			...e.label ? { label: e.label } : {}
		});
		if (n.size > 0) await e.opts.onVisibleWorkSessions([...n.values()]);
	}
	const n = resolveAgentTurnExecutionStatus(t?.outcome);
	if (n !== "cancelled" && !(t?.outcome.kind === "rejected" && resolveReplyOperationRunState(e.opts)?.replyCompletion?.outcome === "pending")) e.opts?.onAgentRunTerminalOutcome?.(n === "ok" ? "completed" : "failed");
	if ((e.followupRun.run.sourceReplyDeliveryMode ?? e.opts?.sourceReplyDeliveryMode) !== "message_tool_only") return;
	const r = e.sessionKey ?? e.followupRun.run.sessionKey;
	if (!r) {
		messageToolOutcomeLog.warn("message-tool-only run outcome missing session key", {
			runId: t?.runId ?? e.opts?.runId,
			agentId: e.followupRun.run.agentId
		});
		return;
	}
	const i = t?.outcome;
	const a = i?.kind === "settled" || i?.kind === "rejected" ? i.resolved : void 0;
	const o = n === "ok" ? "completed" : n === "failed" ? "errored" : "aborted";
	const s = i?.kind === "settled" && hasCompletedSourceReplyDeliveryEvidence(i.result);
	if (s && n === "ok" && e.replyOperation) handoffCompletedSourceReply(e.replyOperation, e.followupRun);
	const c = {
		runId: t?.runId ?? e.opts?.runId ?? "unknown",
		sessionKey: r,
		agentId: e.followupRun.run.agentId,
		provider: a?.provider ?? e.followupRun.run.provider,
		model: a?.model ?? e.followupRun.run.model,
		outcome: s ? "tool_delivered" : "mute",
		runStatus: o,
		occurredAt: Date.now(),
		storePath: e.storePath
	};
	try {
		if (await recordMessageToolRunOutcome(c)) messageToolOutcomeLog.info("recorded message-tool-only run outcome", c);
	} catch (e) {
		messageToolOutcomeLog.warn("failed to record message-tool-only run outcome", {
			...c,
			error: formatErrorMessage$1(e)
		});
	}
}
async function recordSessionEventTerminalOutcome(e, t, n) {
	await e?.onTerminal(t, n?.outcome.kind === "aborted" ? "aborted" : n?.outcome.kind === "settled" && n.outcome.status === "ok" ? "completed" : "failed", n?.outcome.kind === "settled" ? {
		...n.outcome.result,
		resolved: n.outcome.resolved
	} : n?.outcome.kind === "rejected" ? {
		payloads: [n.outcome.payload],
		resolved: n.outcome.resolved
	} : void 0);
}
/** Source custody settles native work before publishing the turn's terminal observations. */
async function runAgentTurnWithOutcome(e, t, n) {
	bindGoalContinuationExecution(t, e.sessionKey ?? e.followupRun.run.sessionKey);
	const r = e.followupRun.run.internalEventExecution;
	const i = prepareReplyTurnRunSource(e, t);
	let a = false;
	try {
		if (r) {
			r.assertCurrent?.();
			await r.beforeStart?.();
			e.replyOperation?.abortSignal.throwIfAborted();
			r.assertCurrent?.();
		}
		i.claim();
		const o = e.followupRun.controllerInput?.sourceAdapter;
		const s = await withExecRequestTurn({
			identity: {
				runId: t,
				sessionKey: e.sessionKey ?? e.followupRun.run.sessionKey,
				sessionId: e.followupRun.run.sessionId,
				agentId: e.followupRun.run.agentId,
				...o?.requester?.connectionId !== void 0 ? { ownerConnId: o.requester.connectionId } : {},
				...o?.requester?.deviceId !== void 0 ? { ownerDeviceId: o.requester.deviceId } : {},
				...o?.initiatingPersonalOperator ? { initiatingPersonalOperator: o.initiatingPersonalOperator } : {},
				...o?.controlUiVisible !== void 0 ? { controlUiVisible: o.controlUiVisible } : {},
				...o?.turnKind ? { turnKind: o.turnKind } : {}
			},
			owners: r?.execRequestOwners,
			abortSignal: e.replyOperation?.abortSignal ?? e.opts?.abortSignal
		}, () => withVisibleWorkSessionReporter({
			requesterSessionKey: e.sessionKey ?? e.followupRun.run.sessionKey,
			report: e.opts?.onVisibleWorkSessions
		}, n));
		const c = e.followupRun.run.scheduledAutomation;
		const l = c ? getAgentRunContext(t)?.cronRunsByJobId?.get(c.job.id) : void 0;
		if (c && l) {
			l.closed = true;
			if (s.outcome.kind === "settled") s.outcome.automation = {
				result: l.result,
				includeReasoning: c.job.payload.kind === "agentTurn" && c.job.payload.includeReasoning === true
			};
		}
		await recordAgentTurnExecutionOutcome(e, s);
		a = true;
		await recordSessionEventTerminalOutcome(r, t, s);
		return s;
	} catch (n) {
		r?.onFailed?.(n);
		if (!a) {
			await recordAgentTurnExecutionOutcome(e, void 0);
			await recordSessionEventTerminalOutcome(r, t, void 0);
		}
		throw n;
	} finally {
		i.close();
	}
}
//#endregion
//#region src/auto-reply/reply/agent-event-bridge.ts
function createAgentEventDeliveryStartOrder(e) {
	let t = Promise.resolve();
	let n = Promise.resolve();
	return {
		preserveCallbackStartOrder: e?.preserveCallbackStartOrder ?? true,
		schedule: (e, r) => {
			const i = t;
			const a = n;
			const o = createDeferredCore();
			t = o.promise;
			const s = (async () => {
				await i;
				if (r?.waitForEarlierDeliveries) await a;
				let t;
				try {
					t = e();
				} finally {
					o.resolve();
				}
				await t;
			})();
			n = Promise.all([a, s.catch(() => void 0)]).then(() => void 0);
			return s;
		}
	};
}
function createAgentEventBridge(e) {
	const t = e.deliver;
	if (!t) return {
		unsubscribe: () => void 0,
		drain: async () => void 0
	};
	let n = Promise.resolve();
	return {
		unsubscribe: onAgentEventForRun(e.runId, (r) => {
			if (e.suppressed) return;
			const i = e.read(r);
			if (i === void 0) return;
			if (!e.startOrder) {
				n = n.then(() => t(i)).catch(() => void 0);
				return;
			}
			const a = n;
			const o = e.startOrder.schedule(() => e.startOrder?.preserveCallbackStartOrder === false ? a.then(() => t(i)) : t(i), { waitForEarlierDeliveries: e.waitForEarlierDeliveries?.(i) }).catch(() => void 0);
			n = Promise.all([n, o]).then(() => void 0);
		}),
		async drain() {
			await n;
		}
	};
}
//#endregion
//#region src/auto-reply/reply/agent-runner-cli-dispatch.ts
async function stopAgentEventBridges(e) {
	for (const t of e) t.unsubscribe();
	for (const t of e) await t.drain();
}
function createCliReasoningStreamBridge(e) {
	if (!e) return;
	return async ({ text: t, isReasoningSnapshot: n }) => {
		await e({
			text: t,
			...n ? { isReasoningSnapshot: n } : {},
			requiresReasoningProgressOptIn: true
		});
	};
}
function keepCliSessionBindingOnlyWhenReused(e) {
	const t = normalizeOptionalString(e.existingSessionId);
	const n = e.result.meta.agentMeta;
	const r = normalizeOptionalString(n?.cliSessionBinding?.sessionId);
	const i = n?.clearCliSessionBinding === true;
	if (n === void 0 || !i && t === void 0 || r === t) return e.result;
	if (r || i) e.onDroppedReplacement?.();
	return {
		...e.result,
		meta: {
			...e.result.meta,
			agentMeta: {
				...n,
				sessionId: "",
				cliSessionBinding: void 0,
				clearCliSessionBinding: void 0
			}
		}
	};
}
function readToolEventPayload(e) {
	const t = e.data.phase;
	if (t !== "start" && t !== "update" && t !== "result") return;
	return {
		name: typeof e.data.name === "string" ? e.data.name : void 0,
		phase: t,
		args: isRecord(e.data.args) ? e.data.args : void 0,
		toolCallId: typeof e.data.toolCallId === "string" ? e.data.toolCallId : void 0,
		...t === "result" ? {
			isError: e.data.isError === true,
			result: e.data.result
		} : {}
	};
}
/** CLI result summaries use start-event metadata; full verbosity also carries raw output. */
function createCliToolSummaryTracker(e) {
	const t = /* @__PURE__ */ new Map();
	return { noteToolEvent: async (n) => {
		if (n.phase === "start") {
			if (n.toolCallId && n.name) {
				const r = stripOpenClawMcpToolPrefix(n.name);
				t.set(n.toolCallId, {
					name: r,
					meta: inferToolMetaFromArgsCore(r, n.args, { detailMode: e.detailMode ?? "explain" }),
					commandBearing: isCommandBearingToolCall(r, n.args)
				});
			}
			return false;
		}
		if (n.phase !== "result") return false;
		const r = n.toolCallId ? t.get(n.toolCallId) : void 0;
		const i = n.name === void 0 ? r?.name : stripOpenClawMcpToolPrefix(n.name);
		const a = e.commandDetailsVisible || !r?.commandBearing ? r?.meta : void 0;
		if (n.toolCallId) t.delete(n.toolCallId);
		if (n.isError !== true && isAgentPlanProgressToolName(i ?? "")) return false;
		if (!e.shouldEmitToolResult()) return r?.commandBearing === true;
		const o = formatToolAggregate(i, a ? [a] : void 0, { markdown: true });
		let s = o;
		if (e.shouldEmitToolOutput()) {
			const e = extractToolResultText(n.result)?.trim();
			if (e) s = `${o}\n\`\`\`txt\n${e}\n\`\`\``;
		}
		if (!s.trim()) return r?.commandBearing === true;
		await e.deliver({
			text: s,
			...n.isError === true ? { isError: true } : {}
		});
		return r?.commandBearing === true;
	} };
}
function runCliAgentWithLifecycle(e) {
	if (!e.lifecycleGeneration) return runCliAgentWithLifecycleInternal(e);
	return withAgentRunLifecycleGeneration(e.lifecycleGeneration, () => runCliAgentWithLifecycleInternal(e));
}
async function runCliAgentWithLifecycleInternal(e) {
	const t = e.startedAt ?? Date.now();
	const n = e.runParams.fastModeStartedAtMs ?? t;
	const r = e.runParams.fastModeAutoOnSeconds ?? 60;
	const i = e.runParams.fastModeAutoProgressState ?? {
		offAnnounced: false,
		resetAnnounced: false
	};
	const emitFastModeAutoProgress = async (t) => {
		const n = formatFastModeAutoProgressText(t);
		emitAgentEvent({
			runId: e.runId,
			stream: "item",
			data: {
				kind: "status",
				title: "Fast",
				phase: "update",
				summary: n
			},
			...e.runParams.sessionKey ? { sessionKey: e.runParams.sessionKey } : {}
		});
		try {
			await e.onFastModeAutoProgress?.({
				text: n,
				channelData: { openclawProgressKind: FAST_MODE_AUTO_PROGRESS_KIND }
			});
		} catch {}
	};
	const maybeAnnounceFastModeAutoOff = async () => {
		if (e.runParams.fastMode !== "auto" || i.offAnnounced) return;
		const t = resolveFastModeForElapsed({
			mode: "auto",
			startedAtMs: n,
			fastAutoOnSeconds: r
		});
		if (t.enabled) return;
		i.offAnnounced = true;
		await emitFastModeAutoProgress(t);
	};
	let a = false;
	const startLifecycle = () => {
		if (a) return;
		e.onAgentRunStart?.();
		a = true;
		emitAgentEvent({
			runId: e.runId,
			...e.runParams.agentId ? { agentId: e.runParams.agentId } : {},
			...e.runParams.sessionKey ? { sessionKey: e.runParams.sessionKey } : {},
			...e.runParams.sessionId ? { sessionId: e.runParams.sessionId } : {},
			...e.lifecycleGeneration ? { lifecycleGeneration: e.lifecycleGeneration } : {},
			stream: "lifecycle",
			data: {
				phase: "start",
				startedAt: t
			}
		});
	};
	if (!e.deferLifecycleStartUntilExecution) startLifecycle();
	const o = createAgentEventDeliveryStartOrder({ preserveCallbackStartOrder: e.preserveProgressCallbackStartOrder === true });
	const s = {
		runId: e.runId,
		suppressed: e.suppressAssistantBridge,
		startOrder: o
	};
	const createProgressBridge = (e, t) => createAgentEventBridge({
		...s,
		...t,
		read: (n) => n.stream === e ? t.read(n) : void 0
	});
	const { onAssistantText: c, onCompletedReply: l } = e;
	let u;
	let d;
	let f;
	let p;
	const m = [
		e.onActivity ? createAgentEventBridge({
			runId: e.runId,
			read: () => ({}),
			deliver: async () => {
				e.onActivity?.();
			}
		}) : void 0,
		createProgressBridge("assistant", {
			waitForEarlierDeliveries: (e) => e.completed,
			deliver: async (e) => {
				if (e.completed) await l?.(e.text, e.assistantMessageIndex);
				else await c?.(e.text);
			},
			read: (e) => {
				if (typeof e.data.completedText === "string" && typeof e.data.assistantMessageIndex === "number") return {
					text: e.data.completedText,
					completed: true,
					assistantMessageIndex: e.data.assistantMessageIndex
				};
				const t = typeof e.data.text === "string" ? e.data.text : void 0;
				if (t === void 0 || t === u) return;
				u = t;
				return {
					text: t,
					completed: false
				};
			}
		}),
		createProgressBridge("thinking", {
			read: (e) => {
				const t = typeof e.data.text === "string" ? e.data.text : void 0;
				if (t === void 0 || t === f) return;
				f = t;
				return {
					text: t,
					...e.data.isReasoningSnapshot === true ? { isReasoningSnapshot: true } : {}
				};
			},
			deliver: async (t) => {
				d = normalizeOptionalString(t.text);
				await e.onReasoningText?.(t);
			}
		}),
		createProgressBridge("thinking", {
			read: (e) => {
				const t = asPositiveFiniteNumber(e.data.progressTokens);
				if (t === void 0 || t === p) return;
				p = t;
				return { progressTokens: t };
			},
			deliver: e.onReasoningProgress
		}),
		createProgressBridge("compaction", {
			deliver: async (t) => {
				if (t.phase === "start") await e.onCompactionStart?.();
				else await e.onCompactionEnd?.({ completed: t.completed });
			},
			read: (e) => {
				if (e.data.phase === "start") return { phase: "start" };
				return e.data.phase === "end" ? {
					phase: "end",
					completed: e.data.completed === true
				} : void 0;
			}
		}),
		createProgressBridge("tool", {
			deliver: e.onToolEvent,
			read: readToolEventPayload
		}),
		createProgressBridge("item", {
			deliver: e.onCommentaryText,
			read: (e) => {
				if (e.data.kind !== "preamble") return;
				const t = typeof e.data.progressText === "string" ? e.data.progressText.trim() : "";
				return t ? {
					text: t,
					...typeof e.data.itemId === "string" ? { itemId: e.data.itemId } : {}
				} : void 0;
			}
		}),
		createProgressBridge("item", {
			read: (e) => e.data.kind !== "preamble" && Value.Check(AgentActivityItemSchema, e.data) ? e.data : void 0,
			deliver: e.onItemEvent ? (t) => e.onItemEvent?.(t) : void 0
		}),
		createProgressBridge("plan", {
			deliver: e.onPlanUpdate,
			read: (e) => ({
				phase: normalizeOptionalString(e.data.phase),
				title: normalizeOptionalString(e.data.title),
				explanation: normalizeOptionalString(e.data.explanation),
				...e.data.explanationFormat === "plain" ? { explanationFormat: "plain" } : {},
				steps: normalizeAgentPlanSteps(e.data.steps),
				source: normalizeOptionalString(e.data.source)
			})
		}),
		createAgentEventBridge({
			runId: e.runId,
			suppressed: e.suppressAssistantBridge,
			deliver: maybeAnnounceFastModeAutoOff,
			read: (e) => {
				if (e.stream !== "tool") return;
				const t = typeof e.data.phase === "string" ? e.data.phase : "";
				return [
					"completed",
					"end",
					"error",
					"result"
				].includes(t) ? true : void 0;
			}
		})
	].filter((e) => e !== void 0);
	try {
		await e.runParams.awaitSessionDiffBaseline?.();
		const t = await runCliAgent({
			...e.runParams,
			...e.deferLifecycleStartUntilExecution ? { onExecutionStarted: async () => {
				await e.runParams.onExecutionStarted?.();
				e.runParams.abortSignal?.throwIfAborted();
				e.runParams.assertCurrent?.();
				startLifecycle();
			} } : {},
			emitCommentaryText: e.runParams.emitCommentaryText ?? Boolean(e.onCommentaryText)
		});
		const n = e.runParams.abortSignal?.reason;
		if (isAgentRunRestartAbortReason(n)) throw n;
		const r = e.transformResult?.(t) ?? t;
		await stopAgentEventBridges(m);
		const i = r.payloads?.length ? normalizeOptionalString(r.meta.finalAssistantVisibleText) ?? normalizeOptionalString(r.payloads[0]?.text) : void 0;
		const a = d ? {
			...r,
			payloads: [{
				text: d,
				isReasoning: true
			}, ...r.payloads ?? []]
		} : r;
		if (i) emitAgentEvent({
			runId: e.runId,
			stream: "assistant",
			data: {
				itemId: cliAssistantItemId(e.runId),
				text: i
			}
		});
		return a;
	} catch (t) {
		await stopAgentEventBridges(m);
		await e.onErrorBeforeLifecycle?.(t);
		throw t;
	} finally {
		if (e.runParams.isFinalFallbackAttempt !== false && e.runParams.fastMode === "auto" && i.offAnnounced && !i.resetAnnounced) {
			i.resetAnnounced = true;
			await emitFastModeAutoProgress({
				enabled: true,
				elapsedSeconds: 0,
				fastAutoOnSeconds: r
			});
		}
	}
}
//#endregion
//#region src/auto-reply/reply/agent-runner-command-output.ts
/** CLI outcomes use raw strings/text blocks; structured runners supply records. */
function readToolResultText(e) {
	const t = readStringValue(e);
	if (t !== void 0) return t;
	if (!Array.isArray(e)) return;
	return e.map((e) => readStringValue(asOptionalRecord(e)?.text)).filter((e) => e !== void 0).join("\n").trim() || void 0;
}
function buildCommandOutputFromToolResultEvent(e) {
	if (e.stream !== "tool" || e.data.phase !== "result") return;
	const t = e.data.name;
	const n = e.data.commandBearing === true;
	if (!t || !n && !isShellToolDisplayName(t)) return;
	const r = asOptionalRecord(e.data.result);
	const i = asOptionalRecord(r?.details);
	const a = e.data.output ?? readStringValue(r?.output) ?? readStringValue(i?.output) ?? readToolResultText(e.data.result);
	const o = e.data.status ?? readStringValue(r?.status) ?? readStringValue(i?.status);
	const s = r?.exitCode ?? i?.exitCode ?? e.data.exitCode;
	const c = s === null ? null : asFiniteNumber(s);
	const l = asFiniteNumber(r?.durationMs ?? i?.durationMs ?? e.data.durationMs);
	const u = e.data.cwd;
	const d = e.data.isError === true ? "failed" : e.data.isError === false ? "completed" : void 0;
	if (!(a !== void 0 || o !== void 0 || c !== void 0 || l !== void 0 || u !== void 0 || n && typeof e.data.isError === "boolean" || r !== void 0 && Object.keys(r).length > 0)) return;
	const f = e.data.args;
	const p = e.data.title ?? (f ? inferToolMetaFromArgsCore(stripOpenClawMcpToolPrefix(t), f, { detailMode: "explain" }) : void 0);
	return {
		itemId: e.data.itemId,
		phase: "end",
		title: p,
		toolCallId: e.data.toolCallId,
		name: t,
		output: a,
		status: o ?? d,
		exitCode: c,
		durationMs: l,
		cwd: u
	};
}
//#endregion
//#region src/auto-reply/reply/agent-runner-helpers.ts
const isAudioPayload = (e) => resolveSendableOutboundReplyParts(e).mediaUrls.some(isAudioFileName);
function createVerboseGate(e, t) {
	return () => t(e.verboseLevelOverride ?? normalizeVerboseLevel(e.getVerboseLevel?.() ?? "") ?? e.resolvedVerboseLevel);
}
const createShouldEmitToolResult = (e) => createVerboseGate(e, (e) => e !== "off");
const createShouldEmitToolOutput = (e) => createVerboseGate(e, (e) => e === "full");
const signalTypingIfNeeded = async (e, t) => {
	if (e.some((e) => hasOutboundReplyContent(e, { trimText: true }))) await t.signalRunStart();
};
//#endregion
//#region src/auto-reply/reply/agent-runner-media-context.ts
function buildReplyMediaContextParams({ run: e, originatingAccountId: t }, n, r) {
	return {
		cfg: r,
		agentId: e.agentId,
		sessionKey: n,
		workspaceDir: e.workspaceDir,
		mediaNormalizationOwner: e.mediaNormalizationOwner,
		messageProvider: e.messageProvider,
		accountId: t ?? e.agentAccountId,
		groupId: e.groupId,
		groupChannel: e.groupChannel,
		groupSpace: e.groupSpace,
		requesterSenderId: e.senderId,
		requesterSenderName: e.senderName,
		requesterSenderUsername: e.senderUsername,
		requesterSenderE164: e.senderE164
	};
}
//#endregion
//#region src/auto-reply/reply/agent-runner-presentation.ts
async function deliverPreparedBlockReply(e, t, n) {
	if (e?.onPreparedBlockReply) for (const r of createStructuredOutboundPayloadPlan([t])) await e.onPreparedBlockReply(r, n);
	else await e?.onBlockReply?.(t, n);
}
/** Builds the channel-presentation callbacks shared by CLI and embedded runs. */
function createAgentTurnPresentation(e) {
	const classifyReplyText = (t, n) => {
		let r = t.text;
		const i = resolveSendableOutboundReplyParts(t, { text: "" });
		if (e.turn.followupRun.run.silentExpected && !shouldKeepPayloadDuringSilentTurn(t)) return { skip: true };
		if (n !== false && r?.includes("HEARTBEAT_OK")) {
			const e = stripHeartbeatToken(r, { mode: "message" });
			if (e.shouldSkip && !i.hasMedia) return { skip: true };
			r = e.text;
		}
		if (getReplyPayloadMetadata(t)?.silentReply === true) return { skip: true };
		if (!r) return i.hasMedia ? {
			text: void 0,
			skip: false
		} : { skip: true };
		return {
			text: r,
			skip: false
		};
	};
	const sanitizeStreamingText = (t, n, r = false) => {
		if (!t) return { skip: true };
		const i = e.turn.sessionCtx.agentText ?? e.turn.sessionCtx.BodyForAgent;
		const a = n ? renderUserFacingText(t, {
			errorContext: true,
			conversationContext: i,
			streaming: true
		}) : sanitizeUserFacingText(t, {
			conversationContext: i,
			streaming: true,
			preserveLeadingSourceBoundary: r
		});
		return a.trim() ? {
			text: a,
			skip: false
		} : { skip: true };
	};
	const normalizeStreamingText = (e) => {
		const t = classifyReplyText(e);
		if (t.skip || !t.text) return t;
		return sanitizeStreamingText(t.text, Boolean(e.isError), getReplyPayloadMetadata(e)?.streamedSourceBoundary === true);
	};
	const t = e.turn.opts?.preserveProgressCallbackStartOrder === true;
	const presentWithTyping = async (n, r) => {
		if (!t) {
			await n;
			const t = e.turn.replyOperation;
			if (t && (t.abortSignal.aborted || t.result || hasCommittedReplyOperationOutcome(t))) return false;
			return await r();
		}
		let i;
		try {
			i = r();
		} catch (e) {
			n.catch(() => void 0);
			throw e;
		}
		const [, a] = await Promise.all([n, i]);
		return a;
	};
	let n = "";
	let r = false;
	let i = 0;
	let a;
	const presentPartialReply = async (t, o) => {
		const s = t.delta;
		const c = o === "embedded" && s !== void 0 && !t.replace;
		if (!r) {
			const e = c ? n + s : t.text ?? "";
			r = e.includes("HEARTBEAT_OK");
			n = e.slice(-11);
		}
		const l = classifyReplyText(t, r);
		if (l.skip || !l.text) return o === "embedded" ? false : void 0;
		let u = l.text;
		if (c && !r) {
			const e = l.text.length === i + s.length;
			a = /\S/.exec(e ? s : l.text)?.[0] ?? (e ? a : void 0);
			i = l.text.length;
			u = a ?? "";
		} else i = 0;
		let d = false;
		let f;
		const materializeText = () => {
			if (!d) {
				const e = sanitizeStreamingText(l.text, false);
				f = e.skip ? void 0 : e.text;
				d = true;
			}
			return f;
		};
		const p = o === "cli" ? { text: materializeText() } : {
			get text() {
				return materializeText();
			},
			mediaUrls: t.mediaUrls
		};
		const m = e.turn.opts?.onPartialReply;
		return await presentWithTyping(e.turn.typingSignals.signalTextDelta(u), () => !m || o === "cli" && !p.text ? false : m(p));
	};
	const o = e.turn.blockReplyPipeline;
	return {
		presentPartialReply,
		normalizeStreamingText,
		presentWithTyping,
		blockReplyHandler: e.turn.opts?.onPreparedBlockReply || e.turn.opts?.onBlockReply ? createBlockReplyDeliveryHandler({
			onBlockReply: (t, n) => deliverPreparedBlockReply(e.turn.opts, t, n),
			currentMessageId: e.turn.sessionCtx.MessageSidFull ?? e.turn.sessionCtx.MessageSid,
			replyThreading: e.turn.replyThreading,
			normalizeStreamingText,
			applyReplyToMode: e.turn.applyReplyToMode,
			normalizeMediaPaths: e.replyMediaContext.normalizePayload,
			typingSignals: e.turn.typingSignals,
			reasoningPayloadsEnabled: e.turn.opts?.reasoningPayloadsEnabled,
			commentaryPayloadsEnabled: e.turn.opts?.commentaryPayloadsEnabled,
			silentExpected: e.turn.followupRun.run.silentExpected,
			blockStreamingEnabled: e.turn.blockStreamingEnabled,
			blockReplyPipeline: o,
			directBlockDeliveries: e.directBlockDeliveries
		}) : void 0
	};
}
/** Records acknowledged partial visibility while preserving lazy payload access. */
function prepareReplyRunOptions({ opts: e, runId: t, abortSignal: n, onVisiblePartialReply: r }) {
	let i = false;
	const a = e?.onPartialReply;
	return {
		runOptions: {
			...e,
			runId: t,
			abortSignal: n,
			...a ? { onPartialReply: async (e) => {
				const t = await settleProgressVisibilityCallbackResult(a(e));
				if (t.visible && (i || hasOutboundReplyContent(e, { trimText: true }))) {
					i = true;
					r();
				}
				return t.result;
			} } : {}
		},
		hasVisiblePartialReply: () => i
	};
}
/** Prepares channel presentation resources for a newly admitted reply turn. */
function prepareReplyRunPresentation(e, t, n, r) {
	const { followupRun: i, sessionCtx: a, sessionKey: o, opts: s, blockStreamingEnabled: c, blockReplyChunking: l } = e;
	const u = resolveOriginMessageProvider({
		originatingChannel: a.OriginatingChannel,
		provider: a.Surface ?? a.Provider
	});
	const d = i.originatingReplyToMode ?? resolveReplyToMode(t, u, a.AccountId, a.ChatType);
	const f = createReplyToModeFilterForChannel(d, u);
	const p = createReplyMediaContext(buildReplyMediaContextParams(i, o, t));
	const m = a.MessageSidFull ?? a.MessageSid;
	const sendDirectCompactionNotice = async (e, r) => {
		if (e !== "context_bounded" && e !== "degraded" && !shouldNotifyUserAboutCompaction(t)) return;
		const i = createCompactionNoticePayload({
			phase: e,
			text: r,
			currentMessageId: m,
			applyReplyToMode: f
		});
		try {
			if (s?.onBlockReply) await s.onBlockReply(i);
			else n.push(i);
		} catch (e) {
			logVerbose(`context maintenance notice delivery failed: ${String(e)}`);
		}
	};
	return {
		cfg: t,
		replyToChannel: u,
		replyToMode: d,
		applyReplyToMode: f,
		replyMediaContext: p,
		blockReplyPipeline: c && (s?.onPreparedBlockReply || s?.onBlockReply) ? createBlockReplyPipeline({
			onBlockReply: (e, t) => deliverPreparedBlockReply(s, e, t),
			timeoutMs: r,
			coalescing: resolveEffectiveBlockStreamingConfig({
				cfg: t,
				provider: a.Provider,
				accountId: a.AccountId,
				chunking: l
			}).coalescing,
			isAudioPayload
		}) : null,
		sendDirectCompactionNotice
	};
}
//#endregion
//#region src/auto-reply/reply/cli-reply-payload.ts
function prepareCliReplyPayload(e, t, n) {
	const r = parseReplyDirectives(e, { currentMessageId: t });
	const i = {
		text: r.text,
		mediaUrls: r.mediaUrls,
		replyToId: r.replyToId,
		replyToCurrent: r.replyToCurrent,
		...r.replyToTag ? { replyToTag: true } : {},
		audioAsVoice: r.audioAsVoice
	};
	addReplyPayloadMediaFailures(i, r.mediaFailures);
	if (n !== void 0) setReplyPayloadMetadata(i, { assistantMessageIndex: n });
	return i;
}
//#endregion
//#region src/auto-reply/reply/agent-runner-cli-candidate.ts
async function runCliFallbackCandidate(e) {
	const t = resolveCyberAccessProgramForProvider(e.candidateRun.cyberAccessProgram, e.provider).program;
	if (t !== void 0 && t !== "standard") throw new Error("Daybreak access is unsupported by this CLI runtime. Select Standard or use the OpenClaw or native Codex runtime.");
	const n = e.turn;
	e.scheduledInference?.assertCandidate(e.provider, true);
	const r = n.opts?.onPreparedBlockReply;
	const i = n.opts?.onBlockReply ?? (r ? (e, t) => deliverPreparedBlockReply({ onPreparedBlockReply: r }, e, t) : void 0);
	const a = n.getActiveSessionEntry()?.lifecycleRevision;
	const o = findModelInCatalog(e.candidateRun.thinkingCatalog ?? [], e.provider, e.model);
	const s = await resolveRunModelHasVision({
		run: e.candidateRun,
		provider: e.provider,
		model: e.model
	});
	const c = n.sessionKey ?? n.followupRun.run.sessionKey;
	const l = c && n.storePath ? {
		agentId: n.followupRun.run.agentId,
		sessionId: n.followupRun.run.sessionId,
		sessionKey: c,
		storePath: n.storePath
	} : void 0;
	const u = Date.now();
	const d = createAgentLifecycleTerminalBackstop({
		runId: e.runId,
		sessionKey: n.sessionKey,
		onTerminalEvent: n.followupRun.run.internalEventExecution?.onTerminalEvent,
		startedAt: u,
		getLifecycleGeneration: () => e.lifecycleGeneration,
		resolveTerminationFields: (t) => resolveReplyOperationTerminationFields(t, e.runAbortSignal, n.replyOperation)
	});
	e.onLifecycleBackstop(d);
	const f = cliBackendAcceptsAuthProfileForwarding({
		provider: e.cliExecutionProvider,
		config: e.runtimeConfig,
		agentId: e.candidateRun.agentId
	});
	const p = resolveOriginMessageProvider({
		originatingChannel: n.followupRun.originatingChannel,
		provider: n.sessionCtx.Provider
	});
	const m = buildReplyRouteThreadingToolContext({
		run: e.candidateRun,
		replyRoute: n.followupRun,
		sessionCtx: n.sessionCtx,
		hasRepliedRef: n.opts?.hasRepliedRef
	});
	const h = m.sameChannelThreadRequired === true;
	const g = h ? m.currentThreadTs : n.followupRun.originatingThreadId ?? n.sessionCtx.MessageThreadId;
	const _ = h ? m.replyToMode : n.followupRun.originatingReplyToMode ?? n.sessionCtx.ReplyToMode;
	const v = m.currentMessageId != null ? String(m.currentMessageId) : void 0;
	const y = n.resolvedVerboseLevel === "full";
	const b = createCliToolSummaryTracker({
		detailMode: n.toolProgressDetail,
		commandDetailsVisible: y,
		shouldEmitToolResult: n.shouldEmitToolResult,
		shouldEmitToolOutput: n.shouldEmitToolOutput,
		deliver: (e) => n.opts?.onToolResult?.(e)
	});
	const deliverCliCommandOutcome = async (e, t) => {
		const r = n.opts?.onCommandOutput;
		if (!r) return;
		const i = buildCommandOutputFromToolResultEvent({
			stream: "tool",
			data: {
				...e,
				commandBearing: t
			}
		});
		if (i) await r(i);
	};
	const x = Boolean(n.opts?.onItemEvent) && shouldBridgeCliPreambleEvents(n.opts);
	const S = Boolean(e.presentation.blockReplyHandler) && (n.blockStreamingEnabled || n.opts?.commentaryPayloadsEnabled === true);
	const C = {
		provider: e.provider,
		model: e.model
	};
	const w = await n.replyOperation?.bindToolAuthorityRouteAsync(C);
	return e.timing.measure("cli_run", () => withAdmittedCliCandidate({
		claim: {
			sessionId: n.followupRun.run.sessionId,
			sessionKey: c,
			agentId: n.followupRun.run.agentId,
			runId: e.runId
		},
		admission: {
			preparedRunAdmission: e.preparedRunAdmission,
			lifecycleGeneration: e.lifecycleGeneration,
			isFinalFallbackAttempt: e.isFinalFallbackAttempt,
			abortSignal: e.runAbortSignal,
			trigger: resolveReplyRunTrigger(n),
			inputProvenance: n.followupRun.run.inputProvenance
		},
		provider: e.cliExecutionProvider,
		sessionTarget: l,
		expectedLifecycleRevision: a,
		readMode: "read-only",
		getSessionEntry: () => n.getActiveSessionEntry(),
		classifyResult: e.classifyResult
	}, async ({ sessionEntry: t, cliSessionBinding: r, assertSettlementCurrent: a, settleResult: m, persistStoppedFirstSession: h }) => {
		let y = t;
		const clearCliBinding = () => clearCliSessionInStore({
			agentId: n.followupRun.run.agentId,
			provider: e.cliExecutionProvider,
			expectedCliSessionId: r?.sessionId,
			expectedSessionId: y?.sessionId,
			assertCommitAllowed: a,
			sessionKey: n.sessionKey,
			sessionStore: n.activeSessionStore,
			storePath: n.storePath,
			activeSessionEntry: y
		});
		const C = e.scheduledInference;
		const T = e.candidateRun.authProfileId?.trim() === y?.authProfileOverride?.trim() && resolveCollapsedSessionAuthPinSource(y) === "user";
		const E = C ? await C.resolveCliAuthProfile(async (t) => f ? await resolveCliExecutionAuthProfileId({
			cliExecutionProvider: e.cliExecutionProvider,
			authProfileProvider: e.provider,
			config: e.runtimeConfig,
			agentDir: e.candidateRun.agentDir,
			selected: t,
			sessionBinding: r
		}) : void 0) : f ? await resolveCliExecutionAuthProfileId({
			cliExecutionProvider: e.cliExecutionProvider,
			authProfileProvider: e.provider,
			config: e.runtimeConfig,
			agentDir: e.candidateRun.agentDir,
			selected: T ? e.candidateRun : resolveRunAuthProfile(e.candidateRun, e.provider, { config: e.runtimeConfig }),
			sessionBinding: r
		}) : resolveRunAuthProfile(e.candidateRun, e.cliExecutionProvider, { config: e.runtimeConfig }).authProfileId;
		if (n.followupRun.run.scheduledAutomation && !C && E) throw createUnrecordedScheduledAccountRefusal({
			runtime: e.cliExecutionProvider,
			modelRef: `${e.provider}/${e.model}`,
			profileId: E
		});
		const D = e.deferredLifecycle.handoffToCli();
		const O = r?.forkNextResume === true;
		const k = r?.sessionId && c && n.activeSessionStore && n.storePath ? buildCliSessionForkRunParams({
			agentId: n.followupRun.run.agentId,
			provider: e.cliExecutionProvider,
			expectedCliSessionId: r.sessionId,
			sessionKey: c,
			sessionStore: n.activeSessionStore,
			storePath: n.storePath,
			assertCommitAllowed: a,
			abortSignal: e.runAbortSignal
		}, (e) => {
			y = e;
		}) : void 0;
		const A = getGeneratedMediaTaskIdsForSessionKey(n.sessionKey, n.followupRun.run.agentId);
		let j = false;
		await e.prepareAgentRunStart();
		a();
		const M = await runCliAgentWithLifecycle({
			runId: e.runId,
			lifecycleGeneration: e.lifecycleGeneration,
			startedAt: u,
			onAgentRunStart: e.notifyAgentRunStart,
			deferLifecycleStartUntilExecution: n.followupRun.run.scheduledAutomation ? true : void 0,
			suppressAssistantBridge: n.followupRun.run.silentExpected,
			onActivity: () => n.replyOperation?.recordActivity(),
			onErrorBeforeLifecycle: e.cliExecutionProvider === "claude-cli" && r?.sessionId ? async (e) => {
				if (!shouldClearFailedCliSessionBinding({
					error: e,
					binding: r,
					hasNewGeneratedMediaTask: hasNewGeneratedMediaTaskForSessionKey(n.sessionKey, A, n.followupRun.run.agentId)
				})) return;
				await clearCliBinding();
			} : void 0,
			preserveProgressCallbackStartOrder: e.preserveProgressCallbackStartOrder,
			onAssistantText: (t) => e.presentation.presentPartialReply({ text: t }, "cli"),
			onCompletedReply: async (t, n) => {
				e.runAbortSignal?.throwIfAborted();
				a();
				const r = prepareCliReplyPayload(t, v, n);
				await e.presentation.blockReplyHandler?.(r, { completed: true });
			},
			onReasoningText: createCliReasoningStreamBridge(n.opts?.onReasoningStream),
			onPlanUpdate: n.opts?.onPlanUpdate,
			onReasoningProgress: (e) => n.opts?.onReasoningProgress?.(e),
			onCompactionStart: n.opts?.onCompactionStart,
			onCompactionEnd: n.opts?.onCompactionEnd,
			onToolEvent: async (t) => {
				const r = b.noteToolEvent(t);
				if (t.phase === "result") {
					await deliverCliCommandOutcome(t, await r);
					return;
				}
				const { name: i, phase: a, args: o, toolCallId: s } = t;
				const deliverToolStart = () => n.opts?.onToolStart?.({
					...s ? { toolCallId: s } : {},
					name: i,
					phase: a,
					args: o,
					detailMode: n.toolProgressDetail
				});
				if (!e.preserveProgressCallbackStartOrder) {
					await r;
					await Promise.all([n.typingSignals.signalToolStart(), deliverToolStart()]);
					return;
				}
				await Promise.all([r, e.presentation.presentWithTyping(n.typingSignals.signalToolStart(), async () => {
					await deliverToolStart();
				})]);
			},
			onItemEvent: n.opts?.onItemEvent,
			onCommentaryText: x || S ? async (t) => {
				const r = [];
				if (x) r.push(n.opts?.onItemEvent?.({
					itemId: t.itemId,
					kind: "preamble",
					progressText: t.text,
					...S ? { suppressDurableProgress: true } : {}
				}));
				if (S) {
					const i = prepareCliReplyPayload(t.text, v);
					if (!n.blockStreamingEnabled) i.isCommentary = true;
					r.push(e.presentation.blockReplyHandler?.(i));
				}
				await Promise.all(r);
			} : void 0,
			onFastModeAutoProgress: (e) => n.opts?.onToolResult?.(e),
			transformResult: n.followupRun.currentInboundEventKind === "room_event" ? (e) => keepCliSessionBindingOnlyWhenReused({
				result: e,
				existingSessionId: r?.sessionId,
				onDroppedReplacement: () => {
					j = true;
				}
			}) : void 0,
			runParams: {
				...buildFallbackCandidateTurnParams(e),
				...buildReplyRunStateParams(n.followupRun.run),
				diagnosticOwner: D,
				sessionId: n.followupRun.run.sessionId,
				sessionKey: c,
				sessionTarget: l,
				sessionEntry: y,
				chatType: normalizeChatType(n.followupRun.originatingChatType) ?? normalizeChatType(n.sessionCtx.ChatType) ?? e.candidateRun.chatType,
				runtimePolicySessionKey: n.followupRun.run.runtimePolicySessionKey ?? n.runtimePolicySessionKey,
				agentId: n.followupRun.run.agentId,
				jobId: n.followupRun.run.scheduledAutomation?.job.id,
				onExecutionStarted: n.followupRun.run.scheduledAutomation ? async () => {
					try {
						await n.followupRun.run.internalEventExecution?.beforeScheduledStart?.(e.runId);
						e.runAbortSignal?.throwIfAborted();
						n.followupRun.run.internalEventExecution?.assertCurrent?.();
						const t = n.followupRun.run.scheduledAutomation;
						if (t && c) t.onExecutionStarted?.({
							runId: e.runId,
							sessionId: n.followupRun.run.sessionId,
							sessionKey: c,
							provider: e.provider,
							model: e.model,
							...e.isFallbackRetry ? { isFallback: true } : {}
						});
					} catch (t) {
						if (!e.hasAgentRunStarted()) d.note({
							stream: "lifecycle",
							data: {
								phase: "finishing",
								executionStarted: false,
								providerStarted: false
							}
						});
						throw t;
					}
				} : void 0,
				scheduledToolPolicy: resolveReplyScheduledToolPolicy(n.followupRun.run),
				config: e.runtimeConfig,
				persistAssistantTranscript: n.followupRun.currentInboundEventKind !== "room_event" && n.followupRun.run.suppressTranscriptOnlyAssistantPersistence !== true,
				storePath: n.storePath,
				...buildCliMcpDelegationCapabilityBinding(resolveDelegationCapability({
					fallbackActive: isFallbackAttempt(e),
					inputProvenance: n.followupRun.run.inputProvenance,
					disableTools: n.opts?.disableTools,
					toolsAllow: n.opts?.toolsAllow
				})),
				modelProvider: e.provider,
				requesterModel: {
					provider: e.provider,
					model: e.model
				},
				modelHasVision: s,
				modelContextWindow: o?.contextWindow,
				modelContextTokens: o?.contextTokens,
				contextWindow: y?.contextWindow,
				provider: e.cliExecutionProvider,
				execOverrides: n.followupRun.run.execOverrides,
				bashElevated: n.followupRun.run.bashElevated,
				model: e.model,
				thinkLevel: e.candidateThinkLevel,
				fastMode: e.candidateFastMode.fastMode,
				fastModeAutoOnSeconds: e.candidateFastMode.fastModeAutoOnSeconds,
				timeoutMs: n.followupRun.run.timeoutMs,
				runTimeoutOverrideMs: n.followupRun.run.runTimeoutOverrideMs,
				runId: e.runId,
				extraSystemPromptStatic: n.followupRun.run.extraSystemPromptStatic,
				cliSessionBindingFacts: n.followupRun.run.cliSessionBindingFacts,
				cliSessionId: r?.sessionId,
				cliSessionBinding: r,
				forkCliSessionOnResume: O,
				...k,
				...n.followupRun.currentInboundEventKind === "room_event" || shouldPreserveUserFacingSessionStateForInputProvenance(n.followupRun.run.inputProvenance) ? {} : { persistStoppedFirstCliSession: (e) => h({
					binding: e,
					expectedSession: y,
					sessionStore: n.activeSessionStore
				}) },
				authProfileId: E,
				assertCurrent: C ? () => {
					a();
					C.runParams.authProfileBinding?.assertCurrent();
				} : void 0,
				nativeAuthOnly: n.followupRun.run.scheduledAutomation && !e.scheduledInference ? true : void 0,
				mediaImageLayout: e.currentTurnImages.mediaImageLayout,
				messageChannel: n.followupRun.originatingChannel,
				messageProvider: p,
				currentChannelId: n.followupRun.originatingTo ?? n.sessionCtx.OriginatingTo ?? n.sessionCtx.To,
				senderId: n.followupRun.run.senderId,
				senderName: n.followupRun.run.senderName,
				senderUsername: n.followupRun.run.senderUsername,
				senderE164: n.followupRun.run.senderE164,
				groupId: n.followupRun.run.groupId,
				groupChannel: n.followupRun.run.groupChannel,
				groupSpace: n.followupRun.run.groupSpace,
				spawnedBy: n.followupRun.run.spawnedBy,
				chatId: n.followupRun.originatingChatId,
				currentThreadTs: g != null ? String(g) : void 0,
				currentMessageId: v,
				replyToMode: _,
				currentInboundAudio: hasInboundAudio(n.sessionCtx),
				agentAccountId: n.followupRun.run.agentAccountId,
				skillLibraryAuthoring: e.candidateRun.skillLibraryAuthoring,
				toolAuthorityFingerprint: w,
				onBlockReply: i,
				onPartialReply: n.opts?.onPartialReply,
				onExecutionPhase: e.signalExecutionPhaseForTyping
			}
		});
		if (l && y) e.onSessionWriter({
			...l,
			lifecycleRevision: y.lifecycleRevision,
			activeWriterRunId: y.activeWriterRunId
		});
		if (j) return await settleCliSessionResult(M, async () => {
			await clearCliBinding();
			e.classifyResult(M);
		});
		return m({
			result: M,
			expectedSession: y,
			sessionStore: n.activeSessionStore,
			preserveBinding: shouldPreserveUserFacingSessionStateForInputProvenance(n.followupRun.run.inputProvenance)
		});
	}));
}
//#endregion
//#region src/auto-reply/reply/agent-runner-event-handler.ts
const agentCompactionLog = createSubsystemLogger("auto-reply/compaction");
const CODEX_APP_SERVER_COMPACTION_BACKEND = "codex-app-server";
function createAgentRunEventHandler(e) {
	const shouldSuppressProgressAfterMessageToolDelivery = () => e.sourceRepliesAreToolOnly && e.messageToolDeliveryState.completed && e.turn.opts?.allowProgressCallbacksWhenSourceDeliverySuppressed !== true;
	let t = false;
	const n = e.turn.sessionCtx.MessageSidFull ?? e.turn.sessionCtx.MessageSid;
	const deliverCompactionNoticePayload = async (t, n) => {
		const r = e.turn.opts?.onBlockReply ?? e.turn.onCompactionNoticePayload;
		if (!r) return;
		try {
			await r(t);
		} catch (e) {
			logVerbose(`compaction ${n} notice delivery failed (non-fatal): ${String(e)}`);
		}
	};
	return async (r) => {
		e.turn.replyOperation?.recordActivity();
		e.lifecycleBackstop.note(r);
		const i = r.stream === "lifecycle" && typeof r.data.phase === "string";
		if (r.stream !== "lifecycle" || i) {
			const t = r.transcriptStart === void 0 ? e.prepareAgentRunStart() : void 0;
			if (t) await t;
			e.notifyAgentRunStart(r.transcriptStart);
		}
		if (r.stream === "run_status" && !shouldSuppressProgressAfterMessageToolDelivery()) {
			const n = r.data.phase === "waiting_for_model";
			if (n || t && r.data.phase === "starting_model") {
				t = n;
				await e.turn.opts?.onItemEvent?.({
					itemId: "model-wait",
					kind: "model-wait",
					suppressDurableProgress: true,
					phase: n ? "update" : "end",
					...n ? { progressText: r.data.reason === "slot" ? "Waiting for a free model slot" : "Waiting for the local model to respond" } : {}
				});
			}
		}
		if (r.stream === "tool" && r.data.hideFromChannelProgress !== true) {
			const t = readStringValue(r.data.phase) ?? "";
			const n = readStringValue(r.data.name);
			const i = readStringValue(r.data.toolCallId) ?? "";
			const a = asOptionalObjectRecord(r.data.args);
			if (e.sourceRepliesAreToolOnly && i && n && (t === "start" || t === "update") && a && isMessagingToolSendAction(n, a)) e.messageToolDeliveryState.toolCallIds.add(i);
			if (shouldSuppressProgressAfterMessageToolDelivery()) return;
			if (t === "start" || t === "update") {
				const i = e.turn.opts?.onToolStart?.({
					itemId: readStringValue(r.data.itemId),
					toolCallId: readStringValue(r.data.toolCallId),
					name: n,
					phase: t,
					args: a,
					detailMode: e.turn.toolProgressDetail
				});
				await Promise.all([e.turn.typingSignals.signalToolStart(), i]);
			}
			const o = buildCommandOutputFromToolResultEvent(r);
			if (o) await e.turn.opts?.onCommandOutput?.(o);
		}
		const a = r.stream === "item" ? readStringValue(r.data.phase) : "";
		const o = r.stream === "item" ? readStringValue(r.data.name) : "";
		const s = r.stream === "item" ? readStringValue(r.data.status) : "";
		const c = r.stream === "item" ? readStringValue(r.data.toolCallId) ?? "" : "";
		const l = e.sourceRepliesAreToolOnly && a === "end" && s === "completed" && c.length > 0 && e.messageToolDeliveryState.toolCallIds.has(c);
		const u = shouldSuppressProgressAfterMessageToolDelivery();
		if (l) {
			e.messageToolDeliveryState.toolCallIds.delete(c);
			e.messageToolDeliveryState.completed = true;
		}
		if (r.stream === "item" && (!u || l)) {
			const t = readStringValue(r.data.summary);
			const n = readStringValue(r.data.progressText);
			const i = readStringValue(r.data.meta);
			const l = typeof r.data.commandBearing === "boolean" ? r.data.commandBearing : void 0;
			const u = readStringValue(r.data.approvalId);
			const d = readStringValue(r.data.approvalSlug);
			await e.turn.opts?.onItemEvent?.({
				itemId: readStringValue(r.data.itemId),
				kind: readStringValue(r.data.kind),
				title: readStringValue(r.data.title),
				phase: a,
				status: s,
				...r.data.hideFromChannelProgress === true ? { hideFromChannelProgress: true } : {},
				...r.data.suppressChannelProgress === true ? { suppressChannelProgress: true } : {},
				...c ? { toolCallId: c } : {},
				...o ? { name: o } : {},
				...t !== void 0 ? { summary: t } : {},
				...n !== void 0 ? { progressText: n } : {},
				...i !== void 0 ? { meta: i } : {},
				...l !== void 0 ? { commandBearing: l } : {},
				...u !== void 0 ? { approvalId: u } : {},
				...d !== void 0 ? { approvalSlug: d } : {}
			});
		}
		if (r.stream === "plan" && !shouldSuppressProgressAfterMessageToolDelivery()) await e.turn.opts?.onPlanUpdate?.({
			phase: readStringValue(r.data.phase),
			title: readStringValue(r.data.title),
			explanation: readStringValue(r.data.explanation),
			...r.data.explanationFormat === "plain" ? { explanationFormat: "plain" } : {},
			steps: normalizeAgentPlanSteps(r.data.steps),
			source: readStringValue(r.data.source)
		});
		if (r.stream === "approval" && !shouldSuppressProgressAfterMessageToolDelivery()) {
			const t = r.data.scope;
			await e.turn.opts?.onApprovalEvent?.({
				phase: readStringValue(r.data.phase),
				kind: readStringValue(r.data.kind),
				status: readStringValue(r.data.status),
				title: readStringValue(r.data.title),
				itemId: readStringValue(r.data.itemId),
				toolCallId: readStringValue(r.data.toolCallId),
				approvalId: readStringValue(r.data.approvalId),
				approvalSlug: readStringValue(r.data.approvalSlug),
				command: readStringValue(r.data.command),
				host: readStringValue(r.data.host),
				reason: readStringValue(r.data.reason),
				scope: t === "turn" || t === "session" ? t : void 0,
				message: readStringValue(r.data.message)
			});
		}
		const readToolEventIdentity = () => ({
			itemId: readStringValue(r.data.itemId),
			phase: readStringValue(r.data.phase),
			title: readStringValue(r.data.title),
			toolCallId: readStringValue(r.data.toolCallId),
			name: readStringValue(r.data.name)
		});
		if (r.stream === "command_output" && !shouldSuppressProgressAfterMessageToolDelivery()) await e.turn.opts?.onCommandOutput?.({
			...readToolEventIdentity(),
			output: readStringValue(r.data.output),
			status: readStringValue(r.data.status),
			exitCode: typeof r.data.exitCode === "number" || r.data.exitCode === null ? r.data.exitCode : void 0,
			durationMs: typeof r.data.durationMs === "number" ? r.data.durationMs : void 0,
			cwd: readStringValue(r.data.cwd)
		});
		if (r.stream === "patch" && !shouldSuppressProgressAfterMessageToolDelivery()) {
			const readPaths = (e) => Array.isArray(e) ? e.filter((e) => typeof e === "string") : void 0;
			await e.turn.opts?.onPatchSummary?.({
				...readToolEventIdentity(),
				added: readPaths(r.data.added),
				modified: readPaths(r.data.modified),
				deleted: readPaths(r.data.deleted),
				summary: readStringValue(r.data.summary)
			});
		}
		if (r.stream !== "compaction") return;
		const d = readStringValue(r.data.phase) ?? "";
		const f = readStringValue(r.data.backend);
		const p = normalizeTrimmedStringList(r.data.messages);
		const sendCompactionUserNotices = async (t) => {
			const r = createCompactionHookNoticePayload({
				messages: p,
				currentMessageId: n,
				applyReplyToMode: e.turn.applyReplyToMode
			});
			if (r) await deliverCompactionNoticePayload(r, "hook");
			if (!t) return;
			if (t === "degraded" || t === "context_bounded" || e.notifyUserAboutCompaction) await deliverCompactionNoticePayload(createCompactionNoticePayload({
				phase: t,
				currentMessageId: n,
				applyReplyToMode: e.turn.applyReplyToMode
			}), t);
		};
		if (d === "notice") {
			await sendCompactionUserNotices();
			return;
		}
		if (d === "context_bounded") {
			await sendCompactionUserNotices("context_bounded");
			return;
		}
		if (d === "start") {
			await e.turn.opts?.onCompactionStart?.();
			await sendCompactionUserNotices("start");
			return;
		}
		if (d !== "end") return;
		if (r.data.completed !== true) {
			await e.turn.opts?.onCompactionEnd?.({ completed: false });
			await sendCompactionUserNotices("incomplete");
			return;
		}
		const m = e.onCompactionCompleted();
		if (f === CODEX_APP_SERVER_COMPACTION_BACKEND) {
			const t = `codex app-server auto-compaction succeeded for ${formatCompactionModelRef(e.provider, e.model)}; refreshed session context`;
			agentCompactionLog.info("codex app-server auto-compaction succeeded", {
				event: "codex_app_server_compaction_succeeded",
				backend: f,
				provider: e.provider,
				model: e.model,
				sessionKey: e.turn.sessionKey,
				sessionId: e.effectiveSessionId,
				threadId: readStringValue(r.data.threadId),
				turnId: readStringValue(r.data.turnId),
				itemId: readStringValue(r.data.itemId),
				compactionCount: m,
				consoleMessage: t
			});
		}
		await e.turn.opts?.onCompactionEnd?.({ completed: true });
		await sendCompactionUserNotices(r.data.qualityDegraded === true ? "degraded" : "end");
	};
}
//#endregion
//#region src/auto-reply/reply/agent-runner-embedded-candidate.ts
async function runEmbeddedFallbackCandidate(e) {
	const t = e.turn;
	const resolveReplyDeliveryFacts = async (n) => {
		let r = "pending";
		const i = await resolveTerminalReplyDelivery({
			blockReplyPipeline: t.blockReplyPipeline,
			directBlockDeliveries: e.directBlockDeliveries,
			minimumAssistantMessageIndex: n,
			resolveReplyDelivery: async (e) => {
				const n = await t.opts?.resolveReplyDeliveryFacts?.(e);
				if (n) {
					r = n.source;
					return n.terminal;
				}
				r = await t.opts?.resolveReplyDelivery?.(e) ?? "missing";
				return r;
			}
		});
		return {
			source: r,
			terminal: i
		};
	};
	let n;
	let r;
	const i = readSourceReplyDeliveryRuntime(e.candidateRun);
	const a = {
		...e.candidateRun,
		...e.candidateFastMode,
		thinkLevel: e.candidateThinkLevel
	};
	const o = await buildEmbeddedRunExecutionParams({
		run: a,
		replyRoute: t.followupRun,
		sessionCtx: t.sessionCtx,
		hasRepliedRef: t.opts?.hasRepliedRef,
		provider: e.provider,
		runId: e.runId,
		promptCacheKey: t.opts?.promptCacheKey,
		allowTransientCooldownProbe: e.allowTransientCooldownProbe,
		model: e.model,
		agentRuntime: e.candidateAgentRuntime
	});
	if (i) bindSourceReplyDeliveryRuntime(o, i);
	const s = e.agentHarnessRuntimeOverride ? {
		runtime: e.agentHarnessRuntimeOverride,
		runtimeSource: "model"
	} : resolveAgentHarnessPolicy({
		provider: e.provider,
		modelId: e.model,
		config: e.runtimeConfig,
		agentId: t.followupRun.run.agentId,
		sessionKey: t.followupRun.run.runtimePolicySessionKey ?? t.sessionKey
	});
	let c = 0;
	let l = false;
	let u;
	const d = createAgentLifecycleTerminalBackstop({
		runId: e.runId,
		sessionKey: t.sessionKey,
		onTerminalEvent: t.followupRun.run.internalEventExecution?.onTerminalEvent,
		getLifecycleGeneration: e.getLifecycleGeneration,
		resolveTerminationFields: (n) => resolveReplyOperationTerminationFields(n, e.runAbortSignal, t.replyOperation)
	});
	e.onLifecycleBackstop(d);
	try {
		e.timing.logMilestoneIfSlow({
			runId: e.runId,
			sessionId: t.followupRun.run.sessionId,
			sessionKey: t.sessionKey,
			milestone: "before_embedded_run"
		});
		let f;
		const p = await e.timing.measure("embedded_run", () => {
			const p = {
				...o,
				beforeRecoveryCompaction: async (n) => {
					if (t.recoveryMemoryFlushAttempted) return "skipped: already attempted this turn";
					t.recoveryMemoryFlushAttempted = true;
					const r = t.sessionKey && t.storePath ? await readSessionEntryInWorker({
						storePath: t.storePath,
						sessionKey: t.sessionKey
					}) : t.getActiveSessionEntry();
					if (r?.sessionId !== n.sessionId) return "skipped: source session changed";
					return (await runMemoryFlushIfNeeded({
						cfg: e.runtimeConfig,
						followupRun: {
							...t.followupRun,
							abortSignal: e.runAbortSignal ?? t.followupRun.abortSignal,
							run: {
								...a,
								...n
							}
						},
						recoveryContextTokenBudget: n.contextTokenBudget,
						defaultModel: n.model,
						resolvedVerboseLevel: t.resolvedVerboseLevel,
						sessionEntry: r,
						sessionStore: t.activeSessionStore,
						sessionKey: t.sessionKey,
						runtimePolicySessionKey: t.runtimePolicySessionKey,
						storePath: t.storePath,
						replyOperation: t.replyOperation,
						abortSignal: e.runAbortSignal,
						opts: { runId: e.runId }
					})).outcome;
				},
				...e.scheduledInference?.runParams,
				lifecycleGeneration: e.getLifecycleGeneration(),
				allowGatewaySubagentBinding: true,
				cronCreatorAuthorityCapability: t.opts?.cronCreatorAuthorityCapability,
				cronCreatorAuthorityUnavailableReason: t.opts?.turnAdoptionLifecycle?.cronCreatorAuthorityUnavailable,
				groupId: resolveGroupSessionKey(t.sessionCtx)?.id,
				groupChannel: normalizeOptionalString(t.sessionCtx.GroupChannel) ?? normalizeOptionalString(t.sessionCtx.GroupSubject),
				groupSpace: normalizeOptionalString(t.sessionCtx.GroupSpace),
				...buildFallbackCandidateTurnParams(e),
				contextWindow: t.getActiveSessionEntry()?.contextWindow,
				sessionPromptDelivery: t.getActiveSessionEntry()?.delivery,
				provider: e.provider,
				agentHarnessId: resolveSessionPinnedHarnessId(t.getActiveSessionEntry()),
				agentHarnessRuntimeOverride: e.agentHarnessRuntimeOverride,
				agentHarnessRuntimePreparationHint: s.runtimeSource !== "implicit" ? s.runtime : void 0,
				sandboxSessionKey: t.runtimePolicySessionKey,
				explicitSkillSelections: t.followupRun.explicitSkillSelections,
				forceMessageTool: t.followupRun.run.scheduledAutomation?.sourceDelivery?.messageTool.force ?? t.followupRun.run.sourceReplyDeliveryMode === "message_tool_only",
				...t.followupRun.run.scheduledAutomation ? { disableMessageTool: t.followupRun.run.scheduledAutomation.sourceDelivery?.messageTool.enabled === false } : {},
				suppressTranscriptOnlyAssistantPersistence: t.followupRun.run.suppressTranscriptOnlyAssistantPersistence,
				assistantErrorTranscript: e.assistantErrorTranscript,
				authProfileFailurePolicy: e.authProfileFailurePolicy,
				...e.cyberAccessProgram ? {
					cyberAccessProgram: e.cyberAccessProgram,
					...e.authProfileId ? {
						authProfileId: e.authProfileId,
						authProfileIdSource: "user"
					} : {}
				} : {},
				onAutoCompactionSucceeded: (e) => {
					c = Math.max(c, e);
				},
				toolResultFormat: (() => {
					const e = resolveMessageChannel(t.sessionCtx.Surface, t.sessionCtx.Provider);
					return !e || isMarkdownCapableMessageChannel(e) ? "markdown" : "plain";
				})(),
				toolProgressDetail: t.toolProgressDetail,
				toolAuthorityFingerprint: t.replyOperation?.toolAuthorityFingerprint,
				deferTerminalLifecycle: true,
				onAttemptStart: d.beginAttempt,
				onAttemptTerminalReplaced: d.replaceAttemptTerminal,
				onCompactionAccounting: (e) => {
					u = e;
				},
				onCompactionRequestBudget: (e) => {
					r = e;
				},
				onDeferredLifecycleOwner: e.deferredLifecycle.adopt,
				onDeferredLifecycleAbort: e.deferredLifecycle.abort,
				onRetryWait: e.deferredLifecycle.beginRetryWait,
				onExecutionStarted: async (n) => {
					if (n?.lifecycleGeneration) e.onLifecycleGeneration(n.lifecycleGeneration);
					if (s.runtime !== "openclaw" || n?.backend === "cloud-worker") await e.prepareAgentRunStart();
					if (t.followupRun.run.scheduledAutomation) try {
						await t.followupRun.run.internalEventExecution?.beforeScheduledStart?.(e.runId);
						e.runAbortSignal?.throwIfAborted();
						t.followupRun.run.internalEventExecution?.assertCurrent?.();
						const n = t.followupRun.run.scheduledAutomation;
						const r = t.sessionKey ?? t.followupRun.run.sessionKey;
						if (n && r) n.onExecutionStarted?.({
							runId: e.runId,
							sessionId: t.followupRun.run.sessionId,
							sessionKey: r,
							provider: e.provider,
							model: e.model,
							...e.isFallbackRetry ? { isFallback: true } : {}
						});
					} catch (t) {
						if (!e.hasAgentRunStarted()) d.note({
							stream: "lifecycle",
							data: {
								phase: "finishing",
								executionStarted: false,
								providerStarted: false
							}
						});
						throw t;
					}
				},
				onExecutionPhase: (t) => {
					if (t.phase === "model_call_started" && c > 0) l = true;
					e.signalExecutionPhaseForTyping(t);
				},
				onLaneWait: ({ waiting: e }) => {
					const n = t.replyOperation;
					if (e && n) markReplyOperationGlobalLaneWaitProgress(n);
					t.followupRun.run.scheduledAutomation?.onLaneWait?.({ waiting: e !== false });
				},
				blockReplyBreak: t.resolvedBlockStreamingBreak,
				blockReplyChunking: t.blockReplyChunking,
				onPartialReply: (t) => e.presentation.presentPartialReply(t, "embedded"),
				onAssistantMessageStart: async () => {
					await e.presentation.presentWithTyping(t.typingSignals.signalMessageStart(), () => t.opts?.onAssistantMessageStart?.());
				},
				onReasoningStream: t.typingSignals.shouldStartOnReasoning || t.opts?.onReasoningStream ? async (n) => {
					if (t.followupRun.run.silentExpected) return;
					await e.presentation.presentWithTyping(t.typingSignals.signalReasoningDelta(), () => t.opts?.onReasoningStream?.({
						text: n.text,
						mediaUrls: n.mediaUrls,
						isReasoningSnapshot: n.isReasoningSnapshot,
						requiresReasoningProgressOptIn: n.requiresReasoningProgressOptIn
					}));
				} : void 0,
				streamReasoningInNonStreamModes: t.opts?.streamReasoningInNonStreamModes,
				onReasoningEnd: t.opts?.onReasoningEnd ? async () => {
					await t.opts?.onReasoningEnd?.();
				} : void 0,
				onAgentEvent: (n) => {
					f ??= createAgentRunEventHandler({
						turn: t,
						lifecycleBackstop: d,
						prepareAgentRunStart: e.prepareAgentRunStart,
						notifyAgentRunStart: e.notifyAgentRunStart,
						sourceRepliesAreToolOnly: (i?.currentMode ?? t.followupRun.run.sourceReplyDeliveryMode) === "message_tool_only",
						messageToolDeliveryState: e.messageToolDeliveryState,
						provider: e.provider,
						model: e.model,
						effectiveSessionId: e.effectiveRun.sessionId,
						notifyUserAboutCompaction: e.notifyUserAboutCompaction,
						onCompactionCompleted: () => {
							c += 1;
							return c;
						}
					});
					return f(n);
				},
				onBlockReply: e.presentation.blockReplyHandler,
				resolveReplyDelivery: async (e) => (await resolveReplyDeliveryFacts(e)).terminal,
				resolveReplyDeliveryFacts,
				onBlockReplyFlush: t.blockStreamingEnabled && t.blockReplyPipeline ? async () => {
					await t.blockReplyPipeline?.flush({ force: true });
				} : void 0,
				shouldEmitToolResult: t.shouldEmitToolResult,
				shouldEmitToolOutput: t.shouldEmitToolOutput,
				onToolResult: t.opts?.onToolResult ? (() => {
					let n = Promise.resolve();
					return (r) => {
						const i = n.then(async () => {
							t.replyOperation?.recordActivity();
							const { text: n, skip: i } = e.presentation.normalizeStreamingText(r);
							if (i) return;
							if (n !== void 0) await t.typingSignals.signalTextDelta(n);
							await t.opts?.onToolResult?.({
								...r,
								text: n
							});
						});
						n = i.catch((e) => {
							logVerbose(`tool result delivery failed: ${String(e)}`);
						});
						const a = n.finally(() => {
							t.pendingToolTasks.delete(a);
						});
						t.pendingToolTasks.add(a);
						return i;
					};
				})() : void 0
			};
			p.onSuccessfulAuthProfile = (t) => {
				e.scheduledInference?.runParams.onSuccessfulAuthProfile?.(t);
				n = {
					authProfileId: t,
					authProfileIdSource: t ? t === p.authProfileId ? p.authProfileIdSource : "auto" : void 0
				};
			};
			e.scheduledInference?.assertCandidate(e.provider, false);
			return runEmbeddedAgent(p);
		});
		const m = Math.max(0, p.meta?.agentMeta?.compactionCount ?? 0);
		c = Math.max(c, m);
		return {
			result: p,
			maintenanceAuthProfile: n,
			compactionRequestBudget: r
		};
	} finally {
		const t = u ?? (c > 0 ? {
			kind: "presentation-only",
			count: c,
			currentContextSnapshot: { tokens: void 0 }
		} : void 0);
		e.onCompactionFacts({
			accounting: t,
			postCompactionModelAttempted: l
		});
	}
}
//#endregion
//#region src/auto-reply/reply/agent-runner-fallback-authority.ts
/** Only the fallback owner can establish that a new route still serves the original selection. */
function bindReplyFallbackSteeringRoute(e) {
	const { operation: t, provenance: n, route: r } = e;
	if (!t) return;
	const i = t.requestedToolAuthorityRoute;
	t.setAutomaticFallbackRoute(void 0);
	if (n.stage !== "fallback" || n.selectionChanged !== false || i?.provider !== n.requestedProvider || i?.model !== n.requestedModel) return;
	const a = resolveManifestModelCatalogProviderAliasMetadata({
		provider: r.provider,
		modelId: r.model,
		cfg: e.config,
		workspaceDir: e.workspaceDir
	});
	if (!a.ambiguous) t.setAutomaticFallbackRoute({
		provider: a.provider,
		model: r.model
	});
}
//#endregion
//#region src/auto-reply/reply/agent-runner-fallback-candidate.ts
/** Runs the provider/model fallback candidates while preserving cross-candidate delivery state. */
async function runAgentFallbackCandidates(e) {
	const t = e.turn;
	const adoptInput = async () => {
		if (t.replyOperation) await lifecycleAdmissionByOperation.get(t.replyOperation)?.adoptInput?.();
	};
	const n = t.opts;
	const r = readSourceReplyDeliveryRuntime(t.followupRun.run) ?? createSourceReplyDeliveryRuntime({
		origin: n?.sourceReplyDeliveryModeOrigin ?? "stable_policy",
		initialMode: t.followupRun.run.sourceReplyDeliveryMode ?? t.opts?.sourceReplyDeliveryMode ?? "automatic",
		projections: [t.followupRun.run, ...t.opts ? [t.opts] : []],
		promptComponentByMode: {
			automatic: "",
			message_tool_only: ""
		},
		promptComponentOffset: void 0,
		onModeResolved: n?.onSourceReplyDeliveryModeResolved
	});
	r.track(t.followupRun.run);
	if (t.opts) r.track(t.opts);
	bindSourceReplyDeliveryRuntime(t.followupRun.run, r);
	const i = r.origin;
	const a = t.opts?.preserveProgressCallbackStartOrder === true;
	const o = t.followupRun.run.scheduledAutomation ? "cron-nested" : t.followupRun.run.internalEventExecution ? t.followupRun.run.inputProvenance?.sourceTool === "restart" ? "restart-recovery" : "cron-nested" : "main";
	let s = false;
	const c = {
		toolCallIds: /* @__PURE__ */ new Set(),
		completed: false
	};
	const l = t.followupRun.userTurnTranscriptRecorder ?? t.opts?.userTurnTranscriptRecorder;
	const u = Date.now();
	const d = {
		offAnnounced: false,
		resetAnnounced: false
	};
	const f = t.followupRun.run.scheduledAutomation ? "cron" : "default";
	e.timing.logMilestoneIfSlow({
		runId: e.runId,
		sessionId: t.followupRun.run.sessionId,
		sessionKey: t.sessionKey,
		milestone: "before_model_fallback"
	});
	const p = resolveModelFallbackOptions(e.effectiveRun, e.runtimeConfig);
	const runtimeSessionEntry = () => {
		const n = e.liveModelSwitchRuntimeEntry ?? t.getActiveSessionEntry();
		return n && e.scheduledInference ? e.scheduledInference.runtimeSessionEntry(n) : n;
	};
	const resolveCandidateRuntime = (n, r, i) => {
		const a = resolveFallbackCandidateRun(e.effectiveRun, n, r);
		const o = e.liveModelSwitchRuntimeEntry ?? t.getActiveSessionEntry();
		const s = resolveRunAuthProfile(a, n, { config: e.runtimeConfig });
		return {
			candidateRun: a,
			...resolveRunEntryCliRuntime({
				config: e.runtimeConfig,
				provider: n,
				model: r,
				agentId: t.followupRun.run.agentId,
				authProfileId: e.scheduledInference?.runParams.authProfileId ?? s.authProfileId,
				sessionRuntimeOverride: i,
				pinnedHarnessId: resolveSessionPinnedHarnessId(o)
			})
		};
	};
	return e.timing.measure("model_fallback", () => runEmbeddedAgentEntry({
		preparedRunAdmission: e.preparedRunAdmission,
		modelResolve: {
			prompt: t.commandBody,
			awaitSessionDiffBaseline: t.opts?.awaitSessionDiffBaseline,
			images: e.currentTurnImages.images,
			cwd: t.followupRun.run.cwd,
			modelSelectionLocked: t.followupRun.run.modelSelectionLocked,
			context: withClaimingHookAdmission(buildModelResolveContext({
				run: t.followupRun.run,
				replyRoute: t.followupRun,
				sessionCtx: t.sessionCtx,
				hasRepliedRef: t.opts?.hasRepliedRef,
				trigger: resolveReplyRunTrigger(t)
			}), { prepare: adoptInput })
		},
		selection: buildRunEntrySelection(p, t.followupRun.run),
		identity: {
			runId: e.runId,
			agentId: t.followupRun.run.agentId,
			sessionId: t.followupRun.run.sessionId,
			sessionKey: t.sessionKey,
			sessionLifecycleRevision: t.getActiveSessionEntry()?.lifecycleRevision ?? null,
			lane: o
		},
		harness: {
			workspaceDir: t.followupRun.run.workspaceDir,
			sessionKey: t.followupRun.run.runtimePolicySessionKey ?? t.sessionKey,
			preparation: {
				kind: "measured",
				run: (t) => e.timing.measure("fallback_prepare_harness", t)
			},
			resolveRuntimeOverride: (t) => resolveSessionRuntimeOverrideForProvider({
				provider: t,
				entry: runtimeSessionEntry(),
				cfg: e.runtimeConfig
			}),
			resolveContextEngineHost: (n, r, i) => {
				const a = resolveCandidateRuntime(n, r, i);
				if (!a.useCliExecution) return;
				const o = resolveCliBackendConfig(a.cliExecutionProvider, e.runtimeConfig, { agentId: t.followupRun.run.agentId });
				return buildGenericCliContextEngineHostSupport({
					backendId: o?.id ?? a.cliExecutionProvider,
					...o?.contextEngineHostCapabilities ? { capabilities: o.contextEngineHostCapabilities } : {}
				});
			}
		},
		behavior: {
			kind: "channel-delivery",
			readDeliveryEvidence: () => ({
				hasRetryBlockedDelivery: t.blockReplyPipeline?.hasRetryBlockedDelivery() === true || e.directBlockDeliveries.some(hasBlockReplyDeliveryCustody),
				hasDirectlySentBlockReply: e.directBlockDeliveries.some((e) => e.terminalDeliveryConfirmed === true),
				hasBlockReplyPipelineOutput: Boolean(t.blockReplyPipeline?.hasBuffered() || t.blockReplyPipeline?.didStream())
			})
		},
		sessionOverride: {
			kind: "reconcile-completed",
			reconcile: e.clearRecoveredAutoFallbackPrimaryProbe
		},
		onAcceptedTerminal: () => {
			e.commitTerminalOutcome();
			return t.replyOperation ? beginReplyOperationFinalizationWork(t.replyOperation, RUN_STALE_TAKEOVER_MS) : void 0;
		},
		abortSignal: e.runAbortSignal,
		onFallbackStep: (n) => {
			emitAgentEvent({
				runId: e.runId,
				...t.sessionKey ? { sessionKey: t.sessionKey } : {},
				stream: "lifecycle",
				data: {
					phase: "fallback_step",
					...n
				}
			});
		},
		runCandidate: async (n, p, m) => {
			bindReplyFallbackSteeringRoute({
				operation: t.replyOperation,
				provenance: m.modelRoutingProvenance,
				route: {
					provider: n,
					model: p
				},
				config: e.runtimeConfig,
				workspaceDir: t.followupRun.run.workspaceDir
			});
			clearAgentRunTerminalWriteContext(e.preparedRunAdmission.operationalRunInstance);
			e.state.maintenanceAuthProfile = void 0;
			e.state.compactionRequestBudget = void 0;
			invalidateTurnCompactionContext(e.state.compaction);
			e.state.attemptedRuntimeProvider = n;
			e.state.attemptedRuntimeModel = p;
			const h = e.timing.measureSync("fallback_resolve_runtime", () => resolveCandidateRuntime(n, p, m.agentHarnessRuntimeOverride));
			const g = h.candidateRun;
			bindSourceReplyDeliveryRuntime(g, r);
			const _ = i === "runtime_default" && h.useCliExecution ? g.cliSessionBindingFacts?.sourceReplyDeliveryMode ?? "automatic" : r.currentMode;
			const v = i !== "runtime_default" || h.useCliExecution;
			if (_ && v) r.applyMode(g, _);
			const y = resolveCandidateAgentRuntime({
				cfg: e.runtimeConfig,
				provider: n,
				modelId: p,
				agentId: t.followupRun.run.agentId,
				sessionKey: t.followupRun.run.runtimePolicySessionKey ?? t.sessionKey,
				sessionEntry: runtimeSessionEntry(),
				agentRuntime: m.agentHarnessRuntimeOverride
			});
			e.scheduledInference?.assertCandidate(n, h.useCliExecution, y);
			assertCronRuntimeAuthorityCandidate({
				authority: g.scheduledAutomation?.job.runtimeAuthority,
				candidateRuntime: y,
				cliExecution: h.useCliExecution
			});
			if (g.scheduledAutomation) assertCronCandidateSandboxPlacement({
				...resolveCronSandboxPlacement({
					cfg: e.runtimeConfig,
					agentId: g.agentId,
					sessionKey: g.sessionKey,
					preparedSessionEntry: t.getActiveSessionEntry() ?? null
				}),
				cliExecution: h.useCliExecution,
				executionProvider: h.cliExecutionProvider
			});
			const b = resolveRunThinkingLevelForFallbackCandidate({
				cfg: e.runtimeConfig,
				provider: n,
				modelId: p,
				run: t.followupRun.run,
				catalog: t.followupRun.run.thinkingCatalog,
				agentId: t.followupRun.run.agentId,
				sessionKey: t.followupRun.run.runtimePolicySessionKey ?? t.sessionKey,
				sessionEntry: e.liveModelSwitchRuntimeEntry ?? t.getActiveSessionEntry(),
				agentRuntime: y
			});
			const x = resolveRunFastModeForFallbackCandidate({
				run: g,
				config: e.runtimeConfig,
				provider: n,
				model: p,
				sessionEntry: t.getActiveSessionEntry()
			});
			const S = e.effectiveRun.autoFallbackPrimaryProbe;
			if (S && n === S.provider && p === S.model) markAutoFallbackPrimaryProbe({
				probe: S,
				sessionKey: t.sessionKey
			});
			t.opts?.onModelSelected?.({
				provider: n,
				model: p,
				thinkLevel: b
			});
			const C = e.createAgentRunStartCallbacks();
			const signalExecutionPhaseForCandidate = (t) => {
				if (e.state.compaction.count > 0 && (t.phase === "model_call_started" || t.phase === "process_spawned")) e.state.postCompactionModelAttempted = true;
				C.signalExecutionPhaseForTyping(t);
			};
			await t.opts?.dashboardReadAdmission?.prepare?.();
			await readUserTurnPromptReactionSource(t.followupRun.userTurnTranscriptRecorder)?.prepare?.();
			const w = t.followupRun.run.scheduledAutomation ? e.scheduledMessageActionTurnCapability : mintReplyMessageActionTurnCapability(t, e.runId);
			try {
				const r = {
					...m,
					...e,
					turn: t,
					messageActionTurnCapability: w,
					candidateRun: g,
					provider: n,
					model: p,
					candidateThinkLevel: b,
					candidateFastMode: x,
					runLane: o,
					suppressQueuedUserPersistenceForCandidate: (t.followupRun.run.suppressNextUserMessagePersistence ?? false) || s,
					userTurnTranscriptRecorder: l,
					notifyUserMessagePersisted: () => {
						s = true;
					},
					fastModeStartedAtMs: u,
					fastModeAutoProgressState: d,
					bootstrapContextRunKind: f,
					bootstrapPromptWarningSignaturesSeen: e.state.bootstrapPromptWarningSignaturesSeen,
					signalExecutionPhaseForTyping: signalExecutionPhaseForCandidate,
					prepareAgentRunStart: C.prepareAgentRunStart,
					notifyAgentRunStart: C.notifyAgentRunStart,
					hasAgentRunStarted: C.hasAgentRunStarted,
					preserveProgressCallbackStartOrder: a,
					onLifecycleBackstop: (t) => {
						e.state.pendingLifecycleTerminal = {
							provider: n,
							model: p,
							backstop: t
						};
					},
					deferredLifecycle: e.state.deferredLifecycle
				};
				let i;
				if (h.useCliExecution) {
					await adoptInput();
					i = await runCliFallbackCandidate({
						...r,
						cliExecutionProvider: h.cliExecutionProvider,
						lifecycleGeneration: e.state.lifecycleGeneration,
						onSessionWriter: (t) => {
							e.state.sessionWriter = t;
						}
					});
				} else {
					const t = await runEmbeddedFallbackCandidate({
						...r,
						candidateAgentRuntime: y,
						getLifecycleGeneration: () => e.state.lifecycleGeneration,
						onLifecycleGeneration: (t) => {
							e.state.lifecycleGeneration = t;
						},
						messageToolDeliveryState: c,
						onCompactionFacts: ({ accounting: t, postCompactionModelAttempted: n }) => {
							if (t) {
								if (t.kind === "durable") e.state.sessionWriter = t.target;
								recordTurnCompaction(e.state.compaction, t);
							}
							e.state.postCompactionModelAttempted ||= n;
						}
					});
					e.state.maintenanceAuthProfile = t.maintenanceAuthProfile;
					e.state.compactionRequestBudget = t.compactionRequestBudget;
					i = t.result;
				}
				const _ = i.meta.requestShaping?.thinking ?? b;
				const v = formatThinkingLevelClampNotice({
					requested: t.followupRun.run.thinkLevel,
					effective: _,
					provider: i.meta.agentMeta?.provider ?? n,
					model: i.meta.agentMeta?.model ?? p
				});
				if (v) i = {
					...i,
					meta: {
						...i.meta,
						requestShaping: {
							...i.meta.requestShaping,
							thinking: _,
							thinkingClamp: v
						}
					}
				};
				e.state.bootstrapPromptWarningSignaturesSeen = resolveBootstrapWarningSignaturesSeen(i.meta?.systemPromptReport);
				return i;
			} finally {
				C.close();
				if (!e.scheduledMessageActionTurnCapability) revokeMessageActionTurnCapability(w);
			}
		}
	}));
}
//#endregion
//#region src/auto-reply/reply/pending-tool-task-drain.ts
/** Waits for asynchronous tool tasks before final reply delivery. */
const DEFAULT_PENDING_TOOL_DRAIN_IDLE_TIMEOUT_MS = 3e4;
function observePendingTask(e, t) {
	const settled = () => t.settled?.(e);
	e.then(settled, settled);
}
/** Waits for pending tool tasks to settle or times out to avoid session deadlock. */
async function drainPendingToolTasks({ tasks: e }) {
	if (e.size === 0) return;
	const t = /* @__PURE__ */ new WeakSet();
	const n = {};
	if (await new Promise((r) => {
		const finish = (e) => {
			n.settled = void 0;
			clearTimeout(i);
			r(e);
		};
		const i = setTimeout(() => finish("timeout"), DEFAULT_PENDING_TOOL_DRAIN_IDLE_TIMEOUT_MS);
		i.unref?.();
		const observeNewTasks = () => {
			for (const r of e) if (!t.has(r)) {
				t.add(r);
				observePendingTask(r, n);
			}
		};
		n.settled = (n) => {
			t.delete(n);
			e.delete(n);
			if (e.size === 0) finish("settled");
			else {
				i.refresh();
				observeNewTasks();
			}
		};
		observeNewTasks();
	}) === "timeout") {
		const t = e.size;
		logVerbose(`pending tool tasks made no progress within ${DEFAULT_PENDING_TOOL_DRAIN_IDLE_TIMEOUT_MS}ms; proceeding with ${t} task(s) still pending to avoid session deadlock`);
	}
}
//#endregion
//#region src/auto-reply/reply/private-message-tool-final.ts
const privateFinalReplyLogger = createSubsystemLogger("source-reply/private-final");
/** A terminal reply is stranded when the configured tool did not deliver it. */
function isStrandedPrivateMessageToolFinal(e) {
	return Boolean(isRequiredReplyExpectation(e.replyExpectation) && e.terminalReply && e.terminalReply.disposition !== "silent" && e.sourceReplyDeliveryMode === "message_tool_only" && !e.isRoomEvent && !e.sendPolicyDenied && !e.successfulSourceReplyDelivery);
}
/**
* Emit metadata-only operator signal. The body is intentionally omitted:
* `message_tool_only` keeps normal final text private by design.
*/
function warnPrivateMessageToolFinal(e) {
	privateFinalReplyLogger.warn("agent produced a private final reply without calling the configured delivery tool (message_tool_only); response kept private and not delivered to the source channel", {
		sessionKey: e.sessionKey,
		channel: e.channel,
		chars: e.finalTextLength
	});
}
//#endregion
//#region src/auto-reply/reply/agent-runner-fallback-settlement.ts
/** Settles abort, lifecycle, and terminal failure state after fallback execution. */
async function settleAgentFallbackCycle(e) {
	const { cycle: t, fallbackResult: n } = e;
	const r = t.turn;
	const i = n.result;
	const a = n.provider;
	const o = n.model;
	const s = n.outcome === "exhausted";
	const c = n.terminal.metadata;
	const l = n.terminal.outcome;
	const u = t.state.pendingLifecycleTerminal?.provider === a && t.state.pendingLifecycleTerminal.model === o ? t.state.pendingLifecycleTerminal.backstop : void 0;
	t.state.pendingLifecycleTerminal = void 0;
	const d = resolveReplyOperationAbortReason(r.replyOperation);
	if (d) {
		u?.emit("end", i, c);
		await drainPendingToolTasks({ tasks: r.pendingToolTasks });
		return {
			kind: "aborted",
			reason: d
		};
	}
	t.commitTerminalOutcome();
	const f = n.attempts.map((e) => ({
		provider: e.provider,
		model: e.model,
		error: e.error,
		reason: e.reason ?? "unknown",
		status: e.status,
		code: e.code || void 0
	}));
	if (!s) await n.settleSessionOverride();
	const p = i.meta?.error;
	const m = u?.getDeferredError();
	const h = i.payloads?.find((e) => e.isError === true && e.text !== void 0)?.text;
	const g = isHostMissingReplyNoticeText(p?.message) ? p?.message : void 0;
	const _ = m ?? (l.status === "timeout" ? l.error : h) ?? g ?? (p ? "Agent run failed" : void 0);
	const emitSettledLifecycleError = (e, n) => {
		if (u) {
			u.emit("error", e, n);
			return;
		}
		emitAgentEvent({
			runId: t.runId,
			lifecycleGeneration: t.state.lifecycleGeneration,
			...r.sessionKey ? { sessionKey: r.sessionKey } : {},
			stream: "lifecycle",
			data: {
				phase: "error",
				error: e.message,
				endedAt: Date.now(),
				...n,
				executionSettled: true
			}
		});
	};
	const v = p && isContextOverflowError(p.message);
	if (v || p?.kind === "role_ordering") {
		emitSettledLifecycleError(new Error(_ ?? "Agent run failed"));
		if (v) defaultRuntime.error(`Auto-compaction failed (${p.message}). Preserving existing session mapping for ${r.sessionKey ?? r.followupRun.run.sessionId}.`);
		r.replyOperation?.fail("run_failed", p);
		const e = v ? buildContextOverflowRecoveryText() : t.shouldSurfaceToControlUi ? renderControlUiAgentFailureCopy() : PROVIDER_CONVERSATION_STATE_ERROR_USER_MESSAGE;
		return {
			kind: "final",
			payload: markAgentRunFailureReplyPayload({ text: e }),
			postCompactionModelFailure: t.state.postCompactionModelAttempted || void 0
		};
	}
	const y = r.sessionKey ? resolveSourceReplyPolicy({
		cfg: t.runtimeConfig,
		sessionCtx: r.sessionCtx,
		sessionEntry: r.getActiveSessionEntry(),
		sessionKey: r.sessionKey,
		runtimePolicySessionKey: r.runtimePolicySessionKey,
		opts: r.opts
	}) : void 0;
	const b = hasCompletedSourceReplyDeliveryEvidence(i);
	const x = !(i.meta?.yielded === true || i.meta?.continuationPending === true || (i.meta?.pendingToolCalls?.length ?? 0) > 0) && isStrandedPrivateMessageToolFinal({
		replyExpectation: resolveReplyExpectation({
			...r.followupRun.run,
			scheduledAutomation: r.followupRun.run.scheduledAutomation !== void 0
		}),
		sourceReplyDeliveryMode: y?.sourceReplyDeliveryMode,
		sendPolicyDenied: y?.sendPolicyDenied === true,
		successfulSourceReplyDelivery: b,
		isRoomEvent: r.sessionCtx.InboundEventKind === "room_event",
		terminalReply: i.meta?.terminalReply
	}) ? {
		disposition: "empty",
		code: "message-tool-not-called"
	} : void 0;
	const S = s || Boolean(m || p || l.status === "timeout" || classifyAgentRunTerminalOutcome(l) === "failure");
	if (S) {
		const e = new Error(_ ?? (s ? "All model fallback candidates failed" : "Agent run failed"));
		if (!s || t.modelPatch.captureFallbackFailure(f) === void 0) t.modelPatch.captureFailure(p ?? e);
		emitSettledLifecycleError(e, c);
		r.replyOperation?.fail("run_failed", e);
	} else {
		if (x) i.meta.terminalReply = x;
		u?.emit("end", i, x ? {
			...c,
			terminalReply: x
		} : c);
	}
	return {
		kind: "completed",
		runResult: i,
		fallbackProvider: a,
		fallbackModel: o,
		fallbackExhausted: s,
		fallbackAttempts: f,
		terminalRunFailed: S
	};
}
//#endregion
//#region src/auto-reply/reply/agent-runner-subagent.ts
/**
* Human replies inherit the retained child's native custody. A tool handoff result
* continues the task whose own run handed off; other internal turns stay separate follow-ups.
*/
async function prepareReplySubagentContinuation(e, t, n, r) {
	const i = e.getActiveSessionEntry();
	const a = e.followupRun.run.inputProvenance;
	const o = a?.kind === "internal_system" && a.sourceTool === "tool_handoff" ? a.runId : void 0;
	if (!e.sessionKey || a && a.kind !== "external_user" && !o || !(i?.spawnedBy || i?.subagentRole || (i?.spawnDepth ?? 0) > 0)) return;
	const assertCurrent = () => {
		r.assertSourceCurrent();
		e.replyOperation?.abortSignal.throwIfAborted();
		e.opts?.abortSignal?.throwIfAborted();
	};
	assertCurrent();
	const { reactivateCompletedSubagentSession: s } = await import("./session-subagent-reactivation-CYGnHQqM.mjs");
	await s({
		sessionKey: e.sessionKey,
		runId: t,
		...o ? {} : { task: e.followupRun.prompt },
		...o ? { pausedRunId: o } : {},
		gatewayContextResolver: readChannelContextGatewayContextResolver(e.sessionCtx) ?? getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext,
		assertCurrent,
		session: {
			cfg: n,
			activeSessionAgentId: e.followupRun.run.agentId,
			sessionEntry: i
		}
	});
	assertCurrent();
}
//#endregion
//#region src/auto-reply/reply/agent-runner-turn-timing.ts
const agentTurnTimingLog = createSubsystemLogger("auto-reply/agent-turn-timing");
function createAgentTurnTimingTracker(e = {}) {
	const t = /* @__PURE__ */ new Set();
	const n = createReplyTimingTracker({
		log: { warn(t, n) {
			if ((n?.milestone === "assistant_output_started" || n?.milestone === "tool_execution_started") && !e.profilerEnabled) agentTurnTimingLog.info(t, n);
			else agentTurnTimingLog.warn(t, n);
		} },
		enabled: e.profilerEnabled === true,
		formatMessage: (e, t, n) => {
			const r = `runId=${e.runId} sessionId=${e.sessionId ?? "unknown"} sessionKey=${e.sessionKey ?? "unknown"}`;
			return "milestone" in e ? `agent turn milestone ${r} milestone=${e.milestone} totalMs=${t.totalMs} stages=${n}` : `agent turn timings ${r} outcome=${e.outcome} totalMs=${t.totalMs} stages=${n}${e.error ? ` error="${e.error}"` : ""}`;
		},
		detailKeys: (e) => "milestone" in e ? [
			"runId",
			"sessionId",
			"sessionKey",
			"milestone"
		] : [
			"runId",
			"sessionId",
			"sessionKey",
			"outcome",
			"error"
		]
	});
	return {
		observe(e) {
			try {
				const t = e?.();
				return t ? { [Symbol.dispose]() {
					try {
						t();
					} catch {}
				} } : void 0;
			} catch {
				return;
			}
		},
		measure: n.measure,
		measureSync: n.measureSync,
		logIfSlow(t) {
			if (!e.profilerEnabled) return;
			const { runId: r, sessionId: i, sessionKey: a, outcome: o, error: s } = t;
			n.logIfSlow({
				runId: r,
				sessionId: i,
				sessionKey: a,
				outcome: o,
				error: s
			});
		},
		logMilestoneIfSlow(e) {
			const { runId: t, sessionId: r, sessionKey: i, milestone: a } = e;
			n.logIfSlow({
				runId: t,
				sessionId: r,
				sessionKey: i,
				milestone: a
			}, { repeat: true });
		},
		logExecutionPhaseIfSlow(e) {
			if (t.has(e.phase)) return;
			t.add(e.phase);
			const { runId: r, sessionId: i, sessionKey: a, phase: o } = e;
			n.logIfSlow({
				runId: r,
				sessionId: i,
				sessionKey: a,
				milestone: o
			}, { repeat: true });
		}
	};
}
//#endregion
//#region src/auto-reply/reply/agent-runner-execution.ts
async function executeAgentTurnInternalLoop(e, t, n, r, i, a, o, s, c, l) {
	let u = e;
	const d = [];
	const f = u.replyOperation?.turnKind === "queued_followup" ? u.followupRun.run : resolveRunAfterAutoFallbackPrimaryProbeRecheck({
		run: u.followupRun.run,
		entry: u.activeSessionStore?.[u.sessionKey ?? ""] ?? u.getActiveSessionEntry(),
		sessionKey: u.sessionKey
	});
	if (f !== u.followupRun.run) u.followupRun.run = f;
	const p = selectLiveRuntimeConfig(f.config);
	const m = p === f.config ? f : {
		...f,
		config: p
	};
	let h;
	const applyLiveModelSwitchToRun = (e, t) => {
		e.provider = t.provider;
		e.model = t.model;
		e.authProfileId = t.authProfileId;
		e.authProfileIdSource = t.authProfileId ? t.authProfileIdSource : void 0;
		e.autoFallbackPrimaryProbe = void 0;
		h = { agentRuntimeOverride: t.agentRuntimeOverride };
	};
	const g = createAgentTurnTimingTracker({ profilerEnabled: isReplyProfilerEnabled({ config: p }) });
	const _ = u.followupRun.run.messageProvider ?? u.sessionCtx.Surface ?? u.sessionCtx.Provider;
	const v = isInternalMessageChannel(_);
	const y = captureAgentRunLifecycleGeneration(t);
	if (u.sessionKey) {
		registerAgentRunContext(t, {
			sessionKey: u.sessionKey,
			...u.followupRun.run.sessionId ? { sessionId: u.followupRun.run.sessionId } : {},
			agentId: u.followupRun.run.agentId,
			lifecycleGeneration: y,
			verboseLevel: u.resolvedVerboseLevel,
			isControlUiVisible: v,
			...progressCardRefreshRunProjection(u.followupRun.run.inputProvenance),
			...isCronExecutionInputProvenance(u.followupRun.run.inputProvenance) ? {
				projectSessionActive: false,
				projectSessionLifecycle: false
			} : {},
			completionSource: u.completionSource,
			sessionEventDelivery: resolveReplySessionEventDelivery(u.opts, u.followupRun.run)
		});
		bindAgentRunTerminalWriteSettlement(i.operationalRunInstance);
	}
	if (isDiagnosticsEnabled(p)) {
		const e = resolveReplyRunTrigger(u);
		logSessionTurnCreated({
			runId: t,
			sessionKey: u.sessionKey,
			sessionId: u.followupRun.run.sessionId,
			agentId: u.followupRun.run.agentId,
			channel: _,
			trigger: e === "cron" ? "event" : e
		});
	}
	let b;
	let x;
	let S;
	try {
		b = u.replyMediaContext ?? g.measureSync("reply_media_context", () => createReplyMediaContext(buildReplyMediaContextParams(u.followupRun, u.sessionKey, p)));
		x = u.followupRun.currentTurnImagesPrepared === true || Object.hasOwn(u.followupRun, "images") || Object.hasOwn(u.followupRun, "imageOrder") ? {
			images: u.followupRun.images,
			imageOrder: u.followupRun.imageOrder,
			mediaImageLayout: u.followupRun.mediaImageLayout
		} : await g.measure("current_turn_images", () => resolveCurrentTurnImages({
			ctx: u.sessionCtx,
			cfg: p,
			images: u.opts?.images,
			imageOrder: u.opts?.imageOrder
		}));
		const e = await r();
		if (e) u = {
			...u,
			mcpAppContextLease: e
		};
		({params: u, currentTurnImages: x} = applyMcpAppModelContext(u, x));
		S = await createAgentPatchedSessionModelRunGuard({
			cfg: p,
			agentId: u.followupRun.run.agentId,
			sessionKey: u.sessionKey,
			storePath: u.storePath,
			assertReadCurrent: () => {
				u.replyOperation?.abortSignal?.throwIfAborted();
				u.opts?.abortSignal?.throwIfAborted();
				i.assertSourceCurrent();
			},
			onError: (e) => logVerbose(`agent model patch reconciliation failed: ${formatErrorMessage$1(e)}`)
		});
	} catch (e) {
		clearAgentRunContext(t, y);
		throw e;
	}
	let C = false;
	let w;
	const createAgentRunStartCallbacks = () => {
		let e = true;
		let n = (u.opts?.onPreparedAgentRunStart || u.opts?.onAgentRunStart) && u.sessionKey ? void 0 : null;
		let r;
		const prepareAgentRunStart = () => {
			if (!e || C || n !== void 0 || !u.sessionKey) return;
			if (r) return r;
			const t = {
				agentId: m.agentId,
				sessionId: u.replyOperation?.sessionId ?? m.sessionId,
				sessionKey: u.sessionKey,
				storePath: u.storePath ?? resolveSessionStorePathCore(p.session?.store, { agentId: m.agentId })
			};
			return r = (async () => {
				try {
					var r = _usingCtx();
					r.u(g.observe(u.opts?.onTranscriptStartPreparation));
					const { readSessionTranscriptStartAsync: a } = await import("./session-transcript-watermark-CWMMMqBX.mjs");
					const o = await a(t);
					i.assertSourceCurrent();
					u.opts?.abortSignal?.throwIfAborted();
					u.replyOperation?.abortSignal?.throwIfAborted();
					if (e && !C) n = o;
				} catch (e) {
					r.e = e;
				} finally {
					r.d();
				}
			})();
		};
		const notifyAgentRunStart = (r) => {
			const i = r === void 0 ? n : r;
			if (!e || C || i === void 0) return;
			C = true;
			if (u.replyOperation) markReplyOperationExecutionStarted(u.replyOperation);
			u.followupRun.run.internalEventExecution?.onStarted(t);
			notifyPreparedAgentRunStart(u.opts, {
				runId: t,
				executionIdentityToken: a.current?.executionIdentityToken,
				transcriptStart: i
			});
		};
		const signalExecutionPhaseForTyping = (n) => {
			if (!e) return;
			g.logExecutionPhaseIfSlow({
				runId: t,
				sessionId: u.followupRun.run.sessionId,
				sessionKey: u.sessionKey,
				phase: n.phase
			});
			const r = resolveRunStartupPhase(n.phase);
			if (r && r !== w) {
				w = r;
				emitAgentRunStatusEvent({
					runId: t,
					phase: r
				});
			}
			if (n.phase === "turn_accepted" || n.phase === "model_call_started" || n.phase === "process_spawned") u.mcpAppContextLease?.commit();
			if (n.phase === "turn_accepted" || n.phase === "process_spawned" || n.phase === "model_call_started" || n.phase === "tool_execution_started" || n.phase === "assistant_output_started") {
				notifyAgentRunStart();
				(u.typingSignals.signalExecutionActivity?.() ?? u.typingSignals.signalRunStart()).catch((e) => {
					logVerbose(`execution phase typing signal failed: ${String(e)}`);
				});
			}
			const i = u.followupRun.run.scheduledAutomation;
			i?.onExecutionPhase?.({
				...n,
				jobId: i.job.id,
				agentId: m.agentId,
				sessionId: u.followupRun.run.sessionId,
				sessionKey: u.sessionKey,
				runId: t
			});
		};
		return {
			prepareAgentRunStart,
			notifyAgentRunStart,
			hasAgentRunStarted: () => C,
			signalExecutionPhaseForTyping,
			close: () => {
				e = false;
			}
		};
	};
	const T = shouldNotifyUserAboutCompaction(p);
	let E;
	let D = 0;
	const O = {
		deferredLifecycle: o,
		lifecycleGeneration: y,
		turnStartedAtMs: Date.now(),
		compaction: s,
		postCompactionModelAttempted: false,
		attemptedRuntimeProvider: u.followupRun.run.provider,
		attemptedRuntimeModel: u.followupRun.run.model,
		bootstrapPromptWarningSignaturesSeen: resolveBootstrapWarningSignaturesSeen(u.getActiveSessionEntry()?.systemPromptReport)
	};
	const clearRecoveredAutoFallbackPrimaryProbe = async (e) => clearRecoveredAutoFallbackPrimaryProbeSelection({
		run: m,
		...e,
		sessionKey: u.sessionKey,
		activeSessionStore: u.activeSessionStore,
		getActiveSessionEntry: u.getActiveSessionEntry,
		storePath: u.storePath
	});
	let k = false;
	while (true) {
		try {
			if (!k) {
				await prepareReplySubagentContinuation(u, t, p, i);
				k = true;
			}
			const e = createAgentTurnPresentation({
				turn: u,
				replyMediaContext: b,
				directBlockDeliveries: d
			});
			const r = {
				preparedRunAdmission: i,
				scheduledMessageActionTurnCapability: c,
				scheduledInference: l,
				turn: u,
				effectiveRun: m,
				runtimeConfig: p,
				liveModelSwitchRuntimeEntry: h,
				runId: t,
				runAbortSignal: O.deferredLifecycle.signal,
				currentTurnImages: x,
				state: O,
				presentation: e,
				directBlockDeliveries: d,
				createAgentRunStartCallbacks,
				notifyUserAboutCompaction: T,
				timing: g,
				modelPatch: S,
				shouldSurfaceToControlUi: v,
				commitTerminalOutcome: n,
				clearRecoveredAutoFallbackPrimaryProbe
			};
			let a;
			try {
				a = await runAgentFallbackCandidates(r);
			} finally {
				await captureAgentWorkspaceReadiness(u.sessionKey)?.waitUntilReady();
			}
			r.timing.logIfSlow({
				runId: r.runId,
				sessionId: r.turn.followupRun.run.sessionId,
				sessionKey: r.turn.sessionKey,
				outcome: "completed"
			});
			E = await settleAgentFallbackCycle({
				cycle: r,
				fallbackResult: a
			});
		} catch (e) {
			if (e instanceof LiveSessionModelSwitchError) D += 1;
			const n = await handleAgentExecutionError({
				turn: u,
				error: e,
				runtimeConfig: p,
				runId: t,
				state: O,
				liveModelSwitchRetries: D,
				shouldSurfaceToControlUi: v,
				timing: g,
				modelPatch: S,
				resolveVisibleReplyDelivery: () => resolveReplyFailureVisibility(u.resolveVisibleReplyDelivery, d)
			});
			if (n.kind !== "retry") E = n;
			else {
				if (n.liveModelSwitchError) for (const e of /* @__PURE__ */ new Set([
					u.followupRun.run,
					f,
					m
				])) applyLiveModelSwitchToRun(e, n.liveModelSwitchError);
				continue;
			}
		}
		if (E.kind === "aborted") return {
			...E,
			sessionWriter: O.sessionWriter
		};
		if (E.kind === "final") return {
			...E,
			sessionWriter: O.sessionWriter,
			resolved: {
				provider: O.attemptedRuntimeProvider,
				model: O.attemptedRuntimeModel
			}
		};
		break;
	}
	const { runResult: A, fallbackProvider: j, fallbackModel: M, fallbackExhausted: N, fallbackAttempts: P, terminalRunFailed: F } = E;
	if (!A.payloads?.some((e) => !e.isError && !e.isReasoning && hasOutboundReplyContent(e, { trimText: true }))) {
		const e = A.payloads?.filter((e) => e.isError).map((e) => getReplyPayloadMetadata(e)?.providerFailure).find((e) => e?.rateLimitRetriesExhausted !== void 0);
		const t = A.meta?.error?.message ?? "";
		const n = A.payloads?.find((e) => e.isError && hasNonEmptyString(e.text) && !e.text.startsWith("⚠️"))?.text ?? "";
		const r = t || n;
		const i = e?.reason ?? (r ? classifyFailoverReason(r) : null);
		const a = i === "rate_limit" || i === "overloaded" ? renderRateLimitOrOverloadedCopy({
			reason: i,
			raw: r,
			rateLimitRetriesExhausted: e?.rateLimitRetriesExhausted
		}) : void 0;
		if (a) A.payloads = [markAgentRunFailureReplyPayload({
			text: a,
			isError: true
		})];
	}
	const I = F ? false : S.captureFallbackFailure(P) ?? false;
	await S.finish(!F && !I);
	const L = F ? await resolveTerminalAgentRunFailurePayload({
		result: A,
		run: {
			...u.followupRun.run,
			scheduledAutomation: u.followupRun.run.scheduledAutomation !== void 0,
			trigger: resolveReplyRunTrigger(u),
			currentInboundEventKind: u.followupRun.currentInboundEventKind
		},
		visibleReplyDelivered: () => resolveReplyFailureVisibility(u.resolveVisibleReplyDelivery, d)
	}) : void 0;
	return {
		kind: "settled",
		sessionWriter: O.sessionWriter,
		maintenanceAuthProfile: O.maintenanceAuthProfile,
		compactionRequestBudget: O.compactionRequestBudget,
		result: A,
		resolved: {
			provider: j,
			model: M
		},
		fallback: {
			exhausted: N,
			attempts: P
		},
		autoCompactionCount: s.count,
		hasDirectlySentBlockReply: d.some((e) => e.terminalDeliveryConfirmed === true) || void 0,
		directBlockDeliveries: d,
		...F ? {
			status: "failed",
			terminalFailurePayload: L,
			...O.postCompactionModelAttempted ? { postCompactionModelFailure: true } : {}
		} : { status: "ok" }
	};
}
async function executeAgentTurnOutcome(e, t) {
	const n = e.followupRun.operatorAuthority;
	if (n) {
		assertAdmittedRunOperatorAuthority(n);
		n.assertCurrent();
	}
	let r;
	const prepareMcpAppModelContext = async () => {
		n?.assertCurrent();
		r = await leaseMcpAppModelContextForSessionTurn({
			agentId: e.followupRun.run.agentId,
			sessionId: e.followupRun.run.sessionId,
			sessionKey: e.sessionKey ?? e.followupRun.run.sessionKey,
			requesterId: n?.profileId
		});
		n?.assertCurrent();
		return r;
	};
	const i = {
		count: 0,
		durable: []
	};
	const completedCompaction = () => i.count > 0 ? { compaction: {
		count: i.count,
		durable: [...i.durable]
	} } : {};
	let a = false;
	const commitTerminalOutcome = () => {
		if (a) return;
		a = true;
		e.replyOperation?.freezeAbort();
	};
	const o = captureAgentRunLifecycleGeneration(t);
	try {
		const n = await withAgentRunLifecycleGeneration(o, async () => {
			try {
				const n = prepareReplyTurnExecution(e, t);
				let r;
				let a;
				try {
					n.preparedRunAdmission.assertSourceCurrent();
					const o = e.followupRun.run;
					if (o.scheduledAutomation) {
						const { prepareCronSessionWorktree: t } = await import("./run-workspace-C_4qUbq2.mjs");
						n.preparedRunAdmission.assertSourceCurrent();
						const r = await t({
							sessionKey: e.sessionKey ?? o.sessionKey ?? o.sessionId,
							entry: e.getActiveSessionEntry(),
							workspaceDir: o.workspaceDir,
							cwd: o.cwd,
							assertCurrent: () => {
								n.deferredLifecycle.signal?.throwIfAborted();
								n.preparedRunAdmission.assertSourceCurrent();
							}
						});
						a = r.lease;
						o.workspaceDir = r.workspaceDir;
						o.cwd = r.cwd;
					}
					const s = o.scheduledAutomation?.job.inferenceBinding;
					if (s) r = await prepareCronRunInference({
						binding: s,
						cfg: selectLiveRuntimeConfig(e.followupRun.run.config),
						agentDir: e.followupRun.run.agentDir
					});
					n.preparedRunAdmission.assertSourceCurrent();
					return await executeAgentTurnInternalLoop(e, t, commitTerminalOutcome, prepareMcpAppModelContext, n.preparedRunAdmission, n.admittedRunContext, n.deferredLifecycle, i, n.scheduledMessageActionTurnCapability, r);
				} finally {
					try {
						await n.close();
					} finally {
						try {
							r?.dispose();
						} finally {
							await a?.release();
						}
					}
				}
			} finally {
				r?.rollback();
				commitTerminalOutcome();
			}
		});
		const a = n.kind !== "aborted" && resolveReplyOperationAbortReason(e.replyOperation);
		if (a) return {
			runId: t,
			outcome: {
				kind: "aborted",
				reason: a,
				sessionWriter: n.sessionWriter,
				...completedCompaction()
			}
		};
		return {
			runId: t,
			outcome: {
				...n.kind === "final" ? {
					kind: "rejected",
					sessionWriter: n.sessionWriter,
					payload: n.payload,
					resolved: n.resolved,
					...n.postCompactionModelFailure ? { postCompactionModelFailure: n.postCompactionModelFailure } : {}
				} : n,
				...completedCompaction()
			}
		};
	} catch (n) {
		const r = resolveReplyOperationAbortReason(e.replyOperation, n);
		if (r) return {
			runId: t,
			outcome: {
				kind: "aborted",
				reason: r,
				...completedCompaction()
			}
		};
		throw n;
	}
}
async function executeAgentTurn(e) {
	e.opts?.onRunVerbosityResolved?.({
		verboseLevelOverride: e.followupRun.run.verboseLevelOverride,
		resolvedVerboseLevel: e.resolvedVerboseLevel
	});
	const t = e.opts?.runId ?? crypto.randomUUID();
	const n = e.opts?.runId === t ? e : {
		...e,
		opts: {
			...e.opts,
			runId: t
		}
	};
	return await runAgentTurnWithOutcome(n, t, () => executeAgentTurnOutcome(n, t));
}
//#endregion
//#region src/auto-reply/reply/agent-runner-result-diagnostics.ts
const TRACE_USAGE_FIELDS = [
	["input", "⬇️"],
	["output", "⬆️"],
	["cacheRead", "♻️"],
	["cacheWrite", "🆕"],
	["total", "🔢"]
];
/** Builds the same authorized diagnostic supplement for immediate and queued replies. */
async function buildReplyDiagnosticsPayload(e) {
	const { activeSessionEntry: t, followupRun: n, accounting: r, cfg: i, storePath: a, userText: o, resolvedVerboseLevel: s, resolvedBlockStreamingBreak: c, preflightCompactionApplied: l } = e;
	const { runResult: u, providerUsed: d, modelUsed: f, contextTokensUsed: p, promptTokens: m } = r;
	const h = (normalizeVerboseLevel(n.run.verboseLevelOverride ?? t?.verboseLevel ?? s ?? n.run.verboseLevel) ?? "off") !== "off";
	const g = n.run.traceAuthorized === true;
	const _ = n.run.traceLevelOverride ?? t?.traceLevel;
	const v = g && (_ === "on" || _ === "raw");
	const y = u.meta?.requestShaping?.thinkingClamp;
	if (!h && !v) return;
	const b = [
		...y ? [y] : [],
		...h ? resolveSessionPluginStatusLines(t) : [],
		...v ? resolveSessionPluginTraceLines(t) : []
	];
	let x = b.length ? { text: b.join("\n") } : void 0;
	if (g && _ === "raw") {
		const e = u.meta?.error?.kind === "hook_block";
		const r = e ? u.meta?.finalPromptText : u.meta?.finalPromptText ?? o;
		const h = e ? void 0 : u.meta?.finalAssistantRawText ?? u.meta?.finalAssistantVisibleText;
		const g = u.meta?.executionTrace;
		const _ = {
			authMode: u.meta?.requestShaping?.authMode ?? (i?.models?.providers && d in i.models.providers ? await resolveModelAuthModeAsync(d, i, void 0, { workspaceDir: n.run.workspaceDir }) : void 0),
			thinking: u.meta?.requestShaping?.thinking ?? normalizeOptionalString(n.run.thinkLevel),
			reasoning: u.meta?.requestShaping?.reasoning ?? normalizeOptionalString(n.run.reasoningLevel),
			verbose: u.meta?.requestShaping?.verbose ?? normalizeOptionalString(s),
			trace: n.run.traceLevelOverride ?? u.meta?.requestShaping?.trace ?? normalizeOptionalString(t?.traceLevel),
			fallbackEligible: u.meta?.requestShaping?.fallbackEligible ?? resolveModelFallbackOptions(n.run, i ?? {}).modelFallbackAvailability.kind === "active",
			blockStreaming: u.meta?.requestShaping?.blockStreaming ?? normalizeOptionalString(c)
		};
		const v = u.meta?.promptSegments ?? derivePromptSegments(r);
		const y = u.meta?.toolSummary;
		const b = u.meta?.completion ?? (u.meta?.stopReason ? {
			stopReason: u.meta.stopReason,
			finishReason: u.meta.stopReason,
			...u.meta.stopReason.toLowerCase().includes("refusal") ? { refusal: true } : {}
		} : void 0);
		const S = u.meta?.contextManagement;
		let C;
		const w = normalizeOptionalString(u.meta?.agentMeta?.sessionId ?? n.run.sessionId);
		if (w) try {
			const e = n.run.sessionFile?.trim();
			const t = Boolean(e && path.isAbsolute(e) && e.endsWith(".jsonl"));
			const r = await readLatestSessionUsageFromTranscriptAsync({
				agentId: n.run.agentId,
				sessionId: w,
				sessionKey: t ? void 0 : n.run.sessionKey,
				storePath: a,
				sessionFile: n.run.sessionFile
			});
			if (r) C = {
				input: r.inputTokens,
				output: r.outputTokens,
				cacheRead: r.cacheRead,
				cacheWrite: r.cacheWrite,
				total: r.totalTokens
			};
		} catch {}
		const T = u.meta?.agentMeta?.usage;
		const E = S?.lastTurnCompactions ?? u.meta?.agentMeta?.compactionCount;
		const D = deriveContextPromptTokens({
			lastCallUsage: u.meta?.agentMeta?.lastCallUsage,
			promptTokens: m,
			usage: T
		});
		let O;
		const k = asFiniteNumber(p);
		const A = asFiniteNumber(D);
		if (k !== void 0 && k > 0 || A !== void 0 && A > 0 || d || f) {
			const e = k !== void 0 && A !== void 0 ? Math.max(0, k - A) : void 0;
			const t = k !== void 0 && k > 0 && A !== void 0 ? Math.round(A / k * 100) : void 0;
			O = `🔎 Context Window (Last Model Request):\n~~~text\n${[
				`provider=${d ?? "n/a"}`,
				`model=${f ?? "n/a"}`,
				formatTraceUsageLine("used", A),
				formatTraceUsageLine("limit", k),
				`headroom=${e !== void 0 ? `${e.toLocaleString()} tok (${formatTokenCount(e)})` : "n/a"}`,
				`usage=${t !== void 0 ? `${t}%` : "n/a"}`
			].join("\n")}\n~~~`;
		}
		let j;
		if (v?.length || r?.length) {
			const e = (v ?? []).map((e) => `${e.key}=${e.chars.toLocaleString()} chars`);
			if (r?.length) e.push(`totalPromptText=${r.length.toLocaleString()} chars`);
			j = `🔎 Prompt Segments:\n~~~text\n${e.join("\n")}\n~~~`;
		}
		const M = [
			formatUsageTraceBlock("Usage (Session Total)", C),
			formatUsageTraceBlock("Usage (Last Turn Total)", T),
			O,
			!g?.winnerProvider && !g?.winnerModel ? void 0 : formatKeyValueTraceBlock("Execution Result", [
				["winner", g.winnerProvider && g.winnerModel ? `${g.winnerProvider}/${g.winnerModel}` : void 0],
				["fallbackUsed", g.fallbackUsed],
				["attempts", g.attempts?.length],
				["runner", g.runner]
			]),
			formatFallbackChainTraceBlock(g),
			formatKeyValueTraceBlock("Request Shaping", [
				["provider", d],
				["model", f],
				["auth", _.authMode],
				["thinking", _.thinking],
				["reasoning", _.reasoning],
				["verbose", _.verbose],
				["trace", _.trace],
				["fallbackEligible", _.fallbackEligible],
				["blockStreaming", _.blockStreaming]
			]),
			j,
			!y || y.calls <= 0 ? void 0 : formatKeyValueTraceBlock("Tool Summary", [
				["calls", y.calls],
				["tools", y.tools.length > 0 ? y.tools.join(", ") : void 0],
				["failures", y.failures],
				["totalToolTimeMs", y.totalToolTimeMs]
			]),
			formatKeyValueTraceBlock("Completion", [
				["finishReason", b?.finishReason],
				["stopReason", b?.stopReason],
				["refusal", b?.refusal]
			]),
			formatKeyValueTraceBlock("Context Management", [
				["sessionCompactions", t?.compactionCount],
				["lastTurnCompactions", E],
				["preflightCompactionApplied", S?.preflightCompactionApplied ?? (l || void 0)],
				["postCompactionContextInjected", S?.postCompactionContextInjected]
			])
		].filter((e) => Boolean(e));
		const N = normalizeOptionalString(_.thinking);
		const P = asPositiveFiniteNumber(D);
		const F = asPositiveFiniteNumber(p);
		const I = [
			g?.winnerModel ? `winner=${g.winnerModel}${N ? ` 🧠 ${N}` : ""}` : void 0,
			g?.fallbackUsed !== void 0 ? `fallback=${g.fallbackUsed ? "yes" : "no"}` : void 0,
			g?.attempts !== void 0 ? `attempts=${g.attempts.length.toLocaleString()}` : void 0,
			b?.stopReason ? `stop=${b.stopReason}` : void 0,
			P !== void 0 && F !== void 0 ? `prompt=${formatTokenCount(P)}/${formatTokenCount(F)}` : void 0,
			...TRACE_USAGE_FIELDS.map(([e, t]) => {
				const n = T?.[e];
				return n !== void 0 && n > 0 ? `${t} ${formatTokenCount(n)}` : void 0;
			}),
			y && y.calls > 0 ? `tools=${y.calls.toLocaleString()}` : void 0,
			E !== void 0 && E > 0 ? `compactions=${E.toLocaleString()}` : void 0
		].filter((e) => Boolean(e));
		const L = { text: [
			...M,
			formatRawTraceBlock("Model Input (User Role)", r),
			formatRawTraceBlock("Model Output (Assistant Role)", h),
			I.length > 0 ? `Summary: ${I.join(" ")}` : void 0
		].join("\n\n\n") };
		x = x ? { text: `${x.text}\n\n${L.text}` } : L;
	}
	return x ? {
		...x,
		isStatusNotice: true
	} : void 0;
}
function formatRawTraceBlock(e, t) {
	return `🔎 ${e}:\n~~~text\n${t?.trim() ? t.replace(/^~~~/gm, "\\~~~") : "<empty>"}\n~~~`;
}
function formatTraceUsageLine(e, t) {
	const n = asFiniteNumber(t);
	return `${e}=${n !== void 0 ? `${n.toLocaleString()} tok (${formatTokenCount(n)})` : "n/a"}`;
}
function formatUsageTraceBlock(e, t) {
	if (!t || TRACE_USAGE_FIELDS.every(([e]) => asFiniteNumber(t[e]) === void 0)) return;
	return `🔎 ${e}:\n~~~text\n${TRACE_USAGE_FIELDS.map(([e]) => formatTraceUsageLine(e, t[e])).join("\n")}\n~~~`;
}
function formatTraceScalar(e) {
	if (typeof e === "boolean") return e ? "yes" : "no";
	if (typeof e === "number") return Number.isFinite(e) ? e.toLocaleString() : void 0;
	return normalizeOptionalString(e);
}
function formatKeyValueTraceBlock(e, t) {
	const n = t.flatMap(([e, t]) => {
		const n = formatTraceScalar(t);
		return n ? [`${e}=${n}`] : [];
	});
	if (n.length === 0) return;
	return `🔎 ${e}:\n~~~text\n${n.join("\n")}\n~~~`;
}
function formatFallbackChainTraceBlock(e) {
	const t = e?.attempts ?? [];
	if (t.length <= 1) return;
	return `🔎 Fallback Chain:\n~~~text\n${t.map((e, t) => [
		`${t + 1}. ${e.provider}/${e.model}`,
		`   result=${e.result}`,
		...e.reason ? [`   reason=${e.reason}`] : [],
		...e.stage ? [`   stage=${e.stage}`] : [],
		...e.elapsedMs !== void 0 ? [`   elapsed=${(e.elapsedMs / 1e3).toFixed(1)}s`] : [],
		...e.status !== void 0 ? [`   status=${e.status}`] : []
	].join("\n")).join("\n\n")}\n~~~`;
}
function resolveMetadataSegmentKey(e) {
	const t = e.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
	if (t === "conversation_info") return "conversation_metadata";
	if (t === "sender") return "sender_metadata";
	return t.endsWith("_metadata") ? t : `${t}_metadata`;
}
function derivePromptSegments(e) {
	const t = e ?? "";
	if (!t.trim()) return;
	const n = t.split("\n");
	const r = /* @__PURE__ */ new Map();
	let i = 0;
	const addChars = (e, t) => {
		r.set(e, (r.get(e) ?? 0) + t);
	};
	let a = 0;
	while (a < n.length) {
		const e = n[a] ?? "";
		let t;
		let r = a + 2;
		if (e === "Context:") {
			const e = (n[a + 1] ?? "").trim().match(/^<([a-z0-9_:-]+)>$/i);
			if (e) {
				t = expectDefined(e[1], "tag match capture group 1");
				const i = `</${e[1]}>`;
				while (r < n.length && n[r]?.trim() !== i) r += 1;
			}
		} else if (e.trim().endsWith("⟦openclaw:ctx⟧")) {
			if ((n[a + 1] ?? "").trim() === "```json") {
				while (r < n.length && !(n[r] ?? "").startsWith("```")) r += 1;
				t = resolveMetadataSegmentKey(e.trim().slice(0, -"⟦openclaw:ctx⟧".length).trim() || "metadata");
			}
		}
		if (t && r < n.length) {
			addChars(t, n.slice(a, r + 1).join("\n").length);
			a = r + 1;
			while (a < n.length && n[a] === "") a += 1;
			continue;
		}
		if (e.trim()) i += e.length + 1;
		a += 1;
	}
	if (i > 0) addChars("user_message", i);
	const o = Array.from(r.entries()).map(([e, t]) => ({
		key: e,
		chars: t
	}));
	return o.length > 0 ? o : void 0;
}
//#endregion
//#region src/auto-reply/reply/session-usage.ts
/** Prepare host-owned pricing without choosing a persistence envelope. */
function prepareSessionUsageUpdate(e) {
	const t = e.cfg ?? readRuntimeConfig();
	const n = e.runtimeModelSelection ?? {
		provider: e.providerUsed,
		model: e.modelUsed
	};
	const r = hasNonzeroUsage(e.usage);
	const i = hasBillableUsage(e.usage);
	const a = e.promptTokens !== void 0 && Number.isFinite(e.promptTokens) && e.promptTokens > 0;
	const o = Boolean(e.lastCallUsage) && e.lastCallUsage?.contextUsage?.state !== "unavailable" || a;
	const s = e.currentContextSnapshot !== void 0;
	const c = e.usage?.usageReport?.state === "unavailable" || r || o || s || Boolean(n.model || e.contextTokensUsed);
	if (!i && !c) return;
	const l = e.preserveUserFacingSessionModelState === true;
	const u = asNonNegativeFiniteNumber(e.currentContextSnapshot?.tokens);
	const d = {
		usage: e.usage,
		lastCallUsage: e.lastCallUsage,
		modelSelection: n,
		agentHarnessId: normalizeOptionalString(e.agentHarnessId),
		contextTokensUsed: e.contextTokensUsed,
		contextTokensSource: e.contextTokensSource,
		contextBudgetStatus: e.contextBudgetStatus,
		systemPromptReport: e.systemPromptReport,
		promptTokens: e.promptTokens,
		currentContextTokens: u === void 0 ? void 0 : Math.floor(u),
		hasContextUpdate: c,
		hasFreshContextSnapshot: o,
		hasCurrentContextSnapshot: s,
		preserveSessionModelState: e.preserveRuntimeModel === true || l,
		preserveUserFacingRunState: l,
		preserveFreshTotalTokensOnStaleUsage: e.preserveFreshTotalTokensOnStaleUsage
	};
	const estimateCost = (n) => l || !i ? void 0 : asNonNegativeFiniteNumber(estimateAggregateUsageCost({
		config: t,
		agentDir: e.agentDir,
		usage: e.usage,
		provider: e.providerUsed ?? n?.modelProvider,
		model: e.modelUsed ?? n?.model
	}));
	return {
		update: d,
		estimateCost
	};
}
//#endregion
//#region src/auto-reply/reply/agent-runner-result-accounting.ts
const modelFallbackLog = createSubsystemLogger("model-fallback");
/** Persists only host-bound facts while the exact logical turn still owns accounting. */
async function accountAgentTurnCompaction(e) {
	const t = e.replyOperation;
	if (!t) return;
	const authorize = () => isCurrentSessionControllerOperation(t);
	let n;
	for (const t of e.compaction?.durable ?? []) {
		const r = await incrementCompactionCount({
			...t.target,
			sessionStore: e.sessionStore,
			expectedSession: t.target,
			amount: t.count,
			tokensAfter: t.currentContextSnapshot?.tokens,
			transcriptByteCompactionLatch: t.hostCompactionCommitted ? null : void 0,
			authorize
		});
		if (r !== void 0) n = r;
	}
	return n;
}
async function accountAgentTurn(e) {
	const { activeSessionStore: t, blockReplyPipeline: n, cfg: r, defaultModel: i, followupRun: a, pendingToolTasks: o, preflightCompactionApplied: s, resolvedVerboseLevel: c, execution: l, runId: u, runStartedAt: d, sessionKey: f, sessionCtx: p, shouldInjectGroupIntro: m } = e;
	let { activeSessionEntry: h } = e;
	const g = e.completion;
	h = g?.current() ?? h;
	const patchBookkeeping = (n, r) => {
		if (g) {
			for (const e of r) g.patch(e);
			return g.current();
		}
		if (n && !e.storePath) {
			Object.assign(n, reduceSessionActorEntry(n, r));
			if (t && f) t[f] = n;
		}
		return n;
	};
	const _ = l.compaction?.durable.at(-1);
	const v = l.compaction ? _?.currentContextSnapshot ?? { tokens: void 0 } : void 0;
	const y = _?.target ?? {
		sessionId: h?.sessionId ?? a.run.sessionId,
		lifecycleRevision: h?.lifecycleRevision
	};
	const b = e.replyOperation;
	const x = l.result;
	const { provider: S, model: C } = l.resolved;
	const { exhausted: w, attempts: T } = l.fallback;
	const E = l.hasDirectlySentBlockReply;
	const D = l.directBlockDeliveries;
	const O = l.terminalFailurePayload;
	const { autoCompactionCount: k } = l;
	if (m && h && t && f && h.groupActivationNeedsSystemIntro) h = patchBookkeeping(h, [{
		kind: "group-intro",
		needsSystemIntro: false
	}, {
		kind: "activity",
		updatedAt: Date.now()
	}]);
	const A = x.payloads ?? [];
	if (n) {
		await n.flush({ force: true });
		n.stop();
	}
	if (o.size > 0) await drainPendingToolTasks({ tasks: o });
	const j = x.meta?.agentMeta?.usage;
	const M = x.meta?.agentMeta?.promptTokens;
	const N = x.meta?.agentMeta?.model ?? C ?? i;
	const P = x.meta?.agentMeta?.provider ?? S ?? a.run.provider;
	const F = x.meta?.agentMeta?.runtimeModelSelection;
	const I = F ?? {
		provider: P,
		model: N
	};
	const L = w ? void 0 : x.meta?.executionTrace?.winnerProvider ?? P;
	const ee = w ? void 0 : x.meta?.executionTrace?.winnerModel ?? N;
	const R = x.meta?.agentMeta?.contextTokens;
	const z = x.meta?.agentMeta?.compactionCount;
	const B = x.meta?.agentMeta?.lastCallUsage;
	const V = buildReplyUsageState({
		config: r,
		agentDir: a.run.agentDir,
		provider: P,
		model: N,
		fallbackExhausted: w,
		winnerProvider: L,
		winnerModel: ee,
		reasoningEffort: a.run.thinkLevel,
		fastMode: resolveFastModeState({
			cfg: r,
			provider: P ?? "",
			model: N ?? "",
			agentId: a.run.agentId,
			sessionEntry: h
		}).enabled,
		fallbackUsed: x.meta?.executionTrace?.fallbackUsed === true,
		agentId: a.run.agentId,
		sessionId: a.run.sessionId,
		chatType: p.ChatType,
		authMode: x.meta?.requestShaping?.authMode,
		overrideSource: h?.modelOverrideSource,
		requestedProvider: a.run.provider,
		requestedModel: a.run.model,
		durationMs: Date.now() - d,
		compactionCount: z,
		contextTokenBudget: R,
		contextUsedTokens: M,
		promptTokens: M,
		usage: j,
		lastCallUsage: B
	});
	recordReplyUsageState(u, V);
	const te = c !== "off";
	const H = shouldPreserveUserFacingSessionStateForInputProvenance(a.run.inputProvenance);
	const U = (g ? await g.refresh() : h) ?? (f ? t?.[f] : void 0);
	const W = resolveFallbackOriginModel({
		run: a.run,
		fallbackStateEntry: U,
		runtimeModelSelection: F
	});
	const ne = W.provider;
	const G = W.model;
	const K = resolveFallbackTransition({
		selectedProvider: ne,
		selectedModel: G,
		activeProvider: I.provider,
		activeModel: I.model,
		attempts: T,
		state: U,
		cfg: r
	});
	if (K.fallbackCleared) {
		const t = x.meta?.agentMeta;
		const n = l.status === "ok" && !w && x.meta?.aborted !== true && !x.meta?.error && !x.meta?.replayInvalid && !x.meta?.failureSignal && !A.some((e) => e.isError) && b?.abortSignal.aborted !== true && t !== void 0 && areRuntimeModelRefsEquivalent(buildModelCatalogRef(I.provider, I.model), K.selectedModelRef, { config: r });
		const selectionUnchanged = (e) => {
			const t = e.modelOverrideSource !== "auto" ? resolvePersistedOverrideModelRef({
				defaultProvider: ne,
				overrideProvider: e.providerOverride,
				overrideModel: e.modelOverride,
				routeResolution: "resolved"
			}) : null;
			return e.fallbackNotice?.selectedModel === K.selectedModelRef && (!t || areRuntimeModelRefsEquivalent(buildModelCatalogRef(t.provider, t.model), K.selectedModelRef, { config: r }));
		};
		if (!n) {
			K.fallbackCleared = false;
			K.stateChanged = false;
		} else if (!U || !selectionUnchanged(U)) K.fallbackCleared = false;
		else if (g && f && e.storePath && !H) {
			const t = K.previousState.activeModel;
			const n = a.run.agentId;
			const i = e.storePath;
			const o = K.selectedModelRef;
			let s = false;
			if (u && u.length <= 4096 && t && t.length <= 512 && o && o.length <= 512 && t !== o) {
				const assertCurrent = () => {
					b?.abortSignal.throwIfAborted();
					g.assertCurrent();
				};
				try {
					assertCurrent();
					const { appendAssistantMessageToSessionTranscript: e } = await import("./transcript-DluvB2hw.mjs");
					assertCurrent();
					const a = createHash("sha256").update(u).digest("hex");
					const c = await e({
						agentId: n,
						sessionKey: f,
						storePath: i,
						expectedSessionId: U.sessionId,
						expectedLifecycleRevision: U.lifecycleRevision ?? null,
						expectedWriterRunId: U.activeWriterRunId,
						runId: u,
						config: r,
						assertCurrent,
						idempotencyKey: `model-fallback-restored:${a}`,
						text: `Selected model ${o} restored (was ${t}).`,
						deliveryMirror: {
							kind: MODEL_FALLBACK_NOTICE_KIND,
							phase: "restored",
							runId: u,
							fromModel: t,
							toModel: o
						}
					});
					s = c.ok;
					if (!c.ok && c.code !== "session-rebound") modelFallbackLog.warn("Model restoration transcript notice was not persisted.");
				} catch {
					modelFallbackLog.warn("Model restoration transcript notice was not persisted.");
				}
			}
			if (s) x.meta.modelFallbackTranscriptToModel = o;
			else {
				K.fallbackCleared = false;
				K.stateChanged = false;
			}
		}
	}
	if (K.stateChanged && !w && !H) h = patchBookkeeping(U, [{
		kind: "fallback-notice",
		notice: K.nextState.selectedModel ? {
			kind: "active",
			selectedModel: K.nextState.selectedModel,
			activeModel: K.nextState.activeModel,
			...K.nextState.reason ? { reason: K.nextState.reason } : {}
		} : void 0
	}, {
		kind: "activity",
		updatedAt: Date.now()
	}]);
	const re = R !== void 0 && Number.isFinite(R) && R > 0 ? Math.floor(R) : void 0;
	const ie = re === void 0 ? resolveContextTokensForModel({
		cfg: r,
		provider: I.provider,
		model: I.model,
		allowAsyncLoad: false
	}) : void 0;
	const ae = re ?? ie ?? h?.contextTokens ?? 2e5;
	const oe = x.meta?.agentMeta?.contextTokensSource ?? (re !== void 0 ? "runtime" : ie !== void 0 ? "resolved-v1" : void 0);
	const q = await accountAgentTurnCompaction({
		compaction: l.compaction,
		sessionStore: t,
		replyOperation: b
	});
	if (g) h = await g.refresh();
	const se = h?.liveModelSwitchPending === true;
	const ce = {
		cfg: r,
		agentDir: a.run.agentDir,
		usage: j,
		lastCallUsage: B,
		currentContextSnapshot: v,
		promptTokens: M,
		preserveRuntimeModel: w || (K.stateChanged ? K.nextState : K.previousState).selectedModel !== void 0,
		preserveUserFacingSessionModelState: H,
		modelUsed: N,
		providerUsed: P,
		runtimeModelSelection: F,
		contextTokensUsed: ae,
		contextTokensSource: oe,
		contextBudgetStatus: q === void 0 ? x.meta?.agentMeta?.contextBudgetStatus : void 0,
		systemPromptReport: x.meta?.systemPromptReport,
		preserveFreshTotalTokensOnStaleUsage: s,
		agentHarnessId: x.meta?.agentMeta?.agentHarnessId
	};
	if (g) g.patch((e) => {
		try {
			const t = prepareSessionUsageUpdate(ce);
			return t ? {
				kind: "usage",
				update: {
					...t.update,
					estimatedCostUsd: t.estimateCost(e)
				},
				updatedAt: e.updatedAt
			} : void 0;
		} catch (e) {
			logVerbose(`failed to prepare usage update: ${String(e)}`);
			return;
		}
	});
	if (!H && !w) {
		if (g && f && se) {
			const e = prepareLiveModelSwitchAfterRun({
				cfg: r,
				sessionKey: f,
				agentId: a.run.agentId,
				providerUsed: I.provider,
				modelUsed: I.model,
				entry: g.current()
			});
			if (e) g.patch(e);
		}
	}
	if (!g && q !== void 0 && f) h = t?.[f] ?? h;
	h = g?.current() ?? h;
	return {
		activeSessionEntry: h,
		autoCompactionCount: k,
		compactionCount: q,
		expectedSession: y,
		configuredFallbackModel: W,
		contextTokensUsed: ae,
		hasDirectlySentBlockReply: E,
		directBlockDeliveries: D,
		fallbackAttempts: T,
		fallbackExhausted: w,
		fallbackTransition: K,
		modelUsed: N,
		payloadArray: A,
		preserveUserFacingSessionState: H,
		promptTokens: M,
		providerUsed: P,
		replyUsageState: V,
		runId: u,
		runResult: x,
		selectedModel: G,
		selectedProvider: ne,
		sessionModel: I,
		terminalFailurePayload: O,
		usage: j,
		verboseEnabled: te
	};
}
/** Applies common accounting plus the queue/session projection owned by follow-up turns. */
async function accountFollowupTurn(e) {
	const { turn: t, defaults: n, execution: r, completion: i } = e;
	const a = r.execution.outcome;
	const o = t.session.kind === "session" ? t.session.key : void 0;
	if (a.kind !== "settled") {
		await accountAgentTurnCompaction({
			compaction: a.compaction,
			sessionStore: t.sessionStore,
			replyOperation: t.operation
		});
		return;
	}
	if (t.queued.goalContinuation) i?.patch({
		kind: "goal-continuation",
		goalId: t.queued.goalContinuation.goalId
	});
	const s = normalizeVerboseLevel(t.queued.run.verboseLevelOverride ?? t.session.current()?.verboseLevel ?? t.queued.run.verboseLevel) ?? "off";
	const c = await accountAgentTurn({
		activeSessionEntry: t.session.current(),
		activeSessionStore: t.sessionStore,
		blockReplyPipeline: null,
		cfg: t.config,
		defaultModel: n.defaultModel,
		followupRun: t.queued,
		pendingToolTasks: r.pendingToolTasks,
		replyOperation: t.operation,
		completion: i,
		preflightCompactionApplied: t.preflightCompactionApplied,
		resolvedVerboseLevel: s,
		execution: a,
		runId: r.execution.runId,
		runStartedAt: r.runStartedAt,
		sessionCtx: r.sessionCtx,
		sessionKey: o,
		shouldInjectGroupIntro: false,
		storePath: t.session.kind === "session" ? t.session.storePath : void 0
	});
	const l = t.queued.run.sessionKey ?? n.sessionKey ?? o;
	if (l && c.fallbackTransition.stateChanged && !c.fallbackExhausted && !c.preserveUserFacingSessionState) {
		const e = c.activeSessionEntry;
		refreshQueuedFollowupSession({
			key: l,
			previousSessionId: t.queued.run.sessionId,
			nextSessionId: e?.sessionId ?? t.queued.run.sessionId,
			nextSessionFile: l,
			nextProvider: c.sessionModel.provider,
			nextModel: c.sessionModel.model,
			nextModelOverrideSource: e?.modelOverrideSource === "default" ? void 0 : e?.modelOverrideSource,
			nextAuthProfileId: e?.authProfileOverride,
			nextAuthProfileIdSource: resolveCollapsedSessionAuthPinSource(e)
		});
	}
	let u;
	if (c.autoCompactionCount > 0) {
		const e = t.queued.run.sessionId;
		const n = c.compactionCount;
		const r = c.activeSessionEntry;
		if (r) refreshQueuedFollowupSession({
			key: l ?? "",
			previousSessionId: e,
			nextSessionId: r.sessionId,
			nextSessionFile: l ?? o
		});
		if (c.verboseEnabled) u = { text: `🧹 Auto-compaction complete${n !== void 0 ? ` (count ${n})` : ""}.` };
	}
	const d = await buildReplyDiagnosticsPayload({
		activeSessionEntry: c.activeSessionEntry,
		followupRun: t.queued,
		accounting: c,
		cfg: t.config,
		storePath: t.session.kind === "session" ? t.session.storePath : void 0,
		userText: t.queued.prompt,
		resolvedVerboseLevel: s,
		resolvedBlockStreamingBreak: t.queued.run.blockReplyBreak,
		preflightCompactionApplied: t.preflightCompactionApplied
	});
	return {
		...c,
		compactionNotice: u,
		diagnosticsPayload: d
	};
}
//#endregion
//#region src/auto-reply/reply/agent-runner-completion.ts
/** One retained terminal owner, including no-send and exceptional completion. */
async function withAgentTurnCompletion(e, t) {
	const { storePath: n, sessionKey: r, entry: i, operation: a } = e;
	if (!n || !r || !i) return t(void 0);
	const o = e.writer ?? i;
	const s = {
		sessionId: o.sessionId,
		lifecycleRevision: o.lifecycleRevision,
		writerRunId: o.activeWriterRunId
	};
	const c = a.key;
	const assertCurrent = () => {
		if (a.key !== c || !isCurrentSessionControllerOperation(a)) throw new Error("Terminal accounting lost its reply operation");
	};
	assertCurrent();
	const l = await withSessionActor({
		agentId: e.agentId,
		storePath: n,
		sessionKey: r
	}, {
		assertCurrent,
		assertReadable: assertCurrent
	}, async (n) => {
		const r = {
			assertCurrent,
			authorize(e, t) {
				const n = t.entry;
				if (!n || n.sessionId !== s.sessionId || n.lifecycleRevision !== s.lifecycleRevision || n.activeWriterRunId !== s.writerRunId) throw new Error("Terminal accounting session changed");
			}
		};
		let i = n.snapshot(r) ?? await n.read(r);
		const a = [];
		let o = false;
		const project = () => {
			let e = i.entry;
			const t = [];
			for (const n of a) {
				const r = typeof n === "function" ? n(e) : n;
				if (r) {
					t.push(r);
					e = reduceSessionActorEntry(e, [r]);
				}
			}
			return {
				entry: e,
				reducers: t
			};
		};
		const refresh = async () => {
			i = n.snapshot(r) ?? await n.read(r);
			return project().entry;
		};
		const l = {
			assertCurrent() {
				assertCurrent();
				n.assertCurrent();
				return n.snapshot(r)?.entry;
			},
			current: () => project().entry,
			refresh,
			patch(e) {
				if (o) throw new Error("Terminal accounting is already settled");
				a.push(e);
			},
			async complete(t) {
				if (o) {
					if (t) throw new Error("Final delivery custody is already settled");
					return i.entry;
				}
				o = true;
				await refresh();
				let { reducers: a } = project();
				const l = e.activitySummaryCompletion?.take();
				if (a.length === 0 && !t && !l) return i.entry;
				const u = {};
				const d = await runSessionActorCommand(n, r, async (o) => {
					i = o ?? n.snapshot(r) ?? await n.read(r);
					({reducers: a} = project());
					return n.completeTurn({
						commandId: randomUUID(),
						phaseId: `complete:${c}`,
						expected: n.target.database.kind === "memory" ? void 0 : i.version,
						reducers: a,
						activitySummary: l,
						bookkeeping: {
							sessionId: s.sessionId,
							lifecycleRevision: s.lifecycleRevision ?? null,
							writerRunId: s.writerRunId,
							expectedState: buildSessionTranscriptTurnExpectedState(i.entry)
						},
						pendingFinalDelivery: t
					}, r, { committed: (t) => {
						u.receipt = t.receipt;
						if (l && t.receipt.postimage.entry) e.activitySummaryCompletion?.committed(t.receipt.postimage.entry);
					} });
				});
				if (u.receipt) {
					i = u.receipt.postimage;
					e.publish(i.entry);
				}
				if (d.kind === "rolled-back" && d.reason !== "stale-state" && !t && a.every((e) => e.kind === "usage")) {
					await refresh();
					logVerbose(`failed to persist usage update: ${d.error.message}`);
					return i.entry;
				}
				if (d.kind !== "committed") throw wrapSqliteWorkerError(d.error.message, d.kind === "unknown" ? "outcome-unknown" : "unavailable", d.error);
				if (d.failure) throw new Error(d.failure.message);
				return i.entry;
			}
		};
		let u;
		try {
			u = await t(l);
		} catch (e) {
			try {
				await l.complete();
			} catch (t) {
				throw new AggregateError([e, t], "Terminal accounting failed to settle", { cause: t });
			}
			throw e;
		}
		await l.complete();
		return { value: u };
	});
	if (!l) throw new Error("Terminal accounting session is unavailable");
	return l.value;
}
//#endregion
//#region src/auto-reply/reply/reply-payloads-base.ts
function applyReplyTagsToPayload(e) {
	const t = normalizeOptionalString(e.payload.replyToId) ? setReplyPayloadMetadata(copyReplyPayloadMetadata(e.payload, { ...e.payload }), { replyToIdExplicit: true }) : e.payload;
	const n = normalizeOptionalString(e.implicitReplyToId);
	const r = normalizeOptionalString(e.currentMessageId);
	const i = resolveImplicitCurrentMessageReplyAllowance(e.replyToMode, e.replyThreading);
	let a = t.replyToId || t.replyToCurrent === false || !n || !i ? t : copyReplyPayloadMetadata(t, {
		...t,
		replyToId: n
	});
	if (a.text?.includes("[[")) {
		const e = parseInlineDirectives(a.text, {
			currentMessageId: r,
			stripAudioTag: false
		});
		a = copyReplyPayloadMetadata(a, {
			...a,
			text: e.text || void 0,
			replyToId: e.replyToId ?? a.replyToId,
			replyToTag: e.hasReplyTag || a.replyToTag,
			replyToCurrent: e.replyToCurrent || a.replyToCurrent
		});
	}
	if (a.replyToCurrent && !a.replyToId && r) a = copyReplyPayloadMetadata(a, {
		...a,
		replyToId: r
	});
	return a;
}
function resolveReplyThreadingPayloads(e) {
	const { payloads: t, replyToMode: n, currentMessageId: r, replyThreading: i } = e;
	const a = normalizeOptionalString(r);
	return t.map((e) => applyReplyTagsToPayload({
		payload: e,
		replyToMode: n,
		implicitReplyToId: a,
		currentMessageId: r,
		replyThreading: i
	})).filter(isRenderablePayload);
}
function applyReplyThreading(e) {
	const t = createReplyToModeFilterForChannel(e.replyToMode, e.replyToChannel);
	return resolveReplyThreadingPayloads(e).map(t);
}
//#endregion
//#region src/auto-reply/reply/agent-runner-payloads.ts
const replyPayloadsDedupeRuntimeLoader = createLazyImportLoader(() => import("./reply-payloads-dedupe-lSCgdZct.mjs"));
const BUN_FETCH_SOCKET_ERROR_RE = /socket connection was closed unexpectedly/i;
async function normalizeSentMediaUrlsForDedupe(e) {
	if (e.sentMediaUrls.length === 0 || !e.normalizeMediaPaths) return e.sentMediaUrls;
	const t = /* @__PURE__ */ new Set();
	for (const n of e.sentMediaUrls) {
		const r = n.trim();
		if (!r) continue;
		t.add(r);
		try {
			const n = await e.normalizeMediaPaths({
				mediaUrl: r,
				mediaUrls: [r]
			});
			const i = resolveSendableOutboundReplyParts(n).mediaUrls;
			for (const e of i) t.add(e);
		} catch (e) {
			logVerbose(`messaging tool sent-media normalization failed: ${String(e)}`);
		}
	}
	return [...t];
}
function sanitizeFinalReplyText(e, t, n) {
	if (!t) return t;
	return e.isError ? renderUserFacingText(t, {
		errorContext: true,
		conversationContext: n
	}) : sanitizeUserFacingText(t, { conversationContext: n });
}
async function buildReplyPayloads(e) {
	const t = [];
	for (const n of e.payloads) {
		let r = n.text;
		if (n.isError && r && BUN_FETCH_SOCKET_ERROR_RE.test(r)) r = "⚠️ Lost the connection to the AI service. Check the conversation before trying again. For details, open Settings → Logs in the Control UI or run `openclaw logs --follow`.";
		if (r?.includes("HEARTBEAT_OK")) {
			const e = stripHeartbeatToken(r, { mode: "message" });
			if (e.shouldSkip && !resolveSendableOutboundReplyParts(n).hasMedia) continue;
			r = e.text;
		}
		const i = e.conversationContext;
		const a = sanitizeFinalReplyText(n, r, i);
		const o = copyReplyPayloadMetadata(n, {
			...n,
			text: a
		});
		const s = getReplyPayloadMetadata(n)?.sourceReplyTranscriptMirror;
		if (s?.text) setReplyPayloadMetadata(o, { sourceReplyTranscriptMirror: {
			...s,
			text: sanitizeFinalReplyText(n, s.text, i) || void 0
		} });
		t.push(o);
	}
	const n = resolveOriginMessageProvider({
		originatingChannel: e.originatingChannel,
		provider: e.messageProvider
	});
	const r = e.accountId;
	const i = createReplyDeliveryContext(e.replyToMode, e.originatingChatType);
	const a = n ? {
		channel: n,
		...r ? { accountId: r } : {}
	} : void 0;
	const o = e.applyReplyToMode ? resolveReplyThreadingPayloads : applyReplyThreading;
	const s = (await Promise.all(o({
		payloads: t,
		replyToMode: e.replyToMode,
		replyToChannel: e.replyToChannel,
		currentMessageId: e.currentMessageId,
		replyThreading: e.replyThreading
	}).map(async (t) => {
		const n = normalizeReplyPayloadDirectives({
			payload: t,
			currentMessageId: e.currentMessageId,
			parseMode: "always",
			extractMarkdownImages: e.extractMarkdownImages
		});
		const r = e.normalizeMediaPaths && resolveSendableOutboundReplyParts(n.payload).hasMedia ? copyReplyPayloadMetadata(n.payload, await e.normalizeMediaPaths(n.payload)) : n.payload;
		return setReplyPayloadMetadata(r, {
			replyDelivery: i,
			...a ? { replyDeliverySource: a } : {}
		});
	}))).filter(isRenderablePayload);
	const c = e.silentExpected ? s.filter(shouldKeepPayloadDuringSilentTurn) : s;
	const l = e.applyReplyToMode ? c.map(e.applyReplyToMode) : c;
	const u = e.blockStreamingEnabled && Boolean(e.blockReplyPipeline?.didStream()) && !e.blockReplyPipeline?.isAborted();
	const d = e.messagingToolSentTexts ?? [];
	const f = e.messagingToolSentTargets ?? [];
	const p = d.length > 0 || (e.messagingToolSentMediaUrls?.length ?? 0) > 0 || f.length > 0;
	let m = l;
	if (p) {
		const t = await replyPayloadsDedupeRuntimeLoader.load();
		const i = e.originatingTo;
		m = [];
		for (const a of l) {
			if (getReplyPayloadMetadata(a)?.sourceReplyTranscriptMirror) {
				m.push(a);
				continue;
			}
			m.push(...await t.filterMessagingToolReplyPayload({
				payload: a,
				config: e.config,
				messageProvider: n,
				messagingToolSentTargets: f,
				originatingTo: i,
				originatingThreadId: e.originatingThreadId,
				accountId: r,
				sentMediaUrls: e.messagingToolSentMediaUrls,
				sentTexts: d,
				onDeliveredTerminalDuplicate: e.onDeliveredTerminalDuplicate,
				normalizeSentMediaUrls: (t) => normalizeSentMediaUrlsForDedupe({
					sentMediaUrls: t,
					normalizeMediaPaths: e.normalizeMediaPaths
				})
			}));
		}
	}
	const h = (e.directBlockDeliveries ?? []).filter((e) => e.pending || !shouldRetryReplyDispatch(e.outcome)).map((e) => e.payload);
	for (const t of m) {
		const n = getReplyPayloadMetadata(t)?.assistantMessageIndex;
		const r = (e.directBlockDeliveries ?? []).filter((e) => isReplyPayloadTerminalContent(e.payload) && getReplyPayloadMetadata(e.payload)?.assistantMessageIndex === n);
		const i = r.some((e) => e.source?.complete === false) && r.map((e) => e.payload.text ?? "").join("").trim() === t.text?.trim() ? Array.from(new Set(r.flatMap((e) => e.source ?? []))) : void 0;
		const a = e.blockReplyPipeline?.getSourceRecovery?.(t) ?? i;
		if (a) setReplyPayloadMetadata(t, { blockReplySources: a });
	}
	const g = /* @__PURE__ */ new Map();
	for (const e of h) {
		if (!isReplyPayloadTerminalContent(e)) continue;
		const t = e.text ?? resolveSendableOutboundReplyParts(e).trimmedText;
		if (!t) continue;
		const n = getReplyPayloadMetadata(e)?.assistantMessageIndex;
		const r = g.get(n) ?? [];
		r.push(t);
		g.set(n, r);
	}
	const isDirectBlockRetryBlocked = (e) => {
		if (getReplyPayloadMetadata(e)?.blockReplySources) return false;
		const t = createBlockReplyContentKey(e);
		const n = getReplyPayloadMetadata(e)?.assistantMessageIndex;
		return h.some((e) => isReplyPayloadTerminalContent(e) && (n === void 0 || getReplyPayloadMetadata(e)?.assistantMessageIndex === n) && createBlockReplyContentKey(e) === t);
	};
	const isDirectTextRetryBlocked = (e) => {
		if (isDirectBlockRetryBlocked(e)) return true;
		const t = resolveSendableOutboundReplyParts(e).trimmedText;
		if (!t || !h.length) return false;
		const n = getReplyPayloadMetadata(e)?.assistantMessageIndex;
		const r = g.get(n);
		return r ? r.join("").trim() === t : false;
	};
	const preserveUnsentMediaAfterBlockSend = (t) => {
		if (t.isError || t.isFallbackNotice || getReplyPayloadMetadata(t)?.blockReplySources) return t;
		if (e.blockReplyPipeline?.isFinalPayloadRetryBlocked?.(t)) return null;
		const n = resolveSendableOutboundReplyParts(t);
		if (!n.hasMedia) return (hasOutboundReplyContent({
			...t,
			text: void 0,
			mediaUrl: void 0,
			mediaUrls: void 0
		}, { trimText: true }) ? e.blockReplyPipeline?.hasSentExactPayload?.(t) : e.blockReplyPipeline?.hasSentPayload(t) || isDirectTextRetryBlocked(t)) ? null : t;
		if (!n.trimmedText) return t;
		const r = copyReplyPayloadMetadata(t, {
			...t,
			mediaUrl: void 0,
			mediaUrls: void 0,
			audioAsVoice: void 0
		});
		if (!(e.blockReplyPipeline?.hasSentPayload(r) || e.blockReplyPipeline?.isFinalPayloadRetryBlocked?.(copyReplyPayloadMetadata(t, { text: t.text })) || isDirectTextRetryBlocked(r))) return t;
		return copyReplyPayloadMetadata(t, {
			...t,
			text: void 0,
			audioAsVoice: t.audioAsVoice || void 0
		});
	};
	const _ = u || e.blockStreamingEnabled || h.length > 0 ? m.flatMap((t) => {
		if (!u && (e.blockStreamingEnabled && e.blockReplyPipeline?.hasSentPayload(t) || isDirectBlockRetryBlocked(t))) return [];
		return preserveUnsentMediaAfterBlockSend(t) ?? [];
	}) : m;
	const v = await normalizeSentMediaUrlsForDedupe({
		sentMediaUrls: [
			...e.blockStreamingEnabled ? e.blockReplyPipeline?.getSentMediaUrls() ?? [] : [],
			...e.blockReplyPipeline?.getRetryBlockedMediaUrls?.() ?? [],
			...h.flatMap((e) => resolveSendableOutboundReplyParts(e).mediaUrls)
		],
		normalizeMediaPaths: e.normalizeMediaPaths
	});
	return { replyPayloads: (v.length > 0 ? (await replyPayloadsDedupeRuntimeLoader.load()).filterMessagingToolMediaDuplicates({
		payloads: _,
		sentMediaUrls: v
	}) : _).flatMap((t) => normalizeReplyPayload(t, {
		applyChannelTransforms: false,
		conversationContext: e.conversationContext
	}) ?? []) };
}
//#endregion
//#region src/auto-reply/reply/agent-runner-reminder-guard.ts
const UNSCHEDULED_REMINDER_NOTE = "Note: I did not schedule a reminder in this turn, so this will not trigger automatically.";
const REMINDER_COMMITMENT_PATTERNS = [
	/\b(?:i\s*['’]?ll|i will)\s+(?:make sure to\s+)?(?:remind|ping|follow up|follow-up|check (?:back|on)|circle back)\b/i,
	/\b(?:i\s*['’]?ll|i will)\s+(?:make sure to\s+)?remember\s+to\s+(?:(?:remind|ping|follow up|follow-up|check (?:back|on)|circle back)\b|(?:set|create|schedule)\s+(?:a\s+)?reminder\b)/i,
	/\b(?:i\s*['’]?ll|i will)\s+(?:make sure to\s+)?remember\b[^.!?]{0,160}?(?:\s+and(?:\s+then)?|,\s*(?:(?:and\s+)?then)?)\s+(?:(?:i\s*['’]?ll|i will|will)\s+)?(?:make sure to\s+)?(?:remind|ping|follow up|follow-up|check (?:back|on)|circle back|(?:set|create|schedule)\s+(?:a\s+)?reminder)\b/i,
	/\b(?:i\s*['’]?ll|i will)\s+(?:set|create|schedule)\s+(?:a\s+)?reminder\b/i
];
/** Returns true when text promises a reminder/follow-up without the guard note. */
function hasUnbackedReminderCommitment(e) {
	const t = normalizeLowercaseStringOrEmpty(e);
	if (!t.trim()) return false;
	if (t.includes(normalizeLowercaseStringOrEmpty(UNSCHEDULED_REMINDER_NOTE))) return false;
	return REMINDER_COMMITMENT_PATTERNS.some((t) => t.test(e));
}
/**
* Returns true when the cron store has at least one enabled job that shares the
* current session key. Used to suppress the "no reminder scheduled" guard note
* when an existing cron (created in a prior turn) already covers the commitment.
*/
async function hasSessionRelatedCronJobs(e) {
	try {
		const t = await loadCronJobsStore();
		return Boolean(e && t.jobs.some((t) => t.enabled && t.sessionKey === e));
	} catch {
		return false;
	}
}
/** Appends the unscheduled-reminder note to the first payload that needs it. */
function appendUnscheduledReminderNote(e) {
	let t = false;
	return e.map((e) => {
		if (t || e.isError || e.text === void 0) return e;
		if (!hasUnbackedReminderCommitment(e.text)) return e;
		t = true;
		return copyReplyPayloadMetadata(e, {
			...e,
			text: `${e.text.trimEnd()}\n\n${UNSCHEDULED_REMINDER_NOTE}`
		});
	});
}
//#endregion
//#region src/auto-reply/usage-bar/template.ts
function usageSegments() {
	return [
		{
			map: "model.is_fallback",
			cases: { true: "🔄" }
		},
		{
			map: "model.is_override",
			cases: { true: "📌" }
		},
		{
			when: "model.reasoning",
			text: "{model.reasoning|alias:reasoning}"
		},
		{
			map: "state.fast_mode",
			cases: {
				true: "⚡️",
				false: "🐌"
			}
		},
		{
			when: "context.max_tokens",
			text: "\xA0| 📚[{context.pct_used|meter:5:braille}]{context.max_tokens|num}"
		},
		{
			when: "cost.turn_usd",
			text: "\xA0💰{cost.turn_usd|fixed:4}"
		}
	];
}
const DEFAULT_USAGE_BAR_TEMPLATE = {
	schema: "openclaw.usageBar.v1",
	scales: {
		braille: "⠐⡀⡄⡆⡇⣇⣧⣷⣿",
		block: "░▏▎▍▌▋▊▉█",
		shade: "░▒▓█",
		moon: "🌑🌘🌗🌖🌕",
		level: "▁▂▃▄▅▆▇█",
		weather: [
			"🥶",
			"☁️",
			"🌥",
			"⛅️",
			"🌤",
			"☀️"
		],
		plants: [
			"🪾",
			"🍂",
			"🌱",
			"☘️",
			"🍀",
			"🌿"
		],
		moons6: [
			"🌑",
			"🌚",
			"🌘",
			"🌗",
			"🌖",
			"🌝"
		]
	},
	aliases: {
		models: {
			"claude-opus-4-6": "opus46",
			"claude-opus-4-8": "opus48",
			"claude-sonnet-4-6": "sonnet46",
			"claude-haiku-4-5": "haiku45",
			"gpt-5.5": "gpt5.5"
		},
		reasoning: {
			off: "🌑",
			minimal: "🌚",
			low: "🌘",
			medium: "🌗",
			high: "🌕",
			xhigh: "🌝"
		}
	},
	output: {
		sep: "",
		default: [{ text: "{model.provider}{identity.emoji|🤖}{model.display_name|alias:models}" }, ...usageSegments()],
		surfaces: { discord: [
			{ text: "-# -\n" },
			{ text: "-# {model.provider}{identity.emoji|🤖}{model.display_name|alias:models}" },
			...usageSegments()
		] }
	}
};
const fileCache = /* @__PURE__ */ new Map();
const MAX_CACHED_TEMPLATE_FILES = 64;
const warnedTemplateOverrides = createDedupeCache({
	maxSize: 256,
	ttlMs: 0
});
const usageTemplateLog = createSubsystemLogger("usage-template");
function hasPieces(e) {
	return Array.isArray(e) && e.some(isRecord);
}
function hasOutputPieces(e) {
	if (!isRecord(e)) return false;
	if (hasPieces(e.default)) return true;
	const t = e.surfaces;
	return isRecord(t) && Object.values(t).some(hasPieces);
}
function resolveTemplateOrWarn(e, t, n) {
	const r = e.reason;
	if (r && !warnedTemplateOverrides.check(`${t}:${r}:${n ?? ""}`)) usageTemplateLog.warn("configured usage template could not be used; using built-in footer", {
		source: t,
		reason: r,
		...n ? { path: n } : {}
	});
	return e.template;
}
function parseTemplate(e) {
	if (isRecord(e)) {
		const t = hasOutputPieces(e.output) || hasPieces(e.segments);
		const n = t ? void 0 : e.surfaces;
		if (t || isRecord(n) && Object.values(n).some((e) => isRecord(e) && hasPieces(e.segments))) return { template: e };
		if (Object.keys(e).length === 0) return {};
		if (Array.isArray(e.segments)) return e.segments.length === 0 ? {} : { reason: "unsupported-shape" };
		const r = e.output;
		if (isRecord(r) && !hasOutputPieces(r)) return {};
	}
	return { reason: "unsupported-shape" };
}
function readTemplateFile(e) {
	let t;
	try {
		t = readFileSync(e, "utf8");
	} catch (e) {
		return extractErrorCode(e) === "ENOENT" ? {} : { reason: "unreadable" };
	}
	if (t.trim().length === 0) return {};
	try {
		return parseTemplate(JSON.parse(t));
	} catch {
		return { reason: "invalid-json" };
	}
}
function cacheTemplateFile(e) {
	const t = resolveTemplateOrWarn(readTemplateFile(e), "file", e);
	if (!fileCache.has(e) && fileCache.size >= MAX_CACHED_TEMPLATE_FILES) {
		const e = fileCache.keys().next().value;
		if (e !== void 0) {
			fileCache.get(e)?.abort.abort();
			fileCache.delete(e);
		}
	}
	const n = {
		template: t,
		abort: new AbortController()
	};
	if (n.template) n.watcher = (async () => {
		const t = await realpath(e);
		const r = await root(dirname(t), { hardlinks: "allow" });
		if (n.abort.signal.aborted) return;
		const i = watch$1(r, {
			mode: "auto",
			persistent: false,
			scopes: [{
				path: basename(t),
				kind: "entry"
			}],
			signal: n.abort.signal,
			onInvalidate: () => {
				const t = resolveTemplateOrWarn(readTemplateFile(e), "file", e);
				if (JSON.stringify(t) !== JSON.stringify(n.template)) n.template = t;
			},
			onHealth: (e) => {
				if (e.state === "unavailable") {
					n.abort.abort();
					n.watcher = void 0;
					n.template = void 0;
				}
			}
		});
		await i.ready;
		return i;
	})().catch(() => {
		n.abort.abort();
		n.watcher = void 0;
		n.template = void 0;
	});
	fileCache.set(e, n);
	return n.template;
}
function loadUsageBarTemplate(e) {
	if (!e) return DEFAULT_USAGE_BAR_TEMPLATE;
	if (typeof e === "object") return resolveTemplateOrWarn(parseTemplate(e), "inline") ?? DEFAULT_USAGE_BAR_TEMPLATE;
	const t = e.startsWith("~") ? resolve(expandHomePrefix(e, { home: homedir() })) : resolve(e);
	const n = fileCache.get(t);
	return n?.template ?? (n?.watcher ? void 0 : cacheTemplateFile(t)) ?? DEFAULT_USAGE_BAR_TEMPLATE;
}
async function clearUsageBarTemplateCacheForTest() {
	const e = [...fileCache.values()];
	fileCache.clear();
	warnedTemplateOverrides.clear();
	for (const t of e) t.abort.abort();
	await Promise.all(e.map(async (e) => (await e.watcher)?.close()));
}
if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.usageBarTemplateTestApi")] = { clearUsageBarTemplateCacheForTest };
//#endregion
//#region src/auto-reply/usage-bar/translator.ts
function coerceFiniteValue(e) {
	if (e === null || e === void 0 || e === "") return;
	return asFiniteNumber(Number(e));
}
function num(e) {
	if (Math.abs(e) >= 1e6) {
		const t = formatTokenCount(Math.abs(e));
		return e < 0 ? `-${t}` : t;
	}
	if (Math.abs(e) >= 1e3) {
		const t = e / 1e3;
		return Math.abs(t) < 10 ? `${t.toFixed(1)}k` : `${Math.round(t)}k`;
	}
	return String(Math.trunc(e));
}
function fixed(e, t) {
	const n = coerceFiniteValue(e);
	return n === void 0 ? "" : n.toFixed(t);
}
function dur(e) {
	const t = Math.max(0, Math.trunc(e));
	if (t >= 86400) return `${(t / 86400).toFixed(1)}d`;
	if (t >= 3600) {
		const e = Math.floor(t % 3600 / 60);
		return `${Math.floor(t / 3600)}h${String(e).padStart(2, "0")}m`;
	}
	return `${Math.floor(t / 60)}m`;
}
function meter(e, t, n) {
	const r = typeof n === "string" ? Array.from(n) : filterStringEntries(n);
	if (r.length < 2 || t < 1) return "";
	const i = expectDefined(r[0], "glyphs entry at 0");
	const a = expectDefined(r[r.length - 1], "glyphs entry at glyphs.length 1");
	const o = Math.max(0, Math.min(100, coerceFiniteValue(e) ?? 0)) / 100 * t;
	const s = Math.trunc(o);
	if (s === t) return a.repeat(t);
	const c = expectDefined(r[Math.round((o - s) * (r.length - 1))], "glyphs entry at math.round((total fullc) * (glyphs.length 1))");
	return a.repeat(s) + c + i.repeat(t - s - 1);
}
function parseBoundedIntegerArg(e, t) {
	const n = e === void 0 ? t.defaultValue : parseStrictInteger(e);
	return asSafeIntegerInRange(n, t);
}
function numeric(e, t = false) {
	return (n) => {
		const r = coerceFiniteValue(n);
		return r === void 0 ? t ? n : "" : e(r);
	};
}
const VERBS = {
	num: numeric(num),
	dur: numeric(dur),
	pct: numeric((e) => `${Math.round(e)}%`),
	inv: numeric((e) => 100 - Math.max(0, Math.min(100, e)), true),
	fixed(e, t) {
		const n = parseBoundedIntegerArg(t[0], {
			defaultValue: 2,
			min: 0,
			max: 100
		});
		return n === void 0 ? "" : fixed(e, n);
	},
	alias(e, t, n) {
		const r = isRecord(n["_aliases"]) ? n["_aliases"] : {};
		const i = t[0] && isRecord(r[t[0]]) ? r[t[0]] : {};
		const a = String(e);
		if (Object.hasOwn(i, a)) return i[a];
		const o = a.toLowerCase();
		return Object.hasOwn(i, o) ? i[o] : e;
	},
	meter(e, t, n) {
		const r = parseBoundedIntegerArg(t[0]?.trim() ? t[0] : void 0, {
			defaultValue: 5,
			min: 1,
			max: 100
		});
		const i = t.length > 1 ? n[expectDefined(t[1], "args entry at 1")] : void 0;
		return r === void 0 ? "" : meter(e, r, i);
	}
};
function getPath(e, t) {
	let n = e;
	for (const e of t.split(".")) {
		if (!isRecord(n)) return;
		n = n[e];
		if (n === null || n === void 0) return;
	}
	return n;
}
const TOKEN = /\{([^}]+)\}/g;
function interp(e, t, n) {
	return e.replace(TOKEN, (e, r) => {
		const i = r.split("|");
		let a = getPath(t, (i[0] ?? "").trim());
		const o = [];
		let s;
		for (const e of i.slice(1)) {
			const t = e.trim();
			const [n = "", ...r] = t.split(":");
			const i = Object.hasOwn(VERBS, n) ? VERBS[n] : void 0;
			if (i) o.push({
				apply: i,
				args: r
			});
			else s = t;
		}
		if (a === null || a === void 0 || a === "") return s ?? "";
		for (const e of o) a = e.apply(a, e.args, n);
		return String(a);
	});
}
function renderSegment(e, t, n) {
	if ("when" in e) {
		const n = getPath(t, String(e.when));
		if (n === null || n === void 0 || n === false || n === "") return null;
	}
	if ("map" in e) {
		const n = getPath(t, String(e.map));
		const r = String(n);
		const i = isRecord(e.cases) ? e.cases : {};
		const a = Object.hasOwn(i, r) ? i[r] : i["_default"];
		return typeof a === "string" ? a : null;
	}
	if ("each" in e) {
		const r = getPath(t, String(e.each));
		const i = Array.isArray(r) ? r : [];
		const a = typeof e.item === "string" ? e.item : "";
		const o = Array.isArray(e.item_scales) ? e.item_scales : void 0;
		const s = i.map((e, t) => interp(a, e, o?.length ? {
			...n,
			"*": n[expectDefined(o[Math.min(t, o.length - 1)], "names entry at math.min(i, names.length 1)")]
		} : n)).filter(Boolean);
		const c = typeof e.join === "string" ? e.join : " ";
		const l = s.join(c);
		if (!l) return null;
		const u = typeof e.text === "string" ? e.text : "";
		return u ? `${u} ${l}` : l;
	}
	if ("text" in e) return interp(String(e.text), t, n) || null;
	return null;
}
function resolveLayout(e, t) {
	const n = e.output;
	if (isRecord(n)) {
		const e = isRecord(n.surfaces) ? n.surfaces : {};
		let r = typeof t === "string" ? e[t] : void 0;
		if (r === void 0) r = n.default;
		return {
			sep: typeof n.sep === "string" ? n.sep : "",
			pieces: Array.isArray(r) ? r : []
		};
	}
	const r = typeof t === "string" && isRecord(e.surfaces) && isRecord(e.surfaces[t]) ? e.surfaces[t] : {};
	return {
		sep: typeof r.sep === "string" ? r.sep : typeof e.sep === "string" ? e.sep : " ",
		pieces: Array.isArray(r.segments) ? r.segments : Array.isArray(e.segments) ? e.segments : []
	};
}
function renderUsageBar(e, t) {
	try {
		const { sep: n, pieces: r } = resolveLayout(e, t.surface);
		const i = {
			...isRecord(e.ramps) ? e.ramps : {},
			...isRecord(e.series) ? e.series : {},
			...isRecord(e.scales) ? e.scales : {}
		};
		i["_aliases"] = isRecord(e.aliases) ? e.aliases : {};
		return r.filter(isRecord).map((e) => renderSegment(e, t, i)).filter(Boolean).join(n);
	} catch {
		return "";
	}
}
//#endregion
//#region src/auto-reply/reply/agent-runner-usage-line.ts
function projectUsage(e) {
	const t = (e.cacheRead ?? 0) + (e.cacheWrite ?? 0) + (e.input ?? 0);
	return {
		promptTotal: t,
		tokens: {
			input_tokens: e.input,
			output_tokens: e.output,
			cache_read_tokens: e.cacheRead,
			cache_write_tokens: e.cacheWrite,
			total_tokens: e.total,
			cache_hit_pct: t > 0 ? Math.round((e.cacheRead ?? 0) / t * 100) : void 0
		}
	};
}
function buildUsageContract(e, t) {
	const n = e.usage ?? {};
	const { input: r, output: i, cacheRead: a, cacheWrite: o, total: s } = n;
	const c = r !== void 0 || i !== void 0;
	const l = !c && s !== void 0;
	const u = c || a !== void 0 || o !== void 0 || s !== void 0;
	const { promptTotal: d, tokens: f } = projectUsage(n);
	const p = e.lastUsage;
	const m = e.contextTokenBudget;
	const h = e.contextUsedTokens !== void 0 && e.contextUsedTokens > 0 ? e.contextUsedTokens : d > 0 ? d : void 0;
	const g = m && h !== void 0 ? Math.round(h / m * 100) : void 0;
	const _ = e.overrideSource ?? null;
	const v = e.overrideSource !== void 0 && e.overrideSource !== "" && e.overrideSource !== "auto";
	return {
		schema: "openclaw.usageLine.v1",
		surface: t ?? null,
		agentId: e.agentId ?? null,
		chat_type: e.chatType ?? null,
		model: {
			id: e.model ?? null,
			display_name: e.model ?? null,
			provider: e.provider ?? null,
			reasoning: e.reasoningEffort ?? null,
			actual: e.resolvedRef ?? null,
			resolved_ref: e.resolvedRef ?? null,
			requested: e.requested ?? null,
			is_fallback: e.fallbackUsed === true,
			is_override: v,
			override_source: _,
			auth_mode: e.authMode ?? null
		},
		state: {
			fast_mode: e.fastMode ?? null,
			compactions: e.compactionCount ?? null
		},
		usage: {
			...f,
			has_tokens: u,
			has_split_tokens: c,
			has_total_only_tokens: l,
			last: p ? projectUsage(p).tokens : void 0
		},
		context: {
			used_tokens: h,
			max_tokens: m,
			pct_used: g
		},
		cost: {
			turn_usd: e.turnUsd ?? null,
			available: e.turnUsd !== void 0
		},
		timing: { duration_ms: e.durationMs ?? null },
		identity: {
			name: e.identity?.name ?? null,
			emoji: e.identity?.emoji ?? null,
			avatar: e.identity?.avatar ?? null
		},
		session: { id: e.sessionId ?? null }
	};
}
const formatResponseUsageLine = (e) => {
	const t = e.usage;
	if (!t) return null;
	const n = t.input;
	const r = t.output;
	const i = n !== void 0 || r !== void 0;
	const a = n !== void 0 ? formatTokenCount(n) : "?";
	const o = r !== void 0 ? formatTokenCount(r) : "?";
	const s = !i && t.total !== void 0 ? `${formatTokenCount(t.total)} total` : void 0;
	const c = t.cacheRead;
	const l = t.cacheWrite;
	const u = t.cost !== void 0 || n !== void 0 && r !== void 0;
	const d = e.showCost && u ? estimateAggregateUsageCost(e) : void 0;
	const f = e.showCost ? formatUsd(d) : void 0;
	const p = (c ?? 0) > 0 || (l ?? 0) > 0 ? ` · cache ${formatTokenCount(c ?? 0)} cached / ${formatTokenCount(l ?? 0)} new` : "";
	if (!i && !s && !p && !f) return null;
	const m = f ? ` · est ${f}` : "";
	return `Usage: ${s ?? `${a} in / ${o} out`}${p}${m}`;
};
const resolveResponseUsageLine = (e) => {
	const t = resolveEffectiveResponseUsage(e.sessionRaw, e.config.messages?.responseUsage, e.channel);
	const n = t === "full";
	const r = n ? hasBillableUsage(e.usage) : hasNonzeroUsage(e.usage);
	if (t === "off" || !r || e.preserveUserFacingSessionState === true) return;
	const i = formatResponseUsageLine({
		usage: e.usage,
		showCost: n,
		provider: e.provider,
		model: e.model,
		config: e.config,
		agentDir: e.agentDir,
		allowPluginNormalization: false
	});
	const a = t === "full" && e.replyUsageState ? loadUsageBarTemplate(e.config.messages?.usageTemplate) : void 0;
	return (a && e.replyUsageState ? renderUsageBar(a, buildUsageContract(e.replyUsageState, e.channel)) : void 0) || i || void 0;
};
const appendUsageLine = (e, t, n) => {
	const r = n?.completedSourceReply ? e.findLastIndex((e) => {
		const t = getReplyPayloadMetadata(e);
		return Boolean(e?.text) && Boolean(t?.sourceReplyTranscriptMirror) && t?.deliverDespiteSourceReplySuppression === true;
	}) : -1;
	if (n?.completedSourceReply && r === -1) {
		const n = markReplyPayloadForSourceSuppressionDelivery({
			text: t,
			isStatusNotice: true
		});
		setReplyPayloadMetadata(n, { responseUsageLine: t });
		return [...e, n];
	}
	const i = r >= 0 ? r : e.findLastIndex((e) => e?.text);
	if (i === -1) return [...e, {
		text: t,
		isStatusNotice: true
	}];
	const a = expectDefined(e[i], "payloads entry at index");
	const o = a.text ?? "";
	const s = o.endsWith("\n") ? "" : "\n";
	const c = copyReplyPayloadMetadata(a, {
		...a,
		text: `${o}${s}${t}`
	});
	setReplyPayloadMetadata(c, { responseUsageLine: t });
	const l = getReplyPayloadMetadata(a)?.sourceReplyTranscriptMirror;
	if (l) setReplyPayloadMetadata(c, { sourceReplyTranscriptMirror: {
		...l,
		text: c.text
	} });
	const u = e.slice();
	u[i] = c;
	return u;
};
//#endregion
//#region src/auto-reply/reply/automation-reply-payloads.ts
/** Shared terminal facts keep foreground and queued automation delivery in agreement. */
function resolveAutomationReplyState(e, t = {}) {
	const { opts: n, terminalFailurePayload: r = e.terminalFailurePayload } = t;
	const i = e.result;
	const a = i.meta?.error?.kind === "hook_block" || i.didSendDeterministicApprovalPrompt === true;
	const o = e.status === "ok" && !a && !i.meta?.error && i.meta?.aborted !== true && !r;
	const s = o && i.meta?.terminalReply?.disposition === "silent";
	const c = hasPendingAutomationContinuation(i.meta);
	const l = o && !c && e.automation?.result?.outcome === "no_change";
	return {
		blocked: a,
		successfulTerminal: o,
		authoredSilence: s,
		pendingContinuation: c,
		automationNoChange: l,
		reasoningPayloadsEnabled: e.automation ? e.automation.includeReasoning && o && !c && !s && !l : n?.reasoningPayloadsEnabled === true
	};
}
/** Reasoning can accompany an automation's deliverable result, never replace it. */
function retainAutomationReasoningWithFinal(e) {
	return !e.some((e) => e.isError) && e.some((e) => isReplyPayloadTerminalContent(e) && !isHostNoticePayload(e) && hasOutboundReplyContent(e)) ? e : e.filter((e) => e.isReasoning !== true);
}
//#endregion
//#region src/gateway/mcp-app-channel-action.ts
/** Mint one short-lived launch action only after the final reply route is known. */
function materializeMcpAppChannelPresentation(e) {
	const t = getTailscalePublishedOrigin();
	if (!t) return;
	const n = peekSessionMcpRuntime({ sessionKey: e.sessionKey });
	if (!n || n.mcpAppsEnabled !== true) return;
	const r = Date.now();
	const i = getMcpAppViewLease(e.view.viewId, n);
	if (!i || i.expiresAtMs <= r) return;
	const a = createMcpAppStandaloneTicket({
		sessionKey: e.sessionKey,
		view: i,
		toolOperationsAuthorized: true,
		nowMs: r
	});
	if (!a) return;
	return { blocks: [{
		type: "buttons",
		buttons: [{
			label: "Open app",
			action: {
				type: "web-app",
				url: new URL(a.url, t.origin).href
			}
		}]
	}] };
}
//#endregion
//#region src/auto-reply/reply/mcp-channel-actions.ts
function attachChannelPresentation(e, t) {
	const n = e.findLastIndex((e) => Boolean(e.text?.trim()) && e.isError !== true && isReplyPayloadTerminalContent(e));
	if (n < 0) return e;
	const r = t();
	if (!r) return e;
	const i = e.slice();
	const a = e[n];
	i[n] = copyReplyPayloadMetadata(a, {
		...a,
		presentation: a.presentation ? {
			...a.presentation,
			blocks: [...a.presentation.blocks, ...r.blocks]
		} : r
	});
	return i;
}
function attachMcpAppChannelAction(e) {
	const { channel: t, sessionKey: n, view: r } = e;
	if (!t || t === "webchat" || !n || !r) return e.payloads;
	return attachChannelPresentation(e.payloads, () => materializeMcpAppChannelPresentation({
		sessionKey: n,
		view: r
	}));
}
function attachMcpConnectChannelAction(e) {
	const { action: t } = e;
	if (!t) return e.payloads;
	return attachChannelPresentation(e.payloads, () => ({ blocks: [{
		type: "buttons",
		buttons: [{
			label: `Connect ${t.serverName}`,
			action: {
				type: "url",
				url: t.authorizationUrl
			}
		}]
	}] }));
}
//#endregion
//#region src/auto-reply/reply/stranded-reply-recovery.ts
const STRANDED_REPLY_RETRY_MARKER = "stranded-reply-retry";
/** Resolve the one allowed recovery action for a final that missed source delivery. */
function resolveStrandedReplyRecovery(e) {
	if (!isStrandedPrivateMessageToolFinal({
		...e,
		replyExpectation: resolveReplyExpectation({
			...e.base.run,
			scheduledAutomation: e.base.run.scheduledAutomation !== void 0
		})
	}) || e.payloads.some((e) => (isReplyPayloadTerminalContent(e) || e.isError === true) && getReplyPayloadMetadata(e)?.deliverDespiteSourceReplySuppression === true)) return { kind: "none" };
	if (e.base.strandedReplyRetry === true) return {
		kind: "diagnostic",
		payload: createMissingReplyNotice()
	};
	return {
		kind: "retry",
		run: {
			...e.base,
			prompt: buildStrandedReplyRetryPrompt(e.finalText),
			summaryLine: STRANDED_REPLY_RETRY_MARKER,
			strandedReplyRetry: true,
			disableCollectBatching: true,
			toolsAllow: isRuntimeToolAllowed("message", e.base.toolsAllow) ? ["message"] : [],
			transcriptPrompt: void 0,
			userTurnTranscriptRecorder: void 0,
			currentInboundContext: void 0,
			turnAdoptionLifecycle: void 0,
			replyOperationRunStates: void 0,
			run: {
				...e.base.run,
				sourceReplyDeliveryMode: e.sourceReplyDeliveryMode,
				suppressNextUserMessagePersistence: true,
				skillLibraryAuthoring: expireSkillLibraryAuthoring(e.base.run.skillLibraryAuthoring, "Skill authoring is unavailable while retrying an undelivered reply. Send a fresh message requesting the change.")
			}
		}
	};
}
function buildStrandedReplyRetryPrompt(e) {
	return formatSystemTurnPrompt(`Your previous reply was not delivered because you did not call message(action=send). Your reply text was: "${e}". If the user should see a reply, send it now with message(action=send). If no reply is needed, answer exactly NO_REPLY.`);
}
//#endregion
//#region src/auto-reply/reply/waiting-status.ts
function buildWaitingStatusPayload(e) {
	const t = e.yieldAcknowledgment?.trim() || (e.mediaContinuation ? "I’m continuing this work and will send the result when it is ready." : void 0);
	if (!isRequiredReplyExpectation(e.completion.expectation) || e.completion.outcome !== "pending" || !e.yielded && !e.continuationPending || e.hasVisibleMessageDelivery || !t) return;
	return setReplyPayloadMetadata({ text: t }, {
		deliverDespiteSourceReplySuppression: true,
		continuationStatus: true
	});
}
/**
* Ordinary and queued waiting replies offer their progress draft to the work
* that owes the result: the yielding turn's children, or its in-flight media runs.
*/
async function attachWaitingStatusProgressContinuation(e) {
	const { acceptedSessionSpawns: t, mediaRequester: n, operation: r } = e;
	let adoptDraft;
	if (n) adoptDraft = (e) => adoptMediaGenerationProgressDraft(n.sessionKey, n.agentId, e);
	else if (t?.length) {
		const { adoptSubagentProgressDraft: e } = await import("./subagent-progress-draft-3TRTLcel.mjs");
		adoptDraft = (n) => e(t, n);
	} else return;
	let i = true;
	setReplyPayloadMetadata(e.payload, { progressContinuation: {
		adopt: (e) => i && resolveReplyOperationAbortReason(r) === void 0 && adoptDraft(e),
		close: () => {
			i = false;
		}
	} });
}
async function prepareWaitingStatusContinuation(e) {
	const { context: t, payload: n, owner: r } = e;
	const { execution: i, followupRun: a, opts: o, replyOperation: s, runId: c, runtimePolicySessionKey: l, sessionKey: u } = t;
	const d = i.result.acceptedSessionSpawns;
	const f = i.result.meta?.continuationPending === true && !r ? l ?? u ?? a.run.sessionKey : void 0;
	if (n) await attachWaitingStatusProgressContinuation({
		payload: n,
		acceptedSessionSpawns: d,
		mediaRequester: f ? {
			sessionKey: f,
			agentId: a.run.agentId
		} : void 0,
		operation: s
	});
	if (!r) return;
	const p = u ?? a.run.sessionKey;
	if (!p || !d?.length) throw new Error("accepted continuation status could not be prepared for delivery");
	const { stateContext: m, operationKey: h, operationSessionId: g } = r;
	const assertRequesterCurrent = () => {
		assertSubagentRegistryWriteSourceCurrent(m);
		if (!isCurrentSessionControllerOperation(s) || s.key !== h || s.sessionId !== g) throw new Error("Requester continuation lost its original reply operation");
	};
	assertRequesterCurrent();
	let _;
	o?.onPendingContinuation?.({ settle: (e) => _ ??= (async () => {
		try {
			assertRequesterCurrent();
			const { settleRequesterAfterSessionSpawns: t } = await import("./subagent-registry-DxTolEfW.mjs");
			assertRequesterCurrent();
			if (!await t({
				requesterSessionKey: p,
				requesterAgentId: a.run.agentId,
				requesterTurnRunId: c,
				acceptedSessionSpawns: d,
				requesterYielded: e && resolveReplyOperationAbortReason(s) === void 0,
				stateContext: m,
				assertCurrent: assertRequesterCurrent
			})) throw new Error("accepted continuation children could not transfer terminal delivery");
			try {
				assertRequesterCurrent();
			} catch (e) {
				throw new SubagentRegistryWriteError("committed", e, "published");
			}
		} finally {
			if (n) getReplyPayloadMetadata(n)?.progressContinuation?.close();
		}
	})().catch((e) => {
		if (!(e instanceof SubagentRegistryWriteError) || e.outcome === "not-committed") _ = void 0;
		throw e;
	}) });
}
//#endregion
//#region src/auto-reply/reply/agent-runner-result-payloads.ts
async function prepareReplyAgentPayloads(e) {
	const { context: t, accounting: n } = e;
	const { activeSessionStore: r, blockReplyPipeline: i, blockStreamingEnabled: a, cfg: o, followupRun: s, opts: c, replyMediaContext: l, replyOperation: u, replyRouteThreadId: d, replyThreadingOverride: f, replyToChannel: p, replyToMode: m, returnWithQueuedFollowupDrain: h, runStartedAt: g, runtimePolicySessionKey: _, sessionCtx: v, sessionKey: y, storePath: b, typingSignals: x } = t;
	const { configuredFallbackModel: S, contextTokensUsed: C, hasDirectlySentBlockReply: w, directBlockDeliveries: T, fallbackAttempts: E, fallbackExhausted: D, fallbackTransition: O, modelUsed: k, payloadArray: A, preserveUserFacingSessionState: j, promptTokens: M, providerUsed: N, replyUsageState: P, runId: F, runResult: I, selectedModel: L, selectedProvider: ee, sessionModel: R, terminalFailurePayload: z, usage: B } = n;
	let { activeSessionEntry: V } = n;
	const te = s.run.terminalReplyExpectation ?? resolveSourceReplyExpectation({
		ctx: {
			...v,
			InboundEventKind: s.currentInboundEventKind,
			InputProvenance: s.run.inputProvenance
		},
		cfg: o,
		scheduledAutomation: s.run.scheduledAutomation !== void 0
	});
	const H = shouldDeliverMissingReplyNotice({
		...s.run,
		scheduledAutomation: s.run.scheduledAutomation !== void 0,
		config: o,
		terminalReplyExpectation: te,
		trigger: resolveReplyRunTrigger(t),
		currentInboundEventKind: s.currentInboundEventKind
	});
	const U = !H && (!I.meta?.error || I.meta.error.kind === "incomplete_turn" && I.meta.error.message.startsWith("No answer was returned. Ask again if you still need one."));
	const W = resolveReplyOperationRunState(c);
	const { blocked: ne, successfulTerminal: G, authoredSilence: K, pendingContinuation: re, automationNoChange: ie, reasoningPayloadsEnabled: ae } = resolveAutomationReplyState(t.execution, { opts: c });
	const oe = G && I.meta?.terminalReply?.disposition === "empty" && I.meta.terminalReply.code === "message-tool-not-called" && s.strandedReplyRetry !== true;
	const q = I.meta?.continuationPending === true;
	const se = q && hasCompletionMessageSessionSpawn(I.acceptedSessionSpawns) ? {
		stateContext: captureOpenClawStateWorkerContext(),
		operationKey: u.key,
		operationSessionId: u.sessionId
	} : void 0;
	if (re && !q) c?.onPendingContinuation?.();
	const ce = hasSuccessfulSourceReplyDelivery({
		blockReplyPipeline: i,
		hasDirectlySentBlockReply: w,
		messagingToolSentTexts: I.messagingToolSentTexts,
		messagingToolSentMediaUrls: I.messagingToolSentMediaUrls,
		messagingToolSentTargets: I.messagingToolSentTargets
	});
	const le = hasCommittedSourceReplyDeliveryEvidence(I);
	const ue = hasCompletedSourceReplyDeliveryEvidence(I);
	const de = I.sourceReplyDeliveryState === void 0 && (resolveExplicitFinalSourceReplyDeliveryEvidence(I) === void 0 || G && !re && s.run.sourceReplyDeliveryMode !== "message_tool_only");
	const J = hasVisibleOutboundDeliveryEvidence(I);
	const Y = ce || le || J || I.didSendDeterministicApprovalPrompt === true;
	const X = await resolveTerminalReplyDelivery({
		blockReplyPipeline: i,
		directBlockDeliveries: T,
		resolveReplyDelivery: c?.resolveReplyDelivery,
		sourceReplyDeliveryState: I.sourceReplyDeliveryState
	});
	const fe = resolveSourceReplyDelivery(I, X);
	let Z = resolveReplyCompletion(resolveClaimedReplyExpectation(te, I.meta), ne ? "blocked" : K ? "silent" : fe !== "missing" ? fe : ie ? "silent" : re ? "pending" : "empty");
	const pe = Z.outcome === "silent";
	if (W) W.replyCompletion = Z;
	const me = de ? () => {
		if (Z.outcome !== "blocked") {
			Z = resolveReplyCompletion(te, "delivered");
			if (W) W.replyCompletion = Z;
		}
	} : void 0;
	const he = Boolean(z && Z.outcome !== "delivered" && Z.outcome !== "pending" && Z.outcome !== "blocked");
	const ge = E.length > 0 || S.persistedAutoFallback;
	const _e = O.fallbackActive && ge;
	const Q = t.execution.status === "failed" ? void 0 : buildWaitingStatusPayload({
		completion: Z,
		yielded: I.meta?.yielded === true,
		continuationPending: q,
		mediaContinuation: q && !se,
		yieldAcknowledgment: I.meta?.yieldAcknowledgment,
		hasVisibleMessageDelivery: ce || le || I.didSendDeterministicApprovalPrompt === true
	});
	const ve = oe || z || !H || Z.outcome !== "missing" ? void 0 : createMissingReplyNotice();
	const buildStrandedRetryMissingDeliveryDiagnostic = () => {
		if (!H || K || ie || !y || !b || s.strandedReplyRetry !== true || v.InboundEventKind === "room_event" || ue) return;
		const e = resolveSourceReplyPolicy({
			cfg: o,
			sessionCtx: v,
			sessionEntry: V,
			sessionKey: y,
			runtimePolicySessionKey: _,
			opts: c
		});
		const t = resolveStrandedReplyRecovery({
			base: s,
			payloads: [],
			finalText: "",
			terminalReply: I.meta?.terminalReply,
			sourceReplyDeliveryMode: e.sourceReplyDeliveryMode,
			sendPolicyDenied: e.sendPolicyDenied,
			successfulSourceReplyDelivery: ue,
			isRoomEvent: false
		});
		return t.kind === "diagnostic" ? t.payload : void 0;
	};
	if (fe === "delivered") await c?.onObservedReplyDelivery?.();
	const ye = v.MessageSidFull ?? v.MessageSid;
	const be = createReplyToModeFilterForChannel(m, p);
	const isGeneratedToolWarning = (e) => getReplyPayloadMetadata(e)?.toolErrorWarning !== void 0;
	const isPayloadLaneEnabled = (e) => (e.isReasoning !== true || ae) && (e.isCommentary !== true || c?.commentaryPayloadsEnabled === true);
	const applyFinalReplyToMode = (e) => {
		const t = isPayloadLaneEnabled(e);
		const n = normalizeReplyPayload(e, { applyChannelTransforms: false }) === null;
		const r = Q && isGeneratedToolWarning(e);
		return !t || n || r ? e : be(e);
	};
	const buildFinalPayloads = async (e) => {
		return (await buildReplyPayloads({
			config: o,
			payloads: e,
			conversationContext: v.agentText ?? v.BodyForAgent,
			silentExpected: s.run.silentExpected,
			blockStreamingEnabled: a,
			blockReplyPipeline: i,
			directBlockDeliveries: T,
			replyToMode: m,
			replyToChannel: p,
			currentMessageId: ye,
			replyThreading: f ?? v.ReplyThreading,
			applyReplyToMode: applyFinalReplyToMode,
			messageProvider: s.run.messageProvider,
			messagingToolSentTexts: I.messagingToolSentTexts,
			messagingToolSentMediaUrls: I.messagingToolSentMediaUrls,
			messagingToolSentTargets: I.messagingToolSentTargets,
			onDeliveredTerminalDuplicate: me,
			originatingChannel: v.OriginatingChannel,
			originatingChatType: v.ChatType,
			originatingTo: v.OriginatingTo ?? v.To,
			originatingThreadId: d,
			accountId: v.AccountId,
			normalizeMediaPaths: l.normalizePayload
		})).replyPayloads;
	};
	const returnSilentFallbackFailureIfNeeded = async () => {
		if (U) return;
		const e = buildSilentFallbackFailurePayload({
			fallbackTransition: O,
			fallbackFailureKnown: ge,
			fallbackAttempts: E,
			cfg: o,
			completion: Z
		});
		if (!e) return;
		if (!u.result) {
			u.fail("run_failed", /* @__PURE__ */ new Error(`configured model backend ${O.selectedModelRef} failed and fallback ${O.activeModelRef} produced no visible reply`));
			c?.onAgentRunTerminalOutcome?.("failed");
		}
		const [t] = await buildFinalPayloads([e]);
		if (!t) return;
		await signalTypingIfNeeded([t], x);
		return h(t);
	};
	const recordMissingReply = () => {
		if (Z.outcome === "missing" && !u.result) {
			u.fail("run_failed", new Error(MISSING_REPLY_NOTICE_TEXT));
			recordReplyOperationAgentTurn(s.replyOperationRunStates, u, {
				kind: "settled",
				status: "failed",
				result: I
			});
			c?.onAgentRunTerminalOutcome?.("failed");
		}
	};
	const xe = Z.outcome === "pending" && !Q;
	if (pe || xe) await prepareWaitingStatusContinuation({
		context: t,
		owner: se
	});
	const finishEmptyReply = async () => {
		recordMissingReply();
		if (Z.outcome === "silent" || Z.outcome === "blocked") c?.onDeliberateSilentTerminalReply?.();
		return {
			kind: "return",
			value: await returnSilentFallbackFailureIfNeeded() ?? h(buildStrandedRetryMissingDeliveryDiagnostic())
		};
	};
	const Se = I.meta?.executionTrace?.providerPolicyRetry;
	const Ce = s.currentInboundEventKind !== "room_event" && !isSyntheticSourceReplyTurn({
		inputProvenance: s.run.inputProvenance,
		scheduledAutomation: s.run.scheduledAutomation !== void 0
	}) && t.execution.status === "ok" && I.meta?.aborted !== true && Se?.category === "cyber" ? Se : void 0;
	const we = Ce !== void 0;
	const Te = !D && !j && (O.fallbackTransitioned || O.fallbackCleared);
	const Ee = Te && !we ? normalizeChatType(v.ChatType) : void 0;
	const De = Ee !== "group" && Ee !== "channel";
	let Oe = Ce ? buildProviderPolicyRetryNotice({
		provider: Ce.provider,
		model: Ce.model,
		cfg: o
	}) : null;
	const ke = {
		selectedProvider: ee,
		selectedModel: L,
		activeProvider: R.provider,
		activeModel: R.model
	};
	if (Te && O.fallbackTransitioned) {
		emitAgentEvent({
			runId: F,
			sessionKey: y,
			stream: "lifecycle",
			data: {
				phase: "fallback",
				...ke,
				reasonSummary: O.reasonSummary,
				attemptSummaries: O.attemptSummaries,
				attempts: E
			}
		});
		if (De && !we) Oe = buildFallbackNotice({
			...ke,
			attempts: E,
			cfg: o
		});
	}
	if (Te && O.fallbackCleared) {
		emitAgentEvent({
			runId: F,
			sessionKey: y,
			stream: "lifecycle",
			data: {
				phase: "fallback_cleared",
				...ke,
				previousActiveModel: O.previousState.activeModel
			}
		});
		if (De && !we) Oe = buildFallbackClearedNotice({
			selectedProvider: ee,
			selectedModel: L,
			previousActiveModel: O.previousState.activeModel
		});
	}
	const Ae = Oe ? [setReplyPayloadMetadata(markReplyPayloadForSourceSuppressionDelivery({
		text: Oe,
		isFallbackNotice: true
	}), !we && I.meta.modelFallbackTranscriptToModel === O.activeModelRef ? { modelFallbackNotice: true } : {})] : [];
	const je = I.meta?.agentMeta?.diagnosticUsage ?? B;
	if (isDiagnosticsEnabled(o) && hasBillableUsage(je)) {
		const e = deriveContextPromptTokens({
			lastCallUsage: I.meta?.agentMeta?.lastCallUsage,
			promptTokens: M,
			usage: B
		});
		const t = estimateAggregateUsageCost({
			usage: je,
			provider: N,
			model: k,
			config: o,
			agentDir: s.run.agentDir
		});
		emitTrustedDiagnosticEvent({
			type: "model.usage",
			...I.diagnosticTrace ? { trace: freezeDiagnosticTraceContext(createChildDiagnosticTraceContext(I.diagnosticTrace)) } : {},
			sessionKey: y,
			sessionId: s.run.sessionId,
			channel: p,
			agentId: s.run.agentId,
			provider: N,
			model: k,
			usage: toDiagnosticUsage(je),
			lastCallUsage: I.meta?.agentMeta?.lastCallUsage,
			context: {
				limit: C,
				...e !== void 0 ? { used: e } : {}
			},
			costUsd: t,
			durationMs: Date.now() - g
		});
	}
	if (c?.onRawLlmResponse) {
		const e = resolveDiagnosticModelResponse(I);
		if (e !== void 0) c.onRawLlmResponse(e);
	}
	const Me = K || ie;
	const Ne = selectAutomationReplyPayloads(A, ie, Me);
	if (Me && Ne.length === 0 || !oe && Z.outcome !== "delivered" && A.length === 0 && Ae.length === 0 && !he && !Q && (!ve || _e)) return finishEmptyReply();
	let $ = await buildFinalPayloads((!Me && Ae.length > 0 ? [...Ae, ...Ne] : Ne).filter(isPayloadLaneEnabled));
	if (t.execution.automation) $ = retainAutomationReasoningWithFinal($);
	if (fe !== "delivered" && Z.outcome === "delivered") await c?.onObservedReplyDelivery?.();
	const Pe = Q ? $.filter((e) => !isGeneratedToolWarning(e)) : $;
	const Fe = Z.outcome === "delivered" || Pe.some((e) => isReplyPayloadTerminalContent(e) && (!he && !Q || s.run.sourceReplyDeliveryMode !== "message_tool_only" || getReplyPayloadMetadata(e)?.deliverDespiteSourceReplySuppression === true) && normalizeReplyPayload(e, { applyChannelTransforms: false }) !== null);
	if (Q && Fe) $ = Pe;
	if (!Fe && !Q && !oe) recordMissingReply();
	if (he && !Fe && z) $ = [...$, ...await buildFinalPayloads([z])];
	else if (Q && !Fe) {
		const e = await buildFinalPayloads([Q]);
		$ = e.length > 0 ? [...Pe, ...e] : $.map((e) => isGeneratedToolWarning(e) ? applyFinalReplyToMode(e) : e);
	} else if (_e && !Fe) {
		const e = await returnSilentFallbackFailureIfNeeded();
		if (e) return {
			kind: "return",
			value: e
		};
	} else if (ve && !Fe) {
		const e = await buildFinalPayloads([buildStrandedRetryMissingDeliveryDiagnostic() ?? ve]);
		$ = [...$, ...e];
	}
	$ = attachMcpAppChannelAction({
		payloads: $,
		channel: p,
		sessionKey: y,
		view: I.latestMcpAppChannelView
	});
	$ = attachMcpConnectChannelAction({
		payloads: $,
		action: I.latestMcpConnectAction
	});
	const Ie = $.some((e) => e.isError || !isReplyPayloadStatusNotice(e) && isPayloadLaneEnabled(e) && normalizeReplyPayload(e, { applyChannelTransforms: false }) !== null);
	const Le = Boolean(i?.didStream()) || Y;
	if (!oe && Z.outcome !== "delivered" && ($.length === 0 || !Ie && !Le)) return finishEmptyReply();
	const Re = I.successfulCronAdds ?? 0;
	const ze = $.some((e) => !e.isError && !isReplyPayloadStatusNotice(e) && typeof e.text === "string" && hasUnbackedReminderCommitment(e.text));
	const Be = ze && Re === 0 ? await hasSessionRelatedCronJobs(y) : false;
	const Ve = ze && Re === 0 && !Be ? appendUnscheduledReminderNote($) : $;
	const He = Ve.find((e) => getReplyPayloadMetadata(e)?.continuationStatus === true);
	if (!pe && !xe) await prepareWaitingStatusContinuation({
		context: t,
		owner: se,
		payload: He
	});
	await signalTypingIfNeeded(Ve, x);
	const Ue = V?.responseUsage ?? (y ? r?.[y]?.responseUsage : void 0);
	const We = resolveResponseUsageLine({
		config: o,
		agentDir: s.run.agentDir,
		sessionRaw: Ue,
		channel: p,
		usage: B,
		provider: N,
		model: k,
		preserveUserFacingSessionState: j,
		replyUsageState: P
	});
	if (s.run.verboseLevelOverride !== "off" || s.run.traceAuthorized === true) V = t.completion ? await t.completion.refresh() : await refreshSessionEntryFromStore({
		storePath: b,
		sessionKey: y,
		fallbackEntry: V,
		activeSessionStore: r,
		expectedGeneration: n.expectedSession,
		reader: getReplyOperationSessionReader(u)
	});
	return {
		kind: "continue",
		activeSessionEntry: V,
		replyCompletion: Z,
		completedSourceReplyDelivery: ue,
		reminderNoteAppended: Ve !== $,
		guardedReplyPayloads: Ve,
		responseUsageLine: We
	};
}
//#endregion
//#region src/auto-reply/reply/goal-continuation.ts
/** Selects supported Codex placement facts; execution still acquires a fresh turn claim. */
async function resolveCodexGoalPlacement(e) {
	const t = getRegisteredAgentHarness("codex")?.harness;
	if (!t) return;
	const n = await (getInProcessGatewayRequestContext()?.workerSessionPlacementService)?.prepareSessionPlacement?.(e.sessionId);
	if (!n) return e.requiresWorker ? void 0 : "local";
	try {
		const r = n.prepareRead();
		if (r) await r;
		const i = n.current();
		if (!i) return e.requiresWorker ? void 0 : "local";
		if (i.agentId !== e.agentId || i.sessionKey !== e.sessionKey || i.sessionId !== e.sessionId) return;
		if (i.state === "local") return e.requiresWorker ? void 0 : "local";
		return i.executionMode === "remote-exec" && t.cloudPlacement?.mode === "remote-exec" ? "worker" : void 0;
	} finally {
		n.release();
	}
}
function isGoalContinuationCurrent(e, t) {
	const n = t && accountSessionGoalUsage(t, Date.now());
	return Boolean(t && n?.id === e.goalId && n.status === "active" && !t.abortedLastRun && (t.agentHarnessId === void 0 || t.agentHarnessId === "openclaw" || t.agentHarnessId === "codex" && (e.workerGoal === true || e.localCodexGoal === true)));
}
/** Revalidates Codex placement at admission; built-in runs have no placement marker. */
async function isGoalContinuationPlacementCurrent(e) {
	const { continuation: t } = e;
	if (!t.workerGoal && !t.localCodexGoal) return true;
	if (t.workerGoal && !e.hasOperatorAuthority) return false;
	if (t.localCodexGoal && e.requiresWorker) return false;
	const n = await resolveCodexGoalPlacement({
		agentId: e.agentId,
		sessionKey: e.sessionKey,
		sessionId: t.sessionId,
		requiresWorker: t.workerGoal === true
	});
	return t.workerGoal ? n === "worker" : n === "local";
}
function isGoalContinuationOutcome(e) {
	const t = e.meta;
	return (t.stopReason === "end_turn" || t.stopReason === "stop") && !t.aborted && !t.error && !t.timeoutPhase && !t.yielded && !t.continuationPending && !t.pendingToolCalls?.length && !hasCompletionMessageSessionSpawn(e.acceptedSessionSpawns) && !e.didSendDeterministicApprovalPrompt && !e.payloads?.some((e) => e.isError);
}
async function enqueueGoalContinuation(e) {
	const eligible = () => e.isCurrent?.() !== false && !e.controllerInput?.abortSignal.aborted && !e.operation.abortSignal.aborted && e.operation.result?.kind !== "failed" && e.operation.result?.kind !== "aborted" && !isFollowupRunAborted(e.base) && getFollowupQueueDepth(e.queueKey) === 0;
	if (!isGoalContinuationOutcome(e.result) || !eligible()) return false;
	const { listUnsettledRequesterChildren: t } = await import("./subagent-registry-DxTolEfW.mjs");
	if ((await t({
		requesterSessionKey: e.sessionKey,
		requesterAgentId: e.base.run.agentId
	})).length > 0 || !eligible()) return false;
	const n = await readSessionEntryReadOnlyInWorker({
		storePath: e.storePath,
		sessionKey: e.sessionKey
	}, void 0, e.reader);
	e.base.operatorAuthority?.assertCurrent();
	if (!eligible() || !n?.goal) return false;
	const r = n.agentHarnessId === "codex" ? await resolveCodexGoalPlacement({
		agentId: e.base.run.agentId,
		sessionKey: e.sessionKey,
		sessionId: e.expectedSession.sessionId,
		requiresWorker: Boolean(e.base.run.config?.cloudWorkers?.requiredProfile)
	}) : void 0;
	if (n.agentHarnessId === "codex" && (!r || r === "worker" && !e.base.operatorAuthority)) return false;
	e.base.operatorAuthority?.assertCurrent();
	if (!eligible()) return false;
	const i = {
		...e.expectedSession,
		goalId: e.initialGoalId ?? n.goal.id,
		...r === "worker" ? { workerGoal: true } : {},
		...r === "local" ? { localCodexGoal: true } : {}
	};
	if (!isGoalContinuationCurrent(i, n)) return false;
	if (e.base.queuedFollowupReplyDisposition?.kind === "drop") return false;
	const a = e.base;
	const o = new AbortController();
	const s = buildTranscriptFollowupRun(a, {
		prompt: "Advance the active goal; keep it active until fully achieved. Use the current goal context, and verify the entire objective before marking it complete.",
		sourceTool: "session_goal_continue",
		expiredSkillAuthoringMessage: "Skill authoring requires a fresh user request after the previous turn settled."
	});
	const c = a.run.internalEventExecution;
	const l = c ? void 0 : a.abortSignal;
	let u = s.run;
	if (c) {
		u = {
			...s.run,
			internalEventExecution: void 0,
			sessionEventOrigin: c.deliver === false ? { deliver: false } : {}
		};
		if (transferCommandOwnerAuthorityToSuccessor(u) === "removed") u.senderIsOwner = false;
	}
	const d = {
		...s,
		run: u,
		...c ? { queuedFollowupReplyDisposition: void 0 } : {},
		goalContinuation: i,
		summaryLine: "goal-continuation",
		messageId: [
			"goal",
			i.sessionId,
			i.goalId,
			e.sourceRunId
		].join(":"),
		abortSignal: l ? AbortSignal.any([l, o.signal]) : o.signal,
		controllerInput: e.controllerInput,
		strandedReplyRetry: void 0,
		stalledTurnRecovery: void 0
	};
	if (e.controllerInput) bindSessionControllerSource(e.controllerInput, d);
	const f = enqueueFollowupRun(e.queueKey, d, e.settings, "message-id", e.runFollowup, false, { storePath: e.storePath });
	if (f) runAfterReplyOperationClear(e.operation, () => {
		if (e.operation.result?.kind !== "completed") o.abort();
	});
	return f;
}
/** The queue owner retains only the return from an admitted built-in chat Goal. */
function createGoalContinuationReturn(e) {
	if (!e) return (e) => e();
	return createGoalContinuationReturnScope({
		base: e.base,
		sessionKey: e.sessionKey,
		storePath: e.storePath,
		expectedSession: {
			sessionId: e.expectedSession.sessionId,
			lifecycleRevision: e.expectedSession.lifecycleRevision
		},
		initialGoalId: e.initialGoalId,
		operation: e.operation,
		context: (e, t, n) => isGoalContinuationCurrent(e, t) ? refreshActiveGoalContext(n, t) : void 0,
		async resume({ continuation: t, base: n, runId: r, result: i, isCurrent: a }) {
			const o = reserveSessionControllerSource(e.queueKey, {
				policy: e.settings,
				target: captureSessionTarget({
					storeScope: e.storePath,
					sessionKey: e.sessionKey,
					agentId: n.run.agentId,
					incarnation: t.sessionId
				}),
				adapter: {
					scope: e.storePath,
					authority: n.operatorAuthority,
					signal: n.abortSignal
				}
			});
			let s = false;
			try {
				s = await enqueueGoalContinuation({
					...e,
					base: n,
					result: i,
					sourceRunId: r,
					expectedSession: t,
					initialGoalId: t.goalId,
					reader: void 0,
					controllerInput: o,
					isCurrent: a
				});
				if (s) scheduleFollowupDrain(e.queueKey, e.runFollowup);
			} finally {
				if (!s) retireSessionControllerInput(o);
			}
		}
	});
}
//#endregion
//#region src/auto-reply/reply/agent-runner-result.ts
async function finalizeReplyAgentRun(e) {
	const t = e.activeSessionEntry?.goal?.id;
	const { result: n, accounting: r } = await withAgentTurnCompletion({
		agentId: e.followupRun.run.agentId,
		storePath: e.storePath,
		sessionKey: e.sessionKey,
		entry: e.activeSessionEntry,
		writer: e.execution.sessionWriter,
		operation: e.replyOperation,
		activitySummaryCompletion: e.activitySummaryCompletion,
		publish(t) {
			e.activeSessionEntry = t;
			if (e.activeSessionStore && e.sessionKey) e.activeSessionStore[e.sessionKey] = t;
		}
	}, async (t) => {
		const n = {
			...e,
			completion: t
		};
		const r = await accountAgentTurn(n);
		const i = await prepareReplyAgentPayloads({
			context: n,
			accounting: r
		});
		if (i.kind === "return") {
			const n = await buildReplyDiagnosticsPayload({
				activeSessionEntry: r.activeSessionEntry,
				followupRun: e.followupRun,
				accounting: r,
				cfg: e.cfg,
				storePath: e.storePath,
				userText: e.sessionCtx.commandText || e.sessionCtx.agentText,
				resolvedVerboseLevel: e.resolvedVerboseLevel,
				resolvedBlockStreamingBreak: e.resolvedBlockStreamingBreak,
				preflightCompactionApplied: e.preflightCompactionApplied
			});
			await t?.complete();
			if (!n) return {
				result: i.value,
				accounting: r
			};
			return {
				result: i.value ? [...Array.isArray(i.value) ? i.value : [i.value], n] : n,
				accounting: r
			};
		}
		const { activeIsNewSession: a, activeSessionStore: o, cfg: s, followupRun: c, opts: l, preflightCompactionApplied: u, queueKey: d, resolvedBlockStreamingBreak: f, resolvedQueue: p, resolvedVerboseLevel: m, returnWithQueuedFollowupDrain: h, runFollowupTurn: g, runtimePolicySessionKey: _, sessionCtx: v, sessionKey: y, storePath: b } = n;
		const { autoCompactionCount: x, runResult: S, verboseEnabled: C } = r;
		const { completedSourceReplyDelivery: w, guardedReplyPayloads: T, responseUsageLine: E } = i;
		let { activeSessionEntry: D } = i;
		let O = T;
		const k = [];
		if (C && a) k.push({ text: `🧭 New session: ${c.run.sessionId}` });
		if (x > 0) {
			const e = r.expectedSession.sessionId;
			const t = r.compactionCount;
			const n = y && o ? o[y] : void 0;
			if (n) {
				D = n;
				refreshQueuedFollowupSession({
					key: d,
					previousSessionId: e,
					nextSessionId: n.sessionId,
					nextSessionFile: d
				});
			}
			if (y) {
				const e = await readPostCompactionContext(c.run.workspaceDir, {
					cfg: s,
					agentId: c.run.agentId
				});
				if (e) enqueueSystemEvent(e, withSystemEventOwner({ sessionKey: y }, c.run.agentId));
			}
			if (C) {
				const e = t !== void 0 ? ` (count ${t})` : "";
				k.push(setReplyPayloadMetadata({ text: `🧹 Auto-compaction complete${e}.` }, { hostNotice: true }));
			}
		}
		const A = await buildReplyDiagnosticsPayload({
			activeSessionEntry: D,
			followupRun: c,
			accounting: r,
			cfg: s,
			storePath: b,
			userText: v.commandText || v.agentText,
			resolvedVerboseLevel: m,
			resolvedBlockStreamingBreak: f,
			preflightCompactionApplied: u
		});
		const j = S.meta?.error?.kind === "hook_block";
		const M = j ? void 0 : S.meta?.finalAssistantRawText ?? S.meta?.finalAssistantVisibleText;
		if (k.length > 0) O = [...k, ...O];
		if (A) O = [...O, A];
		const resolveReplyPolicy = (e) => resolveSourceReplyPolicy({
			cfg: s,
			sessionCtx: v,
			sessionEntry: D,
			sessionKey: e,
			runtimePolicySessionKey: _,
			opts: l
		});
		const N = y ? resolveReplyPolicy(y) : void 0;
		if (E) O = appendUsageLine(O, E, { completedSourceReply: N?.sourceReplyDeliveryMode === "message_tool_only" && w && i.replyCompletion.outcome === "delivered" });
		if (j) O = markBeforeAgentRunBlockedPayloads(O);
		const P = c.strandedReplyRetry === true;
		if (y && b && S.meta?.terminalReply?.disposition !== "silent" && i.replyCompletion.outcome !== "silent" && (O.length > 0 || P || S.meta?.terminalReply !== void 0)) {
			const e = N ?? resolveReplyPolicy(y);
			const n = normalizeAssistantFinalDeliveryText(S.meta?.finalAssistantVisibleText ?? M ?? "");
			const r = i.replyCompletion.outcome === "pending" ? { kind: "none" } : resolveStrandedReplyRecovery({
				base: c,
				payloads: O,
				finalText: n,
				terminalReply: S.meta?.terminalReply,
				sourceReplyDeliveryMode: e.sourceReplyDeliveryMode,
				sendPolicyDenied: e.sendPolicyDenied,
				successfulSourceReplyDelivery: w,
				isRoomEvent: v.InboundEventKind === "room_event"
			});
			if (r.kind === "retry") warnPrivateMessageToolFinal({
				sessionKey: y,
				channel: v.OriginatingChannel ?? v.Surface ?? v.Provider ?? sessionDeliveryChannel(D),
				finalTextLength: n.trim().length
			});
			if (r.kind === "diagnostic") O = [...O, r.payload];
			else if (r.kind === "retry") {
				if (!enqueueFollowupRun(d, {
					...r.run,
					controllerInput: void 0,
					controllerClaim: void 0
				}, p, "none", g, false, {
					position: "front",
					storePath: b
				})) O = [...O, createMissingReplyNotice()];
			}
			const a = buildRecoverablePendingFinalDeliveryText(normalizePendingFinalRecoveryPayloads(O));
			const o = e.suppressDelivery ? "" : a ?? "";
			const u = isInternalSourceReplyChannel(v) && !i.reminderNoteAppended;
			const f = e.suppressDelivery ? [] : O.filter((e) => {
				const t = getReplyPayloadMetadata(e);
				const n = t?.sourceReplyTranscriptMirror?.transcriptOwner === true;
				return !(u && (t?.localTranscriptDeliveryConfirmed === true || n) && !t?.assistantMediaFailures?.length && (n || !e.mediaUrl && !e.mediaUrls?.length) && !e.attachments?.length && !e.presentation && !e.interactive && !e.channelData && !e.location && !e.btw && !e.delivery && !e.spokenText && !e.ttsSupplement && !t?.responsePrefix && !t?.responseUsageLine) && normalizePendingFinalDeliveryPayloads([e]).length > 0;
			});
			if (f.length > 0) {
				const e = getCommandOwnerAuthority(c.run);
				const n = e ? e.recoveryReference ?? null : void 0;
				const r = crypto.randomUUID();
				const i = D?.sessionId ?? c.run.sessionId;
				const a = f.map((e) => {
					const t = crypto.randomUUID();
					setReplyPayloadMetadata(e, { pendingFinalDeliveryCompletion: {
						commandOwnerReference: n,
						agentId: c.run.agentId,
						deliveryId: t,
						intentId: r,
						sessionId: i,
						sessionKey: y,
						storePath: b
					} });
					return {
						id: t,
						state: "prepared"
					};
				});
				const u = resolveReplyRunDeliveryContext({
					cfg: s,
					sessionCtx: v,
					sessionEntry: D,
					sessionKey: y,
					runtimePolicySessionKey: _,
					opts: l
				});
				if (!t) throw new Error("Pending final delivery has no admitted completion actor");
				const d = await t.complete({
					...o && n === void 0 ? {
						kind: "replayable",
						text: o
					} : { kind: "transport-only" },
					intentId: r,
					deliveries: a,
					context: u,
					createdAt: Date.now()
				});
				if (d?.sessionId !== i || d.pendingFinalDelivery?.intentId !== r) throw new Error("pending final delivery session changed or was deleted");
				D = d;
			}
		}
		D = await t?.complete() ?? D;
		const F = h(O.length <= 1 ? O[0] : O);
		const { replyOperation: I } = n;
		const L = S.meta;
		const ee = n.execution.maintenanceAuthProfile;
		if (!D || !y || !b || !r.providerUsed || !I.lifecycleGeneration || r.preserveUserFacingSessionState || n.execution.status !== "ok" || r.fallbackExhausted || x > 0 || L?.aborted || L?.yielded || L?.error || L?.agentMeta?.agentHarnessId !== "openclaw" || ee === void 0 || s.agents?.defaults?.compaction?.enabled === false) return {
			result: F,
			accounting: r
		};
		const R = {
			cfg: s,
			sessionKey: y,
			storePath: b,
			timeoutMs: c.run.timeoutMs,
			runtimePolicySessionKey: _
		};
		scheduleSessionMaintenance({
			prepared: R,
			followupRun: createSessionMaintenanceFollowup({
				run: c.run,
				sessionEntry: D,
				cfg: s,
				sessionKey: y,
				runtimePolicySessionKey: _ ?? c.run.runtimePolicySessionKey,
				provider: r.providerUsed,
				model: r.modelUsed,
				auth: ee
			}),
			sessionId: D.sessionId,
			lifecycleRevision: D.lifecycleRevision,
			lifecycleGeneration: I.lifecycleGeneration,
			startedAt: I.startedAtMs,
			agentHarnessId: L.agentMeta.agentHarnessId,
			compactionRequestBudget: n.execution.compactionRequestBudget
		}, I.ownerSettlement.then(() => I.result?.kind === "completed" && !I.abortSignal.aborted));
		return {
			result: F,
			accounting: r
		};
	});
	if (e.sessionKey && e.storePath && e.execution.status === "ok" && r.activeSessionEntry?.goal?.status === "active") await enqueueGoalContinuation({
		base: e.followupRun,
		result: r.runResult,
		initialGoalId: t,
		expectedSession: r.expectedSession,
		sessionKey: e.sessionKey,
		storePath: e.storePath,
		reader: getReplyOperationSessionReader(e.replyOperation),
		queueKey: e.queueKey,
		settings: e.resolvedQueue,
		sourceRunId: e.runId,
		operation: e.replyOperation,
		runFollowup: e.runFollowupTurn
	});
	return e.returnWithQueuedFollowupDrain(n);
}
//#endregion
//#region src/auto-reply/reply/followup-delivery-payloads.ts
/** Normalizes delivery content, applies threading, and dedupes message-tool sends. */
function resolveFollowupDeliveryPayloads(e) {
	const t = resolveOriginMessageProvider({
		originatingChannel: e.originatingChannel,
		provider: e.messageProvider
	});
	const n = t;
	const r = e.originatingReplyToMode ?? resolveReplyToMode(e.cfg, n, e.originatingAccountId, e.originatingChatType);
	const i = e.originatingAccountId;
	const a = createReplyDeliveryContext(r, e.originatingChatType);
	const o = t ? {
		channel: t,
		...i ? { accountId: i } : {}
	} : void 0;
	const s = e.payloads.flatMap((t) => t.isReasoning === true && e.reasoningPayloadsEnabled !== true || t.isCommentary === true && e.commentaryPayloadsEnabled !== true ? [] : normalizeReplyPayload(t, { applyChannelTransforms: false }) ?? []);
	const c = createReplyToModeFilterForChannel(r, n);
	return s.flatMap((n) => filterMessagingToolReplyPayload({
		payload: c.preview(setReplyPayloadMetadata(applyReplyTagsToPayload({ payload: n }), {
			replyDelivery: a,
			...o ? { replyDeliverySource: o } : {}
		})),
		config: e.cfg,
		messageProvider: t,
		messagingToolSentTargets: e.sentTargets,
		originatingTo: e.originatingTo,
		originatingThreadId: e.originatingThreadId,
		accountId: i,
		sentMediaUrls: e.sentMediaUrls,
		sentTexts: e.sentTexts,
		onDeliveredTerminalDuplicate: e.onDeliveredTerminalDuplicate
	}).filter(isRenderablePayload).map(c));
}
//#endregion
//#region src/auto-reply/reply/followup-delivery-tts.ts
function createFollowupSpeechPreparer({ turn: e, defaults: t, kind: n }) {
	let r = t.opts?.preparedTtsPreferences;
	return async (t, i) => {
		if (t.isReasoning || t.isCommentary || isReplyPayloadStatusNotice(t)) return t;
		r ??= await prepareTtsPreferences();
		const a = i === "origin" ? e.queued.originatingChannel : e.queued.run.messageProvider;
		const o = {
			cfg: e.config,
			preparedTtsPreferences: r,
			ttsAuto: e.session.current()?.ttsAuto,
			agentId: e.queued.run.agentId,
			channelId: normalizeMessageChannel(a) ?? a,
			accountId: i === "origin" ? e.queued.originatingAccountId : e.queued.run.agentAccountId
		};
		if (!shouldAttemptTtsPayload(o)) return t;
		e.operation.abortSignal.throwIfAborted();
		e.queued.operatorAuthority?.assertCurrent();
		const s = beginReplyOperationFinalizationWork(e.operation, RUN_STALE_TAKEOVER_MS);
		let c = t;
		try {
			c = await maybeApplyTtsToReplyPayload({
				...o,
				channel: o.channelId,
				payload: t,
				kind: n,
				inboundAudio: e.queued.currentInboundAudio === true || e.operation.acceptedSteeredInboundAudio
			});
			e.operation.watchdog.progress("finalization", "reply:tts_prepared");
		} catch {
			logVerbose("followup queue: speech preparation failed; delivering the original payload");
		} finally {
			s();
		}
		e.operation.abortSignal.throwIfAborted();
		e.queued.operatorAuthority?.assertCurrent();
		return c;
	};
}
//#endregion
//#region src/auto-reply/reply/followup-delivery.ts
function resolveFollowupPayloadContext(e) {
	return {
		cfg: e.config,
		messageProvider: e.queued.run.messageProvider,
		originatingAccountId: e.queued.originatingAccountId ?? e.queued.run.agentAccountId,
		originatingChannel: e.queued.originatingChannel,
		originatingChatType: e.queued.originatingChatType,
		originatingReplyToMode: e.queued.originatingReplyToMode,
		originatingTo: e.queued.originatingTo,
		originatingThreadId: e.queued.originatingThreadId
	};
}
/** Resolves one final queued delivery action without performing transport I/O. */
async function resolveFollowupDeliveryDecision(e) {
	const { turn: t, execution: n, accounting: r, opts: i } = e;
	if (t.sendPolicy === "deny") return {
		kind: "suppress",
		reason: "send-policy"
	};
	if (t.queued.currentInboundEventKind === "room_event" && !isInternalMessageChannel(t.queued.originatingChannel)) return {
		kind: "suppress",
		reason: "room-event"
	};
	const a = resolveSourceReplyVisibilityPolicy({
		cfg: t.config,
		scheduledAutomation: t.queued.run.scheduledAutomation !== void 0,
		ctx: {
			ChatType: t.queued.originatingChatType ?? t.queued.run.chatType,
			InboundEventKind: t.queued.currentInboundEventKind,
			Provider: t.queued.originatingChannel ?? t.queued.run.messageProvider,
			Surface: t.queued.originatingChannel ?? t.queued.run.messageProvider
		},
		requested: t.queued.run.sourceReplyDeliveryMode ?? i?.sourceReplyDeliveryMode,
		sendPolicy: t.sendPolicy
	});
	const o = resolveFollowupReplyExpectation(t.queued, t.config);
	const s = isRequiredReplyExpectation(o) || !isSyntheticSourceReplyTurn({
		inputProvenance: t.queued.run.inputProvenance,
		scheduledAutomation: t.queued.run.scheduledAutomation !== void 0
	}) && !isInternalMessageChannel(t.queued.originatingChannel ?? t.queued.run.messageProvider) && Boolean(t.queued.originatingTo?.trim() || i?.onBlockReply || t.queued.queuedFollowupReplyDisposition?.kind === "deliver");
	const c = resolveFollowupPayloadContext(t);
	const preparePayloads = (e, t = {}) => resolveFollowupDeliveryPayloads({
		...c,
		...t,
		payloads: e
	});
	if (n.outcome.kind === "aborted") {
		if (t.queued.stalledTurnRecovery === true && isReplyOperationStalledBeforeOutput(t.operation)) {
			const e = preparePayloads([markReplyPayloadForSourceSuppressionDelivery({
				text: resolveStalledTurnNoticeText(t.operation),
				isError: true
			})]);
			if (e.length > 0) return {
				kind: "deliver",
				payloads: e
			};
		}
		return {
			kind: "suppress",
			reason: "aborted"
		};
	}
	const l = n.outcome.postCompactionModelFailure;
	const renderFailurePayloads = (e) => e.map((e) => renderPostCompactionModelFailurePayload(markPostCompactionModelFailurePayload(l, e)));
	if (n.outcome.kind === "rejected") {
		if (!s) return {
			kind: "suppress",
			reason: "silent"
		};
		if (a.sourceReplyDeliveryMode === "message_tool_only" && getReplyPayloadMetadata(n.outcome.payload)?.deliverDespiteSourceReplySuppression !== true) return {
			kind: "suppress",
			reason: "message-tool-only"
		};
		const e = renderFailurePayloads(preparePayloads([n.outcome.payload], {
			reasoningPayloadsEnabled: i?.reasoningPayloadsEnabled === true,
			commentaryPayloadsEnabled: i?.commentaryPayloadsEnabled === true
		}));
		return e.length > 0 ? {
			kind: "deliver",
			payloads: e,
			resolved: n.outcome.resolved
		} : {
			kind: "suppress",
			reason: "silent"
		};
	}
	if (!r) return {
		kind: "suppress",
		reason: "silent"
	};
	const u = {
		provider: r.providerUsed,
		model: r.modelUsed
	};
	const d = n.outcome.result;
	const f = n.outcome.status === "failed";
	const p = shouldDeliverMissingReplyNotice({
		...t.queued.run,
		scheduledAutomation: t.queued.run.scheduledAutomation !== void 0,
		terminalReplyExpectation: o,
		trigger: t.queued.run.internalEventExecution ? "event" : "user",
		currentInboundEventKind: t.queued.currentInboundEventKind
	});
	const { successfulTerminal: m, authoredSilence: h, pendingContinuation: g, automationNoChange: _, reasoningPayloadsEnabled: v } = resolveAutomationReplyState(n.outcome, {
		opts: i,
		terminalFailurePayload: r.terminalFailurePayload
	});
	const y = n.outcome.directBlockDeliveries;
	const b = resolveSourceReplyDelivery(d, await resolveTerminalReplyDelivery({
		directBlockDeliveries: y,
		resolveReplyDelivery: i?.resolveReplyDelivery,
		sourceReplyDeliveryState: d.sourceReplyDeliveryState
	}));
	let x = resolveReplyCompletion(resolveClaimedReplyExpectation(o, d.meta), d.meta?.error?.kind === "hook_block" || d.didSendDeterministicApprovalPrompt === true ? "blocked" : h ? "silent" : b !== "missing" ? b : _ ? "silent" : g ? "pending" : "empty");
	const S = x.outcome === "silent";
	const C = selectAutomationReplyPayloads(r.payloadArray, _, h);
	if ((S || _) && C.length === 0) return {
		kind: "suppress",
		reason: "silent"
	};
	const w = hasCompletedSourceReplyDeliveryEvidence(d);
	const T = d.sourceReplyDeliveryState === void 0 && (resolveExplicitFinalSourceReplyDeliveryEvidence(d) === void 0 || m && !g && a.sourceReplyDeliveryMode !== "message_tool_only");
	const E = normalizeAssistantFinalDeliveryText(d.meta?.finalAssistantVisibleText ?? "");
	let D = preparePayloads(C, {
		reasoningPayloadsEnabled: v,
		commentaryPayloadsEnabled: i?.commentaryPayloadsEnabled === true,
		sentMediaUrls: d.messagingToolSentMediaUrls,
		sentTargets: d.messagingToolSentTargets,
		sentTexts: d.messagingToolSentTexts,
		onDeliveredTerminalDuplicate: T ? () => {
			if (x.outcome !== "blocked") x = resolveReplyCompletion(o, "delivered");
		} : void 0
	});
	if (!w && x.outcome === "delivered") await i?.onObservedReplyDelivery?.();
	const O = S || f || !p || x.outcome !== "missing" ? { kind: "none" } : resolveStrandedReplyRecovery({
		base: t.queued,
		payloads: D,
		finalText: E,
		terminalReply: d.meta?.terminalReply,
		sourceReplyDeliveryMode: a.sourceReplyDeliveryMode,
		sendPolicyDenied: a.sendPolicyDenied,
		successfulSourceReplyDelivery: w,
		isRoomEvent: false
	});
	if (O.kind === "retry") return {
		kind: "retry-source-delivery",
		run: O.run,
		finalTextLength: E.trim().length,
		resolved: u
	};
	if (O.kind === "diagnostic") {
		const [e] = preparePayloads([O.payload]);
		return e ? {
			kind: "deliver",
			payloads: [e],
			resolved: u
		} : {
			kind: "suppress",
			reason: "silent"
		};
	}
	const k = D.some((e) => isReplyPayloadTerminalContent(e) && (!f && !g || a.sourceReplyDeliveryMode !== "message_tool_only" || getReplyPayloadMetadata(e)?.deliverDespiteSourceReplySuppression === true));
	if (!k && x.outcome === "missing" && !t.operation.result) {
		t.operation.fail("run_failed", new Error(MISSING_REPLY_NOTICE_TEXT));
		i?.onAgentRunTerminalOutcome?.("failed");
	}
	const A = {
		completion: x,
		continuationPending: d.meta?.continuationPending === true,
		mediaContinuation: d.meta?.continuationPending === true && !hasCompletionMessageSessionSpawn(d.acceptedSessionSpawns),
		yielded: d.meta?.yielded === true,
		yieldAcknowledgment: d.meta?.yieldAcknowledgment,
		hasVisibleMessageDelivery: hasCommittedSourceReplyDeliveryEvidence(d) || hasVisibleCommittedMessagingToolDeliveryEvidence(d) || d.didSendDeterministicApprovalPrompt === true
	};
	const j = f ? void 0 : buildWaitingStatusPayload(A);
	const M = f ? r.terminalFailurePayload && s && x.outcome !== "delivered" && x.outcome !== "pending" && x.outcome !== "blocked" ? a.sourceReplyDeliveryMode === "message_tool_only" ? markReplyPayloadForSourceSuppressionDelivery(r.terminalFailurePayload) : r.terminalFailurePayload : void 0 : j ?? (p && x.outcome === "missing" ? createMissingReplyNotice() : void 0);
	if (!k && M) D.push(...preparePayloads([M]));
	if (r.compactionNotice) D.unshift(...preparePayloads([r.compactionNotice]));
	if (r.diagnosticsPayload && D.length > 0) D.push(...preparePayloads([r.diagnosticsPayload]));
	const N = resolveResponseUsageLine({
		config: t.config,
		agentDir: t.queued.run.agentDir,
		sessionRaw: t.session.current()?.responseUsage,
		channel: resolveOriginMessageProvider({
			originatingChannel: t.queued.originatingChannel,
			provider: t.queued.run.messageProvider
		}),
		usage: r.usage,
		provider: r.providerUsed,
		model: r.modelUsed,
		preserveUserFacingSessionState: r.preserveUserFacingSessionState,
		replyUsageState: r.replyUsageState
	});
	let P;
	if (N) {
		if (a.sourceReplyDeliveryMode === "message_tool_only" && hasCompletedSourceReplyDeliveryEvidence(d)) P = markReplyPayloadForSourceSuppressionDelivery({
			text: N,
			isStatusNotice: true
		});
		else D = appendUsageLine(D, N);
	}
	D = renderFailurePayloads(D);
	if (P) D = [...D, P];
	if (a.sourceReplyDeliveryMode === "message_tool_only") {
		D = D.filter((e) => getReplyPayloadMetadata(e)?.deliverDespiteSourceReplySuppression === true);
		if (D.length === 0) return {
			kind: "suppress",
			reason: "message-tool-only"
		};
	}
	if (n.outcome.automation) D = retainAutomationReasoningWithFinal(D);
	return D.length > 0 ? {
		kind: "deliver",
		payloads: D,
		resolved: u
	} : {
		kind: "suppress",
		reason: "silent"
	};
}
async function deliverFollowupDecision(e) {
	const { decision: t, turn: n, defaults: r } = e;
	if (t.kind === "suppress") {
		n.queued.run.internalEventExecution?.onSuppressed?.(t.reason);
		logVerbose(`followup queue: delivery suppressed (${t.reason})`);
		return {
			kind: "completed",
			payloads: []
		};
	}
	if (n.queued.run.sessionEventOrigin?.deliver === false) {
		logVerbose("followup queue: delivery suppressed by its silent source event");
		return {
			kind: "completed",
			payloads: []
		};
	}
	let i;
	if (t.kind === "retry-source-delivery") {
		warnPrivateMessageToolFinal({
			sessionKey: n.session.kind === "session" ? n.session.key : void 0,
			channel: n.queued.originatingChannel ?? n.queued.run.messageProvider ?? sessionDeliveryChannel(n.session.current()),
			finalTextLength: t.finalTextLength
		});
		const r = n.session.kind === "session" ? n.session.key : n.queued.run.sessionKey;
		const a = n.queued.queuedFollowupReplyDisposition;
		const o = a?.kind === "deliver" ? a.deliver.createSourceRetry?.() : void 0;
		const s = {
			...t.run,
			controllerInput: void 0,
			controllerClaim: void 0,
			...o ? { queuedFollowupReplyDisposition: {
				kind: "deliver",
				deliver: o
			} } : {}
		};
		if (r && enqueueFollowupRun(r, s, resolveQueueSettings({
			cfg: n.config,
			channel: n.queued.originatingChannel ?? n.queued.run.messageProvider,
			sessionEntry: n.session.current()
		}), "none", e.runFollowup, false, {
			position: "front",
			storePath: n.session.kind === "session" ? n.session.storePath : void 0
		})) return { kind: "source-retry" };
		i = resolveFollowupDeliveryPayloads({
			...resolveFollowupPayloadContext(n),
			payloads: [createMissingReplyNotice()]
		});
	} else i = t.payloads;
	const a = e.runId;
	const o = e.kind ?? "final";
	const s = t.kind === "deliver" && e.kind && e.kind !== "final" ? false : void 0;
	const c = t.resolved;
	const l = e.onObservedReplyDelivery;
	const { originatingChannel: u, originatingTo: d } = n.queued;
	const f = Boolean(isRoutableChannel(u) && d);
	const p = buildAgentRuntimeDeliveryPlan({
		provider: c?.provider ?? n.queued.run.provider,
		modelId: c?.model ?? n.queued.run.model,
		config: n.config,
		workspaceDir: n.queued.run.workspaceDir,
		agentDir: n.queued.run.agentDir
	});
	i = i.filter((e) => hasOutboundReplyContent(e));
	if (i.length === 0) return {
		kind: "completed",
		payloads: []
	};
	const m = n.queued.queuedFollowupReplyDisposition;
	if (m?.kind === "drop") {
		logVerbose(`followup queue: source delivery dropped (${m.reason})`);
		return {
			kind: "completed",
			payloads: []
		};
	}
	const h = m?.deliver;
	if (n.queued.run.internalEventExecution || h?.ownsCompletion?.(u)) {
		if (!h) throw new Error("Internal event lost its originating delivery owner");
		if (o !== "final") await h({
			kind: "queued-followup",
			runId: a,
			originatingChannel: u,
			payloads: i,
			completion: { kind: "progress" }
		});
		return {
			kind: "completed",
			payloads: i
		};
	}
	const g = m ? void 0 : r.opts?.onBlockReply;
	const _ = Boolean(h || g);
	if (!f && !_) {
		defaultRuntime.error?.("followup queue: completed with payloads but no origin route or visible dispatcher is available");
		return {
			kind: "completed",
			payloads: []
		};
	}
	const v = createTypingSignaler({
		typing: r.typing,
		mode: r.typingMode
	});
	const y = [];
	const b = [];
	let x = false;
	const dispatchPayload = async (e) => {
		if (h) b.push(e);
		else if (g) {
			const t = await deliverBlockReply(() => g(e));
			x ||= t.pending === true || t.outcome === "recovery-owned";
			if (t.outcome === "delivered" && !t.pending && (!f || T)) await l?.();
		}
	};
	let S = false;
	const C = resolveOriginMessageProvider({ provider: n.queued.run.messageProvider });
	const w = resolveOriginMessageProvider({ originatingChannel: u });
	const T = Boolean(w && w === C);
	const E = Boolean(w && C && w !== C);
	const D = createFollowupSpeechPreparer({
		turn: n,
		defaults: r,
		kind: o
	});
	const O = n.session.current();
	const k = n.session.kind === "session" && n.session.storePath && O ? {
		agentId: resolveSessionAgentId({
			sessionKey: n.session.key,
			config: n.config,
			fallbackAgentId: n.queued.run.agentId
		}),
		storePath: n.session.storePath,
		sessionKey: n.session.key,
		sessionId: O.sessionId,
		lifecycleRevision: O.lifecycleRevision ?? null
	} : void 0;
	for (let e of i) {
		const t = p.resolveFollowupRoute({
			payload: e,
			originatingChannel: u,
			originatingTo: d,
			originRoutable: f,
			dispatcherAvailable: _
		});
		if (t?.route === "drop") continue;
		const r = t?.route === "origin" && f ? "origin" : t?.route === "dispatcher" && _ ? "dispatcher" : f ? "origin" : "dispatcher";
		if (r === "origin") {
			const t = (n.queued.deliveryCorrelations ?? []).flatMap((t) => t.shouldSuppressReply ? [t.shouldSuppressReply(e)] : []);
			if (t.length > 0 && t.every(Boolean)) {
				logVerbose("followup queue: origin reply suppressed by source policy");
				continue;
			}
		}
		await v.signalTextDelta(e.text);
		if (n.queued.stalledTurnRecovery !== true || !isReplyOperationStalledBeforeOutput(n.operation)) e = await D(e, r);
		if (r !== "origin") await dispatchPayload(e);
		else if (isRoutableChannel(u) && d) {
			const t = getReplyPayloadMetadata(e);
			const r = await routeReply({
				payload: e,
				channel: u,
				to: d,
				agentId: n.queued.run.agentId,
				sessionKey: n.queued.run.sessionKey,
				sessionGeneration: k,
				accountId: n.queued.originatingAccountId,
				requesterSenderId: n.queued.run.senderId,
				requesterSenderName: n.queued.run.senderName,
				requesterSenderUsername: n.queued.run.senderUsername,
				requesterSenderE164: n.queued.run.senderE164,
				threadId: n.queued.originatingThreadId,
				currentMessageId: T && (n.queued.run.inputProvenance?.kind === void 0 || n.queued.run.inputProvenance.kind === "external_user") ? n.queued.messageId : void 0,
				cfg: n.config,
				mirror: t?.assistantMessageIndex !== void 0 || t?.assistantTranscriptOwned === true ? false : s,
				replyKind: o,
				runId: a
			});
			if (!r.delivered && (r.queueCustody === "held" || r.ambiguous)) {
				x = true;
				logVerbose(`followup queue: route-reply remains pending: ${r.error ?? "unconfirmed delivery"}`);
				continue;
			}
			if (!r.delivered && !r.suppressed) {
				const t = r.error ?? "no visible delivery";
				(_ ? logVerbose : defaultRuntime.error)?.(`followup queue: route-reply failed: ${t}`);
				if (T && _) await dispatchPayload(e);
				else if (_) y.push(e);
			} else if (r.delivered) {
				for (const t of n.queued.deliveryCorrelations ?? []) t.onReplyDelivered?.(e);
				await l?.();
				if (!r.ok) logVerbose(`followup queue: route-reply partially failed after delivery: ${r.error ?? "unknown error"}`);
				S ||= E;
			}
		}
	}
	if ((y.some(isReplyPayloadTerminalContent) || y.length > 0 && !S) && _) await dispatchPayload({
		text: "Follow-up completed, but OpenClaw could not deliver it to the originating channel. The reply content was not forwarded to this channel to avoid cross-channel misdelivery.",
		isError: true
	});
	if (o !== "final" && b.length > 0) await h?.({
		kind: "queued-followup",
		runId: a,
		originatingChannel: u,
		payloads: b,
		completion: { kind: "progress" }
	});
	return {
		kind: x ? "pending" : "completed",
		payloads: b
	};
}
//#endregion
//#region src/auto-reply/reply/followup-presentation.ts
async function settleQueuedFollowupPresentation(e) {
	try {
		await e?.();
	} catch (e) {
		defaultRuntime.error?.(`followup queue: queued presentation cleanup failed: ${formatErrorMessage$1(e)}`);
	}
}
//#endregion
//#region src/auto-reply/reply/reply-input-placement.ts
/** Read admission facts without treating same-destination claim settlement as revocation. */
async function readReplyAdmissionSession(e) {
	const { sessionId: t, placementContext: n } = e;
	const r = n?.workerSessionPlacementService;
	if (r && !r.prepareSessionPlacement) throw new Error("Worker placement observation service is unavailable");
	const i = r?.prepareSessionPlacement ? await r.prepareSessionPlacement(t) : void 0;
	try {
		const n = i?.prepareRead();
		if (n) await n;
		const r = await e.readEntry();
		e.assertCurrent();
		const a = i?.current();
		if (!r || r.sessionId !== t) throw new Error("session changed before durable user-turn admission");
		return {
			entry: r,
			stagedWorkerInput: Boolean(a && a.state !== "local")
		};
	} finally {
		i?.release();
	}
}
//#endregion
//#region src/auto-reply/reply/reply-input-admission.ts
/** Transfers ordinary accepted input into its admitted session, without restart checkpoints. */
function createReplyInputAdmission(e) {
	const { replyOperation: t, followupRun: n, sessionKey: r, storePath: i } = e;
	let a;
	const assertCurrent = () => {
		t.abortSignal.throwIfAborted();
		if (t.lifecycleGeneration) assertAgentRunLifecycleGenerationCurrent(t.lifecycleGeneration);
		n.operatorAuthority?.assertCurrent();
	};
	const bindSource = () => {
		assertCurrent();
		if (e.sourceTurnId) bindSessionControllerSourceTurnId(t, e.sourceTurnId);
	};
	const acquire = async () => {
		const e = await acquireReplyOperationSessionActor(t);
		assertCurrent();
		const n = getReplyOperationSessionTarget(t);
		if (e && n) {
			a = n;
			return {
				actor: e,
				target: n
			};
		}
	};
	const read = async () => {
		if (!r) throw new Error("Reply input has no session target");
		const e = await acquire();
		if (e) {
			const t = {
				assertCurrent,
				authorize: assertCurrent
			};
			return (e.actor.snapshot(t) ?? await e.actor.read(t)).entry;
		}
		return readSessionEntryInWorker({
			agentId: n.run.agentId,
			sessionKey: r,
			storePath: i
		}, assertCurrent, void 0, (e) => {
			a = e;
		});
	};
	return {
		async admitUserTurn(o) {
			assertCurrent();
			if (!o || o.hasPersisted()) {
				bindSource();
				return;
			}
			if (!r || !i) {
				await o.persistApproved();
				bindSource();
				return;
			}
			const { entry: s, stagedWorkerInput: c } = await readReplyAdmissionSession({
				sessionId: t.sessionId,
				placementContext: o?.getPendingInputMessage?.() ? resolveSessionWorkerPlacementContext() : void 0,
				readEntry: read,
				assertCurrent
			});
			if (!c && o && !o.hasPersisted() && !(n.run.inputProvenance?.kind === "internal_system" && o.getPendingInputMessage?.())) {
				bindUserTurnInputActor(o, {
					phase: "adoptRun",
					acquire
				});
				const t = await o.persistApproved({
					target: {
						agentId: n.run.agentId,
						sessionId: s.sessionId,
						sessionKey: r,
						sessionEntry: s,
						storePath: a?.readSource?.path ?? a?.storePath ?? i,
						cwd: n.run.workspaceDir,
						config: n.run.config
					},
					expectedSessionId: s.sessionId,
					expectedSessionState: buildSessionTranscriptTurnExpectedState(s)
				});
				if (t?.sessionEntry) e.setEntry(t.sessionEntry);
			}
			bindSource();
		},
		async recordPendingDelivery(n) {
			const r = await read();
			assertCurrent();
			if (!r || r.sessionId !== t.sessionId || !a) throw new Error("Session changed before recording reply delivery");
			const i = await patchSessionEntryTarget(a, (e) => {
				assertCurrent();
				if (!e || e.sessionId !== r.sessionId || e.lifecycleRevision !== r.lifecycleRevision) throw new Error("Session changed before recording reply delivery");
				return { pendingFinalDelivery: {
					...n.text ? {
						kind: "replayable",
						text: n.text
					} : { kind: "transport-only" },
					createdAt: Date.now(),
					intentId: n.intentId,
					deliveries: n.deliveries,
					...n.context ? { context: n.context } : {}
				} };
			}, {
				skipMaintenance: true,
				takeCacheOwnership: true,
				preserveActivity: true,
				workerGuard: { assertCurrent }
			});
			if (i) e.setEntry(i);
		}
	};
}
//#endregion
//#region src/auto-reply/reply/followup-turn-execution.ts
function buildFollowupTemplateContext(e) {
	const t = e.queued;
	const n = t.run;
	const r = t.originatingChannel ?? n.messageProvider;
	const i = e.session.kind === "session" ? e.session.key : n.sessionKey;
	const a = resolveFollowupCurrentMessageId(t);
	return {
		Provider: n.messageProvider,
		Surface: r,
		OriginatingChannel: t.originatingChannel,
		OriginatingTo: t.originatingTo,
		To: t.originatingTo,
		AccountId: t.originatingAccountId ?? n.agentAccountId,
		ChatType: t.originatingChatType ?? n.chatType,
		SessionKey: i,
		RuntimePolicySessionKey: n.runtimePolicySessionKey ?? i,
		MessageSid: a,
		MessageSidFull: a,
		MessageThreadId: t.originatingThreadId,
		ReplyToId: t.originatingReplyToId,
		SenderId: n.senderId,
		MemberRoleIds: n.memberRoleIds,
		ChannelContext: n.channelContext,
		SenderName: n.senderName,
		SenderUsername: n.senderUsername,
		SenderE164: n.senderE164,
		GroupChannel: n.groupChannel,
		GroupSpace: n.groupSpace,
		InputProvenance: n.inputProvenance,
		InboundEventKind: t.currentInboundEventKind,
		media: t.media
	};
}
/** Adapts an admitted queued turn to the canonical agent execution owner. */
async function executeFollowupTurn(e) {
	const { turn: t, defaults: n } = e;
	const r = n.opts;
	const i = resolveFollowupReplyExpectation(t.queued, t.config);
	t.queued.run.terminalReplyExpectation = i;
	const a = t.queued.currentInboundEventKind === "room_event";
	const deliveryAllowed = () => t.sendPolicy === "allow" && !a;
	const progressAllowed = () => deliveryAllowed() && (r?.progressRequiresReply !== true || isRequiredReplyExpectation(i));
	const currentVerboseLevel = () => {
		const e = t.queued.run.verboseLevelOverride ?? t.session.current()?.verboseLevel ?? t.queued.run.verboseLevel;
		return e === "on" || e === "full" ? e : "off";
	};
	const o = r?.forceToolResultProgress === true;
	const s = o ? r.onToolResult : void 0;
	const shouldEmitVerboseToolResult = () => {
		const e = currentVerboseLevel();
		return e === "on" || e === "full";
	};
	const shouldEmitToolResult = () => progressAllowed() && (o || shouldEmitVerboseToolResult());
	const shouldEmitToolOutput = () => progressAllowed() && currentVerboseLevel() === "full";
	const shouldEmitStructuredProgress = () => progressAllowed() && (r?.suppressDefaultToolProgressMessages === true || shouldEmitToolResult());
	const shouldEmitToolLifecycle = () => progressAllowed() && (shouldEmitStructuredProgress() || r?.allowToolLifecycleWhenProgressHidden === true);
	const { commentaryPayloadsEnabled: c, draftOwnsCommentaryProgress: l } = await resolveTurnCommentaryProgressOwner({
		commentaryPayloadsEnabled: r?.commentaryPayloadsEnabled === true,
		options: r,
		resolveVerboseProgressVisibility: () => progressAllowed() && shouldEmitVerboseToolResult(),
		resolveVerboseProgressVisibilityAsync: async () => {
			t.operation.abortSignal.throwIfAborted();
			t.queued.operatorAuthority?.assertCurrent();
			return progressAllowed() && shouldEmitVerboseToolResult();
		}
	});
	t.operation.abortSignal.throwIfAborted();
	t.queued.operatorAuthority?.assertCurrent();
	let u = Promise.resolve();
	let d = false;
	const f = {};
	const p = /* @__PURE__ */ new Set();
	const trackPendingWork = (e, n) => {
		const r = t.operation.retainExecution();
		const i = e.catch((e) => {
			f[n] ??= e;
			throw e;
		}).finally(() => {
			p.delete(i);
			r();
		});
		i.catch(() => void 0);
		p.add(i);
	};
	const enqueueProgress = (e) => {
		const t = u.then(e);
		u = t.catch(() => void 0);
		trackPendingWork(t, "progress");
		return u;
	};
	const enqueueProgressResult = async (e) => {
		let t = false;
		await enqueueProgress(async () => {
			t = await e();
			d ||= t !== false;
		});
		return t;
	};
	const wrap = (e, t = progressAllowed) => e ? (n) => enqueueProgress(async () => {
		if (t()) await e(n);
	}) : void 0;
	const wrapVisibility = (e, t = progressAllowed) => e ? (...n) => enqueueProgressResult(async () => {
		if (!t(...n)) return false;
		return (await settleProgressVisibilityCallbackResult(e(...n))).visible;
	}) : void 0;
	const m = createTypingSignaler({
		typing: n.typing,
		mode: progressAllowed() ? n.typingMode : "never"
	});
	const h = {
		...m,
		signalRunStart: () => enqueueProgress(m.signalRunStart),
		signalMessageStart: () => enqueueProgress(m.signalMessageStart),
		signalTextDelta: (e) => enqueueProgress(() => m.signalTextDelta(e)),
		signalReasoningDelta: () => enqueueProgress(m.signalReasoningDelta),
		signalToolStart: () => enqueueProgress(m.signalToolStart),
		signalExecutionActivity: () => enqueueProgress(m.signalExecutionActivity ?? m.signalRunStart)
	};
	const g = {
		...r,
		cronCreatorAuthorityCapability: void 0,
		sourceReplyDeliveryMode: t.queued.run.sourceReplyDeliveryMode,
		bootstrapContextMode: t.queued.run.bootstrapContextMode,
		cleanupBundleMcpOnRunEnd: void 0,
		scheduledAutomation: t.queued.run.scheduledAutomation,
		internalEventExecution: t.queued.run.internalEventExecution,
		userTurnTranscriptRecorder: t.queued.userTurnTranscriptRecorder,
		operatorAuthority: t.queued.operatorAuthority,
		abortSignal: t.operation.abortSignal,
		toolsAllow: t.queued.toolsAllow,
		disableTools: t.queued.disableTools,
		awaitSessionDiffBaseline: t.queued.runObservers?.awaitSessionDiffBaseline,
		onAgentRunStart: t.queued.runObservers?.onAgentRunStart,
		onPreparedAgentRunStart: t.queued.runObservers?.onPreparedAgentRunStart,
		onAgentRunTerminalOutcome: t.queued.runObservers?.onAgentRunTerminalOutcome,
		onModelSelected: t.queued.runObservers?.onModelSelected,
		prepareAssistantTranscriptMessage: t.queued.runObservers?.prepareAssistantTranscriptMessage,
		resolveReplyDelivery: t.queued.runObservers?.resolveReplyDelivery,
		resolveReplyDeliveryFacts: t.queued.runObservers?.resolveReplyDeliveryFacts,
		onDeliberateSilentTerminalReply: t.queued.runObservers?.onDeliberateSilentTerminalReply,
		commentaryPayloadsEnabled: c,
		runId: t.runId,
		onBlockReply: void 0,
		onPreparedBlockReply: void 0,
		onPartialReply: void 0,
		onAssistantMessageStart: void 0,
		onToolStart: wrapVisibility(r?.onToolStart, shouldEmitToolLifecycle),
		onCommandOutput: wrapVisibility(r?.onCommandOutput, shouldEmitStructuredProgress),
		onItemEvent: wrapVisibility(r?.onItemEvent ? (e) => r.onItemEvent(e) : void 0, (e) => e.kind === "model-wait" ? progressAllowed() : progressAllowed() && e.kind === "preamble" && l || shouldEmitStructuredProgress()),
		onNarrationUpdate: wrap(r?.onNarrationUpdate),
		onPlanUpdate: wrapVisibility(r?.onPlanUpdate),
		onApprovalEvent: wrapVisibility(r?.onApprovalEvent, shouldEmitStructuredProgress),
		onPatchSummary: wrapVisibility(r?.onPatchSummary, shouldEmitStructuredProgress),
		onCompactionStart: wrapVisibility(r?.onCompactionStart),
		onCompactionEnd: wrapVisibility(r?.onCompactionEnd),
		onReasoningStream: wrapVisibility(r?.onReasoningStream),
		onReasoningProgress: wrap(r?.onReasoningProgress),
		onReasoningEnd: wrapVisibility(r?.onReasoningEnd),
		onToolResult: async (n) => {
			return await enqueueProgressResult(async () => {
				const i = requiresDurableToolResultDelivery(n);
				if (!deliveryAllowed() || !i && !progressAllowed()) return false;
				if (r?.suppressToolProgressMessages && !i) return false;
				const a = isFastModeAutoProgressPayload(n) && !i;
				const c = !i && shouldEmitVerboseToolResult();
				const l = i ? void 0 : s;
				let u = c ? void 0 : l;
				if (a) {
					const e = r?.allowToolLifecycleWhenProgressHidden === true;
					u = (!(t.queued.run.sourceReplyDeliveryMode === "message_tool_only") || r?.allowProgressCallbacksWhenSourceDeliverySuppressed === true) && (o || c || e) ? r?.onToolResult : void 0;
				} else if (t.queued.run.sourceReplyDeliveryMode === "message_tool_only" && !l && !c && !i) return false;
				if (u) {
					const e = (await settleProgressVisibilityCallbackResult(u(n))).visible;
					if (e || !a) return e;
				}
				if (a && !o && !c) return false;
				await e.onToolResult(n);
				return true;
			});
		}
	};
	const _ = new class extends Set {
		add(e) {
			trackPendingWork(e, "tool");
			return super.add(e);
		}
	}();
	let v;
	const drainPendingWork = () => {
		v ??= (async () => {
			await drainPendingToolTasks({ tasks: p });
			_.clear();
		})();
		return v;
	};
	const y = buildFollowupTemplateContext(t);
	if (t.preflightError && !t.preflightFailurePayload) throw t.preflightError instanceof Error ? t.preflightError : new Error(formatErrorMessage$1(t.preflightError));
	const b = t.queued.userTurnTranscriptRecorder;
	const x = await b?.resolveMessage();
	t.operation.abortSignal.throwIfAborted();
	const S = resolveReplySourceTurnId({
		sourceTurnId: x?.idempotencyKey ?? t.queued.sourceTurnId,
		admissionRunId: t.queued.run.inputProvenance?.kind === "internal_system" ? void 0 : t.queued.messageId,
		ingressProvider: t.queued.run.messageProvider
	});
	const C = createReplyInputAdmission({
		followupRun: t.queued,
		replyOperation: t.operation,
		sourceTurnId: S,
		sessionKey: t.session.kind === "session" ? t.session.key : void 0,
		setEntry: (e) => t.session.publish(e),
		storePath: t.session.kind === "session" ? t.session.storePath : void 0
	});
	let w = false;
	let T;
	const E = Date.now();
	try {
		t.queued.run.internalEventExecution?.assertCurrent?.();
		await C.admitUserTurn(b);
		w = true;
		await admitFollowupRunLifecycle(t.queued);
		t.operation.abortSignal.throwIfAborted();
		setChannelSourceTurnId(y, S);
		if (t.preflightFailurePayload) {
			t.operation.fail("run_failed", t.preflightError);
			T = {
				runId: t.runId,
				outcome: {
					kind: "rejected",
					payload: t.preflightFailurePayload
				}
			};
		} else {
			t.queued.run.bootstrapUserProfileId = t.queued.personalBootstrapEligible ? sessionPersonalProfileId(t.session.current()) : void 0;
			await t.operation.bindToolAuthoritySnapshotAsync(prepareReplyRunToolAuthority(t.queued, t.session.current(), captureReplyOperationSessionReader(t.operation)));
			t.operation.setPhase("running");
			const r = t.queued.queuedFollowupReplyDisposition?.kind === "deliver" && t.queued.queuedFollowupReplyDisposition.deliver.ownsCompletion?.(t.queued.originatingChannel) === true;
			if (r) t.queued.run.mediaNormalizationOwner = "gateway";
			const execute = () => executeAgentTurn({
				recoveryMemoryFlushAttempted: t.memoryFlushAttempted,
				completionSource: r ? "reply-dispatch" : void 0,
				commandBody: t.queued.prompt,
				transcriptCommandBody: t.queued.transcriptPrompt,
				followupRun: t.queued,
				sessionCtx: y,
				replyOperation: t.operation,
				opts: g,
				resolveVisibleReplyDelivery: async () => {
					await drainPendingWork();
					return d;
				},
				typingSignals: h,
				blockReplyPipeline: null,
				blockStreamingEnabled: false,
				resolvedBlockStreamingBreak: t.queued.run.blockReplyBreak,
				applyReplyToMode: (e) => e,
				shouldEmitToolResult,
				shouldEmitToolOutput,
				pendingToolTasks: _,
				sessionKey: t.session.kind === "session" ? t.session.key : void 0,
				runtimePolicySessionKey: t.queued.run.runtimePolicySessionKey,
				getActiveSessionEntry: t.session.current,
				activeSessionStore: t.sessionStore,
				storePath: t.session.kind === "session" ? t.session.storePath : void 0,
				resolvedVerboseLevel: currentVerboseLevel(),
				toolProgressDetail: n.toolProgressDetail,
				onCompactionNoticePayload: async (t) => {
					await enqueueProgressResult(async () => {
						if (!progressAllowed()) return false;
						await e.onCompactionNoticePayload(t);
						return true;
					});
				}
			});
			t.operation.abortSignal.throwIfAborted();
			const i = t.queued.run;
			const o = i.senderIsOwner && isFreshChannelCronAuthorityTurn({
				messageProvider: i.messageProvider,
				senderId: i.senderId,
				isRoomEvent: a,
				inputProvenance: i.inputProvenance,
				spawnedBy: i.spawnedBy,
				suppressNextUserMessagePersistence: i.suppressNextUserMessagePersistence
			}) ? t.queued.createChannelCronAuthority?.(t.runId, getCommandOwnerAuthority(i)?.isCurrent) : void 0;
			g.cronCreatorAuthorityCapability = o;
			const runWithInput = () => withCurrentUserTurnInput(b, execute);
			T = o ? await runWithCronCreatorAuthorityCapability(o, runWithInput, t.operation.abortSignal) : await runWithInput();
		}
	} catch (e) {
		await drainPendingWork();
		const n = isIngressAdoptionLostError(e) && e.code === "guillotined" && !isAgentRunDirectAbortReason(t.operation.abortSignal.reason);
		if (!w || t.operation.abortSignal.aborted && !n) throw e;
		t.queued.operatorAuthority?.assertCurrent();
		t.operation.fail("run_failed", e);
		T = {
			runId: t.runId,
			outcome: {
				kind: "rejected",
				payload: buildTerminalAgentRunFailureReplyPayload({
					replyExpectation: i,
					visibleReplyDelivered: d
				})
			}
		};
	}
	recordReplyOperationAgentTurn(t.queued.replyOperationRunStates, t.operation, T.outcome);
	return {
		commentaryPayloadsEnabled: c,
		execution: T,
		runStartedAt: E,
		sessionCtx: y,
		pendingToolTasks: _,
		progress: { drain: async () => {
			await drainPendingWork();
			const e = f.progress ?? f.tool;
			if (e !== void 0) throw e instanceof Error ? e : new Error(formatErrorMessage$1(e));
		} }
	};
}
//#endregion
//#region src/auto-reply/reply/reply-source-admission.ts
/** Acquire original input custody before maintenance or a provider can consume it. */
async function prepareReplySourceAdmission(e) {
	const { operation: t, followupRun: n, recorder: r } = e;
	if (!r) return;
	if (n.run.internalEventExecution) return;
	const assertCurrent = () => {
		t.abortSignal.throwIfAborted();
		if (t.lifecycleGeneration) assertAgentRunLifecycleGenerationCurrent(t.lifecycleGeneration);
		n.operatorAuthority?.assertCurrent();
		assertSessionControllerOperation(t);
	};
	assertCurrent();
	await r.resolveMessage();
	assertCurrent();
	const i = !r.getPendingInputMessage?.() && !r.hasPersisted();
	const a = i ? async () => {
		try {
			r.finishPendingInput?.("cancelled");
		} finally {
			await r.waitForPendingInputSettlement?.();
		}
	} : void 0;
	try {
		if (i && getReplyOperationSessionTarget(t)) bindUserTurnInputActor(r, {
			phase: "acceptInput",
			acquire: async () => {
				assertCurrent();
				const e = await acquireReplyOperationSessionActor(t);
				assertCurrent();
				const n = getReplyOperationSessionTarget(t);
				if (!e || !n) throw new Error("Reply operation lost its session actor admission");
				return {
					actor: e,
					target: n
				};
			}
		});
		await r.stageApproved?.({
			runId: e.runId ?? randomUUID(),
			assertCurrent
		});
		assertCurrent();
		return a;
	} catch (e) {
		await a?.();
		throw e;
	}
}
/** Required preflight can invoke models and tools before the reply runner exists. */
async function admitReplyMaintenance(e, t, n) {
	const r = e.queued.run.internalEventExecution;
	await r?.beforeScheduledStart?.(e.runId);
	n();
	r?.onStarted(e.runId);
	const i = e.queued.run.scheduledAutomation;
	if (i && t) {
		i.onExecutionStarted?.({
			runId: e.runId,
			sessionId: e.operation.sessionId,
			sessionKey: t,
			provider: e.queued.run.provider,
			model: e.queued.run.model
		});
		i.onExecutionPhase?.({
			jobId: i.job.id,
			phase: "context_engine"
		});
	}
}
/** Acquire caller-owned custody before publishing a queued execution. */
async function enqueueReplySourceAdmission(e) {
	const { options: t, input: n, runId: r } = e;
	const i = t?.turnAdoptionLifecycle?.admission === "cancel-only" ? t.userTurnTranscriptRecorder : void 0;
	const assertCurrent = () => {
		n.abortSignal.throwIfAborted();
		e.assertCurrent();
		n.sourceAdapter?.authority?.assertCurrent();
	};
	let a = false;
	if (i && !i.getPendingInputMessage?.() && !i.hasPersisted()) {
		const t = await i.stageApproved?.({
			runId: r,
			assertCurrent
		});
		assertCurrent();
		if (i.isPendingInputConsumed?.()) {
			completeFollowupRunLifecycle(e.followupRun, "consumed");
			return false;
		}
		if (t === false) throw new Error("Followup input could not acquire durable custody");
		a = t === true;
	}
	const o = e.enqueue();
	if (!o && a) {
		i?.finishPendingInput?.("cancelled");
		await i?.waitForPendingInputSettlement?.();
	}
	return o;
}
/** Only unattributed host inputs may fall back to the current session principal. */
async function prepareReplySystemPrincipalAuthority(e) {
	const { followupRun: t, sessionKey: n } = e;
	if (!t.sessionPrincipalTurn || t.operatorAuthority) return;
	const r = getInProcessGatewayRequestContext(e.resolveGatewayContext);
	if (!r || !n) return;
	const i = await prepareSessionSystemTurnAuthority({
		context: r,
		agentId: t.run.agentId,
		sessionKey: n,
		sessionId: e.sessionId,
		storePath: e.storePath,
		assertCurrent: e.assertCurrent
	});
	if (i) {
		const { authority: e } = i;
		const n = t.run;
		n.senderIsOwner = e.scopes.includes("operator.admin");
		n.traceAuthorized = n.senderIsOwner;
		n.senderId = void 0;
		n.senderName = void 0;
		bindCommandOwnerAuthority(n, {
			operatorAuthority: e,
			isCurrent: () => {
				e.assertCurrent();
				return true;
			}
		});
	}
	return i;
}
//#endregion
//#region src/auto-reply/reply/reply-agent-turn-preparation.ts
async function prepareReplyAgentTurn(e) {
	let t = e.queued.operatorAuthority;
	const assertOperatorCurrent = () => t?.assertCurrent();
	assertOperatorCurrent();
	const readAdmissionConfig = () => e.queued.readAdmissionConfig?.() ?? selectLiveRuntimeConfig(e.queued.run.config);
	let n = captureRuntimeConfig(e.queued.run.config);
	const r = e.queued.controllerInput?.claim;
	const i = !e.providedReplyOperation && !e.claimSource;
	let a;
	try {
		if (i) a = await claimSessionControllerInput(e.queued);
		if (!i && !e.providedReplyOperation) a = await e.claimSource?.();
		if (!a && !e.providedReplyOperation) return {
			kind: "skipped",
			reason: resolveFollowupAbortSignal(e.queued)?.aborted ? "aborted" : "active-run"
		};
		const o = e.queued.run.sessionKey ?? e.defaults.sessionKey;
		const s = (o ? e.defaults.sessionStore?.[o] : void 0) ?? (o === e.defaults.sessionKey ? e.defaults.sessionEntry : void 0);
		let c = {
			...e.queued.run,
			config: n
		};
		const resolveRunSessionFile = (e) => normalizeOptionalString(o) ?? e.sessionFile;
		const l = e.kind ?? "queued_followup";
		const u = resolveFollowupAbortSignal(e.queued);
		const d = e.providedReplyOperation ? {
			status: "owned",
			operation: e.providedReplyOperation,
			sessionEntry: s
		} : await admitReplyTurn({
			mailboxClaim: a,
			rotationEvidence: e.rotationEvidence,
			runId: e.queued.controllerInput?.protocolRunId,
			onDatabaseRegistration: e.defaults.opts?.onDatabaseRegistration,
			providerReviewAcknowledgment: e.defaults.opts?.providerReviewAcknowledgment,
			agentId: c.agentId,
			resolveGatewayContext: e.defaults.resolveGatewayContext,
			sessionId: e.queued.admissionSessionId ?? c.sessionId,
			sessionKey: o ?? "",
			expectedSessionId: s?.sessionId,
			storePath: e.defaults.storePath,
			kind: l,
			captureRunSelection: () => {
				const t = e.queued.run;
				n = captureRuntimeConfig(readAdmissionConfig());
				c = {
					...c,
					config: n,
					provider: t.provider,
					model: t.model,
					requestedRouteResolution: t.requestedRouteResolution,
					hasAutoFallbackProvenance: t.hasAutoFallbackProvenance,
					autoFallbackPrimaryProbe: t.autoFallbackPrimaryProbe ? { ...t.autoFallbackPrimaryProbe } : void 0,
					hasSessionModelOverride: t.hasSessionModelOverride,
					modelOverrideSource: t.modelOverrideSource,
					...c.scheduledAutomation ? { scheduledAutomation: {
						...c.scheduledAutomation,
						modelFallbackPolicy: t.scheduledAutomation?.modelFallbackPolicy
					} } : {},
					authProfileId: t.authProfileId,
					authProfileIdSource: t.authProfileIdSource,
					thinkLevel: t.thinkLevel,
					thinkingCatalog: t.thinkingCatalog,
					cyberAccessProgram: t.cyberAccessProgram
				};
			},
			resetTriggered: e.resetTriggered === true,
			routeThreadId: e.routeThreadId ?? e.queued.originatingThreadId,
			originatingLeafEntryId: e.queued.turnAdoptionLifecycle?.originatingLeafEntryId,
			upstreamAbortSignal: u && a ? AbortSignal.any([u, a.abortController.signal]) : u ?? a?.abortController.signal
		});
		if (d.status === "skipped") {
			if (d.error) e.queued.run.internalEventExecution?.onFailed?.(d.error);
			if (!r && a) releaseSessionControllerClaim(a);
			return {
				kind: "skipped",
				reason: l === "queued_followup" && d.reason === "active-run" ? "lifecycle-invalidated" : d.reason
			};
		}
		const f = d.operation;
		const assertAdmissionCurrent = () => {
			assertOperatorCurrent();
			f.abortSignal.throwIfAborted();
			if (f.result) throw new Error("Reply execution is no longer current");
		};
		if (e.providedReplyOperation) attachSessionControllerInputOperation(e.queued, f);
		else bindSessionControllerInputOperation(e.queued, f);
		const p = d.sessionEntry ?? s;
		const m = p ? { ...p } : void 0;
		if (l === "queued_followup" && d.sessionEntry) c.cyberAccessProgram = m?.cyberAccessProgram;
		let h = false;
		let g = false;
		let _ = false;
		let releaseSourceAdmission;
		let v;
		try {
			_ = e.onOperationOwned?.(f) === true;
			e.queued.run.onOperationAdmitted?.(f);
			if (isFollowupRunAborted(e.queued)) return {
				kind: "skipped",
				reason: "aborted",
				operation: f
			};
			if (l === "queued_followup") {
				h = true;
				await e.defaults.opts?.onQueuedFollowupAdmitted?.();
			}
			n = await resolveQueuedReplyExecutionConfig(n, {
				originatingChannel: e.queued.originatingChannel,
				messageProvider: c.messageProvider,
				originatingAccountId: e.queued.originatingAccountId,
				agentAccountId: c.agentAccountId
			});
			assertAdmissionCurrent();
			c = {
				...c,
				config: n
			};
			v = await prepareReplySystemPrincipalAuthority({
				followupRun: {
					...e.queued,
					run: c
				},
				sessionKey: o,
				sessionId: f.sessionId,
				storePath: e.defaults.storePath,
				resolveGatewayContext: e.defaults.resolveGatewayContext,
				assertCurrent: () => f.abortSignal.throwIfAborted()
			});
			t = v?.authority ?? t;
			assertAdmissionCurrent();
			const r = c.requesterOrigin;
			if (!v && !e.providedReplyOperation && r?.messageProvider && !r.operatorProfileId && r.messageProvider !== "webchat" && !c.internalEventExecution && !c.sessionEventOrigin) {
				const e = await prepareCommandOwnerAuthority(n, {
					channel: r.messageProvider,
					accountId: r.accountId ?? void 0,
					senderId: r.senderId ?? void 0,
					senderE164: r.senderE164 ?? void 0
				});
				assertAdmissionCurrent();
				c.senderIsOwner = e.isCurrent(n);
				c.traceAuthorized = c.senderIsOwner;
				bindCommandOwnerAuthority(c, {
					recoveryReference: e.recoveryReference,
					isCurrent: () => e.isCurrent(readAdmissionConfig())
				});
				if (c.senderIsOwner) captureCommandOwnerAssertion(c)?.();
			}
			const i = await e.configure?.(n);
			assertAdmissionCurrent();
			const a = f.sessionId !== c.sessionId;
			let u = (d.sessionEntry?.sessionId === f.sessionId ? d.sessionEntry : void 0) ?? (s?.sessionId === f.sessionId ? s : void 0);
			const p = e.queued.goalContinuation;
			if (p) {
				const t = o && e.defaults.storePath ? await readSessionEntryInWorker({
					storePath: e.defaults.storePath,
					sessionKey: o
				}) : u;
				assertOperatorCurrent();
				if (!isGoalContinuationCurrent(p, t) || getFollowupQueueDepth(o ?? "") > 0) return {
					kind: "skipped",
					reason: "goal-inactive",
					operation: f
				};
			}
			const g = f.sessionId === e.queued.run.sessionId && u?.sessionId === f.sessionId && u.lifecycleRevision !== (s?.sessionId === f.sessionId ? s.lifecycleRevision : void 0);
			if (a || u?.sessionId === f.sessionId) c = {
				...c,
				...a ? { sessionId: f.sessionId } : {},
				sessionFile: resolveRunSessionFile(c),
				modelSelectionLocked: u?.modelSelectionLocked === true,
				...a || g ? {
					cliSessionBindingFacts: void 0,
					autoFallbackPrimaryProbe: void 0
				} : {}
			};
			c = resolveRunAfterAutoFallbackPrimaryProbeRecheck({
				run: c,
				entry: m,
				sessionKey: o
			});
			const y = {
				...e.queued,
				operatorAuthority: t,
				run: c
			};
			const b = createReplySessionEntryHandle({
				sessionEntry: u,
				sessionKey: o,
				sessionStore: e.defaults.sessionStore
			});
			const x = {
				...o ? {
					kind: "session",
					key: o,
					storePath: e.defaults.storePath
				} : { kind: "detached" },
				current: () => b.getCurrent(),
				publish: (e) => e && b.replaceCurrent(e)
			};
			const S = o ? b.toCompatSessionStore() : e.defaults.sessionStore;
			const resolveTurnSendPolicy = (e, t = y) => resolveSendPolicy({
				cfg: n,
				entry: e,
				sessionKey: t.run.runtimePolicySessionKey ?? o,
				channel: t.originatingChannel ?? t.run.messageProvider ?? sessionDeliveryChannel(e),
				chatType: normalizeChatType(t.originatingChatType ?? t.run.chatType ?? e?.chatType)
			});
			const C = refreshActiveGoalContext(y.currentInboundContext, u);
			const w = {
				runId: e.queued.controllerInput?.protocolRunId ?? (l !== "queued_followup" ? e.defaults.opts?.runId : void 0) ?? crypto.randomUUID(),
				queued: {
					...y,
					currentInboundContext: C
				},
				operation: f,
				config: n,
				session: x,
				sessionStore: S,
				sendPolicy: resolveTurnSendPolicy(u),
				preflightCompactionApplied: false
			};
			const readNoticeSessionEntry = async () => o && e.defaults.storePath ? await readSessionEntryInWorker({
				storePath: e.defaults.storePath,
				sessionKey: o
			}) : o && e.defaults.sessionStore ? e.defaults.sessionStore[o] : x.current();
			const refreshTurnSessionState = (t, n) => {
				const r = Boolean(t && (!n || t.sessionId !== n.sessionId || t.lifecycleRevision !== n.lifecycleRevision));
				if (t && r) {
					f.updateSessionId(t.sessionId);
					w.queued = {
						...w.queued,
						run: {
							...w.queued.run,
							sessionId: t.sessionId,
							sessionFile: resolveRunSessionFile(w.queued.run),
							cliSessionBindingFacts: void 0,
							autoFallbackPrimaryProbe: void 0,
							modelSelectionLocked: t.modelSelectionLocked === true
						}
					};
				}
				const i = refreshActiveGoalContext(e.queued.currentInboundContext, t);
				w.sendPolicy = resolveTurnSendPolicy(t, w.queued);
				w.queued = {
					...w.queued,
					currentInboundContext: i
				};
				return r;
			};
			const T = u?.compactionCount ?? 0;
			let E;
			const D = w.sendPolicy === "allow" && y.currentInboundEventKind !== "room_event" ? async (t, r) => {
				if (t !== "context_bounded" && t !== "degraded" && !shouldNotifyUserAboutCompaction(n)) return;
				if (l === "queued_followup" && t !== "start" && t !== "memory_flush_degraded") {
					E = {
						phase: t,
						text: r
					};
					return;
				}
				const i = await readNoticeSessionEntry();
				if (resolveTurnSendPolicy(i, w.queued) === "deny") return;
				await e.onCompactionNotice?.(t, r, w);
			} : void 0;
			const O = await prepareReplySourceAdmission({
				operation: f,
				followupRun: w.queued,
				recorder: w.queued.userTurnTranscriptRecorder,
				runId: w.runId
			});
			const k = v;
			releaseSourceAdmission = async () => {
				try {
					await O?.();
				} finally {
					k?.release();
				}
			};
			v = void 0;
			w.releaseSourceAdmission = releaseSourceAdmission;
			const A = x.current();
			try {
				await e.signalRunStart?.();
				const t = normalizeVerboseLevel(w.queued.run.verboseLevelOverride ?? u?.verboseLevel ?? w.queued.run.verboseLevel) ?? "off";
				const r = {
					cfg: n,
					followupRun: w.queued,
					promptForEstimate: w.queued.prompt,
					defaultModel: e.defaults.defaultModel,
					sessionEntry: u,
					sessionStore: S,
					sessionKey: o,
					storePath: e.defaults.storePath,
					opts: {
						...e.defaults.opts,
						runId: w.runId
					},
					resolvedVerboseLevel: t,
					runtimePolicySessionKey: w.queued.run.runtimePolicySessionKey,
					onCompactionNotice: D
				};
				const i = readPendingUserTurnTranscriptAdmission(r.followupRun.userTurnTranscriptRecorder);
				const a = e.trace;
				const tracePhase = (e, t) => a ? a(e, t) : t();
				try {
					u = await tracePhase("reply.preflight_compaction", () => runSessionCompactionIfNeeded({
						...r,
						replyOperation: f,
						pendingUserEntryId: i?.entryId,
						abortSignal: f.abortSignal,
						beforeCompaction: async (e) => {
							await admitReplyMaintenance(w, o, assertAdmissionCurrent);
							const t = await tracePhase("reply.memory_flush", () => runMemoryFlushIfNeeded({
								...r,
								preflightAdmission: i,
								replyOperation: f,
								abortSignal: f.abortSignal,
								sessionEntry: e
							}));
							w.memoryFlushAttempted ||= t.outcome !== "skipped";
							x.publish(t.sessionEntry);
							f.abortSignal.throwIfAborted();
							if (t.outcome === "exhausted") await r.onCompactionNotice?.("memory_flush_degraded");
							return t.sessionEntry;
						},
						onCompactionStart: () => f.setPhase("preflight_compacting"),
						onSessionIdChanged: (e) => f.updateSessionId(e)
					}));
				} catch (e) {
					const t = r.followupRun.userTurnTranscriptRecorder;
					if (t && buildPreflightCompactionFailureText(formatErrorMessage$1(e)) !== null) try {
						await t.persistApproved({
							expectedSessionId: f.sessionId,
							beforeFreshMessageCommit: () => {
								f.abortSignal.throwIfAborted();
								r.followupRun.operatorAuthority?.assertCurrent();
								if (f.lifecycleGeneration) assertAgentRunLifecycleGenerationCurrent(f.lifecycleGeneration);
							}
						});
					} catch (e) {
						logVerbose(`user turn not kept after failed preflight: ${formatErrorMessage$1(e)}`);
					}
					throw e;
				}
				if (u) {
					x.publish(u);
					u = x.current() ?? u;
				}
				w.preflightCompactionApplied = refreshTurnSessionState(u, A) || (u?.compactionCount ?? 0) > T;
			} catch (e) {
				const t = x.current();
				if (t) {
					x.publish(t);
					u = x.current() ?? t;
				}
				refreshTurnSessionState(u, A);
				w.preflightError = toErrorObject(e, "Reply preparation failed");
				const n = w.queued.run.verboseLevelOverride ?? x.current()?.verboseLevel ?? w.queued.run.verboseLevel;
				const r = renderAgentHarnessPreflightUserMessage(e) ?? buildPreflightCompactionFailureText(formatErrorMessage$1(e), { includeDetails: n === "on" || n === "full" });
				if (r) w.preflightFailurePayload = markReplyPayloadForSourceSuppressionDelivery({ text: r });
			}
			if (E && w.sendPolicy === "allow" && w.queued.currentInboundEventKind !== "room_event") {
				if (resolveTurnSendPolicy(await readNoticeSessionEntry(), w.queued) === "allow") await e.onCompactionNotice?.(E.phase, E.text, w);
			}
			if (p) {
				const n = o && e.defaults.storePath ? await readSessionEntryInWorker({
					storePath: e.defaults.storePath,
					sessionKey: o
				}) : x.current();
				const r = await isGoalContinuationPlacementCurrent({
					continuation: p,
					agentId: c.agentId,
					sessionKey: o ?? "",
					hasOperatorAuthority: Boolean(t),
					requiresWorker: Boolean(c.config?.cloudWorkers?.requiredProfile)
				});
				assertOperatorCurrent();
				if (!r || f.abortSignal.aborted || !isGoalContinuationCurrent(p, n) || getFollowupQueueDepth(o ?? "") > 0) return {
					kind: "skipped",
					reason: "goal-inactive",
					operation: f
				};
			}
			h = false;
			releaseSourceAdmission = void 0;
			return {
				kind: "admitted",
				configured: i,
				turn: w
			};
		} catch (e) {
			g = true;
			const t = e instanceof Error ? e : new Error(formatErrorMessage$1(e));
			if (!f.result) f.fail("run_failed", t);
			throw t;
		} finally {
			try {
				if (h) await settleQueuedFollowupPresentation(e.defaults.opts?.onQueuedFollowupSettled);
			} finally {
				try {
					try {
						await releaseSourceAdmission?.();
					} finally {
						v?.release();
					}
				} finally {
					if (g && !_) f.complete();
				}
			}
		}
	} catch (e) {
		if (!r && a) releaseSessionControllerClaim(a);
		throw e;
	}
}
//#endregion
//#region src/auto-reply/reply/followup-runner.ts
function resolveFollowupCompletion(e) {
	const t = e.kind === "settled" ? e.result.meta : void 0;
	const n = e.kind === "rejected" || e.kind === "settled" && e.status === "failed";
	const r = buildAgentRunTerminalOutcomeFromLifecycleEvent({
		phase: n ? "error" : "end",
		data: {
			aborted: e.kind === "aborted" || t?.aborted,
			stopReason: e.kind === "aborted" ? e.reason === "user" ? "aborted" : e.reason : t?.stopReason,
			timeoutPhase: t?.timeoutPhase,
			providerStarted: t?.providerStarted,
			livenessState: t?.livenessState,
			error: e.kind === "rejected" ? e.payload.text : e.kind === "settled" && e.status === "failed" ? e.terminalFailurePayload?.text ?? t?.error?.message : t?.error?.message
		}
	});
	const i = classifyAgentRunTerminalOutcome(r);
	const a = r.stopReason ? { stopReason: r.stopReason } : {};
	if (i === "cancellation") return {
		kind: "aborted",
		...a
	};
	if (i === "failure" || i === "timeout") return {
		kind: "failed",
		error: r.error ?? "Follow-up failed.",
		...a,
		...i === "timeout" ? { errorKind: "timeout" } : {}
	};
	return {
		kind: "completed",
		...a
	};
}
function createFollowupRunner(e) {
	const t = Object.hasOwn(e, "resolveGatewayContext") ? e.resolveGatewayContext : getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext;
	const n = {
		...e,
		resolveGatewayContext: t
	};
	const runFollowup = (e) => withoutRequiredSessionPlacement(() => withoutSessionTranscriptReadFence(() => runWithAgentWorkspaceReadiness(void 0, () => withPluginRuntimeGatewayContextResolver(t, () => executeFollowup(e), { inheritRequestScope: false }))));
	const executeFollowup = async (e) => {
		let r = {
			kind: "retry",
			error: void 0
		};
		let i;
		let a;
		let o;
		let s = [];
		let c;
		const l = [];
		let u = { kind: "completed" };
		let d = false;
		let f = false;
		const hasSurvivingSources = () => {
			const t = e.controllerClaim ?? e.controllerInput?.claim;
			return Boolean(t && t.sources.length > 1 && t.sources.some((e) => !isFollowupRunAborted(e) && !e.controllerInput?.retirementRequested));
		};
		let p = false;
		let m = false;
		let h = false;
		const onObservedReplyDelivery = async () => {
			if (p) return;
			p = true;
			await n.opts?.onObservedReplyDelivery?.();
		};
		const deliverProgress = async (e, t, r) => {
			const i = await deliverFollowupDecision({
				decision: {
					kind: "deliver",
					payloads: t
				},
				turn: e,
				defaults: n,
				runId: e.runId,
				runFollowup,
				kind: r,
				onObservedReplyDelivery
			});
			m ||= i.kind === "pending";
		};
		const g = (e.deliveryCorrelations ?? []).map((e) => e.begin()).filter((e) => typeof e === "function");
		try {
			if (isFollowupRunAborted(e)) {
				r = hasSurvivingSources() ? {
					kind: "retry",
					error: e.abortSignal?.reason
				} : { kind: "consumed" };
				return;
			}
			const deliverCompactionNotice = async (e, t, n) => {
				const r = n.queued.queuedFollowupReplyDisposition;
				if (t !== "memory_flush_degraded" && r?.kind === "deliver" && r.deliver.ownsCompletion?.(n.queued.originatingChannel)) {
					l.push(e);
					return;
				}
				await deliverProgress(n, [e], "block");
			};
			const f = await prepareReplyAgentTurn({
				queued: e,
				defaults: n,
				onOperationOwned: (e) => {
					i = e;
				},
				onCompactionNotice: async (e, t, n) => {
					await deliverCompactionNotice(createCompactionNoticePayload({
						phase: e,
						text: t,
						currentMessageId: resolveFollowupCurrentMessageId(n.queued)
					}), e, n);
				}
			});
			if (f.kind === "skipped") {
				i = f.operation;
				r = f.reason === "aborted" && hasSurvivingSources() ? {
					kind: "retry",
					error: e.abortSignal?.reason
				} : { kind: "consumed" };
				return;
			}
			const p = f.turn;
			i = p.operation;
			a = p;
			if (p.session.kind === "session" && p.session.storePath) o = t?.()?.sessionActivitySummaries?.beginCompletion({
				agentId: p.queued.run.agentId,
				key: p.session.key,
				storePath: p.session.storePath
			}, p.session.current());
			const g = p.session.current();
			const _ = g?.goal?.id;
			const v = createGoalContinuationReturn(p.session.kind === "session" && p.session.storePath && g && (g.agentHarnessId === void 0 || g.agentHarnessId === "openclaw") ? {
				base: p.queued,
				initialGoalId: g.goal?.status === "active" ? _ : void 0,
				expectedSession: g,
				sessionKey: p.session.key,
				storePath: p.session.storePath,
				queueKey: p.queued.run.sessionKey ?? p.session.key,
				settings: resolveQueueSettings({
					cfg: p.config,
					sessionEntry: g,
					channel: p.queued.originatingChannel
				}),
				operation: p.operation,
				runFollowup
			} : void 0);
			d = true;
			const y = await runWithReplyOperationLifecycleAdmission(p.operation, () => v(() => executeFollowupTurn({
				turn: p,
				defaults: n,
				onToolResult: (e) => deliverProgress(p, [e], "tool"),
				onCompactionNoticePayload: (e) => deliverProgress(p, [e], "block")
			})));
			r = { kind: "consumed" };
			u = p.queued.stalledTurnRecovery === true && isReplyOperationStalledBeforeOutput(p.operation) ? {
				kind: "failed",
				error: resolveStalledTurnNoticeText(p.operation)
			} : resolveFollowupCompletion(y.execution.outcome);
			try {
				await y.progress.drain();
			} catch (e) {
				if (u.kind === "completed") u = {
					kind: "failed",
					error: formatErrorMessage$1(e)
				};
				defaultRuntime.error?.(`followup queue: progress presentation failed after execution: ${formatErrorMessage$1(e)}`);
				i.fail("run_failed", e);
			}
			if (l.length > 0 && p.sendPolicy === "allow" && p.queued.currentInboundEventKind !== "room_event") await deliverProgress(p, l, "block");
			if (y.execution.outcome.kind === "settled" && hasCompletedSourceReplyDeliveryEvidence(y.execution.outcome.result)) await onObservedReplyDelivery();
			const b = {
				...n.opts,
				sourceReplyDeliveryMode: p.queued.run.sourceReplyDeliveryMode,
				resolveReplyDelivery: p.queued.runObservers?.resolveReplyDelivery,
				resolveReplyDeliveryFacts: p.queued.runObservers?.resolveReplyDeliveryFacts,
				commentaryPayloadsEnabled: y.commentaryPayloadsEnabled,
				onObservedReplyDelivery
			};
			const { decision: x, accounting: S } = await v(() => withAgentTurnCompletion({
				agentId: p.queued.run.agentId,
				storePath: p.session.kind === "session" ? p.session.storePath : void 0,
				sessionKey: p.session.kind === "session" ? p.session.key : void 0,
				entry: p.session.current(),
				writer: y.execution.outcome.sessionWriter,
				operation: p.operation,
				activitySummaryCompletion: o,
				publish: (e) => p.session.publish(e)
			}, async (e) => {
				const t = await accountFollowupTurn({
					turn: p,
					defaults: n,
					execution: y,
					completion: e
				});
				const r = await resolveFollowupDeliveryDecision({
					turn: p,
					execution: y.execution,
					accounting: t,
					opts: b
				});
				await e?.complete();
				return {
					decision: r,
					accounting: t
				};
			}));
			if (x.kind === "deliver") for (const e of x.payloads) {
				c = getReplyPayloadMetadata(e)?.progressContinuation;
				if (c) break;
			}
			if (u.kind === "completed" && x.kind === "suppress" && (x.reason === "silent" || x.reason === "message-tool-only")) u = {
				...u,
				allowCanvasOnly: true
			};
			const C = await deliverFollowupDecision({
				decision: x,
				turn: p,
				defaults: n,
				runId: y.execution.runId,
				runFollowup,
				onObservedReplyDelivery
			});
			s = C.kind === "source-retry" ? [] : C.payloads;
			m ||= C.kind === "pending";
			h = C.kind === "source-retry";
			if (u.kind === "completed" && S?.activeSessionEntry?.goal?.status === "active" && p.session.kind === "session" && p.session.storePath) await enqueueGoalContinuation({
				base: p.queued,
				result: S.runResult,
				initialGoalId: p.queued.goalContinuation?.goalId ?? _,
				expectedSession: S.expectedSession,
				sessionKey: p.session.key,
				storePath: p.session.storePath,
				reader: getReplyOperationSessionReader(p.operation),
				queueKey: p.queued.run.sessionKey ?? p.session.key,
				settings: resolveQueueSettings({
					cfg: p.config,
					sessionEntry: p.session.current(),
					channel: p.queued.originatingChannel
				}),
				sourceRunId: p.runId,
				operation: p.operation,
				runFollowup
			});
		} catch (t) {
			const n = !isFollowupOperatorAuthorityCurrent(e);
			if (!n && (e.run.internalEventExecution && (d || (e.controllerClaim ?? e.controllerInput?.claim)?.retryBeforeExecution !== true) || i?.result?.kind === "aborted" && i.result.code === "aborted_by_user")) {
				r = !e.run.internalEventExecution && hasSurvivingSources() ? {
					kind: "retry",
					error: t
				} : { kind: "consumed" };
				e.run.internalEventExecution?.onFailed?.(t);
				u = e.run.internalEventExecution ? {
					kind: "failed",
					error: formatErrorMessage$1(t)
				} : resolveFollowupCompletion({
					kind: "aborted",
					reason: "user"
				});
			} else if (n || r.kind === "consumed") {
				r = { kind: "consumed" };
				f = n;
				u = {
					kind: "failed",
					error: formatErrorMessage$1(t),
					...n ? { notice: `withheld: ${formatErrorMessage$1(t)}` } : {}
				};
				defaultRuntime.error?.(`followup queue: input withheld; refusing replay: ${formatErrorMessage$1(t)}`);
				i?.fail("run_failed", t);
			} else r = {
				kind: "retry",
				error: t
			};
		} finally {
			const t = e.controllerClaim ?? e.controllerInput?.claim;
			if (r.kind === "retry" && t && (d || !deferSessionControllerClaimBeforeExecution(t))) {
				u = {
					kind: "failed",
					error: formatErrorMessage$1(r.error)
				};
				i?.fail("run_failed", r.error);
				r = { kind: "consumed" };
			}
			o?.release();
			const l = (a?.queued ?? e).queuedFollowupReplyDisposition;
			if (r.kind === "consumed" && (a || f) && l?.kind === "deliver") try {
				await l.deliver({
					kind: "queued-followup",
					runId: a?.runId ?? e.sourceTurnId ?? e.messageId ?? "",
					originatingChannel: (a?.queued ?? e).originatingChannel,
					payloads: s,
					completion: u
				});
			} catch (e) {
				u = {
					kind: "failed",
					error: formatErrorMessage$1(e)
				};
				defaultRuntime.error?.(`followup queue: completion delivery failed; refusing replay: ${formatErrorMessage$1(e)}`);
				i?.fail("run_failed", e);
			}
			try {
				if (a) await settleQueuedFollowupPresentation(n.opts?.onQueuedFollowupSettled);
			} finally {
				c?.close();
			}
			for (const e of g.toReversed()) try {
				e(r.kind === "consumed" && (!h || p || u.kind === "failed") && l?.kind !== "deliver" ? {
					visibleReplySent: p,
					failed: !a || u.kind === "failed",
					completed: Boolean(a) && u.kind === "completed",
					...m ? { transportPending: true } : {}
				} : void 0);
			} catch (e) {
				defaultRuntime.error?.(`followup queue: delivery correlation cleanup failed: ${formatErrorMessage$1(e)}`);
			}
			if (r.kind === "consumed") {
				if (t) t.retryBeforeExecution = false;
				completeFollowupRunLifecycle(e);
			}
			if (a?.runId) clearAgentRunContext(a.runId);
			try {
				await a?.releaseSourceAdmission?.();
			} finally {
				i?.complete();
				n.typing.markRunComplete();
				n.typing.markDispatchIdle();
			}
		}
		if (r.kind === "retry") throw r.error;
	};
	return runFollowup;
}
//#endregion
//#region src/auto-reply/reply/agent-runner-execute.ts
function prependCompactionNotices(e, t, n) {
	if (t.length === 0 || resolveReplyOperationAbortReason(n)) return e;
	return [...t, ...Array.isArray(e) ? e : e ? [e] : []];
}
/** Continues a saved stalled request once, retaining its final-feedback obligation. */
function continueStalledReplyTurn({ followupRun: e, queueKey: t, resolvedQueue: n, replyOperation: r, runFollowupTurn: i, guidance: a }) {
	if (r.staleExpiryReason === "rate_limited") return false;
	if (e.stalledTurnRecovery || e.userTurnTranscriptRecorder?.hasPersisted() !== true) return false;
	if (!isFollowupOperatorAuthorityCurrent(e)) return false;
	const o = !a && claimNextQueuedFollowupRequestFrom(t, e);
	if (o) {
		o.stalledTurnRecovery = true;
		e.stalledTurnRecovery = true;
		o.currentInboundContext = appendCurrentInboundContext(o.currentInboundContext, [{
			kind: "runtime-instruction",
			text: STALLED_TURN_GUIDANCE
		}]);
		return true;
	}
	if (e.queuedFollowupReplyDisposition?.kind === "drop") return false;
	const s = enqueueFollowupRun(t, buildStalledTurnRecoveryRun(e, a), n, "none", i, false, {
		position: "front",
		storePath: e.controllerInput?.mailbox.owner.target?.storeScope
	});
	if (s) {
		e.stalledTurnRecovery = true;
		scheduleFollowupDrainAfterReplyOperationClear({
			operation: r,
			queueKey: t,
			runFollowup: i
		});
	}
	return s;
}
async function executePreparedReplyAgentRun(e) {
	const t = e.opts?.onAgentRunTerminalOutcome;
	let n;
	const r = t ? {
		...e.opts,
		onAgentRunTerminalOutcome: (e) => {
			n = e === "failed" ? e : n ?? e;
		}
	} : e.opts;
	const i = e.sessionKey && e.storePath ? getGatewayContextResolver(e.replyOperation)?.()?.sessionActivitySummaries?.beginCompletion({
		agentId: e.followupRun.run.agentId,
		key: e.sessionKey,
		storePath: e.storePath
	}, e.getActiveSessionEntry()) : void 0;
	try {
		return await executePreparedReplyAgentRunWithCompletion({
			...e,
			activitySummaryCompletion: i
		}, r);
	} catch (e) {
		if (n !== void 0) n = "failed";
		throw e;
	} finally {
		i?.release();
		if (n) t?.(n);
	}
}
async function executePreparedReplyAgentRunWithCompletion(e, t) {
	const { activeSessionStore: n, admitUserTurn: r, recordPendingDelivery: i, defaultModel: a, followupRun: o, getActiveSessionEntry: s, opts: c, replyOperation: l, replyThreadingOverride: u, returnWithQueuedFollowupDrain: d, preflightCompactionApplied: f, sessionCtx: p, sessionKey: m, setRunFollowupTurn: h, storePath: g, toolProgressDetail: _, traceAgentPhase: v, typing: y, typingMode: b } = e;
	let x = s();
	const S = createFollowupRunner({
		resolveGatewayContext: getGatewayContextResolver(l),
		opts: c,
		typing: y,
		typingMode: b,
		sessionEntry: x,
		sessionStore: n,
		sessionKey: m,
		storePath: g,
		defaultModel: a,
		toolProgressDetail: _
	});
	h(S);
	l.setPhase("running");
	const C = Date.now();
	await r(o.userTurnTranscriptRecorder);
	x = s();
	await admitFollowupRunLifecycle(o);
	const w = createGoalContinuationReturn(m && g && x && (x.agentHarnessId === void 0 || x.agentHarnessId === "openclaw") ? {
		base: o,
		initialGoalId: x.goal?.status === "active" ? x.goal.id : void 0,
		expectedSession: x,
		sessionKey: m,
		storePath: g,
		queueKey: e.queueKey,
		settings: e.resolvedQueue,
		operation: l,
		runFollowup: S
	} : void 0);
	const T = await withBeforeAgentReplyObserver({
		beforeDispatch: async () => {
			l.abortSignal.throwIfAborted();
			return true;
		},
		afterDispatch: async (t) => {
			if (!t?.handled) return t;
			const n = t.reply ?? {};
			const r = buildRecoverablePendingFinalDeliveryText([n]);
			const a = normalizePendingFinalDeliveryPayloads([n]);
			if (m && g && a.length > 0) {
				if (!resolveSourceReplyPolicy({
					...e,
					sessionKey: m,
					sessionEntry: x
				}).suppressDelivery) {
					const t = crypto.randomUUID();
					const a = crypto.randomUUID();
					setReplyPayloadMetadata(n, { pendingFinalDeliveryCompletion: {
						agentId: o.run.agentId,
						deliveryId: a,
						intentId: t,
						sessionId: l.sessionId,
						sessionKey: m,
						storePath: g
					} });
					await i({
						text: r ?? "",
						intentId: t,
						deliveries: [{
							id: a,
							state: "prepared"
						}],
						context: resolveReplyRunDeliveryContext({
							...e,
							sessionKey: m,
							sessionEntry: x
						})
					});
				}
			}
			x = s();
			return t;
		}
	}, () => withCurrentUserTurnInput(o.userTurnTranscriptRecorder, () => v("reply.run_agent_turn", () => w(() => executeAgentTurn({
		...e,
		opts: t,
		resolveVisibleReplyDelivery: e.resolveVisibleReplyDelivery,
		replyThreading: u ?? p.ReplyThreading
	})))));
	const E = isReplyOperationSuperseded(l);
	recordReplyOperationAgentTurn(o.replyOperationRunStates, l, T.outcome);
	x = s();
	if (T.outcome.kind !== "settled") await accountAgentTurnCompaction({
		compaction: T.outcome.compaction,
		sessionStore: n,
		replyOperation: l
	});
	if (E) return {};
	if (T.outcome.kind !== "settled") {
		if (T.outcome.kind === "rejected" && !l.result && resolveReplyOperationRunState(c)?.replyCompletion?.outcome !== "pending") l.fail("run_failed", /* @__PURE__ */ new Error("reply operation exited with final payload"));
		return d(T.outcome.kind === "rejected" ? markPostCompactionModelFailurePayload(T.outcome.postCompactionModelFailure, T.outcome.payload) : {});
	}
	const D = T.outcome;
	const O = await w(() => finalizeReplyAgentRun({
		...e,
		opts: t,
		activeSessionEntry: x,
		preflightCompactionApplied: f,
		runFollowupTurn: S,
		execution: D,
		runId: T.runId,
		runStartedAt: C
	}));
	const { postCompactionModelFailure: k } = D;
	if (Array.isArray(O)) return O.map((e) => markPostCompactionModelFailurePayload(k, e));
	return O ? markPostCompactionModelFailurePayload(k, O) : O;
}
//#endregion
//#region src/auto-reply/reply/agent-runner-question-input.ts
/** Question-only runtimes accept answers without exposing ordinary steering. */
async function runReplyQuestionInput(e) {
	const { followupRun: t, opts: n, sessionKey: r } = e;
	const i = t.run.inputProvenance === void 0 || t.run.inputProvenance.kind === "external_user";
	const a = (e.transcriptCommandBody ?? t.transcriptPrompt ?? e.commandBody).trim();
	if (!r || e.steeringIntent?.kind === "new-execution" || e.resetTriggered || isExplicitFollowupCommandTurn(e.sessionCtx) || n?.messageInjectionDisposition === "accepted" || !i || !a || t.images?.length || t.media?.length) return { handled: false };
	const o = resolveInboundReplyToolAuthorityOverlay({
		ctx: e.sessionCtx,
		sessionEntry: e.sessionEntry,
		senderIsOwner: t.run.senderIsOwner === true,
		operatorAuthority: t.operatorAuthority,
		toolsAllow: t.toolsAllow,
		disableTools: t.disableTools === true
	});
	const s = n?.abortSignal;
	const c = resolveFollowupAbortSignal(t);
	const assertSourceCurrent = () => {
		t.controllerInput?.abortSignal.throwIfAborted();
		s?.throwIfAborted();
		c?.throwIfAborted();
		t.operatorAuthority?.assertCurrent();
	};
	const l = resolveReplyOperationRunState(n);
	const u = t.controllerInput && !t.controllerInput.claim ? beginSessionControllerSourceInjection(t.controllerInput, { keepOrderOnDecline: true }) : void 0;
	let d = false;
	try {
		if (u && !await u.admit()) {
			const e = t.controllerInput;
			return e?.retirementRequested || e?.abortSignal.aborted ? {
				handled: true,
				payload: void 0
			} : { handled: false };
		}
		let e;
		try {
			const n = await claimPendingAgentQuestionAnswerFromCaller({
				sessionKey: r,
				text: a,
				caller: o,
				assertSourceCurrent,
				sourceRecorder: t.userTurnTranscriptRecorder,
				onAnswerProcessed: () => {
					d = true;
					u?.accepted(true);
					if (l) l.questionInputHandled = true;
				}
			});
			if (n === "requester-mismatch") return {
				handled: false,
				requesterMismatch: true
			};
			if (!n) return { handled: false };
			e = { status: "answered" };
		} catch (t) {
			if (t instanceof QuestionDispatchUnsupportedError) {
				assertSourceCurrent();
				return { handled: false };
			}
			if (t instanceof QuestionDispatchRefusedError) {
				if (l) l.admission = {
					status: "skipped",
					reason: "question-response-refused"
				};
				return {
					handled: true,
					payload: markReplyPayloadForSourceSuppressionDelivery({
						text: `The answer was not sent: ${t.message}. Use the question controls in the Control UI, or check the active run and your permissions before retrying.`,
						isError: true
					})
				};
			}
			const n = readQuestionRejection(t);
			if (n?.code === "INVALID_REQUEST" && n.reason === "QUESTION_INVALID_ANSWER") {
				const e = t instanceof Error ? t.message.trim() : "";
				if (l) l.admission = {
					status: "skipped",
					reason: "question-response-rejected"
				};
				return {
					handled: true,
					payload: markReplyPayloadForSourceSuppressionDelivery({
						text: `${e ? `The answer was not accepted: ${e}.` : "The answer was not accepted because a question is still unanswered."} The question is still open, so reply again and answer every question by number or question id.`,
						isError: true
					})
				};
			}
			if (!(t instanceof QuestionAnswerUnconfirmedError)) throw t;
			e = {
				status: "indeterminate",
				errorMessage: t.message
			};
		}
		d = true;
		if (l) l.admission = e.status === "indeterminate" ? {
			status: "skipped",
			reason: "question-response-indeterminate"
		} : {
			status: "accepted",
			mode: "steer"
		};
		try {
			await admitFollowupRunLifecycle(t);
		} catch (e) {
			logVerbose(`question input adoption failed after custody transferred: ${String(e)}`);
		} finally {
			completeFollowupRunLifecycle(t, "consumed");
		}
		return {
			handled: true,
			payload: e.status === "indeterminate" ? markReplyPayloadForSourceSuppressionDelivery({
				text: e.errorMessage,
				isError: true
			}) : void 0
		};
	} finally {
		u?.finish(d);
	}
}
//#endregion
//#region src/auto-reply/reply/agent-runner-session-activity.ts
async function commitQueuedReplySessionActivity(e) {
	const assertCurrent = () => e.assertCurrent();
	const t = {
		assertCurrent,
		authorize(t, n) {
			const r = n.entry;
			if (!r || r.sessionId !== e.expected.sessionId || r.lifecycleRevision !== e.expected.lifecycleRevision) throw new Error("Queued activity session changed");
		}
	};
	await withSessionActor(e.target, {
		assertCurrent,
		assertReadable: assertCurrent
	}, async (n) => {
		const r = await runSessionActorCommand(n, t, (r) => n.patch({
			commandId: randomUUID(),
			phaseId: `activity:${e.target.sessionKey}`,
			expected: r?.version,
			reducers: [{
				kind: "activity",
				updatedAt: e.updatedAt
			}]
		}, t));
		if (r.kind !== "committed") throw wrapSqliteWorkerError(r.error.message, r.kind === "unknown" ? "outcome-unknown" : "unavailable", r.error);
		e.onCommittedEntry(r.receipt.postimage.entry);
		if (r.failure) throw new Error(r.failure.message);
	});
}
/** Keep queued/steered activity and its in-memory session projection at one write boundary. */
async function touchQueuedReplySessionActivity(e, t, n) {
	const { opts: r, followupRun: i, sessionKey: a, sessionStore: o, storePath: s } = e;
	if (r?.internalEventExecution || !t || !o || !a) return;
	const c = t.updatedAt === 0 ? 0 : Date.now();
	if (s) await commitQueuedReplySessionActivity({
		target: {
			agentId: i.run.agentId,
			storePath: s,
			sessionKey: a
		},
		expected: t,
		updatedAt: c,
		assertCurrent: () => {
			i.operatorAuthority?.assertCurrent();
		},
		onCommittedEntry: (e) => {
			n(e);
			if (e) o[a] = e;
		}
	});
	else {
		t.updatedAt = c;
		o[a] = t;
	}
}
//#endregion
//#region src/auto-reply/reply/reply-run-typing.ts
const typingByReplyOperation = /* @__PURE__ */ new WeakMap();
/** Keep one feedback controller attached to the task that owns a reply run. */
function bindReplyOperationTyping(e, t) {
	if (typingByReplyOperation.has(e)) return;
	typingByReplyOperation.set(e, t);
	runAfterReplyOperationClear(e, () => {
		typingByReplyOperation.delete(e);
		t.cleanup();
	});
}
/** Refresh the continuing task's feedback after it adopts another inbound turn. */
async function refreshReplyOperationTyping(e, t) {
	const n = typingByReplyOperation.get(e);
	if (!n || e.result || !t.startIfIdle && !n.isActive()) return;
	await n.startTypingLoop();
}
//#endregion
//#region src/auto-reply/reply/agent-runner-steer-adoption.ts
function resolveAcceptedSteerRunId(e) {
	const { followupRun: t, sessionCtx: n } = e;
	return expectDefined(e.sourceTurnId ?? buildChannelSourceTurnId({
		provider: t.originatingChannel ?? t.run.messageProvider ?? n.Provider,
		accountId: t.originatingAccountId ?? t.run.agentAccountId ?? n.AccountId,
		conversationId: t.originatingTo ?? t.originatingChatId ?? e.sessionKey ?? t.run.sessionKey,
		messageId: t.messageId ?? n.MessageSidFull ?? n.MessageSid
	}) ?? normalizeOptionalString(e.opts?.runId), "steered turn id");
}
async function runActiveReplySteer(e) {
	const { followupRun: t, queueKey: n, replyOperationRunState: r, resolvedQueue: i, runFollowup: a, sessionKey: o, touchActiveSessionEntry: s, typingSignals: c } = e;
	const l = t.currentInboundEventKind !== "room_event" && (!t.run.inputProvenance || t.run.inputProvenance.kind === "external_user");
	const u = e.providedReplyOperation;
	const d = u?.key;
	const f = u ? getSessionControllerEntryForOperation(u) : void 0;
	const p = f?.attachment?.backend;
	let m = captureReplyMessageInjectionTarget(u);
	const isCurrentOwner = () => u !== void 0 && u.key === d && isCurrentSessionControllerOperation(u) && getSessionControllerEntryForOperation(u) === f && (!t.controllerInput || t.controllerInput.mailbox.owner === f);
	const assertReadCurrent = () => {
		resolveFollowupAbortSignal(t)?.throwIfAborted();
		e.opts?.abortSignal?.throwIfAborted();
		t.operatorAuthority?.assertCurrent();
	};
	let h;
	let g;
	let _ = u?.sessionId ?? t.run.sessionId;
	const v = reserveSteerCandidate(n, t, i, a);
	if (!v) return "handled";
	const y = expectDefined(t.controllerInput, "Parked steer source").mailbox;
	const b = y.owner.active;
	if (b) scheduleFollowupDrainAfterReplyOperationClear({
		operation: b,
		queueKey: n,
		runFollowup: a
	});
	else scheduleFollowupDrain(n, a, y.owner);
	let x = false;
	const fallback = async (n, i, a) => {
		assertReadCurrent();
		v.fallback();
		x = true;
		const o = r?.admission?.status === "skipped" && r.admission.reason === "queue-cap";
		if (r && !o) r.admission = {
			status: "accepted",
			mode: "followup",
			...n === "collaborative_steering_disabled" ? { reason: "collaborative-steering-disabled" } : n === "requester-mismatch" ? { reason: n } : l ? { reason: "steering-unavailable" } : {}
		};
		diagnosticLogger.warn("steering rejected; applying follow-up policy", {
			reason: n,
			...a ? { error: a } : {},
			disposition: o ? "skipped-queue-cap" : "followup-policy",
			channel: t.originatingChannel ?? t.run.messageProvider ?? e.sessionCtx.Provider,
			sessionId: _,
			runId: e.opts?.runId,
			activeRunId: i
		});
		await s();
		return "handled";
	};
	let S;
	let C = false;
	try {
		assertReadCurrent();
		const n = await v.admit();
		if (n === "cancelled") {
			v.consume();
			x = true;
			return "handled";
		}
		if (n === "fallback") return await fallback("admission-changed");
		if (e.steeringIntent?.kind === "new-execution") return await fallback("execution-settings-changed");
		if (!u || !isCurrentOwner() || !await waitForReplyOperationBackend(u, resolveFollowupAbortSignal(t)) || !isCurrentOwner()) return await fallback("reply-owner-ended");
		_ = u.sessionId;
		if (!p) m = captureReplyMessageInjectionTarget(u);
		if (!m) return await fallback("injection_unavailable");
		assertReadCurrent();
		if (l && t.run.config.messages?.queue?.allowCollaborativeSteering !== true && hasReplySteeringRequesterMismatch(t, u)) {
			if (!canInjectReplyMessageTarget(m)) return await fallback("injection_unavailable", m.runId);
			if (t.run.config.messages?.queue?.collaborativeSteeringFallback !== "reject") return await fallback("collaborative_steering_disabled", m.runId);
			await refuseCollaborativeSteering(t, r, () => {
				x = true;
				v.consume("consumed");
			});
			return "handled";
		}
		if (l && (t.originatingChannel ?? t.run.messageProvider) === "discord" && e.sessionCtx.ChatType === "channel" && resolveCommandTurnContext(e.sessionCtx).kind === "normal" && t.run.config.messages?.queue?.allowCollaborativeSteering !== false && hasReplySteeringRequesterMismatch(t, u)) return await fallback("independent-request", m.runId);
		h = prepareSteeringDelivery({
			agentId: t.run.agentId,
			sessionKey: o,
			storePath: e.storePath,
			entry: e.sessionEntry,
			assertCurrent: assertReadCurrent
		});
		const a = h;
		const d = l ? resolveInboundReplyToolAuthorityOverlay({
			ctx: e.sessionCtx,
			sessionEntry: {
				...e.sessionEntry,
				permissionMode: t.run.permissionMode,
				toolOverrides: t.run.toolOverrides
			},
			senderIsOwner: t.run.senderIsOwner === true,
			operatorAuthority: t.operatorAuthority,
			toolsAllow: t.toolsAllow,
			disableTools: t.disableTools === true
		}) : void 0;
		const f = t.run.config.messages?.queue?.allowCollaborativeSteering === true && !isExplicitCommandTurn(resolveCommandTurnContext(e.sessionCtx)) ? d : void 0;
		const { traceAuthorized: y, allowCollaborativeSteering: b, ...w } = d ?? {};
		const T = await prepareReplyMessageJoin({
			followupRun: t,
			operation: u,
			target: m,
			assertCurrent: assertReadCurrent,
			collaborativeCaller: f,
			delivery: a,
			continuation: d && e.steeringIntent?.kind === "continue-existing" ? {
				kind: "continuation",
				caller: {
					...w,
					senderIsOwner: d.senderIsOwner,
					disableTools: d.disableTools
				},
				config: t.run.config,
				executionSelection: captureReplyExecutionSelection({
					run: t.run,
					sessionEntry: e.sessionEntry
				}),
				selectedRoute: {
					provider: t.run.provider,
					model: t.run.model
				},
				fallbackAvailability: resolveModelFallbackOptions(t.run).modelFallbackAvailability
			} : void 0
		});
		if (T.kind === "deferred") return await fallback(T.reason, m.runId, T.errorMessage);
		g = T.toolAuthority.release;
		assertReadCurrent();
		if (!isCurrentOwner() || u.result || u.abortSignal.aborted) return await fallback("reply-owner-ended", m.runId);
		const E = T.automaticFallbackRoute;
		const isCurrentFallback = () => !E || u.toolAuthorityRoute?.provider === E.provider && u.toolAuthorityRoute.model === E.model;
		if (!isCurrentFallback()) return await fallback("model-fallback-changed", m.runId);
		const assertSourceCurrent = () => {
			assertReadCurrent();
			if (!isCurrentOwner()) throw new Error("Reply owner changed during steering admission");
			if (!isCurrentFallback()) throw new Error("Automatic model fallback changed during steering admission");
		};
		const assertPolicy = (e) => {
			assertSourceCurrent();
			if (e !== T.toolAuthorityFingerprint) throw new Error("Steering tool authority changed");
		};
		const D = t.prompt;
		const assertLegacyPolicyCurrent = () => assertPolicy(T.toolAuthority.read());
		const O = await beginReplyMessageInjectionTarget(m, D, {
			currentInboundContext: t.currentInboundContext,
			inboundAudio: t.currentInboundAudio === true,
			assertCurrent: assertReadCurrent,
			toolAuthorityPreparation: bindPreparedToolAuthority(bindWorkerToolPreparation({
				authorityKind: "source-bound",
				assertCurrent: assertSourceCurrent,
				compatAssertCurrent: assertLegacyPolicyCurrent,
				prepareCurrent: async () => {
					await T.prepareCurrent();
					assertPolicy(T.toolAuthority.read());
					await a.prepareCurrent();
					assertSourceCurrent();
				}
			})),
			steeringMode: "all",
			isInboundUserMessage: l,
			terminalReplyExpectation: t.run.terminalReplyExpectation,
			toolAuthorityFingerprint: T.toolAuthorityFingerprint,
			...T.collaborativeCaller ? {
				toolAuthorityOverlay: T.collaborativeCaller,
				allowCollaborativeSteering: true
			} : {},
			personalToolParticipant: {
				operatorAuthority: t.operatorAuthority,
				requesterOrigin: t.run.requesterOrigin,
				senderId: t.run.senderId,
				senderName: t.run.senderName,
				gatewayUiCommandTarget: t.run.gatewayUiCommandTarget
			},
			...T.pendingInputAuthorityFingerprint ? { pendingInputAuthorityFingerprint: T.pendingInputAuthorityFingerprint } : {},
			...t.images?.length ? { images: t.images } : {},
			...t.imageOrder?.length ? { imageOrder: t.imageOrder } : {},
			...t.media?.length ? { media: t.media } : {},
			waitForTranscriptCommit: true,
			queueIdentity: resolveAcceptedSteerRunId(e),
			abortSignal: resolveFollowupAbortSignal(t),
			onQueueAccepted: v.accepted,
			...i.debounceMs !== void 0 ? { debounceMs: i.debounceMs } : {},
			...t.run.sourceReplyDeliveryMode ? { sourceReplyDeliveryMode: t.run.sourceReplyDeliveryMode } : {},
			taskSuggestionDeliveryMode: t.run.taskSuggestionDeliveryMode,
			...t.userTurnTranscriptRecorder ? { userTurnTranscriptRecorder: t.userTurnTranscriptRecorder } : {}
		});
		S = O.outcome;
		const k = await finalizeReplyMessageInjectionAttempt({
			attempt: O,
			target: m,
			inboundAudio: t.currentInboundAudio === true,
			onOutcome: (e) => {
				C = true;
				if (r) r.admission = e === "indeterminate" ? {
					status: "skipped",
					reason: "question-response-indeterminate"
				} : {
					status: "accepted",
					mode: "steer"
				};
			},
			onAdopted: () => admitFollowupRunLifecycle(t),
			shouldAbortOnAdoptionError: isIngressAdoptionLostError
		});
		if (k.status === "rejected") return await fallback(k.outcome.reason, O.targetRunId);
		v.consume("consumed");
		x = true;
		if (k.status === "indeterminate") return markReplyPayloadForSourceSuppressionDelivery({
			text: k.outcome.errorMessage,
			isError: true
		});
		if (k.aborted) {
			if (r) r.messageInjectionAborted = true;
			const e = `adoption lost: ${formatErrorMessage$1(k.adoptionError)}`;
			logVerbose(`queue: active session ${_} aborted exact steered target without replay (${e})`);
			return "handled";
		}
		if (k.adoptionError) logVerbose(`queue: active session ${_} adoption finalizer failed: ${formatErrorMessage$1(k.adoptionError)}`);
		await refreshReplyOperationTyping(u, { startIfIdle: c.shouldStartImmediately });
		await s();
		return "handled";
	} finally {
		try {
			if (!x) {
				if (S) try {
					const e = await S;
					C ||= e.status === "accepted" || e.status === "indeterminate";
				} catch {
					C = true;
				}
				if (C) v.consume("consumed");
				else try {
					assertReadCurrent();
					v.fallback();
				} catch {
					diagnosticLogger.warn("steering followup unavailable: source authority lost", {
						sessionId: _,
						runId: e.opts?.runId
					});
					v.consume();
				}
			}
		} finally {
			g?.();
			h?.release();
		}
	}
}
//#endregion
//#region src/auto-reply/reply/agent-runner-run.ts
async function runReplyAgent(e) {
	const { followupRun: t, queueKey: n, resolvedQueue: r, shouldSteer: i, shouldFollowup: a, hasQueuedFollowups: o = false, isActive: s, isRunActive: c, opts: l, typing: u, sessionEntry: d, sessionStore: f, sessionKey: p, storePath: m, defaultModel: h, resolvedVerboseLevel: g, toolProgressDetail: _, isNewSession: v, blockStreamingEnabled: y, sessionCtx: b, typingMode: x, resetTriggered: S = false, replyOperation: C } = e;
	t.run.agentId ??= resolveDefaultAgentId(t.run.config);
	t.turnAdoptionLifecycle ??= l?.turnAdoptionLifecycle;
	bindReplySourceToFollowup(l, t);
	const w = l?.runId ?? randomUUID();
	const T = submitSessionControllerInput(n, t, r, {
		protocolRunId: w,
		storePath: m
	});
	let E;
	const D = [
		T.abortSignal,
		t.abortSignal,
		l?.abortSignal,
		t.turnAdoptionLifecycle?.abortSignal
	].filter((e) => e !== void 0);
	t.abortSignal = D.length > 1 ? AbortSignal.any(D) : D[0];
	const O = {};
	const k = getAgentEventLifecycleGeneration();
	try {
		t.operatorAuthority?.assertCurrent();
		const D = C ? getGatewayContextResolver(C) : readChannelContextGatewayContextResolver(b) ?? getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext;
		let A = d;
		let j = f;
		const M = t.run.terminalReplyExpectation ??= resolveSourceReplyExpectation({
			ctx: {
				...b,
				InboundEventKind: t.currentInboundEventKind ?? b.InboundEventKind,
				InputProvenance: t.run.inputProvenance ?? b.InputProvenance
			},
			cfg: t.run.config,
			scheduledAutomation: t.run.scheduledAutomation !== void 0
		});
		const N = isExplicitFollowupCommandTurn(b);
		if (N) t.disableCollectBatching = true;
		const P = resolveReplyOperationRunState(l);
		const { runOptions: F, hasVisiblePartialReply: I } = prepareReplyRunOptions({
			opts: l,
			runId: T.protocolRunId ?? w,
			abortSignal: t.abortSignal,
			onVisiblePartialReply: () => T.claim?.operation?.watchdog.progress("finalization", "reply:partial_delivered")
		});
		if (P && isRequiredReplyExpectation(M)) P.continueStalledTurn = () => false;
		if (P) P.replyCompletion = resolveReplyCompletion(t.run.terminalReplyExpectation, "empty");
		t.replyOperationRunStates = P ? [P] : void 0;
		const L = {
			provider: t.run.provider,
			hasSessionKey: Boolean(p ?? t.run.sessionKey),
			queueMode: r.mode,
			isActive: s,
			blockStreamingEnabled: y
		};
		const traceAgentPhase = (e, n) => measureDiagnosticsTimelineSpan(e, n, {
			phase: "agent-turn",
			config: t.run.config,
			attributes: L
		});
		const ee = readChannelSourceTurnId(b);
		const R = !S && i;
		const z = R && s;
		const B = l?.messageInjectionDisposition ?? "none";
		const V = T.mailbox.owner.active;
		const te = z && hasReplySteeringRequesterMismatch(t, V);
		const H = B === "collaborative-steering-disabled";
		if (H && t.run.config.messages?.queue?.collaborativeSteeringFallback === "reject") {
			try {
				await refuseCollaborativeSteering(t, P);
			} finally {
				u.cleanup();
			}
			return;
		}
		const U = z && (H || B === "rejected" || B === "none" && !V);
		const W = createTypingSignaler({
			typing: u,
			mode: x
		});
		const ne = te && V ? { handled: false } : await runReplyQuestionInput(e);
		if (ne.handled) {
			u.cleanup();
			return ne.payload;
		}
		const G = ne.requesterMismatch === true;
		const K = {
			getVerboseLevel: () => (p ? j?.[p]?.verboseLevel : void 0) ?? A?.verboseLevel,
			resolvedVerboseLevel: g,
			verboseLevelOverride: t.run.verboseLevelOverride
		};
		const re = l?.forceToolResultProgress && l.onToolResult ? () => true : createShouldEmitToolResult(K);
		const ie = l?.blockReplyTimeoutMs ?? 15e3;
		const touchActiveSessionEntry = () => touchQueuedReplySessionActivity({
			...e,
			sessionStore: j
		}, A, (e) => {
			A = e;
		});
		const ae = createFollowupRunner({
			resolveGatewayContext: D,
			opts: l,
			typing: u,
			typingMode: x,
			sessionEntry: A,
			sessionStore: j,
			sessionKey: p,
			storePath: m,
			defaultModel: h,
			toolProgressDetail: _
		});
		if (B === "accepted") {
			if (P) P.admission = {
				status: "accepted",
				mode: "steer"
			};
			u.cleanup();
			return;
		}
		if (z && !U && !G && B === "none") {
			bindReplyOperationQueueDisposition(t, P);
			const i = await runActiveReplySteer({
				steeringIntent: e.steeringIntent,
				followupRun: t,
				opts: l,
				providedReplyOperation: V,
				queueKey: n,
				replyOperationRunState: P,
				resolvedQueue: r,
				sourceTurnId: ee,
				runFollowup: ae,
				sessionCtx: b,
				sessionKey: p,
				sessionEntry: A,
				storePath: m,
				touchActiveSessionEntry,
				typingSignals: W
			});
			u.cleanup();
			return i === "handled" ? void 0 : i;
		}
		if (resolveActiveRunQueueAction({
			hasQueuedFollowups: o,
			interrupt: r.mode === "interrupt",
			isActive: s || G,
			shouldFollowup: a || U || G,
			resetTriggered: S
		}) === "enqueue-followup") {
			bindReplyOperationQueueDisposition(t, P);
			const e = await enqueueReplySourceAdmission({
				options: N ? l : void 0,
				input: T,
				followupRun: t,
				runId: w,
				assertCurrent: () => {
					assertAgentRunLifecycleGenerationCurrent(k);
					t.operatorAuthority?.assertCurrent();
				},
				enqueue: () => enqueueFollowupRun(n, t, r, "message-id", ae, false)
			});
			if (U) diagnosticLogger.warn("steering rejected; applying follow-up policy", {
				reason: B === "rejected" ? "runtime_rejected" : C ? "source-operation-pending" : "reply-owner-ended",
				disposition: e ? "followup-queued" : P?.admission?.status === "skipped" && P.admission.reason === "queue-cap" ? "skipped-queue-cap" : "followup-not-enqueued",
				channel: t.originatingChannel ?? t.run.messageProvider ?? b.Provider,
				sessionId: V?.sessionId ?? t.run.sessionId,
				runId: l?.runId
			});
			if (!e) {
				u.cleanup();
				return;
			}
			recordReplyFollowupAdmission(P, {
				explicitFollowup: N,
				requesterMismatch: G,
				collaborationBlocked: H,
				unavailableSteer: R && (s || B === "rejected"),
				followupRun: t
			});
			const i = T.mailbox.owner.active ?? V ?? C;
			if (i) scheduleFollowupDrainAfterReplyOperationClear({
				operation: i,
				queueKey: n,
				runFollowup: ae
			});
			else scheduleFollowupDrain(n, ae, T.mailbox.owner);
			const a = await c?.() === true;
			await touchActiveSessionEntry();
			if (a) await W.signalToolStart();
			else u.cleanup();
			return;
		}
		const oe = p ?? t.run.sessionKey;
		const q = resolveRoutedDeliveryThreadId({
			ctx: b,
			sessionKey: oe
		});
		const se = resolveReplyTurnKind(l);
		const ce = C ? void 0 : createReplyTurnRotationEvidence({
			sessionKey: oe ?? "",
			controller: T.mailbox.owner
		});
		let le = C;
		const ue = [];
		let de;
		const J = await prepareReplyAgentTurn({
			queued: t,
			defaults: {
				resolveGatewayContext: D,
				opts: F,
				typing: u,
				typingMode: x,
				sessionEntry: A,
				sessionStore: j,
				sessionKey: p,
				storePath: m,
				defaultModel: h,
				toolProgressDetail: _
			},
			kind: se,
			resetTriggered: S,
			routeThreadId: q,
			providedReplyOperation: C,
			rotationEvidence: ce,
			claimSource: C ? void 0 : async () => {
				const e = ce?.observeAdmission();
				try {
					E = await claimSessionControllerInput(t);
					return E;
				} catch (e) {
					if (!resolveFollowupAbortSignal(t)?.aborted) throw e;
					return;
				} finally {
					e?.dispose();
				}
			},
			onOperationOwned: (e) => {
				if (C) E = T.claim;
				if (!C && l?.onReplyOperationOwned?.(e) === true) {
					le = e;
					return true;
				}
				return Boolean(C);
			},
			configure: (t) => {
				const n = prepareReplyRunPresentation(e, t, ue, ie);
				O.stopBlockReply = n.blockReplyPipeline?.stop;
				de = n.sendDirectCompactionNotice;
				return n;
			},
			signalRunStart: W.signalRunStart,
			trace: traceAgentPhase,
			onCompactionNotice: async (e, t) => await de?.(e, t)
		});
		if (J.kind === "skipped") {
			if (J.operation && J.operation !== le) J.operation.complete();
			if (P) P.admission = {
				status: "skipped",
				reason: J.reason === "goal-inactive" ? "lifecycle-invalidated" : J.reason
			};
			O.stopBlockReply?.();
			u.cleanup();
			if (J.reason !== "active-run" || se !== "visible") return;
			return markReplyPayloadForSourceSuppressionDelivery({ text: REPLY_RUN_STILL_SHUTTING_DOWN_TEXT });
		}
		if (P) P.admission = { status: "owned" };
		const Y = J.turn;
		Object.assign(t, Y.queued);
		A = Y.session.current();
		j = Y.sessionStore;
		const X = Y.operation;
		const { cfg: fe, replyToChannel: Z, replyToMode: pe, applyReplyToMode: me, replyMediaContext: he, blockReplyPipeline: ge } = J.configured;
		const resolveVisibleReplyDelivery = async () => {
			try {
				await ge?.flush({ force: true });
			} catch (e) {
				logVerbose(`failed to flush streamed reply blocks before surfacing run failure: ${String(e)}`);
			}
			return I() || ge?.didStream() === true;
		};
		bindReplyOperationTyping(X, u);
		let _e = ae;
		let Q = false;
		const returnWithQueuedFollowupDrain = (e) => {
			Q = true;
			return e;
		};
		if (P && isRequiredReplyExpectation(M)) P.continueStalledTurn = (e, i = X) => i === X && continueStalledReplyTurn({
			followupRun: t,
			queueKey: n,
			resolvedQueue: r,
			replyOperation: X,
			runFollowupTurn: _e,
			guidance: e
		});
		const { admitUserTurn: ve, recordPendingDelivery: ye } = createReplyInputAdmission({
			followupRun: t,
			replyOperation: X,
			sourceTurnId: ee,
			sessionKey: p,
			storePath: m,
			setEntry: (e) => {
				A = e;
				if (j && p) j[p] = e;
			}
		});
		try {
			if (Y.preflightError) throw Y.preflightError;
			await X.bindToolAuthoritySnapshotAsync(prepareReplyRunToolAuthority(t, A, captureReplyOperationSessionReader(X)));
			const executePrepared = () => executePreparedReplyAgentRun({
				...e,
				activeSessionStore: j,
				admitUserTurn: ve,
				recordPendingDelivery: ye,
				applyReplyToMode: me,
				blockReplyPipeline: ge,
				cfg: fe,
				resolveVisibleReplyDelivery,
				activeIsNewSession: v,
				getActiveSessionEntry: () => A,
				opts: F,
				onCompactionNoticePayload: (e) => {
					ue.push(e);
				},
				pendingToolTasks: /* @__PURE__ */ new Set(),
				replyMediaContext: he,
				replyOperation: X,
				replyRouteThreadId: q,
				replyToChannel: Z,
				replyToMode: pe,
				returnWithQueuedFollowupDrain,
				runFollowupTurn: _e,
				preflightCompactionApplied: Y.preflightCompactionApplied,
				recoveryMemoryFlushAttempted: Y.memoryFlushAttempted,
				setRunFollowupTurn: (e) => {
					_e = e;
				},
				shouldEmitToolOutput: createShouldEmitToolOutput(K),
				shouldEmitToolResult: re,
				traceAgentPhase,
				typingSignals: W
			});
			const n = await runWithReplyOperationLifecycleAdmission(X, executePrepared);
			return prependCompactionNotices(n, ue, X);
		} catch (e) {
			recordReplyOperationAgentTurn(t.replyOperationRunStates, X);
			const n = await handleReplyAgentRunError(e, {
				resolveVisibleReplyDelivery,
				userTurnAccepted: t.userTurnTranscriptRecorder?.hasPersisted() === true,
				replyExpectation: M,
				replyOperation: X,
				resolvedVerboseLevel: g,
				returnWithQueuedFollowupDrain,
				sessionCtx: b
			});
			return prependCompactionNotices(n, ue, X);
		} finally {
			try {
				await cleanupReplyAgentRun({
					blockReplyPipeline: ge,
					releaseSourceAdmission: Y.releaseSourceAdmission,
					providedReplyOperation: le,
					queueKey: n,
					replyOperation: X,
					runFollowupTurn: _e,
					sessionKey: p,
					shouldDrainQueuedFollowupsAfterClear: Q,
					typing: u
				});
			} finally {
				completeFollowupRunLifecycle(t);
			}
		}
	} catch (e) {
		O.stopBlockReply?.();
		u.cleanup();
		throw e;
	} finally {
		if (E) releaseSessionControllerClaim(E);
		retireUnadoptedReplySource(T);
	}
}
//#endregion
export { runReplyAgent };